tcp.c 128 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847
  1. // SPDX-License-Identifier: GPL-2.0-or-later
  2. /*
  3. * INET An implementation of the TCP/IP protocol suite for the LINUX
  4. * operating system. INET is implemented using the BSD Socket
  5. * interface as the means of communication with the user level.
  6. *
  7. * Implementation of the Transmission Control Protocol(TCP).
  8. *
  9. * Authors: Ross Biro
  10. * Fred N. van Kempen, <[email protected]>
  11. * Mark Evans, <[email protected]>
  12. * Corey Minyard <[email protected]>
  13. * Florian La Roche, <[email protected]>
  14. * Charles Hedrick, <[email protected]>
  15. * Linus Torvalds, <[email protected]>
  16. * Alan Cox, <[email protected]>
  17. * Matthew Dillon, <[email protected]>
  18. * Arnt Gulbrandsen, <[email protected]>
  19. * Jorge Cwik, <[email protected]>
  20. *
  21. * Fixes:
  22. * Alan Cox : Numerous verify_area() calls
  23. * Alan Cox : Set the ACK bit on a reset
  24. * Alan Cox : Stopped it crashing if it closed while
  25. * sk->inuse=1 and was trying to connect
  26. * (tcp_err()).
  27. * Alan Cox : All icmp error handling was broken
  28. * pointers passed where wrong and the
  29. * socket was looked up backwards. Nobody
  30. * tested any icmp error code obviously.
  31. * Alan Cox : tcp_err() now handled properly. It
  32. * wakes people on errors. poll
  33. * behaves and the icmp error race
  34. * has gone by moving it into sock.c
  35. * Alan Cox : tcp_send_reset() fixed to work for
  36. * everything not just packets for
  37. * unknown sockets.
  38. * Alan Cox : tcp option processing.
  39. * Alan Cox : Reset tweaked (still not 100%) [Had
  40. * syn rule wrong]
  41. * Herp Rosmanith : More reset fixes
  42. * Alan Cox : No longer acks invalid rst frames.
  43. * Acking any kind of RST is right out.
  44. * Alan Cox : Sets an ignore me flag on an rst
  45. * receive otherwise odd bits of prattle
  46. * escape still
  47. * Alan Cox : Fixed another acking RST frame bug.
  48. * Should stop LAN workplace lockups.
  49. * Alan Cox : Some tidyups using the new skb list
  50. * facilities
  51. * Alan Cox : sk->keepopen now seems to work
  52. * Alan Cox : Pulls options out correctly on accepts
  53. * Alan Cox : Fixed assorted sk->rqueue->next errors
  54. * Alan Cox : PSH doesn't end a TCP read. Switched a
  55. * bit to skb ops.
  56. * Alan Cox : Tidied tcp_data to avoid a potential
  57. * nasty.
  58. * Alan Cox : Added some better commenting, as the
  59. * tcp is hard to follow
  60. * Alan Cox : Removed incorrect check for 20 * psh
  61. * Michael O'Reilly : ack < copied bug fix.
  62. * Johannes Stille : Misc tcp fixes (not all in yet).
  63. * Alan Cox : FIN with no memory -> CRASH
  64. * Alan Cox : Added socket option proto entries.
  65. * Also added awareness of them to accept.
  66. * Alan Cox : Added TCP options (SOL_TCP)
  67. * Alan Cox : Switched wakeup calls to callbacks,
  68. * so the kernel can layer network
  69. * sockets.
  70. * Alan Cox : Use ip_tos/ip_ttl settings.
  71. * Alan Cox : Handle FIN (more) properly (we hope).
  72. * Alan Cox : RST frames sent on unsynchronised
  73. * state ack error.
  74. * Alan Cox : Put in missing check for SYN bit.
  75. * Alan Cox : Added tcp_select_window() aka NET2E
  76. * window non shrink trick.
  77. * Alan Cox : Added a couple of small NET2E timer
  78. * fixes
  79. * Charles Hedrick : TCP fixes
  80. * Toomas Tamm : TCP window fixes
  81. * Alan Cox : Small URG fix to rlogin ^C ack fight
  82. * Charles Hedrick : Rewrote most of it to actually work
  83. * Linus : Rewrote tcp_read() and URG handling
  84. * completely
  85. * Gerhard Koerting: Fixed some missing timer handling
  86. * Matthew Dillon : Reworked TCP machine states as per RFC
  87. * Gerhard Koerting: PC/TCP workarounds
  88. * Adam Caldwell : Assorted timer/timing errors
  89. * Matthew Dillon : Fixed another RST bug
  90. * Alan Cox : Move to kernel side addressing changes.
  91. * Alan Cox : Beginning work on TCP fastpathing
  92. * (not yet usable)
  93. * Arnt Gulbrandsen: Turbocharged tcp_check() routine.
  94. * Alan Cox : TCP fast path debugging
  95. * Alan Cox : Window clamping
  96. * Michael Riepe : Bug in tcp_check()
  97. * Matt Dillon : More TCP improvements and RST bug fixes
  98. * Matt Dillon : Yet more small nasties remove from the
  99. * TCP code (Be very nice to this man if
  100. * tcp finally works 100%) 8)
  101. * Alan Cox : BSD accept semantics.
  102. * Alan Cox : Reset on closedown bug.
  103. * Peter De Schrijver : ENOTCONN check missing in tcp_sendto().
  104. * Michael Pall : Handle poll() after URG properly in
  105. * all cases.
  106. * Michael Pall : Undo the last fix in tcp_read_urg()
  107. * (multi URG PUSH broke rlogin).
  108. * Michael Pall : Fix the multi URG PUSH problem in
  109. * tcp_readable(), poll() after URG
  110. * works now.
  111. * Michael Pall : recv(...,MSG_OOB) never blocks in the
  112. * BSD api.
  113. * Alan Cox : Changed the semantics of sk->socket to
  114. * fix a race and a signal problem with
  115. * accept() and async I/O.
  116. * Alan Cox : Relaxed the rules on tcp_sendto().
  117. * Yury Shevchuk : Really fixed accept() blocking problem.
  118. * Craig I. Hagan : Allow for BSD compatible TIME_WAIT for
  119. * clients/servers which listen in on
  120. * fixed ports.
  121. * Alan Cox : Cleaned the above up and shrank it to
  122. * a sensible code size.
  123. * Alan Cox : Self connect lockup fix.
  124. * Alan Cox : No connect to multicast.
  125. * Ross Biro : Close unaccepted children on master
  126. * socket close.
  127. * Alan Cox : Reset tracing code.
  128. * Alan Cox : Spurious resets on shutdown.
  129. * Alan Cox : Giant 15 minute/60 second timer error
  130. * Alan Cox : Small whoops in polling before an
  131. * accept.
  132. * Alan Cox : Kept the state trace facility since
  133. * it's handy for debugging.
  134. * Alan Cox : More reset handler fixes.
  135. * Alan Cox : Started rewriting the code based on
  136. * the RFC's for other useful protocol
  137. * references see: Comer, KA9Q NOS, and
  138. * for a reference on the difference
  139. * between specifications and how BSD
  140. * works see the 4.4lite source.
  141. * A.N.Kuznetsov : Don't time wait on completion of tidy
  142. * close.
  143. * Linus Torvalds : Fin/Shutdown & copied_seq changes.
  144. * Linus Torvalds : Fixed BSD port reuse to work first syn
  145. * Alan Cox : Reimplemented timers as per the RFC
  146. * and using multiple timers for sanity.
  147. * Alan Cox : Small bug fixes, and a lot of new
  148. * comments.
  149. * Alan Cox : Fixed dual reader crash by locking
  150. * the buffers (much like datagram.c)
  151. * Alan Cox : Fixed stuck sockets in probe. A probe
  152. * now gets fed up of retrying without
  153. * (even a no space) answer.
  154. * Alan Cox : Extracted closing code better
  155. * Alan Cox : Fixed the closing state machine to
  156. * resemble the RFC.
  157. * Alan Cox : More 'per spec' fixes.
  158. * Jorge Cwik : Even faster checksumming.
  159. * Alan Cox : tcp_data() doesn't ack illegal PSH
  160. * only frames. At least one pc tcp stack
  161. * generates them.
  162. * Alan Cox : Cache last socket.
  163. * Alan Cox : Per route irtt.
  164. * Matt Day : poll()->select() match BSD precisely on error
  165. * Alan Cox : New buffers
  166. * Marc Tamsky : Various sk->prot->retransmits and
  167. * sk->retransmits misupdating fixed.
  168. * Fixed tcp_write_timeout: stuck close,
  169. * and TCP syn retries gets used now.
  170. * Mark Yarvis : In tcp_read_wakeup(), don't send an
  171. * ack if state is TCP_CLOSED.
  172. * Alan Cox : Look up device on a retransmit - routes may
  173. * change. Doesn't yet cope with MSS shrink right
  174. * but it's a start!
  175. * Marc Tamsky : Closing in closing fixes.
  176. * Mike Shaver : RFC1122 verifications.
  177. * Alan Cox : rcv_saddr errors.
  178. * Alan Cox : Block double connect().
  179. * Alan Cox : Small hooks for enSKIP.
  180. * Alexey Kuznetsov: Path MTU discovery.
  181. * Alan Cox : Support soft errors.
  182. * Alan Cox : Fix MTU discovery pathological case
  183. * when the remote claims no mtu!
  184. * Marc Tamsky : TCP_CLOSE fix.
  185. * Colin (G3TNE) : Send a reset on syn ack replies in
  186. * window but wrong (fixes NT lpd problems)
  187. * Pedro Roque : Better TCP window handling, delayed ack.
  188. * Joerg Reuter : No modification of locked buffers in
  189. * tcp_do_retransmit()
  190. * Eric Schenk : Changed receiver side silly window
  191. * avoidance algorithm to BSD style
  192. * algorithm. This doubles throughput
  193. * against machines running Solaris,
  194. * and seems to result in general
  195. * improvement.
  196. * Stefan Magdalinski : adjusted tcp_readable() to fix FIONREAD
  197. * Willy Konynenberg : Transparent proxying support.
  198. * Mike McLagan : Routing by source
  199. * Keith Owens : Do proper merging with partial SKB's in
  200. * tcp_do_sendmsg to avoid burstiness.
  201. * Eric Schenk : Fix fast close down bug with
  202. * shutdown() followed by close().
  203. * Andi Kleen : Make poll agree with SIGIO
  204. * Salvatore Sanfilippo : Support SO_LINGER with linger == 1 and
  205. * lingertime == 0 (RFC 793 ABORT Call)
  206. * Hirokazu Takahashi : Use copy_from_user() instead of
  207. * csum_and_copy_from_user() if possible.
  208. *
  209. * Description of States:
  210. *
  211. * TCP_SYN_SENT sent a connection request, waiting for ack
  212. *
  213. * TCP_SYN_RECV received a connection request, sent ack,
  214. * waiting for final ack in three-way handshake.
  215. *
  216. * TCP_ESTABLISHED connection established
  217. *
  218. * TCP_FIN_WAIT1 our side has shutdown, waiting to complete
  219. * transmission of remaining buffered data
  220. *
  221. * TCP_FIN_WAIT2 all buffered data sent, waiting for remote
  222. * to shutdown
  223. *
  224. * TCP_CLOSING both sides have shutdown but we still have
  225. * data we have to finish sending
  226. *
  227. * TCP_TIME_WAIT timeout to catch resent junk before entering
  228. * closed, can only be entered from FIN_WAIT2
  229. * or CLOSING. Required because the other end
  230. * may not have gotten our last ACK causing it
  231. * to retransmit the data packet (which we ignore)
  232. *
  233. * TCP_CLOSE_WAIT remote side has shutdown and is waiting for
  234. * us to finish writing our data and to shutdown
  235. * (we have to close() to move on to LAST_ACK)
  236. *
  237. * TCP_LAST_ACK out side has shutdown after remote has
  238. * shutdown. There may still be data in our
  239. * buffer that we have to finish sending
  240. *
  241. * TCP_CLOSE socket is finished
  242. */
  243. #define pr_fmt(fmt) "TCP: " fmt
  244. #include <crypto/hash.h>
  245. #include <linux/kernel.h>
  246. #include <linux/module.h>
  247. #include <linux/types.h>
  248. #include <linux/fcntl.h>
  249. #include <linux/poll.h>
  250. #include <linux/inet_diag.h>
  251. #include <linux/init.h>
  252. #include <linux/fs.h>
  253. #include <linux/skbuff.h>
  254. #include <linux/scatterlist.h>
  255. #include <linux/splice.h>
  256. #include <linux/net.h>
  257. #include <linux/socket.h>
  258. #include <linux/random.h>
  259. #include <linux/memblock.h>
  260. #include <linux/highmem.h>
  261. #include <linux/cache.h>
  262. #include <linux/err.h>
  263. #include <linux/time.h>
  264. #include <linux/slab.h>
  265. #include <linux/errqueue.h>
  266. #include <linux/static_key.h>
  267. #include <linux/btf.h>
  268. #include <net/icmp.h>
  269. #include <net/inet_common.h>
  270. #include <net/tcp.h>
  271. #include <net/mptcp.h>
  272. #include <net/xfrm.h>
  273. #include <net/ip.h>
  274. #include <net/sock.h>
  275. #include <linux/uaccess.h>
  276. #include <asm/ioctls.h>
  277. #include <net/busy_poll.h>
  278. /* Track pending CMSGs. */
  279. enum {
  280. TCP_CMSG_INQ = 1,
  281. TCP_CMSG_TS = 2
  282. };
  283. DEFINE_PER_CPU(unsigned int, tcp_orphan_count);
  284. EXPORT_PER_CPU_SYMBOL_GPL(tcp_orphan_count);
  285. long sysctl_tcp_mem[3] __read_mostly;
  286. EXPORT_SYMBOL(sysctl_tcp_mem);
  287. atomic_long_t tcp_memory_allocated ____cacheline_aligned_in_smp; /* Current allocated memory. */
  288. EXPORT_SYMBOL(tcp_memory_allocated);
  289. DEFINE_PER_CPU(int, tcp_memory_per_cpu_fw_alloc);
  290. EXPORT_PER_CPU_SYMBOL_GPL(tcp_memory_per_cpu_fw_alloc);
  291. #if IS_ENABLED(CONFIG_SMC)
  292. DEFINE_STATIC_KEY_FALSE(tcp_have_smc);
  293. EXPORT_SYMBOL(tcp_have_smc);
  294. #endif
  295. /*
  296. * Current number of TCP sockets.
  297. */
  298. struct percpu_counter tcp_sockets_allocated ____cacheline_aligned_in_smp;
  299. EXPORT_SYMBOL(tcp_sockets_allocated);
  300. /*
  301. * TCP splice context
  302. */
  303. struct tcp_splice_state {
  304. struct pipe_inode_info *pipe;
  305. size_t len;
  306. unsigned int flags;
  307. };
  308. /*
  309. * Pressure flag: try to collapse.
  310. * Technical note: it is used by multiple contexts non atomically.
  311. * All the __sk_mem_schedule() is of this nature: accounting
  312. * is strict, actions are advisory and have some latency.
  313. */
  314. unsigned long tcp_memory_pressure __read_mostly;
  315. EXPORT_SYMBOL_GPL(tcp_memory_pressure);
  316. void tcp_enter_memory_pressure(struct sock *sk)
  317. {
  318. unsigned long val;
  319. if (READ_ONCE(tcp_memory_pressure))
  320. return;
  321. val = jiffies;
  322. if (!val)
  323. val--;
  324. if (!cmpxchg(&tcp_memory_pressure, 0, val))
  325. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMEMORYPRESSURES);
  326. }
  327. EXPORT_SYMBOL_GPL(tcp_enter_memory_pressure);
  328. void tcp_leave_memory_pressure(struct sock *sk)
  329. {
  330. unsigned long val;
  331. if (!READ_ONCE(tcp_memory_pressure))
  332. return;
  333. val = xchg(&tcp_memory_pressure, 0);
  334. if (val)
  335. NET_ADD_STATS(sock_net(sk), LINUX_MIB_TCPMEMORYPRESSURESCHRONO,
  336. jiffies_to_msecs(jiffies - val));
  337. }
  338. EXPORT_SYMBOL_GPL(tcp_leave_memory_pressure);
  339. /* Convert seconds to retransmits based on initial and max timeout */
  340. static u8 secs_to_retrans(int seconds, int timeout, int rto_max)
  341. {
  342. u8 res = 0;
  343. if (seconds > 0) {
  344. int period = timeout;
  345. res = 1;
  346. while (seconds > period && res < 255) {
  347. res++;
  348. timeout <<= 1;
  349. if (timeout > rto_max)
  350. timeout = rto_max;
  351. period += timeout;
  352. }
  353. }
  354. return res;
  355. }
  356. /* Convert retransmits to seconds based on initial and max timeout */
  357. static int retrans_to_secs(u8 retrans, int timeout, int rto_max)
  358. {
  359. int period = 0;
  360. if (retrans > 0) {
  361. period = timeout;
  362. while (--retrans) {
  363. timeout <<= 1;
  364. if (timeout > rto_max)
  365. timeout = rto_max;
  366. period += timeout;
  367. }
  368. }
  369. return period;
  370. }
  371. static u64 tcp_compute_delivery_rate(const struct tcp_sock *tp)
  372. {
  373. u32 rate = READ_ONCE(tp->rate_delivered);
  374. u32 intv = READ_ONCE(tp->rate_interval_us);
  375. u64 rate64 = 0;
  376. if (rate && intv) {
  377. rate64 = (u64)rate * tp->mss_cache * USEC_PER_SEC;
  378. do_div(rate64, intv);
  379. }
  380. return rate64;
  381. }
  382. /* Address-family independent initialization for a tcp_sock.
  383. *
  384. * NOTE: A lot of things set to zero explicitly by call to
  385. * sk_alloc() so need not be done here.
  386. */
  387. void tcp_init_sock(struct sock *sk)
  388. {
  389. struct inet_connection_sock *icsk = inet_csk(sk);
  390. struct tcp_sock *tp = tcp_sk(sk);
  391. tp->out_of_order_queue = RB_ROOT;
  392. sk->tcp_rtx_queue = RB_ROOT;
  393. tcp_init_xmit_timers(sk);
  394. INIT_LIST_HEAD(&tp->tsq_node);
  395. INIT_LIST_HEAD(&tp->tsorted_sent_queue);
  396. icsk->icsk_rto = TCP_TIMEOUT_INIT;
  397. icsk->icsk_rto_min = TCP_RTO_MIN;
  398. icsk->icsk_delack_max = TCP_DELACK_MAX;
  399. tp->mdev_us = jiffies_to_usecs(TCP_TIMEOUT_INIT);
  400. minmax_reset(&tp->rtt_min, tcp_jiffies32, ~0U);
  401. /* So many TCP implementations out there (incorrectly) count the
  402. * initial SYN frame in their delayed-ACK and congestion control
  403. * algorithms that we must have the following bandaid to talk
  404. * efficiently to them. -DaveM
  405. */
  406. tcp_snd_cwnd_set(tp, TCP_INIT_CWND);
  407. /* There's a bubble in the pipe until at least the first ACK. */
  408. tp->app_limited = ~0U;
  409. tp->rate_app_limited = 1;
  410. /* See draft-stevens-tcpca-spec-01 for discussion of the
  411. * initialization of these values.
  412. */
  413. tp->snd_ssthresh = TCP_INFINITE_SSTHRESH;
  414. tp->snd_cwnd_clamp = ~0;
  415. tp->mss_cache = TCP_MSS_DEFAULT;
  416. tp->reordering = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_reordering);
  417. tcp_assign_congestion_control(sk);
  418. tp->tsoffset = 0;
  419. tp->rack.reo_wnd_steps = 1;
  420. sk->sk_write_space = sk_stream_write_space;
  421. sock_set_flag(sk, SOCK_USE_WRITE_QUEUE);
  422. icsk->icsk_sync_mss = tcp_sync_mss;
  423. WRITE_ONCE(sk->sk_sndbuf, READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_wmem[1]));
  424. WRITE_ONCE(sk->sk_rcvbuf, READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_rmem[1]));
  425. set_bit(SOCK_SUPPORT_ZC, &sk->sk_socket->flags);
  426. sk_sockets_allocated_inc(sk);
  427. }
  428. EXPORT_SYMBOL(tcp_init_sock);
  429. static void tcp_tx_timestamp(struct sock *sk, u16 tsflags)
  430. {
  431. struct sk_buff *skb = tcp_write_queue_tail(sk);
  432. if (tsflags && skb) {
  433. struct skb_shared_info *shinfo = skb_shinfo(skb);
  434. struct tcp_skb_cb *tcb = TCP_SKB_CB(skb);
  435. sock_tx_timestamp(sk, tsflags, &shinfo->tx_flags);
  436. if (tsflags & SOF_TIMESTAMPING_TX_ACK)
  437. tcb->txstamp_ack = 1;
  438. if (tsflags & SOF_TIMESTAMPING_TX_RECORD_MASK)
  439. shinfo->tskey = TCP_SKB_CB(skb)->seq + skb->len - 1;
  440. }
  441. }
  442. static bool tcp_stream_is_readable(struct sock *sk, int target)
  443. {
  444. if (tcp_epollin_ready(sk, target))
  445. return true;
  446. return sk_is_readable(sk);
  447. }
  448. /*
  449. * Wait for a TCP event.
  450. *
  451. * Note that we don't need to lock the socket, as the upper poll layers
  452. * take care of normal races (between the test and the event) and we don't
  453. * go look at any of the socket buffers directly.
  454. */
  455. __poll_t tcp_poll(struct file *file, struct socket *sock, poll_table *wait)
  456. {
  457. __poll_t mask;
  458. struct sock *sk = sock->sk;
  459. const struct tcp_sock *tp = tcp_sk(sk);
  460. u8 shutdown;
  461. int state;
  462. sock_poll_wait(file, sock, wait);
  463. state = inet_sk_state_load(sk);
  464. if (state == TCP_LISTEN)
  465. return inet_csk_listen_poll(sk);
  466. /* Socket is not locked. We are protected from async events
  467. * by poll logic and correct handling of state changes
  468. * made by other threads is impossible in any case.
  469. */
  470. mask = 0;
  471. /*
  472. * EPOLLHUP is certainly not done right. But poll() doesn't
  473. * have a notion of HUP in just one direction, and for a
  474. * socket the read side is more interesting.
  475. *
  476. * Some poll() documentation says that EPOLLHUP is incompatible
  477. * with the EPOLLOUT/POLLWR flags, so somebody should check this
  478. * all. But careful, it tends to be safer to return too many
  479. * bits than too few, and you can easily break real applications
  480. * if you don't tell them that something has hung up!
  481. *
  482. * Check-me.
  483. *
  484. * Check number 1. EPOLLHUP is _UNMASKABLE_ event (see UNIX98 and
  485. * our fs/select.c). It means that after we received EOF,
  486. * poll always returns immediately, making impossible poll() on write()
  487. * in state CLOSE_WAIT. One solution is evident --- to set EPOLLHUP
  488. * if and only if shutdown has been made in both directions.
  489. * Actually, it is interesting to look how Solaris and DUX
  490. * solve this dilemma. I would prefer, if EPOLLHUP were maskable,
  491. * then we could set it on SND_SHUTDOWN. BTW examples given
  492. * in Stevens' books assume exactly this behaviour, it explains
  493. * why EPOLLHUP is incompatible with EPOLLOUT. --ANK
  494. *
  495. * NOTE. Check for TCP_CLOSE is added. The goal is to prevent
  496. * blocking on fresh not-connected or disconnected socket. --ANK
  497. */
  498. shutdown = READ_ONCE(sk->sk_shutdown);
  499. if (shutdown == SHUTDOWN_MASK || state == TCP_CLOSE)
  500. mask |= EPOLLHUP;
  501. if (shutdown & RCV_SHUTDOWN)
  502. mask |= EPOLLIN | EPOLLRDNORM | EPOLLRDHUP;
  503. /* Connected or passive Fast Open socket? */
  504. if (state != TCP_SYN_SENT &&
  505. (state != TCP_SYN_RECV || rcu_access_pointer(tp->fastopen_rsk))) {
  506. int target = sock_rcvlowat(sk, 0, INT_MAX);
  507. u16 urg_data = READ_ONCE(tp->urg_data);
  508. if (unlikely(urg_data) &&
  509. READ_ONCE(tp->urg_seq) == READ_ONCE(tp->copied_seq) &&
  510. !sock_flag(sk, SOCK_URGINLINE))
  511. target++;
  512. if (tcp_stream_is_readable(sk, target))
  513. mask |= EPOLLIN | EPOLLRDNORM;
  514. if (!(shutdown & SEND_SHUTDOWN)) {
  515. if (__sk_stream_is_writeable(sk, 1)) {
  516. mask |= EPOLLOUT | EPOLLWRNORM;
  517. } else { /* send SIGIO later */
  518. sk_set_bit(SOCKWQ_ASYNC_NOSPACE, sk);
  519. set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
  520. /* Race breaker. If space is freed after
  521. * wspace test but before the flags are set,
  522. * IO signal will be lost. Memory barrier
  523. * pairs with the input side.
  524. */
  525. smp_mb__after_atomic();
  526. if (__sk_stream_is_writeable(sk, 1))
  527. mask |= EPOLLOUT | EPOLLWRNORM;
  528. }
  529. } else
  530. mask |= EPOLLOUT | EPOLLWRNORM;
  531. if (urg_data & TCP_URG_VALID)
  532. mask |= EPOLLPRI;
  533. } else if (state == TCP_SYN_SENT && inet_sk(sk)->defer_connect) {
  534. /* Active TCP fastopen socket with defer_connect
  535. * Return EPOLLOUT so application can call write()
  536. * in order for kernel to generate SYN+data
  537. */
  538. mask |= EPOLLOUT | EPOLLWRNORM;
  539. }
  540. /* This barrier is coupled with smp_wmb() in tcp_reset() */
  541. smp_rmb();
  542. if (sk->sk_err || !skb_queue_empty_lockless(&sk->sk_error_queue))
  543. mask |= EPOLLERR;
  544. return mask;
  545. }
  546. EXPORT_SYMBOL(tcp_poll);
  547. int tcp_ioctl(struct sock *sk, int cmd, unsigned long arg)
  548. {
  549. struct tcp_sock *tp = tcp_sk(sk);
  550. int answ;
  551. bool slow;
  552. switch (cmd) {
  553. case SIOCINQ:
  554. if (sk->sk_state == TCP_LISTEN)
  555. return -EINVAL;
  556. slow = lock_sock_fast(sk);
  557. answ = tcp_inq(sk);
  558. unlock_sock_fast(sk, slow);
  559. break;
  560. case SIOCATMARK:
  561. answ = READ_ONCE(tp->urg_data) &&
  562. READ_ONCE(tp->urg_seq) == READ_ONCE(tp->copied_seq);
  563. break;
  564. case SIOCOUTQ:
  565. if (sk->sk_state == TCP_LISTEN)
  566. return -EINVAL;
  567. if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV))
  568. answ = 0;
  569. else
  570. answ = READ_ONCE(tp->write_seq) - tp->snd_una;
  571. break;
  572. case SIOCOUTQNSD:
  573. if (sk->sk_state == TCP_LISTEN)
  574. return -EINVAL;
  575. if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV))
  576. answ = 0;
  577. else
  578. answ = READ_ONCE(tp->write_seq) -
  579. READ_ONCE(tp->snd_nxt);
  580. break;
  581. default:
  582. return -ENOIOCTLCMD;
  583. }
  584. return put_user(answ, (int __user *)arg);
  585. }
  586. EXPORT_SYMBOL(tcp_ioctl);
  587. void tcp_mark_push(struct tcp_sock *tp, struct sk_buff *skb)
  588. {
  589. TCP_SKB_CB(skb)->tcp_flags |= TCPHDR_PSH;
  590. tp->pushed_seq = tp->write_seq;
  591. }
  592. static inline bool forced_push(const struct tcp_sock *tp)
  593. {
  594. return after(tp->write_seq, tp->pushed_seq + (tp->max_window >> 1));
  595. }
  596. void tcp_skb_entail(struct sock *sk, struct sk_buff *skb)
  597. {
  598. struct tcp_sock *tp = tcp_sk(sk);
  599. struct tcp_skb_cb *tcb = TCP_SKB_CB(skb);
  600. tcb->seq = tcb->end_seq = tp->write_seq;
  601. tcb->tcp_flags = TCPHDR_ACK;
  602. __skb_header_release(skb);
  603. tcp_add_write_queue_tail(sk, skb);
  604. sk_wmem_queued_add(sk, skb->truesize);
  605. sk_mem_charge(sk, skb->truesize);
  606. if (tp->nonagle & TCP_NAGLE_PUSH)
  607. tp->nonagle &= ~TCP_NAGLE_PUSH;
  608. tcp_slow_start_after_idle_check(sk);
  609. }
  610. static inline void tcp_mark_urg(struct tcp_sock *tp, int flags)
  611. {
  612. if (flags & MSG_OOB)
  613. tp->snd_up = tp->write_seq;
  614. }
  615. /* If a not yet filled skb is pushed, do not send it if
  616. * we have data packets in Qdisc or NIC queues :
  617. * Because TX completion will happen shortly, it gives a chance
  618. * to coalesce future sendmsg() payload into this skb, without
  619. * need for a timer, and with no latency trade off.
  620. * As packets containing data payload have a bigger truesize
  621. * than pure acks (dataless) packets, the last checks prevent
  622. * autocorking if we only have an ACK in Qdisc/NIC queues,
  623. * or if TX completion was delayed after we processed ACK packet.
  624. */
  625. static bool tcp_should_autocork(struct sock *sk, struct sk_buff *skb,
  626. int size_goal)
  627. {
  628. return skb->len < size_goal &&
  629. READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_autocorking) &&
  630. !tcp_rtx_queue_empty(sk) &&
  631. refcount_read(&sk->sk_wmem_alloc) > skb->truesize &&
  632. tcp_skb_can_collapse_to(skb);
  633. }
  634. void tcp_push(struct sock *sk, int flags, int mss_now,
  635. int nonagle, int size_goal)
  636. {
  637. struct tcp_sock *tp = tcp_sk(sk);
  638. struct sk_buff *skb;
  639. skb = tcp_write_queue_tail(sk);
  640. if (!skb)
  641. return;
  642. if (!(flags & MSG_MORE) || forced_push(tp))
  643. tcp_mark_push(tp, skb);
  644. tcp_mark_urg(tp, flags);
  645. if (tcp_should_autocork(sk, skb, size_goal)) {
  646. /* avoid atomic op if TSQ_THROTTLED bit is already set */
  647. if (!test_bit(TSQ_THROTTLED, &sk->sk_tsq_flags)) {
  648. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPAUTOCORKING);
  649. set_bit(TSQ_THROTTLED, &sk->sk_tsq_flags);
  650. }
  651. /* It is possible TX completion already happened
  652. * before we set TSQ_THROTTLED.
  653. */
  654. if (refcount_read(&sk->sk_wmem_alloc) > skb->truesize)
  655. return;
  656. }
  657. if (flags & MSG_MORE)
  658. nonagle = TCP_NAGLE_CORK;
  659. __tcp_push_pending_frames(sk, mss_now, nonagle);
  660. }
  661. static int tcp_splice_data_recv(read_descriptor_t *rd_desc, struct sk_buff *skb,
  662. unsigned int offset, size_t len)
  663. {
  664. struct tcp_splice_state *tss = rd_desc->arg.data;
  665. int ret;
  666. ret = skb_splice_bits(skb, skb->sk, offset, tss->pipe,
  667. min(rd_desc->count, len), tss->flags);
  668. if (ret > 0)
  669. rd_desc->count -= ret;
  670. return ret;
  671. }
  672. static int __tcp_splice_read(struct sock *sk, struct tcp_splice_state *tss)
  673. {
  674. /* Store TCP splice context information in read_descriptor_t. */
  675. read_descriptor_t rd_desc = {
  676. .arg.data = tss,
  677. .count = tss->len,
  678. };
  679. return tcp_read_sock(sk, &rd_desc, tcp_splice_data_recv);
  680. }
  681. /**
  682. * tcp_splice_read - splice data from TCP socket to a pipe
  683. * @sock: socket to splice from
  684. * @ppos: position (not valid)
  685. * @pipe: pipe to splice to
  686. * @len: number of bytes to splice
  687. * @flags: splice modifier flags
  688. *
  689. * Description:
  690. * Will read pages from given socket and fill them into a pipe.
  691. *
  692. **/
  693. ssize_t tcp_splice_read(struct socket *sock, loff_t *ppos,
  694. struct pipe_inode_info *pipe, size_t len,
  695. unsigned int flags)
  696. {
  697. struct sock *sk = sock->sk;
  698. struct tcp_splice_state tss = {
  699. .pipe = pipe,
  700. .len = len,
  701. .flags = flags,
  702. };
  703. long timeo;
  704. ssize_t spliced;
  705. int ret;
  706. sock_rps_record_flow(sk);
  707. /*
  708. * We can't seek on a socket input
  709. */
  710. if (unlikely(*ppos))
  711. return -ESPIPE;
  712. ret = spliced = 0;
  713. lock_sock(sk);
  714. timeo = sock_rcvtimeo(sk, sock->file->f_flags & O_NONBLOCK);
  715. while (tss.len) {
  716. ret = __tcp_splice_read(sk, &tss);
  717. if (ret < 0)
  718. break;
  719. else if (!ret) {
  720. if (spliced)
  721. break;
  722. if (sock_flag(sk, SOCK_DONE))
  723. break;
  724. if (sk->sk_err) {
  725. ret = sock_error(sk);
  726. break;
  727. }
  728. if (sk->sk_shutdown & RCV_SHUTDOWN)
  729. break;
  730. if (sk->sk_state == TCP_CLOSE) {
  731. /*
  732. * This occurs when user tries to read
  733. * from never connected socket.
  734. */
  735. ret = -ENOTCONN;
  736. break;
  737. }
  738. if (!timeo) {
  739. ret = -EAGAIN;
  740. break;
  741. }
  742. /* if __tcp_splice_read() got nothing while we have
  743. * an skb in receive queue, we do not want to loop.
  744. * This might happen with URG data.
  745. */
  746. if (!skb_queue_empty(&sk->sk_receive_queue))
  747. break;
  748. sk_wait_data(sk, &timeo, NULL);
  749. if (signal_pending(current)) {
  750. ret = sock_intr_errno(timeo);
  751. break;
  752. }
  753. continue;
  754. }
  755. tss.len -= ret;
  756. spliced += ret;
  757. if (!timeo)
  758. break;
  759. release_sock(sk);
  760. lock_sock(sk);
  761. if (sk->sk_err || sk->sk_state == TCP_CLOSE ||
  762. (sk->sk_shutdown & RCV_SHUTDOWN) ||
  763. signal_pending(current))
  764. break;
  765. }
  766. release_sock(sk);
  767. if (spliced)
  768. return spliced;
  769. return ret;
  770. }
  771. EXPORT_SYMBOL(tcp_splice_read);
  772. struct sk_buff *tcp_stream_alloc_skb(struct sock *sk, int size, gfp_t gfp,
  773. bool force_schedule)
  774. {
  775. struct sk_buff *skb;
  776. skb = alloc_skb_fclone(size + MAX_TCP_HEADER, gfp);
  777. if (likely(skb)) {
  778. bool mem_scheduled;
  779. skb->truesize = SKB_TRUESIZE(skb_end_offset(skb));
  780. if (force_schedule) {
  781. mem_scheduled = true;
  782. sk_forced_mem_schedule(sk, skb->truesize);
  783. } else {
  784. mem_scheduled = sk_wmem_schedule(sk, skb->truesize);
  785. }
  786. if (likely(mem_scheduled)) {
  787. skb_reserve(skb, MAX_TCP_HEADER);
  788. skb->ip_summed = CHECKSUM_PARTIAL;
  789. INIT_LIST_HEAD(&skb->tcp_tsorted_anchor);
  790. return skb;
  791. }
  792. __kfree_skb(skb);
  793. } else {
  794. sk->sk_prot->enter_memory_pressure(sk);
  795. sk_stream_moderate_sndbuf(sk);
  796. }
  797. return NULL;
  798. }
  799. static unsigned int tcp_xmit_size_goal(struct sock *sk, u32 mss_now,
  800. int large_allowed)
  801. {
  802. struct tcp_sock *tp = tcp_sk(sk);
  803. u32 new_size_goal, size_goal;
  804. if (!large_allowed)
  805. return mss_now;
  806. /* Note : tcp_tso_autosize() will eventually split this later */
  807. new_size_goal = tcp_bound_to_half_wnd(tp, sk->sk_gso_max_size);
  808. /* We try hard to avoid divides here */
  809. size_goal = tp->gso_segs * mss_now;
  810. if (unlikely(new_size_goal < size_goal ||
  811. new_size_goal >= size_goal + mss_now)) {
  812. tp->gso_segs = min_t(u16, new_size_goal / mss_now,
  813. sk->sk_gso_max_segs);
  814. size_goal = tp->gso_segs * mss_now;
  815. }
  816. return max(size_goal, mss_now);
  817. }
  818. int tcp_send_mss(struct sock *sk, int *size_goal, int flags)
  819. {
  820. int mss_now;
  821. mss_now = tcp_current_mss(sk);
  822. *size_goal = tcp_xmit_size_goal(sk, mss_now, !(flags & MSG_OOB));
  823. return mss_now;
  824. }
  825. /* In some cases, both sendpage() and sendmsg() could have added
  826. * an skb to the write queue, but failed adding payload on it.
  827. * We need to remove it to consume less memory, but more
  828. * importantly be able to generate EPOLLOUT for Edge Trigger epoll()
  829. * users.
  830. */
  831. void tcp_remove_empty_skb(struct sock *sk)
  832. {
  833. struct sk_buff *skb = tcp_write_queue_tail(sk);
  834. if (skb && TCP_SKB_CB(skb)->seq == TCP_SKB_CB(skb)->end_seq) {
  835. tcp_unlink_write_queue(skb, sk);
  836. if (tcp_write_queue_empty(sk))
  837. tcp_chrono_stop(sk, TCP_CHRONO_BUSY);
  838. tcp_wmem_free_skb(sk, skb);
  839. }
  840. }
  841. /* skb changing from pure zc to mixed, must charge zc */
  842. static int tcp_downgrade_zcopy_pure(struct sock *sk, struct sk_buff *skb)
  843. {
  844. if (unlikely(skb_zcopy_pure(skb))) {
  845. u32 extra = skb->truesize -
  846. SKB_TRUESIZE(skb_end_offset(skb));
  847. if (!sk_wmem_schedule(sk, extra))
  848. return -ENOMEM;
  849. sk_mem_charge(sk, extra);
  850. skb_shinfo(skb)->flags &= ~SKBFL_PURE_ZEROCOPY;
  851. }
  852. return 0;
  853. }
  854. static int tcp_wmem_schedule(struct sock *sk, int copy)
  855. {
  856. int left;
  857. if (likely(sk_wmem_schedule(sk, copy)))
  858. return copy;
  859. /* We could be in trouble if we have nothing queued.
  860. * Use whatever is left in sk->sk_forward_alloc and tcp_wmem[0]
  861. * to guarantee some progress.
  862. */
  863. left = sock_net(sk)->ipv4.sysctl_tcp_wmem[0] - sk->sk_wmem_queued;
  864. if (left > 0)
  865. sk_forced_mem_schedule(sk, min(left, copy));
  866. return min(copy, sk->sk_forward_alloc);
  867. }
  868. static struct sk_buff *tcp_build_frag(struct sock *sk, int size_goal, int flags,
  869. struct page *page, int offset, size_t *size)
  870. {
  871. struct sk_buff *skb = tcp_write_queue_tail(sk);
  872. struct tcp_sock *tp = tcp_sk(sk);
  873. bool can_coalesce;
  874. int copy, i;
  875. if (!skb || (copy = size_goal - skb->len) <= 0 ||
  876. !tcp_skb_can_collapse_to(skb)) {
  877. new_segment:
  878. if (!sk_stream_memory_free(sk))
  879. return NULL;
  880. skb = tcp_stream_alloc_skb(sk, 0, sk->sk_allocation,
  881. tcp_rtx_and_write_queues_empty(sk));
  882. if (!skb)
  883. return NULL;
  884. #ifdef CONFIG_TLS_DEVICE
  885. skb->decrypted = !!(flags & MSG_SENDPAGE_DECRYPTED);
  886. #endif
  887. tcp_skb_entail(sk, skb);
  888. copy = size_goal;
  889. }
  890. if (copy > *size)
  891. copy = *size;
  892. i = skb_shinfo(skb)->nr_frags;
  893. can_coalesce = skb_can_coalesce(skb, i, page, offset);
  894. if (!can_coalesce && i >= READ_ONCE(sysctl_max_skb_frags)) {
  895. tcp_mark_push(tp, skb);
  896. goto new_segment;
  897. }
  898. if (tcp_downgrade_zcopy_pure(sk, skb))
  899. return NULL;
  900. copy = tcp_wmem_schedule(sk, copy);
  901. if (!copy)
  902. return NULL;
  903. if (can_coalesce) {
  904. skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy);
  905. } else {
  906. get_page(page);
  907. skb_fill_page_desc_noacc(skb, i, page, offset, copy);
  908. }
  909. if (!(flags & MSG_NO_SHARED_FRAGS))
  910. skb_shinfo(skb)->flags |= SKBFL_SHARED_FRAG;
  911. skb->len += copy;
  912. skb->data_len += copy;
  913. skb->truesize += copy;
  914. sk_wmem_queued_add(sk, copy);
  915. sk_mem_charge(sk, copy);
  916. WRITE_ONCE(tp->write_seq, tp->write_seq + copy);
  917. TCP_SKB_CB(skb)->end_seq += copy;
  918. tcp_skb_pcount_set(skb, 0);
  919. *size = copy;
  920. return skb;
  921. }
  922. ssize_t do_tcp_sendpages(struct sock *sk, struct page *page, int offset,
  923. size_t size, int flags)
  924. {
  925. struct tcp_sock *tp = tcp_sk(sk);
  926. int mss_now, size_goal;
  927. int err;
  928. ssize_t copied;
  929. long timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT);
  930. if (IS_ENABLED(CONFIG_DEBUG_VM) &&
  931. WARN_ONCE(!sendpage_ok(page),
  932. "page must not be a Slab one and have page_count > 0"))
  933. return -EINVAL;
  934. /* Wait for a connection to finish. One exception is TCP Fast Open
  935. * (passive side) where data is allowed to be sent before a connection
  936. * is fully established.
  937. */
  938. if (((1 << sk->sk_state) & ~(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT)) &&
  939. !tcp_passive_fastopen(sk)) {
  940. err = sk_stream_wait_connect(sk, &timeo);
  941. if (err != 0)
  942. goto out_err;
  943. }
  944. sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk);
  945. mss_now = tcp_send_mss(sk, &size_goal, flags);
  946. copied = 0;
  947. err = -EPIPE;
  948. if (sk->sk_err || (sk->sk_shutdown & SEND_SHUTDOWN))
  949. goto out_err;
  950. while (size > 0) {
  951. struct sk_buff *skb;
  952. size_t copy = size;
  953. skb = tcp_build_frag(sk, size_goal, flags, page, offset, &copy);
  954. if (!skb)
  955. goto wait_for_space;
  956. if (!copied)
  957. TCP_SKB_CB(skb)->tcp_flags &= ~TCPHDR_PSH;
  958. copied += copy;
  959. offset += copy;
  960. size -= copy;
  961. if (!size)
  962. goto out;
  963. if (skb->len < size_goal || (flags & MSG_OOB))
  964. continue;
  965. if (forced_push(tp)) {
  966. tcp_mark_push(tp, skb);
  967. __tcp_push_pending_frames(sk, mss_now, TCP_NAGLE_PUSH);
  968. } else if (skb == tcp_send_head(sk))
  969. tcp_push_one(sk, mss_now);
  970. continue;
  971. wait_for_space:
  972. set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
  973. tcp_push(sk, flags & ~MSG_MORE, mss_now,
  974. TCP_NAGLE_PUSH, size_goal);
  975. err = sk_stream_wait_memory(sk, &timeo);
  976. if (err != 0)
  977. goto do_error;
  978. mss_now = tcp_send_mss(sk, &size_goal, flags);
  979. }
  980. out:
  981. if (copied) {
  982. tcp_tx_timestamp(sk, sk->sk_tsflags);
  983. if (!(flags & MSG_SENDPAGE_NOTLAST))
  984. tcp_push(sk, flags, mss_now, tp->nonagle, size_goal);
  985. }
  986. return copied;
  987. do_error:
  988. tcp_remove_empty_skb(sk);
  989. if (copied)
  990. goto out;
  991. out_err:
  992. /* make sure we wake any epoll edge trigger waiter */
  993. if (unlikely(tcp_rtx_and_write_queues_empty(sk) && err == -EAGAIN)) {
  994. sk->sk_write_space(sk);
  995. tcp_chrono_stop(sk, TCP_CHRONO_SNDBUF_LIMITED);
  996. }
  997. return sk_stream_error(sk, flags, err);
  998. }
  999. EXPORT_SYMBOL_GPL(do_tcp_sendpages);
  1000. int tcp_sendpage_locked(struct sock *sk, struct page *page, int offset,
  1001. size_t size, int flags)
  1002. {
  1003. if (!(sk->sk_route_caps & NETIF_F_SG))
  1004. return sock_no_sendpage_locked(sk, page, offset, size, flags);
  1005. tcp_rate_check_app_limited(sk); /* is sending application-limited? */
  1006. return do_tcp_sendpages(sk, page, offset, size, flags);
  1007. }
  1008. EXPORT_SYMBOL_GPL(tcp_sendpage_locked);
  1009. int tcp_sendpage(struct sock *sk, struct page *page, int offset,
  1010. size_t size, int flags)
  1011. {
  1012. int ret;
  1013. lock_sock(sk);
  1014. ret = tcp_sendpage_locked(sk, page, offset, size, flags);
  1015. release_sock(sk);
  1016. return ret;
  1017. }
  1018. EXPORT_SYMBOL(tcp_sendpage);
  1019. void tcp_free_fastopen_req(struct tcp_sock *tp)
  1020. {
  1021. if (tp->fastopen_req) {
  1022. kfree(tp->fastopen_req);
  1023. tp->fastopen_req = NULL;
  1024. }
  1025. }
  1026. int tcp_sendmsg_fastopen(struct sock *sk, struct msghdr *msg, int *copied,
  1027. size_t size, struct ubuf_info *uarg)
  1028. {
  1029. struct tcp_sock *tp = tcp_sk(sk);
  1030. struct inet_sock *inet = inet_sk(sk);
  1031. struct sockaddr *uaddr = msg->msg_name;
  1032. int err, flags;
  1033. if (!(READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_fastopen) &
  1034. TFO_CLIENT_ENABLE) ||
  1035. (uaddr && msg->msg_namelen >= sizeof(uaddr->sa_family) &&
  1036. uaddr->sa_family == AF_UNSPEC))
  1037. return -EOPNOTSUPP;
  1038. if (tp->fastopen_req)
  1039. return -EALREADY; /* Another Fast Open is in progress */
  1040. tp->fastopen_req = kzalloc(sizeof(struct tcp_fastopen_request),
  1041. sk->sk_allocation);
  1042. if (unlikely(!tp->fastopen_req))
  1043. return -ENOBUFS;
  1044. tp->fastopen_req->data = msg;
  1045. tp->fastopen_req->size = size;
  1046. tp->fastopen_req->uarg = uarg;
  1047. if (inet->defer_connect) {
  1048. err = tcp_connect(sk);
  1049. /* Same failure procedure as in tcp_v4/6_connect */
  1050. if (err) {
  1051. tcp_set_state(sk, TCP_CLOSE);
  1052. inet->inet_dport = 0;
  1053. sk->sk_route_caps = 0;
  1054. }
  1055. }
  1056. flags = (msg->msg_flags & MSG_DONTWAIT) ? O_NONBLOCK : 0;
  1057. err = __inet_stream_connect(sk->sk_socket, uaddr,
  1058. msg->msg_namelen, flags, 1);
  1059. /* fastopen_req could already be freed in __inet_stream_connect
  1060. * if the connection times out or gets rst
  1061. */
  1062. if (tp->fastopen_req) {
  1063. *copied = tp->fastopen_req->copied;
  1064. tcp_free_fastopen_req(tp);
  1065. inet->defer_connect = 0;
  1066. }
  1067. return err;
  1068. }
  1069. int tcp_sendmsg_locked(struct sock *sk, struct msghdr *msg, size_t size)
  1070. {
  1071. struct tcp_sock *tp = tcp_sk(sk);
  1072. struct ubuf_info *uarg = NULL;
  1073. struct sk_buff *skb;
  1074. struct sockcm_cookie sockc;
  1075. int flags, err, copied = 0;
  1076. int mss_now = 0, size_goal, copied_syn = 0;
  1077. int process_backlog = 0;
  1078. bool zc = false;
  1079. long timeo;
  1080. flags = msg->msg_flags;
  1081. if ((flags & MSG_ZEROCOPY) && size) {
  1082. skb = tcp_write_queue_tail(sk);
  1083. if (msg->msg_ubuf) {
  1084. uarg = msg->msg_ubuf;
  1085. net_zcopy_get(uarg);
  1086. zc = sk->sk_route_caps & NETIF_F_SG;
  1087. } else if (sock_flag(sk, SOCK_ZEROCOPY)) {
  1088. uarg = msg_zerocopy_realloc(sk, size, skb_zcopy(skb));
  1089. if (!uarg) {
  1090. err = -ENOBUFS;
  1091. goto out_err;
  1092. }
  1093. zc = sk->sk_route_caps & NETIF_F_SG;
  1094. if (!zc)
  1095. uarg_to_msgzc(uarg)->zerocopy = 0;
  1096. }
  1097. }
  1098. if (unlikely(flags & MSG_FASTOPEN || inet_sk(sk)->defer_connect) &&
  1099. !tp->repair) {
  1100. err = tcp_sendmsg_fastopen(sk, msg, &copied_syn, size, uarg);
  1101. if (err == -EINPROGRESS && copied_syn > 0)
  1102. goto out;
  1103. else if (err)
  1104. goto out_err;
  1105. }
  1106. timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT);
  1107. tcp_rate_check_app_limited(sk); /* is sending application-limited? */
  1108. /* Wait for a connection to finish. One exception is TCP Fast Open
  1109. * (passive side) where data is allowed to be sent before a connection
  1110. * is fully established.
  1111. */
  1112. if (((1 << sk->sk_state) & ~(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT)) &&
  1113. !tcp_passive_fastopen(sk)) {
  1114. err = sk_stream_wait_connect(sk, &timeo);
  1115. if (err != 0)
  1116. goto do_error;
  1117. }
  1118. if (unlikely(tp->repair)) {
  1119. if (tp->repair_queue == TCP_RECV_QUEUE) {
  1120. copied = tcp_send_rcvq(sk, msg, size);
  1121. goto out_nopush;
  1122. }
  1123. err = -EINVAL;
  1124. if (tp->repair_queue == TCP_NO_QUEUE)
  1125. goto out_err;
  1126. /* 'common' sending to sendq */
  1127. }
  1128. sockcm_init(&sockc, sk);
  1129. if (msg->msg_controllen) {
  1130. err = sock_cmsg_send(sk, msg, &sockc);
  1131. if (unlikely(err)) {
  1132. err = -EINVAL;
  1133. goto out_err;
  1134. }
  1135. }
  1136. /* This should be in poll */
  1137. sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk);
  1138. /* Ok commence sending. */
  1139. copied = 0;
  1140. restart:
  1141. mss_now = tcp_send_mss(sk, &size_goal, flags);
  1142. err = -EPIPE;
  1143. if (sk->sk_err || (sk->sk_shutdown & SEND_SHUTDOWN))
  1144. goto do_error;
  1145. while (msg_data_left(msg)) {
  1146. int copy = 0;
  1147. skb = tcp_write_queue_tail(sk);
  1148. if (skb)
  1149. copy = size_goal - skb->len;
  1150. if (copy <= 0 || !tcp_skb_can_collapse_to(skb)) {
  1151. bool first_skb;
  1152. new_segment:
  1153. if (!sk_stream_memory_free(sk))
  1154. goto wait_for_space;
  1155. if (unlikely(process_backlog >= 16)) {
  1156. process_backlog = 0;
  1157. if (sk_flush_backlog(sk))
  1158. goto restart;
  1159. }
  1160. first_skb = tcp_rtx_and_write_queues_empty(sk);
  1161. skb = tcp_stream_alloc_skb(sk, 0, sk->sk_allocation,
  1162. first_skb);
  1163. if (!skb)
  1164. goto wait_for_space;
  1165. process_backlog++;
  1166. tcp_skb_entail(sk, skb);
  1167. copy = size_goal;
  1168. /* All packets are restored as if they have
  1169. * already been sent. skb_mstamp_ns isn't set to
  1170. * avoid wrong rtt estimation.
  1171. */
  1172. if (tp->repair)
  1173. TCP_SKB_CB(skb)->sacked |= TCPCB_REPAIRED;
  1174. }
  1175. /* Try to append data to the end of skb. */
  1176. if (copy > msg_data_left(msg))
  1177. copy = msg_data_left(msg);
  1178. if (!zc) {
  1179. bool merge = true;
  1180. int i = skb_shinfo(skb)->nr_frags;
  1181. struct page_frag *pfrag = sk_page_frag(sk);
  1182. if (!sk_page_frag_refill(sk, pfrag))
  1183. goto wait_for_space;
  1184. if (!skb_can_coalesce(skb, i, pfrag->page,
  1185. pfrag->offset)) {
  1186. if (i >= READ_ONCE(sysctl_max_skb_frags)) {
  1187. tcp_mark_push(tp, skb);
  1188. goto new_segment;
  1189. }
  1190. merge = false;
  1191. }
  1192. copy = min_t(int, copy, pfrag->size - pfrag->offset);
  1193. if (unlikely(skb_zcopy_pure(skb) || skb_zcopy_managed(skb))) {
  1194. if (tcp_downgrade_zcopy_pure(sk, skb))
  1195. goto wait_for_space;
  1196. skb_zcopy_downgrade_managed(skb);
  1197. }
  1198. copy = tcp_wmem_schedule(sk, copy);
  1199. if (!copy)
  1200. goto wait_for_space;
  1201. err = skb_copy_to_page_nocache(sk, &msg->msg_iter, skb,
  1202. pfrag->page,
  1203. pfrag->offset,
  1204. copy);
  1205. if (err)
  1206. goto do_error;
  1207. /* Update the skb. */
  1208. if (merge) {
  1209. skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy);
  1210. } else {
  1211. skb_fill_page_desc(skb, i, pfrag->page,
  1212. pfrag->offset, copy);
  1213. page_ref_inc(pfrag->page);
  1214. }
  1215. pfrag->offset += copy;
  1216. } else {
  1217. /* First append to a fragless skb builds initial
  1218. * pure zerocopy skb
  1219. */
  1220. if (!skb->len)
  1221. skb_shinfo(skb)->flags |= SKBFL_PURE_ZEROCOPY;
  1222. if (!skb_zcopy_pure(skb)) {
  1223. copy = tcp_wmem_schedule(sk, copy);
  1224. if (!copy)
  1225. goto wait_for_space;
  1226. }
  1227. err = skb_zerocopy_iter_stream(sk, skb, msg, copy, uarg);
  1228. if (err == -EMSGSIZE || err == -EEXIST) {
  1229. tcp_mark_push(tp, skb);
  1230. goto new_segment;
  1231. }
  1232. if (err < 0)
  1233. goto do_error;
  1234. copy = err;
  1235. }
  1236. if (!copied)
  1237. TCP_SKB_CB(skb)->tcp_flags &= ~TCPHDR_PSH;
  1238. WRITE_ONCE(tp->write_seq, tp->write_seq + copy);
  1239. TCP_SKB_CB(skb)->end_seq += copy;
  1240. tcp_skb_pcount_set(skb, 0);
  1241. copied += copy;
  1242. if (!msg_data_left(msg)) {
  1243. if (unlikely(flags & MSG_EOR))
  1244. TCP_SKB_CB(skb)->eor = 1;
  1245. goto out;
  1246. }
  1247. if (skb->len < size_goal || (flags & MSG_OOB) || unlikely(tp->repair))
  1248. continue;
  1249. if (forced_push(tp)) {
  1250. tcp_mark_push(tp, skb);
  1251. __tcp_push_pending_frames(sk, mss_now, TCP_NAGLE_PUSH);
  1252. } else if (skb == tcp_send_head(sk))
  1253. tcp_push_one(sk, mss_now);
  1254. continue;
  1255. wait_for_space:
  1256. set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
  1257. if (copied)
  1258. tcp_push(sk, flags & ~MSG_MORE, mss_now,
  1259. TCP_NAGLE_PUSH, size_goal);
  1260. err = sk_stream_wait_memory(sk, &timeo);
  1261. if (err != 0)
  1262. goto do_error;
  1263. mss_now = tcp_send_mss(sk, &size_goal, flags);
  1264. }
  1265. out:
  1266. if (copied) {
  1267. tcp_tx_timestamp(sk, sockc.tsflags);
  1268. tcp_push(sk, flags, mss_now, tp->nonagle, size_goal);
  1269. }
  1270. out_nopush:
  1271. net_zcopy_put(uarg);
  1272. return copied + copied_syn;
  1273. do_error:
  1274. tcp_remove_empty_skb(sk);
  1275. if (copied + copied_syn)
  1276. goto out;
  1277. out_err:
  1278. net_zcopy_put_abort(uarg, true);
  1279. err = sk_stream_error(sk, flags, err);
  1280. /* make sure we wake any epoll edge trigger waiter */
  1281. if (unlikely(tcp_rtx_and_write_queues_empty(sk) && err == -EAGAIN)) {
  1282. sk->sk_write_space(sk);
  1283. tcp_chrono_stop(sk, TCP_CHRONO_SNDBUF_LIMITED);
  1284. }
  1285. return err;
  1286. }
  1287. EXPORT_SYMBOL_GPL(tcp_sendmsg_locked);
  1288. int tcp_sendmsg(struct sock *sk, struct msghdr *msg, size_t size)
  1289. {
  1290. int ret;
  1291. lock_sock(sk);
  1292. ret = tcp_sendmsg_locked(sk, msg, size);
  1293. release_sock(sk);
  1294. return ret;
  1295. }
  1296. EXPORT_SYMBOL(tcp_sendmsg);
  1297. /*
  1298. * Handle reading urgent data. BSD has very simple semantics for
  1299. * this, no blocking and very strange errors 8)
  1300. */
  1301. static int tcp_recv_urg(struct sock *sk, struct msghdr *msg, int len, int flags)
  1302. {
  1303. struct tcp_sock *tp = tcp_sk(sk);
  1304. /* No URG data to read. */
  1305. if (sock_flag(sk, SOCK_URGINLINE) || !tp->urg_data ||
  1306. tp->urg_data == TCP_URG_READ)
  1307. return -EINVAL; /* Yes this is right ! */
  1308. if (sk->sk_state == TCP_CLOSE && !sock_flag(sk, SOCK_DONE))
  1309. return -ENOTCONN;
  1310. if (tp->urg_data & TCP_URG_VALID) {
  1311. int err = 0;
  1312. char c = tp->urg_data;
  1313. if (!(flags & MSG_PEEK))
  1314. WRITE_ONCE(tp->urg_data, TCP_URG_READ);
  1315. /* Read urgent data. */
  1316. msg->msg_flags |= MSG_OOB;
  1317. if (len > 0) {
  1318. if (!(flags & MSG_TRUNC))
  1319. err = memcpy_to_msg(msg, &c, 1);
  1320. len = 1;
  1321. } else
  1322. msg->msg_flags |= MSG_TRUNC;
  1323. return err ? -EFAULT : len;
  1324. }
  1325. if (sk->sk_state == TCP_CLOSE || (sk->sk_shutdown & RCV_SHUTDOWN))
  1326. return 0;
  1327. /* Fixed the recv(..., MSG_OOB) behaviour. BSD docs and
  1328. * the available implementations agree in this case:
  1329. * this call should never block, independent of the
  1330. * blocking state of the socket.
  1331. * Mike <[email protected]>
  1332. */
  1333. return -EAGAIN;
  1334. }
  1335. static int tcp_peek_sndq(struct sock *sk, struct msghdr *msg, int len)
  1336. {
  1337. struct sk_buff *skb;
  1338. int copied = 0, err = 0;
  1339. /* XXX -- need to support SO_PEEK_OFF */
  1340. skb_rbtree_walk(skb, &sk->tcp_rtx_queue) {
  1341. err = skb_copy_datagram_msg(skb, 0, msg, skb->len);
  1342. if (err)
  1343. return err;
  1344. copied += skb->len;
  1345. }
  1346. skb_queue_walk(&sk->sk_write_queue, skb) {
  1347. err = skb_copy_datagram_msg(skb, 0, msg, skb->len);
  1348. if (err)
  1349. break;
  1350. copied += skb->len;
  1351. }
  1352. return err ?: copied;
  1353. }
  1354. /* Clean up the receive buffer for full frames taken by the user,
  1355. * then send an ACK if necessary. COPIED is the number of bytes
  1356. * tcp_recvmsg has given to the user so far, it speeds up the
  1357. * calculation of whether or not we must ACK for the sake of
  1358. * a window update.
  1359. */
  1360. void __tcp_cleanup_rbuf(struct sock *sk, int copied)
  1361. {
  1362. struct tcp_sock *tp = tcp_sk(sk);
  1363. bool time_to_ack = false;
  1364. if (inet_csk_ack_scheduled(sk)) {
  1365. const struct inet_connection_sock *icsk = inet_csk(sk);
  1366. if (/* Once-per-two-segments ACK was not sent by tcp_input.c */
  1367. tp->rcv_nxt - tp->rcv_wup > icsk->icsk_ack.rcv_mss ||
  1368. /*
  1369. * If this read emptied read buffer, we send ACK, if
  1370. * connection is not bidirectional, user drained
  1371. * receive buffer and there was a small segment
  1372. * in queue.
  1373. */
  1374. (copied > 0 &&
  1375. ((icsk->icsk_ack.pending & ICSK_ACK_PUSHED2) ||
  1376. ((icsk->icsk_ack.pending & ICSK_ACK_PUSHED) &&
  1377. !inet_csk_in_pingpong_mode(sk))) &&
  1378. !atomic_read(&sk->sk_rmem_alloc)))
  1379. time_to_ack = true;
  1380. }
  1381. /* We send an ACK if we can now advertise a non-zero window
  1382. * which has been raised "significantly".
  1383. *
  1384. * Even if window raised up to infinity, do not send window open ACK
  1385. * in states, where we will not receive more. It is useless.
  1386. */
  1387. if (copied > 0 && !time_to_ack && !(sk->sk_shutdown & RCV_SHUTDOWN)) {
  1388. __u32 rcv_window_now = tcp_receive_window(tp);
  1389. /* Optimize, __tcp_select_window() is not cheap. */
  1390. if (2*rcv_window_now <= tp->window_clamp) {
  1391. __u32 new_window = __tcp_select_window(sk);
  1392. /* Send ACK now, if this read freed lots of space
  1393. * in our buffer. Certainly, new_window is new window.
  1394. * We can advertise it now, if it is not less than current one.
  1395. * "Lots" means "at least twice" here.
  1396. */
  1397. if (new_window && new_window >= 2 * rcv_window_now)
  1398. time_to_ack = true;
  1399. }
  1400. }
  1401. if (time_to_ack)
  1402. tcp_send_ack(sk);
  1403. }
  1404. void tcp_cleanup_rbuf(struct sock *sk, int copied)
  1405. {
  1406. struct sk_buff *skb = skb_peek(&sk->sk_receive_queue);
  1407. struct tcp_sock *tp = tcp_sk(sk);
  1408. WARN(skb && !before(tp->copied_seq, TCP_SKB_CB(skb)->end_seq),
  1409. "cleanup rbuf bug: copied %X seq %X rcvnxt %X\n",
  1410. tp->copied_seq, TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt);
  1411. __tcp_cleanup_rbuf(sk, copied);
  1412. }
  1413. static void tcp_eat_recv_skb(struct sock *sk, struct sk_buff *skb)
  1414. {
  1415. __skb_unlink(skb, &sk->sk_receive_queue);
  1416. if (likely(skb->destructor == sock_rfree)) {
  1417. sock_rfree(skb);
  1418. skb->destructor = NULL;
  1419. skb->sk = NULL;
  1420. return skb_attempt_defer_free(skb);
  1421. }
  1422. __kfree_skb(skb);
  1423. }
  1424. struct sk_buff *tcp_recv_skb(struct sock *sk, u32 seq, u32 *off)
  1425. {
  1426. struct sk_buff *skb;
  1427. u32 offset;
  1428. while ((skb = skb_peek(&sk->sk_receive_queue)) != NULL) {
  1429. offset = seq - TCP_SKB_CB(skb)->seq;
  1430. if (unlikely(TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN)) {
  1431. pr_err_once("%s: found a SYN, please report !\n", __func__);
  1432. offset--;
  1433. }
  1434. if (offset < skb->len || (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)) {
  1435. *off = offset;
  1436. return skb;
  1437. }
  1438. /* This looks weird, but this can happen if TCP collapsing
  1439. * splitted a fat GRO packet, while we released socket lock
  1440. * in skb_splice_bits()
  1441. */
  1442. tcp_eat_recv_skb(sk, skb);
  1443. }
  1444. return NULL;
  1445. }
  1446. EXPORT_SYMBOL(tcp_recv_skb);
  1447. /*
  1448. * This routine provides an alternative to tcp_recvmsg() for routines
  1449. * that would like to handle copying from skbuffs directly in 'sendfile'
  1450. * fashion.
  1451. * Note:
  1452. * - It is assumed that the socket was locked by the caller.
  1453. * - The routine does not block.
  1454. * - At present, there is no support for reading OOB data
  1455. * or for 'peeking' the socket using this routine
  1456. * (although both would be easy to implement).
  1457. */
  1458. int tcp_read_sock(struct sock *sk, read_descriptor_t *desc,
  1459. sk_read_actor_t recv_actor)
  1460. {
  1461. struct sk_buff *skb;
  1462. struct tcp_sock *tp = tcp_sk(sk);
  1463. u32 seq = tp->copied_seq;
  1464. u32 offset;
  1465. int copied = 0;
  1466. if (sk->sk_state == TCP_LISTEN)
  1467. return -ENOTCONN;
  1468. while ((skb = tcp_recv_skb(sk, seq, &offset)) != NULL) {
  1469. if (offset < skb->len) {
  1470. int used;
  1471. size_t len;
  1472. len = skb->len - offset;
  1473. /* Stop reading if we hit a patch of urgent data */
  1474. if (unlikely(tp->urg_data)) {
  1475. u32 urg_offset = tp->urg_seq - seq;
  1476. if (urg_offset < len)
  1477. len = urg_offset;
  1478. if (!len)
  1479. break;
  1480. }
  1481. used = recv_actor(desc, skb, offset, len);
  1482. if (used <= 0) {
  1483. if (!copied)
  1484. copied = used;
  1485. break;
  1486. }
  1487. if (WARN_ON_ONCE(used > len))
  1488. used = len;
  1489. seq += used;
  1490. copied += used;
  1491. offset += used;
  1492. /* If recv_actor drops the lock (e.g. TCP splice
  1493. * receive) the skb pointer might be invalid when
  1494. * getting here: tcp_collapse might have deleted it
  1495. * while aggregating skbs from the socket queue.
  1496. */
  1497. skb = tcp_recv_skb(sk, seq - 1, &offset);
  1498. if (!skb)
  1499. break;
  1500. /* TCP coalescing might have appended data to the skb.
  1501. * Try to splice more frags
  1502. */
  1503. if (offset + 1 != skb->len)
  1504. continue;
  1505. }
  1506. if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN) {
  1507. tcp_eat_recv_skb(sk, skb);
  1508. ++seq;
  1509. break;
  1510. }
  1511. tcp_eat_recv_skb(sk, skb);
  1512. if (!desc->count)
  1513. break;
  1514. WRITE_ONCE(tp->copied_seq, seq);
  1515. }
  1516. WRITE_ONCE(tp->copied_seq, seq);
  1517. tcp_rcv_space_adjust(sk);
  1518. /* Clean up data we have read: This will do ACK frames. */
  1519. if (copied > 0) {
  1520. tcp_recv_skb(sk, seq, &offset);
  1521. tcp_cleanup_rbuf(sk, copied);
  1522. }
  1523. return copied;
  1524. }
  1525. EXPORT_SYMBOL(tcp_read_sock);
  1526. int tcp_read_skb(struct sock *sk, skb_read_actor_t recv_actor)
  1527. {
  1528. struct sk_buff *skb;
  1529. int copied = 0;
  1530. if (sk->sk_state == TCP_LISTEN)
  1531. return -ENOTCONN;
  1532. while ((skb = skb_peek(&sk->sk_receive_queue)) != NULL) {
  1533. u8 tcp_flags;
  1534. int used;
  1535. __skb_unlink(skb, &sk->sk_receive_queue);
  1536. WARN_ON_ONCE(!skb_set_owner_sk_safe(skb, sk));
  1537. tcp_flags = TCP_SKB_CB(skb)->tcp_flags;
  1538. used = recv_actor(sk, skb);
  1539. if (used < 0) {
  1540. if (!copied)
  1541. copied = used;
  1542. break;
  1543. }
  1544. copied += used;
  1545. if (tcp_flags & TCPHDR_FIN)
  1546. break;
  1547. }
  1548. return copied;
  1549. }
  1550. EXPORT_SYMBOL(tcp_read_skb);
  1551. void tcp_read_done(struct sock *sk, size_t len)
  1552. {
  1553. struct tcp_sock *tp = tcp_sk(sk);
  1554. u32 seq = tp->copied_seq;
  1555. struct sk_buff *skb;
  1556. size_t left;
  1557. u32 offset;
  1558. if (sk->sk_state == TCP_LISTEN)
  1559. return;
  1560. left = len;
  1561. while (left && (skb = tcp_recv_skb(sk, seq, &offset)) != NULL) {
  1562. int used;
  1563. used = min_t(size_t, skb->len - offset, left);
  1564. seq += used;
  1565. left -= used;
  1566. if (skb->len > offset + used)
  1567. break;
  1568. if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN) {
  1569. tcp_eat_recv_skb(sk, skb);
  1570. ++seq;
  1571. break;
  1572. }
  1573. tcp_eat_recv_skb(sk, skb);
  1574. }
  1575. WRITE_ONCE(tp->copied_seq, seq);
  1576. tcp_rcv_space_adjust(sk);
  1577. /* Clean up data we have read: This will do ACK frames. */
  1578. if (left != len)
  1579. tcp_cleanup_rbuf(sk, len - left);
  1580. }
  1581. EXPORT_SYMBOL(tcp_read_done);
  1582. int tcp_peek_len(struct socket *sock)
  1583. {
  1584. return tcp_inq(sock->sk);
  1585. }
  1586. EXPORT_SYMBOL(tcp_peek_len);
  1587. /* Make sure sk_rcvbuf is big enough to satisfy SO_RCVLOWAT hint */
  1588. int tcp_set_rcvlowat(struct sock *sk, int val)
  1589. {
  1590. int cap;
  1591. if (sk->sk_userlocks & SOCK_RCVBUF_LOCK)
  1592. cap = sk->sk_rcvbuf >> 1;
  1593. else
  1594. cap = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_rmem[2]) >> 1;
  1595. val = min(val, cap);
  1596. WRITE_ONCE(sk->sk_rcvlowat, val ? : 1);
  1597. /* Check if we need to signal EPOLLIN right now */
  1598. tcp_data_ready(sk);
  1599. if (sk->sk_userlocks & SOCK_RCVBUF_LOCK)
  1600. return 0;
  1601. val <<= 1;
  1602. if (val > sk->sk_rcvbuf) {
  1603. WRITE_ONCE(sk->sk_rcvbuf, val);
  1604. tcp_sk(sk)->window_clamp = tcp_win_from_space(sk, val);
  1605. }
  1606. return 0;
  1607. }
  1608. EXPORT_SYMBOL(tcp_set_rcvlowat);
  1609. void tcp_update_recv_tstamps(struct sk_buff *skb,
  1610. struct scm_timestamping_internal *tss)
  1611. {
  1612. if (skb->tstamp)
  1613. tss->ts[0] = ktime_to_timespec64(skb->tstamp);
  1614. else
  1615. tss->ts[0] = (struct timespec64) {0};
  1616. if (skb_hwtstamps(skb)->hwtstamp)
  1617. tss->ts[2] = ktime_to_timespec64(skb_hwtstamps(skb)->hwtstamp);
  1618. else
  1619. tss->ts[2] = (struct timespec64) {0};
  1620. }
  1621. #ifdef CONFIG_MMU
  1622. static const struct vm_operations_struct tcp_vm_ops = {
  1623. };
  1624. int tcp_mmap(struct file *file, struct socket *sock,
  1625. struct vm_area_struct *vma)
  1626. {
  1627. if (vma->vm_flags & (VM_WRITE | VM_EXEC))
  1628. return -EPERM;
  1629. vm_flags_clear(vma, VM_MAYWRITE | VM_MAYEXEC);
  1630. /* Instruct vm_insert_page() to not mmap_read_lock(mm) */
  1631. vm_flags_set(vma, VM_MIXEDMAP);
  1632. vma->vm_ops = &tcp_vm_ops;
  1633. return 0;
  1634. }
  1635. EXPORT_SYMBOL(tcp_mmap);
  1636. static skb_frag_t *skb_advance_to_frag(struct sk_buff *skb, u32 offset_skb,
  1637. u32 *offset_frag)
  1638. {
  1639. skb_frag_t *frag;
  1640. if (unlikely(offset_skb >= skb->len))
  1641. return NULL;
  1642. offset_skb -= skb_headlen(skb);
  1643. if ((int)offset_skb < 0 || skb_has_frag_list(skb))
  1644. return NULL;
  1645. frag = skb_shinfo(skb)->frags;
  1646. while (offset_skb) {
  1647. if (skb_frag_size(frag) > offset_skb) {
  1648. *offset_frag = offset_skb;
  1649. return frag;
  1650. }
  1651. offset_skb -= skb_frag_size(frag);
  1652. ++frag;
  1653. }
  1654. *offset_frag = 0;
  1655. return frag;
  1656. }
  1657. static bool can_map_frag(const skb_frag_t *frag)
  1658. {
  1659. return skb_frag_size(frag) == PAGE_SIZE && !skb_frag_off(frag);
  1660. }
  1661. static int find_next_mappable_frag(const skb_frag_t *frag,
  1662. int remaining_in_skb)
  1663. {
  1664. int offset = 0;
  1665. if (likely(can_map_frag(frag)))
  1666. return 0;
  1667. while (offset < remaining_in_skb && !can_map_frag(frag)) {
  1668. offset += skb_frag_size(frag);
  1669. ++frag;
  1670. }
  1671. return offset;
  1672. }
  1673. static void tcp_zerocopy_set_hint_for_skb(struct sock *sk,
  1674. struct tcp_zerocopy_receive *zc,
  1675. struct sk_buff *skb, u32 offset)
  1676. {
  1677. u32 frag_offset, partial_frag_remainder = 0;
  1678. int mappable_offset;
  1679. skb_frag_t *frag;
  1680. /* worst case: skip to next skb. try to improve on this case below */
  1681. zc->recv_skip_hint = skb->len - offset;
  1682. /* Find the frag containing this offset (and how far into that frag) */
  1683. frag = skb_advance_to_frag(skb, offset, &frag_offset);
  1684. if (!frag)
  1685. return;
  1686. if (frag_offset) {
  1687. struct skb_shared_info *info = skb_shinfo(skb);
  1688. /* We read part of the last frag, must recvmsg() rest of skb. */
  1689. if (frag == &info->frags[info->nr_frags - 1])
  1690. return;
  1691. /* Else, we must at least read the remainder in this frag. */
  1692. partial_frag_remainder = skb_frag_size(frag) - frag_offset;
  1693. zc->recv_skip_hint -= partial_frag_remainder;
  1694. ++frag;
  1695. }
  1696. /* partial_frag_remainder: If part way through a frag, must read rest.
  1697. * mappable_offset: Bytes till next mappable frag, *not* counting bytes
  1698. * in partial_frag_remainder.
  1699. */
  1700. mappable_offset = find_next_mappable_frag(frag, zc->recv_skip_hint);
  1701. zc->recv_skip_hint = mappable_offset + partial_frag_remainder;
  1702. }
  1703. static int tcp_recvmsg_locked(struct sock *sk, struct msghdr *msg, size_t len,
  1704. int flags, struct scm_timestamping_internal *tss,
  1705. int *cmsg_flags);
  1706. static int receive_fallback_to_copy(struct sock *sk,
  1707. struct tcp_zerocopy_receive *zc, int inq,
  1708. struct scm_timestamping_internal *tss)
  1709. {
  1710. unsigned long copy_address = (unsigned long)zc->copybuf_address;
  1711. struct msghdr msg = {};
  1712. struct iovec iov;
  1713. int err;
  1714. zc->length = 0;
  1715. zc->recv_skip_hint = 0;
  1716. if (copy_address != zc->copybuf_address)
  1717. return -EINVAL;
  1718. err = import_single_range(ITER_DEST, (void __user *)copy_address,
  1719. inq, &iov, &msg.msg_iter);
  1720. if (err)
  1721. return err;
  1722. err = tcp_recvmsg_locked(sk, &msg, inq, MSG_DONTWAIT,
  1723. tss, &zc->msg_flags);
  1724. if (err < 0)
  1725. return err;
  1726. zc->copybuf_len = err;
  1727. if (likely(zc->copybuf_len)) {
  1728. struct sk_buff *skb;
  1729. u32 offset;
  1730. skb = tcp_recv_skb(sk, tcp_sk(sk)->copied_seq, &offset);
  1731. if (skb)
  1732. tcp_zerocopy_set_hint_for_skb(sk, zc, skb, offset);
  1733. }
  1734. return 0;
  1735. }
  1736. static int tcp_copy_straggler_data(struct tcp_zerocopy_receive *zc,
  1737. struct sk_buff *skb, u32 copylen,
  1738. u32 *offset, u32 *seq)
  1739. {
  1740. unsigned long copy_address = (unsigned long)zc->copybuf_address;
  1741. struct msghdr msg = {};
  1742. struct iovec iov;
  1743. int err;
  1744. if (copy_address != zc->copybuf_address)
  1745. return -EINVAL;
  1746. err = import_single_range(ITER_DEST, (void __user *)copy_address,
  1747. copylen, &iov, &msg.msg_iter);
  1748. if (err)
  1749. return err;
  1750. err = skb_copy_datagram_msg(skb, *offset, &msg, copylen);
  1751. if (err)
  1752. return err;
  1753. zc->recv_skip_hint -= copylen;
  1754. *offset += copylen;
  1755. *seq += copylen;
  1756. return (__s32)copylen;
  1757. }
  1758. static int tcp_zc_handle_leftover(struct tcp_zerocopy_receive *zc,
  1759. struct sock *sk,
  1760. struct sk_buff *skb,
  1761. u32 *seq,
  1762. s32 copybuf_len,
  1763. struct scm_timestamping_internal *tss)
  1764. {
  1765. u32 offset, copylen = min_t(u32, copybuf_len, zc->recv_skip_hint);
  1766. if (!copylen)
  1767. return 0;
  1768. /* skb is null if inq < PAGE_SIZE. */
  1769. if (skb) {
  1770. offset = *seq - TCP_SKB_CB(skb)->seq;
  1771. } else {
  1772. skb = tcp_recv_skb(sk, *seq, &offset);
  1773. if (TCP_SKB_CB(skb)->has_rxtstamp) {
  1774. tcp_update_recv_tstamps(skb, tss);
  1775. zc->msg_flags |= TCP_CMSG_TS;
  1776. }
  1777. }
  1778. zc->copybuf_len = tcp_copy_straggler_data(zc, skb, copylen, &offset,
  1779. seq);
  1780. return zc->copybuf_len < 0 ? 0 : copylen;
  1781. }
  1782. static int tcp_zerocopy_vm_insert_batch_error(struct vm_area_struct *vma,
  1783. struct page **pending_pages,
  1784. unsigned long pages_remaining,
  1785. unsigned long *address,
  1786. u32 *length,
  1787. u32 *seq,
  1788. struct tcp_zerocopy_receive *zc,
  1789. u32 total_bytes_to_map,
  1790. int err)
  1791. {
  1792. /* At least one page did not map. Try zapping if we skipped earlier. */
  1793. if (err == -EBUSY &&
  1794. zc->flags & TCP_RECEIVE_ZEROCOPY_FLAG_TLB_CLEAN_HINT) {
  1795. u32 maybe_zap_len;
  1796. maybe_zap_len = total_bytes_to_map - /* All bytes to map */
  1797. *length + /* Mapped or pending */
  1798. (pages_remaining * PAGE_SIZE); /* Failed map. */
  1799. zap_page_range(vma, *address, maybe_zap_len);
  1800. err = 0;
  1801. }
  1802. if (!err) {
  1803. unsigned long leftover_pages = pages_remaining;
  1804. int bytes_mapped;
  1805. /* We called zap_page_range, try to reinsert. */
  1806. err = vm_insert_pages(vma, *address,
  1807. pending_pages,
  1808. &pages_remaining);
  1809. bytes_mapped = PAGE_SIZE * (leftover_pages - pages_remaining);
  1810. *seq += bytes_mapped;
  1811. *address += bytes_mapped;
  1812. }
  1813. if (err) {
  1814. /* Either we were unable to zap, OR we zapped, retried an
  1815. * insert, and still had an issue. Either ways, pages_remaining
  1816. * is the number of pages we were unable to map, and we unroll
  1817. * some state we speculatively touched before.
  1818. */
  1819. const int bytes_not_mapped = PAGE_SIZE * pages_remaining;
  1820. *length -= bytes_not_mapped;
  1821. zc->recv_skip_hint += bytes_not_mapped;
  1822. }
  1823. return err;
  1824. }
  1825. static int tcp_zerocopy_vm_insert_batch(struct vm_area_struct *vma,
  1826. struct page **pages,
  1827. unsigned int pages_to_map,
  1828. unsigned long *address,
  1829. u32 *length,
  1830. u32 *seq,
  1831. struct tcp_zerocopy_receive *zc,
  1832. u32 total_bytes_to_map)
  1833. {
  1834. unsigned long pages_remaining = pages_to_map;
  1835. unsigned int pages_mapped;
  1836. unsigned int bytes_mapped;
  1837. int err;
  1838. err = vm_insert_pages(vma, *address, pages, &pages_remaining);
  1839. pages_mapped = pages_to_map - (unsigned int)pages_remaining;
  1840. bytes_mapped = PAGE_SIZE * pages_mapped;
  1841. /* Even if vm_insert_pages fails, it may have partially succeeded in
  1842. * mapping (some but not all of the pages).
  1843. */
  1844. *seq += bytes_mapped;
  1845. *address += bytes_mapped;
  1846. if (likely(!err))
  1847. return 0;
  1848. /* Error: maybe zap and retry + rollback state for failed inserts. */
  1849. return tcp_zerocopy_vm_insert_batch_error(vma, pages + pages_mapped,
  1850. pages_remaining, address, length, seq, zc, total_bytes_to_map,
  1851. err);
  1852. }
  1853. #define TCP_VALID_ZC_MSG_FLAGS (TCP_CMSG_TS)
  1854. static void tcp_zc_finalize_rx_tstamp(struct sock *sk,
  1855. struct tcp_zerocopy_receive *zc,
  1856. struct scm_timestamping_internal *tss)
  1857. {
  1858. unsigned long msg_control_addr;
  1859. struct msghdr cmsg_dummy;
  1860. msg_control_addr = (unsigned long)zc->msg_control;
  1861. cmsg_dummy.msg_control = (void *)msg_control_addr;
  1862. cmsg_dummy.msg_controllen =
  1863. (__kernel_size_t)zc->msg_controllen;
  1864. cmsg_dummy.msg_flags = in_compat_syscall()
  1865. ? MSG_CMSG_COMPAT : 0;
  1866. cmsg_dummy.msg_control_is_user = true;
  1867. zc->msg_flags = 0;
  1868. if (zc->msg_control == msg_control_addr &&
  1869. zc->msg_controllen == cmsg_dummy.msg_controllen) {
  1870. tcp_recv_timestamp(&cmsg_dummy, sk, tss);
  1871. zc->msg_control = (__u64)
  1872. ((uintptr_t)cmsg_dummy.msg_control);
  1873. zc->msg_controllen =
  1874. (__u64)cmsg_dummy.msg_controllen;
  1875. zc->msg_flags = (__u32)cmsg_dummy.msg_flags;
  1876. }
  1877. }
  1878. #define TCP_ZEROCOPY_PAGE_BATCH_SIZE 32
  1879. static int tcp_zerocopy_receive(struct sock *sk,
  1880. struct tcp_zerocopy_receive *zc,
  1881. struct scm_timestamping_internal *tss)
  1882. {
  1883. u32 length = 0, offset, vma_len, avail_len, copylen = 0;
  1884. unsigned long address = (unsigned long)zc->address;
  1885. struct page *pages[TCP_ZEROCOPY_PAGE_BATCH_SIZE];
  1886. s32 copybuf_len = zc->copybuf_len;
  1887. struct tcp_sock *tp = tcp_sk(sk);
  1888. const skb_frag_t *frags = NULL;
  1889. unsigned int pages_to_map = 0;
  1890. struct vm_area_struct *vma;
  1891. struct sk_buff *skb = NULL;
  1892. u32 seq = tp->copied_seq;
  1893. u32 total_bytes_to_map;
  1894. int inq = tcp_inq(sk);
  1895. int ret;
  1896. zc->copybuf_len = 0;
  1897. zc->msg_flags = 0;
  1898. if (address & (PAGE_SIZE - 1) || address != zc->address)
  1899. return -EINVAL;
  1900. if (sk->sk_state == TCP_LISTEN)
  1901. return -ENOTCONN;
  1902. sock_rps_record_flow(sk);
  1903. if (inq && inq <= copybuf_len)
  1904. return receive_fallback_to_copy(sk, zc, inq, tss);
  1905. if (inq < PAGE_SIZE) {
  1906. zc->length = 0;
  1907. zc->recv_skip_hint = inq;
  1908. if (!inq && sock_flag(sk, SOCK_DONE))
  1909. return -EIO;
  1910. return 0;
  1911. }
  1912. mmap_read_lock(current->mm);
  1913. vma = vma_lookup(current->mm, address);
  1914. if (!vma || vma->vm_ops != &tcp_vm_ops) {
  1915. mmap_read_unlock(current->mm);
  1916. return -EINVAL;
  1917. }
  1918. vma_len = min_t(unsigned long, zc->length, vma->vm_end - address);
  1919. avail_len = min_t(u32, vma_len, inq);
  1920. total_bytes_to_map = avail_len & ~(PAGE_SIZE - 1);
  1921. if (total_bytes_to_map) {
  1922. if (!(zc->flags & TCP_RECEIVE_ZEROCOPY_FLAG_TLB_CLEAN_HINT))
  1923. zap_page_range(vma, address, total_bytes_to_map);
  1924. zc->length = total_bytes_to_map;
  1925. zc->recv_skip_hint = 0;
  1926. } else {
  1927. zc->length = avail_len;
  1928. zc->recv_skip_hint = avail_len;
  1929. }
  1930. ret = 0;
  1931. while (length + PAGE_SIZE <= zc->length) {
  1932. int mappable_offset;
  1933. struct page *page;
  1934. if (zc->recv_skip_hint < PAGE_SIZE) {
  1935. u32 offset_frag;
  1936. if (skb) {
  1937. if (zc->recv_skip_hint > 0)
  1938. break;
  1939. skb = skb->next;
  1940. offset = seq - TCP_SKB_CB(skb)->seq;
  1941. } else {
  1942. skb = tcp_recv_skb(sk, seq, &offset);
  1943. }
  1944. if (TCP_SKB_CB(skb)->has_rxtstamp) {
  1945. tcp_update_recv_tstamps(skb, tss);
  1946. zc->msg_flags |= TCP_CMSG_TS;
  1947. }
  1948. zc->recv_skip_hint = skb->len - offset;
  1949. frags = skb_advance_to_frag(skb, offset, &offset_frag);
  1950. if (!frags || offset_frag)
  1951. break;
  1952. }
  1953. mappable_offset = find_next_mappable_frag(frags,
  1954. zc->recv_skip_hint);
  1955. if (mappable_offset) {
  1956. zc->recv_skip_hint = mappable_offset;
  1957. break;
  1958. }
  1959. page = skb_frag_page(frags);
  1960. prefetchw(page);
  1961. pages[pages_to_map++] = page;
  1962. length += PAGE_SIZE;
  1963. zc->recv_skip_hint -= PAGE_SIZE;
  1964. frags++;
  1965. if (pages_to_map == TCP_ZEROCOPY_PAGE_BATCH_SIZE ||
  1966. zc->recv_skip_hint < PAGE_SIZE) {
  1967. /* Either full batch, or we're about to go to next skb
  1968. * (and we cannot unroll failed ops across skbs).
  1969. */
  1970. ret = tcp_zerocopy_vm_insert_batch(vma, pages,
  1971. pages_to_map,
  1972. &address, &length,
  1973. &seq, zc,
  1974. total_bytes_to_map);
  1975. if (ret)
  1976. goto out;
  1977. pages_to_map = 0;
  1978. }
  1979. }
  1980. if (pages_to_map) {
  1981. ret = tcp_zerocopy_vm_insert_batch(vma, pages, pages_to_map,
  1982. &address, &length, &seq,
  1983. zc, total_bytes_to_map);
  1984. }
  1985. out:
  1986. mmap_read_unlock(current->mm);
  1987. /* Try to copy straggler data. */
  1988. if (!ret)
  1989. copylen = tcp_zc_handle_leftover(zc, sk, skb, &seq, copybuf_len, tss);
  1990. if (length + copylen) {
  1991. WRITE_ONCE(tp->copied_seq, seq);
  1992. tcp_rcv_space_adjust(sk);
  1993. /* Clean up data we have read: This will do ACK frames. */
  1994. tcp_recv_skb(sk, seq, &offset);
  1995. tcp_cleanup_rbuf(sk, length + copylen);
  1996. ret = 0;
  1997. if (length == zc->length)
  1998. zc->recv_skip_hint = 0;
  1999. } else {
  2000. if (!zc->recv_skip_hint && sock_flag(sk, SOCK_DONE))
  2001. ret = -EIO;
  2002. }
  2003. zc->length = length;
  2004. return ret;
  2005. }
  2006. #endif
  2007. /* Similar to __sock_recv_timestamp, but does not require an skb */
  2008. void tcp_recv_timestamp(struct msghdr *msg, const struct sock *sk,
  2009. struct scm_timestamping_internal *tss)
  2010. {
  2011. int new_tstamp = sock_flag(sk, SOCK_TSTAMP_NEW);
  2012. bool has_timestamping = false;
  2013. if (tss->ts[0].tv_sec || tss->ts[0].tv_nsec) {
  2014. if (sock_flag(sk, SOCK_RCVTSTAMP)) {
  2015. if (sock_flag(sk, SOCK_RCVTSTAMPNS)) {
  2016. if (new_tstamp) {
  2017. struct __kernel_timespec kts = {
  2018. .tv_sec = tss->ts[0].tv_sec,
  2019. .tv_nsec = tss->ts[0].tv_nsec,
  2020. };
  2021. put_cmsg(msg, SOL_SOCKET, SO_TIMESTAMPNS_NEW,
  2022. sizeof(kts), &kts);
  2023. } else {
  2024. struct __kernel_old_timespec ts_old = {
  2025. .tv_sec = tss->ts[0].tv_sec,
  2026. .tv_nsec = tss->ts[0].tv_nsec,
  2027. };
  2028. put_cmsg(msg, SOL_SOCKET, SO_TIMESTAMPNS_OLD,
  2029. sizeof(ts_old), &ts_old);
  2030. }
  2031. } else {
  2032. if (new_tstamp) {
  2033. struct __kernel_sock_timeval stv = {
  2034. .tv_sec = tss->ts[0].tv_sec,
  2035. .tv_usec = tss->ts[0].tv_nsec / 1000,
  2036. };
  2037. put_cmsg(msg, SOL_SOCKET, SO_TIMESTAMP_NEW,
  2038. sizeof(stv), &stv);
  2039. } else {
  2040. struct __kernel_old_timeval tv = {
  2041. .tv_sec = tss->ts[0].tv_sec,
  2042. .tv_usec = tss->ts[0].tv_nsec / 1000,
  2043. };
  2044. put_cmsg(msg, SOL_SOCKET, SO_TIMESTAMP_OLD,
  2045. sizeof(tv), &tv);
  2046. }
  2047. }
  2048. }
  2049. if (sk->sk_tsflags & SOF_TIMESTAMPING_SOFTWARE)
  2050. has_timestamping = true;
  2051. else
  2052. tss->ts[0] = (struct timespec64) {0};
  2053. }
  2054. if (tss->ts[2].tv_sec || tss->ts[2].tv_nsec) {
  2055. if (sk->sk_tsflags & SOF_TIMESTAMPING_RAW_HARDWARE)
  2056. has_timestamping = true;
  2057. else
  2058. tss->ts[2] = (struct timespec64) {0};
  2059. }
  2060. if (has_timestamping) {
  2061. tss->ts[1] = (struct timespec64) {0};
  2062. if (sock_flag(sk, SOCK_TSTAMP_NEW))
  2063. put_cmsg_scm_timestamping64(msg, tss);
  2064. else
  2065. put_cmsg_scm_timestamping(msg, tss);
  2066. }
  2067. }
  2068. static int tcp_inq_hint(struct sock *sk)
  2069. {
  2070. const struct tcp_sock *tp = tcp_sk(sk);
  2071. u32 copied_seq = READ_ONCE(tp->copied_seq);
  2072. u32 rcv_nxt = READ_ONCE(tp->rcv_nxt);
  2073. int inq;
  2074. inq = rcv_nxt - copied_seq;
  2075. if (unlikely(inq < 0 || copied_seq != READ_ONCE(tp->copied_seq))) {
  2076. lock_sock(sk);
  2077. inq = tp->rcv_nxt - tp->copied_seq;
  2078. release_sock(sk);
  2079. }
  2080. /* After receiving a FIN, tell the user-space to continue reading
  2081. * by returning a non-zero inq.
  2082. */
  2083. if (inq == 0 && sock_flag(sk, SOCK_DONE))
  2084. inq = 1;
  2085. return inq;
  2086. }
  2087. /*
  2088. * This routine copies from a sock struct into the user buffer.
  2089. *
  2090. * Technical note: in 2.3 we work on _locked_ socket, so that
  2091. * tricks with *seq access order and skb->users are not required.
  2092. * Probably, code can be easily improved even more.
  2093. */
  2094. static int tcp_recvmsg_locked(struct sock *sk, struct msghdr *msg, size_t len,
  2095. int flags, struct scm_timestamping_internal *tss,
  2096. int *cmsg_flags)
  2097. {
  2098. struct tcp_sock *tp = tcp_sk(sk);
  2099. int copied = 0;
  2100. u32 peek_seq;
  2101. u32 *seq;
  2102. unsigned long used;
  2103. int err;
  2104. int target; /* Read at least this many bytes */
  2105. long timeo;
  2106. struct sk_buff *skb, *last;
  2107. u32 urg_hole = 0;
  2108. err = -ENOTCONN;
  2109. if (sk->sk_state == TCP_LISTEN)
  2110. goto out;
  2111. if (tp->recvmsg_inq) {
  2112. *cmsg_flags = TCP_CMSG_INQ;
  2113. msg->msg_get_inq = 1;
  2114. }
  2115. timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
  2116. /* Urgent data needs to be handled specially. */
  2117. if (flags & MSG_OOB)
  2118. goto recv_urg;
  2119. if (unlikely(tp->repair)) {
  2120. err = -EPERM;
  2121. if (!(flags & MSG_PEEK))
  2122. goto out;
  2123. if (tp->repair_queue == TCP_SEND_QUEUE)
  2124. goto recv_sndq;
  2125. err = -EINVAL;
  2126. if (tp->repair_queue == TCP_NO_QUEUE)
  2127. goto out;
  2128. /* 'common' recv queue MSG_PEEK-ing */
  2129. }
  2130. seq = &tp->copied_seq;
  2131. if (flags & MSG_PEEK) {
  2132. peek_seq = tp->copied_seq;
  2133. seq = &peek_seq;
  2134. }
  2135. target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
  2136. do {
  2137. u32 offset;
  2138. /* Are we at urgent data? Stop if we have read anything or have SIGURG pending. */
  2139. if (unlikely(tp->urg_data) && tp->urg_seq == *seq) {
  2140. if (copied)
  2141. break;
  2142. if (signal_pending(current)) {
  2143. copied = timeo ? sock_intr_errno(timeo) : -EAGAIN;
  2144. break;
  2145. }
  2146. }
  2147. /* Next get a buffer. */
  2148. last = skb_peek_tail(&sk->sk_receive_queue);
  2149. skb_queue_walk(&sk->sk_receive_queue, skb) {
  2150. last = skb;
  2151. /* Now that we have two receive queues this
  2152. * shouldn't happen.
  2153. */
  2154. if (WARN(before(*seq, TCP_SKB_CB(skb)->seq),
  2155. "TCP recvmsg seq # bug: copied %X, seq %X, rcvnxt %X, fl %X\n",
  2156. *seq, TCP_SKB_CB(skb)->seq, tp->rcv_nxt,
  2157. flags))
  2158. break;
  2159. offset = *seq - TCP_SKB_CB(skb)->seq;
  2160. if (unlikely(TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN)) {
  2161. pr_err_once("%s: found a SYN, please report !\n", __func__);
  2162. offset--;
  2163. }
  2164. if (offset < skb->len)
  2165. goto found_ok_skb;
  2166. if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)
  2167. goto found_fin_ok;
  2168. WARN(!(flags & MSG_PEEK),
  2169. "TCP recvmsg seq # bug 2: copied %X, seq %X, rcvnxt %X, fl %X\n",
  2170. *seq, TCP_SKB_CB(skb)->seq, tp->rcv_nxt, flags);
  2171. }
  2172. /* Well, if we have backlog, try to process it now yet. */
  2173. if (copied >= target && !READ_ONCE(sk->sk_backlog.tail))
  2174. break;
  2175. if (copied) {
  2176. if (!timeo ||
  2177. sk->sk_err ||
  2178. sk->sk_state == TCP_CLOSE ||
  2179. (sk->sk_shutdown & RCV_SHUTDOWN) ||
  2180. signal_pending(current))
  2181. break;
  2182. } else {
  2183. if (sock_flag(sk, SOCK_DONE))
  2184. break;
  2185. if (sk->sk_err) {
  2186. copied = sock_error(sk);
  2187. break;
  2188. }
  2189. if (sk->sk_shutdown & RCV_SHUTDOWN)
  2190. break;
  2191. if (sk->sk_state == TCP_CLOSE) {
  2192. /* This occurs when user tries to read
  2193. * from never connected socket.
  2194. */
  2195. copied = -ENOTCONN;
  2196. break;
  2197. }
  2198. if (!timeo) {
  2199. copied = -EAGAIN;
  2200. break;
  2201. }
  2202. if (signal_pending(current)) {
  2203. copied = sock_intr_errno(timeo);
  2204. break;
  2205. }
  2206. }
  2207. if (copied >= target) {
  2208. /* Do not sleep, just process backlog. */
  2209. __sk_flush_backlog(sk);
  2210. } else {
  2211. tcp_cleanup_rbuf(sk, copied);
  2212. sk_wait_data(sk, &timeo, last);
  2213. }
  2214. if ((flags & MSG_PEEK) &&
  2215. (peek_seq - copied - urg_hole != tp->copied_seq)) {
  2216. net_dbg_ratelimited("TCP(%s:%d): Application bug, race in MSG_PEEK\n",
  2217. current->comm,
  2218. task_pid_nr(current));
  2219. peek_seq = tp->copied_seq;
  2220. }
  2221. continue;
  2222. found_ok_skb:
  2223. /* Ok so how much can we use? */
  2224. used = skb->len - offset;
  2225. if (len < used)
  2226. used = len;
  2227. /* Do we have urgent data here? */
  2228. if (unlikely(tp->urg_data)) {
  2229. u32 urg_offset = tp->urg_seq - *seq;
  2230. if (urg_offset < used) {
  2231. if (!urg_offset) {
  2232. if (!sock_flag(sk, SOCK_URGINLINE)) {
  2233. WRITE_ONCE(*seq, *seq + 1);
  2234. urg_hole++;
  2235. offset++;
  2236. used--;
  2237. if (!used)
  2238. goto skip_copy;
  2239. }
  2240. } else
  2241. used = urg_offset;
  2242. }
  2243. }
  2244. if (!(flags & MSG_TRUNC)) {
  2245. err = skb_copy_datagram_msg(skb, offset, msg, used);
  2246. if (err) {
  2247. /* Exception. Bailout! */
  2248. if (!copied)
  2249. copied = -EFAULT;
  2250. break;
  2251. }
  2252. }
  2253. WRITE_ONCE(*seq, *seq + used);
  2254. copied += used;
  2255. len -= used;
  2256. tcp_rcv_space_adjust(sk);
  2257. skip_copy:
  2258. if (unlikely(tp->urg_data) && after(tp->copied_seq, tp->urg_seq)) {
  2259. WRITE_ONCE(tp->urg_data, 0);
  2260. tcp_fast_path_check(sk);
  2261. }
  2262. if (TCP_SKB_CB(skb)->has_rxtstamp) {
  2263. tcp_update_recv_tstamps(skb, tss);
  2264. *cmsg_flags |= TCP_CMSG_TS;
  2265. }
  2266. if (used + offset < skb->len)
  2267. continue;
  2268. if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)
  2269. goto found_fin_ok;
  2270. if (!(flags & MSG_PEEK))
  2271. tcp_eat_recv_skb(sk, skb);
  2272. continue;
  2273. found_fin_ok:
  2274. /* Process the FIN. */
  2275. WRITE_ONCE(*seq, *seq + 1);
  2276. if (!(flags & MSG_PEEK))
  2277. tcp_eat_recv_skb(sk, skb);
  2278. break;
  2279. } while (len > 0);
  2280. /* According to UNIX98, msg_name/msg_namelen are ignored
  2281. * on connected socket. I was just happy when found this 8) --ANK
  2282. */
  2283. /* Clean up data we have read: This will do ACK frames. */
  2284. tcp_cleanup_rbuf(sk, copied);
  2285. return copied;
  2286. out:
  2287. return err;
  2288. recv_urg:
  2289. err = tcp_recv_urg(sk, msg, len, flags);
  2290. goto out;
  2291. recv_sndq:
  2292. err = tcp_peek_sndq(sk, msg, len);
  2293. goto out;
  2294. }
  2295. int tcp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int flags,
  2296. int *addr_len)
  2297. {
  2298. int cmsg_flags = 0, ret;
  2299. struct scm_timestamping_internal tss;
  2300. if (unlikely(flags & MSG_ERRQUEUE))
  2301. return inet_recv_error(sk, msg, len, addr_len);
  2302. if (sk_can_busy_loop(sk) &&
  2303. skb_queue_empty_lockless(&sk->sk_receive_queue) &&
  2304. sk->sk_state == TCP_ESTABLISHED)
  2305. sk_busy_loop(sk, flags & MSG_DONTWAIT);
  2306. lock_sock(sk);
  2307. ret = tcp_recvmsg_locked(sk, msg, len, flags, &tss, &cmsg_flags);
  2308. release_sock(sk);
  2309. if ((cmsg_flags || msg->msg_get_inq) && ret >= 0) {
  2310. if (cmsg_flags & TCP_CMSG_TS)
  2311. tcp_recv_timestamp(msg, sk, &tss);
  2312. if (msg->msg_get_inq) {
  2313. msg->msg_inq = tcp_inq_hint(sk);
  2314. if (cmsg_flags & TCP_CMSG_INQ)
  2315. put_cmsg(msg, SOL_TCP, TCP_CM_INQ,
  2316. sizeof(msg->msg_inq), &msg->msg_inq);
  2317. }
  2318. }
  2319. return ret;
  2320. }
  2321. EXPORT_SYMBOL(tcp_recvmsg);
  2322. void tcp_set_state(struct sock *sk, int state)
  2323. {
  2324. int oldstate = sk->sk_state;
  2325. /* We defined a new enum for TCP states that are exported in BPF
  2326. * so as not force the internal TCP states to be frozen. The
  2327. * following checks will detect if an internal state value ever
  2328. * differs from the BPF value. If this ever happens, then we will
  2329. * need to remap the internal value to the BPF value before calling
  2330. * tcp_call_bpf_2arg.
  2331. */
  2332. BUILD_BUG_ON((int)BPF_TCP_ESTABLISHED != (int)TCP_ESTABLISHED);
  2333. BUILD_BUG_ON((int)BPF_TCP_SYN_SENT != (int)TCP_SYN_SENT);
  2334. BUILD_BUG_ON((int)BPF_TCP_SYN_RECV != (int)TCP_SYN_RECV);
  2335. BUILD_BUG_ON((int)BPF_TCP_FIN_WAIT1 != (int)TCP_FIN_WAIT1);
  2336. BUILD_BUG_ON((int)BPF_TCP_FIN_WAIT2 != (int)TCP_FIN_WAIT2);
  2337. BUILD_BUG_ON((int)BPF_TCP_TIME_WAIT != (int)TCP_TIME_WAIT);
  2338. BUILD_BUG_ON((int)BPF_TCP_CLOSE != (int)TCP_CLOSE);
  2339. BUILD_BUG_ON((int)BPF_TCP_CLOSE_WAIT != (int)TCP_CLOSE_WAIT);
  2340. BUILD_BUG_ON((int)BPF_TCP_LAST_ACK != (int)TCP_LAST_ACK);
  2341. BUILD_BUG_ON((int)BPF_TCP_LISTEN != (int)TCP_LISTEN);
  2342. BUILD_BUG_ON((int)BPF_TCP_CLOSING != (int)TCP_CLOSING);
  2343. BUILD_BUG_ON((int)BPF_TCP_NEW_SYN_RECV != (int)TCP_NEW_SYN_RECV);
  2344. BUILD_BUG_ON((int)BPF_TCP_MAX_STATES != (int)TCP_MAX_STATES);
  2345. /* bpf uapi header bpf.h defines an anonymous enum with values
  2346. * BPF_TCP_* used by bpf programs. Currently gcc built vmlinux
  2347. * is able to emit this enum in DWARF due to the above BUILD_BUG_ON.
  2348. * But clang built vmlinux does not have this enum in DWARF
  2349. * since clang removes the above code before generating IR/debuginfo.
  2350. * Let us explicitly emit the type debuginfo to ensure the
  2351. * above-mentioned anonymous enum in the vmlinux DWARF and hence BTF
  2352. * regardless of which compiler is used.
  2353. */
  2354. BTF_TYPE_EMIT_ENUM(BPF_TCP_ESTABLISHED);
  2355. if (BPF_SOCK_OPS_TEST_FLAG(tcp_sk(sk), BPF_SOCK_OPS_STATE_CB_FLAG))
  2356. tcp_call_bpf_2arg(sk, BPF_SOCK_OPS_STATE_CB, oldstate, state);
  2357. switch (state) {
  2358. case TCP_ESTABLISHED:
  2359. if (oldstate != TCP_ESTABLISHED)
  2360. TCP_INC_STATS(sock_net(sk), TCP_MIB_CURRESTAB);
  2361. break;
  2362. case TCP_CLOSE:
  2363. if (oldstate == TCP_CLOSE_WAIT || oldstate == TCP_ESTABLISHED)
  2364. TCP_INC_STATS(sock_net(sk), TCP_MIB_ESTABRESETS);
  2365. sk->sk_prot->unhash(sk);
  2366. if (inet_csk(sk)->icsk_bind_hash &&
  2367. !(sk->sk_userlocks & SOCK_BINDPORT_LOCK))
  2368. inet_put_port(sk);
  2369. fallthrough;
  2370. default:
  2371. if (oldstate == TCP_ESTABLISHED)
  2372. TCP_DEC_STATS(sock_net(sk), TCP_MIB_CURRESTAB);
  2373. }
  2374. /* Change state AFTER socket is unhashed to avoid closed
  2375. * socket sitting in hash tables.
  2376. */
  2377. inet_sk_state_store(sk, state);
  2378. }
  2379. EXPORT_SYMBOL_GPL(tcp_set_state);
  2380. /*
  2381. * State processing on a close. This implements the state shift for
  2382. * sending our FIN frame. Note that we only send a FIN for some
  2383. * states. A shutdown() may have already sent the FIN, or we may be
  2384. * closed.
  2385. */
  2386. static const unsigned char new_state[16] = {
  2387. /* current state: new state: action: */
  2388. [0 /* (Invalid) */] = TCP_CLOSE,
  2389. [TCP_ESTABLISHED] = TCP_FIN_WAIT1 | TCP_ACTION_FIN,
  2390. [TCP_SYN_SENT] = TCP_CLOSE,
  2391. [TCP_SYN_RECV] = TCP_FIN_WAIT1 | TCP_ACTION_FIN,
  2392. [TCP_FIN_WAIT1] = TCP_FIN_WAIT1,
  2393. [TCP_FIN_WAIT2] = TCP_FIN_WAIT2,
  2394. [TCP_TIME_WAIT] = TCP_CLOSE,
  2395. [TCP_CLOSE] = TCP_CLOSE,
  2396. [TCP_CLOSE_WAIT] = TCP_LAST_ACK | TCP_ACTION_FIN,
  2397. [TCP_LAST_ACK] = TCP_LAST_ACK,
  2398. [TCP_LISTEN] = TCP_CLOSE,
  2399. [TCP_CLOSING] = TCP_CLOSING,
  2400. [TCP_NEW_SYN_RECV] = TCP_CLOSE, /* should not happen ! */
  2401. };
  2402. static int tcp_close_state(struct sock *sk)
  2403. {
  2404. int next = (int)new_state[sk->sk_state];
  2405. int ns = next & TCP_STATE_MASK;
  2406. tcp_set_state(sk, ns);
  2407. return next & TCP_ACTION_FIN;
  2408. }
  2409. /*
  2410. * Shutdown the sending side of a connection. Much like close except
  2411. * that we don't receive shut down or sock_set_flag(sk, SOCK_DEAD).
  2412. */
  2413. void tcp_shutdown(struct sock *sk, int how)
  2414. {
  2415. /* We need to grab some memory, and put together a FIN,
  2416. * and then put it into the queue to be sent.
  2417. * Tim MacKenzie([email protected]) 4 Dec '92.
  2418. */
  2419. if (!(how & SEND_SHUTDOWN))
  2420. return;
  2421. /* If we've already sent a FIN, or it's a closed state, skip this. */
  2422. if ((1 << sk->sk_state) &
  2423. (TCPF_ESTABLISHED | TCPF_SYN_SENT |
  2424. TCPF_SYN_RECV | TCPF_CLOSE_WAIT)) {
  2425. /* Clear out any half completed packets. FIN if needed. */
  2426. if (tcp_close_state(sk))
  2427. tcp_send_fin(sk);
  2428. }
  2429. }
  2430. EXPORT_SYMBOL(tcp_shutdown);
  2431. int tcp_orphan_count_sum(void)
  2432. {
  2433. int i, total = 0;
  2434. for_each_possible_cpu(i)
  2435. total += per_cpu(tcp_orphan_count, i);
  2436. return max(total, 0);
  2437. }
  2438. static int tcp_orphan_cache;
  2439. static struct timer_list tcp_orphan_timer;
  2440. #define TCP_ORPHAN_TIMER_PERIOD msecs_to_jiffies(100)
  2441. static void tcp_orphan_update(struct timer_list *unused)
  2442. {
  2443. WRITE_ONCE(tcp_orphan_cache, tcp_orphan_count_sum());
  2444. mod_timer(&tcp_orphan_timer, jiffies + TCP_ORPHAN_TIMER_PERIOD);
  2445. }
  2446. static bool tcp_too_many_orphans(int shift)
  2447. {
  2448. return READ_ONCE(tcp_orphan_cache) << shift >
  2449. READ_ONCE(sysctl_tcp_max_orphans);
  2450. }
  2451. bool tcp_check_oom(struct sock *sk, int shift)
  2452. {
  2453. bool too_many_orphans, out_of_socket_memory;
  2454. too_many_orphans = tcp_too_many_orphans(shift);
  2455. out_of_socket_memory = tcp_out_of_memory(sk);
  2456. if (too_many_orphans)
  2457. net_info_ratelimited("too many orphaned sockets\n");
  2458. if (out_of_socket_memory)
  2459. net_info_ratelimited("out of memory -- consider tuning tcp_mem\n");
  2460. return too_many_orphans || out_of_socket_memory;
  2461. }
  2462. void __tcp_close(struct sock *sk, long timeout)
  2463. {
  2464. struct sk_buff *skb;
  2465. int data_was_unread = 0;
  2466. int state;
  2467. WRITE_ONCE(sk->sk_shutdown, SHUTDOWN_MASK);
  2468. if (sk->sk_state == TCP_LISTEN) {
  2469. tcp_set_state(sk, TCP_CLOSE);
  2470. /* Special case. */
  2471. inet_csk_listen_stop(sk);
  2472. goto adjudge_to_death;
  2473. }
  2474. /* We need to flush the recv. buffs. We do this only on the
  2475. * descriptor close, not protocol-sourced closes, because the
  2476. * reader process may not have drained the data yet!
  2477. */
  2478. while ((skb = __skb_dequeue(&sk->sk_receive_queue)) != NULL) {
  2479. u32 len = TCP_SKB_CB(skb)->end_seq - TCP_SKB_CB(skb)->seq;
  2480. if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)
  2481. len--;
  2482. data_was_unread += len;
  2483. __kfree_skb(skb);
  2484. }
  2485. /* If socket has been already reset (e.g. in tcp_reset()) - kill it. */
  2486. if (sk->sk_state == TCP_CLOSE)
  2487. goto adjudge_to_death;
  2488. /* As outlined in RFC 2525, section 2.17, we send a RST here because
  2489. * data was lost. To witness the awful effects of the old behavior of
  2490. * always doing a FIN, run an older 2.1.x kernel or 2.0.x, start a bulk
  2491. * GET in an FTP client, suspend the process, wait for the client to
  2492. * advertise a zero window, then kill -9 the FTP client, wheee...
  2493. * Note: timeout is always zero in such a case.
  2494. */
  2495. if (unlikely(tcp_sk(sk)->repair)) {
  2496. sk->sk_prot->disconnect(sk, 0);
  2497. } else if (data_was_unread) {
  2498. /* Unread data was tossed, zap the connection. */
  2499. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONCLOSE);
  2500. tcp_set_state(sk, TCP_CLOSE);
  2501. tcp_send_active_reset(sk, sk->sk_allocation);
  2502. } else if (sock_flag(sk, SOCK_LINGER) && !sk->sk_lingertime) {
  2503. /* Check zero linger _after_ checking for unread data. */
  2504. sk->sk_prot->disconnect(sk, 0);
  2505. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONDATA);
  2506. } else if (tcp_close_state(sk)) {
  2507. /* We FIN if the application ate all the data before
  2508. * zapping the connection.
  2509. */
  2510. /* RED-PEN. Formally speaking, we have broken TCP state
  2511. * machine. State transitions:
  2512. *
  2513. * TCP_ESTABLISHED -> TCP_FIN_WAIT1
  2514. * TCP_SYN_RECV -> TCP_FIN_WAIT1 (forget it, it's impossible)
  2515. * TCP_CLOSE_WAIT -> TCP_LAST_ACK
  2516. *
  2517. * are legal only when FIN has been sent (i.e. in window),
  2518. * rather than queued out of window. Purists blame.
  2519. *
  2520. * F.e. "RFC state" is ESTABLISHED,
  2521. * if Linux state is FIN-WAIT-1, but FIN is still not sent.
  2522. *
  2523. * The visible declinations are that sometimes
  2524. * we enter time-wait state, when it is not required really
  2525. * (harmless), do not send active resets, when they are
  2526. * required by specs (TCP_ESTABLISHED, TCP_CLOSE_WAIT, when
  2527. * they look as CLOSING or LAST_ACK for Linux)
  2528. * Probably, I missed some more holelets.
  2529. * --ANK
  2530. * XXX (TFO) - To start off we don't support SYN+ACK+FIN
  2531. * in a single packet! (May consider it later but will
  2532. * probably need API support or TCP_CORK SYN-ACK until
  2533. * data is written and socket is closed.)
  2534. */
  2535. tcp_send_fin(sk);
  2536. }
  2537. sk_stream_wait_close(sk, timeout);
  2538. adjudge_to_death:
  2539. state = sk->sk_state;
  2540. sock_hold(sk);
  2541. sock_orphan(sk);
  2542. local_bh_disable();
  2543. bh_lock_sock(sk);
  2544. /* remove backlog if any, without releasing ownership. */
  2545. __release_sock(sk);
  2546. this_cpu_inc(tcp_orphan_count);
  2547. /* Have we already been destroyed by a softirq or backlog? */
  2548. if (state != TCP_CLOSE && sk->sk_state == TCP_CLOSE)
  2549. goto out;
  2550. /* This is a (useful) BSD violating of the RFC. There is a
  2551. * problem with TCP as specified in that the other end could
  2552. * keep a socket open forever with no application left this end.
  2553. * We use a 1 minute timeout (about the same as BSD) then kill
  2554. * our end. If they send after that then tough - BUT: long enough
  2555. * that we won't make the old 4*rto = almost no time - whoops
  2556. * reset mistake.
  2557. *
  2558. * Nope, it was not mistake. It is really desired behaviour
  2559. * f.e. on http servers, when such sockets are useless, but
  2560. * consume significant resources. Let's do it with special
  2561. * linger2 option. --ANK
  2562. */
  2563. if (sk->sk_state == TCP_FIN_WAIT2) {
  2564. struct tcp_sock *tp = tcp_sk(sk);
  2565. if (tp->linger2 < 0) {
  2566. tcp_set_state(sk, TCP_CLOSE);
  2567. tcp_send_active_reset(sk, GFP_ATOMIC);
  2568. __NET_INC_STATS(sock_net(sk),
  2569. LINUX_MIB_TCPABORTONLINGER);
  2570. } else {
  2571. const int tmo = tcp_fin_time(sk);
  2572. if (tmo > TCP_TIMEWAIT_LEN) {
  2573. inet_csk_reset_keepalive_timer(sk,
  2574. tmo - TCP_TIMEWAIT_LEN);
  2575. } else {
  2576. tcp_time_wait(sk, TCP_FIN_WAIT2, tmo);
  2577. goto out;
  2578. }
  2579. }
  2580. }
  2581. if (sk->sk_state != TCP_CLOSE) {
  2582. if (tcp_check_oom(sk, 0)) {
  2583. tcp_set_state(sk, TCP_CLOSE);
  2584. tcp_send_active_reset(sk, GFP_ATOMIC);
  2585. __NET_INC_STATS(sock_net(sk),
  2586. LINUX_MIB_TCPABORTONMEMORY);
  2587. } else if (!check_net(sock_net(sk))) {
  2588. /* Not possible to send reset; just close */
  2589. tcp_set_state(sk, TCP_CLOSE);
  2590. }
  2591. }
  2592. if (sk->sk_state == TCP_CLOSE) {
  2593. struct request_sock *req;
  2594. req = rcu_dereference_protected(tcp_sk(sk)->fastopen_rsk,
  2595. lockdep_sock_is_held(sk));
  2596. /* We could get here with a non-NULL req if the socket is
  2597. * aborted (e.g., closed with unread data) before 3WHS
  2598. * finishes.
  2599. */
  2600. if (req)
  2601. reqsk_fastopen_remove(sk, req, false);
  2602. inet_csk_destroy_sock(sk);
  2603. }
  2604. /* Otherwise, socket is reprieved until protocol close. */
  2605. out:
  2606. bh_unlock_sock(sk);
  2607. local_bh_enable();
  2608. }
  2609. void tcp_close(struct sock *sk, long timeout)
  2610. {
  2611. lock_sock(sk);
  2612. __tcp_close(sk, timeout);
  2613. release_sock(sk);
  2614. sock_put(sk);
  2615. }
  2616. EXPORT_SYMBOL(tcp_close);
  2617. /* These states need RST on ABORT according to RFC793 */
  2618. static inline bool tcp_need_reset(int state)
  2619. {
  2620. return (1 << state) &
  2621. (TCPF_ESTABLISHED | TCPF_CLOSE_WAIT | TCPF_FIN_WAIT1 |
  2622. TCPF_FIN_WAIT2 | TCPF_SYN_RECV);
  2623. }
  2624. static void tcp_rtx_queue_purge(struct sock *sk)
  2625. {
  2626. struct rb_node *p = rb_first(&sk->tcp_rtx_queue);
  2627. tcp_sk(sk)->highest_sack = NULL;
  2628. while (p) {
  2629. struct sk_buff *skb = rb_to_skb(p);
  2630. p = rb_next(p);
  2631. /* Since we are deleting whole queue, no need to
  2632. * list_del(&skb->tcp_tsorted_anchor)
  2633. */
  2634. tcp_rtx_queue_unlink(skb, sk);
  2635. tcp_wmem_free_skb(sk, skb);
  2636. }
  2637. }
  2638. void tcp_write_queue_purge(struct sock *sk)
  2639. {
  2640. struct sk_buff *skb;
  2641. tcp_chrono_stop(sk, TCP_CHRONO_BUSY);
  2642. while ((skb = __skb_dequeue(&sk->sk_write_queue)) != NULL) {
  2643. tcp_skb_tsorted_anchor_cleanup(skb);
  2644. tcp_wmem_free_skb(sk, skb);
  2645. }
  2646. tcp_rtx_queue_purge(sk);
  2647. INIT_LIST_HEAD(&tcp_sk(sk)->tsorted_sent_queue);
  2648. tcp_clear_all_retrans_hints(tcp_sk(sk));
  2649. tcp_sk(sk)->packets_out = 0;
  2650. inet_csk(sk)->icsk_backoff = 0;
  2651. }
  2652. int tcp_disconnect(struct sock *sk, int flags)
  2653. {
  2654. struct inet_sock *inet = inet_sk(sk);
  2655. struct inet_connection_sock *icsk = inet_csk(sk);
  2656. struct tcp_sock *tp = tcp_sk(sk);
  2657. int old_state = sk->sk_state;
  2658. u32 seq;
  2659. /* Deny disconnect if other threads are blocked in sk_wait_event()
  2660. * or inet_wait_for_connect().
  2661. */
  2662. if (sk->sk_wait_pending)
  2663. return -EBUSY;
  2664. if (old_state != TCP_CLOSE)
  2665. tcp_set_state(sk, TCP_CLOSE);
  2666. /* ABORT function of RFC793 */
  2667. if (old_state == TCP_LISTEN) {
  2668. inet_csk_listen_stop(sk);
  2669. } else if (unlikely(tp->repair)) {
  2670. sk->sk_err = ECONNABORTED;
  2671. } else if (tcp_need_reset(old_state) ||
  2672. (tp->snd_nxt != tp->write_seq &&
  2673. (1 << old_state) & (TCPF_CLOSING | TCPF_LAST_ACK))) {
  2674. /* The last check adjusts for discrepancy of Linux wrt. RFC
  2675. * states
  2676. */
  2677. tcp_send_active_reset(sk, gfp_any());
  2678. sk->sk_err = ECONNRESET;
  2679. } else if (old_state == TCP_SYN_SENT)
  2680. sk->sk_err = ECONNRESET;
  2681. tcp_clear_xmit_timers(sk);
  2682. __skb_queue_purge(&sk->sk_receive_queue);
  2683. WRITE_ONCE(tp->copied_seq, tp->rcv_nxt);
  2684. WRITE_ONCE(tp->urg_data, 0);
  2685. tcp_write_queue_purge(sk);
  2686. tcp_fastopen_active_disable_ofo_check(sk);
  2687. skb_rbtree_purge(&tp->out_of_order_queue);
  2688. inet->inet_dport = 0;
  2689. inet_bhash2_reset_saddr(sk);
  2690. WRITE_ONCE(sk->sk_shutdown, 0);
  2691. sock_reset_flag(sk, SOCK_DONE);
  2692. tp->srtt_us = 0;
  2693. tp->mdev_us = jiffies_to_usecs(TCP_TIMEOUT_INIT);
  2694. tp->rcv_rtt_last_tsecr = 0;
  2695. seq = tp->write_seq + tp->max_window + 2;
  2696. if (!seq)
  2697. seq = 1;
  2698. WRITE_ONCE(tp->write_seq, seq);
  2699. icsk->icsk_backoff = 0;
  2700. icsk->icsk_probes_out = 0;
  2701. icsk->icsk_probes_tstamp = 0;
  2702. icsk->icsk_rto = TCP_TIMEOUT_INIT;
  2703. icsk->icsk_rto_min = TCP_RTO_MIN;
  2704. icsk->icsk_delack_max = TCP_DELACK_MAX;
  2705. tp->snd_ssthresh = TCP_INFINITE_SSTHRESH;
  2706. tcp_snd_cwnd_set(tp, TCP_INIT_CWND);
  2707. tp->snd_cwnd_cnt = 0;
  2708. tp->is_cwnd_limited = 0;
  2709. tp->max_packets_out = 0;
  2710. tp->window_clamp = 0;
  2711. tp->delivered = 0;
  2712. tp->delivered_ce = 0;
  2713. if (icsk->icsk_ca_ops->release)
  2714. icsk->icsk_ca_ops->release(sk);
  2715. memset(icsk->icsk_ca_priv, 0, sizeof(icsk->icsk_ca_priv));
  2716. icsk->icsk_ca_initialized = 0;
  2717. tcp_set_ca_state(sk, TCP_CA_Open);
  2718. tp->is_sack_reneg = 0;
  2719. tcp_clear_retrans(tp);
  2720. tp->total_retrans = 0;
  2721. inet_csk_delack_init(sk);
  2722. /* Initialize rcv_mss to TCP_MIN_MSS to avoid division by 0
  2723. * issue in __tcp_select_window()
  2724. */
  2725. icsk->icsk_ack.rcv_mss = TCP_MIN_MSS;
  2726. memset(&tp->rx_opt, 0, sizeof(tp->rx_opt));
  2727. __sk_dst_reset(sk);
  2728. dst_release(xchg((__force struct dst_entry **)&sk->sk_rx_dst, NULL));
  2729. tcp_saved_syn_free(tp);
  2730. tp->compressed_ack = 0;
  2731. tp->segs_in = 0;
  2732. tp->segs_out = 0;
  2733. tp->bytes_sent = 0;
  2734. tp->bytes_acked = 0;
  2735. tp->bytes_received = 0;
  2736. tp->bytes_retrans = 0;
  2737. tp->data_segs_in = 0;
  2738. tp->data_segs_out = 0;
  2739. tp->duplicate_sack[0].start_seq = 0;
  2740. tp->duplicate_sack[0].end_seq = 0;
  2741. tp->dsack_dups = 0;
  2742. tp->reord_seen = 0;
  2743. tp->retrans_out = 0;
  2744. tp->sacked_out = 0;
  2745. tp->tlp_high_seq = 0;
  2746. tp->last_oow_ack_time = 0;
  2747. /* There's a bubble in the pipe until at least the first ACK. */
  2748. tp->app_limited = ~0U;
  2749. tp->rate_app_limited = 1;
  2750. tp->rack.mstamp = 0;
  2751. tp->rack.advanced = 0;
  2752. tp->rack.reo_wnd_steps = 1;
  2753. tp->rack.last_delivered = 0;
  2754. tp->rack.reo_wnd_persist = 0;
  2755. tp->rack.dsack_seen = 0;
  2756. tp->syn_data_acked = 0;
  2757. tp->rx_opt.saw_tstamp = 0;
  2758. tp->rx_opt.dsack = 0;
  2759. tp->rx_opt.num_sacks = 0;
  2760. tp->rcv_ooopack = 0;
  2761. /* Clean up fastopen related fields */
  2762. tcp_free_fastopen_req(tp);
  2763. inet->defer_connect = 0;
  2764. tp->fastopen_client_fail = 0;
  2765. WARN_ON(inet->inet_num && !icsk->icsk_bind_hash);
  2766. if (sk->sk_frag.page) {
  2767. put_page(sk->sk_frag.page);
  2768. sk->sk_frag.page = NULL;
  2769. sk->sk_frag.offset = 0;
  2770. }
  2771. sk_error_report(sk);
  2772. return 0;
  2773. }
  2774. EXPORT_SYMBOL(tcp_disconnect);
  2775. static inline bool tcp_can_repair_sock(const struct sock *sk)
  2776. {
  2777. return sockopt_ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN) &&
  2778. (sk->sk_state != TCP_LISTEN);
  2779. }
  2780. static int tcp_repair_set_window(struct tcp_sock *tp, sockptr_t optbuf, int len)
  2781. {
  2782. struct tcp_repair_window opt;
  2783. if (!tp->repair)
  2784. return -EPERM;
  2785. if (len != sizeof(opt))
  2786. return -EINVAL;
  2787. if (copy_from_sockptr(&opt, optbuf, sizeof(opt)))
  2788. return -EFAULT;
  2789. if (opt.max_window < opt.snd_wnd)
  2790. return -EINVAL;
  2791. if (after(opt.snd_wl1, tp->rcv_nxt + opt.rcv_wnd))
  2792. return -EINVAL;
  2793. if (after(opt.rcv_wup, tp->rcv_nxt))
  2794. return -EINVAL;
  2795. tp->snd_wl1 = opt.snd_wl1;
  2796. tp->snd_wnd = opt.snd_wnd;
  2797. tp->max_window = opt.max_window;
  2798. tp->rcv_wnd = opt.rcv_wnd;
  2799. tp->rcv_wup = opt.rcv_wup;
  2800. return 0;
  2801. }
  2802. static int tcp_repair_options_est(struct sock *sk, sockptr_t optbuf,
  2803. unsigned int len)
  2804. {
  2805. struct tcp_sock *tp = tcp_sk(sk);
  2806. struct tcp_repair_opt opt;
  2807. size_t offset = 0;
  2808. while (len >= sizeof(opt)) {
  2809. if (copy_from_sockptr_offset(&opt, optbuf, offset, sizeof(opt)))
  2810. return -EFAULT;
  2811. offset += sizeof(opt);
  2812. len -= sizeof(opt);
  2813. switch (opt.opt_code) {
  2814. case TCPOPT_MSS:
  2815. tp->rx_opt.mss_clamp = opt.opt_val;
  2816. tcp_mtup_init(sk);
  2817. break;
  2818. case TCPOPT_WINDOW:
  2819. {
  2820. u16 snd_wscale = opt.opt_val & 0xFFFF;
  2821. u16 rcv_wscale = opt.opt_val >> 16;
  2822. if (snd_wscale > TCP_MAX_WSCALE || rcv_wscale > TCP_MAX_WSCALE)
  2823. return -EFBIG;
  2824. tp->rx_opt.snd_wscale = snd_wscale;
  2825. tp->rx_opt.rcv_wscale = rcv_wscale;
  2826. tp->rx_opt.wscale_ok = 1;
  2827. }
  2828. break;
  2829. case TCPOPT_SACK_PERM:
  2830. if (opt.opt_val != 0)
  2831. return -EINVAL;
  2832. tp->rx_opt.sack_ok |= TCP_SACK_SEEN;
  2833. break;
  2834. case TCPOPT_TIMESTAMP:
  2835. if (opt.opt_val != 0)
  2836. return -EINVAL;
  2837. tp->rx_opt.tstamp_ok = 1;
  2838. break;
  2839. }
  2840. }
  2841. return 0;
  2842. }
  2843. DEFINE_STATIC_KEY_FALSE(tcp_tx_delay_enabled);
  2844. EXPORT_SYMBOL(tcp_tx_delay_enabled);
  2845. static void tcp_enable_tx_delay(void)
  2846. {
  2847. if (!static_branch_unlikely(&tcp_tx_delay_enabled)) {
  2848. static int __tcp_tx_delay_enabled = 0;
  2849. if (cmpxchg(&__tcp_tx_delay_enabled, 0, 1) == 0) {
  2850. static_branch_enable(&tcp_tx_delay_enabled);
  2851. pr_info("TCP_TX_DELAY enabled\n");
  2852. }
  2853. }
  2854. }
  2855. /* When set indicates to always queue non-full frames. Later the user clears
  2856. * this option and we transmit any pending partial frames in the queue. This is
  2857. * meant to be used alongside sendfile() to get properly filled frames when the
  2858. * user (for example) must write out headers with a write() call first and then
  2859. * use sendfile to send out the data parts.
  2860. *
  2861. * TCP_CORK can be set together with TCP_NODELAY and it is stronger than
  2862. * TCP_NODELAY.
  2863. */
  2864. void __tcp_sock_set_cork(struct sock *sk, bool on)
  2865. {
  2866. struct tcp_sock *tp = tcp_sk(sk);
  2867. if (on) {
  2868. tp->nonagle |= TCP_NAGLE_CORK;
  2869. } else {
  2870. tp->nonagle &= ~TCP_NAGLE_CORK;
  2871. if (tp->nonagle & TCP_NAGLE_OFF)
  2872. tp->nonagle |= TCP_NAGLE_PUSH;
  2873. tcp_push_pending_frames(sk);
  2874. }
  2875. }
  2876. void tcp_sock_set_cork(struct sock *sk, bool on)
  2877. {
  2878. lock_sock(sk);
  2879. __tcp_sock_set_cork(sk, on);
  2880. release_sock(sk);
  2881. }
  2882. EXPORT_SYMBOL(tcp_sock_set_cork);
  2883. /* TCP_NODELAY is weaker than TCP_CORK, so that this option on corked socket is
  2884. * remembered, but it is not activated until cork is cleared.
  2885. *
  2886. * However, when TCP_NODELAY is set we make an explicit push, which overrides
  2887. * even TCP_CORK for currently queued segments.
  2888. */
  2889. void __tcp_sock_set_nodelay(struct sock *sk, bool on)
  2890. {
  2891. if (on) {
  2892. tcp_sk(sk)->nonagle |= TCP_NAGLE_OFF|TCP_NAGLE_PUSH;
  2893. tcp_push_pending_frames(sk);
  2894. } else {
  2895. tcp_sk(sk)->nonagle &= ~TCP_NAGLE_OFF;
  2896. }
  2897. }
  2898. void tcp_sock_set_nodelay(struct sock *sk)
  2899. {
  2900. lock_sock(sk);
  2901. __tcp_sock_set_nodelay(sk, true);
  2902. release_sock(sk);
  2903. }
  2904. EXPORT_SYMBOL(tcp_sock_set_nodelay);
  2905. static void __tcp_sock_set_quickack(struct sock *sk, int val)
  2906. {
  2907. if (!val) {
  2908. inet_csk_enter_pingpong_mode(sk);
  2909. return;
  2910. }
  2911. inet_csk_exit_pingpong_mode(sk);
  2912. if ((1 << sk->sk_state) & (TCPF_ESTABLISHED | TCPF_CLOSE_WAIT) &&
  2913. inet_csk_ack_scheduled(sk)) {
  2914. inet_csk(sk)->icsk_ack.pending |= ICSK_ACK_PUSHED;
  2915. tcp_cleanup_rbuf(sk, 1);
  2916. if (!(val & 1))
  2917. inet_csk_enter_pingpong_mode(sk);
  2918. }
  2919. }
  2920. void tcp_sock_set_quickack(struct sock *sk, int val)
  2921. {
  2922. lock_sock(sk);
  2923. __tcp_sock_set_quickack(sk, val);
  2924. release_sock(sk);
  2925. }
  2926. EXPORT_SYMBOL(tcp_sock_set_quickack);
  2927. int tcp_sock_set_syncnt(struct sock *sk, int val)
  2928. {
  2929. if (val < 1 || val > MAX_TCP_SYNCNT)
  2930. return -EINVAL;
  2931. lock_sock(sk);
  2932. WRITE_ONCE(inet_csk(sk)->icsk_syn_retries, val);
  2933. release_sock(sk);
  2934. return 0;
  2935. }
  2936. EXPORT_SYMBOL(tcp_sock_set_syncnt);
  2937. void tcp_sock_set_user_timeout(struct sock *sk, u32 val)
  2938. {
  2939. lock_sock(sk);
  2940. WRITE_ONCE(inet_csk(sk)->icsk_user_timeout, val);
  2941. release_sock(sk);
  2942. }
  2943. EXPORT_SYMBOL(tcp_sock_set_user_timeout);
  2944. int tcp_sock_set_keepidle_locked(struct sock *sk, int val)
  2945. {
  2946. struct tcp_sock *tp = tcp_sk(sk);
  2947. if (val < 1 || val > MAX_TCP_KEEPIDLE)
  2948. return -EINVAL;
  2949. /* Paired with WRITE_ONCE() in keepalive_time_when() */
  2950. WRITE_ONCE(tp->keepalive_time, val * HZ);
  2951. if (sock_flag(sk, SOCK_KEEPOPEN) &&
  2952. !((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN))) {
  2953. u32 elapsed = keepalive_time_elapsed(tp);
  2954. if (tp->keepalive_time > elapsed)
  2955. elapsed = tp->keepalive_time - elapsed;
  2956. else
  2957. elapsed = 0;
  2958. inet_csk_reset_keepalive_timer(sk, elapsed);
  2959. }
  2960. return 0;
  2961. }
  2962. int tcp_sock_set_keepidle(struct sock *sk, int val)
  2963. {
  2964. int err;
  2965. lock_sock(sk);
  2966. err = tcp_sock_set_keepidle_locked(sk, val);
  2967. release_sock(sk);
  2968. return err;
  2969. }
  2970. EXPORT_SYMBOL(tcp_sock_set_keepidle);
  2971. int tcp_sock_set_keepintvl(struct sock *sk, int val)
  2972. {
  2973. if (val < 1 || val > MAX_TCP_KEEPINTVL)
  2974. return -EINVAL;
  2975. lock_sock(sk);
  2976. WRITE_ONCE(tcp_sk(sk)->keepalive_intvl, val * HZ);
  2977. release_sock(sk);
  2978. return 0;
  2979. }
  2980. EXPORT_SYMBOL(tcp_sock_set_keepintvl);
  2981. int tcp_sock_set_keepcnt(struct sock *sk, int val)
  2982. {
  2983. if (val < 1 || val > MAX_TCP_KEEPCNT)
  2984. return -EINVAL;
  2985. lock_sock(sk);
  2986. /* Paired with READ_ONCE() in keepalive_probes() */
  2987. WRITE_ONCE(tcp_sk(sk)->keepalive_probes, val);
  2988. release_sock(sk);
  2989. return 0;
  2990. }
  2991. EXPORT_SYMBOL(tcp_sock_set_keepcnt);
  2992. int tcp_set_window_clamp(struct sock *sk, int val)
  2993. {
  2994. struct tcp_sock *tp = tcp_sk(sk);
  2995. if (!val) {
  2996. if (sk->sk_state != TCP_CLOSE)
  2997. return -EINVAL;
  2998. tp->window_clamp = 0;
  2999. } else {
  3000. u32 new_rcv_ssthresh, old_window_clamp = tp->window_clamp;
  3001. u32 new_window_clamp = val < SOCK_MIN_RCVBUF / 2 ?
  3002. SOCK_MIN_RCVBUF / 2 : val;
  3003. if (new_window_clamp == old_window_clamp)
  3004. return 0;
  3005. tp->window_clamp = new_window_clamp;
  3006. if (new_window_clamp < old_window_clamp) {
  3007. /* need to apply the reserved mem provisioning only
  3008. * when shrinking the window clamp
  3009. */
  3010. __tcp_adjust_rcv_ssthresh(sk, tp->window_clamp);
  3011. } else {
  3012. new_rcv_ssthresh = min(tp->rcv_wnd, tp->window_clamp);
  3013. tp->rcv_ssthresh = max(new_rcv_ssthresh,
  3014. tp->rcv_ssthresh);
  3015. }
  3016. }
  3017. return 0;
  3018. }
  3019. /*
  3020. * Socket option code for TCP.
  3021. */
  3022. int do_tcp_setsockopt(struct sock *sk, int level, int optname,
  3023. sockptr_t optval, unsigned int optlen)
  3024. {
  3025. struct tcp_sock *tp = tcp_sk(sk);
  3026. struct inet_connection_sock *icsk = inet_csk(sk);
  3027. struct net *net = sock_net(sk);
  3028. int val;
  3029. int err = 0;
  3030. /* These are data/string values, all the others are ints */
  3031. switch (optname) {
  3032. case TCP_CONGESTION: {
  3033. char name[TCP_CA_NAME_MAX];
  3034. if (optlen < 1)
  3035. return -EINVAL;
  3036. val = strncpy_from_sockptr(name, optval,
  3037. min_t(long, TCP_CA_NAME_MAX-1, optlen));
  3038. if (val < 0)
  3039. return -EFAULT;
  3040. name[val] = 0;
  3041. sockopt_lock_sock(sk);
  3042. err = tcp_set_congestion_control(sk, name, !has_current_bpf_ctx(),
  3043. sockopt_ns_capable(sock_net(sk)->user_ns,
  3044. CAP_NET_ADMIN));
  3045. sockopt_release_sock(sk);
  3046. return err;
  3047. }
  3048. case TCP_ULP: {
  3049. char name[TCP_ULP_NAME_MAX];
  3050. if (optlen < 1)
  3051. return -EINVAL;
  3052. val = strncpy_from_sockptr(name, optval,
  3053. min_t(long, TCP_ULP_NAME_MAX - 1,
  3054. optlen));
  3055. if (val < 0)
  3056. return -EFAULT;
  3057. name[val] = 0;
  3058. sockopt_lock_sock(sk);
  3059. err = tcp_set_ulp(sk, name);
  3060. sockopt_release_sock(sk);
  3061. return err;
  3062. }
  3063. case TCP_FASTOPEN_KEY: {
  3064. __u8 key[TCP_FASTOPEN_KEY_BUF_LENGTH];
  3065. __u8 *backup_key = NULL;
  3066. /* Allow a backup key as well to facilitate key rotation
  3067. * First key is the active one.
  3068. */
  3069. if (optlen != TCP_FASTOPEN_KEY_LENGTH &&
  3070. optlen != TCP_FASTOPEN_KEY_BUF_LENGTH)
  3071. return -EINVAL;
  3072. if (copy_from_sockptr(key, optval, optlen))
  3073. return -EFAULT;
  3074. if (optlen == TCP_FASTOPEN_KEY_BUF_LENGTH)
  3075. backup_key = key + TCP_FASTOPEN_KEY_LENGTH;
  3076. return tcp_fastopen_reset_cipher(net, sk, key, backup_key);
  3077. }
  3078. default:
  3079. /* fallthru */
  3080. break;
  3081. }
  3082. if (optlen < sizeof(int))
  3083. return -EINVAL;
  3084. if (copy_from_sockptr(&val, optval, sizeof(val)))
  3085. return -EFAULT;
  3086. sockopt_lock_sock(sk);
  3087. switch (optname) {
  3088. case TCP_MAXSEG:
  3089. /* Values greater than interface MTU won't take effect. However
  3090. * at the point when this call is done we typically don't yet
  3091. * know which interface is going to be used
  3092. */
  3093. if (val && (val < TCP_MIN_MSS || val > MAX_TCP_WINDOW)) {
  3094. err = -EINVAL;
  3095. break;
  3096. }
  3097. tp->rx_opt.user_mss = val;
  3098. break;
  3099. case TCP_NODELAY:
  3100. __tcp_sock_set_nodelay(sk, val);
  3101. break;
  3102. case TCP_THIN_LINEAR_TIMEOUTS:
  3103. if (val < 0 || val > 1)
  3104. err = -EINVAL;
  3105. else
  3106. tp->thin_lto = val;
  3107. break;
  3108. case TCP_THIN_DUPACK:
  3109. if (val < 0 || val > 1)
  3110. err = -EINVAL;
  3111. break;
  3112. case TCP_REPAIR:
  3113. if (!tcp_can_repair_sock(sk))
  3114. err = -EPERM;
  3115. else if (val == TCP_REPAIR_ON) {
  3116. tp->repair = 1;
  3117. sk->sk_reuse = SK_FORCE_REUSE;
  3118. tp->repair_queue = TCP_NO_QUEUE;
  3119. } else if (val == TCP_REPAIR_OFF) {
  3120. tp->repair = 0;
  3121. sk->sk_reuse = SK_NO_REUSE;
  3122. tcp_send_window_probe(sk);
  3123. } else if (val == TCP_REPAIR_OFF_NO_WP) {
  3124. tp->repair = 0;
  3125. sk->sk_reuse = SK_NO_REUSE;
  3126. } else
  3127. err = -EINVAL;
  3128. break;
  3129. case TCP_REPAIR_QUEUE:
  3130. if (!tp->repair)
  3131. err = -EPERM;
  3132. else if ((unsigned int)val < TCP_QUEUES_NR)
  3133. tp->repair_queue = val;
  3134. else
  3135. err = -EINVAL;
  3136. break;
  3137. case TCP_QUEUE_SEQ:
  3138. if (sk->sk_state != TCP_CLOSE) {
  3139. err = -EPERM;
  3140. } else if (tp->repair_queue == TCP_SEND_QUEUE) {
  3141. if (!tcp_rtx_queue_empty(sk))
  3142. err = -EPERM;
  3143. else
  3144. WRITE_ONCE(tp->write_seq, val);
  3145. } else if (tp->repair_queue == TCP_RECV_QUEUE) {
  3146. if (tp->rcv_nxt != tp->copied_seq) {
  3147. err = -EPERM;
  3148. } else {
  3149. WRITE_ONCE(tp->rcv_nxt, val);
  3150. WRITE_ONCE(tp->copied_seq, val);
  3151. }
  3152. } else {
  3153. err = -EINVAL;
  3154. }
  3155. break;
  3156. case TCP_REPAIR_OPTIONS:
  3157. if (!tp->repair)
  3158. err = -EINVAL;
  3159. else if (sk->sk_state == TCP_ESTABLISHED && !tp->bytes_sent)
  3160. err = tcp_repair_options_est(sk, optval, optlen);
  3161. else
  3162. err = -EPERM;
  3163. break;
  3164. case TCP_CORK:
  3165. __tcp_sock_set_cork(sk, val);
  3166. break;
  3167. case TCP_KEEPIDLE:
  3168. err = tcp_sock_set_keepidle_locked(sk, val);
  3169. break;
  3170. case TCP_KEEPINTVL:
  3171. if (val < 1 || val > MAX_TCP_KEEPINTVL)
  3172. err = -EINVAL;
  3173. else
  3174. WRITE_ONCE(tp->keepalive_intvl, val * HZ);
  3175. break;
  3176. case TCP_KEEPCNT:
  3177. if (val < 1 || val > MAX_TCP_KEEPCNT)
  3178. err = -EINVAL;
  3179. else
  3180. WRITE_ONCE(tp->keepalive_probes, val);
  3181. break;
  3182. case TCP_SYNCNT:
  3183. if (val < 1 || val > MAX_TCP_SYNCNT)
  3184. err = -EINVAL;
  3185. else
  3186. WRITE_ONCE(icsk->icsk_syn_retries, val);
  3187. break;
  3188. case TCP_SAVE_SYN:
  3189. /* 0: disable, 1: enable, 2: start from ether_header */
  3190. if (val < 0 || val > 2)
  3191. err = -EINVAL;
  3192. else
  3193. tp->save_syn = val;
  3194. break;
  3195. case TCP_LINGER2:
  3196. if (val < 0)
  3197. WRITE_ONCE(tp->linger2, -1);
  3198. else if (val > TCP_FIN_TIMEOUT_MAX / HZ)
  3199. WRITE_ONCE(tp->linger2, TCP_FIN_TIMEOUT_MAX);
  3200. else
  3201. WRITE_ONCE(tp->linger2, val * HZ);
  3202. break;
  3203. case TCP_DEFER_ACCEPT:
  3204. /* Translate value in seconds to number of retransmits */
  3205. WRITE_ONCE(icsk->icsk_accept_queue.rskq_defer_accept,
  3206. secs_to_retrans(val, TCP_TIMEOUT_INIT / HZ,
  3207. TCP_RTO_MAX / HZ));
  3208. break;
  3209. case TCP_WINDOW_CLAMP:
  3210. err = tcp_set_window_clamp(sk, val);
  3211. break;
  3212. case TCP_QUICKACK:
  3213. __tcp_sock_set_quickack(sk, val);
  3214. break;
  3215. #ifdef CONFIG_TCP_MD5SIG
  3216. case TCP_MD5SIG:
  3217. case TCP_MD5SIG_EXT:
  3218. err = tp->af_specific->md5_parse(sk, optname, optval, optlen);
  3219. break;
  3220. #endif
  3221. case TCP_USER_TIMEOUT:
  3222. /* Cap the max time in ms TCP will retry or probe the window
  3223. * before giving up and aborting (ETIMEDOUT) a connection.
  3224. */
  3225. if (val < 0)
  3226. err = -EINVAL;
  3227. else
  3228. WRITE_ONCE(icsk->icsk_user_timeout, val);
  3229. break;
  3230. case TCP_FASTOPEN:
  3231. if (val >= 0 && ((1 << sk->sk_state) & (TCPF_CLOSE |
  3232. TCPF_LISTEN))) {
  3233. tcp_fastopen_init_key_once(net);
  3234. fastopen_queue_tune(sk, val);
  3235. } else {
  3236. err = -EINVAL;
  3237. }
  3238. break;
  3239. case TCP_FASTOPEN_CONNECT:
  3240. if (val > 1 || val < 0) {
  3241. err = -EINVAL;
  3242. } else if (READ_ONCE(net->ipv4.sysctl_tcp_fastopen) &
  3243. TFO_CLIENT_ENABLE) {
  3244. if (sk->sk_state == TCP_CLOSE)
  3245. tp->fastopen_connect = val;
  3246. else
  3247. err = -EINVAL;
  3248. } else {
  3249. err = -EOPNOTSUPP;
  3250. }
  3251. break;
  3252. case TCP_FASTOPEN_NO_COOKIE:
  3253. if (val > 1 || val < 0)
  3254. err = -EINVAL;
  3255. else if (!((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN)))
  3256. err = -EINVAL;
  3257. else
  3258. tp->fastopen_no_cookie = val;
  3259. break;
  3260. case TCP_TIMESTAMP:
  3261. if (!tp->repair)
  3262. err = -EPERM;
  3263. else
  3264. WRITE_ONCE(tp->tsoffset, val - tcp_time_stamp_raw());
  3265. break;
  3266. case TCP_REPAIR_WINDOW:
  3267. err = tcp_repair_set_window(tp, optval, optlen);
  3268. break;
  3269. case TCP_NOTSENT_LOWAT:
  3270. WRITE_ONCE(tp->notsent_lowat, val);
  3271. sk->sk_write_space(sk);
  3272. break;
  3273. case TCP_INQ:
  3274. if (val > 1 || val < 0)
  3275. err = -EINVAL;
  3276. else
  3277. tp->recvmsg_inq = val;
  3278. break;
  3279. case TCP_TX_DELAY:
  3280. if (val)
  3281. tcp_enable_tx_delay();
  3282. WRITE_ONCE(tp->tcp_tx_delay, val);
  3283. break;
  3284. default:
  3285. err = -ENOPROTOOPT;
  3286. break;
  3287. }
  3288. sockopt_release_sock(sk);
  3289. return err;
  3290. }
  3291. int tcp_setsockopt(struct sock *sk, int level, int optname, sockptr_t optval,
  3292. unsigned int optlen)
  3293. {
  3294. const struct inet_connection_sock *icsk = inet_csk(sk);
  3295. if (level != SOL_TCP)
  3296. /* Paired with WRITE_ONCE() in do_ipv6_setsockopt() and tcp_v6_connect() */
  3297. return READ_ONCE(icsk->icsk_af_ops)->setsockopt(sk, level, optname,
  3298. optval, optlen);
  3299. return do_tcp_setsockopt(sk, level, optname, optval, optlen);
  3300. }
  3301. EXPORT_SYMBOL(tcp_setsockopt);
  3302. static void tcp_get_info_chrono_stats(const struct tcp_sock *tp,
  3303. struct tcp_info *info)
  3304. {
  3305. u64 stats[__TCP_CHRONO_MAX], total = 0;
  3306. enum tcp_chrono i;
  3307. for (i = TCP_CHRONO_BUSY; i < __TCP_CHRONO_MAX; ++i) {
  3308. stats[i] = tp->chrono_stat[i - 1];
  3309. if (i == tp->chrono_type)
  3310. stats[i] += tcp_jiffies32 - tp->chrono_start;
  3311. stats[i] *= USEC_PER_SEC / HZ;
  3312. total += stats[i];
  3313. }
  3314. info->tcpi_busy_time = total;
  3315. info->tcpi_rwnd_limited = stats[TCP_CHRONO_RWND_LIMITED];
  3316. info->tcpi_sndbuf_limited = stats[TCP_CHRONO_SNDBUF_LIMITED];
  3317. }
  3318. /* Return information about state of tcp endpoint in API format. */
  3319. void tcp_get_info(struct sock *sk, struct tcp_info *info)
  3320. {
  3321. const struct tcp_sock *tp = tcp_sk(sk); /* iff sk_type == SOCK_STREAM */
  3322. const struct inet_connection_sock *icsk = inet_csk(sk);
  3323. unsigned long rate;
  3324. u32 now;
  3325. u64 rate64;
  3326. bool slow;
  3327. memset(info, 0, sizeof(*info));
  3328. if (sk->sk_type != SOCK_STREAM)
  3329. return;
  3330. info->tcpi_state = inet_sk_state_load(sk);
  3331. /* Report meaningful fields for all TCP states, including listeners */
  3332. rate = READ_ONCE(sk->sk_pacing_rate);
  3333. rate64 = (rate != ~0UL) ? rate : ~0ULL;
  3334. info->tcpi_pacing_rate = rate64;
  3335. rate = READ_ONCE(sk->sk_max_pacing_rate);
  3336. rate64 = (rate != ~0UL) ? rate : ~0ULL;
  3337. info->tcpi_max_pacing_rate = rate64;
  3338. info->tcpi_reordering = tp->reordering;
  3339. info->tcpi_snd_cwnd = tcp_snd_cwnd(tp);
  3340. if (info->tcpi_state == TCP_LISTEN) {
  3341. /* listeners aliased fields :
  3342. * tcpi_unacked -> Number of children ready for accept()
  3343. * tcpi_sacked -> max backlog
  3344. */
  3345. info->tcpi_unacked = READ_ONCE(sk->sk_ack_backlog);
  3346. info->tcpi_sacked = READ_ONCE(sk->sk_max_ack_backlog);
  3347. return;
  3348. }
  3349. slow = lock_sock_fast(sk);
  3350. info->tcpi_ca_state = icsk->icsk_ca_state;
  3351. info->tcpi_retransmits = icsk->icsk_retransmits;
  3352. info->tcpi_probes = icsk->icsk_probes_out;
  3353. info->tcpi_backoff = icsk->icsk_backoff;
  3354. if (tp->rx_opt.tstamp_ok)
  3355. info->tcpi_options |= TCPI_OPT_TIMESTAMPS;
  3356. if (tcp_is_sack(tp))
  3357. info->tcpi_options |= TCPI_OPT_SACK;
  3358. if (tp->rx_opt.wscale_ok) {
  3359. info->tcpi_options |= TCPI_OPT_WSCALE;
  3360. info->tcpi_snd_wscale = tp->rx_opt.snd_wscale;
  3361. info->tcpi_rcv_wscale = tp->rx_opt.rcv_wscale;
  3362. }
  3363. if (tp->ecn_flags & TCP_ECN_OK)
  3364. info->tcpi_options |= TCPI_OPT_ECN;
  3365. if (tp->ecn_flags & TCP_ECN_SEEN)
  3366. info->tcpi_options |= TCPI_OPT_ECN_SEEN;
  3367. if (tp->syn_data_acked)
  3368. info->tcpi_options |= TCPI_OPT_SYN_DATA;
  3369. info->tcpi_rto = jiffies_to_usecs(icsk->icsk_rto);
  3370. info->tcpi_ato = jiffies_to_usecs(icsk->icsk_ack.ato);
  3371. info->tcpi_snd_mss = tp->mss_cache;
  3372. info->tcpi_rcv_mss = icsk->icsk_ack.rcv_mss;
  3373. info->tcpi_unacked = tp->packets_out;
  3374. info->tcpi_sacked = tp->sacked_out;
  3375. info->tcpi_lost = tp->lost_out;
  3376. info->tcpi_retrans = tp->retrans_out;
  3377. now = tcp_jiffies32;
  3378. info->tcpi_last_data_sent = jiffies_to_msecs(now - tp->lsndtime);
  3379. info->tcpi_last_data_recv = jiffies_to_msecs(now - icsk->icsk_ack.lrcvtime);
  3380. info->tcpi_last_ack_recv = jiffies_to_msecs(now - tp->rcv_tstamp);
  3381. info->tcpi_pmtu = icsk->icsk_pmtu_cookie;
  3382. info->tcpi_rcv_ssthresh = tp->rcv_ssthresh;
  3383. info->tcpi_rtt = tp->srtt_us >> 3;
  3384. info->tcpi_rttvar = tp->mdev_us >> 2;
  3385. info->tcpi_snd_ssthresh = tp->snd_ssthresh;
  3386. info->tcpi_advmss = tp->advmss;
  3387. info->tcpi_rcv_rtt = tp->rcv_rtt_est.rtt_us >> 3;
  3388. info->tcpi_rcv_space = tp->rcvq_space.space;
  3389. info->tcpi_total_retrans = tp->total_retrans;
  3390. info->tcpi_bytes_acked = tp->bytes_acked;
  3391. info->tcpi_bytes_received = tp->bytes_received;
  3392. info->tcpi_notsent_bytes = max_t(int, 0, tp->write_seq - tp->snd_nxt);
  3393. tcp_get_info_chrono_stats(tp, info);
  3394. info->tcpi_segs_out = tp->segs_out;
  3395. /* segs_in and data_segs_in can be updated from tcp_segs_in() from BH */
  3396. info->tcpi_segs_in = READ_ONCE(tp->segs_in);
  3397. info->tcpi_data_segs_in = READ_ONCE(tp->data_segs_in);
  3398. info->tcpi_min_rtt = tcp_min_rtt(tp);
  3399. info->tcpi_data_segs_out = tp->data_segs_out;
  3400. info->tcpi_delivery_rate_app_limited = tp->rate_app_limited ? 1 : 0;
  3401. rate64 = tcp_compute_delivery_rate(tp);
  3402. if (rate64)
  3403. info->tcpi_delivery_rate = rate64;
  3404. info->tcpi_delivered = tp->delivered;
  3405. info->tcpi_delivered_ce = tp->delivered_ce;
  3406. info->tcpi_bytes_sent = tp->bytes_sent;
  3407. info->tcpi_bytes_retrans = tp->bytes_retrans;
  3408. info->tcpi_dsack_dups = tp->dsack_dups;
  3409. info->tcpi_reord_seen = tp->reord_seen;
  3410. info->tcpi_rcv_ooopack = tp->rcv_ooopack;
  3411. info->tcpi_snd_wnd = tp->snd_wnd;
  3412. info->tcpi_fastopen_client_fail = tp->fastopen_client_fail;
  3413. unlock_sock_fast(sk, slow);
  3414. }
  3415. EXPORT_SYMBOL_GPL(tcp_get_info);
  3416. static size_t tcp_opt_stats_get_size(void)
  3417. {
  3418. return
  3419. nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_BUSY */
  3420. nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_RWND_LIMITED */
  3421. nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_SNDBUF_LIMITED */
  3422. nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_DATA_SEGS_OUT */
  3423. nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_TOTAL_RETRANS */
  3424. nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_PACING_RATE */
  3425. nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_DELIVERY_RATE */
  3426. nla_total_size(sizeof(u32)) + /* TCP_NLA_SND_CWND */
  3427. nla_total_size(sizeof(u32)) + /* TCP_NLA_REORDERING */
  3428. nla_total_size(sizeof(u32)) + /* TCP_NLA_MIN_RTT */
  3429. nla_total_size(sizeof(u8)) + /* TCP_NLA_RECUR_RETRANS */
  3430. nla_total_size(sizeof(u8)) + /* TCP_NLA_DELIVERY_RATE_APP_LMT */
  3431. nla_total_size(sizeof(u32)) + /* TCP_NLA_SNDQ_SIZE */
  3432. nla_total_size(sizeof(u8)) + /* TCP_NLA_CA_STATE */
  3433. nla_total_size(sizeof(u32)) + /* TCP_NLA_SND_SSTHRESH */
  3434. nla_total_size(sizeof(u32)) + /* TCP_NLA_DELIVERED */
  3435. nla_total_size(sizeof(u32)) + /* TCP_NLA_DELIVERED_CE */
  3436. nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_BYTES_SENT */
  3437. nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_BYTES_RETRANS */
  3438. nla_total_size(sizeof(u32)) + /* TCP_NLA_DSACK_DUPS */
  3439. nla_total_size(sizeof(u32)) + /* TCP_NLA_REORD_SEEN */
  3440. nla_total_size(sizeof(u32)) + /* TCP_NLA_SRTT */
  3441. nla_total_size(sizeof(u16)) + /* TCP_NLA_TIMEOUT_REHASH */
  3442. nla_total_size(sizeof(u32)) + /* TCP_NLA_BYTES_NOTSENT */
  3443. nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_EDT */
  3444. nla_total_size(sizeof(u8)) + /* TCP_NLA_TTL */
  3445. 0;
  3446. }
  3447. /* Returns TTL or hop limit of an incoming packet from skb. */
  3448. static u8 tcp_skb_ttl_or_hop_limit(const struct sk_buff *skb)
  3449. {
  3450. if (skb->protocol == htons(ETH_P_IP))
  3451. return ip_hdr(skb)->ttl;
  3452. else if (skb->protocol == htons(ETH_P_IPV6))
  3453. return ipv6_hdr(skb)->hop_limit;
  3454. else
  3455. return 0;
  3456. }
  3457. struct sk_buff *tcp_get_timestamping_opt_stats(const struct sock *sk,
  3458. const struct sk_buff *orig_skb,
  3459. const struct sk_buff *ack_skb)
  3460. {
  3461. const struct tcp_sock *tp = tcp_sk(sk);
  3462. struct sk_buff *stats;
  3463. struct tcp_info info;
  3464. unsigned long rate;
  3465. u64 rate64;
  3466. stats = alloc_skb(tcp_opt_stats_get_size(), GFP_ATOMIC);
  3467. if (!stats)
  3468. return NULL;
  3469. tcp_get_info_chrono_stats(tp, &info);
  3470. nla_put_u64_64bit(stats, TCP_NLA_BUSY,
  3471. info.tcpi_busy_time, TCP_NLA_PAD);
  3472. nla_put_u64_64bit(stats, TCP_NLA_RWND_LIMITED,
  3473. info.tcpi_rwnd_limited, TCP_NLA_PAD);
  3474. nla_put_u64_64bit(stats, TCP_NLA_SNDBUF_LIMITED,
  3475. info.tcpi_sndbuf_limited, TCP_NLA_PAD);
  3476. nla_put_u64_64bit(stats, TCP_NLA_DATA_SEGS_OUT,
  3477. tp->data_segs_out, TCP_NLA_PAD);
  3478. nla_put_u64_64bit(stats, TCP_NLA_TOTAL_RETRANS,
  3479. tp->total_retrans, TCP_NLA_PAD);
  3480. rate = READ_ONCE(sk->sk_pacing_rate);
  3481. rate64 = (rate != ~0UL) ? rate : ~0ULL;
  3482. nla_put_u64_64bit(stats, TCP_NLA_PACING_RATE, rate64, TCP_NLA_PAD);
  3483. rate64 = tcp_compute_delivery_rate(tp);
  3484. nla_put_u64_64bit(stats, TCP_NLA_DELIVERY_RATE, rate64, TCP_NLA_PAD);
  3485. nla_put_u32(stats, TCP_NLA_SND_CWND, tcp_snd_cwnd(tp));
  3486. nla_put_u32(stats, TCP_NLA_REORDERING, tp->reordering);
  3487. nla_put_u32(stats, TCP_NLA_MIN_RTT, tcp_min_rtt(tp));
  3488. nla_put_u8(stats, TCP_NLA_RECUR_RETRANS, inet_csk(sk)->icsk_retransmits);
  3489. nla_put_u8(stats, TCP_NLA_DELIVERY_RATE_APP_LMT, !!tp->rate_app_limited);
  3490. nla_put_u32(stats, TCP_NLA_SND_SSTHRESH, tp->snd_ssthresh);
  3491. nla_put_u32(stats, TCP_NLA_DELIVERED, tp->delivered);
  3492. nla_put_u32(stats, TCP_NLA_DELIVERED_CE, tp->delivered_ce);
  3493. nla_put_u32(stats, TCP_NLA_SNDQ_SIZE, tp->write_seq - tp->snd_una);
  3494. nla_put_u8(stats, TCP_NLA_CA_STATE, inet_csk(sk)->icsk_ca_state);
  3495. nla_put_u64_64bit(stats, TCP_NLA_BYTES_SENT, tp->bytes_sent,
  3496. TCP_NLA_PAD);
  3497. nla_put_u64_64bit(stats, TCP_NLA_BYTES_RETRANS, tp->bytes_retrans,
  3498. TCP_NLA_PAD);
  3499. nla_put_u32(stats, TCP_NLA_DSACK_DUPS, tp->dsack_dups);
  3500. nla_put_u32(stats, TCP_NLA_REORD_SEEN, tp->reord_seen);
  3501. nla_put_u32(stats, TCP_NLA_SRTT, tp->srtt_us >> 3);
  3502. nla_put_u16(stats, TCP_NLA_TIMEOUT_REHASH, tp->timeout_rehash);
  3503. nla_put_u32(stats, TCP_NLA_BYTES_NOTSENT,
  3504. max_t(int, 0, tp->write_seq - tp->snd_nxt));
  3505. nla_put_u64_64bit(stats, TCP_NLA_EDT, orig_skb->skb_mstamp_ns,
  3506. TCP_NLA_PAD);
  3507. if (ack_skb)
  3508. nla_put_u8(stats, TCP_NLA_TTL,
  3509. tcp_skb_ttl_or_hop_limit(ack_skb));
  3510. return stats;
  3511. }
  3512. int do_tcp_getsockopt(struct sock *sk, int level,
  3513. int optname, sockptr_t optval, sockptr_t optlen)
  3514. {
  3515. struct inet_connection_sock *icsk = inet_csk(sk);
  3516. struct tcp_sock *tp = tcp_sk(sk);
  3517. struct net *net = sock_net(sk);
  3518. int val, len;
  3519. if (copy_from_sockptr(&len, optlen, sizeof(int)))
  3520. return -EFAULT;
  3521. len = min_t(unsigned int, len, sizeof(int));
  3522. if (len < 0)
  3523. return -EINVAL;
  3524. switch (optname) {
  3525. case TCP_MAXSEG:
  3526. val = tp->mss_cache;
  3527. if (tp->rx_opt.user_mss &&
  3528. ((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN)))
  3529. val = tp->rx_opt.user_mss;
  3530. if (tp->repair)
  3531. val = tp->rx_opt.mss_clamp;
  3532. break;
  3533. case TCP_NODELAY:
  3534. val = !!(tp->nonagle&TCP_NAGLE_OFF);
  3535. break;
  3536. case TCP_CORK:
  3537. val = !!(tp->nonagle&TCP_NAGLE_CORK);
  3538. break;
  3539. case TCP_KEEPIDLE:
  3540. val = keepalive_time_when(tp) / HZ;
  3541. break;
  3542. case TCP_KEEPINTVL:
  3543. val = keepalive_intvl_when(tp) / HZ;
  3544. break;
  3545. case TCP_KEEPCNT:
  3546. val = keepalive_probes(tp);
  3547. break;
  3548. case TCP_SYNCNT:
  3549. val = READ_ONCE(icsk->icsk_syn_retries) ? :
  3550. READ_ONCE(net->ipv4.sysctl_tcp_syn_retries);
  3551. break;
  3552. case TCP_LINGER2:
  3553. val = READ_ONCE(tp->linger2);
  3554. if (val >= 0)
  3555. val = (val ? : READ_ONCE(net->ipv4.sysctl_tcp_fin_timeout)) / HZ;
  3556. break;
  3557. case TCP_DEFER_ACCEPT:
  3558. val = READ_ONCE(icsk->icsk_accept_queue.rskq_defer_accept);
  3559. val = retrans_to_secs(val, TCP_TIMEOUT_INIT / HZ,
  3560. TCP_RTO_MAX / HZ);
  3561. break;
  3562. case TCP_WINDOW_CLAMP:
  3563. val = tp->window_clamp;
  3564. break;
  3565. case TCP_INFO: {
  3566. struct tcp_info info;
  3567. if (copy_from_sockptr(&len, optlen, sizeof(int)))
  3568. return -EFAULT;
  3569. tcp_get_info(sk, &info);
  3570. len = min_t(unsigned int, len, sizeof(info));
  3571. if (copy_to_sockptr(optlen, &len, sizeof(int)))
  3572. return -EFAULT;
  3573. if (copy_to_sockptr(optval, &info, len))
  3574. return -EFAULT;
  3575. return 0;
  3576. }
  3577. case TCP_CC_INFO: {
  3578. const struct tcp_congestion_ops *ca_ops;
  3579. union tcp_cc_info info;
  3580. size_t sz = 0;
  3581. int attr;
  3582. if (copy_from_sockptr(&len, optlen, sizeof(int)))
  3583. return -EFAULT;
  3584. ca_ops = icsk->icsk_ca_ops;
  3585. if (ca_ops && ca_ops->get_info)
  3586. sz = ca_ops->get_info(sk, ~0U, &attr, &info);
  3587. len = min_t(unsigned int, len, sz);
  3588. if (copy_to_sockptr(optlen, &len, sizeof(int)))
  3589. return -EFAULT;
  3590. if (copy_to_sockptr(optval, &info, len))
  3591. return -EFAULT;
  3592. return 0;
  3593. }
  3594. case TCP_QUICKACK:
  3595. val = !inet_csk_in_pingpong_mode(sk);
  3596. break;
  3597. case TCP_CONGESTION:
  3598. if (copy_from_sockptr(&len, optlen, sizeof(int)))
  3599. return -EFAULT;
  3600. len = min_t(unsigned int, len, TCP_CA_NAME_MAX);
  3601. if (copy_to_sockptr(optlen, &len, sizeof(int)))
  3602. return -EFAULT;
  3603. if (copy_to_sockptr(optval, icsk->icsk_ca_ops->name, len))
  3604. return -EFAULT;
  3605. return 0;
  3606. case TCP_ULP:
  3607. if (copy_from_sockptr(&len, optlen, sizeof(int)))
  3608. return -EFAULT;
  3609. len = min_t(unsigned int, len, TCP_ULP_NAME_MAX);
  3610. if (!icsk->icsk_ulp_ops) {
  3611. len = 0;
  3612. if (copy_to_sockptr(optlen, &len, sizeof(int)))
  3613. return -EFAULT;
  3614. return 0;
  3615. }
  3616. if (copy_to_sockptr(optlen, &len, sizeof(int)))
  3617. return -EFAULT;
  3618. if (copy_to_sockptr(optval, icsk->icsk_ulp_ops->name, len))
  3619. return -EFAULT;
  3620. return 0;
  3621. case TCP_FASTOPEN_KEY: {
  3622. u64 key[TCP_FASTOPEN_KEY_BUF_LENGTH / sizeof(u64)];
  3623. unsigned int key_len;
  3624. if (copy_from_sockptr(&len, optlen, sizeof(int)))
  3625. return -EFAULT;
  3626. key_len = tcp_fastopen_get_cipher(net, icsk, key) *
  3627. TCP_FASTOPEN_KEY_LENGTH;
  3628. len = min_t(unsigned int, len, key_len);
  3629. if (copy_to_sockptr(optlen, &len, sizeof(int)))
  3630. return -EFAULT;
  3631. if (copy_to_sockptr(optval, key, len))
  3632. return -EFAULT;
  3633. return 0;
  3634. }
  3635. case TCP_THIN_LINEAR_TIMEOUTS:
  3636. val = tp->thin_lto;
  3637. break;
  3638. case TCP_THIN_DUPACK:
  3639. val = 0;
  3640. break;
  3641. case TCP_REPAIR:
  3642. val = tp->repair;
  3643. break;
  3644. case TCP_REPAIR_QUEUE:
  3645. if (tp->repair)
  3646. val = tp->repair_queue;
  3647. else
  3648. return -EINVAL;
  3649. break;
  3650. case TCP_REPAIR_WINDOW: {
  3651. struct tcp_repair_window opt;
  3652. if (copy_from_sockptr(&len, optlen, sizeof(int)))
  3653. return -EFAULT;
  3654. if (len != sizeof(opt))
  3655. return -EINVAL;
  3656. if (!tp->repair)
  3657. return -EPERM;
  3658. opt.snd_wl1 = tp->snd_wl1;
  3659. opt.snd_wnd = tp->snd_wnd;
  3660. opt.max_window = tp->max_window;
  3661. opt.rcv_wnd = tp->rcv_wnd;
  3662. opt.rcv_wup = tp->rcv_wup;
  3663. if (copy_to_sockptr(optval, &opt, len))
  3664. return -EFAULT;
  3665. return 0;
  3666. }
  3667. case TCP_QUEUE_SEQ:
  3668. if (tp->repair_queue == TCP_SEND_QUEUE)
  3669. val = tp->write_seq;
  3670. else if (tp->repair_queue == TCP_RECV_QUEUE)
  3671. val = tp->rcv_nxt;
  3672. else
  3673. return -EINVAL;
  3674. break;
  3675. case TCP_USER_TIMEOUT:
  3676. val = READ_ONCE(icsk->icsk_user_timeout);
  3677. break;
  3678. case TCP_FASTOPEN:
  3679. val = READ_ONCE(icsk->icsk_accept_queue.fastopenq.max_qlen);
  3680. break;
  3681. case TCP_FASTOPEN_CONNECT:
  3682. val = tp->fastopen_connect;
  3683. break;
  3684. case TCP_FASTOPEN_NO_COOKIE:
  3685. val = tp->fastopen_no_cookie;
  3686. break;
  3687. case TCP_TX_DELAY:
  3688. val = READ_ONCE(tp->tcp_tx_delay);
  3689. break;
  3690. case TCP_TIMESTAMP:
  3691. val = tcp_time_stamp_raw() + READ_ONCE(tp->tsoffset);
  3692. break;
  3693. case TCP_NOTSENT_LOWAT:
  3694. val = READ_ONCE(tp->notsent_lowat);
  3695. break;
  3696. case TCP_INQ:
  3697. val = tp->recvmsg_inq;
  3698. break;
  3699. case TCP_SAVE_SYN:
  3700. val = tp->save_syn;
  3701. break;
  3702. case TCP_SAVED_SYN: {
  3703. if (copy_from_sockptr(&len, optlen, sizeof(int)))
  3704. return -EFAULT;
  3705. sockopt_lock_sock(sk);
  3706. if (tp->saved_syn) {
  3707. if (len < tcp_saved_syn_len(tp->saved_syn)) {
  3708. len = tcp_saved_syn_len(tp->saved_syn);
  3709. if (copy_to_sockptr(optlen, &len, sizeof(int))) {
  3710. sockopt_release_sock(sk);
  3711. return -EFAULT;
  3712. }
  3713. sockopt_release_sock(sk);
  3714. return -EINVAL;
  3715. }
  3716. len = tcp_saved_syn_len(tp->saved_syn);
  3717. if (copy_to_sockptr(optlen, &len, sizeof(int))) {
  3718. sockopt_release_sock(sk);
  3719. return -EFAULT;
  3720. }
  3721. if (copy_to_sockptr(optval, tp->saved_syn->data, len)) {
  3722. sockopt_release_sock(sk);
  3723. return -EFAULT;
  3724. }
  3725. tcp_saved_syn_free(tp);
  3726. sockopt_release_sock(sk);
  3727. } else {
  3728. sockopt_release_sock(sk);
  3729. len = 0;
  3730. if (copy_to_sockptr(optlen, &len, sizeof(int)))
  3731. return -EFAULT;
  3732. }
  3733. return 0;
  3734. }
  3735. #ifdef CONFIG_MMU
  3736. case TCP_ZEROCOPY_RECEIVE: {
  3737. struct scm_timestamping_internal tss;
  3738. struct tcp_zerocopy_receive zc = {};
  3739. int err;
  3740. if (copy_from_sockptr(&len, optlen, sizeof(int)))
  3741. return -EFAULT;
  3742. if (len < 0 ||
  3743. len < offsetofend(struct tcp_zerocopy_receive, length))
  3744. return -EINVAL;
  3745. if (unlikely(len > sizeof(zc))) {
  3746. err = check_zeroed_sockptr(optval, sizeof(zc),
  3747. len - sizeof(zc));
  3748. if (err < 1)
  3749. return err == 0 ? -EINVAL : err;
  3750. len = sizeof(zc);
  3751. if (copy_to_sockptr(optlen, &len, sizeof(int)))
  3752. return -EFAULT;
  3753. }
  3754. if (copy_from_sockptr(&zc, optval, len))
  3755. return -EFAULT;
  3756. if (zc.reserved)
  3757. return -EINVAL;
  3758. if (zc.msg_flags & ~(TCP_VALID_ZC_MSG_FLAGS))
  3759. return -EINVAL;
  3760. sockopt_lock_sock(sk);
  3761. err = tcp_zerocopy_receive(sk, &zc, &tss);
  3762. err = BPF_CGROUP_RUN_PROG_GETSOCKOPT_KERN(sk, level, optname,
  3763. &zc, &len, err);
  3764. sockopt_release_sock(sk);
  3765. if (len >= offsetofend(struct tcp_zerocopy_receive, msg_flags))
  3766. goto zerocopy_rcv_cmsg;
  3767. switch (len) {
  3768. case offsetofend(struct tcp_zerocopy_receive, msg_flags):
  3769. goto zerocopy_rcv_cmsg;
  3770. case offsetofend(struct tcp_zerocopy_receive, msg_controllen):
  3771. case offsetofend(struct tcp_zerocopy_receive, msg_control):
  3772. case offsetofend(struct tcp_zerocopy_receive, flags):
  3773. case offsetofend(struct tcp_zerocopy_receive, copybuf_len):
  3774. case offsetofend(struct tcp_zerocopy_receive, copybuf_address):
  3775. case offsetofend(struct tcp_zerocopy_receive, err):
  3776. goto zerocopy_rcv_sk_err;
  3777. case offsetofend(struct tcp_zerocopy_receive, inq):
  3778. goto zerocopy_rcv_inq;
  3779. case offsetofend(struct tcp_zerocopy_receive, length):
  3780. default:
  3781. goto zerocopy_rcv_out;
  3782. }
  3783. zerocopy_rcv_cmsg:
  3784. if (zc.msg_flags & TCP_CMSG_TS)
  3785. tcp_zc_finalize_rx_tstamp(sk, &zc, &tss);
  3786. else
  3787. zc.msg_flags = 0;
  3788. zerocopy_rcv_sk_err:
  3789. if (!err)
  3790. zc.err = sock_error(sk);
  3791. zerocopy_rcv_inq:
  3792. zc.inq = tcp_inq_hint(sk);
  3793. zerocopy_rcv_out:
  3794. if (!err && copy_to_sockptr(optval, &zc, len))
  3795. err = -EFAULT;
  3796. return err;
  3797. }
  3798. #endif
  3799. default:
  3800. return -ENOPROTOOPT;
  3801. }
  3802. if (copy_to_sockptr(optlen, &len, sizeof(int)))
  3803. return -EFAULT;
  3804. if (copy_to_sockptr(optval, &val, len))
  3805. return -EFAULT;
  3806. return 0;
  3807. }
  3808. bool tcp_bpf_bypass_getsockopt(int level, int optname)
  3809. {
  3810. /* TCP do_tcp_getsockopt has optimized getsockopt implementation
  3811. * to avoid extra socket lock for TCP_ZEROCOPY_RECEIVE.
  3812. */
  3813. if (level == SOL_TCP && optname == TCP_ZEROCOPY_RECEIVE)
  3814. return true;
  3815. return false;
  3816. }
  3817. EXPORT_SYMBOL(tcp_bpf_bypass_getsockopt);
  3818. int tcp_getsockopt(struct sock *sk, int level, int optname, char __user *optval,
  3819. int __user *optlen)
  3820. {
  3821. struct inet_connection_sock *icsk = inet_csk(sk);
  3822. if (level != SOL_TCP)
  3823. /* Paired with WRITE_ONCE() in do_ipv6_setsockopt() and tcp_v6_connect() */
  3824. return READ_ONCE(icsk->icsk_af_ops)->getsockopt(sk, level, optname,
  3825. optval, optlen);
  3826. return do_tcp_getsockopt(sk, level, optname, USER_SOCKPTR(optval),
  3827. USER_SOCKPTR(optlen));
  3828. }
  3829. EXPORT_SYMBOL(tcp_getsockopt);
  3830. #ifdef CONFIG_TCP_MD5SIG
  3831. static DEFINE_PER_CPU(struct tcp_md5sig_pool, tcp_md5sig_pool);
  3832. static DEFINE_MUTEX(tcp_md5sig_mutex);
  3833. static bool tcp_md5sig_pool_populated = false;
  3834. static void __tcp_alloc_md5sig_pool(void)
  3835. {
  3836. struct crypto_ahash *hash;
  3837. int cpu;
  3838. hash = crypto_alloc_ahash("md5", 0, CRYPTO_ALG_ASYNC);
  3839. if (IS_ERR(hash))
  3840. return;
  3841. for_each_possible_cpu(cpu) {
  3842. void *scratch = per_cpu(tcp_md5sig_pool, cpu).scratch;
  3843. struct ahash_request *req;
  3844. if (!scratch) {
  3845. scratch = kmalloc_node(sizeof(union tcp_md5sum_block) +
  3846. sizeof(struct tcphdr),
  3847. GFP_KERNEL,
  3848. cpu_to_node(cpu));
  3849. if (!scratch)
  3850. return;
  3851. per_cpu(tcp_md5sig_pool, cpu).scratch = scratch;
  3852. }
  3853. if (per_cpu(tcp_md5sig_pool, cpu).md5_req)
  3854. continue;
  3855. req = ahash_request_alloc(hash, GFP_KERNEL);
  3856. if (!req)
  3857. return;
  3858. ahash_request_set_callback(req, 0, NULL, NULL);
  3859. per_cpu(tcp_md5sig_pool, cpu).md5_req = req;
  3860. }
  3861. /* before setting tcp_md5sig_pool_populated, we must commit all writes
  3862. * to memory. See smp_rmb() in tcp_get_md5sig_pool()
  3863. */
  3864. smp_wmb();
  3865. /* Paired with READ_ONCE() from tcp_alloc_md5sig_pool()
  3866. * and tcp_get_md5sig_pool().
  3867. */
  3868. WRITE_ONCE(tcp_md5sig_pool_populated, true);
  3869. }
  3870. bool tcp_alloc_md5sig_pool(void)
  3871. {
  3872. /* Paired with WRITE_ONCE() from __tcp_alloc_md5sig_pool() */
  3873. if (unlikely(!READ_ONCE(tcp_md5sig_pool_populated))) {
  3874. mutex_lock(&tcp_md5sig_mutex);
  3875. if (!tcp_md5sig_pool_populated) {
  3876. __tcp_alloc_md5sig_pool();
  3877. if (tcp_md5sig_pool_populated)
  3878. static_branch_inc(&tcp_md5_needed);
  3879. }
  3880. mutex_unlock(&tcp_md5sig_mutex);
  3881. }
  3882. /* Paired with WRITE_ONCE() from __tcp_alloc_md5sig_pool() */
  3883. return READ_ONCE(tcp_md5sig_pool_populated);
  3884. }
  3885. EXPORT_SYMBOL(tcp_alloc_md5sig_pool);
  3886. /**
  3887. * tcp_get_md5sig_pool - get md5sig_pool for this user
  3888. *
  3889. * We use percpu structure, so if we succeed, we exit with preemption
  3890. * and BH disabled, to make sure another thread or softirq handling
  3891. * wont try to get same context.
  3892. */
  3893. struct tcp_md5sig_pool *tcp_get_md5sig_pool(void)
  3894. {
  3895. local_bh_disable();
  3896. /* Paired with WRITE_ONCE() from __tcp_alloc_md5sig_pool() */
  3897. if (READ_ONCE(tcp_md5sig_pool_populated)) {
  3898. /* coupled with smp_wmb() in __tcp_alloc_md5sig_pool() */
  3899. smp_rmb();
  3900. return this_cpu_ptr(&tcp_md5sig_pool);
  3901. }
  3902. local_bh_enable();
  3903. return NULL;
  3904. }
  3905. EXPORT_SYMBOL(tcp_get_md5sig_pool);
  3906. int tcp_md5_hash_skb_data(struct tcp_md5sig_pool *hp,
  3907. const struct sk_buff *skb, unsigned int header_len)
  3908. {
  3909. struct scatterlist sg;
  3910. const struct tcphdr *tp = tcp_hdr(skb);
  3911. struct ahash_request *req = hp->md5_req;
  3912. unsigned int i;
  3913. const unsigned int head_data_len = skb_headlen(skb) > header_len ?
  3914. skb_headlen(skb) - header_len : 0;
  3915. const struct skb_shared_info *shi = skb_shinfo(skb);
  3916. struct sk_buff *frag_iter;
  3917. sg_init_table(&sg, 1);
  3918. sg_set_buf(&sg, ((u8 *) tp) + header_len, head_data_len);
  3919. ahash_request_set_crypt(req, &sg, NULL, head_data_len);
  3920. if (crypto_ahash_update(req))
  3921. return 1;
  3922. for (i = 0; i < shi->nr_frags; ++i) {
  3923. const skb_frag_t *f = &shi->frags[i];
  3924. unsigned int offset = skb_frag_off(f);
  3925. struct page *page = skb_frag_page(f) + (offset >> PAGE_SHIFT);
  3926. sg_set_page(&sg, page, skb_frag_size(f),
  3927. offset_in_page(offset));
  3928. ahash_request_set_crypt(req, &sg, NULL, skb_frag_size(f));
  3929. if (crypto_ahash_update(req))
  3930. return 1;
  3931. }
  3932. skb_walk_frags(skb, frag_iter)
  3933. if (tcp_md5_hash_skb_data(hp, frag_iter, 0))
  3934. return 1;
  3935. return 0;
  3936. }
  3937. EXPORT_SYMBOL(tcp_md5_hash_skb_data);
  3938. int tcp_md5_hash_key(struct tcp_md5sig_pool *hp, const struct tcp_md5sig_key *key)
  3939. {
  3940. u8 keylen = READ_ONCE(key->keylen); /* paired with WRITE_ONCE() in tcp_md5_do_add */
  3941. struct scatterlist sg;
  3942. sg_init_one(&sg, key->key, keylen);
  3943. ahash_request_set_crypt(hp->md5_req, &sg, NULL, keylen);
  3944. /* We use data_race() because tcp_md5_do_add() might change key->key under us */
  3945. return data_race(crypto_ahash_update(hp->md5_req));
  3946. }
  3947. EXPORT_SYMBOL(tcp_md5_hash_key);
  3948. /* Called with rcu_read_lock() */
  3949. enum skb_drop_reason
  3950. tcp_inbound_md5_hash(const struct sock *sk, const struct sk_buff *skb,
  3951. const void *saddr, const void *daddr,
  3952. int family, int dif, int sdif)
  3953. {
  3954. /*
  3955. * This gets called for each TCP segment that arrives
  3956. * so we want to be efficient.
  3957. * We have 3 drop cases:
  3958. * o No MD5 hash and one expected.
  3959. * o MD5 hash and we're not expecting one.
  3960. * o MD5 hash and its wrong.
  3961. */
  3962. const __u8 *hash_location = NULL;
  3963. struct tcp_md5sig_key *hash_expected;
  3964. const struct tcphdr *th = tcp_hdr(skb);
  3965. struct tcp_sock *tp = tcp_sk(sk);
  3966. int genhash, l3index;
  3967. u8 newhash[16];
  3968. /* sdif set, means packet ingressed via a device
  3969. * in an L3 domain and dif is set to the l3mdev
  3970. */
  3971. l3index = sdif ? dif : 0;
  3972. hash_expected = tcp_md5_do_lookup(sk, l3index, saddr, family);
  3973. hash_location = tcp_parse_md5sig_option(th);
  3974. /* We've parsed the options - do we have a hash? */
  3975. if (!hash_expected && !hash_location)
  3976. return SKB_NOT_DROPPED_YET;
  3977. if (hash_expected && !hash_location) {
  3978. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMD5NOTFOUND);
  3979. return SKB_DROP_REASON_TCP_MD5NOTFOUND;
  3980. }
  3981. if (!hash_expected && hash_location) {
  3982. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMD5UNEXPECTED);
  3983. return SKB_DROP_REASON_TCP_MD5UNEXPECTED;
  3984. }
  3985. /* Check the signature.
  3986. * To support dual stack listeners, we need to handle
  3987. * IPv4-mapped case.
  3988. */
  3989. if (family == AF_INET)
  3990. genhash = tcp_v4_md5_hash_skb(newhash,
  3991. hash_expected,
  3992. NULL, skb);
  3993. else
  3994. genhash = tp->af_specific->calc_md5_hash(newhash,
  3995. hash_expected,
  3996. NULL, skb);
  3997. if (genhash || memcmp(hash_location, newhash, 16) != 0) {
  3998. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMD5FAILURE);
  3999. if (family == AF_INET) {
  4000. net_info_ratelimited("MD5 Hash failed for (%pI4, %d)->(%pI4, %d)%s L3 index %d\n",
  4001. saddr, ntohs(th->source),
  4002. daddr, ntohs(th->dest),
  4003. genhash ? " tcp_v4_calc_md5_hash failed"
  4004. : "", l3index);
  4005. } else {
  4006. net_info_ratelimited("MD5 Hash %s for [%pI6c]:%u->[%pI6c]:%u L3 index %d\n",
  4007. genhash ? "failed" : "mismatch",
  4008. saddr, ntohs(th->source),
  4009. daddr, ntohs(th->dest), l3index);
  4010. }
  4011. return SKB_DROP_REASON_TCP_MD5FAILURE;
  4012. }
  4013. return SKB_NOT_DROPPED_YET;
  4014. }
  4015. EXPORT_SYMBOL(tcp_inbound_md5_hash);
  4016. #endif
  4017. void tcp_done(struct sock *sk)
  4018. {
  4019. struct request_sock *req;
  4020. /* We might be called with a new socket, after
  4021. * inet_csk_prepare_forced_close() has been called
  4022. * so we can not use lockdep_sock_is_held(sk)
  4023. */
  4024. req = rcu_dereference_protected(tcp_sk(sk)->fastopen_rsk, 1);
  4025. if (sk->sk_state == TCP_SYN_SENT || sk->sk_state == TCP_SYN_RECV)
  4026. TCP_INC_STATS(sock_net(sk), TCP_MIB_ATTEMPTFAILS);
  4027. tcp_set_state(sk, TCP_CLOSE);
  4028. tcp_clear_xmit_timers(sk);
  4029. if (req)
  4030. reqsk_fastopen_remove(sk, req, false);
  4031. WRITE_ONCE(sk->sk_shutdown, SHUTDOWN_MASK);
  4032. if (!sock_flag(sk, SOCK_DEAD))
  4033. sk->sk_state_change(sk);
  4034. else
  4035. inet_csk_destroy_sock(sk);
  4036. }
  4037. EXPORT_SYMBOL_GPL(tcp_done);
  4038. int tcp_abort(struct sock *sk, int err)
  4039. {
  4040. int state = inet_sk_state_load(sk);
  4041. if (state == TCP_NEW_SYN_RECV) {
  4042. struct request_sock *req = inet_reqsk(sk);
  4043. local_bh_disable();
  4044. inet_csk_reqsk_queue_drop(req->rsk_listener, req);
  4045. local_bh_enable();
  4046. return 0;
  4047. }
  4048. if (state == TCP_TIME_WAIT) {
  4049. struct inet_timewait_sock *tw = inet_twsk(sk);
  4050. refcount_inc(&tw->tw_refcnt);
  4051. local_bh_disable();
  4052. inet_twsk_deschedule_put(tw);
  4053. local_bh_enable();
  4054. return 0;
  4055. }
  4056. /* Don't race with userspace socket closes such as tcp_close. */
  4057. lock_sock(sk);
  4058. if (sk->sk_state == TCP_LISTEN) {
  4059. tcp_set_state(sk, TCP_CLOSE);
  4060. inet_csk_listen_stop(sk);
  4061. }
  4062. /* Don't race with BH socket closes such as inet_csk_listen_stop. */
  4063. local_bh_disable();
  4064. bh_lock_sock(sk);
  4065. if (!sock_flag(sk, SOCK_DEAD)) {
  4066. sk->sk_err = err;
  4067. /* This barrier is coupled with smp_rmb() in tcp_poll() */
  4068. smp_wmb();
  4069. sk_error_report(sk);
  4070. if (tcp_need_reset(sk->sk_state))
  4071. tcp_send_active_reset(sk, GFP_ATOMIC);
  4072. tcp_done(sk);
  4073. }
  4074. bh_unlock_sock(sk);
  4075. local_bh_enable();
  4076. tcp_write_queue_purge(sk);
  4077. release_sock(sk);
  4078. return 0;
  4079. }
  4080. EXPORT_SYMBOL_GPL(tcp_abort);
  4081. extern struct tcp_congestion_ops tcp_reno;
  4082. static __initdata unsigned long thash_entries;
  4083. static int __init set_thash_entries(char *str)
  4084. {
  4085. ssize_t ret;
  4086. if (!str)
  4087. return 0;
  4088. ret = kstrtoul(str, 0, &thash_entries);
  4089. if (ret)
  4090. return 0;
  4091. return 1;
  4092. }
  4093. __setup("thash_entries=", set_thash_entries);
  4094. static void __init tcp_init_mem(void)
  4095. {
  4096. unsigned long limit = nr_free_buffer_pages() / 16;
  4097. limit = max(limit, 128UL);
  4098. sysctl_tcp_mem[0] = limit / 4 * 3; /* 4.68 % */
  4099. sysctl_tcp_mem[1] = limit; /* 6.25 % */
  4100. sysctl_tcp_mem[2] = sysctl_tcp_mem[0] * 2; /* 9.37 % */
  4101. }
  4102. void __init tcp_init(void)
  4103. {
  4104. int max_rshare, max_wshare, cnt;
  4105. unsigned long limit;
  4106. unsigned int i;
  4107. BUILD_BUG_ON(TCP_MIN_SND_MSS <= MAX_TCP_OPTION_SPACE);
  4108. BUILD_BUG_ON(sizeof(struct tcp_skb_cb) >
  4109. sizeof_field(struct sk_buff, cb));
  4110. percpu_counter_init(&tcp_sockets_allocated, 0, GFP_KERNEL);
  4111. timer_setup(&tcp_orphan_timer, tcp_orphan_update, TIMER_DEFERRABLE);
  4112. mod_timer(&tcp_orphan_timer, jiffies + TCP_ORPHAN_TIMER_PERIOD);
  4113. inet_hashinfo2_init(&tcp_hashinfo, "tcp_listen_portaddr_hash",
  4114. thash_entries, 21, /* one slot per 2 MB*/
  4115. 0, 64 * 1024);
  4116. tcp_hashinfo.bind_bucket_cachep =
  4117. kmem_cache_create("tcp_bind_bucket",
  4118. sizeof(struct inet_bind_bucket), 0,
  4119. SLAB_HWCACHE_ALIGN | SLAB_PANIC |
  4120. SLAB_ACCOUNT,
  4121. NULL);
  4122. tcp_hashinfo.bind2_bucket_cachep =
  4123. kmem_cache_create("tcp_bind2_bucket",
  4124. sizeof(struct inet_bind2_bucket), 0,
  4125. SLAB_HWCACHE_ALIGN | SLAB_PANIC |
  4126. SLAB_ACCOUNT,
  4127. NULL);
  4128. /* Size and allocate the main established and bind bucket
  4129. * hash tables.
  4130. *
  4131. * The methodology is similar to that of the buffer cache.
  4132. */
  4133. tcp_hashinfo.ehash =
  4134. alloc_large_system_hash("TCP established",
  4135. sizeof(struct inet_ehash_bucket),
  4136. thash_entries,
  4137. 17, /* one slot per 128 KB of memory */
  4138. 0,
  4139. NULL,
  4140. &tcp_hashinfo.ehash_mask,
  4141. 0,
  4142. thash_entries ? 0 : 512 * 1024);
  4143. for (i = 0; i <= tcp_hashinfo.ehash_mask; i++)
  4144. INIT_HLIST_NULLS_HEAD(&tcp_hashinfo.ehash[i].chain, i);
  4145. if (inet_ehash_locks_alloc(&tcp_hashinfo))
  4146. panic("TCP: failed to alloc ehash_locks");
  4147. tcp_hashinfo.bhash =
  4148. alloc_large_system_hash("TCP bind",
  4149. 2 * sizeof(struct inet_bind_hashbucket),
  4150. tcp_hashinfo.ehash_mask + 1,
  4151. 17, /* one slot per 128 KB of memory */
  4152. 0,
  4153. &tcp_hashinfo.bhash_size,
  4154. NULL,
  4155. 0,
  4156. 64 * 1024);
  4157. tcp_hashinfo.bhash_size = 1U << tcp_hashinfo.bhash_size;
  4158. tcp_hashinfo.bhash2 = tcp_hashinfo.bhash + tcp_hashinfo.bhash_size;
  4159. for (i = 0; i < tcp_hashinfo.bhash_size; i++) {
  4160. spin_lock_init(&tcp_hashinfo.bhash[i].lock);
  4161. INIT_HLIST_HEAD(&tcp_hashinfo.bhash[i].chain);
  4162. spin_lock_init(&tcp_hashinfo.bhash2[i].lock);
  4163. INIT_HLIST_HEAD(&tcp_hashinfo.bhash2[i].chain);
  4164. }
  4165. tcp_hashinfo.pernet = false;
  4166. cnt = tcp_hashinfo.ehash_mask + 1;
  4167. sysctl_tcp_max_orphans = cnt / 2;
  4168. tcp_init_mem();
  4169. /* Set per-socket limits to no more than 1/128 the pressure threshold */
  4170. limit = nr_free_buffer_pages() << (PAGE_SHIFT - 7);
  4171. max_wshare = min(4UL*1024*1024, limit);
  4172. max_rshare = min(6UL*1024*1024, limit);
  4173. init_net.ipv4.sysctl_tcp_wmem[0] = PAGE_SIZE;
  4174. init_net.ipv4.sysctl_tcp_wmem[1] = 16*1024;
  4175. init_net.ipv4.sysctl_tcp_wmem[2] = max(64*1024, max_wshare);
  4176. init_net.ipv4.sysctl_tcp_rmem[0] = PAGE_SIZE;
  4177. init_net.ipv4.sysctl_tcp_rmem[1] = 131072;
  4178. init_net.ipv4.sysctl_tcp_rmem[2] = max(131072, max_rshare);
  4179. pr_info("Hash tables configured (established %u bind %u)\n",
  4180. tcp_hashinfo.ehash_mask + 1, tcp_hashinfo.bhash_size);
  4181. tcp_v4_init();
  4182. tcp_metrics_init();
  4183. BUG_ON(tcp_register_congestion_control(&tcp_reno) != 0);
  4184. tcp_tasklet_init();
  4185. mptcp_init();
  4186. }