tcp.c 99 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870
  1. /*
  2. * INET An implementation of the TCP/IP protocol suite for the LINUX
  3. * operating system. INET is implemented using the BSD Socket
  4. * interface as the means of communication with the user level.
  5. *
  6. * Implementation of the Transmission Control Protocol(TCP).
  7. *
  8. * Authors: Ross Biro
  9. * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
  10. * Mark Evans, <evansmp@uhura.aston.ac.uk>
  11. * Corey Minyard <wf-rch!minyard@relay.EU.net>
  12. * Florian La Roche, <flla@stud.uni-sb.de>
  13. * Charles Hedrick, <hedrick@klinzhai.rutgers.edu>
  14. * Linus Torvalds, <torvalds@cs.helsinki.fi>
  15. * Alan Cox, <gw4pts@gw4pts.ampr.org>
  16. * Matthew Dillon, <dillon@apollo.west.oic.com>
  17. * Arnt Gulbrandsen, <agulbra@nvg.unit.no>
  18. * Jorge Cwik, <jorge@laser.satlink.net>
  19. *
  20. * Fixes:
  21. * Alan Cox : Numerous verify_area() calls
  22. * Alan Cox : Set the ACK bit on a reset
  23. * Alan Cox : Stopped it crashing if it closed while
  24. * sk->inuse=1 and was trying to connect
  25. * (tcp_err()).
  26. * Alan Cox : All icmp error handling was broken
  27. * pointers passed where wrong and the
  28. * socket was looked up backwards. Nobody
  29. * tested any icmp error code obviously.
  30. * Alan Cox : tcp_err() now handled properly. It
  31. * wakes people on errors. poll
  32. * behaves and the icmp error race
  33. * has gone by moving it into sock.c
  34. * Alan Cox : tcp_send_reset() fixed to work for
  35. * everything not just packets for
  36. * unknown sockets.
  37. * Alan Cox : tcp option processing.
  38. * Alan Cox : Reset tweaked (still not 100%) [Had
  39. * syn rule wrong]
  40. * Herp Rosmanith : More reset fixes
  41. * Alan Cox : No longer acks invalid rst frames.
  42. * Acking any kind of RST is right out.
  43. * Alan Cox : Sets an ignore me flag on an rst
  44. * receive otherwise odd bits of prattle
  45. * escape still
  46. * Alan Cox : Fixed another acking RST frame bug.
  47. * Should stop LAN workplace lockups.
  48. * Alan Cox : Some tidyups using the new skb list
  49. * facilities
  50. * Alan Cox : sk->keepopen now seems to work
  51. * Alan Cox : Pulls options out correctly on accepts
  52. * Alan Cox : Fixed assorted sk->rqueue->next errors
  53. * Alan Cox : PSH doesn't end a TCP read. Switched a
  54. * bit to skb ops.
  55. * Alan Cox : Tidied tcp_data to avoid a potential
  56. * nasty.
  57. * Alan Cox : Added some better commenting, as the
  58. * tcp is hard to follow
  59. * Alan Cox : Removed incorrect check for 20 * psh
  60. * Michael O'Reilly : ack < copied bug fix.
  61. * Johannes Stille : Misc tcp fixes (not all in yet).
  62. * Alan Cox : FIN with no memory -> CRASH
  63. * Alan Cox : Added socket option proto entries.
  64. * Also added awareness of them to accept.
  65. * Alan Cox : Added TCP options (SOL_TCP)
  66. * Alan Cox : Switched wakeup calls to callbacks,
  67. * so the kernel can layer network
  68. * sockets.
  69. * Alan Cox : Use ip_tos/ip_ttl settings.
  70. * Alan Cox : Handle FIN (more) properly (we hope).
  71. * Alan Cox : RST frames sent on unsynchronised
  72. * state ack error.
  73. * Alan Cox : Put in missing check for SYN bit.
  74. * Alan Cox : Added tcp_select_window() aka NET2E
  75. * window non shrink trick.
  76. * Alan Cox : Added a couple of small NET2E timer
  77. * fixes
  78. * Charles Hedrick : TCP fixes
  79. * Toomas Tamm : TCP window fixes
  80. * Alan Cox : Small URG fix to rlogin ^C ack fight
  81. * Charles Hedrick : Rewrote most of it to actually work
  82. * Linus : Rewrote tcp_read() and URG handling
  83. * completely
  84. * Gerhard Koerting: Fixed some missing timer handling
  85. * Matthew Dillon : Reworked TCP machine states as per RFC
  86. * Gerhard Koerting: PC/TCP workarounds
  87. * Adam Caldwell : Assorted timer/timing errors
  88. * Matthew Dillon : Fixed another RST bug
  89. * Alan Cox : Move to kernel side addressing changes.
  90. * Alan Cox : Beginning work on TCP fastpathing
  91. * (not yet usable)
  92. * Arnt Gulbrandsen: Turbocharged tcp_check() routine.
  93. * Alan Cox : TCP fast path debugging
  94. * Alan Cox : Window clamping
  95. * Michael Riepe : Bug in tcp_check()
  96. * Matt Dillon : More TCP improvements and RST bug fixes
  97. * Matt Dillon : Yet more small nasties remove from the
  98. * TCP code (Be very nice to this man if
  99. * tcp finally works 100%) 8)
  100. * Alan Cox : BSD accept semantics.
  101. * Alan Cox : Reset on closedown bug.
  102. * Peter De Schrijver : ENOTCONN check missing in tcp_sendto().
  103. * Michael Pall : Handle poll() after URG properly in
  104. * all cases.
  105. * Michael Pall : Undo the last fix in tcp_read_urg()
  106. * (multi URG PUSH broke rlogin).
  107. * Michael Pall : Fix the multi URG PUSH problem in
  108. * tcp_readable(), poll() after URG
  109. * works now.
  110. * Michael Pall : recv(...,MSG_OOB) never blocks in the
  111. * BSD api.
  112. * Alan Cox : Changed the semantics of sk->socket to
  113. * fix a race and a signal problem with
  114. * accept() and async I/O.
  115. * Alan Cox : Relaxed the rules on tcp_sendto().
  116. * Yury Shevchuk : Really fixed accept() blocking problem.
  117. * Craig I. Hagan : Allow for BSD compatible TIME_WAIT for
  118. * clients/servers which listen in on
  119. * fixed ports.
  120. * Alan Cox : Cleaned the above up and shrank it to
  121. * a sensible code size.
  122. * Alan Cox : Self connect lockup fix.
  123. * Alan Cox : No connect to multicast.
  124. * Ross Biro : Close unaccepted children on master
  125. * socket close.
  126. * Alan Cox : Reset tracing code.
  127. * Alan Cox : Spurious resets on shutdown.
  128. * Alan Cox : Giant 15 minute/60 second timer error
  129. * Alan Cox : Small whoops in polling before an
  130. * accept.
  131. * Alan Cox : Kept the state trace facility since
  132. * it's handy for debugging.
  133. * Alan Cox : More reset handler fixes.
  134. * Alan Cox : Started rewriting the code based on
  135. * the RFC's for other useful protocol
  136. * references see: Comer, KA9Q NOS, and
  137. * for a reference on the difference
  138. * between specifications and how BSD
  139. * works see the 4.4lite source.
  140. * A.N.Kuznetsov : Don't time wait on completion of tidy
  141. * close.
  142. * Linus Torvalds : Fin/Shutdown & copied_seq changes.
  143. * Linus Torvalds : Fixed BSD port reuse to work first syn
  144. * Alan Cox : Reimplemented timers as per the RFC
  145. * and using multiple timers for sanity.
  146. * Alan Cox : Small bug fixes, and a lot of new
  147. * comments.
  148. * Alan Cox : Fixed dual reader crash by locking
  149. * the buffers (much like datagram.c)
  150. * Alan Cox : Fixed stuck sockets in probe. A probe
  151. * now gets fed up of retrying without
  152. * (even a no space) answer.
  153. * Alan Cox : Extracted closing code better
  154. * Alan Cox : Fixed the closing state machine to
  155. * resemble the RFC.
  156. * Alan Cox : More 'per spec' fixes.
  157. * Jorge Cwik : Even faster checksumming.
  158. * Alan Cox : tcp_data() doesn't ack illegal PSH
  159. * only frames. At least one pc tcp stack
  160. * generates them.
  161. * Alan Cox : Cache last socket.
  162. * Alan Cox : Per route irtt.
  163. * Matt Day : poll()->select() match BSD precisely on error
  164. * Alan Cox : New buffers
  165. * Marc Tamsky : Various sk->prot->retransmits and
  166. * sk->retransmits misupdating fixed.
  167. * Fixed tcp_write_timeout: stuck close,
  168. * and TCP syn retries gets used now.
  169. * Mark Yarvis : In tcp_read_wakeup(), don't send an
  170. * ack if state is TCP_CLOSED.
  171. * Alan Cox : Look up device on a retransmit - routes may
  172. * change. Doesn't yet cope with MSS shrink right
  173. * but it's a start!
  174. * Marc Tamsky : Closing in closing fixes.
  175. * Mike Shaver : RFC1122 verifications.
  176. * Alan Cox : rcv_saddr errors.
  177. * Alan Cox : Block double connect().
  178. * Alan Cox : Small hooks for enSKIP.
  179. * Alexey Kuznetsov: Path MTU discovery.
  180. * Alan Cox : Support soft errors.
  181. * Alan Cox : Fix MTU discovery pathological case
  182. * when the remote claims no mtu!
  183. * Marc Tamsky : TCP_CLOSE fix.
  184. * Colin (G3TNE) : Send a reset on syn ack replies in
  185. * window but wrong (fixes NT lpd problems)
  186. * Pedro Roque : Better TCP window handling, delayed ack.
  187. * Joerg Reuter : No modification of locked buffers in
  188. * tcp_do_retransmit()
  189. * Eric Schenk : Changed receiver side silly window
  190. * avoidance algorithm to BSD style
  191. * algorithm. This doubles throughput
  192. * against machines running Solaris,
  193. * and seems to result in general
  194. * improvement.
  195. * Stefan Magdalinski : adjusted tcp_readable() to fix FIONREAD
  196. * Willy Konynenberg : Transparent proxying support.
  197. * Mike McLagan : Routing by source
  198. * Keith Owens : Do proper merging with partial SKB's in
  199. * tcp_do_sendmsg to avoid burstiness.
  200. * Eric Schenk : Fix fast close down bug with
  201. * shutdown() followed by close().
  202. * Andi Kleen : Make poll agree with SIGIO
  203. * Salvatore Sanfilippo : Support SO_LINGER with linger == 1 and
  204. * lingertime == 0 (RFC 793 ABORT Call)
  205. * Hirokazu Takahashi : Use copy_from_user() instead of
  206. * csum_and_copy_from_user() if possible.
  207. *
  208. * This program is free software; you can redistribute it and/or
  209. * modify it under the terms of the GNU General Public License
  210. * as published by the Free Software Foundation; either version
  211. * 2 of the License, or(at your option) any later version.
  212. *
  213. * Description of States:
  214. *
  215. * TCP_SYN_SENT sent a connection request, waiting for ack
  216. *
  217. * TCP_SYN_RECV received a connection request, sent ack,
  218. * waiting for final ack in three-way handshake.
  219. *
  220. * TCP_ESTABLISHED connection established
  221. *
  222. * TCP_FIN_WAIT1 our side has shutdown, waiting to complete
  223. * transmission of remaining buffered data
  224. *
  225. * TCP_FIN_WAIT2 all buffered data sent, waiting for remote
  226. * to shutdown
  227. *
  228. * TCP_CLOSING both sides have shutdown but we still have
  229. * data we have to finish sending
  230. *
  231. * TCP_TIME_WAIT timeout to catch resent junk before entering
  232. * closed, can only be entered from FIN_WAIT2
  233. * or CLOSING. Required because the other end
  234. * may not have gotten our last ACK causing it
  235. * to retransmit the data packet (which we ignore)
  236. *
  237. * TCP_CLOSE_WAIT remote side has shutdown and is waiting for
  238. * us to finish writing our data and to shutdown
  239. * (we have to close() to move on to LAST_ACK)
  240. *
  241. * TCP_LAST_ACK out side has shutdown after remote has
  242. * shutdown. There may still be data in our
  243. * buffer that we have to finish sending
  244. *
  245. * TCP_CLOSE socket is finished
  246. */
  247. #define pr_fmt(fmt) "TCP: " fmt
  248. #include <crypto/hash.h>
  249. #include <linux/kernel.h>
  250. #include <linux/module.h>
  251. #include <linux/types.h>
  252. #include <linux/fcntl.h>
  253. #include <linux/poll.h>
  254. #include <linux/inet_diag.h>
  255. #include <linux/init.h>
  256. #include <linux/fs.h>
  257. #include <linux/skbuff.h>
  258. #include <linux/scatterlist.h>
  259. #include <linux/splice.h>
  260. #include <linux/net.h>
  261. #include <linux/socket.h>
  262. #include <linux/random.h>
  263. #include <linux/bootmem.h>
  264. #include <linux/highmem.h>
  265. #include <linux/swap.h>
  266. #include <linux/cache.h>
  267. #include <linux/err.h>
  268. #include <linux/time.h>
  269. #include <linux/slab.h>
  270. #include <linux/errqueue.h>
  271. #include <linux/static_key.h>
  272. #include <net/icmp.h>
  273. #include <net/inet_common.h>
  274. #include <net/tcp.h>
  275. #include <net/xfrm.h>
  276. #include <net/ip.h>
  277. #include <net/sock.h>
  278. #include <linux/uaccess.h>
  279. #include <asm/ioctls.h>
  280. #include <net/busy_poll.h>
  281. struct percpu_counter tcp_orphan_count;
  282. EXPORT_SYMBOL_GPL(tcp_orphan_count);
  283. long sysctl_tcp_mem[3] __read_mostly;
  284. EXPORT_SYMBOL(sysctl_tcp_mem);
  285. atomic_long_t tcp_memory_allocated; /* Current allocated memory. */
  286. EXPORT_SYMBOL(tcp_memory_allocated);
  287. #if IS_ENABLED(CONFIG_SMC)
  288. DEFINE_STATIC_KEY_FALSE(tcp_have_smc);
  289. EXPORT_SYMBOL(tcp_have_smc);
  290. #endif
  291. /*
  292. * Current number of TCP sockets.
  293. */
  294. struct percpu_counter tcp_sockets_allocated;
  295. EXPORT_SYMBOL(tcp_sockets_allocated);
  296. /*
  297. * TCP splice context
  298. */
  299. struct tcp_splice_state {
  300. struct pipe_inode_info *pipe;
  301. size_t len;
  302. unsigned int flags;
  303. };
  304. /*
  305. * Pressure flag: try to collapse.
  306. * Technical note: it is used by multiple contexts non atomically.
  307. * All the __sk_mem_schedule() is of this nature: accounting
  308. * is strict, actions are advisory and have some latency.
  309. */
  310. unsigned long tcp_memory_pressure __read_mostly;
  311. EXPORT_SYMBOL_GPL(tcp_memory_pressure);
  312. void tcp_enter_memory_pressure(struct sock *sk)
  313. {
  314. unsigned long val;
  315. if (tcp_memory_pressure)
  316. return;
  317. val = jiffies;
  318. if (!val)
  319. val--;
  320. if (!cmpxchg(&tcp_memory_pressure, 0, val))
  321. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMEMORYPRESSURES);
  322. }
  323. EXPORT_SYMBOL_GPL(tcp_enter_memory_pressure);
  324. void tcp_leave_memory_pressure(struct sock *sk)
  325. {
  326. unsigned long val;
  327. if (!tcp_memory_pressure)
  328. return;
  329. val = xchg(&tcp_memory_pressure, 0);
  330. if (val)
  331. NET_ADD_STATS(sock_net(sk), LINUX_MIB_TCPMEMORYPRESSURESCHRONO,
  332. jiffies_to_msecs(jiffies - val));
  333. }
  334. EXPORT_SYMBOL_GPL(tcp_leave_memory_pressure);
  335. /* Convert seconds to retransmits based on initial and max timeout */
  336. static u8 secs_to_retrans(int seconds, int timeout, int rto_max)
  337. {
  338. u8 res = 0;
  339. if (seconds > 0) {
  340. int period = timeout;
  341. res = 1;
  342. while (seconds > period && res < 255) {
  343. res++;
  344. timeout <<= 1;
  345. if (timeout > rto_max)
  346. timeout = rto_max;
  347. period += timeout;
  348. }
  349. }
  350. return res;
  351. }
  352. /* Convert retransmits to seconds based on initial and max timeout */
  353. static int retrans_to_secs(u8 retrans, int timeout, int rto_max)
  354. {
  355. int period = 0;
  356. if (retrans > 0) {
  357. period = timeout;
  358. while (--retrans) {
  359. timeout <<= 1;
  360. if (timeout > rto_max)
  361. timeout = rto_max;
  362. period += timeout;
  363. }
  364. }
  365. return period;
  366. }
  367. static u64 tcp_compute_delivery_rate(const struct tcp_sock *tp)
  368. {
  369. u32 rate = READ_ONCE(tp->rate_delivered);
  370. u32 intv = READ_ONCE(tp->rate_interval_us);
  371. u64 rate64 = 0;
  372. if (rate && intv) {
  373. rate64 = (u64)rate * tp->mss_cache * USEC_PER_SEC;
  374. do_div(rate64, intv);
  375. }
  376. return rate64;
  377. }
  378. /* Address-family independent initialization for a tcp_sock.
  379. *
  380. * NOTE: A lot of things set to zero explicitly by call to
  381. * sk_alloc() so need not be done here.
  382. */
  383. void tcp_init_sock(struct sock *sk)
  384. {
  385. struct inet_connection_sock *icsk = inet_csk(sk);
  386. struct tcp_sock *tp = tcp_sk(sk);
  387. tp->out_of_order_queue = RB_ROOT;
  388. sk->tcp_rtx_queue = RB_ROOT;
  389. tcp_init_xmit_timers(sk);
  390. INIT_LIST_HEAD(&tp->tsq_node);
  391. INIT_LIST_HEAD(&tp->tsorted_sent_queue);
  392. icsk->icsk_rto = TCP_TIMEOUT_INIT;
  393. tp->mdev_us = jiffies_to_usecs(TCP_TIMEOUT_INIT);
  394. minmax_reset(&tp->rtt_min, tcp_jiffies32, ~0U);
  395. /* So many TCP implementations out there (incorrectly) count the
  396. * initial SYN frame in their delayed-ACK and congestion control
  397. * algorithms that we must have the following bandaid to talk
  398. * efficiently to them. -DaveM
  399. */
  400. tp->snd_cwnd = TCP_INIT_CWND;
  401. /* There's a bubble in the pipe until at least the first ACK. */
  402. tp->app_limited = ~0U;
  403. /* See draft-stevens-tcpca-spec-01 for discussion of the
  404. * initialization of these values.
  405. */
  406. tp->snd_ssthresh = TCP_INFINITE_SSTHRESH;
  407. tp->snd_cwnd_clamp = ~0;
  408. tp->mss_cache = TCP_MSS_DEFAULT;
  409. tp->reordering = sock_net(sk)->ipv4.sysctl_tcp_reordering;
  410. tcp_assign_congestion_control(sk);
  411. tp->tsoffset = 0;
  412. tp->rack.reo_wnd_steps = 1;
  413. sk->sk_state = TCP_CLOSE;
  414. sk->sk_write_space = sk_stream_write_space;
  415. sock_set_flag(sk, SOCK_USE_WRITE_QUEUE);
  416. icsk->icsk_sync_mss = tcp_sync_mss;
  417. sk->sk_sndbuf = sock_net(sk)->ipv4.sysctl_tcp_wmem[1];
  418. sk->sk_rcvbuf = sock_net(sk)->ipv4.sysctl_tcp_rmem[1];
  419. sk_sockets_allocated_inc(sk);
  420. sk->sk_route_forced_caps = NETIF_F_GSO;
  421. }
  422. EXPORT_SYMBOL(tcp_init_sock);
  423. void tcp_init_transfer(struct sock *sk, int bpf_op)
  424. {
  425. struct inet_connection_sock *icsk = inet_csk(sk);
  426. tcp_mtup_init(sk);
  427. icsk->icsk_af_ops->rebuild_header(sk);
  428. tcp_init_metrics(sk);
  429. tcp_call_bpf(sk, bpf_op, 0, NULL);
  430. tcp_init_congestion_control(sk);
  431. tcp_init_buffer_space(sk);
  432. }
  433. static void tcp_tx_timestamp(struct sock *sk, u16 tsflags)
  434. {
  435. struct sk_buff *skb = tcp_write_queue_tail(sk);
  436. if (tsflags && skb) {
  437. struct skb_shared_info *shinfo = skb_shinfo(skb);
  438. struct tcp_skb_cb *tcb = TCP_SKB_CB(skb);
  439. sock_tx_timestamp(sk, tsflags, &shinfo->tx_flags);
  440. if (tsflags & SOF_TIMESTAMPING_TX_ACK)
  441. tcb->txstamp_ack = 1;
  442. if (tsflags & SOF_TIMESTAMPING_TX_RECORD_MASK)
  443. shinfo->tskey = TCP_SKB_CB(skb)->seq + skb->len - 1;
  444. }
  445. }
  446. static inline bool tcp_stream_is_readable(const struct tcp_sock *tp,
  447. int target, struct sock *sk)
  448. {
  449. return (tp->rcv_nxt - tp->copied_seq >= target) ||
  450. (sk->sk_prot->stream_memory_read ?
  451. sk->sk_prot->stream_memory_read(sk) : false);
  452. }
  453. /*
  454. * Wait for a TCP event.
  455. *
  456. * Note that we don't need to lock the socket, as the upper poll layers
  457. * take care of normal races (between the test and the event) and we don't
  458. * go look at any of the socket buffers directly.
  459. */
  460. __poll_t tcp_poll(struct file *file, struct socket *sock, poll_table *wait)
  461. {
  462. __poll_t mask;
  463. struct sock *sk = sock->sk;
  464. const struct tcp_sock *tp = tcp_sk(sk);
  465. int state;
  466. sock_poll_wait(file, sk_sleep(sk), wait);
  467. state = inet_sk_state_load(sk);
  468. if (state == TCP_LISTEN)
  469. return inet_csk_listen_poll(sk);
  470. /* Socket is not locked. We are protected from async events
  471. * by poll logic and correct handling of state changes
  472. * made by other threads is impossible in any case.
  473. */
  474. mask = 0;
  475. /*
  476. * EPOLLHUP is certainly not done right. But poll() doesn't
  477. * have a notion of HUP in just one direction, and for a
  478. * socket the read side is more interesting.
  479. *
  480. * Some poll() documentation says that EPOLLHUP is incompatible
  481. * with the EPOLLOUT/POLLWR flags, so somebody should check this
  482. * all. But careful, it tends to be safer to return too many
  483. * bits than too few, and you can easily break real applications
  484. * if you don't tell them that something has hung up!
  485. *
  486. * Check-me.
  487. *
  488. * Check number 1. EPOLLHUP is _UNMASKABLE_ event (see UNIX98 and
  489. * our fs/select.c). It means that after we received EOF,
  490. * poll always returns immediately, making impossible poll() on write()
  491. * in state CLOSE_WAIT. One solution is evident --- to set EPOLLHUP
  492. * if and only if shutdown has been made in both directions.
  493. * Actually, it is interesting to look how Solaris and DUX
  494. * solve this dilemma. I would prefer, if EPOLLHUP were maskable,
  495. * then we could set it on SND_SHUTDOWN. BTW examples given
  496. * in Stevens' books assume exactly this behaviour, it explains
  497. * why EPOLLHUP is incompatible with EPOLLOUT. --ANK
  498. *
  499. * NOTE. Check for TCP_CLOSE is added. The goal is to prevent
  500. * blocking on fresh not-connected or disconnected socket. --ANK
  501. */
  502. if (sk->sk_shutdown == SHUTDOWN_MASK || state == TCP_CLOSE)
  503. mask |= EPOLLHUP;
  504. if (sk->sk_shutdown & RCV_SHUTDOWN)
  505. mask |= EPOLLIN | EPOLLRDNORM | EPOLLRDHUP;
  506. /* Connected or passive Fast Open socket? */
  507. if (state != TCP_SYN_SENT &&
  508. (state != TCP_SYN_RECV || tp->fastopen_rsk)) {
  509. int target = sock_rcvlowat(sk, 0, INT_MAX);
  510. if (tp->urg_seq == tp->copied_seq &&
  511. !sock_flag(sk, SOCK_URGINLINE) &&
  512. tp->urg_data)
  513. target++;
  514. if (tcp_stream_is_readable(tp, target, sk))
  515. mask |= EPOLLIN | EPOLLRDNORM;
  516. if (!(sk->sk_shutdown & SEND_SHUTDOWN)) {
  517. if (sk_stream_is_writeable(sk)) {
  518. mask |= EPOLLOUT | EPOLLWRNORM;
  519. } else { /* send SIGIO later */
  520. sk_set_bit(SOCKWQ_ASYNC_NOSPACE, sk);
  521. set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
  522. /* Race breaker. If space is freed after
  523. * wspace test but before the flags are set,
  524. * IO signal will be lost. Memory barrier
  525. * pairs with the input side.
  526. */
  527. smp_mb__after_atomic();
  528. if (sk_stream_is_writeable(sk))
  529. mask |= EPOLLOUT | EPOLLWRNORM;
  530. }
  531. } else
  532. mask |= EPOLLOUT | EPOLLWRNORM;
  533. if (tp->urg_data & TCP_URG_VALID)
  534. mask |= EPOLLPRI;
  535. } else if (state == TCP_SYN_SENT && inet_sk(sk)->defer_connect) {
  536. /* Active TCP fastopen socket with defer_connect
  537. * Return EPOLLOUT so application can call write()
  538. * in order for kernel to generate SYN+data
  539. */
  540. mask |= EPOLLOUT | EPOLLWRNORM;
  541. }
  542. /* This barrier is coupled with smp_wmb() in tcp_reset() */
  543. smp_rmb();
  544. if (sk->sk_err || !skb_queue_empty(&sk->sk_error_queue))
  545. mask |= EPOLLERR;
  546. return mask;
  547. }
  548. EXPORT_SYMBOL(tcp_poll);
  549. int tcp_ioctl(struct sock *sk, int cmd, unsigned long arg)
  550. {
  551. struct tcp_sock *tp = tcp_sk(sk);
  552. int answ;
  553. bool slow;
  554. switch (cmd) {
  555. case SIOCINQ:
  556. if (sk->sk_state == TCP_LISTEN)
  557. return -EINVAL;
  558. slow = lock_sock_fast(sk);
  559. answ = tcp_inq(sk);
  560. unlock_sock_fast(sk, slow);
  561. break;
  562. case SIOCATMARK:
  563. answ = tp->urg_data && tp->urg_seq == tp->copied_seq;
  564. break;
  565. case SIOCOUTQ:
  566. if (sk->sk_state == TCP_LISTEN)
  567. return -EINVAL;
  568. if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV))
  569. answ = 0;
  570. else
  571. answ = tp->write_seq - tp->snd_una;
  572. break;
  573. case SIOCOUTQNSD:
  574. if (sk->sk_state == TCP_LISTEN)
  575. return -EINVAL;
  576. if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV))
  577. answ = 0;
  578. else
  579. answ = tp->write_seq - tp->snd_nxt;
  580. break;
  581. default:
  582. return -ENOIOCTLCMD;
  583. }
  584. return put_user(answ, (int __user *)arg);
  585. }
  586. EXPORT_SYMBOL(tcp_ioctl);
  587. static inline void tcp_mark_push(struct tcp_sock *tp, struct sk_buff *skb)
  588. {
  589. TCP_SKB_CB(skb)->tcp_flags |= TCPHDR_PSH;
  590. tp->pushed_seq = tp->write_seq;
  591. }
  592. static inline bool forced_push(const struct tcp_sock *tp)
  593. {
  594. return after(tp->write_seq, tp->pushed_seq + (tp->max_window >> 1));
  595. }
  596. static void skb_entail(struct sock *sk, struct sk_buff *skb)
  597. {
  598. struct tcp_sock *tp = tcp_sk(sk);
  599. struct tcp_skb_cb *tcb = TCP_SKB_CB(skb);
  600. skb->csum = 0;
  601. tcb->seq = tcb->end_seq = tp->write_seq;
  602. tcb->tcp_flags = TCPHDR_ACK;
  603. tcb->sacked = 0;
  604. __skb_header_release(skb);
  605. tcp_add_write_queue_tail(sk, skb);
  606. sk->sk_wmem_queued += skb->truesize;
  607. sk_mem_charge(sk, skb->truesize);
  608. if (tp->nonagle & TCP_NAGLE_PUSH)
  609. tp->nonagle &= ~TCP_NAGLE_PUSH;
  610. tcp_slow_start_after_idle_check(sk);
  611. }
  612. static inline void tcp_mark_urg(struct tcp_sock *tp, int flags)
  613. {
  614. if (flags & MSG_OOB)
  615. tp->snd_up = tp->write_seq;
  616. }
  617. /* If a not yet filled skb is pushed, do not send it if
  618. * we have data packets in Qdisc or NIC queues :
  619. * Because TX completion will happen shortly, it gives a chance
  620. * to coalesce future sendmsg() payload into this skb, without
  621. * need for a timer, and with no latency trade off.
  622. * As packets containing data payload have a bigger truesize
  623. * than pure acks (dataless) packets, the last checks prevent
  624. * autocorking if we only have an ACK in Qdisc/NIC queues,
  625. * or if TX completion was delayed after we processed ACK packet.
  626. */
  627. static bool tcp_should_autocork(struct sock *sk, struct sk_buff *skb,
  628. int size_goal)
  629. {
  630. return skb->len < size_goal &&
  631. sock_net(sk)->ipv4.sysctl_tcp_autocorking &&
  632. !tcp_rtx_queue_empty(sk) &&
  633. refcount_read(&sk->sk_wmem_alloc) > skb->truesize;
  634. }
  635. static void tcp_push(struct sock *sk, int flags, int mss_now,
  636. int nonagle, int size_goal)
  637. {
  638. struct tcp_sock *tp = tcp_sk(sk);
  639. struct sk_buff *skb;
  640. skb = tcp_write_queue_tail(sk);
  641. if (!skb)
  642. return;
  643. if (!(flags & MSG_MORE) || forced_push(tp))
  644. tcp_mark_push(tp, skb);
  645. tcp_mark_urg(tp, flags);
  646. if (tcp_should_autocork(sk, skb, size_goal)) {
  647. /* avoid atomic op if TSQ_THROTTLED bit is already set */
  648. if (!test_bit(TSQ_THROTTLED, &sk->sk_tsq_flags)) {
  649. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPAUTOCORKING);
  650. set_bit(TSQ_THROTTLED, &sk->sk_tsq_flags);
  651. }
  652. /* It is possible TX completion already happened
  653. * before we set TSQ_THROTTLED.
  654. */
  655. if (refcount_read(&sk->sk_wmem_alloc) > skb->truesize)
  656. return;
  657. }
  658. if (flags & MSG_MORE)
  659. nonagle = TCP_NAGLE_CORK;
  660. __tcp_push_pending_frames(sk, mss_now, nonagle);
  661. }
  662. static int tcp_splice_data_recv(read_descriptor_t *rd_desc, struct sk_buff *skb,
  663. unsigned int offset, size_t len)
  664. {
  665. struct tcp_splice_state *tss = rd_desc->arg.data;
  666. int ret;
  667. ret = skb_splice_bits(skb, skb->sk, offset, tss->pipe,
  668. min(rd_desc->count, len), tss->flags);
  669. if (ret > 0)
  670. rd_desc->count -= ret;
  671. return ret;
  672. }
  673. static int __tcp_splice_read(struct sock *sk, struct tcp_splice_state *tss)
  674. {
  675. /* Store TCP splice context information in read_descriptor_t. */
  676. read_descriptor_t rd_desc = {
  677. .arg.data = tss,
  678. .count = tss->len,
  679. };
  680. return tcp_read_sock(sk, &rd_desc, tcp_splice_data_recv);
  681. }
  682. /**
  683. * tcp_splice_read - splice data from TCP socket to a pipe
  684. * @sock: socket to splice from
  685. * @ppos: position (not valid)
  686. * @pipe: pipe to splice to
  687. * @len: number of bytes to splice
  688. * @flags: splice modifier flags
  689. *
  690. * Description:
  691. * Will read pages from given socket and fill them into a pipe.
  692. *
  693. **/
  694. ssize_t tcp_splice_read(struct socket *sock, loff_t *ppos,
  695. struct pipe_inode_info *pipe, size_t len,
  696. unsigned int flags)
  697. {
  698. struct sock *sk = sock->sk;
  699. struct tcp_splice_state tss = {
  700. .pipe = pipe,
  701. .len = len,
  702. .flags = flags,
  703. };
  704. long timeo;
  705. ssize_t spliced;
  706. int ret;
  707. sock_rps_record_flow(sk);
  708. /*
  709. * We can't seek on a socket input
  710. */
  711. if (unlikely(*ppos))
  712. return -ESPIPE;
  713. ret = spliced = 0;
  714. lock_sock(sk);
  715. timeo = sock_rcvtimeo(sk, sock->file->f_flags & O_NONBLOCK);
  716. while (tss.len) {
  717. ret = __tcp_splice_read(sk, &tss);
  718. if (ret < 0)
  719. break;
  720. else if (!ret) {
  721. if (spliced)
  722. break;
  723. if (sock_flag(sk, SOCK_DONE))
  724. break;
  725. if (sk->sk_err) {
  726. ret = sock_error(sk);
  727. break;
  728. }
  729. if (sk->sk_shutdown & RCV_SHUTDOWN)
  730. break;
  731. if (sk->sk_state == TCP_CLOSE) {
  732. /*
  733. * This occurs when user tries to read
  734. * from never connected socket.
  735. */
  736. if (!sock_flag(sk, SOCK_DONE))
  737. ret = -ENOTCONN;
  738. break;
  739. }
  740. if (!timeo) {
  741. ret = -EAGAIN;
  742. break;
  743. }
  744. /* if __tcp_splice_read() got nothing while we have
  745. * an skb in receive queue, we do not want to loop.
  746. * This might happen with URG data.
  747. */
  748. if (!skb_queue_empty(&sk->sk_receive_queue))
  749. break;
  750. sk_wait_data(sk, &timeo, NULL);
  751. if (signal_pending(current)) {
  752. ret = sock_intr_errno(timeo);
  753. break;
  754. }
  755. continue;
  756. }
  757. tss.len -= ret;
  758. spliced += ret;
  759. if (!timeo)
  760. break;
  761. release_sock(sk);
  762. lock_sock(sk);
  763. if (sk->sk_err || sk->sk_state == TCP_CLOSE ||
  764. (sk->sk_shutdown & RCV_SHUTDOWN) ||
  765. signal_pending(current))
  766. break;
  767. }
  768. release_sock(sk);
  769. if (spliced)
  770. return spliced;
  771. return ret;
  772. }
  773. EXPORT_SYMBOL(tcp_splice_read);
  774. struct sk_buff *sk_stream_alloc_skb(struct sock *sk, int size, gfp_t gfp,
  775. bool force_schedule)
  776. {
  777. struct sk_buff *skb;
  778. /* The TCP header must be at least 32-bit aligned. */
  779. size = ALIGN(size, 4);
  780. if (unlikely(tcp_under_memory_pressure(sk)))
  781. sk_mem_reclaim_partial(sk);
  782. skb = alloc_skb_fclone(size + sk->sk_prot->max_header, gfp);
  783. if (likely(skb)) {
  784. bool mem_scheduled;
  785. if (force_schedule) {
  786. mem_scheduled = true;
  787. sk_forced_mem_schedule(sk, skb->truesize);
  788. } else {
  789. mem_scheduled = sk_wmem_schedule(sk, skb->truesize);
  790. }
  791. if (likely(mem_scheduled)) {
  792. skb_reserve(skb, sk->sk_prot->max_header);
  793. /*
  794. * Make sure that we have exactly size bytes
  795. * available to the caller, no more, no less.
  796. */
  797. skb->reserved_tailroom = skb->end - skb->tail - size;
  798. INIT_LIST_HEAD(&skb->tcp_tsorted_anchor);
  799. return skb;
  800. }
  801. __kfree_skb(skb);
  802. } else {
  803. sk->sk_prot->enter_memory_pressure(sk);
  804. sk_stream_moderate_sndbuf(sk);
  805. }
  806. return NULL;
  807. }
  808. static unsigned int tcp_xmit_size_goal(struct sock *sk, u32 mss_now,
  809. int large_allowed)
  810. {
  811. struct tcp_sock *tp = tcp_sk(sk);
  812. u32 new_size_goal, size_goal;
  813. if (!large_allowed)
  814. return mss_now;
  815. /* Note : tcp_tso_autosize() will eventually split this later */
  816. new_size_goal = sk->sk_gso_max_size - 1 - MAX_TCP_HEADER;
  817. new_size_goal = tcp_bound_to_half_wnd(tp, new_size_goal);
  818. /* We try hard to avoid divides here */
  819. size_goal = tp->gso_segs * mss_now;
  820. if (unlikely(new_size_goal < size_goal ||
  821. new_size_goal >= size_goal + mss_now)) {
  822. tp->gso_segs = min_t(u16, new_size_goal / mss_now,
  823. sk->sk_gso_max_segs);
  824. size_goal = tp->gso_segs * mss_now;
  825. }
  826. return max(size_goal, mss_now);
  827. }
  828. static int tcp_send_mss(struct sock *sk, int *size_goal, int flags)
  829. {
  830. int mss_now;
  831. mss_now = tcp_current_mss(sk);
  832. *size_goal = tcp_xmit_size_goal(sk, mss_now, !(flags & MSG_OOB));
  833. return mss_now;
  834. }
  835. ssize_t do_tcp_sendpages(struct sock *sk, struct page *page, int offset,
  836. size_t size, int flags)
  837. {
  838. struct tcp_sock *tp = tcp_sk(sk);
  839. int mss_now, size_goal;
  840. int err;
  841. ssize_t copied;
  842. long timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT);
  843. /* Wait for a connection to finish. One exception is TCP Fast Open
  844. * (passive side) where data is allowed to be sent before a connection
  845. * is fully established.
  846. */
  847. if (((1 << sk->sk_state) & ~(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT)) &&
  848. !tcp_passive_fastopen(sk)) {
  849. err = sk_stream_wait_connect(sk, &timeo);
  850. if (err != 0)
  851. goto out_err;
  852. }
  853. sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk);
  854. mss_now = tcp_send_mss(sk, &size_goal, flags);
  855. copied = 0;
  856. err = -EPIPE;
  857. if (sk->sk_err || (sk->sk_shutdown & SEND_SHUTDOWN))
  858. goto out_err;
  859. while (size > 0) {
  860. struct sk_buff *skb = tcp_write_queue_tail(sk);
  861. int copy, i;
  862. bool can_coalesce;
  863. if (!skb || (copy = size_goal - skb->len) <= 0 ||
  864. !tcp_skb_can_collapse_to(skb)) {
  865. new_segment:
  866. if (!sk_stream_memory_free(sk))
  867. goto wait_for_sndbuf;
  868. skb = sk_stream_alloc_skb(sk, 0, sk->sk_allocation,
  869. tcp_rtx_and_write_queues_empty(sk));
  870. if (!skb)
  871. goto wait_for_memory;
  872. skb_entail(sk, skb);
  873. copy = size_goal;
  874. }
  875. if (copy > size)
  876. copy = size;
  877. i = skb_shinfo(skb)->nr_frags;
  878. can_coalesce = skb_can_coalesce(skb, i, page, offset);
  879. if (!can_coalesce && i >= sysctl_max_skb_frags) {
  880. tcp_mark_push(tp, skb);
  881. goto new_segment;
  882. }
  883. if (!sk_wmem_schedule(sk, copy))
  884. goto wait_for_memory;
  885. if (can_coalesce) {
  886. skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy);
  887. } else {
  888. get_page(page);
  889. skb_fill_page_desc(skb, i, page, offset, copy);
  890. }
  891. if (!(flags & MSG_NO_SHARED_FRAGS))
  892. skb_shinfo(skb)->tx_flags |= SKBTX_SHARED_FRAG;
  893. skb->len += copy;
  894. skb->data_len += copy;
  895. skb->truesize += copy;
  896. sk->sk_wmem_queued += copy;
  897. sk_mem_charge(sk, copy);
  898. skb->ip_summed = CHECKSUM_PARTIAL;
  899. tp->write_seq += copy;
  900. TCP_SKB_CB(skb)->end_seq += copy;
  901. tcp_skb_pcount_set(skb, 0);
  902. if (!copied)
  903. TCP_SKB_CB(skb)->tcp_flags &= ~TCPHDR_PSH;
  904. copied += copy;
  905. offset += copy;
  906. size -= copy;
  907. if (!size)
  908. goto out;
  909. if (skb->len < size_goal || (flags & MSG_OOB))
  910. continue;
  911. if (forced_push(tp)) {
  912. tcp_mark_push(tp, skb);
  913. __tcp_push_pending_frames(sk, mss_now, TCP_NAGLE_PUSH);
  914. } else if (skb == tcp_send_head(sk))
  915. tcp_push_one(sk, mss_now);
  916. continue;
  917. wait_for_sndbuf:
  918. set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
  919. wait_for_memory:
  920. tcp_push(sk, flags & ~MSG_MORE, mss_now,
  921. TCP_NAGLE_PUSH, size_goal);
  922. err = sk_stream_wait_memory(sk, &timeo);
  923. if (err != 0)
  924. goto do_error;
  925. mss_now = tcp_send_mss(sk, &size_goal, flags);
  926. }
  927. out:
  928. if (copied) {
  929. tcp_tx_timestamp(sk, sk->sk_tsflags);
  930. if (!(flags & MSG_SENDPAGE_NOTLAST))
  931. tcp_push(sk, flags, mss_now, tp->nonagle, size_goal);
  932. }
  933. return copied;
  934. do_error:
  935. if (copied)
  936. goto out;
  937. out_err:
  938. /* make sure we wake any epoll edge trigger waiter */
  939. if (unlikely(skb_queue_len(&sk->sk_write_queue) == 0 &&
  940. err == -EAGAIN)) {
  941. sk->sk_write_space(sk);
  942. tcp_chrono_stop(sk, TCP_CHRONO_SNDBUF_LIMITED);
  943. }
  944. return sk_stream_error(sk, flags, err);
  945. }
  946. EXPORT_SYMBOL_GPL(do_tcp_sendpages);
  947. int tcp_sendpage_locked(struct sock *sk, struct page *page, int offset,
  948. size_t size, int flags)
  949. {
  950. if (!(sk->sk_route_caps & NETIF_F_SG))
  951. return sock_no_sendpage_locked(sk, page, offset, size, flags);
  952. tcp_rate_check_app_limited(sk); /* is sending application-limited? */
  953. return do_tcp_sendpages(sk, page, offset, size, flags);
  954. }
  955. EXPORT_SYMBOL_GPL(tcp_sendpage_locked);
  956. int tcp_sendpage(struct sock *sk, struct page *page, int offset,
  957. size_t size, int flags)
  958. {
  959. int ret;
  960. lock_sock(sk);
  961. ret = tcp_sendpage_locked(sk, page, offset, size, flags);
  962. release_sock(sk);
  963. return ret;
  964. }
  965. EXPORT_SYMBOL(tcp_sendpage);
  966. /* Do not bother using a page frag for very small frames.
  967. * But use this heuristic only for the first skb in write queue.
  968. *
  969. * Having no payload in skb->head allows better SACK shifting
  970. * in tcp_shift_skb_data(), reducing sack/rack overhead, because
  971. * write queue has less skbs.
  972. * Each skb can hold up to MAX_SKB_FRAGS * 32Kbytes, or ~0.5 MB.
  973. * This also speeds up tso_fragment(), since it wont fallback
  974. * to tcp_fragment().
  975. */
  976. static int linear_payload_sz(bool first_skb)
  977. {
  978. if (first_skb)
  979. return SKB_WITH_OVERHEAD(2048 - MAX_TCP_HEADER);
  980. return 0;
  981. }
  982. static int select_size(bool first_skb, bool zc)
  983. {
  984. if (zc)
  985. return 0;
  986. return linear_payload_sz(first_skb);
  987. }
  988. void tcp_free_fastopen_req(struct tcp_sock *tp)
  989. {
  990. if (tp->fastopen_req) {
  991. kfree(tp->fastopen_req);
  992. tp->fastopen_req = NULL;
  993. }
  994. }
  995. static int tcp_sendmsg_fastopen(struct sock *sk, struct msghdr *msg,
  996. int *copied, size_t size)
  997. {
  998. struct tcp_sock *tp = tcp_sk(sk);
  999. struct inet_sock *inet = inet_sk(sk);
  1000. struct sockaddr *uaddr = msg->msg_name;
  1001. int err, flags;
  1002. if (!(sock_net(sk)->ipv4.sysctl_tcp_fastopen & TFO_CLIENT_ENABLE) ||
  1003. (uaddr && msg->msg_namelen >= sizeof(uaddr->sa_family) &&
  1004. uaddr->sa_family == AF_UNSPEC))
  1005. return -EOPNOTSUPP;
  1006. if (tp->fastopen_req)
  1007. return -EALREADY; /* Another Fast Open is in progress */
  1008. tp->fastopen_req = kzalloc(sizeof(struct tcp_fastopen_request),
  1009. sk->sk_allocation);
  1010. if (unlikely(!tp->fastopen_req))
  1011. return -ENOBUFS;
  1012. tp->fastopen_req->data = msg;
  1013. tp->fastopen_req->size = size;
  1014. if (inet->defer_connect) {
  1015. err = tcp_connect(sk);
  1016. /* Same failure procedure as in tcp_v4/6_connect */
  1017. if (err) {
  1018. tcp_set_state(sk, TCP_CLOSE);
  1019. inet->inet_dport = 0;
  1020. sk->sk_route_caps = 0;
  1021. }
  1022. }
  1023. flags = (msg->msg_flags & MSG_DONTWAIT) ? O_NONBLOCK : 0;
  1024. err = __inet_stream_connect(sk->sk_socket, uaddr,
  1025. msg->msg_namelen, flags, 1);
  1026. /* fastopen_req could already be freed in __inet_stream_connect
  1027. * if the connection times out or gets rst
  1028. */
  1029. if (tp->fastopen_req) {
  1030. *copied = tp->fastopen_req->copied;
  1031. tcp_free_fastopen_req(tp);
  1032. inet->defer_connect = 0;
  1033. }
  1034. return err;
  1035. }
  1036. int tcp_sendmsg_locked(struct sock *sk, struct msghdr *msg, size_t size)
  1037. {
  1038. struct tcp_sock *tp = tcp_sk(sk);
  1039. struct ubuf_info *uarg = NULL;
  1040. struct sk_buff *skb;
  1041. struct sockcm_cookie sockc;
  1042. int flags, err, copied = 0;
  1043. int mss_now = 0, size_goal, copied_syn = 0;
  1044. bool process_backlog = false;
  1045. bool zc = false;
  1046. long timeo;
  1047. flags = msg->msg_flags;
  1048. if (flags & MSG_ZEROCOPY && size) {
  1049. if (sk->sk_state != TCP_ESTABLISHED) {
  1050. err = -EINVAL;
  1051. goto out_err;
  1052. }
  1053. skb = tcp_write_queue_tail(sk);
  1054. uarg = sock_zerocopy_realloc(sk, size, skb_zcopy(skb));
  1055. if (!uarg) {
  1056. err = -ENOBUFS;
  1057. goto out_err;
  1058. }
  1059. zc = sk->sk_route_caps & NETIF_F_SG;
  1060. if (!zc)
  1061. uarg->zerocopy = 0;
  1062. }
  1063. if (unlikely(flags & MSG_FASTOPEN || inet_sk(sk)->defer_connect) &&
  1064. !tp->repair) {
  1065. err = tcp_sendmsg_fastopen(sk, msg, &copied_syn, size);
  1066. if (err == -EINPROGRESS && copied_syn > 0)
  1067. goto out;
  1068. else if (err)
  1069. goto out_err;
  1070. }
  1071. timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT);
  1072. tcp_rate_check_app_limited(sk); /* is sending application-limited? */
  1073. /* Wait for a connection to finish. One exception is TCP Fast Open
  1074. * (passive side) where data is allowed to be sent before a connection
  1075. * is fully established.
  1076. */
  1077. if (((1 << sk->sk_state) & ~(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT)) &&
  1078. !tcp_passive_fastopen(sk)) {
  1079. err = sk_stream_wait_connect(sk, &timeo);
  1080. if (err != 0)
  1081. goto do_error;
  1082. }
  1083. if (unlikely(tp->repair)) {
  1084. if (tp->repair_queue == TCP_RECV_QUEUE) {
  1085. copied = tcp_send_rcvq(sk, msg, size);
  1086. goto out_nopush;
  1087. }
  1088. err = -EINVAL;
  1089. if (tp->repair_queue == TCP_NO_QUEUE)
  1090. goto out_err;
  1091. /* 'common' sending to sendq */
  1092. }
  1093. sockc.tsflags = sk->sk_tsflags;
  1094. if (msg->msg_controllen) {
  1095. err = sock_cmsg_send(sk, msg, &sockc);
  1096. if (unlikely(err)) {
  1097. err = -EINVAL;
  1098. goto out_err;
  1099. }
  1100. }
  1101. /* This should be in poll */
  1102. sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk);
  1103. /* Ok commence sending. */
  1104. copied = 0;
  1105. restart:
  1106. mss_now = tcp_send_mss(sk, &size_goal, flags);
  1107. err = -EPIPE;
  1108. if (sk->sk_err || (sk->sk_shutdown & SEND_SHUTDOWN))
  1109. goto do_error;
  1110. while (msg_data_left(msg)) {
  1111. int copy = 0;
  1112. skb = tcp_write_queue_tail(sk);
  1113. if (skb)
  1114. copy = size_goal - skb->len;
  1115. if (copy <= 0 || !tcp_skb_can_collapse_to(skb)) {
  1116. bool first_skb;
  1117. int linear;
  1118. new_segment:
  1119. /* Allocate new segment. If the interface is SG,
  1120. * allocate skb fitting to single page.
  1121. */
  1122. if (!sk_stream_memory_free(sk))
  1123. goto wait_for_sndbuf;
  1124. if (process_backlog && sk_flush_backlog(sk)) {
  1125. process_backlog = false;
  1126. goto restart;
  1127. }
  1128. first_skb = tcp_rtx_and_write_queues_empty(sk);
  1129. linear = select_size(first_skb, zc);
  1130. skb = sk_stream_alloc_skb(sk, linear, sk->sk_allocation,
  1131. first_skb);
  1132. if (!skb)
  1133. goto wait_for_memory;
  1134. process_backlog = true;
  1135. skb->ip_summed = CHECKSUM_PARTIAL;
  1136. skb_entail(sk, skb);
  1137. copy = size_goal;
  1138. /* All packets are restored as if they have
  1139. * already been sent. skb_mstamp isn't set to
  1140. * avoid wrong rtt estimation.
  1141. */
  1142. if (tp->repair)
  1143. TCP_SKB_CB(skb)->sacked |= TCPCB_REPAIRED;
  1144. }
  1145. /* Try to append data to the end of skb. */
  1146. if (copy > msg_data_left(msg))
  1147. copy = msg_data_left(msg);
  1148. /* Where to copy to? */
  1149. if (skb_availroom(skb) > 0 && !zc) {
  1150. /* We have some space in skb head. Superb! */
  1151. copy = min_t(int, copy, skb_availroom(skb));
  1152. err = skb_add_data_nocache(sk, skb, &msg->msg_iter, copy);
  1153. if (err)
  1154. goto do_fault;
  1155. } else if (!zc) {
  1156. bool merge = true;
  1157. int i = skb_shinfo(skb)->nr_frags;
  1158. struct page_frag *pfrag = sk_page_frag(sk);
  1159. if (!sk_page_frag_refill(sk, pfrag))
  1160. goto wait_for_memory;
  1161. if (!skb_can_coalesce(skb, i, pfrag->page,
  1162. pfrag->offset)) {
  1163. if (i >= sysctl_max_skb_frags) {
  1164. tcp_mark_push(tp, skb);
  1165. goto new_segment;
  1166. }
  1167. merge = false;
  1168. }
  1169. copy = min_t(int, copy, pfrag->size - pfrag->offset);
  1170. if (!sk_wmem_schedule(sk, copy))
  1171. goto wait_for_memory;
  1172. err = skb_copy_to_page_nocache(sk, &msg->msg_iter, skb,
  1173. pfrag->page,
  1174. pfrag->offset,
  1175. copy);
  1176. if (err)
  1177. goto do_error;
  1178. /* Update the skb. */
  1179. if (merge) {
  1180. skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy);
  1181. } else {
  1182. skb_fill_page_desc(skb, i, pfrag->page,
  1183. pfrag->offset, copy);
  1184. page_ref_inc(pfrag->page);
  1185. }
  1186. pfrag->offset += copy;
  1187. } else {
  1188. err = skb_zerocopy_iter_stream(sk, skb, msg, copy, uarg);
  1189. if (err == -EMSGSIZE || err == -EEXIST) {
  1190. tcp_mark_push(tp, skb);
  1191. goto new_segment;
  1192. }
  1193. if (err < 0)
  1194. goto do_error;
  1195. copy = err;
  1196. }
  1197. if (!copied)
  1198. TCP_SKB_CB(skb)->tcp_flags &= ~TCPHDR_PSH;
  1199. tp->write_seq += copy;
  1200. TCP_SKB_CB(skb)->end_seq += copy;
  1201. tcp_skb_pcount_set(skb, 0);
  1202. copied += copy;
  1203. if (!msg_data_left(msg)) {
  1204. if (unlikely(flags & MSG_EOR))
  1205. TCP_SKB_CB(skb)->eor = 1;
  1206. goto out;
  1207. }
  1208. if (skb->len < size_goal || (flags & MSG_OOB) || unlikely(tp->repair))
  1209. continue;
  1210. if (forced_push(tp)) {
  1211. tcp_mark_push(tp, skb);
  1212. __tcp_push_pending_frames(sk, mss_now, TCP_NAGLE_PUSH);
  1213. } else if (skb == tcp_send_head(sk))
  1214. tcp_push_one(sk, mss_now);
  1215. continue;
  1216. wait_for_sndbuf:
  1217. set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
  1218. wait_for_memory:
  1219. if (copied)
  1220. tcp_push(sk, flags & ~MSG_MORE, mss_now,
  1221. TCP_NAGLE_PUSH, size_goal);
  1222. err = sk_stream_wait_memory(sk, &timeo);
  1223. if (err != 0)
  1224. goto do_error;
  1225. mss_now = tcp_send_mss(sk, &size_goal, flags);
  1226. }
  1227. out:
  1228. if (copied) {
  1229. tcp_tx_timestamp(sk, sockc.tsflags);
  1230. tcp_push(sk, flags, mss_now, tp->nonagle, size_goal);
  1231. }
  1232. out_nopush:
  1233. sock_zerocopy_put(uarg);
  1234. return copied + copied_syn;
  1235. do_fault:
  1236. if (!skb->len) {
  1237. tcp_unlink_write_queue(skb, sk);
  1238. /* It is the one place in all of TCP, except connection
  1239. * reset, where we can be unlinking the send_head.
  1240. */
  1241. tcp_check_send_head(sk, skb);
  1242. sk_wmem_free_skb(sk, skb);
  1243. }
  1244. do_error:
  1245. if (copied + copied_syn)
  1246. goto out;
  1247. out_err:
  1248. sock_zerocopy_put_abort(uarg);
  1249. err = sk_stream_error(sk, flags, err);
  1250. /* make sure we wake any epoll edge trigger waiter */
  1251. if (unlikely(skb_queue_len(&sk->sk_write_queue) == 0 &&
  1252. err == -EAGAIN)) {
  1253. sk->sk_write_space(sk);
  1254. tcp_chrono_stop(sk, TCP_CHRONO_SNDBUF_LIMITED);
  1255. }
  1256. return err;
  1257. }
  1258. EXPORT_SYMBOL_GPL(tcp_sendmsg_locked);
  1259. int tcp_sendmsg(struct sock *sk, struct msghdr *msg, size_t size)
  1260. {
  1261. int ret;
  1262. lock_sock(sk);
  1263. ret = tcp_sendmsg_locked(sk, msg, size);
  1264. release_sock(sk);
  1265. return ret;
  1266. }
  1267. EXPORT_SYMBOL(tcp_sendmsg);
  1268. /*
  1269. * Handle reading urgent data. BSD has very simple semantics for
  1270. * this, no blocking and very strange errors 8)
  1271. */
  1272. static int tcp_recv_urg(struct sock *sk, struct msghdr *msg, int len, int flags)
  1273. {
  1274. struct tcp_sock *tp = tcp_sk(sk);
  1275. /* No URG data to read. */
  1276. if (sock_flag(sk, SOCK_URGINLINE) || !tp->urg_data ||
  1277. tp->urg_data == TCP_URG_READ)
  1278. return -EINVAL; /* Yes this is right ! */
  1279. if (sk->sk_state == TCP_CLOSE && !sock_flag(sk, SOCK_DONE))
  1280. return -ENOTCONN;
  1281. if (tp->urg_data & TCP_URG_VALID) {
  1282. int err = 0;
  1283. char c = tp->urg_data;
  1284. if (!(flags & MSG_PEEK))
  1285. tp->urg_data = TCP_URG_READ;
  1286. /* Read urgent data. */
  1287. msg->msg_flags |= MSG_OOB;
  1288. if (len > 0) {
  1289. if (!(flags & MSG_TRUNC))
  1290. err = memcpy_to_msg(msg, &c, 1);
  1291. len = 1;
  1292. } else
  1293. msg->msg_flags |= MSG_TRUNC;
  1294. return err ? -EFAULT : len;
  1295. }
  1296. if (sk->sk_state == TCP_CLOSE || (sk->sk_shutdown & RCV_SHUTDOWN))
  1297. return 0;
  1298. /* Fixed the recv(..., MSG_OOB) behaviour. BSD docs and
  1299. * the available implementations agree in this case:
  1300. * this call should never block, independent of the
  1301. * blocking state of the socket.
  1302. * Mike <pall@rz.uni-karlsruhe.de>
  1303. */
  1304. return -EAGAIN;
  1305. }
  1306. static int tcp_peek_sndq(struct sock *sk, struct msghdr *msg, int len)
  1307. {
  1308. struct sk_buff *skb;
  1309. int copied = 0, err = 0;
  1310. /* XXX -- need to support SO_PEEK_OFF */
  1311. skb_rbtree_walk(skb, &sk->tcp_rtx_queue) {
  1312. err = skb_copy_datagram_msg(skb, 0, msg, skb->len);
  1313. if (err)
  1314. return err;
  1315. copied += skb->len;
  1316. }
  1317. skb_queue_walk(&sk->sk_write_queue, skb) {
  1318. err = skb_copy_datagram_msg(skb, 0, msg, skb->len);
  1319. if (err)
  1320. break;
  1321. copied += skb->len;
  1322. }
  1323. return err ?: copied;
  1324. }
  1325. /* Clean up the receive buffer for full frames taken by the user,
  1326. * then send an ACK if necessary. COPIED is the number of bytes
  1327. * tcp_recvmsg has given to the user so far, it speeds up the
  1328. * calculation of whether or not we must ACK for the sake of
  1329. * a window update.
  1330. */
  1331. static void tcp_cleanup_rbuf(struct sock *sk, int copied)
  1332. {
  1333. struct tcp_sock *tp = tcp_sk(sk);
  1334. bool time_to_ack = false;
  1335. struct sk_buff *skb = skb_peek(&sk->sk_receive_queue);
  1336. WARN(skb && !before(tp->copied_seq, TCP_SKB_CB(skb)->end_seq),
  1337. "cleanup rbuf bug: copied %X seq %X rcvnxt %X\n",
  1338. tp->copied_seq, TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt);
  1339. if (inet_csk_ack_scheduled(sk)) {
  1340. const struct inet_connection_sock *icsk = inet_csk(sk);
  1341. /* Delayed ACKs frequently hit locked sockets during bulk
  1342. * receive. */
  1343. if (icsk->icsk_ack.blocked ||
  1344. /* Once-per-two-segments ACK was not sent by tcp_input.c */
  1345. tp->rcv_nxt - tp->rcv_wup > icsk->icsk_ack.rcv_mss ||
  1346. /*
  1347. * If this read emptied read buffer, we send ACK, if
  1348. * connection is not bidirectional, user drained
  1349. * receive buffer and there was a small segment
  1350. * in queue.
  1351. */
  1352. (copied > 0 &&
  1353. ((icsk->icsk_ack.pending & ICSK_ACK_PUSHED2) ||
  1354. ((icsk->icsk_ack.pending & ICSK_ACK_PUSHED) &&
  1355. !icsk->icsk_ack.pingpong)) &&
  1356. !atomic_read(&sk->sk_rmem_alloc)))
  1357. time_to_ack = true;
  1358. }
  1359. /* We send an ACK if we can now advertise a non-zero window
  1360. * which has been raised "significantly".
  1361. *
  1362. * Even if window raised up to infinity, do not send window open ACK
  1363. * in states, where we will not receive more. It is useless.
  1364. */
  1365. if (copied > 0 && !time_to_ack && !(sk->sk_shutdown & RCV_SHUTDOWN)) {
  1366. __u32 rcv_window_now = tcp_receive_window(tp);
  1367. /* Optimize, __tcp_select_window() is not cheap. */
  1368. if (2*rcv_window_now <= tp->window_clamp) {
  1369. __u32 new_window = __tcp_select_window(sk);
  1370. /* Send ACK now, if this read freed lots of space
  1371. * in our buffer. Certainly, new_window is new window.
  1372. * We can advertise it now, if it is not less than current one.
  1373. * "Lots" means "at least twice" here.
  1374. */
  1375. if (new_window && new_window >= 2 * rcv_window_now)
  1376. time_to_ack = true;
  1377. }
  1378. }
  1379. if (time_to_ack)
  1380. tcp_send_ack(sk);
  1381. }
  1382. static struct sk_buff *tcp_recv_skb(struct sock *sk, u32 seq, u32 *off)
  1383. {
  1384. struct sk_buff *skb;
  1385. u32 offset;
  1386. while ((skb = skb_peek(&sk->sk_receive_queue)) != NULL) {
  1387. offset = seq - TCP_SKB_CB(skb)->seq;
  1388. if (unlikely(TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN)) {
  1389. pr_err_once("%s: found a SYN, please report !\n", __func__);
  1390. offset--;
  1391. }
  1392. if (offset < skb->len || (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)) {
  1393. *off = offset;
  1394. return skb;
  1395. }
  1396. /* This looks weird, but this can happen if TCP collapsing
  1397. * splitted a fat GRO packet, while we released socket lock
  1398. * in skb_splice_bits()
  1399. */
  1400. sk_eat_skb(sk, skb);
  1401. }
  1402. return NULL;
  1403. }
  1404. /*
  1405. * This routine provides an alternative to tcp_recvmsg() for routines
  1406. * that would like to handle copying from skbuffs directly in 'sendfile'
  1407. * fashion.
  1408. * Note:
  1409. * - It is assumed that the socket was locked by the caller.
  1410. * - The routine does not block.
  1411. * - At present, there is no support for reading OOB data
  1412. * or for 'peeking' the socket using this routine
  1413. * (although both would be easy to implement).
  1414. */
  1415. int tcp_read_sock(struct sock *sk, read_descriptor_t *desc,
  1416. sk_read_actor_t recv_actor)
  1417. {
  1418. struct sk_buff *skb;
  1419. struct tcp_sock *tp = tcp_sk(sk);
  1420. u32 seq = tp->copied_seq;
  1421. u32 offset;
  1422. int copied = 0;
  1423. if (sk->sk_state == TCP_LISTEN)
  1424. return -ENOTCONN;
  1425. while ((skb = tcp_recv_skb(sk, seq, &offset)) != NULL) {
  1426. if (offset < skb->len) {
  1427. int used;
  1428. size_t len;
  1429. len = skb->len - offset;
  1430. /* Stop reading if we hit a patch of urgent data */
  1431. if (tp->urg_data) {
  1432. u32 urg_offset = tp->urg_seq - seq;
  1433. if (urg_offset < len)
  1434. len = urg_offset;
  1435. if (!len)
  1436. break;
  1437. }
  1438. used = recv_actor(desc, skb, offset, len);
  1439. if (used <= 0) {
  1440. if (!copied)
  1441. copied = used;
  1442. break;
  1443. } else if (used <= len) {
  1444. seq += used;
  1445. copied += used;
  1446. offset += used;
  1447. }
  1448. /* If recv_actor drops the lock (e.g. TCP splice
  1449. * receive) the skb pointer might be invalid when
  1450. * getting here: tcp_collapse might have deleted it
  1451. * while aggregating skbs from the socket queue.
  1452. */
  1453. skb = tcp_recv_skb(sk, seq - 1, &offset);
  1454. if (!skb)
  1455. break;
  1456. /* TCP coalescing might have appended data to the skb.
  1457. * Try to splice more frags
  1458. */
  1459. if (offset + 1 != skb->len)
  1460. continue;
  1461. }
  1462. if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN) {
  1463. sk_eat_skb(sk, skb);
  1464. ++seq;
  1465. break;
  1466. }
  1467. sk_eat_skb(sk, skb);
  1468. if (!desc->count)
  1469. break;
  1470. tp->copied_seq = seq;
  1471. }
  1472. tp->copied_seq = seq;
  1473. tcp_rcv_space_adjust(sk);
  1474. /* Clean up data we have read: This will do ACK frames. */
  1475. if (copied > 0) {
  1476. tcp_recv_skb(sk, seq, &offset);
  1477. tcp_cleanup_rbuf(sk, copied);
  1478. }
  1479. return copied;
  1480. }
  1481. EXPORT_SYMBOL(tcp_read_sock);
  1482. int tcp_peek_len(struct socket *sock)
  1483. {
  1484. return tcp_inq(sock->sk);
  1485. }
  1486. EXPORT_SYMBOL(tcp_peek_len);
  1487. /* Make sure sk_rcvbuf is big enough to satisfy SO_RCVLOWAT hint */
  1488. int tcp_set_rcvlowat(struct sock *sk, int val)
  1489. {
  1490. int cap;
  1491. if (sk->sk_userlocks & SOCK_RCVBUF_LOCK)
  1492. cap = sk->sk_rcvbuf >> 1;
  1493. else
  1494. cap = sock_net(sk)->ipv4.sysctl_tcp_rmem[2] >> 1;
  1495. val = min(val, cap);
  1496. sk->sk_rcvlowat = val ? : 1;
  1497. /* Check if we need to signal EPOLLIN right now */
  1498. tcp_data_ready(sk);
  1499. if (sk->sk_userlocks & SOCK_RCVBUF_LOCK)
  1500. return 0;
  1501. val <<= 1;
  1502. if (val > sk->sk_rcvbuf) {
  1503. sk->sk_rcvbuf = val;
  1504. tcp_sk(sk)->window_clamp = tcp_win_from_space(sk, val);
  1505. }
  1506. return 0;
  1507. }
  1508. EXPORT_SYMBOL(tcp_set_rcvlowat);
  1509. #ifdef CONFIG_MMU
  1510. static const struct vm_operations_struct tcp_vm_ops = {
  1511. };
  1512. int tcp_mmap(struct file *file, struct socket *sock,
  1513. struct vm_area_struct *vma)
  1514. {
  1515. if (vma->vm_flags & (VM_WRITE | VM_EXEC))
  1516. return -EPERM;
  1517. vma->vm_flags &= ~(VM_MAYWRITE | VM_MAYEXEC);
  1518. /* Instruct vm_insert_page() to not down_read(mmap_sem) */
  1519. vma->vm_flags |= VM_MIXEDMAP;
  1520. vma->vm_ops = &tcp_vm_ops;
  1521. return 0;
  1522. }
  1523. EXPORT_SYMBOL(tcp_mmap);
  1524. static int tcp_zerocopy_receive(struct sock *sk,
  1525. struct tcp_zerocopy_receive *zc)
  1526. {
  1527. unsigned long address = (unsigned long)zc->address;
  1528. const skb_frag_t *frags = NULL;
  1529. u32 length = 0, seq, offset;
  1530. struct vm_area_struct *vma;
  1531. struct sk_buff *skb = NULL;
  1532. struct tcp_sock *tp;
  1533. int ret;
  1534. if (address & (PAGE_SIZE - 1) || address != zc->address)
  1535. return -EINVAL;
  1536. if (sk->sk_state == TCP_LISTEN)
  1537. return -ENOTCONN;
  1538. sock_rps_record_flow(sk);
  1539. down_read(&current->mm->mmap_sem);
  1540. ret = -EINVAL;
  1541. vma = find_vma(current->mm, address);
  1542. if (!vma || vma->vm_start > address || vma->vm_ops != &tcp_vm_ops)
  1543. goto out;
  1544. zc->length = min_t(unsigned long, zc->length, vma->vm_end - address);
  1545. tp = tcp_sk(sk);
  1546. seq = tp->copied_seq;
  1547. zc->length = min_t(u32, zc->length, tcp_inq(sk));
  1548. zc->length &= ~(PAGE_SIZE - 1);
  1549. zap_page_range(vma, address, zc->length);
  1550. zc->recv_skip_hint = 0;
  1551. ret = 0;
  1552. while (length + PAGE_SIZE <= zc->length) {
  1553. if (zc->recv_skip_hint < PAGE_SIZE) {
  1554. if (skb) {
  1555. skb = skb->next;
  1556. offset = seq - TCP_SKB_CB(skb)->seq;
  1557. } else {
  1558. skb = tcp_recv_skb(sk, seq, &offset);
  1559. }
  1560. zc->recv_skip_hint = skb->len - offset;
  1561. offset -= skb_headlen(skb);
  1562. if ((int)offset < 0 || skb_has_frag_list(skb))
  1563. break;
  1564. frags = skb_shinfo(skb)->frags;
  1565. while (offset) {
  1566. if (frags->size > offset)
  1567. goto out;
  1568. offset -= frags->size;
  1569. frags++;
  1570. }
  1571. }
  1572. if (frags->size != PAGE_SIZE || frags->page_offset)
  1573. break;
  1574. ret = vm_insert_page(vma, address + length,
  1575. skb_frag_page(frags));
  1576. if (ret)
  1577. break;
  1578. length += PAGE_SIZE;
  1579. seq += PAGE_SIZE;
  1580. zc->recv_skip_hint -= PAGE_SIZE;
  1581. frags++;
  1582. }
  1583. out:
  1584. up_read(&current->mm->mmap_sem);
  1585. if (length) {
  1586. tp->copied_seq = seq;
  1587. tcp_rcv_space_adjust(sk);
  1588. /* Clean up data we have read: This will do ACK frames. */
  1589. tcp_recv_skb(sk, seq, &offset);
  1590. tcp_cleanup_rbuf(sk, length);
  1591. ret = 0;
  1592. if (length == zc->length)
  1593. zc->recv_skip_hint = 0;
  1594. } else {
  1595. if (!zc->recv_skip_hint && sock_flag(sk, SOCK_DONE))
  1596. ret = -EIO;
  1597. }
  1598. zc->length = length;
  1599. return ret;
  1600. }
  1601. #endif
  1602. static void tcp_update_recv_tstamps(struct sk_buff *skb,
  1603. struct scm_timestamping *tss)
  1604. {
  1605. if (skb->tstamp)
  1606. tss->ts[0] = ktime_to_timespec(skb->tstamp);
  1607. else
  1608. tss->ts[0] = (struct timespec) {0};
  1609. if (skb_hwtstamps(skb)->hwtstamp)
  1610. tss->ts[2] = ktime_to_timespec(skb_hwtstamps(skb)->hwtstamp);
  1611. else
  1612. tss->ts[2] = (struct timespec) {0};
  1613. }
  1614. /* Similar to __sock_recv_timestamp, but does not require an skb */
  1615. static void tcp_recv_timestamp(struct msghdr *msg, const struct sock *sk,
  1616. struct scm_timestamping *tss)
  1617. {
  1618. struct timeval tv;
  1619. bool has_timestamping = false;
  1620. if (tss->ts[0].tv_sec || tss->ts[0].tv_nsec) {
  1621. if (sock_flag(sk, SOCK_RCVTSTAMP)) {
  1622. if (sock_flag(sk, SOCK_RCVTSTAMPNS)) {
  1623. put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPNS,
  1624. sizeof(tss->ts[0]), &tss->ts[0]);
  1625. } else {
  1626. tv.tv_sec = tss->ts[0].tv_sec;
  1627. tv.tv_usec = tss->ts[0].tv_nsec / 1000;
  1628. put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMP,
  1629. sizeof(tv), &tv);
  1630. }
  1631. }
  1632. if (sk->sk_tsflags & SOF_TIMESTAMPING_SOFTWARE)
  1633. has_timestamping = true;
  1634. else
  1635. tss->ts[0] = (struct timespec) {0};
  1636. }
  1637. if (tss->ts[2].tv_sec || tss->ts[2].tv_nsec) {
  1638. if (sk->sk_tsflags & SOF_TIMESTAMPING_RAW_HARDWARE)
  1639. has_timestamping = true;
  1640. else
  1641. tss->ts[2] = (struct timespec) {0};
  1642. }
  1643. if (has_timestamping) {
  1644. tss->ts[1] = (struct timespec) {0};
  1645. put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPING,
  1646. sizeof(*tss), tss);
  1647. }
  1648. }
  1649. static int tcp_inq_hint(struct sock *sk)
  1650. {
  1651. const struct tcp_sock *tp = tcp_sk(sk);
  1652. u32 copied_seq = READ_ONCE(tp->copied_seq);
  1653. u32 rcv_nxt = READ_ONCE(tp->rcv_nxt);
  1654. int inq;
  1655. inq = rcv_nxt - copied_seq;
  1656. if (unlikely(inq < 0 || copied_seq != READ_ONCE(tp->copied_seq))) {
  1657. lock_sock(sk);
  1658. inq = tp->rcv_nxt - tp->copied_seq;
  1659. release_sock(sk);
  1660. }
  1661. return inq;
  1662. }
  1663. /*
  1664. * This routine copies from a sock struct into the user buffer.
  1665. *
  1666. * Technical note: in 2.3 we work on _locked_ socket, so that
  1667. * tricks with *seq access order and skb->users are not required.
  1668. * Probably, code can be easily improved even more.
  1669. */
  1670. int tcp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int nonblock,
  1671. int flags, int *addr_len)
  1672. {
  1673. struct tcp_sock *tp = tcp_sk(sk);
  1674. int copied = 0;
  1675. u32 peek_seq;
  1676. u32 *seq;
  1677. unsigned long used;
  1678. int err, inq;
  1679. int target; /* Read at least this many bytes */
  1680. long timeo;
  1681. struct sk_buff *skb, *last;
  1682. u32 urg_hole = 0;
  1683. struct scm_timestamping tss;
  1684. bool has_tss = false;
  1685. bool has_cmsg;
  1686. if (unlikely(flags & MSG_ERRQUEUE))
  1687. return inet_recv_error(sk, msg, len, addr_len);
  1688. if (sk_can_busy_loop(sk) && skb_queue_empty(&sk->sk_receive_queue) &&
  1689. (sk->sk_state == TCP_ESTABLISHED))
  1690. sk_busy_loop(sk, nonblock);
  1691. lock_sock(sk);
  1692. err = -ENOTCONN;
  1693. if (sk->sk_state == TCP_LISTEN)
  1694. goto out;
  1695. has_cmsg = tp->recvmsg_inq;
  1696. timeo = sock_rcvtimeo(sk, nonblock);
  1697. /* Urgent data needs to be handled specially. */
  1698. if (flags & MSG_OOB)
  1699. goto recv_urg;
  1700. if (unlikely(tp->repair)) {
  1701. err = -EPERM;
  1702. if (!(flags & MSG_PEEK))
  1703. goto out;
  1704. if (tp->repair_queue == TCP_SEND_QUEUE)
  1705. goto recv_sndq;
  1706. err = -EINVAL;
  1707. if (tp->repair_queue == TCP_NO_QUEUE)
  1708. goto out;
  1709. /* 'common' recv queue MSG_PEEK-ing */
  1710. }
  1711. seq = &tp->copied_seq;
  1712. if (flags & MSG_PEEK) {
  1713. peek_seq = tp->copied_seq;
  1714. seq = &peek_seq;
  1715. }
  1716. target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
  1717. do {
  1718. u32 offset;
  1719. /* Are we at urgent data? Stop if we have read anything or have SIGURG pending. */
  1720. if (tp->urg_data && tp->urg_seq == *seq) {
  1721. if (copied)
  1722. break;
  1723. if (signal_pending(current)) {
  1724. copied = timeo ? sock_intr_errno(timeo) : -EAGAIN;
  1725. break;
  1726. }
  1727. }
  1728. /* Next get a buffer. */
  1729. last = skb_peek_tail(&sk->sk_receive_queue);
  1730. skb_queue_walk(&sk->sk_receive_queue, skb) {
  1731. last = skb;
  1732. /* Now that we have two receive queues this
  1733. * shouldn't happen.
  1734. */
  1735. if (WARN(before(*seq, TCP_SKB_CB(skb)->seq),
  1736. "recvmsg bug: copied %X seq %X rcvnxt %X fl %X\n",
  1737. *seq, TCP_SKB_CB(skb)->seq, tp->rcv_nxt,
  1738. flags))
  1739. break;
  1740. offset = *seq - TCP_SKB_CB(skb)->seq;
  1741. if (unlikely(TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN)) {
  1742. pr_err_once("%s: found a SYN, please report !\n", __func__);
  1743. offset--;
  1744. }
  1745. if (offset < skb->len)
  1746. goto found_ok_skb;
  1747. if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)
  1748. goto found_fin_ok;
  1749. WARN(!(flags & MSG_PEEK),
  1750. "recvmsg bug 2: copied %X seq %X rcvnxt %X fl %X\n",
  1751. *seq, TCP_SKB_CB(skb)->seq, tp->rcv_nxt, flags);
  1752. }
  1753. /* Well, if we have backlog, try to process it now yet. */
  1754. if (copied >= target && !sk->sk_backlog.tail)
  1755. break;
  1756. if (copied) {
  1757. if (sk->sk_err ||
  1758. sk->sk_state == TCP_CLOSE ||
  1759. (sk->sk_shutdown & RCV_SHUTDOWN) ||
  1760. !timeo ||
  1761. signal_pending(current))
  1762. break;
  1763. } else {
  1764. if (sock_flag(sk, SOCK_DONE))
  1765. break;
  1766. if (sk->sk_err) {
  1767. copied = sock_error(sk);
  1768. break;
  1769. }
  1770. if (sk->sk_shutdown & RCV_SHUTDOWN)
  1771. break;
  1772. if (sk->sk_state == TCP_CLOSE) {
  1773. if (!sock_flag(sk, SOCK_DONE)) {
  1774. /* This occurs when user tries to read
  1775. * from never connected socket.
  1776. */
  1777. copied = -ENOTCONN;
  1778. break;
  1779. }
  1780. break;
  1781. }
  1782. if (!timeo) {
  1783. copied = -EAGAIN;
  1784. break;
  1785. }
  1786. if (signal_pending(current)) {
  1787. copied = sock_intr_errno(timeo);
  1788. break;
  1789. }
  1790. }
  1791. tcp_cleanup_rbuf(sk, copied);
  1792. if (copied >= target) {
  1793. /* Do not sleep, just process backlog. */
  1794. release_sock(sk);
  1795. lock_sock(sk);
  1796. } else {
  1797. sk_wait_data(sk, &timeo, last);
  1798. }
  1799. if ((flags & MSG_PEEK) &&
  1800. (peek_seq - copied - urg_hole != tp->copied_seq)) {
  1801. net_dbg_ratelimited("TCP(%s:%d): Application bug, race in MSG_PEEK\n",
  1802. current->comm,
  1803. task_pid_nr(current));
  1804. peek_seq = tp->copied_seq;
  1805. }
  1806. continue;
  1807. found_ok_skb:
  1808. /* Ok so how much can we use? */
  1809. used = skb->len - offset;
  1810. if (len < used)
  1811. used = len;
  1812. /* Do we have urgent data here? */
  1813. if (tp->urg_data) {
  1814. u32 urg_offset = tp->urg_seq - *seq;
  1815. if (urg_offset < used) {
  1816. if (!urg_offset) {
  1817. if (!sock_flag(sk, SOCK_URGINLINE)) {
  1818. ++*seq;
  1819. urg_hole++;
  1820. offset++;
  1821. used--;
  1822. if (!used)
  1823. goto skip_copy;
  1824. }
  1825. } else
  1826. used = urg_offset;
  1827. }
  1828. }
  1829. if (!(flags & MSG_TRUNC)) {
  1830. err = skb_copy_datagram_msg(skb, offset, msg, used);
  1831. if (err) {
  1832. /* Exception. Bailout! */
  1833. if (!copied)
  1834. copied = -EFAULT;
  1835. break;
  1836. }
  1837. }
  1838. *seq += used;
  1839. copied += used;
  1840. len -= used;
  1841. tcp_rcv_space_adjust(sk);
  1842. skip_copy:
  1843. if (tp->urg_data && after(tp->copied_seq, tp->urg_seq)) {
  1844. tp->urg_data = 0;
  1845. tcp_fast_path_check(sk);
  1846. }
  1847. if (used + offset < skb->len)
  1848. continue;
  1849. if (TCP_SKB_CB(skb)->has_rxtstamp) {
  1850. tcp_update_recv_tstamps(skb, &tss);
  1851. has_tss = true;
  1852. has_cmsg = true;
  1853. }
  1854. if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)
  1855. goto found_fin_ok;
  1856. if (!(flags & MSG_PEEK))
  1857. sk_eat_skb(sk, skb);
  1858. continue;
  1859. found_fin_ok:
  1860. /* Process the FIN. */
  1861. ++*seq;
  1862. if (!(flags & MSG_PEEK))
  1863. sk_eat_skb(sk, skb);
  1864. break;
  1865. } while (len > 0);
  1866. /* According to UNIX98, msg_name/msg_namelen are ignored
  1867. * on connected socket. I was just happy when found this 8) --ANK
  1868. */
  1869. /* Clean up data we have read: This will do ACK frames. */
  1870. tcp_cleanup_rbuf(sk, copied);
  1871. release_sock(sk);
  1872. if (has_cmsg) {
  1873. if (has_tss)
  1874. tcp_recv_timestamp(msg, sk, &tss);
  1875. if (tp->recvmsg_inq) {
  1876. inq = tcp_inq_hint(sk);
  1877. put_cmsg(msg, SOL_TCP, TCP_CM_INQ, sizeof(inq), &inq);
  1878. }
  1879. }
  1880. return copied;
  1881. out:
  1882. release_sock(sk);
  1883. return err;
  1884. recv_urg:
  1885. err = tcp_recv_urg(sk, msg, len, flags);
  1886. goto out;
  1887. recv_sndq:
  1888. err = tcp_peek_sndq(sk, msg, len);
  1889. goto out;
  1890. }
  1891. EXPORT_SYMBOL(tcp_recvmsg);
  1892. void tcp_set_state(struct sock *sk, int state)
  1893. {
  1894. int oldstate = sk->sk_state;
  1895. /* We defined a new enum for TCP states that are exported in BPF
  1896. * so as not force the internal TCP states to be frozen. The
  1897. * following checks will detect if an internal state value ever
  1898. * differs from the BPF value. If this ever happens, then we will
  1899. * need to remap the internal value to the BPF value before calling
  1900. * tcp_call_bpf_2arg.
  1901. */
  1902. BUILD_BUG_ON((int)BPF_TCP_ESTABLISHED != (int)TCP_ESTABLISHED);
  1903. BUILD_BUG_ON((int)BPF_TCP_SYN_SENT != (int)TCP_SYN_SENT);
  1904. BUILD_BUG_ON((int)BPF_TCP_SYN_RECV != (int)TCP_SYN_RECV);
  1905. BUILD_BUG_ON((int)BPF_TCP_FIN_WAIT1 != (int)TCP_FIN_WAIT1);
  1906. BUILD_BUG_ON((int)BPF_TCP_FIN_WAIT2 != (int)TCP_FIN_WAIT2);
  1907. BUILD_BUG_ON((int)BPF_TCP_TIME_WAIT != (int)TCP_TIME_WAIT);
  1908. BUILD_BUG_ON((int)BPF_TCP_CLOSE != (int)TCP_CLOSE);
  1909. BUILD_BUG_ON((int)BPF_TCP_CLOSE_WAIT != (int)TCP_CLOSE_WAIT);
  1910. BUILD_BUG_ON((int)BPF_TCP_LAST_ACK != (int)TCP_LAST_ACK);
  1911. BUILD_BUG_ON((int)BPF_TCP_LISTEN != (int)TCP_LISTEN);
  1912. BUILD_BUG_ON((int)BPF_TCP_CLOSING != (int)TCP_CLOSING);
  1913. BUILD_BUG_ON((int)BPF_TCP_NEW_SYN_RECV != (int)TCP_NEW_SYN_RECV);
  1914. BUILD_BUG_ON((int)BPF_TCP_MAX_STATES != (int)TCP_MAX_STATES);
  1915. if (BPF_SOCK_OPS_TEST_FLAG(tcp_sk(sk), BPF_SOCK_OPS_STATE_CB_FLAG))
  1916. tcp_call_bpf_2arg(sk, BPF_SOCK_OPS_STATE_CB, oldstate, state);
  1917. switch (state) {
  1918. case TCP_ESTABLISHED:
  1919. if (oldstate != TCP_ESTABLISHED)
  1920. TCP_INC_STATS(sock_net(sk), TCP_MIB_CURRESTAB);
  1921. break;
  1922. case TCP_CLOSE:
  1923. if (oldstate == TCP_CLOSE_WAIT || oldstate == TCP_ESTABLISHED)
  1924. TCP_INC_STATS(sock_net(sk), TCP_MIB_ESTABRESETS);
  1925. sk->sk_prot->unhash(sk);
  1926. if (inet_csk(sk)->icsk_bind_hash &&
  1927. !(sk->sk_userlocks & SOCK_BINDPORT_LOCK))
  1928. inet_put_port(sk);
  1929. /* fall through */
  1930. default:
  1931. if (oldstate == TCP_ESTABLISHED)
  1932. TCP_DEC_STATS(sock_net(sk), TCP_MIB_CURRESTAB);
  1933. }
  1934. /* Change state AFTER socket is unhashed to avoid closed
  1935. * socket sitting in hash tables.
  1936. */
  1937. inet_sk_state_store(sk, state);
  1938. #ifdef STATE_TRACE
  1939. SOCK_DEBUG(sk, "TCP sk=%p, State %s -> %s\n", sk, statename[oldstate], statename[state]);
  1940. #endif
  1941. }
  1942. EXPORT_SYMBOL_GPL(tcp_set_state);
  1943. /*
  1944. * State processing on a close. This implements the state shift for
  1945. * sending our FIN frame. Note that we only send a FIN for some
  1946. * states. A shutdown() may have already sent the FIN, or we may be
  1947. * closed.
  1948. */
  1949. static const unsigned char new_state[16] = {
  1950. /* current state: new state: action: */
  1951. [0 /* (Invalid) */] = TCP_CLOSE,
  1952. [TCP_ESTABLISHED] = TCP_FIN_WAIT1 | TCP_ACTION_FIN,
  1953. [TCP_SYN_SENT] = TCP_CLOSE,
  1954. [TCP_SYN_RECV] = TCP_FIN_WAIT1 | TCP_ACTION_FIN,
  1955. [TCP_FIN_WAIT1] = TCP_FIN_WAIT1,
  1956. [TCP_FIN_WAIT2] = TCP_FIN_WAIT2,
  1957. [TCP_TIME_WAIT] = TCP_CLOSE,
  1958. [TCP_CLOSE] = TCP_CLOSE,
  1959. [TCP_CLOSE_WAIT] = TCP_LAST_ACK | TCP_ACTION_FIN,
  1960. [TCP_LAST_ACK] = TCP_LAST_ACK,
  1961. [TCP_LISTEN] = TCP_CLOSE,
  1962. [TCP_CLOSING] = TCP_CLOSING,
  1963. [TCP_NEW_SYN_RECV] = TCP_CLOSE, /* should not happen ! */
  1964. };
  1965. static int tcp_close_state(struct sock *sk)
  1966. {
  1967. int next = (int)new_state[sk->sk_state];
  1968. int ns = next & TCP_STATE_MASK;
  1969. tcp_set_state(sk, ns);
  1970. return next & TCP_ACTION_FIN;
  1971. }
  1972. /*
  1973. * Shutdown the sending side of a connection. Much like close except
  1974. * that we don't receive shut down or sock_set_flag(sk, SOCK_DEAD).
  1975. */
  1976. void tcp_shutdown(struct sock *sk, int how)
  1977. {
  1978. /* We need to grab some memory, and put together a FIN,
  1979. * and then put it into the queue to be sent.
  1980. * Tim MacKenzie(tym@dibbler.cs.monash.edu.au) 4 Dec '92.
  1981. */
  1982. if (!(how & SEND_SHUTDOWN))
  1983. return;
  1984. /* If we've already sent a FIN, or it's a closed state, skip this. */
  1985. if ((1 << sk->sk_state) &
  1986. (TCPF_ESTABLISHED | TCPF_SYN_SENT |
  1987. TCPF_SYN_RECV | TCPF_CLOSE_WAIT)) {
  1988. /* Clear out any half completed packets. FIN if needed. */
  1989. if (tcp_close_state(sk))
  1990. tcp_send_fin(sk);
  1991. }
  1992. }
  1993. EXPORT_SYMBOL(tcp_shutdown);
  1994. bool tcp_check_oom(struct sock *sk, int shift)
  1995. {
  1996. bool too_many_orphans, out_of_socket_memory;
  1997. too_many_orphans = tcp_too_many_orphans(sk, shift);
  1998. out_of_socket_memory = tcp_out_of_memory(sk);
  1999. if (too_many_orphans)
  2000. net_info_ratelimited("too many orphaned sockets\n");
  2001. if (out_of_socket_memory)
  2002. net_info_ratelimited("out of memory -- consider tuning tcp_mem\n");
  2003. return too_many_orphans || out_of_socket_memory;
  2004. }
  2005. void tcp_close(struct sock *sk, long timeout)
  2006. {
  2007. struct sk_buff *skb;
  2008. int data_was_unread = 0;
  2009. int state;
  2010. lock_sock(sk);
  2011. sk->sk_shutdown = SHUTDOWN_MASK;
  2012. if (sk->sk_state == TCP_LISTEN) {
  2013. tcp_set_state(sk, TCP_CLOSE);
  2014. /* Special case. */
  2015. inet_csk_listen_stop(sk);
  2016. goto adjudge_to_death;
  2017. }
  2018. /* We need to flush the recv. buffs. We do this only on the
  2019. * descriptor close, not protocol-sourced closes, because the
  2020. * reader process may not have drained the data yet!
  2021. */
  2022. while ((skb = __skb_dequeue(&sk->sk_receive_queue)) != NULL) {
  2023. u32 len = TCP_SKB_CB(skb)->end_seq - TCP_SKB_CB(skb)->seq;
  2024. if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)
  2025. len--;
  2026. data_was_unread += len;
  2027. __kfree_skb(skb);
  2028. }
  2029. sk_mem_reclaim(sk);
  2030. /* If socket has been already reset (e.g. in tcp_reset()) - kill it. */
  2031. if (sk->sk_state == TCP_CLOSE)
  2032. goto adjudge_to_death;
  2033. /* As outlined in RFC 2525, section 2.17, we send a RST here because
  2034. * data was lost. To witness the awful effects of the old behavior of
  2035. * always doing a FIN, run an older 2.1.x kernel or 2.0.x, start a bulk
  2036. * GET in an FTP client, suspend the process, wait for the client to
  2037. * advertise a zero window, then kill -9 the FTP client, wheee...
  2038. * Note: timeout is always zero in such a case.
  2039. */
  2040. if (unlikely(tcp_sk(sk)->repair)) {
  2041. sk->sk_prot->disconnect(sk, 0);
  2042. } else if (data_was_unread) {
  2043. /* Unread data was tossed, zap the connection. */
  2044. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONCLOSE);
  2045. tcp_set_state(sk, TCP_CLOSE);
  2046. tcp_send_active_reset(sk, sk->sk_allocation);
  2047. } else if (sock_flag(sk, SOCK_LINGER) && !sk->sk_lingertime) {
  2048. /* Check zero linger _after_ checking for unread data. */
  2049. sk->sk_prot->disconnect(sk, 0);
  2050. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONDATA);
  2051. } else if (tcp_close_state(sk)) {
  2052. /* We FIN if the application ate all the data before
  2053. * zapping the connection.
  2054. */
  2055. /* RED-PEN. Formally speaking, we have broken TCP state
  2056. * machine. State transitions:
  2057. *
  2058. * TCP_ESTABLISHED -> TCP_FIN_WAIT1
  2059. * TCP_SYN_RECV -> TCP_FIN_WAIT1 (forget it, it's impossible)
  2060. * TCP_CLOSE_WAIT -> TCP_LAST_ACK
  2061. *
  2062. * are legal only when FIN has been sent (i.e. in window),
  2063. * rather than queued out of window. Purists blame.
  2064. *
  2065. * F.e. "RFC state" is ESTABLISHED,
  2066. * if Linux state is FIN-WAIT-1, but FIN is still not sent.
  2067. *
  2068. * The visible declinations are that sometimes
  2069. * we enter time-wait state, when it is not required really
  2070. * (harmless), do not send active resets, when they are
  2071. * required by specs (TCP_ESTABLISHED, TCP_CLOSE_WAIT, when
  2072. * they look as CLOSING or LAST_ACK for Linux)
  2073. * Probably, I missed some more holelets.
  2074. * --ANK
  2075. * XXX (TFO) - To start off we don't support SYN+ACK+FIN
  2076. * in a single packet! (May consider it later but will
  2077. * probably need API support or TCP_CORK SYN-ACK until
  2078. * data is written and socket is closed.)
  2079. */
  2080. tcp_send_fin(sk);
  2081. }
  2082. sk_stream_wait_close(sk, timeout);
  2083. adjudge_to_death:
  2084. state = sk->sk_state;
  2085. sock_hold(sk);
  2086. sock_orphan(sk);
  2087. /* It is the last release_sock in its life. It will remove backlog. */
  2088. release_sock(sk);
  2089. /* Now socket is owned by kernel and we acquire BH lock
  2090. * to finish close. No need to check for user refs.
  2091. */
  2092. local_bh_disable();
  2093. bh_lock_sock(sk);
  2094. WARN_ON(sock_owned_by_user(sk));
  2095. percpu_counter_inc(sk->sk_prot->orphan_count);
  2096. /* Have we already been destroyed by a softirq or backlog? */
  2097. if (state != TCP_CLOSE && sk->sk_state == TCP_CLOSE)
  2098. goto out;
  2099. /* This is a (useful) BSD violating of the RFC. There is a
  2100. * problem with TCP as specified in that the other end could
  2101. * keep a socket open forever with no application left this end.
  2102. * We use a 1 minute timeout (about the same as BSD) then kill
  2103. * our end. If they send after that then tough - BUT: long enough
  2104. * that we won't make the old 4*rto = almost no time - whoops
  2105. * reset mistake.
  2106. *
  2107. * Nope, it was not mistake. It is really desired behaviour
  2108. * f.e. on http servers, when such sockets are useless, but
  2109. * consume significant resources. Let's do it with special
  2110. * linger2 option. --ANK
  2111. */
  2112. if (sk->sk_state == TCP_FIN_WAIT2) {
  2113. struct tcp_sock *tp = tcp_sk(sk);
  2114. if (tp->linger2 < 0) {
  2115. tcp_set_state(sk, TCP_CLOSE);
  2116. tcp_send_active_reset(sk, GFP_ATOMIC);
  2117. __NET_INC_STATS(sock_net(sk),
  2118. LINUX_MIB_TCPABORTONLINGER);
  2119. } else {
  2120. const int tmo = tcp_fin_time(sk);
  2121. if (tmo > TCP_TIMEWAIT_LEN) {
  2122. inet_csk_reset_keepalive_timer(sk,
  2123. tmo - TCP_TIMEWAIT_LEN);
  2124. } else {
  2125. tcp_time_wait(sk, TCP_FIN_WAIT2, tmo);
  2126. goto out;
  2127. }
  2128. }
  2129. }
  2130. if (sk->sk_state != TCP_CLOSE) {
  2131. sk_mem_reclaim(sk);
  2132. if (tcp_check_oom(sk, 0)) {
  2133. tcp_set_state(sk, TCP_CLOSE);
  2134. tcp_send_active_reset(sk, GFP_ATOMIC);
  2135. __NET_INC_STATS(sock_net(sk),
  2136. LINUX_MIB_TCPABORTONMEMORY);
  2137. } else if (!check_net(sock_net(sk))) {
  2138. /* Not possible to send reset; just close */
  2139. tcp_set_state(sk, TCP_CLOSE);
  2140. }
  2141. }
  2142. if (sk->sk_state == TCP_CLOSE) {
  2143. struct request_sock *req = tcp_sk(sk)->fastopen_rsk;
  2144. /* We could get here with a non-NULL req if the socket is
  2145. * aborted (e.g., closed with unread data) before 3WHS
  2146. * finishes.
  2147. */
  2148. if (req)
  2149. reqsk_fastopen_remove(sk, req, false);
  2150. inet_csk_destroy_sock(sk);
  2151. }
  2152. /* Otherwise, socket is reprieved until protocol close. */
  2153. out:
  2154. bh_unlock_sock(sk);
  2155. local_bh_enable();
  2156. sock_put(sk);
  2157. }
  2158. EXPORT_SYMBOL(tcp_close);
  2159. /* These states need RST on ABORT according to RFC793 */
  2160. static inline bool tcp_need_reset(int state)
  2161. {
  2162. return (1 << state) &
  2163. (TCPF_ESTABLISHED | TCPF_CLOSE_WAIT | TCPF_FIN_WAIT1 |
  2164. TCPF_FIN_WAIT2 | TCPF_SYN_RECV);
  2165. }
  2166. static void tcp_rtx_queue_purge(struct sock *sk)
  2167. {
  2168. struct rb_node *p = rb_first(&sk->tcp_rtx_queue);
  2169. while (p) {
  2170. struct sk_buff *skb = rb_to_skb(p);
  2171. p = rb_next(p);
  2172. /* Since we are deleting whole queue, no need to
  2173. * list_del(&skb->tcp_tsorted_anchor)
  2174. */
  2175. tcp_rtx_queue_unlink(skb, sk);
  2176. sk_wmem_free_skb(sk, skb);
  2177. }
  2178. }
  2179. void tcp_write_queue_purge(struct sock *sk)
  2180. {
  2181. struct sk_buff *skb;
  2182. tcp_chrono_stop(sk, TCP_CHRONO_BUSY);
  2183. while ((skb = __skb_dequeue(&sk->sk_write_queue)) != NULL) {
  2184. tcp_skb_tsorted_anchor_cleanup(skb);
  2185. sk_wmem_free_skb(sk, skb);
  2186. }
  2187. tcp_rtx_queue_purge(sk);
  2188. INIT_LIST_HEAD(&tcp_sk(sk)->tsorted_sent_queue);
  2189. sk_mem_reclaim(sk);
  2190. tcp_clear_all_retrans_hints(tcp_sk(sk));
  2191. tcp_sk(sk)->packets_out = 0;
  2192. }
  2193. int tcp_disconnect(struct sock *sk, int flags)
  2194. {
  2195. struct inet_sock *inet = inet_sk(sk);
  2196. struct inet_connection_sock *icsk = inet_csk(sk);
  2197. struct tcp_sock *tp = tcp_sk(sk);
  2198. int err = 0;
  2199. int old_state = sk->sk_state;
  2200. if (old_state != TCP_CLOSE)
  2201. tcp_set_state(sk, TCP_CLOSE);
  2202. /* ABORT function of RFC793 */
  2203. if (old_state == TCP_LISTEN) {
  2204. inet_csk_listen_stop(sk);
  2205. } else if (unlikely(tp->repair)) {
  2206. sk->sk_err = ECONNABORTED;
  2207. } else if (tcp_need_reset(old_state) ||
  2208. (tp->snd_nxt != tp->write_seq &&
  2209. (1 << old_state) & (TCPF_CLOSING | TCPF_LAST_ACK))) {
  2210. /* The last check adjusts for discrepancy of Linux wrt. RFC
  2211. * states
  2212. */
  2213. tcp_send_active_reset(sk, gfp_any());
  2214. sk->sk_err = ECONNRESET;
  2215. } else if (old_state == TCP_SYN_SENT)
  2216. sk->sk_err = ECONNRESET;
  2217. tcp_clear_xmit_timers(sk);
  2218. __skb_queue_purge(&sk->sk_receive_queue);
  2219. tcp_write_queue_purge(sk);
  2220. tcp_fastopen_active_disable_ofo_check(sk);
  2221. skb_rbtree_purge(&tp->out_of_order_queue);
  2222. inet->inet_dport = 0;
  2223. if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK))
  2224. inet_reset_saddr(sk);
  2225. sk->sk_shutdown = 0;
  2226. sock_reset_flag(sk, SOCK_DONE);
  2227. tp->srtt_us = 0;
  2228. tp->write_seq += tp->max_window + 2;
  2229. if (tp->write_seq == 0)
  2230. tp->write_seq = 1;
  2231. icsk->icsk_backoff = 0;
  2232. tp->snd_cwnd = 2;
  2233. icsk->icsk_probes_out = 0;
  2234. tp->snd_ssthresh = TCP_INFINITE_SSTHRESH;
  2235. tp->snd_cwnd_cnt = 0;
  2236. tp->window_clamp = 0;
  2237. tp->delivered_ce = 0;
  2238. tcp_set_ca_state(sk, TCP_CA_Open);
  2239. tp->is_sack_reneg = 0;
  2240. tcp_clear_retrans(tp);
  2241. inet_csk_delack_init(sk);
  2242. /* Initialize rcv_mss to TCP_MIN_MSS to avoid division by 0
  2243. * issue in __tcp_select_window()
  2244. */
  2245. icsk->icsk_ack.rcv_mss = TCP_MIN_MSS;
  2246. memset(&tp->rx_opt, 0, sizeof(tp->rx_opt));
  2247. __sk_dst_reset(sk);
  2248. dst_release(sk->sk_rx_dst);
  2249. sk->sk_rx_dst = NULL;
  2250. tcp_saved_syn_free(tp);
  2251. tp->compressed_ack = 0;
  2252. /* Clean up fastopen related fields */
  2253. tcp_free_fastopen_req(tp);
  2254. inet->defer_connect = 0;
  2255. WARN_ON(inet->inet_num && !icsk->icsk_bind_hash);
  2256. if (sk->sk_frag.page) {
  2257. put_page(sk->sk_frag.page);
  2258. sk->sk_frag.page = NULL;
  2259. sk->sk_frag.offset = 0;
  2260. }
  2261. sk->sk_error_report(sk);
  2262. return err;
  2263. }
  2264. EXPORT_SYMBOL(tcp_disconnect);
  2265. static inline bool tcp_can_repair_sock(const struct sock *sk)
  2266. {
  2267. return ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN) &&
  2268. (sk->sk_state != TCP_LISTEN);
  2269. }
  2270. static int tcp_repair_set_window(struct tcp_sock *tp, char __user *optbuf, int len)
  2271. {
  2272. struct tcp_repair_window opt;
  2273. if (!tp->repair)
  2274. return -EPERM;
  2275. if (len != sizeof(opt))
  2276. return -EINVAL;
  2277. if (copy_from_user(&opt, optbuf, sizeof(opt)))
  2278. return -EFAULT;
  2279. if (opt.max_window < opt.snd_wnd)
  2280. return -EINVAL;
  2281. if (after(opt.snd_wl1, tp->rcv_nxt + opt.rcv_wnd))
  2282. return -EINVAL;
  2283. if (after(opt.rcv_wup, tp->rcv_nxt))
  2284. return -EINVAL;
  2285. tp->snd_wl1 = opt.snd_wl1;
  2286. tp->snd_wnd = opt.snd_wnd;
  2287. tp->max_window = opt.max_window;
  2288. tp->rcv_wnd = opt.rcv_wnd;
  2289. tp->rcv_wup = opt.rcv_wup;
  2290. return 0;
  2291. }
  2292. static int tcp_repair_options_est(struct sock *sk,
  2293. struct tcp_repair_opt __user *optbuf, unsigned int len)
  2294. {
  2295. struct tcp_sock *tp = tcp_sk(sk);
  2296. struct tcp_repair_opt opt;
  2297. while (len >= sizeof(opt)) {
  2298. if (copy_from_user(&opt, optbuf, sizeof(opt)))
  2299. return -EFAULT;
  2300. optbuf++;
  2301. len -= sizeof(opt);
  2302. switch (opt.opt_code) {
  2303. case TCPOPT_MSS:
  2304. tp->rx_opt.mss_clamp = opt.opt_val;
  2305. tcp_mtup_init(sk);
  2306. break;
  2307. case TCPOPT_WINDOW:
  2308. {
  2309. u16 snd_wscale = opt.opt_val & 0xFFFF;
  2310. u16 rcv_wscale = opt.opt_val >> 16;
  2311. if (snd_wscale > TCP_MAX_WSCALE || rcv_wscale > TCP_MAX_WSCALE)
  2312. return -EFBIG;
  2313. tp->rx_opt.snd_wscale = snd_wscale;
  2314. tp->rx_opt.rcv_wscale = rcv_wscale;
  2315. tp->rx_opt.wscale_ok = 1;
  2316. }
  2317. break;
  2318. case TCPOPT_SACK_PERM:
  2319. if (opt.opt_val != 0)
  2320. return -EINVAL;
  2321. tp->rx_opt.sack_ok |= TCP_SACK_SEEN;
  2322. break;
  2323. case TCPOPT_TIMESTAMP:
  2324. if (opt.opt_val != 0)
  2325. return -EINVAL;
  2326. tp->rx_opt.tstamp_ok = 1;
  2327. break;
  2328. }
  2329. }
  2330. return 0;
  2331. }
  2332. /*
  2333. * Socket option code for TCP.
  2334. */
  2335. static int do_tcp_setsockopt(struct sock *sk, int level,
  2336. int optname, char __user *optval, unsigned int optlen)
  2337. {
  2338. struct tcp_sock *tp = tcp_sk(sk);
  2339. struct inet_connection_sock *icsk = inet_csk(sk);
  2340. struct net *net = sock_net(sk);
  2341. int val;
  2342. int err = 0;
  2343. /* These are data/string values, all the others are ints */
  2344. switch (optname) {
  2345. case TCP_CONGESTION: {
  2346. char name[TCP_CA_NAME_MAX];
  2347. if (optlen < 1)
  2348. return -EINVAL;
  2349. val = strncpy_from_user(name, optval,
  2350. min_t(long, TCP_CA_NAME_MAX-1, optlen));
  2351. if (val < 0)
  2352. return -EFAULT;
  2353. name[val] = 0;
  2354. lock_sock(sk);
  2355. err = tcp_set_congestion_control(sk, name, true, true);
  2356. release_sock(sk);
  2357. return err;
  2358. }
  2359. case TCP_ULP: {
  2360. char name[TCP_ULP_NAME_MAX];
  2361. if (optlen < 1)
  2362. return -EINVAL;
  2363. val = strncpy_from_user(name, optval,
  2364. min_t(long, TCP_ULP_NAME_MAX - 1,
  2365. optlen));
  2366. if (val < 0)
  2367. return -EFAULT;
  2368. name[val] = 0;
  2369. lock_sock(sk);
  2370. err = tcp_set_ulp(sk, name);
  2371. release_sock(sk);
  2372. return err;
  2373. }
  2374. case TCP_FASTOPEN_KEY: {
  2375. __u8 key[TCP_FASTOPEN_KEY_LENGTH];
  2376. if (optlen != sizeof(key))
  2377. return -EINVAL;
  2378. if (copy_from_user(key, optval, optlen))
  2379. return -EFAULT;
  2380. return tcp_fastopen_reset_cipher(net, sk, key, sizeof(key));
  2381. }
  2382. default:
  2383. /* fallthru */
  2384. break;
  2385. }
  2386. if (optlen < sizeof(int))
  2387. return -EINVAL;
  2388. if (get_user(val, (int __user *)optval))
  2389. return -EFAULT;
  2390. lock_sock(sk);
  2391. switch (optname) {
  2392. case TCP_MAXSEG:
  2393. /* Values greater than interface MTU won't take effect. However
  2394. * at the point when this call is done we typically don't yet
  2395. * know which interface is going to be used
  2396. */
  2397. if (val && (val < TCP_MIN_MSS || val > MAX_TCP_WINDOW)) {
  2398. err = -EINVAL;
  2399. break;
  2400. }
  2401. tp->rx_opt.user_mss = val;
  2402. break;
  2403. case TCP_NODELAY:
  2404. if (val) {
  2405. /* TCP_NODELAY is weaker than TCP_CORK, so that
  2406. * this option on corked socket is remembered, but
  2407. * it is not activated until cork is cleared.
  2408. *
  2409. * However, when TCP_NODELAY is set we make
  2410. * an explicit push, which overrides even TCP_CORK
  2411. * for currently queued segments.
  2412. */
  2413. tp->nonagle |= TCP_NAGLE_OFF|TCP_NAGLE_PUSH;
  2414. tcp_push_pending_frames(sk);
  2415. } else {
  2416. tp->nonagle &= ~TCP_NAGLE_OFF;
  2417. }
  2418. break;
  2419. case TCP_THIN_LINEAR_TIMEOUTS:
  2420. if (val < 0 || val > 1)
  2421. err = -EINVAL;
  2422. else
  2423. tp->thin_lto = val;
  2424. break;
  2425. case TCP_THIN_DUPACK:
  2426. if (val < 0 || val > 1)
  2427. err = -EINVAL;
  2428. break;
  2429. case TCP_REPAIR:
  2430. if (!tcp_can_repair_sock(sk))
  2431. err = -EPERM;
  2432. else if (val == 1) {
  2433. tp->repair = 1;
  2434. sk->sk_reuse = SK_FORCE_REUSE;
  2435. tp->repair_queue = TCP_NO_QUEUE;
  2436. } else if (val == 0) {
  2437. tp->repair = 0;
  2438. sk->sk_reuse = SK_NO_REUSE;
  2439. tcp_send_window_probe(sk);
  2440. } else
  2441. err = -EINVAL;
  2442. break;
  2443. case TCP_REPAIR_QUEUE:
  2444. if (!tp->repair)
  2445. err = -EPERM;
  2446. else if ((unsigned int)val < TCP_QUEUES_NR)
  2447. tp->repair_queue = val;
  2448. else
  2449. err = -EINVAL;
  2450. break;
  2451. case TCP_QUEUE_SEQ:
  2452. if (sk->sk_state != TCP_CLOSE)
  2453. err = -EPERM;
  2454. else if (tp->repair_queue == TCP_SEND_QUEUE)
  2455. tp->write_seq = val;
  2456. else if (tp->repair_queue == TCP_RECV_QUEUE)
  2457. tp->rcv_nxt = val;
  2458. else
  2459. err = -EINVAL;
  2460. break;
  2461. case TCP_REPAIR_OPTIONS:
  2462. if (!tp->repair)
  2463. err = -EINVAL;
  2464. else if (sk->sk_state == TCP_ESTABLISHED)
  2465. err = tcp_repair_options_est(sk,
  2466. (struct tcp_repair_opt __user *)optval,
  2467. optlen);
  2468. else
  2469. err = -EPERM;
  2470. break;
  2471. case TCP_CORK:
  2472. /* When set indicates to always queue non-full frames.
  2473. * Later the user clears this option and we transmit
  2474. * any pending partial frames in the queue. This is
  2475. * meant to be used alongside sendfile() to get properly
  2476. * filled frames when the user (for example) must write
  2477. * out headers with a write() call first and then use
  2478. * sendfile to send out the data parts.
  2479. *
  2480. * TCP_CORK can be set together with TCP_NODELAY and it is
  2481. * stronger than TCP_NODELAY.
  2482. */
  2483. if (val) {
  2484. tp->nonagle |= TCP_NAGLE_CORK;
  2485. } else {
  2486. tp->nonagle &= ~TCP_NAGLE_CORK;
  2487. if (tp->nonagle&TCP_NAGLE_OFF)
  2488. tp->nonagle |= TCP_NAGLE_PUSH;
  2489. tcp_push_pending_frames(sk);
  2490. }
  2491. break;
  2492. case TCP_KEEPIDLE:
  2493. if (val < 1 || val > MAX_TCP_KEEPIDLE)
  2494. err = -EINVAL;
  2495. else {
  2496. tp->keepalive_time = val * HZ;
  2497. if (sock_flag(sk, SOCK_KEEPOPEN) &&
  2498. !((1 << sk->sk_state) &
  2499. (TCPF_CLOSE | TCPF_LISTEN))) {
  2500. u32 elapsed = keepalive_time_elapsed(tp);
  2501. if (tp->keepalive_time > elapsed)
  2502. elapsed = tp->keepalive_time - elapsed;
  2503. else
  2504. elapsed = 0;
  2505. inet_csk_reset_keepalive_timer(sk, elapsed);
  2506. }
  2507. }
  2508. break;
  2509. case TCP_KEEPINTVL:
  2510. if (val < 1 || val > MAX_TCP_KEEPINTVL)
  2511. err = -EINVAL;
  2512. else
  2513. tp->keepalive_intvl = val * HZ;
  2514. break;
  2515. case TCP_KEEPCNT:
  2516. if (val < 1 || val > MAX_TCP_KEEPCNT)
  2517. err = -EINVAL;
  2518. else
  2519. tp->keepalive_probes = val;
  2520. break;
  2521. case TCP_SYNCNT:
  2522. if (val < 1 || val > MAX_TCP_SYNCNT)
  2523. err = -EINVAL;
  2524. else
  2525. icsk->icsk_syn_retries = val;
  2526. break;
  2527. case TCP_SAVE_SYN:
  2528. if (val < 0 || val > 1)
  2529. err = -EINVAL;
  2530. else
  2531. tp->save_syn = val;
  2532. break;
  2533. case TCP_LINGER2:
  2534. if (val < 0)
  2535. tp->linger2 = -1;
  2536. else if (val > net->ipv4.sysctl_tcp_fin_timeout / HZ)
  2537. tp->linger2 = 0;
  2538. else
  2539. tp->linger2 = val * HZ;
  2540. break;
  2541. case TCP_DEFER_ACCEPT:
  2542. /* Translate value in seconds to number of retransmits */
  2543. icsk->icsk_accept_queue.rskq_defer_accept =
  2544. secs_to_retrans(val, TCP_TIMEOUT_INIT / HZ,
  2545. TCP_RTO_MAX / HZ);
  2546. break;
  2547. case TCP_WINDOW_CLAMP:
  2548. if (!val) {
  2549. if (sk->sk_state != TCP_CLOSE) {
  2550. err = -EINVAL;
  2551. break;
  2552. }
  2553. tp->window_clamp = 0;
  2554. } else
  2555. tp->window_clamp = val < SOCK_MIN_RCVBUF / 2 ?
  2556. SOCK_MIN_RCVBUF / 2 : val;
  2557. break;
  2558. case TCP_QUICKACK:
  2559. if (!val) {
  2560. icsk->icsk_ack.pingpong = 1;
  2561. } else {
  2562. icsk->icsk_ack.pingpong = 0;
  2563. if ((1 << sk->sk_state) &
  2564. (TCPF_ESTABLISHED | TCPF_CLOSE_WAIT) &&
  2565. inet_csk_ack_scheduled(sk)) {
  2566. icsk->icsk_ack.pending |= ICSK_ACK_PUSHED;
  2567. tcp_cleanup_rbuf(sk, 1);
  2568. if (!(val & 1))
  2569. icsk->icsk_ack.pingpong = 1;
  2570. }
  2571. }
  2572. break;
  2573. #ifdef CONFIG_TCP_MD5SIG
  2574. case TCP_MD5SIG:
  2575. case TCP_MD5SIG_EXT:
  2576. if ((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN))
  2577. err = tp->af_specific->md5_parse(sk, optname, optval, optlen);
  2578. else
  2579. err = -EINVAL;
  2580. break;
  2581. #endif
  2582. case TCP_USER_TIMEOUT:
  2583. /* Cap the max time in ms TCP will retry or probe the window
  2584. * before giving up and aborting (ETIMEDOUT) a connection.
  2585. */
  2586. if (val < 0)
  2587. err = -EINVAL;
  2588. else
  2589. icsk->icsk_user_timeout = msecs_to_jiffies(val);
  2590. break;
  2591. case TCP_FASTOPEN:
  2592. if (val >= 0 && ((1 << sk->sk_state) & (TCPF_CLOSE |
  2593. TCPF_LISTEN))) {
  2594. tcp_fastopen_init_key_once(net);
  2595. fastopen_queue_tune(sk, val);
  2596. } else {
  2597. err = -EINVAL;
  2598. }
  2599. break;
  2600. case TCP_FASTOPEN_CONNECT:
  2601. if (val > 1 || val < 0) {
  2602. err = -EINVAL;
  2603. } else if (net->ipv4.sysctl_tcp_fastopen & TFO_CLIENT_ENABLE) {
  2604. if (sk->sk_state == TCP_CLOSE)
  2605. tp->fastopen_connect = val;
  2606. else
  2607. err = -EINVAL;
  2608. } else {
  2609. err = -EOPNOTSUPP;
  2610. }
  2611. break;
  2612. case TCP_FASTOPEN_NO_COOKIE:
  2613. if (val > 1 || val < 0)
  2614. err = -EINVAL;
  2615. else if (!((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN)))
  2616. err = -EINVAL;
  2617. else
  2618. tp->fastopen_no_cookie = val;
  2619. break;
  2620. case TCP_TIMESTAMP:
  2621. if (!tp->repair)
  2622. err = -EPERM;
  2623. else
  2624. tp->tsoffset = val - tcp_time_stamp_raw();
  2625. break;
  2626. case TCP_REPAIR_WINDOW:
  2627. err = tcp_repair_set_window(tp, optval, optlen);
  2628. break;
  2629. case TCP_NOTSENT_LOWAT:
  2630. tp->notsent_lowat = val;
  2631. sk->sk_write_space(sk);
  2632. break;
  2633. case TCP_INQ:
  2634. if (val > 1 || val < 0)
  2635. err = -EINVAL;
  2636. else
  2637. tp->recvmsg_inq = val;
  2638. break;
  2639. default:
  2640. err = -ENOPROTOOPT;
  2641. break;
  2642. }
  2643. release_sock(sk);
  2644. return err;
  2645. }
  2646. int tcp_setsockopt(struct sock *sk, int level, int optname, char __user *optval,
  2647. unsigned int optlen)
  2648. {
  2649. const struct inet_connection_sock *icsk = inet_csk(sk);
  2650. if (level != SOL_TCP)
  2651. return icsk->icsk_af_ops->setsockopt(sk, level, optname,
  2652. optval, optlen);
  2653. return do_tcp_setsockopt(sk, level, optname, optval, optlen);
  2654. }
  2655. EXPORT_SYMBOL(tcp_setsockopt);
  2656. #ifdef CONFIG_COMPAT
  2657. int compat_tcp_setsockopt(struct sock *sk, int level, int optname,
  2658. char __user *optval, unsigned int optlen)
  2659. {
  2660. if (level != SOL_TCP)
  2661. return inet_csk_compat_setsockopt(sk, level, optname,
  2662. optval, optlen);
  2663. return do_tcp_setsockopt(sk, level, optname, optval, optlen);
  2664. }
  2665. EXPORT_SYMBOL(compat_tcp_setsockopt);
  2666. #endif
  2667. static void tcp_get_info_chrono_stats(const struct tcp_sock *tp,
  2668. struct tcp_info *info)
  2669. {
  2670. u64 stats[__TCP_CHRONO_MAX], total = 0;
  2671. enum tcp_chrono i;
  2672. for (i = TCP_CHRONO_BUSY; i < __TCP_CHRONO_MAX; ++i) {
  2673. stats[i] = tp->chrono_stat[i - 1];
  2674. if (i == tp->chrono_type)
  2675. stats[i] += tcp_jiffies32 - tp->chrono_start;
  2676. stats[i] *= USEC_PER_SEC / HZ;
  2677. total += stats[i];
  2678. }
  2679. info->tcpi_busy_time = total;
  2680. info->tcpi_rwnd_limited = stats[TCP_CHRONO_RWND_LIMITED];
  2681. info->tcpi_sndbuf_limited = stats[TCP_CHRONO_SNDBUF_LIMITED];
  2682. }
  2683. /* Return information about state of tcp endpoint in API format. */
  2684. void tcp_get_info(struct sock *sk, struct tcp_info *info)
  2685. {
  2686. const struct tcp_sock *tp = tcp_sk(sk); /* iff sk_type == SOCK_STREAM */
  2687. const struct inet_connection_sock *icsk = inet_csk(sk);
  2688. u32 now;
  2689. u64 rate64;
  2690. bool slow;
  2691. u32 rate;
  2692. memset(info, 0, sizeof(*info));
  2693. if (sk->sk_type != SOCK_STREAM)
  2694. return;
  2695. info->tcpi_state = inet_sk_state_load(sk);
  2696. /* Report meaningful fields for all TCP states, including listeners */
  2697. rate = READ_ONCE(sk->sk_pacing_rate);
  2698. rate64 = rate != ~0U ? rate : ~0ULL;
  2699. info->tcpi_pacing_rate = rate64;
  2700. rate = READ_ONCE(sk->sk_max_pacing_rate);
  2701. rate64 = rate != ~0U ? rate : ~0ULL;
  2702. info->tcpi_max_pacing_rate = rate64;
  2703. info->tcpi_reordering = tp->reordering;
  2704. info->tcpi_snd_cwnd = tp->snd_cwnd;
  2705. if (info->tcpi_state == TCP_LISTEN) {
  2706. /* listeners aliased fields :
  2707. * tcpi_unacked -> Number of children ready for accept()
  2708. * tcpi_sacked -> max backlog
  2709. */
  2710. info->tcpi_unacked = sk->sk_ack_backlog;
  2711. info->tcpi_sacked = sk->sk_max_ack_backlog;
  2712. return;
  2713. }
  2714. slow = lock_sock_fast(sk);
  2715. info->tcpi_ca_state = icsk->icsk_ca_state;
  2716. info->tcpi_retransmits = icsk->icsk_retransmits;
  2717. info->tcpi_probes = icsk->icsk_probes_out;
  2718. info->tcpi_backoff = icsk->icsk_backoff;
  2719. if (tp->rx_opt.tstamp_ok)
  2720. info->tcpi_options |= TCPI_OPT_TIMESTAMPS;
  2721. if (tcp_is_sack(tp))
  2722. info->tcpi_options |= TCPI_OPT_SACK;
  2723. if (tp->rx_opt.wscale_ok) {
  2724. info->tcpi_options |= TCPI_OPT_WSCALE;
  2725. info->tcpi_snd_wscale = tp->rx_opt.snd_wscale;
  2726. info->tcpi_rcv_wscale = tp->rx_opt.rcv_wscale;
  2727. }
  2728. if (tp->ecn_flags & TCP_ECN_OK)
  2729. info->tcpi_options |= TCPI_OPT_ECN;
  2730. if (tp->ecn_flags & TCP_ECN_SEEN)
  2731. info->tcpi_options |= TCPI_OPT_ECN_SEEN;
  2732. if (tp->syn_data_acked)
  2733. info->tcpi_options |= TCPI_OPT_SYN_DATA;
  2734. info->tcpi_rto = jiffies_to_usecs(icsk->icsk_rto);
  2735. info->tcpi_ato = jiffies_to_usecs(icsk->icsk_ack.ato);
  2736. info->tcpi_snd_mss = tp->mss_cache;
  2737. info->tcpi_rcv_mss = icsk->icsk_ack.rcv_mss;
  2738. info->tcpi_unacked = tp->packets_out;
  2739. info->tcpi_sacked = tp->sacked_out;
  2740. info->tcpi_lost = tp->lost_out;
  2741. info->tcpi_retrans = tp->retrans_out;
  2742. now = tcp_jiffies32;
  2743. info->tcpi_last_data_sent = jiffies_to_msecs(now - tp->lsndtime);
  2744. info->tcpi_last_data_recv = jiffies_to_msecs(now - icsk->icsk_ack.lrcvtime);
  2745. info->tcpi_last_ack_recv = jiffies_to_msecs(now - tp->rcv_tstamp);
  2746. info->tcpi_pmtu = icsk->icsk_pmtu_cookie;
  2747. info->tcpi_rcv_ssthresh = tp->rcv_ssthresh;
  2748. info->tcpi_rtt = tp->srtt_us >> 3;
  2749. info->tcpi_rttvar = tp->mdev_us >> 2;
  2750. info->tcpi_snd_ssthresh = tp->snd_ssthresh;
  2751. info->tcpi_advmss = tp->advmss;
  2752. info->tcpi_rcv_rtt = tp->rcv_rtt_est.rtt_us >> 3;
  2753. info->tcpi_rcv_space = tp->rcvq_space.space;
  2754. info->tcpi_total_retrans = tp->total_retrans;
  2755. info->tcpi_bytes_acked = tp->bytes_acked;
  2756. info->tcpi_bytes_received = tp->bytes_received;
  2757. info->tcpi_notsent_bytes = max_t(int, 0, tp->write_seq - tp->snd_nxt);
  2758. tcp_get_info_chrono_stats(tp, info);
  2759. info->tcpi_segs_out = tp->segs_out;
  2760. info->tcpi_segs_in = tp->segs_in;
  2761. info->tcpi_min_rtt = tcp_min_rtt(tp);
  2762. info->tcpi_data_segs_in = tp->data_segs_in;
  2763. info->tcpi_data_segs_out = tp->data_segs_out;
  2764. info->tcpi_delivery_rate_app_limited = tp->rate_app_limited ? 1 : 0;
  2765. rate64 = tcp_compute_delivery_rate(tp);
  2766. if (rate64)
  2767. info->tcpi_delivery_rate = rate64;
  2768. info->tcpi_delivered = tp->delivered;
  2769. info->tcpi_delivered_ce = tp->delivered_ce;
  2770. unlock_sock_fast(sk, slow);
  2771. }
  2772. EXPORT_SYMBOL_GPL(tcp_get_info);
  2773. struct sk_buff *tcp_get_timestamping_opt_stats(const struct sock *sk)
  2774. {
  2775. const struct tcp_sock *tp = tcp_sk(sk);
  2776. struct sk_buff *stats;
  2777. struct tcp_info info;
  2778. u64 rate64;
  2779. u32 rate;
  2780. stats = alloc_skb(7 * nla_total_size_64bit(sizeof(u64)) +
  2781. 7 * nla_total_size(sizeof(u32)) +
  2782. 3 * nla_total_size(sizeof(u8)), GFP_ATOMIC);
  2783. if (!stats)
  2784. return NULL;
  2785. tcp_get_info_chrono_stats(tp, &info);
  2786. nla_put_u64_64bit(stats, TCP_NLA_BUSY,
  2787. info.tcpi_busy_time, TCP_NLA_PAD);
  2788. nla_put_u64_64bit(stats, TCP_NLA_RWND_LIMITED,
  2789. info.tcpi_rwnd_limited, TCP_NLA_PAD);
  2790. nla_put_u64_64bit(stats, TCP_NLA_SNDBUF_LIMITED,
  2791. info.tcpi_sndbuf_limited, TCP_NLA_PAD);
  2792. nla_put_u64_64bit(stats, TCP_NLA_DATA_SEGS_OUT,
  2793. tp->data_segs_out, TCP_NLA_PAD);
  2794. nla_put_u64_64bit(stats, TCP_NLA_TOTAL_RETRANS,
  2795. tp->total_retrans, TCP_NLA_PAD);
  2796. rate = READ_ONCE(sk->sk_pacing_rate);
  2797. rate64 = rate != ~0U ? rate : ~0ULL;
  2798. nla_put_u64_64bit(stats, TCP_NLA_PACING_RATE, rate64, TCP_NLA_PAD);
  2799. rate64 = tcp_compute_delivery_rate(tp);
  2800. nla_put_u64_64bit(stats, TCP_NLA_DELIVERY_RATE, rate64, TCP_NLA_PAD);
  2801. nla_put_u32(stats, TCP_NLA_SND_CWND, tp->snd_cwnd);
  2802. nla_put_u32(stats, TCP_NLA_REORDERING, tp->reordering);
  2803. nla_put_u32(stats, TCP_NLA_MIN_RTT, tcp_min_rtt(tp));
  2804. nla_put_u8(stats, TCP_NLA_RECUR_RETRANS, inet_csk(sk)->icsk_retransmits);
  2805. nla_put_u8(stats, TCP_NLA_DELIVERY_RATE_APP_LMT, !!tp->rate_app_limited);
  2806. nla_put_u32(stats, TCP_NLA_SND_SSTHRESH, tp->snd_ssthresh);
  2807. nla_put_u32(stats, TCP_NLA_DELIVERED, tp->delivered);
  2808. nla_put_u32(stats, TCP_NLA_DELIVERED_CE, tp->delivered_ce);
  2809. nla_put_u32(stats, TCP_NLA_SNDQ_SIZE, tp->write_seq - tp->snd_una);
  2810. nla_put_u8(stats, TCP_NLA_CA_STATE, inet_csk(sk)->icsk_ca_state);
  2811. return stats;
  2812. }
  2813. static int do_tcp_getsockopt(struct sock *sk, int level,
  2814. int optname, char __user *optval, int __user *optlen)
  2815. {
  2816. struct inet_connection_sock *icsk = inet_csk(sk);
  2817. struct tcp_sock *tp = tcp_sk(sk);
  2818. struct net *net = sock_net(sk);
  2819. int val, len;
  2820. if (get_user(len, optlen))
  2821. return -EFAULT;
  2822. len = min_t(unsigned int, len, sizeof(int));
  2823. if (len < 0)
  2824. return -EINVAL;
  2825. switch (optname) {
  2826. case TCP_MAXSEG:
  2827. val = tp->mss_cache;
  2828. if (!val && ((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN)))
  2829. val = tp->rx_opt.user_mss;
  2830. if (tp->repair)
  2831. val = tp->rx_opt.mss_clamp;
  2832. break;
  2833. case TCP_NODELAY:
  2834. val = !!(tp->nonagle&TCP_NAGLE_OFF);
  2835. break;
  2836. case TCP_CORK:
  2837. val = !!(tp->nonagle&TCP_NAGLE_CORK);
  2838. break;
  2839. case TCP_KEEPIDLE:
  2840. val = keepalive_time_when(tp) / HZ;
  2841. break;
  2842. case TCP_KEEPINTVL:
  2843. val = keepalive_intvl_when(tp) / HZ;
  2844. break;
  2845. case TCP_KEEPCNT:
  2846. val = keepalive_probes(tp);
  2847. break;
  2848. case TCP_SYNCNT:
  2849. val = icsk->icsk_syn_retries ? : net->ipv4.sysctl_tcp_syn_retries;
  2850. break;
  2851. case TCP_LINGER2:
  2852. val = tp->linger2;
  2853. if (val >= 0)
  2854. val = (val ? : net->ipv4.sysctl_tcp_fin_timeout) / HZ;
  2855. break;
  2856. case TCP_DEFER_ACCEPT:
  2857. val = retrans_to_secs(icsk->icsk_accept_queue.rskq_defer_accept,
  2858. TCP_TIMEOUT_INIT / HZ, TCP_RTO_MAX / HZ);
  2859. break;
  2860. case TCP_WINDOW_CLAMP:
  2861. val = tp->window_clamp;
  2862. break;
  2863. case TCP_INFO: {
  2864. struct tcp_info info;
  2865. if (get_user(len, optlen))
  2866. return -EFAULT;
  2867. tcp_get_info(sk, &info);
  2868. len = min_t(unsigned int, len, sizeof(info));
  2869. if (put_user(len, optlen))
  2870. return -EFAULT;
  2871. if (copy_to_user(optval, &info, len))
  2872. return -EFAULT;
  2873. return 0;
  2874. }
  2875. case TCP_CC_INFO: {
  2876. const struct tcp_congestion_ops *ca_ops;
  2877. union tcp_cc_info info;
  2878. size_t sz = 0;
  2879. int attr;
  2880. if (get_user(len, optlen))
  2881. return -EFAULT;
  2882. ca_ops = icsk->icsk_ca_ops;
  2883. if (ca_ops && ca_ops->get_info)
  2884. sz = ca_ops->get_info(sk, ~0U, &attr, &info);
  2885. len = min_t(unsigned int, len, sz);
  2886. if (put_user(len, optlen))
  2887. return -EFAULT;
  2888. if (copy_to_user(optval, &info, len))
  2889. return -EFAULT;
  2890. return 0;
  2891. }
  2892. case TCP_QUICKACK:
  2893. val = !icsk->icsk_ack.pingpong;
  2894. break;
  2895. case TCP_CONGESTION:
  2896. if (get_user(len, optlen))
  2897. return -EFAULT;
  2898. len = min_t(unsigned int, len, TCP_CA_NAME_MAX);
  2899. if (put_user(len, optlen))
  2900. return -EFAULT;
  2901. if (copy_to_user(optval, icsk->icsk_ca_ops->name, len))
  2902. return -EFAULT;
  2903. return 0;
  2904. case TCP_ULP:
  2905. if (get_user(len, optlen))
  2906. return -EFAULT;
  2907. len = min_t(unsigned int, len, TCP_ULP_NAME_MAX);
  2908. if (!icsk->icsk_ulp_ops) {
  2909. if (put_user(0, optlen))
  2910. return -EFAULT;
  2911. return 0;
  2912. }
  2913. if (put_user(len, optlen))
  2914. return -EFAULT;
  2915. if (copy_to_user(optval, icsk->icsk_ulp_ops->name, len))
  2916. return -EFAULT;
  2917. return 0;
  2918. case TCP_FASTOPEN_KEY: {
  2919. __u8 key[TCP_FASTOPEN_KEY_LENGTH];
  2920. struct tcp_fastopen_context *ctx;
  2921. if (get_user(len, optlen))
  2922. return -EFAULT;
  2923. rcu_read_lock();
  2924. ctx = rcu_dereference(icsk->icsk_accept_queue.fastopenq.ctx);
  2925. if (ctx)
  2926. memcpy(key, ctx->key, sizeof(key));
  2927. else
  2928. len = 0;
  2929. rcu_read_unlock();
  2930. len = min_t(unsigned int, len, sizeof(key));
  2931. if (put_user(len, optlen))
  2932. return -EFAULT;
  2933. if (copy_to_user(optval, key, len))
  2934. return -EFAULT;
  2935. return 0;
  2936. }
  2937. case TCP_THIN_LINEAR_TIMEOUTS:
  2938. val = tp->thin_lto;
  2939. break;
  2940. case TCP_THIN_DUPACK:
  2941. val = 0;
  2942. break;
  2943. case TCP_REPAIR:
  2944. val = tp->repair;
  2945. break;
  2946. case TCP_REPAIR_QUEUE:
  2947. if (tp->repair)
  2948. val = tp->repair_queue;
  2949. else
  2950. return -EINVAL;
  2951. break;
  2952. case TCP_REPAIR_WINDOW: {
  2953. struct tcp_repair_window opt;
  2954. if (get_user(len, optlen))
  2955. return -EFAULT;
  2956. if (len != sizeof(opt))
  2957. return -EINVAL;
  2958. if (!tp->repair)
  2959. return -EPERM;
  2960. opt.snd_wl1 = tp->snd_wl1;
  2961. opt.snd_wnd = tp->snd_wnd;
  2962. opt.max_window = tp->max_window;
  2963. opt.rcv_wnd = tp->rcv_wnd;
  2964. opt.rcv_wup = tp->rcv_wup;
  2965. if (copy_to_user(optval, &opt, len))
  2966. return -EFAULT;
  2967. return 0;
  2968. }
  2969. case TCP_QUEUE_SEQ:
  2970. if (tp->repair_queue == TCP_SEND_QUEUE)
  2971. val = tp->write_seq;
  2972. else if (tp->repair_queue == TCP_RECV_QUEUE)
  2973. val = tp->rcv_nxt;
  2974. else
  2975. return -EINVAL;
  2976. break;
  2977. case TCP_USER_TIMEOUT:
  2978. val = jiffies_to_msecs(icsk->icsk_user_timeout);
  2979. break;
  2980. case TCP_FASTOPEN:
  2981. val = icsk->icsk_accept_queue.fastopenq.max_qlen;
  2982. break;
  2983. case TCP_FASTOPEN_CONNECT:
  2984. val = tp->fastopen_connect;
  2985. break;
  2986. case TCP_FASTOPEN_NO_COOKIE:
  2987. val = tp->fastopen_no_cookie;
  2988. break;
  2989. case TCP_TIMESTAMP:
  2990. val = tcp_time_stamp_raw() + tp->tsoffset;
  2991. break;
  2992. case TCP_NOTSENT_LOWAT:
  2993. val = tp->notsent_lowat;
  2994. break;
  2995. case TCP_INQ:
  2996. val = tp->recvmsg_inq;
  2997. break;
  2998. case TCP_SAVE_SYN:
  2999. val = tp->save_syn;
  3000. break;
  3001. case TCP_SAVED_SYN: {
  3002. if (get_user(len, optlen))
  3003. return -EFAULT;
  3004. lock_sock(sk);
  3005. if (tp->saved_syn) {
  3006. if (len < tp->saved_syn[0]) {
  3007. if (put_user(tp->saved_syn[0], optlen)) {
  3008. release_sock(sk);
  3009. return -EFAULT;
  3010. }
  3011. release_sock(sk);
  3012. return -EINVAL;
  3013. }
  3014. len = tp->saved_syn[0];
  3015. if (put_user(len, optlen)) {
  3016. release_sock(sk);
  3017. return -EFAULT;
  3018. }
  3019. if (copy_to_user(optval, tp->saved_syn + 1, len)) {
  3020. release_sock(sk);
  3021. return -EFAULT;
  3022. }
  3023. tcp_saved_syn_free(tp);
  3024. release_sock(sk);
  3025. } else {
  3026. release_sock(sk);
  3027. len = 0;
  3028. if (put_user(len, optlen))
  3029. return -EFAULT;
  3030. }
  3031. return 0;
  3032. }
  3033. #ifdef CONFIG_MMU
  3034. case TCP_ZEROCOPY_RECEIVE: {
  3035. struct tcp_zerocopy_receive zc;
  3036. int err;
  3037. if (get_user(len, optlen))
  3038. return -EFAULT;
  3039. if (len != sizeof(zc))
  3040. return -EINVAL;
  3041. if (copy_from_user(&zc, optval, len))
  3042. return -EFAULT;
  3043. lock_sock(sk);
  3044. err = tcp_zerocopy_receive(sk, &zc);
  3045. release_sock(sk);
  3046. if (!err && copy_to_user(optval, &zc, len))
  3047. err = -EFAULT;
  3048. return err;
  3049. }
  3050. #endif
  3051. default:
  3052. return -ENOPROTOOPT;
  3053. }
  3054. if (put_user(len, optlen))
  3055. return -EFAULT;
  3056. if (copy_to_user(optval, &val, len))
  3057. return -EFAULT;
  3058. return 0;
  3059. }
  3060. int tcp_getsockopt(struct sock *sk, int level, int optname, char __user *optval,
  3061. int __user *optlen)
  3062. {
  3063. struct inet_connection_sock *icsk = inet_csk(sk);
  3064. if (level != SOL_TCP)
  3065. return icsk->icsk_af_ops->getsockopt(sk, level, optname,
  3066. optval, optlen);
  3067. return do_tcp_getsockopt(sk, level, optname, optval, optlen);
  3068. }
  3069. EXPORT_SYMBOL(tcp_getsockopt);
  3070. #ifdef CONFIG_COMPAT
  3071. int compat_tcp_getsockopt(struct sock *sk, int level, int optname,
  3072. char __user *optval, int __user *optlen)
  3073. {
  3074. if (level != SOL_TCP)
  3075. return inet_csk_compat_getsockopt(sk, level, optname,
  3076. optval, optlen);
  3077. return do_tcp_getsockopt(sk, level, optname, optval, optlen);
  3078. }
  3079. EXPORT_SYMBOL(compat_tcp_getsockopt);
  3080. #endif
  3081. #ifdef CONFIG_TCP_MD5SIG
  3082. static DEFINE_PER_CPU(struct tcp_md5sig_pool, tcp_md5sig_pool);
  3083. static DEFINE_MUTEX(tcp_md5sig_mutex);
  3084. static bool tcp_md5sig_pool_populated = false;
  3085. static void __tcp_alloc_md5sig_pool(void)
  3086. {
  3087. struct crypto_ahash *hash;
  3088. int cpu;
  3089. hash = crypto_alloc_ahash("md5", 0, CRYPTO_ALG_ASYNC);
  3090. if (IS_ERR(hash))
  3091. return;
  3092. for_each_possible_cpu(cpu) {
  3093. void *scratch = per_cpu(tcp_md5sig_pool, cpu).scratch;
  3094. struct ahash_request *req;
  3095. if (!scratch) {
  3096. scratch = kmalloc_node(sizeof(union tcp_md5sum_block) +
  3097. sizeof(struct tcphdr),
  3098. GFP_KERNEL,
  3099. cpu_to_node(cpu));
  3100. if (!scratch)
  3101. return;
  3102. per_cpu(tcp_md5sig_pool, cpu).scratch = scratch;
  3103. }
  3104. if (per_cpu(tcp_md5sig_pool, cpu).md5_req)
  3105. continue;
  3106. req = ahash_request_alloc(hash, GFP_KERNEL);
  3107. if (!req)
  3108. return;
  3109. ahash_request_set_callback(req, 0, NULL, NULL);
  3110. per_cpu(tcp_md5sig_pool, cpu).md5_req = req;
  3111. }
  3112. /* before setting tcp_md5sig_pool_populated, we must commit all writes
  3113. * to memory. See smp_rmb() in tcp_get_md5sig_pool()
  3114. */
  3115. smp_wmb();
  3116. tcp_md5sig_pool_populated = true;
  3117. }
  3118. bool tcp_alloc_md5sig_pool(void)
  3119. {
  3120. if (unlikely(!tcp_md5sig_pool_populated)) {
  3121. mutex_lock(&tcp_md5sig_mutex);
  3122. if (!tcp_md5sig_pool_populated)
  3123. __tcp_alloc_md5sig_pool();
  3124. mutex_unlock(&tcp_md5sig_mutex);
  3125. }
  3126. return tcp_md5sig_pool_populated;
  3127. }
  3128. EXPORT_SYMBOL(tcp_alloc_md5sig_pool);
  3129. /**
  3130. * tcp_get_md5sig_pool - get md5sig_pool for this user
  3131. *
  3132. * We use percpu structure, so if we succeed, we exit with preemption
  3133. * and BH disabled, to make sure another thread or softirq handling
  3134. * wont try to get same context.
  3135. */
  3136. struct tcp_md5sig_pool *tcp_get_md5sig_pool(void)
  3137. {
  3138. local_bh_disable();
  3139. if (tcp_md5sig_pool_populated) {
  3140. /* coupled with smp_wmb() in __tcp_alloc_md5sig_pool() */
  3141. smp_rmb();
  3142. return this_cpu_ptr(&tcp_md5sig_pool);
  3143. }
  3144. local_bh_enable();
  3145. return NULL;
  3146. }
  3147. EXPORT_SYMBOL(tcp_get_md5sig_pool);
  3148. int tcp_md5_hash_skb_data(struct tcp_md5sig_pool *hp,
  3149. const struct sk_buff *skb, unsigned int header_len)
  3150. {
  3151. struct scatterlist sg;
  3152. const struct tcphdr *tp = tcp_hdr(skb);
  3153. struct ahash_request *req = hp->md5_req;
  3154. unsigned int i;
  3155. const unsigned int head_data_len = skb_headlen(skb) > header_len ?
  3156. skb_headlen(skb) - header_len : 0;
  3157. const struct skb_shared_info *shi = skb_shinfo(skb);
  3158. struct sk_buff *frag_iter;
  3159. sg_init_table(&sg, 1);
  3160. sg_set_buf(&sg, ((u8 *) tp) + header_len, head_data_len);
  3161. ahash_request_set_crypt(req, &sg, NULL, head_data_len);
  3162. if (crypto_ahash_update(req))
  3163. return 1;
  3164. for (i = 0; i < shi->nr_frags; ++i) {
  3165. const struct skb_frag_struct *f = &shi->frags[i];
  3166. unsigned int offset = f->page_offset;
  3167. struct page *page = skb_frag_page(f) + (offset >> PAGE_SHIFT);
  3168. sg_set_page(&sg, page, skb_frag_size(f),
  3169. offset_in_page(offset));
  3170. ahash_request_set_crypt(req, &sg, NULL, skb_frag_size(f));
  3171. if (crypto_ahash_update(req))
  3172. return 1;
  3173. }
  3174. skb_walk_frags(skb, frag_iter)
  3175. if (tcp_md5_hash_skb_data(hp, frag_iter, 0))
  3176. return 1;
  3177. return 0;
  3178. }
  3179. EXPORT_SYMBOL(tcp_md5_hash_skb_data);
  3180. int tcp_md5_hash_key(struct tcp_md5sig_pool *hp, const struct tcp_md5sig_key *key)
  3181. {
  3182. struct scatterlist sg;
  3183. sg_init_one(&sg, key->key, key->keylen);
  3184. ahash_request_set_crypt(hp->md5_req, &sg, NULL, key->keylen);
  3185. return crypto_ahash_update(hp->md5_req);
  3186. }
  3187. EXPORT_SYMBOL(tcp_md5_hash_key);
  3188. #endif
  3189. void tcp_done(struct sock *sk)
  3190. {
  3191. struct request_sock *req = tcp_sk(sk)->fastopen_rsk;
  3192. if (sk->sk_state == TCP_SYN_SENT || sk->sk_state == TCP_SYN_RECV)
  3193. TCP_INC_STATS(sock_net(sk), TCP_MIB_ATTEMPTFAILS);
  3194. tcp_set_state(sk, TCP_CLOSE);
  3195. tcp_clear_xmit_timers(sk);
  3196. if (req)
  3197. reqsk_fastopen_remove(sk, req, false);
  3198. sk->sk_shutdown = SHUTDOWN_MASK;
  3199. if (!sock_flag(sk, SOCK_DEAD))
  3200. sk->sk_state_change(sk);
  3201. else
  3202. inet_csk_destroy_sock(sk);
  3203. }
  3204. EXPORT_SYMBOL_GPL(tcp_done);
  3205. int tcp_abort(struct sock *sk, int err)
  3206. {
  3207. if (!sk_fullsock(sk)) {
  3208. if (sk->sk_state == TCP_NEW_SYN_RECV) {
  3209. struct request_sock *req = inet_reqsk(sk);
  3210. local_bh_disable();
  3211. inet_csk_reqsk_queue_drop_and_put(req->rsk_listener,
  3212. req);
  3213. local_bh_enable();
  3214. return 0;
  3215. }
  3216. return -EOPNOTSUPP;
  3217. }
  3218. /* Don't race with userspace socket closes such as tcp_close. */
  3219. lock_sock(sk);
  3220. if (sk->sk_state == TCP_LISTEN) {
  3221. tcp_set_state(sk, TCP_CLOSE);
  3222. inet_csk_listen_stop(sk);
  3223. }
  3224. /* Don't race with BH socket closes such as inet_csk_listen_stop. */
  3225. local_bh_disable();
  3226. bh_lock_sock(sk);
  3227. if (!sock_flag(sk, SOCK_DEAD)) {
  3228. sk->sk_err = err;
  3229. /* This barrier is coupled with smp_rmb() in tcp_poll() */
  3230. smp_wmb();
  3231. sk->sk_error_report(sk);
  3232. if (tcp_need_reset(sk->sk_state))
  3233. tcp_send_active_reset(sk, GFP_ATOMIC);
  3234. tcp_done(sk);
  3235. }
  3236. bh_unlock_sock(sk);
  3237. local_bh_enable();
  3238. tcp_write_queue_purge(sk);
  3239. release_sock(sk);
  3240. return 0;
  3241. }
  3242. EXPORT_SYMBOL_GPL(tcp_abort);
  3243. extern struct tcp_congestion_ops tcp_reno;
  3244. static __initdata unsigned long thash_entries;
  3245. static int __init set_thash_entries(char *str)
  3246. {
  3247. ssize_t ret;
  3248. if (!str)
  3249. return 0;
  3250. ret = kstrtoul(str, 0, &thash_entries);
  3251. if (ret)
  3252. return 0;
  3253. return 1;
  3254. }
  3255. __setup("thash_entries=", set_thash_entries);
  3256. static void __init tcp_init_mem(void)
  3257. {
  3258. unsigned long limit = nr_free_buffer_pages() / 16;
  3259. limit = max(limit, 128UL);
  3260. sysctl_tcp_mem[0] = limit / 4 * 3; /* 4.68 % */
  3261. sysctl_tcp_mem[1] = limit; /* 6.25 % */
  3262. sysctl_tcp_mem[2] = sysctl_tcp_mem[0] * 2; /* 9.37 % */
  3263. }
  3264. void __init tcp_init(void)
  3265. {
  3266. int max_rshare, max_wshare, cnt;
  3267. unsigned long limit;
  3268. unsigned int i;
  3269. BUILD_BUG_ON(sizeof(struct tcp_skb_cb) >
  3270. FIELD_SIZEOF(struct sk_buff, cb));
  3271. percpu_counter_init(&tcp_sockets_allocated, 0, GFP_KERNEL);
  3272. percpu_counter_init(&tcp_orphan_count, 0, GFP_KERNEL);
  3273. inet_hashinfo_init(&tcp_hashinfo);
  3274. inet_hashinfo2_init(&tcp_hashinfo, "tcp_listen_portaddr_hash",
  3275. thash_entries, 21, /* one slot per 2 MB*/
  3276. 0, 64 * 1024);
  3277. tcp_hashinfo.bind_bucket_cachep =
  3278. kmem_cache_create("tcp_bind_bucket",
  3279. sizeof(struct inet_bind_bucket), 0,
  3280. SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL);
  3281. /* Size and allocate the main established and bind bucket
  3282. * hash tables.
  3283. *
  3284. * The methodology is similar to that of the buffer cache.
  3285. */
  3286. tcp_hashinfo.ehash =
  3287. alloc_large_system_hash("TCP established",
  3288. sizeof(struct inet_ehash_bucket),
  3289. thash_entries,
  3290. 17, /* one slot per 128 KB of memory */
  3291. 0,
  3292. NULL,
  3293. &tcp_hashinfo.ehash_mask,
  3294. 0,
  3295. thash_entries ? 0 : 512 * 1024);
  3296. for (i = 0; i <= tcp_hashinfo.ehash_mask; i++)
  3297. INIT_HLIST_NULLS_HEAD(&tcp_hashinfo.ehash[i].chain, i);
  3298. if (inet_ehash_locks_alloc(&tcp_hashinfo))
  3299. panic("TCP: failed to alloc ehash_locks");
  3300. tcp_hashinfo.bhash =
  3301. alloc_large_system_hash("TCP bind",
  3302. sizeof(struct inet_bind_hashbucket),
  3303. tcp_hashinfo.ehash_mask + 1,
  3304. 17, /* one slot per 128 KB of memory */
  3305. 0,
  3306. &tcp_hashinfo.bhash_size,
  3307. NULL,
  3308. 0,
  3309. 64 * 1024);
  3310. tcp_hashinfo.bhash_size = 1U << tcp_hashinfo.bhash_size;
  3311. for (i = 0; i < tcp_hashinfo.bhash_size; i++) {
  3312. spin_lock_init(&tcp_hashinfo.bhash[i].lock);
  3313. INIT_HLIST_HEAD(&tcp_hashinfo.bhash[i].chain);
  3314. }
  3315. cnt = tcp_hashinfo.ehash_mask + 1;
  3316. sysctl_tcp_max_orphans = cnt / 2;
  3317. tcp_init_mem();
  3318. /* Set per-socket limits to no more than 1/128 the pressure threshold */
  3319. limit = nr_free_buffer_pages() << (PAGE_SHIFT - 7);
  3320. max_wshare = min(4UL*1024*1024, limit);
  3321. max_rshare = min(6UL*1024*1024, limit);
  3322. init_net.ipv4.sysctl_tcp_wmem[0] = SK_MEM_QUANTUM;
  3323. init_net.ipv4.sysctl_tcp_wmem[1] = 16*1024;
  3324. init_net.ipv4.sysctl_tcp_wmem[2] = max(64*1024, max_wshare);
  3325. init_net.ipv4.sysctl_tcp_rmem[0] = SK_MEM_QUANTUM;
  3326. init_net.ipv4.sysctl_tcp_rmem[1] = 87380;
  3327. init_net.ipv4.sysctl_tcp_rmem[2] = max(87380, max_rshare);
  3328. pr_info("Hash tables configured (established %u bind %u)\n",
  3329. tcp_hashinfo.ehash_mask + 1, tcp_hashinfo.bhash_size);
  3330. tcp_v4_init();
  3331. tcp_metrics_init();
  3332. BUG_ON(tcp_register_congestion_control(&tcp_reno) != 0);
  3333. tcp_tasklet_init();
  3334. }