tcp.c 140 KB

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