tcp.c 95 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684
  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. /*
  447. * Wait for a TCP event.
  448. *
  449. * Note that we don't need to lock the socket, as the upper poll layers
  450. * take care of normal races (between the test and the event) and we don't
  451. * go look at any of the socket buffers directly.
  452. */
  453. __poll_t tcp_poll(struct file *file, struct socket *sock, poll_table *wait)
  454. {
  455. __poll_t mask;
  456. struct sock *sk = sock->sk;
  457. const struct tcp_sock *tp = tcp_sk(sk);
  458. int state;
  459. sock_poll_wait(file, sk_sleep(sk), wait);
  460. state = inet_sk_state_load(sk);
  461. if (state == TCP_LISTEN)
  462. return inet_csk_listen_poll(sk);
  463. /* Socket is not locked. We are protected from async events
  464. * by poll logic and correct handling of state changes
  465. * made by other threads is impossible in any case.
  466. */
  467. mask = 0;
  468. /*
  469. * EPOLLHUP is certainly not done right. But poll() doesn't
  470. * have a notion of HUP in just one direction, and for a
  471. * socket the read side is more interesting.
  472. *
  473. * Some poll() documentation says that EPOLLHUP is incompatible
  474. * with the EPOLLOUT/POLLWR flags, so somebody should check this
  475. * all. But careful, it tends to be safer to return too many
  476. * bits than too few, and you can easily break real applications
  477. * if you don't tell them that something has hung up!
  478. *
  479. * Check-me.
  480. *
  481. * Check number 1. EPOLLHUP is _UNMASKABLE_ event (see UNIX98 and
  482. * our fs/select.c). It means that after we received EOF,
  483. * poll always returns immediately, making impossible poll() on write()
  484. * in state CLOSE_WAIT. One solution is evident --- to set EPOLLHUP
  485. * if and only if shutdown has been made in both directions.
  486. * Actually, it is interesting to look how Solaris and DUX
  487. * solve this dilemma. I would prefer, if EPOLLHUP were maskable,
  488. * then we could set it on SND_SHUTDOWN. BTW examples given
  489. * in Stevens' books assume exactly this behaviour, it explains
  490. * why EPOLLHUP is incompatible with EPOLLOUT. --ANK
  491. *
  492. * NOTE. Check for TCP_CLOSE is added. The goal is to prevent
  493. * blocking on fresh not-connected or disconnected socket. --ANK
  494. */
  495. if (sk->sk_shutdown == SHUTDOWN_MASK || state == TCP_CLOSE)
  496. mask |= EPOLLHUP;
  497. if (sk->sk_shutdown & RCV_SHUTDOWN)
  498. mask |= EPOLLIN | EPOLLRDNORM | EPOLLRDHUP;
  499. /* Connected or passive Fast Open socket? */
  500. if (state != TCP_SYN_SENT &&
  501. (state != TCP_SYN_RECV || tp->fastopen_rsk)) {
  502. int target = sock_rcvlowat(sk, 0, INT_MAX);
  503. if (tp->urg_seq == tp->copied_seq &&
  504. !sock_flag(sk, SOCK_URGINLINE) &&
  505. tp->urg_data)
  506. target++;
  507. if (tp->rcv_nxt - tp->copied_seq >= target)
  508. mask |= EPOLLIN | EPOLLRDNORM;
  509. if (!(sk->sk_shutdown & SEND_SHUTDOWN)) {
  510. if (sk_stream_is_writeable(sk)) {
  511. mask |= EPOLLOUT | EPOLLWRNORM;
  512. } else { /* send SIGIO later */
  513. sk_set_bit(SOCKWQ_ASYNC_NOSPACE, sk);
  514. set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
  515. /* Race breaker. If space is freed after
  516. * wspace test but before the flags are set,
  517. * IO signal will be lost. Memory barrier
  518. * pairs with the input side.
  519. */
  520. smp_mb__after_atomic();
  521. if (sk_stream_is_writeable(sk))
  522. mask |= EPOLLOUT | EPOLLWRNORM;
  523. }
  524. } else
  525. mask |= EPOLLOUT | EPOLLWRNORM;
  526. if (tp->urg_data & TCP_URG_VALID)
  527. mask |= EPOLLPRI;
  528. } else if (state == TCP_SYN_SENT && inet_sk(sk)->defer_connect) {
  529. /* Active TCP fastopen socket with defer_connect
  530. * Return EPOLLOUT so application can call write()
  531. * in order for kernel to generate SYN+data
  532. */
  533. mask |= EPOLLOUT | EPOLLWRNORM;
  534. }
  535. /* This barrier is coupled with smp_wmb() in tcp_reset() */
  536. smp_rmb();
  537. if (sk->sk_err || !skb_queue_empty(&sk->sk_error_queue))
  538. mask |= EPOLLERR;
  539. return mask;
  540. }
  541. EXPORT_SYMBOL(tcp_poll);
  542. int tcp_ioctl(struct sock *sk, int cmd, unsigned long arg)
  543. {
  544. struct tcp_sock *tp = tcp_sk(sk);
  545. int answ;
  546. bool slow;
  547. switch (cmd) {
  548. case SIOCINQ:
  549. if (sk->sk_state == TCP_LISTEN)
  550. return -EINVAL;
  551. slow = lock_sock_fast(sk);
  552. answ = tcp_inq(sk);
  553. unlock_sock_fast(sk, slow);
  554. break;
  555. case SIOCATMARK:
  556. answ = tp->urg_data && tp->urg_seq == tp->copied_seq;
  557. break;
  558. case SIOCOUTQ:
  559. if (sk->sk_state == TCP_LISTEN)
  560. return -EINVAL;
  561. if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV))
  562. answ = 0;
  563. else
  564. answ = tp->write_seq - tp->snd_una;
  565. break;
  566. case SIOCOUTQNSD:
  567. if (sk->sk_state == TCP_LISTEN)
  568. return -EINVAL;
  569. if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV))
  570. answ = 0;
  571. else
  572. answ = tp->write_seq - tp->snd_nxt;
  573. break;
  574. default:
  575. return -ENOIOCTLCMD;
  576. }
  577. return put_user(answ, (int __user *)arg);
  578. }
  579. EXPORT_SYMBOL(tcp_ioctl);
  580. static inline void tcp_mark_push(struct tcp_sock *tp, struct sk_buff *skb)
  581. {
  582. TCP_SKB_CB(skb)->tcp_flags |= TCPHDR_PSH;
  583. tp->pushed_seq = tp->write_seq;
  584. }
  585. static inline bool forced_push(const struct tcp_sock *tp)
  586. {
  587. return after(tp->write_seq, tp->pushed_seq + (tp->max_window >> 1));
  588. }
  589. static void skb_entail(struct sock *sk, struct sk_buff *skb)
  590. {
  591. struct tcp_sock *tp = tcp_sk(sk);
  592. struct tcp_skb_cb *tcb = TCP_SKB_CB(skb);
  593. skb->csum = 0;
  594. tcb->seq = tcb->end_seq = tp->write_seq;
  595. tcb->tcp_flags = TCPHDR_ACK;
  596. tcb->sacked = 0;
  597. __skb_header_release(skb);
  598. tcp_add_write_queue_tail(sk, skb);
  599. sk->sk_wmem_queued += skb->truesize;
  600. sk_mem_charge(sk, skb->truesize);
  601. if (tp->nonagle & TCP_NAGLE_PUSH)
  602. tp->nonagle &= ~TCP_NAGLE_PUSH;
  603. tcp_slow_start_after_idle_check(sk);
  604. }
  605. static inline void tcp_mark_urg(struct tcp_sock *tp, int flags)
  606. {
  607. if (flags & MSG_OOB)
  608. tp->snd_up = tp->write_seq;
  609. }
  610. /* If a not yet filled skb is pushed, do not send it if
  611. * we have data packets in Qdisc or NIC queues :
  612. * Because TX completion will happen shortly, it gives a chance
  613. * to coalesce future sendmsg() payload into this skb, without
  614. * need for a timer, and with no latency trade off.
  615. * As packets containing data payload have a bigger truesize
  616. * than pure acks (dataless) packets, the last checks prevent
  617. * autocorking if we only have an ACK in Qdisc/NIC queues,
  618. * or if TX completion was delayed after we processed ACK packet.
  619. */
  620. static bool tcp_should_autocork(struct sock *sk, struct sk_buff *skb,
  621. int size_goal)
  622. {
  623. return skb->len < size_goal &&
  624. sock_net(sk)->ipv4.sysctl_tcp_autocorking &&
  625. skb != tcp_write_queue_head(sk) &&
  626. refcount_read(&sk->sk_wmem_alloc) > skb->truesize;
  627. }
  628. static void tcp_push(struct sock *sk, int flags, int mss_now,
  629. int nonagle, int size_goal)
  630. {
  631. struct tcp_sock *tp = tcp_sk(sk);
  632. struct sk_buff *skb;
  633. skb = tcp_write_queue_tail(sk);
  634. if (!skb)
  635. return;
  636. if (!(flags & MSG_MORE) || forced_push(tp))
  637. tcp_mark_push(tp, skb);
  638. tcp_mark_urg(tp, flags);
  639. if (tcp_should_autocork(sk, skb, size_goal)) {
  640. /* avoid atomic op if TSQ_THROTTLED bit is already set */
  641. if (!test_bit(TSQ_THROTTLED, &sk->sk_tsq_flags)) {
  642. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPAUTOCORKING);
  643. set_bit(TSQ_THROTTLED, &sk->sk_tsq_flags);
  644. }
  645. /* It is possible TX completion already happened
  646. * before we set TSQ_THROTTLED.
  647. */
  648. if (refcount_read(&sk->sk_wmem_alloc) > skb->truesize)
  649. return;
  650. }
  651. if (flags & MSG_MORE)
  652. nonagle = TCP_NAGLE_CORK;
  653. __tcp_push_pending_frames(sk, mss_now, nonagle);
  654. }
  655. static int tcp_splice_data_recv(read_descriptor_t *rd_desc, struct sk_buff *skb,
  656. unsigned int offset, size_t len)
  657. {
  658. struct tcp_splice_state *tss = rd_desc->arg.data;
  659. int ret;
  660. ret = skb_splice_bits(skb, skb->sk, offset, tss->pipe,
  661. min(rd_desc->count, len), tss->flags);
  662. if (ret > 0)
  663. rd_desc->count -= ret;
  664. return ret;
  665. }
  666. static int __tcp_splice_read(struct sock *sk, struct tcp_splice_state *tss)
  667. {
  668. /* Store TCP splice context information in read_descriptor_t. */
  669. read_descriptor_t rd_desc = {
  670. .arg.data = tss,
  671. .count = tss->len,
  672. };
  673. return tcp_read_sock(sk, &rd_desc, tcp_splice_data_recv);
  674. }
  675. /**
  676. * tcp_splice_read - splice data from TCP socket to a pipe
  677. * @sock: socket to splice from
  678. * @ppos: position (not valid)
  679. * @pipe: pipe to splice to
  680. * @len: number of bytes to splice
  681. * @flags: splice modifier flags
  682. *
  683. * Description:
  684. * Will read pages from given socket and fill them into a pipe.
  685. *
  686. **/
  687. ssize_t tcp_splice_read(struct socket *sock, loff_t *ppos,
  688. struct pipe_inode_info *pipe, size_t len,
  689. unsigned int flags)
  690. {
  691. struct sock *sk = sock->sk;
  692. struct tcp_splice_state tss = {
  693. .pipe = pipe,
  694. .len = len,
  695. .flags = flags,
  696. };
  697. long timeo;
  698. ssize_t spliced;
  699. int ret;
  700. sock_rps_record_flow(sk);
  701. /*
  702. * We can't seek on a socket input
  703. */
  704. if (unlikely(*ppos))
  705. return -ESPIPE;
  706. ret = spliced = 0;
  707. lock_sock(sk);
  708. timeo = sock_rcvtimeo(sk, sock->file->f_flags & O_NONBLOCK);
  709. while (tss.len) {
  710. ret = __tcp_splice_read(sk, &tss);
  711. if (ret < 0)
  712. break;
  713. else if (!ret) {
  714. if (spliced)
  715. break;
  716. if (sock_flag(sk, SOCK_DONE))
  717. break;
  718. if (sk->sk_err) {
  719. ret = sock_error(sk);
  720. break;
  721. }
  722. if (sk->sk_shutdown & RCV_SHUTDOWN)
  723. break;
  724. if (sk->sk_state == TCP_CLOSE) {
  725. /*
  726. * This occurs when user tries to read
  727. * from never connected socket.
  728. */
  729. if (!sock_flag(sk, SOCK_DONE))
  730. ret = -ENOTCONN;
  731. break;
  732. }
  733. if (!timeo) {
  734. ret = -EAGAIN;
  735. break;
  736. }
  737. /* if __tcp_splice_read() got nothing while we have
  738. * an skb in receive queue, we do not want to loop.
  739. * This might happen with URG data.
  740. */
  741. if (!skb_queue_empty(&sk->sk_receive_queue))
  742. break;
  743. sk_wait_data(sk, &timeo, NULL);
  744. if (signal_pending(current)) {
  745. ret = sock_intr_errno(timeo);
  746. break;
  747. }
  748. continue;
  749. }
  750. tss.len -= ret;
  751. spliced += ret;
  752. if (!timeo)
  753. break;
  754. release_sock(sk);
  755. lock_sock(sk);
  756. if (sk->sk_err || sk->sk_state == TCP_CLOSE ||
  757. (sk->sk_shutdown & RCV_SHUTDOWN) ||
  758. signal_pending(current))
  759. break;
  760. }
  761. release_sock(sk);
  762. if (spliced)
  763. return spliced;
  764. return ret;
  765. }
  766. EXPORT_SYMBOL(tcp_splice_read);
  767. struct sk_buff *sk_stream_alloc_skb(struct sock *sk, int size, gfp_t gfp,
  768. bool force_schedule)
  769. {
  770. struct sk_buff *skb;
  771. /* The TCP header must be at least 32-bit aligned. */
  772. size = ALIGN(size, 4);
  773. if (unlikely(tcp_under_memory_pressure(sk)))
  774. sk_mem_reclaim_partial(sk);
  775. skb = alloc_skb_fclone(size + sk->sk_prot->max_header, gfp);
  776. if (likely(skb)) {
  777. bool mem_scheduled;
  778. if (force_schedule) {
  779. mem_scheduled = true;
  780. sk_forced_mem_schedule(sk, skb->truesize);
  781. } else {
  782. mem_scheduled = sk_wmem_schedule(sk, skb->truesize);
  783. }
  784. if (likely(mem_scheduled)) {
  785. skb_reserve(skb, sk->sk_prot->max_header);
  786. /*
  787. * Make sure that we have exactly size bytes
  788. * available to the caller, no more, no less.
  789. */
  790. skb->reserved_tailroom = skb->end - skb->tail - size;
  791. INIT_LIST_HEAD(&skb->tcp_tsorted_anchor);
  792. return skb;
  793. }
  794. __kfree_skb(skb);
  795. } else {
  796. sk->sk_prot->enter_memory_pressure(sk);
  797. sk_stream_moderate_sndbuf(sk);
  798. }
  799. return NULL;
  800. }
  801. static unsigned int tcp_xmit_size_goal(struct sock *sk, u32 mss_now,
  802. int large_allowed)
  803. {
  804. struct tcp_sock *tp = tcp_sk(sk);
  805. u32 new_size_goal, size_goal;
  806. if (!large_allowed || !sk_can_gso(sk))
  807. return mss_now;
  808. /* Note : tcp_tso_autosize() will eventually split this later */
  809. new_size_goal = sk->sk_gso_max_size - 1 - MAX_TCP_HEADER;
  810. new_size_goal = tcp_bound_to_half_wnd(tp, new_size_goal);
  811. /* We try hard to avoid divides here */
  812. size_goal = tp->gso_segs * mss_now;
  813. if (unlikely(new_size_goal < size_goal ||
  814. new_size_goal >= size_goal + mss_now)) {
  815. tp->gso_segs = min_t(u16, new_size_goal / mss_now,
  816. sk->sk_gso_max_segs);
  817. size_goal = tp->gso_segs * mss_now;
  818. }
  819. return max(size_goal, mss_now);
  820. }
  821. static int tcp_send_mss(struct sock *sk, int *size_goal, int flags)
  822. {
  823. int mss_now;
  824. mss_now = tcp_current_mss(sk);
  825. *size_goal = tcp_xmit_size_goal(sk, mss_now, !(flags & MSG_OOB));
  826. return mss_now;
  827. }
  828. ssize_t do_tcp_sendpages(struct sock *sk, struct page *page, int offset,
  829. size_t size, int flags)
  830. {
  831. struct tcp_sock *tp = tcp_sk(sk);
  832. int mss_now, size_goal;
  833. int err;
  834. ssize_t copied;
  835. long timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT);
  836. /* Wait for a connection to finish. One exception is TCP Fast Open
  837. * (passive side) where data is allowed to be sent before a connection
  838. * is fully established.
  839. */
  840. if (((1 << sk->sk_state) & ~(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT)) &&
  841. !tcp_passive_fastopen(sk)) {
  842. err = sk_stream_wait_connect(sk, &timeo);
  843. if (err != 0)
  844. goto out_err;
  845. }
  846. sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk);
  847. mss_now = tcp_send_mss(sk, &size_goal, flags);
  848. copied = 0;
  849. err = -EPIPE;
  850. if (sk->sk_err || (sk->sk_shutdown & SEND_SHUTDOWN))
  851. goto out_err;
  852. while (size > 0) {
  853. struct sk_buff *skb = tcp_write_queue_tail(sk);
  854. int copy, i;
  855. bool can_coalesce;
  856. if (!skb || (copy = size_goal - skb->len) <= 0 ||
  857. !tcp_skb_can_collapse_to(skb)) {
  858. new_segment:
  859. if (!sk_stream_memory_free(sk))
  860. goto wait_for_sndbuf;
  861. skb = sk_stream_alloc_skb(sk, 0, sk->sk_allocation,
  862. tcp_rtx_and_write_queues_empty(sk));
  863. if (!skb)
  864. goto wait_for_memory;
  865. skb_entail(sk, skb);
  866. copy = size_goal;
  867. }
  868. if (copy > size)
  869. copy = size;
  870. i = skb_shinfo(skb)->nr_frags;
  871. can_coalesce = skb_can_coalesce(skb, i, page, offset);
  872. if (!can_coalesce && i >= sysctl_max_skb_frags) {
  873. tcp_mark_push(tp, skb);
  874. goto new_segment;
  875. }
  876. if (!sk_wmem_schedule(sk, copy))
  877. goto wait_for_memory;
  878. if (can_coalesce) {
  879. skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy);
  880. } else {
  881. get_page(page);
  882. skb_fill_page_desc(skb, i, page, offset, copy);
  883. }
  884. skb_shinfo(skb)->tx_flags |= SKBTX_SHARED_FRAG;
  885. skb->len += copy;
  886. skb->data_len += copy;
  887. skb->truesize += copy;
  888. sk->sk_wmem_queued += copy;
  889. sk_mem_charge(sk, copy);
  890. skb->ip_summed = CHECKSUM_PARTIAL;
  891. tp->write_seq += copy;
  892. TCP_SKB_CB(skb)->end_seq += copy;
  893. tcp_skb_pcount_set(skb, 0);
  894. if (!copied)
  895. TCP_SKB_CB(skb)->tcp_flags &= ~TCPHDR_PSH;
  896. copied += copy;
  897. offset += copy;
  898. size -= copy;
  899. if (!size)
  900. goto out;
  901. if (skb->len < size_goal || (flags & MSG_OOB))
  902. continue;
  903. if (forced_push(tp)) {
  904. tcp_mark_push(tp, skb);
  905. __tcp_push_pending_frames(sk, mss_now, TCP_NAGLE_PUSH);
  906. } else if (skb == tcp_send_head(sk))
  907. tcp_push_one(sk, mss_now);
  908. continue;
  909. wait_for_sndbuf:
  910. set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
  911. wait_for_memory:
  912. tcp_push(sk, flags & ~MSG_MORE, mss_now,
  913. TCP_NAGLE_PUSH, size_goal);
  914. err = sk_stream_wait_memory(sk, &timeo);
  915. if (err != 0)
  916. goto do_error;
  917. mss_now = tcp_send_mss(sk, &size_goal, flags);
  918. }
  919. out:
  920. if (copied) {
  921. tcp_tx_timestamp(sk, sk->sk_tsflags);
  922. if (!(flags & MSG_SENDPAGE_NOTLAST))
  923. tcp_push(sk, flags, mss_now, tp->nonagle, size_goal);
  924. }
  925. return copied;
  926. do_error:
  927. if (copied)
  928. goto out;
  929. out_err:
  930. /* make sure we wake any epoll edge trigger waiter */
  931. if (unlikely(skb_queue_len(&sk->sk_write_queue) == 0 &&
  932. err == -EAGAIN)) {
  933. sk->sk_write_space(sk);
  934. tcp_chrono_stop(sk, TCP_CHRONO_SNDBUF_LIMITED);
  935. }
  936. return sk_stream_error(sk, flags, err);
  937. }
  938. EXPORT_SYMBOL_GPL(do_tcp_sendpages);
  939. int tcp_sendpage_locked(struct sock *sk, struct page *page, int offset,
  940. size_t size, int flags)
  941. {
  942. if (!(sk->sk_route_caps & NETIF_F_SG) ||
  943. !sk_check_csum_caps(sk))
  944. return sock_no_sendpage_locked(sk, page, offset, size, flags);
  945. tcp_rate_check_app_limited(sk); /* is sending application-limited? */
  946. return do_tcp_sendpages(sk, page, offset, size, flags);
  947. }
  948. EXPORT_SYMBOL_GPL(tcp_sendpage_locked);
  949. int tcp_sendpage(struct sock *sk, struct page *page, int offset,
  950. size_t size, int flags)
  951. {
  952. int ret;
  953. lock_sock(sk);
  954. ret = tcp_sendpage_locked(sk, page, offset, size, flags);
  955. release_sock(sk);
  956. return ret;
  957. }
  958. EXPORT_SYMBOL(tcp_sendpage);
  959. /* Do not bother using a page frag for very small frames.
  960. * But use this heuristic only for the first skb in write queue.
  961. *
  962. * Having no payload in skb->head allows better SACK shifting
  963. * in tcp_shift_skb_data(), reducing sack/rack overhead, because
  964. * write queue has less skbs.
  965. * Each skb can hold up to MAX_SKB_FRAGS * 32Kbytes, or ~0.5 MB.
  966. * This also speeds up tso_fragment(), since it wont fallback
  967. * to tcp_fragment().
  968. */
  969. static int linear_payload_sz(bool first_skb)
  970. {
  971. if (first_skb)
  972. return SKB_WITH_OVERHEAD(2048 - MAX_TCP_HEADER);
  973. return 0;
  974. }
  975. static int select_size(const struct sock *sk, bool sg, bool first_skb, bool zc)
  976. {
  977. const struct tcp_sock *tp = tcp_sk(sk);
  978. int tmp = tp->mss_cache;
  979. if (sg) {
  980. if (zc)
  981. return 0;
  982. if (sk_can_gso(sk)) {
  983. tmp = linear_payload_sz(first_skb);
  984. } else {
  985. int pgbreak = SKB_MAX_HEAD(MAX_TCP_HEADER);
  986. if (tmp >= pgbreak &&
  987. tmp <= pgbreak + (MAX_SKB_FRAGS - 1) * PAGE_SIZE)
  988. tmp = pgbreak;
  989. }
  990. }
  991. return tmp;
  992. }
  993. void tcp_free_fastopen_req(struct tcp_sock *tp)
  994. {
  995. if (tp->fastopen_req) {
  996. kfree(tp->fastopen_req);
  997. tp->fastopen_req = NULL;
  998. }
  999. }
  1000. static int tcp_sendmsg_fastopen(struct sock *sk, struct msghdr *msg,
  1001. int *copied, size_t size)
  1002. {
  1003. struct tcp_sock *tp = tcp_sk(sk);
  1004. struct inet_sock *inet = inet_sk(sk);
  1005. struct sockaddr *uaddr = msg->msg_name;
  1006. int err, flags;
  1007. if (!(sock_net(sk)->ipv4.sysctl_tcp_fastopen & TFO_CLIENT_ENABLE) ||
  1008. (uaddr && msg->msg_namelen >= sizeof(uaddr->sa_family) &&
  1009. uaddr->sa_family == AF_UNSPEC))
  1010. return -EOPNOTSUPP;
  1011. if (tp->fastopen_req)
  1012. return -EALREADY; /* Another Fast Open is in progress */
  1013. tp->fastopen_req = kzalloc(sizeof(struct tcp_fastopen_request),
  1014. sk->sk_allocation);
  1015. if (unlikely(!tp->fastopen_req))
  1016. return -ENOBUFS;
  1017. tp->fastopen_req->data = msg;
  1018. tp->fastopen_req->size = size;
  1019. if (inet->defer_connect) {
  1020. err = tcp_connect(sk);
  1021. /* Same failure procedure as in tcp_v4/6_connect */
  1022. if (err) {
  1023. tcp_set_state(sk, TCP_CLOSE);
  1024. inet->inet_dport = 0;
  1025. sk->sk_route_caps = 0;
  1026. }
  1027. }
  1028. flags = (msg->msg_flags & MSG_DONTWAIT) ? O_NONBLOCK : 0;
  1029. err = __inet_stream_connect(sk->sk_socket, uaddr,
  1030. msg->msg_namelen, flags, 1);
  1031. /* fastopen_req could already be freed in __inet_stream_connect
  1032. * if the connection times out or gets rst
  1033. */
  1034. if (tp->fastopen_req) {
  1035. *copied = tp->fastopen_req->copied;
  1036. tcp_free_fastopen_req(tp);
  1037. inet->defer_connect = 0;
  1038. }
  1039. return err;
  1040. }
  1041. int tcp_sendmsg_locked(struct sock *sk, struct msghdr *msg, size_t size)
  1042. {
  1043. struct tcp_sock *tp = tcp_sk(sk);
  1044. struct ubuf_info *uarg = NULL;
  1045. struct sk_buff *skb;
  1046. struct sockcm_cookie sockc;
  1047. int flags, err, copied = 0;
  1048. int mss_now = 0, size_goal, copied_syn = 0;
  1049. bool process_backlog = false;
  1050. bool sg, zc = false;
  1051. long timeo;
  1052. flags = msg->msg_flags;
  1053. if (flags & MSG_ZEROCOPY && size) {
  1054. if (sk->sk_state != TCP_ESTABLISHED) {
  1055. err = -EINVAL;
  1056. goto out_err;
  1057. }
  1058. skb = tcp_write_queue_tail(sk);
  1059. uarg = sock_zerocopy_realloc(sk, size, skb_zcopy(skb));
  1060. if (!uarg) {
  1061. err = -ENOBUFS;
  1062. goto out_err;
  1063. }
  1064. zc = sk_check_csum_caps(sk) && sk->sk_route_caps & NETIF_F_SG;
  1065. if (!zc)
  1066. uarg->zerocopy = 0;
  1067. }
  1068. if (unlikely(flags & MSG_FASTOPEN || inet_sk(sk)->defer_connect)) {
  1069. err = tcp_sendmsg_fastopen(sk, msg, &copied_syn, size);
  1070. if (err == -EINPROGRESS && copied_syn > 0)
  1071. goto out;
  1072. else if (err)
  1073. goto out_err;
  1074. }
  1075. timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT);
  1076. tcp_rate_check_app_limited(sk); /* is sending application-limited? */
  1077. /* Wait for a connection to finish. One exception is TCP Fast Open
  1078. * (passive side) where data is allowed to be sent before a connection
  1079. * is fully established.
  1080. */
  1081. if (((1 << sk->sk_state) & ~(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT)) &&
  1082. !tcp_passive_fastopen(sk)) {
  1083. err = sk_stream_wait_connect(sk, &timeo);
  1084. if (err != 0)
  1085. goto do_error;
  1086. }
  1087. if (unlikely(tp->repair)) {
  1088. if (tp->repair_queue == TCP_RECV_QUEUE) {
  1089. copied = tcp_send_rcvq(sk, msg, size);
  1090. goto out_nopush;
  1091. }
  1092. err = -EINVAL;
  1093. if (tp->repair_queue == TCP_NO_QUEUE)
  1094. goto out_err;
  1095. /* 'common' sending to sendq */
  1096. }
  1097. sockc.tsflags = sk->sk_tsflags;
  1098. if (msg->msg_controllen) {
  1099. err = sock_cmsg_send(sk, msg, &sockc);
  1100. if (unlikely(err)) {
  1101. err = -EINVAL;
  1102. goto out_err;
  1103. }
  1104. }
  1105. /* This should be in poll */
  1106. sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk);
  1107. /* Ok commence sending. */
  1108. copied = 0;
  1109. restart:
  1110. mss_now = tcp_send_mss(sk, &size_goal, flags);
  1111. err = -EPIPE;
  1112. if (sk->sk_err || (sk->sk_shutdown & SEND_SHUTDOWN))
  1113. goto do_error;
  1114. sg = !!(sk->sk_route_caps & NETIF_F_SG);
  1115. while (msg_data_left(msg)) {
  1116. int copy = 0;
  1117. int max = size_goal;
  1118. skb = tcp_write_queue_tail(sk);
  1119. if (skb) {
  1120. if (skb->ip_summed == CHECKSUM_NONE)
  1121. max = mss_now;
  1122. copy = max - skb->len;
  1123. }
  1124. if (copy <= 0 || !tcp_skb_can_collapse_to(skb)) {
  1125. bool first_skb;
  1126. int linear;
  1127. new_segment:
  1128. /* Allocate new segment. If the interface is SG,
  1129. * allocate skb fitting to single page.
  1130. */
  1131. if (!sk_stream_memory_free(sk))
  1132. goto wait_for_sndbuf;
  1133. if (process_backlog && sk_flush_backlog(sk)) {
  1134. process_backlog = false;
  1135. goto restart;
  1136. }
  1137. first_skb = tcp_rtx_and_write_queues_empty(sk);
  1138. linear = select_size(sk, sg, first_skb, zc);
  1139. skb = sk_stream_alloc_skb(sk, linear, sk->sk_allocation,
  1140. first_skb);
  1141. if (!skb)
  1142. goto wait_for_memory;
  1143. process_backlog = true;
  1144. /*
  1145. * Check whether we can use HW checksum.
  1146. */
  1147. if (sk_check_csum_caps(sk))
  1148. skb->ip_summed = CHECKSUM_PARTIAL;
  1149. skb_entail(sk, skb);
  1150. copy = size_goal;
  1151. max = size_goal;
  1152. /* All packets are restored as if they have
  1153. * already been sent. skb_mstamp isn't set to
  1154. * avoid wrong rtt estimation.
  1155. */
  1156. if (tp->repair)
  1157. TCP_SKB_CB(skb)->sacked |= TCPCB_REPAIRED;
  1158. }
  1159. /* Try to append data to the end of skb. */
  1160. if (copy > msg_data_left(msg))
  1161. copy = msg_data_left(msg);
  1162. /* Where to copy to? */
  1163. if (skb_availroom(skb) > 0 && !zc) {
  1164. /* We have some space in skb head. Superb! */
  1165. copy = min_t(int, copy, skb_availroom(skb));
  1166. err = skb_add_data_nocache(sk, skb, &msg->msg_iter, copy);
  1167. if (err)
  1168. goto do_fault;
  1169. } else if (!zc) {
  1170. bool merge = true;
  1171. int i = skb_shinfo(skb)->nr_frags;
  1172. struct page_frag *pfrag = sk_page_frag(sk);
  1173. if (!sk_page_frag_refill(sk, pfrag))
  1174. goto wait_for_memory;
  1175. if (!skb_can_coalesce(skb, i, pfrag->page,
  1176. pfrag->offset)) {
  1177. if (i >= sysctl_max_skb_frags || !sg) {
  1178. tcp_mark_push(tp, skb);
  1179. goto new_segment;
  1180. }
  1181. merge = false;
  1182. }
  1183. copy = min_t(int, copy, pfrag->size - pfrag->offset);
  1184. if (!sk_wmem_schedule(sk, copy))
  1185. goto wait_for_memory;
  1186. err = skb_copy_to_page_nocache(sk, &msg->msg_iter, skb,
  1187. pfrag->page,
  1188. pfrag->offset,
  1189. copy);
  1190. if (err)
  1191. goto do_error;
  1192. /* Update the skb. */
  1193. if (merge) {
  1194. skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy);
  1195. } else {
  1196. skb_fill_page_desc(skb, i, pfrag->page,
  1197. pfrag->offset, copy);
  1198. page_ref_inc(pfrag->page);
  1199. }
  1200. pfrag->offset += copy;
  1201. } else {
  1202. err = skb_zerocopy_iter_stream(sk, skb, msg, copy, uarg);
  1203. if (err == -EMSGSIZE || err == -EEXIST) {
  1204. tcp_mark_push(tp, skb);
  1205. goto new_segment;
  1206. }
  1207. if (err < 0)
  1208. goto do_error;
  1209. copy = err;
  1210. }
  1211. if (!copied)
  1212. TCP_SKB_CB(skb)->tcp_flags &= ~TCPHDR_PSH;
  1213. tp->write_seq += copy;
  1214. TCP_SKB_CB(skb)->end_seq += copy;
  1215. tcp_skb_pcount_set(skb, 0);
  1216. copied += copy;
  1217. if (!msg_data_left(msg)) {
  1218. if (unlikely(flags & MSG_EOR))
  1219. TCP_SKB_CB(skb)->eor = 1;
  1220. goto out;
  1221. }
  1222. if (skb->len < max || (flags & MSG_OOB) || unlikely(tp->repair))
  1223. continue;
  1224. if (forced_push(tp)) {
  1225. tcp_mark_push(tp, skb);
  1226. __tcp_push_pending_frames(sk, mss_now, TCP_NAGLE_PUSH);
  1227. } else if (skb == tcp_send_head(sk))
  1228. tcp_push_one(sk, mss_now);
  1229. continue;
  1230. wait_for_sndbuf:
  1231. set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
  1232. wait_for_memory:
  1233. if (copied)
  1234. tcp_push(sk, flags & ~MSG_MORE, mss_now,
  1235. TCP_NAGLE_PUSH, size_goal);
  1236. err = sk_stream_wait_memory(sk, &timeo);
  1237. if (err != 0)
  1238. goto do_error;
  1239. mss_now = tcp_send_mss(sk, &size_goal, flags);
  1240. }
  1241. out:
  1242. if (copied) {
  1243. tcp_tx_timestamp(sk, sockc.tsflags);
  1244. tcp_push(sk, flags, mss_now, tp->nonagle, size_goal);
  1245. }
  1246. out_nopush:
  1247. sock_zerocopy_put(uarg);
  1248. return copied + copied_syn;
  1249. do_fault:
  1250. if (!skb->len) {
  1251. tcp_unlink_write_queue(skb, sk);
  1252. /* It is the one place in all of TCP, except connection
  1253. * reset, where we can be unlinking the send_head.
  1254. */
  1255. tcp_check_send_head(sk, skb);
  1256. sk_wmem_free_skb(sk, skb);
  1257. }
  1258. do_error:
  1259. if (copied + copied_syn)
  1260. goto out;
  1261. out_err:
  1262. sock_zerocopy_put_abort(uarg);
  1263. err = sk_stream_error(sk, flags, err);
  1264. /* make sure we wake any epoll edge trigger waiter */
  1265. if (unlikely(skb_queue_len(&sk->sk_write_queue) == 0 &&
  1266. err == -EAGAIN)) {
  1267. sk->sk_write_space(sk);
  1268. tcp_chrono_stop(sk, TCP_CHRONO_SNDBUF_LIMITED);
  1269. }
  1270. return err;
  1271. }
  1272. EXPORT_SYMBOL_GPL(tcp_sendmsg_locked);
  1273. int tcp_sendmsg(struct sock *sk, struct msghdr *msg, size_t size)
  1274. {
  1275. int ret;
  1276. lock_sock(sk);
  1277. ret = tcp_sendmsg_locked(sk, msg, size);
  1278. release_sock(sk);
  1279. return ret;
  1280. }
  1281. EXPORT_SYMBOL(tcp_sendmsg);
  1282. /*
  1283. * Handle reading urgent data. BSD has very simple semantics for
  1284. * this, no blocking and very strange errors 8)
  1285. */
  1286. static int tcp_recv_urg(struct sock *sk, struct msghdr *msg, int len, int flags)
  1287. {
  1288. struct tcp_sock *tp = tcp_sk(sk);
  1289. /* No URG data to read. */
  1290. if (sock_flag(sk, SOCK_URGINLINE) || !tp->urg_data ||
  1291. tp->urg_data == TCP_URG_READ)
  1292. return -EINVAL; /* Yes this is right ! */
  1293. if (sk->sk_state == TCP_CLOSE && !sock_flag(sk, SOCK_DONE))
  1294. return -ENOTCONN;
  1295. if (tp->urg_data & TCP_URG_VALID) {
  1296. int err = 0;
  1297. char c = tp->urg_data;
  1298. if (!(flags & MSG_PEEK))
  1299. tp->urg_data = TCP_URG_READ;
  1300. /* Read urgent data. */
  1301. msg->msg_flags |= MSG_OOB;
  1302. if (len > 0) {
  1303. if (!(flags & MSG_TRUNC))
  1304. err = memcpy_to_msg(msg, &c, 1);
  1305. len = 1;
  1306. } else
  1307. msg->msg_flags |= MSG_TRUNC;
  1308. return err ? -EFAULT : len;
  1309. }
  1310. if (sk->sk_state == TCP_CLOSE || (sk->sk_shutdown & RCV_SHUTDOWN))
  1311. return 0;
  1312. /* Fixed the recv(..., MSG_OOB) behaviour. BSD docs and
  1313. * the available implementations agree in this case:
  1314. * this call should never block, independent of the
  1315. * blocking state of the socket.
  1316. * Mike <pall@rz.uni-karlsruhe.de>
  1317. */
  1318. return -EAGAIN;
  1319. }
  1320. static int tcp_peek_sndq(struct sock *sk, struct msghdr *msg, int len)
  1321. {
  1322. struct sk_buff *skb;
  1323. int copied = 0, err = 0;
  1324. /* XXX -- need to support SO_PEEK_OFF */
  1325. skb_rbtree_walk(skb, &sk->tcp_rtx_queue) {
  1326. err = skb_copy_datagram_msg(skb, 0, msg, skb->len);
  1327. if (err)
  1328. return err;
  1329. copied += skb->len;
  1330. }
  1331. skb_queue_walk(&sk->sk_write_queue, skb) {
  1332. err = skb_copy_datagram_msg(skb, 0, msg, skb->len);
  1333. if (err)
  1334. break;
  1335. copied += skb->len;
  1336. }
  1337. return err ?: copied;
  1338. }
  1339. /* Clean up the receive buffer for full frames taken by the user,
  1340. * then send an ACK if necessary. COPIED is the number of bytes
  1341. * tcp_recvmsg has given to the user so far, it speeds up the
  1342. * calculation of whether or not we must ACK for the sake of
  1343. * a window update.
  1344. */
  1345. static void tcp_cleanup_rbuf(struct sock *sk, int copied)
  1346. {
  1347. struct tcp_sock *tp = tcp_sk(sk);
  1348. bool time_to_ack = false;
  1349. struct sk_buff *skb = skb_peek(&sk->sk_receive_queue);
  1350. WARN(skb && !before(tp->copied_seq, TCP_SKB_CB(skb)->end_seq),
  1351. "cleanup rbuf bug: copied %X seq %X rcvnxt %X\n",
  1352. tp->copied_seq, TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt);
  1353. if (inet_csk_ack_scheduled(sk)) {
  1354. const struct inet_connection_sock *icsk = inet_csk(sk);
  1355. /* Delayed ACKs frequently hit locked sockets during bulk
  1356. * receive. */
  1357. if (icsk->icsk_ack.blocked ||
  1358. /* Once-per-two-segments ACK was not sent by tcp_input.c */
  1359. tp->rcv_nxt - tp->rcv_wup > icsk->icsk_ack.rcv_mss ||
  1360. /*
  1361. * If this read emptied read buffer, we send ACK, if
  1362. * connection is not bidirectional, user drained
  1363. * receive buffer and there was a small segment
  1364. * in queue.
  1365. */
  1366. (copied > 0 &&
  1367. ((icsk->icsk_ack.pending & ICSK_ACK_PUSHED2) ||
  1368. ((icsk->icsk_ack.pending & ICSK_ACK_PUSHED) &&
  1369. !icsk->icsk_ack.pingpong)) &&
  1370. !atomic_read(&sk->sk_rmem_alloc)))
  1371. time_to_ack = true;
  1372. }
  1373. /* We send an ACK if we can now advertise a non-zero window
  1374. * which has been raised "significantly".
  1375. *
  1376. * Even if window raised up to infinity, do not send window open ACK
  1377. * in states, where we will not receive more. It is useless.
  1378. */
  1379. if (copied > 0 && !time_to_ack && !(sk->sk_shutdown & RCV_SHUTDOWN)) {
  1380. __u32 rcv_window_now = tcp_receive_window(tp);
  1381. /* Optimize, __tcp_select_window() is not cheap. */
  1382. if (2*rcv_window_now <= tp->window_clamp) {
  1383. __u32 new_window = __tcp_select_window(sk);
  1384. /* Send ACK now, if this read freed lots of space
  1385. * in our buffer. Certainly, new_window is new window.
  1386. * We can advertise it now, if it is not less than current one.
  1387. * "Lots" means "at least twice" here.
  1388. */
  1389. if (new_window && new_window >= 2 * rcv_window_now)
  1390. time_to_ack = true;
  1391. }
  1392. }
  1393. if (time_to_ack)
  1394. tcp_send_ack(sk);
  1395. }
  1396. static struct sk_buff *tcp_recv_skb(struct sock *sk, u32 seq, u32 *off)
  1397. {
  1398. struct sk_buff *skb;
  1399. u32 offset;
  1400. while ((skb = skb_peek(&sk->sk_receive_queue)) != NULL) {
  1401. offset = seq - TCP_SKB_CB(skb)->seq;
  1402. if (unlikely(TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN)) {
  1403. pr_err_once("%s: found a SYN, please report !\n", __func__);
  1404. offset--;
  1405. }
  1406. if (offset < skb->len || (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)) {
  1407. *off = offset;
  1408. return skb;
  1409. }
  1410. /* This looks weird, but this can happen if TCP collapsing
  1411. * splitted a fat GRO packet, while we released socket lock
  1412. * in skb_splice_bits()
  1413. */
  1414. sk_eat_skb(sk, skb);
  1415. }
  1416. return NULL;
  1417. }
  1418. /*
  1419. * This routine provides an alternative to tcp_recvmsg() for routines
  1420. * that would like to handle copying from skbuffs directly in 'sendfile'
  1421. * fashion.
  1422. * Note:
  1423. * - It is assumed that the socket was locked by the caller.
  1424. * - The routine does not block.
  1425. * - At present, there is no support for reading OOB data
  1426. * or for 'peeking' the socket using this routine
  1427. * (although both would be easy to implement).
  1428. */
  1429. int tcp_read_sock(struct sock *sk, read_descriptor_t *desc,
  1430. sk_read_actor_t recv_actor)
  1431. {
  1432. struct sk_buff *skb;
  1433. struct tcp_sock *tp = tcp_sk(sk);
  1434. u32 seq = tp->copied_seq;
  1435. u32 offset;
  1436. int copied = 0;
  1437. if (sk->sk_state == TCP_LISTEN)
  1438. return -ENOTCONN;
  1439. while ((skb = tcp_recv_skb(sk, seq, &offset)) != NULL) {
  1440. if (offset < skb->len) {
  1441. int used;
  1442. size_t len;
  1443. len = skb->len - offset;
  1444. /* Stop reading if we hit a patch of urgent data */
  1445. if (tp->urg_data) {
  1446. u32 urg_offset = tp->urg_seq - seq;
  1447. if (urg_offset < len)
  1448. len = urg_offset;
  1449. if (!len)
  1450. break;
  1451. }
  1452. used = recv_actor(desc, skb, offset, len);
  1453. if (used <= 0) {
  1454. if (!copied)
  1455. copied = used;
  1456. break;
  1457. } else if (used <= len) {
  1458. seq += used;
  1459. copied += used;
  1460. offset += used;
  1461. }
  1462. /* If recv_actor drops the lock (e.g. TCP splice
  1463. * receive) the skb pointer might be invalid when
  1464. * getting here: tcp_collapse might have deleted it
  1465. * while aggregating skbs from the socket queue.
  1466. */
  1467. skb = tcp_recv_skb(sk, seq - 1, &offset);
  1468. if (!skb)
  1469. break;
  1470. /* TCP coalescing might have appended data to the skb.
  1471. * Try to splice more frags
  1472. */
  1473. if (offset + 1 != skb->len)
  1474. continue;
  1475. }
  1476. if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN) {
  1477. sk_eat_skb(sk, skb);
  1478. ++seq;
  1479. break;
  1480. }
  1481. sk_eat_skb(sk, skb);
  1482. if (!desc->count)
  1483. break;
  1484. tp->copied_seq = seq;
  1485. }
  1486. tp->copied_seq = seq;
  1487. tcp_rcv_space_adjust(sk);
  1488. /* Clean up data we have read: This will do ACK frames. */
  1489. if (copied > 0) {
  1490. tcp_recv_skb(sk, seq, &offset);
  1491. tcp_cleanup_rbuf(sk, copied);
  1492. }
  1493. return copied;
  1494. }
  1495. EXPORT_SYMBOL(tcp_read_sock);
  1496. int tcp_peek_len(struct socket *sock)
  1497. {
  1498. return tcp_inq(sock->sk);
  1499. }
  1500. EXPORT_SYMBOL(tcp_peek_len);
  1501. static void tcp_update_recv_tstamps(struct sk_buff *skb,
  1502. struct scm_timestamping *tss)
  1503. {
  1504. if (skb->tstamp)
  1505. tss->ts[0] = ktime_to_timespec(skb->tstamp);
  1506. else
  1507. tss->ts[0] = (struct timespec) {0};
  1508. if (skb_hwtstamps(skb)->hwtstamp)
  1509. tss->ts[2] = ktime_to_timespec(skb_hwtstamps(skb)->hwtstamp);
  1510. else
  1511. tss->ts[2] = (struct timespec) {0};
  1512. }
  1513. /* Similar to __sock_recv_timestamp, but does not require an skb */
  1514. static void tcp_recv_timestamp(struct msghdr *msg, const struct sock *sk,
  1515. struct scm_timestamping *tss)
  1516. {
  1517. struct timeval tv;
  1518. bool has_timestamping = false;
  1519. if (tss->ts[0].tv_sec || tss->ts[0].tv_nsec) {
  1520. if (sock_flag(sk, SOCK_RCVTSTAMP)) {
  1521. if (sock_flag(sk, SOCK_RCVTSTAMPNS)) {
  1522. put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPNS,
  1523. sizeof(tss->ts[0]), &tss->ts[0]);
  1524. } else {
  1525. tv.tv_sec = tss->ts[0].tv_sec;
  1526. tv.tv_usec = tss->ts[0].tv_nsec / 1000;
  1527. put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMP,
  1528. sizeof(tv), &tv);
  1529. }
  1530. }
  1531. if (sk->sk_tsflags & SOF_TIMESTAMPING_SOFTWARE)
  1532. has_timestamping = true;
  1533. else
  1534. tss->ts[0] = (struct timespec) {0};
  1535. }
  1536. if (tss->ts[2].tv_sec || tss->ts[2].tv_nsec) {
  1537. if (sk->sk_tsflags & SOF_TIMESTAMPING_RAW_HARDWARE)
  1538. has_timestamping = true;
  1539. else
  1540. tss->ts[2] = (struct timespec) {0};
  1541. }
  1542. if (has_timestamping) {
  1543. tss->ts[1] = (struct timespec) {0};
  1544. put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPING,
  1545. sizeof(*tss), tss);
  1546. }
  1547. }
  1548. /*
  1549. * This routine copies from a sock struct into the user buffer.
  1550. *
  1551. * Technical note: in 2.3 we work on _locked_ socket, so that
  1552. * tricks with *seq access order and skb->users are not required.
  1553. * Probably, code can be easily improved even more.
  1554. */
  1555. int tcp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int nonblock,
  1556. int flags, int *addr_len)
  1557. {
  1558. struct tcp_sock *tp = tcp_sk(sk);
  1559. int copied = 0;
  1560. u32 peek_seq;
  1561. u32 *seq;
  1562. unsigned long used;
  1563. int err;
  1564. int target; /* Read at least this many bytes */
  1565. long timeo;
  1566. struct sk_buff *skb, *last;
  1567. u32 urg_hole = 0;
  1568. struct scm_timestamping tss;
  1569. bool has_tss = false;
  1570. if (unlikely(flags & MSG_ERRQUEUE))
  1571. return inet_recv_error(sk, msg, len, addr_len);
  1572. if (sk_can_busy_loop(sk) && skb_queue_empty(&sk->sk_receive_queue) &&
  1573. (sk->sk_state == TCP_ESTABLISHED))
  1574. sk_busy_loop(sk, nonblock);
  1575. lock_sock(sk);
  1576. err = -ENOTCONN;
  1577. if (sk->sk_state == TCP_LISTEN)
  1578. goto out;
  1579. timeo = sock_rcvtimeo(sk, nonblock);
  1580. /* Urgent data needs to be handled specially. */
  1581. if (flags & MSG_OOB)
  1582. goto recv_urg;
  1583. if (unlikely(tp->repair)) {
  1584. err = -EPERM;
  1585. if (!(flags & MSG_PEEK))
  1586. goto out;
  1587. if (tp->repair_queue == TCP_SEND_QUEUE)
  1588. goto recv_sndq;
  1589. err = -EINVAL;
  1590. if (tp->repair_queue == TCP_NO_QUEUE)
  1591. goto out;
  1592. /* 'common' recv queue MSG_PEEK-ing */
  1593. }
  1594. seq = &tp->copied_seq;
  1595. if (flags & MSG_PEEK) {
  1596. peek_seq = tp->copied_seq;
  1597. seq = &peek_seq;
  1598. }
  1599. target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
  1600. do {
  1601. u32 offset;
  1602. /* Are we at urgent data? Stop if we have read anything or have SIGURG pending. */
  1603. if (tp->urg_data && tp->urg_seq == *seq) {
  1604. if (copied)
  1605. break;
  1606. if (signal_pending(current)) {
  1607. copied = timeo ? sock_intr_errno(timeo) : -EAGAIN;
  1608. break;
  1609. }
  1610. }
  1611. /* Next get a buffer. */
  1612. last = skb_peek_tail(&sk->sk_receive_queue);
  1613. skb_queue_walk(&sk->sk_receive_queue, skb) {
  1614. last = skb;
  1615. /* Now that we have two receive queues this
  1616. * shouldn't happen.
  1617. */
  1618. if (WARN(before(*seq, TCP_SKB_CB(skb)->seq),
  1619. "recvmsg bug: copied %X seq %X rcvnxt %X fl %X\n",
  1620. *seq, TCP_SKB_CB(skb)->seq, tp->rcv_nxt,
  1621. flags))
  1622. break;
  1623. offset = *seq - TCP_SKB_CB(skb)->seq;
  1624. if (unlikely(TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN)) {
  1625. pr_err_once("%s: found a SYN, please report !\n", __func__);
  1626. offset--;
  1627. }
  1628. if (offset < skb->len)
  1629. goto found_ok_skb;
  1630. if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)
  1631. goto found_fin_ok;
  1632. WARN(!(flags & MSG_PEEK),
  1633. "recvmsg bug 2: copied %X seq %X rcvnxt %X fl %X\n",
  1634. *seq, TCP_SKB_CB(skb)->seq, tp->rcv_nxt, flags);
  1635. }
  1636. /* Well, if we have backlog, try to process it now yet. */
  1637. if (copied >= target && !sk->sk_backlog.tail)
  1638. break;
  1639. if (copied) {
  1640. if (sk->sk_err ||
  1641. sk->sk_state == TCP_CLOSE ||
  1642. (sk->sk_shutdown & RCV_SHUTDOWN) ||
  1643. !timeo ||
  1644. signal_pending(current))
  1645. break;
  1646. } else {
  1647. if (sock_flag(sk, SOCK_DONE))
  1648. break;
  1649. if (sk->sk_err) {
  1650. copied = sock_error(sk);
  1651. break;
  1652. }
  1653. if (sk->sk_shutdown & RCV_SHUTDOWN)
  1654. break;
  1655. if (sk->sk_state == TCP_CLOSE) {
  1656. if (!sock_flag(sk, SOCK_DONE)) {
  1657. /* This occurs when user tries to read
  1658. * from never connected socket.
  1659. */
  1660. copied = -ENOTCONN;
  1661. break;
  1662. }
  1663. break;
  1664. }
  1665. if (!timeo) {
  1666. copied = -EAGAIN;
  1667. break;
  1668. }
  1669. if (signal_pending(current)) {
  1670. copied = sock_intr_errno(timeo);
  1671. break;
  1672. }
  1673. }
  1674. tcp_cleanup_rbuf(sk, copied);
  1675. if (copied >= target) {
  1676. /* Do not sleep, just process backlog. */
  1677. release_sock(sk);
  1678. lock_sock(sk);
  1679. } else {
  1680. sk_wait_data(sk, &timeo, last);
  1681. }
  1682. if ((flags & MSG_PEEK) &&
  1683. (peek_seq - copied - urg_hole != tp->copied_seq)) {
  1684. net_dbg_ratelimited("TCP(%s:%d): Application bug, race in MSG_PEEK\n",
  1685. current->comm,
  1686. task_pid_nr(current));
  1687. peek_seq = tp->copied_seq;
  1688. }
  1689. continue;
  1690. found_ok_skb:
  1691. /* Ok so how much can we use? */
  1692. used = skb->len - offset;
  1693. if (len < used)
  1694. used = len;
  1695. /* Do we have urgent data here? */
  1696. if (tp->urg_data) {
  1697. u32 urg_offset = tp->urg_seq - *seq;
  1698. if (urg_offset < used) {
  1699. if (!urg_offset) {
  1700. if (!sock_flag(sk, SOCK_URGINLINE)) {
  1701. ++*seq;
  1702. urg_hole++;
  1703. offset++;
  1704. used--;
  1705. if (!used)
  1706. goto skip_copy;
  1707. }
  1708. } else
  1709. used = urg_offset;
  1710. }
  1711. }
  1712. if (!(flags & MSG_TRUNC)) {
  1713. err = skb_copy_datagram_msg(skb, offset, msg, used);
  1714. if (err) {
  1715. /* Exception. Bailout! */
  1716. if (!copied)
  1717. copied = -EFAULT;
  1718. break;
  1719. }
  1720. }
  1721. *seq += used;
  1722. copied += used;
  1723. len -= used;
  1724. tcp_rcv_space_adjust(sk);
  1725. skip_copy:
  1726. if (tp->urg_data && after(tp->copied_seq, tp->urg_seq)) {
  1727. tp->urg_data = 0;
  1728. tcp_fast_path_check(sk);
  1729. }
  1730. if (used + offset < skb->len)
  1731. continue;
  1732. if (TCP_SKB_CB(skb)->has_rxtstamp) {
  1733. tcp_update_recv_tstamps(skb, &tss);
  1734. has_tss = true;
  1735. }
  1736. if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)
  1737. goto found_fin_ok;
  1738. if (!(flags & MSG_PEEK))
  1739. sk_eat_skb(sk, skb);
  1740. continue;
  1741. found_fin_ok:
  1742. /* Process the FIN. */
  1743. ++*seq;
  1744. if (!(flags & MSG_PEEK))
  1745. sk_eat_skb(sk, skb);
  1746. break;
  1747. } while (len > 0);
  1748. /* According to UNIX98, msg_name/msg_namelen are ignored
  1749. * on connected socket. I was just happy when found this 8) --ANK
  1750. */
  1751. if (has_tss)
  1752. tcp_recv_timestamp(msg, sk, &tss);
  1753. /* Clean up data we have read: This will do ACK frames. */
  1754. tcp_cleanup_rbuf(sk, copied);
  1755. release_sock(sk);
  1756. return copied;
  1757. out:
  1758. release_sock(sk);
  1759. return err;
  1760. recv_urg:
  1761. err = tcp_recv_urg(sk, msg, len, flags);
  1762. goto out;
  1763. recv_sndq:
  1764. err = tcp_peek_sndq(sk, msg, len);
  1765. goto out;
  1766. }
  1767. EXPORT_SYMBOL(tcp_recvmsg);
  1768. void tcp_set_state(struct sock *sk, int state)
  1769. {
  1770. int oldstate = sk->sk_state;
  1771. /* We defined a new enum for TCP states that are exported in BPF
  1772. * so as not force the internal TCP states to be frozen. The
  1773. * following checks will detect if an internal state value ever
  1774. * differs from the BPF value. If this ever happens, then we will
  1775. * need to remap the internal value to the BPF value before calling
  1776. * tcp_call_bpf_2arg.
  1777. */
  1778. BUILD_BUG_ON((int)BPF_TCP_ESTABLISHED != (int)TCP_ESTABLISHED);
  1779. BUILD_BUG_ON((int)BPF_TCP_SYN_SENT != (int)TCP_SYN_SENT);
  1780. BUILD_BUG_ON((int)BPF_TCP_SYN_RECV != (int)TCP_SYN_RECV);
  1781. BUILD_BUG_ON((int)BPF_TCP_FIN_WAIT1 != (int)TCP_FIN_WAIT1);
  1782. BUILD_BUG_ON((int)BPF_TCP_FIN_WAIT2 != (int)TCP_FIN_WAIT2);
  1783. BUILD_BUG_ON((int)BPF_TCP_TIME_WAIT != (int)TCP_TIME_WAIT);
  1784. BUILD_BUG_ON((int)BPF_TCP_CLOSE != (int)TCP_CLOSE);
  1785. BUILD_BUG_ON((int)BPF_TCP_CLOSE_WAIT != (int)TCP_CLOSE_WAIT);
  1786. BUILD_BUG_ON((int)BPF_TCP_LAST_ACK != (int)TCP_LAST_ACK);
  1787. BUILD_BUG_ON((int)BPF_TCP_LISTEN != (int)TCP_LISTEN);
  1788. BUILD_BUG_ON((int)BPF_TCP_CLOSING != (int)TCP_CLOSING);
  1789. BUILD_BUG_ON((int)BPF_TCP_NEW_SYN_RECV != (int)TCP_NEW_SYN_RECV);
  1790. BUILD_BUG_ON((int)BPF_TCP_MAX_STATES != (int)TCP_MAX_STATES);
  1791. if (BPF_SOCK_OPS_TEST_FLAG(tcp_sk(sk), BPF_SOCK_OPS_STATE_CB_FLAG))
  1792. tcp_call_bpf_2arg(sk, BPF_SOCK_OPS_STATE_CB, oldstate, state);
  1793. switch (state) {
  1794. case TCP_ESTABLISHED:
  1795. if (oldstate != TCP_ESTABLISHED)
  1796. TCP_INC_STATS(sock_net(sk), TCP_MIB_CURRESTAB);
  1797. break;
  1798. case TCP_CLOSE:
  1799. if (oldstate == TCP_CLOSE_WAIT || oldstate == TCP_ESTABLISHED)
  1800. TCP_INC_STATS(sock_net(sk), TCP_MIB_ESTABRESETS);
  1801. sk->sk_prot->unhash(sk);
  1802. if (inet_csk(sk)->icsk_bind_hash &&
  1803. !(sk->sk_userlocks & SOCK_BINDPORT_LOCK))
  1804. inet_put_port(sk);
  1805. /* fall through */
  1806. default:
  1807. if (oldstate == TCP_ESTABLISHED)
  1808. TCP_DEC_STATS(sock_net(sk), TCP_MIB_CURRESTAB);
  1809. }
  1810. /* Change state AFTER socket is unhashed to avoid closed
  1811. * socket sitting in hash tables.
  1812. */
  1813. inet_sk_state_store(sk, state);
  1814. #ifdef STATE_TRACE
  1815. SOCK_DEBUG(sk, "TCP sk=%p, State %s -> %s\n", sk, statename[oldstate], statename[state]);
  1816. #endif
  1817. }
  1818. EXPORT_SYMBOL_GPL(tcp_set_state);
  1819. /*
  1820. * State processing on a close. This implements the state shift for
  1821. * sending our FIN frame. Note that we only send a FIN for some
  1822. * states. A shutdown() may have already sent the FIN, or we may be
  1823. * closed.
  1824. */
  1825. static const unsigned char new_state[16] = {
  1826. /* current state: new state: action: */
  1827. [0 /* (Invalid) */] = TCP_CLOSE,
  1828. [TCP_ESTABLISHED] = TCP_FIN_WAIT1 | TCP_ACTION_FIN,
  1829. [TCP_SYN_SENT] = TCP_CLOSE,
  1830. [TCP_SYN_RECV] = TCP_FIN_WAIT1 | TCP_ACTION_FIN,
  1831. [TCP_FIN_WAIT1] = TCP_FIN_WAIT1,
  1832. [TCP_FIN_WAIT2] = TCP_FIN_WAIT2,
  1833. [TCP_TIME_WAIT] = TCP_CLOSE,
  1834. [TCP_CLOSE] = TCP_CLOSE,
  1835. [TCP_CLOSE_WAIT] = TCP_LAST_ACK | TCP_ACTION_FIN,
  1836. [TCP_LAST_ACK] = TCP_LAST_ACK,
  1837. [TCP_LISTEN] = TCP_CLOSE,
  1838. [TCP_CLOSING] = TCP_CLOSING,
  1839. [TCP_NEW_SYN_RECV] = TCP_CLOSE, /* should not happen ! */
  1840. };
  1841. static int tcp_close_state(struct sock *sk)
  1842. {
  1843. int next = (int)new_state[sk->sk_state];
  1844. int ns = next & TCP_STATE_MASK;
  1845. tcp_set_state(sk, ns);
  1846. return next & TCP_ACTION_FIN;
  1847. }
  1848. /*
  1849. * Shutdown the sending side of a connection. Much like close except
  1850. * that we don't receive shut down or sock_set_flag(sk, SOCK_DEAD).
  1851. */
  1852. void tcp_shutdown(struct sock *sk, int how)
  1853. {
  1854. /* We need to grab some memory, and put together a FIN,
  1855. * and then put it into the queue to be sent.
  1856. * Tim MacKenzie(tym@dibbler.cs.monash.edu.au) 4 Dec '92.
  1857. */
  1858. if (!(how & SEND_SHUTDOWN))
  1859. return;
  1860. /* If we've already sent a FIN, or it's a closed state, skip this. */
  1861. if ((1 << sk->sk_state) &
  1862. (TCPF_ESTABLISHED | TCPF_SYN_SENT |
  1863. TCPF_SYN_RECV | TCPF_CLOSE_WAIT)) {
  1864. /* Clear out any half completed packets. FIN if needed. */
  1865. if (tcp_close_state(sk))
  1866. tcp_send_fin(sk);
  1867. }
  1868. }
  1869. EXPORT_SYMBOL(tcp_shutdown);
  1870. bool tcp_check_oom(struct sock *sk, int shift)
  1871. {
  1872. bool too_many_orphans, out_of_socket_memory;
  1873. too_many_orphans = tcp_too_many_orphans(sk, shift);
  1874. out_of_socket_memory = tcp_out_of_memory(sk);
  1875. if (too_many_orphans)
  1876. net_info_ratelimited("too many orphaned sockets\n");
  1877. if (out_of_socket_memory)
  1878. net_info_ratelimited("out of memory -- consider tuning tcp_mem\n");
  1879. return too_many_orphans || out_of_socket_memory;
  1880. }
  1881. void tcp_close(struct sock *sk, long timeout)
  1882. {
  1883. struct sk_buff *skb;
  1884. int data_was_unread = 0;
  1885. int state;
  1886. lock_sock(sk);
  1887. sk->sk_shutdown = SHUTDOWN_MASK;
  1888. if (sk->sk_state == TCP_LISTEN) {
  1889. tcp_set_state(sk, TCP_CLOSE);
  1890. /* Special case. */
  1891. inet_csk_listen_stop(sk);
  1892. goto adjudge_to_death;
  1893. }
  1894. /* We need to flush the recv. buffs. We do this only on the
  1895. * descriptor close, not protocol-sourced closes, because the
  1896. * reader process may not have drained the data yet!
  1897. */
  1898. while ((skb = __skb_dequeue(&sk->sk_receive_queue)) != NULL) {
  1899. u32 len = TCP_SKB_CB(skb)->end_seq - TCP_SKB_CB(skb)->seq;
  1900. if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)
  1901. len--;
  1902. data_was_unread += len;
  1903. __kfree_skb(skb);
  1904. }
  1905. sk_mem_reclaim(sk);
  1906. /* If socket has been already reset (e.g. in tcp_reset()) - kill it. */
  1907. if (sk->sk_state == TCP_CLOSE)
  1908. goto adjudge_to_death;
  1909. /* As outlined in RFC 2525, section 2.17, we send a RST here because
  1910. * data was lost. To witness the awful effects of the old behavior of
  1911. * always doing a FIN, run an older 2.1.x kernel or 2.0.x, start a bulk
  1912. * GET in an FTP client, suspend the process, wait for the client to
  1913. * advertise a zero window, then kill -9 the FTP client, wheee...
  1914. * Note: timeout is always zero in such a case.
  1915. */
  1916. if (unlikely(tcp_sk(sk)->repair)) {
  1917. sk->sk_prot->disconnect(sk, 0);
  1918. } else if (data_was_unread) {
  1919. /* Unread data was tossed, zap the connection. */
  1920. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONCLOSE);
  1921. tcp_set_state(sk, TCP_CLOSE);
  1922. tcp_send_active_reset(sk, sk->sk_allocation);
  1923. } else if (sock_flag(sk, SOCK_LINGER) && !sk->sk_lingertime) {
  1924. /* Check zero linger _after_ checking for unread data. */
  1925. sk->sk_prot->disconnect(sk, 0);
  1926. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONDATA);
  1927. } else if (tcp_close_state(sk)) {
  1928. /* We FIN if the application ate all the data before
  1929. * zapping the connection.
  1930. */
  1931. /* RED-PEN. Formally speaking, we have broken TCP state
  1932. * machine. State transitions:
  1933. *
  1934. * TCP_ESTABLISHED -> TCP_FIN_WAIT1
  1935. * TCP_SYN_RECV -> TCP_FIN_WAIT1 (forget it, it's impossible)
  1936. * TCP_CLOSE_WAIT -> TCP_LAST_ACK
  1937. *
  1938. * are legal only when FIN has been sent (i.e. in window),
  1939. * rather than queued out of window. Purists blame.
  1940. *
  1941. * F.e. "RFC state" is ESTABLISHED,
  1942. * if Linux state is FIN-WAIT-1, but FIN is still not sent.
  1943. *
  1944. * The visible declinations are that sometimes
  1945. * we enter time-wait state, when it is not required really
  1946. * (harmless), do not send active resets, when they are
  1947. * required by specs (TCP_ESTABLISHED, TCP_CLOSE_WAIT, when
  1948. * they look as CLOSING or LAST_ACK for Linux)
  1949. * Probably, I missed some more holelets.
  1950. * --ANK
  1951. * XXX (TFO) - To start off we don't support SYN+ACK+FIN
  1952. * in a single packet! (May consider it later but will
  1953. * probably need API support or TCP_CORK SYN-ACK until
  1954. * data is written and socket is closed.)
  1955. */
  1956. tcp_send_fin(sk);
  1957. }
  1958. sk_stream_wait_close(sk, timeout);
  1959. adjudge_to_death:
  1960. state = sk->sk_state;
  1961. sock_hold(sk);
  1962. sock_orphan(sk);
  1963. /* It is the last release_sock in its life. It will remove backlog. */
  1964. release_sock(sk);
  1965. /* Now socket is owned by kernel and we acquire BH lock
  1966. * to finish close. No need to check for user refs.
  1967. */
  1968. local_bh_disable();
  1969. bh_lock_sock(sk);
  1970. WARN_ON(sock_owned_by_user(sk));
  1971. percpu_counter_inc(sk->sk_prot->orphan_count);
  1972. /* Have we already been destroyed by a softirq or backlog? */
  1973. if (state != TCP_CLOSE && sk->sk_state == TCP_CLOSE)
  1974. goto out;
  1975. /* This is a (useful) BSD violating of the RFC. There is a
  1976. * problem with TCP as specified in that the other end could
  1977. * keep a socket open forever with no application left this end.
  1978. * We use a 1 minute timeout (about the same as BSD) then kill
  1979. * our end. If they send after that then tough - BUT: long enough
  1980. * that we won't make the old 4*rto = almost no time - whoops
  1981. * reset mistake.
  1982. *
  1983. * Nope, it was not mistake. It is really desired behaviour
  1984. * f.e. on http servers, when such sockets are useless, but
  1985. * consume significant resources. Let's do it with special
  1986. * linger2 option. --ANK
  1987. */
  1988. if (sk->sk_state == TCP_FIN_WAIT2) {
  1989. struct tcp_sock *tp = tcp_sk(sk);
  1990. if (tp->linger2 < 0) {
  1991. tcp_set_state(sk, TCP_CLOSE);
  1992. tcp_send_active_reset(sk, GFP_ATOMIC);
  1993. __NET_INC_STATS(sock_net(sk),
  1994. LINUX_MIB_TCPABORTONLINGER);
  1995. } else {
  1996. const int tmo = tcp_fin_time(sk);
  1997. if (tmo > TCP_TIMEWAIT_LEN) {
  1998. inet_csk_reset_keepalive_timer(sk,
  1999. tmo - TCP_TIMEWAIT_LEN);
  2000. } else {
  2001. tcp_time_wait(sk, TCP_FIN_WAIT2, tmo);
  2002. goto out;
  2003. }
  2004. }
  2005. }
  2006. if (sk->sk_state != TCP_CLOSE) {
  2007. sk_mem_reclaim(sk);
  2008. if (tcp_check_oom(sk, 0)) {
  2009. tcp_set_state(sk, TCP_CLOSE);
  2010. tcp_send_active_reset(sk, GFP_ATOMIC);
  2011. __NET_INC_STATS(sock_net(sk),
  2012. LINUX_MIB_TCPABORTONMEMORY);
  2013. } else if (!check_net(sock_net(sk))) {
  2014. /* Not possible to send reset; just close */
  2015. tcp_set_state(sk, TCP_CLOSE);
  2016. }
  2017. }
  2018. if (sk->sk_state == TCP_CLOSE) {
  2019. struct request_sock *req = tcp_sk(sk)->fastopen_rsk;
  2020. /* We could get here with a non-NULL req if the socket is
  2021. * aborted (e.g., closed with unread data) before 3WHS
  2022. * finishes.
  2023. */
  2024. if (req)
  2025. reqsk_fastopen_remove(sk, req, false);
  2026. inet_csk_destroy_sock(sk);
  2027. }
  2028. /* Otherwise, socket is reprieved until protocol close. */
  2029. out:
  2030. bh_unlock_sock(sk);
  2031. local_bh_enable();
  2032. sock_put(sk);
  2033. }
  2034. EXPORT_SYMBOL(tcp_close);
  2035. /* These states need RST on ABORT according to RFC793 */
  2036. static inline bool tcp_need_reset(int state)
  2037. {
  2038. return (1 << state) &
  2039. (TCPF_ESTABLISHED | TCPF_CLOSE_WAIT | TCPF_FIN_WAIT1 |
  2040. TCPF_FIN_WAIT2 | TCPF_SYN_RECV);
  2041. }
  2042. static void tcp_rtx_queue_purge(struct sock *sk)
  2043. {
  2044. struct rb_node *p = rb_first(&sk->tcp_rtx_queue);
  2045. while (p) {
  2046. struct sk_buff *skb = rb_to_skb(p);
  2047. p = rb_next(p);
  2048. /* Since we are deleting whole queue, no need to
  2049. * list_del(&skb->tcp_tsorted_anchor)
  2050. */
  2051. tcp_rtx_queue_unlink(skb, sk);
  2052. sk_wmem_free_skb(sk, skb);
  2053. }
  2054. }
  2055. void tcp_write_queue_purge(struct sock *sk)
  2056. {
  2057. struct sk_buff *skb;
  2058. tcp_chrono_stop(sk, TCP_CHRONO_BUSY);
  2059. while ((skb = __skb_dequeue(&sk->sk_write_queue)) != NULL) {
  2060. tcp_skb_tsorted_anchor_cleanup(skb);
  2061. sk_wmem_free_skb(sk, skb);
  2062. }
  2063. tcp_rtx_queue_purge(sk);
  2064. INIT_LIST_HEAD(&tcp_sk(sk)->tsorted_sent_queue);
  2065. sk_mem_reclaim(sk);
  2066. tcp_clear_all_retrans_hints(tcp_sk(sk));
  2067. }
  2068. int tcp_disconnect(struct sock *sk, int flags)
  2069. {
  2070. struct inet_sock *inet = inet_sk(sk);
  2071. struct inet_connection_sock *icsk = inet_csk(sk);
  2072. struct tcp_sock *tp = tcp_sk(sk);
  2073. int err = 0;
  2074. int old_state = sk->sk_state;
  2075. if (old_state != TCP_CLOSE)
  2076. tcp_set_state(sk, TCP_CLOSE);
  2077. /* ABORT function of RFC793 */
  2078. if (old_state == TCP_LISTEN) {
  2079. inet_csk_listen_stop(sk);
  2080. } else if (unlikely(tp->repair)) {
  2081. sk->sk_err = ECONNABORTED;
  2082. } else if (tcp_need_reset(old_state) ||
  2083. (tp->snd_nxt != tp->write_seq &&
  2084. (1 << old_state) & (TCPF_CLOSING | TCPF_LAST_ACK))) {
  2085. /* The last check adjusts for discrepancy of Linux wrt. RFC
  2086. * states
  2087. */
  2088. tcp_send_active_reset(sk, gfp_any());
  2089. sk->sk_err = ECONNRESET;
  2090. } else if (old_state == TCP_SYN_SENT)
  2091. sk->sk_err = ECONNRESET;
  2092. tcp_clear_xmit_timers(sk);
  2093. __skb_queue_purge(&sk->sk_receive_queue);
  2094. tcp_write_queue_purge(sk);
  2095. tcp_fastopen_active_disable_ofo_check(sk);
  2096. skb_rbtree_purge(&tp->out_of_order_queue);
  2097. inet->inet_dport = 0;
  2098. if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK))
  2099. inet_reset_saddr(sk);
  2100. sk->sk_shutdown = 0;
  2101. sock_reset_flag(sk, SOCK_DONE);
  2102. tp->srtt_us = 0;
  2103. tp->write_seq += tp->max_window + 2;
  2104. if (tp->write_seq == 0)
  2105. tp->write_seq = 1;
  2106. icsk->icsk_backoff = 0;
  2107. tp->snd_cwnd = 2;
  2108. icsk->icsk_probes_out = 0;
  2109. tp->packets_out = 0;
  2110. tp->snd_ssthresh = TCP_INFINITE_SSTHRESH;
  2111. tp->snd_cwnd_cnt = 0;
  2112. tp->window_clamp = 0;
  2113. tcp_set_ca_state(sk, TCP_CA_Open);
  2114. tp->is_sack_reneg = 0;
  2115. tcp_clear_retrans(tp);
  2116. inet_csk_delack_init(sk);
  2117. /* Initialize rcv_mss to TCP_MIN_MSS to avoid division by 0
  2118. * issue in __tcp_select_window()
  2119. */
  2120. icsk->icsk_ack.rcv_mss = TCP_MIN_MSS;
  2121. memset(&tp->rx_opt, 0, sizeof(tp->rx_opt));
  2122. __sk_dst_reset(sk);
  2123. dst_release(sk->sk_rx_dst);
  2124. sk->sk_rx_dst = NULL;
  2125. tcp_saved_syn_free(tp);
  2126. /* Clean up fastopen related fields */
  2127. tcp_free_fastopen_req(tp);
  2128. inet->defer_connect = 0;
  2129. WARN_ON(inet->inet_num && !icsk->icsk_bind_hash);
  2130. if (sk->sk_frag.page) {
  2131. put_page(sk->sk_frag.page);
  2132. sk->sk_frag.page = NULL;
  2133. sk->sk_frag.offset = 0;
  2134. }
  2135. sk->sk_error_report(sk);
  2136. return err;
  2137. }
  2138. EXPORT_SYMBOL(tcp_disconnect);
  2139. static inline bool tcp_can_repair_sock(const struct sock *sk)
  2140. {
  2141. return ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN) &&
  2142. (sk->sk_state != TCP_LISTEN);
  2143. }
  2144. static int tcp_repair_set_window(struct tcp_sock *tp, char __user *optbuf, int len)
  2145. {
  2146. struct tcp_repair_window opt;
  2147. if (!tp->repair)
  2148. return -EPERM;
  2149. if (len != sizeof(opt))
  2150. return -EINVAL;
  2151. if (copy_from_user(&opt, optbuf, sizeof(opt)))
  2152. return -EFAULT;
  2153. if (opt.max_window < opt.snd_wnd)
  2154. return -EINVAL;
  2155. if (after(opt.snd_wl1, tp->rcv_nxt + opt.rcv_wnd))
  2156. return -EINVAL;
  2157. if (after(opt.rcv_wup, tp->rcv_nxt))
  2158. return -EINVAL;
  2159. tp->snd_wl1 = opt.snd_wl1;
  2160. tp->snd_wnd = opt.snd_wnd;
  2161. tp->max_window = opt.max_window;
  2162. tp->rcv_wnd = opt.rcv_wnd;
  2163. tp->rcv_wup = opt.rcv_wup;
  2164. return 0;
  2165. }
  2166. static int tcp_repair_options_est(struct sock *sk,
  2167. struct tcp_repair_opt __user *optbuf, unsigned int len)
  2168. {
  2169. struct tcp_sock *tp = tcp_sk(sk);
  2170. struct tcp_repair_opt opt;
  2171. while (len >= sizeof(opt)) {
  2172. if (copy_from_user(&opt, optbuf, sizeof(opt)))
  2173. return -EFAULT;
  2174. optbuf++;
  2175. len -= sizeof(opt);
  2176. switch (opt.opt_code) {
  2177. case TCPOPT_MSS:
  2178. tp->rx_opt.mss_clamp = opt.opt_val;
  2179. tcp_mtup_init(sk);
  2180. break;
  2181. case TCPOPT_WINDOW:
  2182. {
  2183. u16 snd_wscale = opt.opt_val & 0xFFFF;
  2184. u16 rcv_wscale = opt.opt_val >> 16;
  2185. if (snd_wscale > TCP_MAX_WSCALE || rcv_wscale > TCP_MAX_WSCALE)
  2186. return -EFBIG;
  2187. tp->rx_opt.snd_wscale = snd_wscale;
  2188. tp->rx_opt.rcv_wscale = rcv_wscale;
  2189. tp->rx_opt.wscale_ok = 1;
  2190. }
  2191. break;
  2192. case TCPOPT_SACK_PERM:
  2193. if (opt.opt_val != 0)
  2194. return -EINVAL;
  2195. tp->rx_opt.sack_ok |= TCP_SACK_SEEN;
  2196. break;
  2197. case TCPOPT_TIMESTAMP:
  2198. if (opt.opt_val != 0)
  2199. return -EINVAL;
  2200. tp->rx_opt.tstamp_ok = 1;
  2201. break;
  2202. }
  2203. }
  2204. return 0;
  2205. }
  2206. /*
  2207. * Socket option code for TCP.
  2208. */
  2209. static int do_tcp_setsockopt(struct sock *sk, int level,
  2210. int optname, char __user *optval, unsigned int optlen)
  2211. {
  2212. struct tcp_sock *tp = tcp_sk(sk);
  2213. struct inet_connection_sock *icsk = inet_csk(sk);
  2214. struct net *net = sock_net(sk);
  2215. int val;
  2216. int err = 0;
  2217. /* These are data/string values, all the others are ints */
  2218. switch (optname) {
  2219. case TCP_CONGESTION: {
  2220. char name[TCP_CA_NAME_MAX];
  2221. if (optlen < 1)
  2222. return -EINVAL;
  2223. val = strncpy_from_user(name, optval,
  2224. min_t(long, TCP_CA_NAME_MAX-1, optlen));
  2225. if (val < 0)
  2226. return -EFAULT;
  2227. name[val] = 0;
  2228. lock_sock(sk);
  2229. err = tcp_set_congestion_control(sk, name, true, true);
  2230. release_sock(sk);
  2231. return err;
  2232. }
  2233. case TCP_ULP: {
  2234. char name[TCP_ULP_NAME_MAX];
  2235. if (optlen < 1)
  2236. return -EINVAL;
  2237. val = strncpy_from_user(name, optval,
  2238. min_t(long, TCP_ULP_NAME_MAX - 1,
  2239. optlen));
  2240. if (val < 0)
  2241. return -EFAULT;
  2242. name[val] = 0;
  2243. lock_sock(sk);
  2244. err = tcp_set_ulp(sk, name);
  2245. release_sock(sk);
  2246. return err;
  2247. }
  2248. case TCP_FASTOPEN_KEY: {
  2249. __u8 key[TCP_FASTOPEN_KEY_LENGTH];
  2250. if (optlen != sizeof(key))
  2251. return -EINVAL;
  2252. if (copy_from_user(key, optval, optlen))
  2253. return -EFAULT;
  2254. return tcp_fastopen_reset_cipher(net, sk, key, sizeof(key));
  2255. }
  2256. default:
  2257. /* fallthru */
  2258. break;
  2259. }
  2260. if (optlen < sizeof(int))
  2261. return -EINVAL;
  2262. if (get_user(val, (int __user *)optval))
  2263. return -EFAULT;
  2264. lock_sock(sk);
  2265. switch (optname) {
  2266. case TCP_MAXSEG:
  2267. /* Values greater than interface MTU won't take effect. However
  2268. * at the point when this call is done we typically don't yet
  2269. * know which interface is going to be used
  2270. */
  2271. if (val && (val < TCP_MIN_MSS || val > MAX_TCP_WINDOW)) {
  2272. err = -EINVAL;
  2273. break;
  2274. }
  2275. tp->rx_opt.user_mss = val;
  2276. break;
  2277. case TCP_NODELAY:
  2278. if (val) {
  2279. /* TCP_NODELAY is weaker than TCP_CORK, so that
  2280. * this option on corked socket is remembered, but
  2281. * it is not activated until cork is cleared.
  2282. *
  2283. * However, when TCP_NODELAY is set we make
  2284. * an explicit push, which overrides even TCP_CORK
  2285. * for currently queued segments.
  2286. */
  2287. tp->nonagle |= TCP_NAGLE_OFF|TCP_NAGLE_PUSH;
  2288. tcp_push_pending_frames(sk);
  2289. } else {
  2290. tp->nonagle &= ~TCP_NAGLE_OFF;
  2291. }
  2292. break;
  2293. case TCP_THIN_LINEAR_TIMEOUTS:
  2294. if (val < 0 || val > 1)
  2295. err = -EINVAL;
  2296. else
  2297. tp->thin_lto = val;
  2298. break;
  2299. case TCP_THIN_DUPACK:
  2300. if (val < 0 || val > 1)
  2301. err = -EINVAL;
  2302. break;
  2303. case TCP_REPAIR:
  2304. if (!tcp_can_repair_sock(sk))
  2305. err = -EPERM;
  2306. else if (val == 1) {
  2307. tp->repair = 1;
  2308. sk->sk_reuse = SK_FORCE_REUSE;
  2309. tp->repair_queue = TCP_NO_QUEUE;
  2310. } else if (val == 0) {
  2311. tp->repair = 0;
  2312. sk->sk_reuse = SK_NO_REUSE;
  2313. tcp_send_window_probe(sk);
  2314. } else
  2315. err = -EINVAL;
  2316. break;
  2317. case TCP_REPAIR_QUEUE:
  2318. if (!tp->repair)
  2319. err = -EPERM;
  2320. else if (val < TCP_QUEUES_NR)
  2321. tp->repair_queue = val;
  2322. else
  2323. err = -EINVAL;
  2324. break;
  2325. case TCP_QUEUE_SEQ:
  2326. if (sk->sk_state != TCP_CLOSE)
  2327. err = -EPERM;
  2328. else if (tp->repair_queue == TCP_SEND_QUEUE)
  2329. tp->write_seq = val;
  2330. else if (tp->repair_queue == TCP_RECV_QUEUE)
  2331. tp->rcv_nxt = val;
  2332. else
  2333. err = -EINVAL;
  2334. break;
  2335. case TCP_REPAIR_OPTIONS:
  2336. if (!tp->repair)
  2337. err = -EINVAL;
  2338. else if (sk->sk_state == TCP_ESTABLISHED)
  2339. err = tcp_repair_options_est(sk,
  2340. (struct tcp_repair_opt __user *)optval,
  2341. optlen);
  2342. else
  2343. err = -EPERM;
  2344. break;
  2345. case TCP_CORK:
  2346. /* When set indicates to always queue non-full frames.
  2347. * Later the user clears this option and we transmit
  2348. * any pending partial frames in the queue. This is
  2349. * meant to be used alongside sendfile() to get properly
  2350. * filled frames when the user (for example) must write
  2351. * out headers with a write() call first and then use
  2352. * sendfile to send out the data parts.
  2353. *
  2354. * TCP_CORK can be set together with TCP_NODELAY and it is
  2355. * stronger than TCP_NODELAY.
  2356. */
  2357. if (val) {
  2358. tp->nonagle |= TCP_NAGLE_CORK;
  2359. } else {
  2360. tp->nonagle &= ~TCP_NAGLE_CORK;
  2361. if (tp->nonagle&TCP_NAGLE_OFF)
  2362. tp->nonagle |= TCP_NAGLE_PUSH;
  2363. tcp_push_pending_frames(sk);
  2364. }
  2365. break;
  2366. case TCP_KEEPIDLE:
  2367. if (val < 1 || val > MAX_TCP_KEEPIDLE)
  2368. err = -EINVAL;
  2369. else {
  2370. tp->keepalive_time = val * HZ;
  2371. if (sock_flag(sk, SOCK_KEEPOPEN) &&
  2372. !((1 << sk->sk_state) &
  2373. (TCPF_CLOSE | TCPF_LISTEN))) {
  2374. u32 elapsed = keepalive_time_elapsed(tp);
  2375. if (tp->keepalive_time > elapsed)
  2376. elapsed = tp->keepalive_time - elapsed;
  2377. else
  2378. elapsed = 0;
  2379. inet_csk_reset_keepalive_timer(sk, elapsed);
  2380. }
  2381. }
  2382. break;
  2383. case TCP_KEEPINTVL:
  2384. if (val < 1 || val > MAX_TCP_KEEPINTVL)
  2385. err = -EINVAL;
  2386. else
  2387. tp->keepalive_intvl = val * HZ;
  2388. break;
  2389. case TCP_KEEPCNT:
  2390. if (val < 1 || val > MAX_TCP_KEEPCNT)
  2391. err = -EINVAL;
  2392. else
  2393. tp->keepalive_probes = val;
  2394. break;
  2395. case TCP_SYNCNT:
  2396. if (val < 1 || val > MAX_TCP_SYNCNT)
  2397. err = -EINVAL;
  2398. else
  2399. icsk->icsk_syn_retries = val;
  2400. break;
  2401. case TCP_SAVE_SYN:
  2402. if (val < 0 || val > 1)
  2403. err = -EINVAL;
  2404. else
  2405. tp->save_syn = val;
  2406. break;
  2407. case TCP_LINGER2:
  2408. if (val < 0)
  2409. tp->linger2 = -1;
  2410. else if (val > net->ipv4.sysctl_tcp_fin_timeout / HZ)
  2411. tp->linger2 = 0;
  2412. else
  2413. tp->linger2 = val * HZ;
  2414. break;
  2415. case TCP_DEFER_ACCEPT:
  2416. /* Translate value in seconds to number of retransmits */
  2417. icsk->icsk_accept_queue.rskq_defer_accept =
  2418. secs_to_retrans(val, TCP_TIMEOUT_INIT / HZ,
  2419. TCP_RTO_MAX / HZ);
  2420. break;
  2421. case TCP_WINDOW_CLAMP:
  2422. if (!val) {
  2423. if (sk->sk_state != TCP_CLOSE) {
  2424. err = -EINVAL;
  2425. break;
  2426. }
  2427. tp->window_clamp = 0;
  2428. } else
  2429. tp->window_clamp = val < SOCK_MIN_RCVBUF / 2 ?
  2430. SOCK_MIN_RCVBUF / 2 : val;
  2431. break;
  2432. case TCP_QUICKACK:
  2433. if (!val) {
  2434. icsk->icsk_ack.pingpong = 1;
  2435. } else {
  2436. icsk->icsk_ack.pingpong = 0;
  2437. if ((1 << sk->sk_state) &
  2438. (TCPF_ESTABLISHED | TCPF_CLOSE_WAIT) &&
  2439. inet_csk_ack_scheduled(sk)) {
  2440. icsk->icsk_ack.pending |= ICSK_ACK_PUSHED;
  2441. tcp_cleanup_rbuf(sk, 1);
  2442. if (!(val & 1))
  2443. icsk->icsk_ack.pingpong = 1;
  2444. }
  2445. }
  2446. break;
  2447. #ifdef CONFIG_TCP_MD5SIG
  2448. case TCP_MD5SIG:
  2449. case TCP_MD5SIG_EXT:
  2450. /* Read the IP->Key mappings from userspace */
  2451. err = tp->af_specific->md5_parse(sk, optname, optval, optlen);
  2452. break;
  2453. #endif
  2454. case TCP_USER_TIMEOUT:
  2455. /* Cap the max time in ms TCP will retry or probe the window
  2456. * before giving up and aborting (ETIMEDOUT) a connection.
  2457. */
  2458. if (val < 0)
  2459. err = -EINVAL;
  2460. else
  2461. icsk->icsk_user_timeout = msecs_to_jiffies(val);
  2462. break;
  2463. case TCP_FASTOPEN:
  2464. if (val >= 0 && ((1 << sk->sk_state) & (TCPF_CLOSE |
  2465. TCPF_LISTEN))) {
  2466. tcp_fastopen_init_key_once(net);
  2467. fastopen_queue_tune(sk, val);
  2468. } else {
  2469. err = -EINVAL;
  2470. }
  2471. break;
  2472. case TCP_FASTOPEN_CONNECT:
  2473. if (val > 1 || val < 0) {
  2474. err = -EINVAL;
  2475. } else if (net->ipv4.sysctl_tcp_fastopen & TFO_CLIENT_ENABLE) {
  2476. if (sk->sk_state == TCP_CLOSE)
  2477. tp->fastopen_connect = val;
  2478. else
  2479. err = -EINVAL;
  2480. } else {
  2481. err = -EOPNOTSUPP;
  2482. }
  2483. break;
  2484. case TCP_FASTOPEN_NO_COOKIE:
  2485. if (val > 1 || val < 0)
  2486. err = -EINVAL;
  2487. else if (!((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN)))
  2488. err = -EINVAL;
  2489. else
  2490. tp->fastopen_no_cookie = val;
  2491. break;
  2492. case TCP_TIMESTAMP:
  2493. if (!tp->repair)
  2494. err = -EPERM;
  2495. else
  2496. tp->tsoffset = val - tcp_time_stamp_raw();
  2497. break;
  2498. case TCP_REPAIR_WINDOW:
  2499. err = tcp_repair_set_window(tp, optval, optlen);
  2500. break;
  2501. case TCP_NOTSENT_LOWAT:
  2502. tp->notsent_lowat = val;
  2503. sk->sk_write_space(sk);
  2504. break;
  2505. default:
  2506. err = -ENOPROTOOPT;
  2507. break;
  2508. }
  2509. release_sock(sk);
  2510. return err;
  2511. }
  2512. int tcp_setsockopt(struct sock *sk, int level, int optname, char __user *optval,
  2513. unsigned int optlen)
  2514. {
  2515. const struct inet_connection_sock *icsk = inet_csk(sk);
  2516. if (level != SOL_TCP)
  2517. return icsk->icsk_af_ops->setsockopt(sk, level, optname,
  2518. optval, optlen);
  2519. return do_tcp_setsockopt(sk, level, optname, optval, optlen);
  2520. }
  2521. EXPORT_SYMBOL(tcp_setsockopt);
  2522. #ifdef CONFIG_COMPAT
  2523. int compat_tcp_setsockopt(struct sock *sk, int level, int optname,
  2524. char __user *optval, unsigned int optlen)
  2525. {
  2526. if (level != SOL_TCP)
  2527. return inet_csk_compat_setsockopt(sk, level, optname,
  2528. optval, optlen);
  2529. return do_tcp_setsockopt(sk, level, optname, optval, optlen);
  2530. }
  2531. EXPORT_SYMBOL(compat_tcp_setsockopt);
  2532. #endif
  2533. static void tcp_get_info_chrono_stats(const struct tcp_sock *tp,
  2534. struct tcp_info *info)
  2535. {
  2536. u64 stats[__TCP_CHRONO_MAX], total = 0;
  2537. enum tcp_chrono i;
  2538. for (i = TCP_CHRONO_BUSY; i < __TCP_CHRONO_MAX; ++i) {
  2539. stats[i] = tp->chrono_stat[i - 1];
  2540. if (i == tp->chrono_type)
  2541. stats[i] += tcp_jiffies32 - tp->chrono_start;
  2542. stats[i] *= USEC_PER_SEC / HZ;
  2543. total += stats[i];
  2544. }
  2545. info->tcpi_busy_time = total;
  2546. info->tcpi_rwnd_limited = stats[TCP_CHRONO_RWND_LIMITED];
  2547. info->tcpi_sndbuf_limited = stats[TCP_CHRONO_SNDBUF_LIMITED];
  2548. }
  2549. /* Return information about state of tcp endpoint in API format. */
  2550. void tcp_get_info(struct sock *sk, struct tcp_info *info)
  2551. {
  2552. const struct tcp_sock *tp = tcp_sk(sk); /* iff sk_type == SOCK_STREAM */
  2553. const struct inet_connection_sock *icsk = inet_csk(sk);
  2554. u32 now;
  2555. u64 rate64;
  2556. bool slow;
  2557. u32 rate;
  2558. memset(info, 0, sizeof(*info));
  2559. if (sk->sk_type != SOCK_STREAM)
  2560. return;
  2561. info->tcpi_state = inet_sk_state_load(sk);
  2562. /* Report meaningful fields for all TCP states, including listeners */
  2563. rate = READ_ONCE(sk->sk_pacing_rate);
  2564. rate64 = rate != ~0U ? rate : ~0ULL;
  2565. info->tcpi_pacing_rate = rate64;
  2566. rate = READ_ONCE(sk->sk_max_pacing_rate);
  2567. rate64 = rate != ~0U ? rate : ~0ULL;
  2568. info->tcpi_max_pacing_rate = rate64;
  2569. info->tcpi_reordering = tp->reordering;
  2570. info->tcpi_snd_cwnd = tp->snd_cwnd;
  2571. if (info->tcpi_state == TCP_LISTEN) {
  2572. /* listeners aliased fields :
  2573. * tcpi_unacked -> Number of children ready for accept()
  2574. * tcpi_sacked -> max backlog
  2575. */
  2576. info->tcpi_unacked = sk->sk_ack_backlog;
  2577. info->tcpi_sacked = sk->sk_max_ack_backlog;
  2578. return;
  2579. }
  2580. slow = lock_sock_fast(sk);
  2581. info->tcpi_ca_state = icsk->icsk_ca_state;
  2582. info->tcpi_retransmits = icsk->icsk_retransmits;
  2583. info->tcpi_probes = icsk->icsk_probes_out;
  2584. info->tcpi_backoff = icsk->icsk_backoff;
  2585. if (tp->rx_opt.tstamp_ok)
  2586. info->tcpi_options |= TCPI_OPT_TIMESTAMPS;
  2587. if (tcp_is_sack(tp))
  2588. info->tcpi_options |= TCPI_OPT_SACK;
  2589. if (tp->rx_opt.wscale_ok) {
  2590. info->tcpi_options |= TCPI_OPT_WSCALE;
  2591. info->tcpi_snd_wscale = tp->rx_opt.snd_wscale;
  2592. info->tcpi_rcv_wscale = tp->rx_opt.rcv_wscale;
  2593. }
  2594. if (tp->ecn_flags & TCP_ECN_OK)
  2595. info->tcpi_options |= TCPI_OPT_ECN;
  2596. if (tp->ecn_flags & TCP_ECN_SEEN)
  2597. info->tcpi_options |= TCPI_OPT_ECN_SEEN;
  2598. if (tp->syn_data_acked)
  2599. info->tcpi_options |= TCPI_OPT_SYN_DATA;
  2600. info->tcpi_rto = jiffies_to_usecs(icsk->icsk_rto);
  2601. info->tcpi_ato = jiffies_to_usecs(icsk->icsk_ack.ato);
  2602. info->tcpi_snd_mss = tp->mss_cache;
  2603. info->tcpi_rcv_mss = icsk->icsk_ack.rcv_mss;
  2604. info->tcpi_unacked = tp->packets_out;
  2605. info->tcpi_sacked = tp->sacked_out;
  2606. info->tcpi_lost = tp->lost_out;
  2607. info->tcpi_retrans = tp->retrans_out;
  2608. now = tcp_jiffies32;
  2609. info->tcpi_last_data_sent = jiffies_to_msecs(now - tp->lsndtime);
  2610. info->tcpi_last_data_recv = jiffies_to_msecs(now - icsk->icsk_ack.lrcvtime);
  2611. info->tcpi_last_ack_recv = jiffies_to_msecs(now - tp->rcv_tstamp);
  2612. info->tcpi_pmtu = icsk->icsk_pmtu_cookie;
  2613. info->tcpi_rcv_ssthresh = tp->rcv_ssthresh;
  2614. info->tcpi_rtt = tp->srtt_us >> 3;
  2615. info->tcpi_rttvar = tp->mdev_us >> 2;
  2616. info->tcpi_snd_ssthresh = tp->snd_ssthresh;
  2617. info->tcpi_advmss = tp->advmss;
  2618. info->tcpi_rcv_rtt = tp->rcv_rtt_est.rtt_us >> 3;
  2619. info->tcpi_rcv_space = tp->rcvq_space.space;
  2620. info->tcpi_total_retrans = tp->total_retrans;
  2621. info->tcpi_bytes_acked = tp->bytes_acked;
  2622. info->tcpi_bytes_received = tp->bytes_received;
  2623. info->tcpi_notsent_bytes = max_t(int, 0, tp->write_seq - tp->snd_nxt);
  2624. tcp_get_info_chrono_stats(tp, info);
  2625. info->tcpi_segs_out = tp->segs_out;
  2626. info->tcpi_segs_in = tp->segs_in;
  2627. info->tcpi_min_rtt = tcp_min_rtt(tp);
  2628. info->tcpi_data_segs_in = tp->data_segs_in;
  2629. info->tcpi_data_segs_out = tp->data_segs_out;
  2630. info->tcpi_delivery_rate_app_limited = tp->rate_app_limited ? 1 : 0;
  2631. rate64 = tcp_compute_delivery_rate(tp);
  2632. if (rate64)
  2633. info->tcpi_delivery_rate = rate64;
  2634. unlock_sock_fast(sk, slow);
  2635. }
  2636. EXPORT_SYMBOL_GPL(tcp_get_info);
  2637. struct sk_buff *tcp_get_timestamping_opt_stats(const struct sock *sk)
  2638. {
  2639. const struct tcp_sock *tp = tcp_sk(sk);
  2640. struct sk_buff *stats;
  2641. struct tcp_info info;
  2642. u64 rate64;
  2643. u32 rate;
  2644. stats = alloc_skb(7 * nla_total_size_64bit(sizeof(u64)) +
  2645. 3 * nla_total_size(sizeof(u32)) +
  2646. 2 * nla_total_size(sizeof(u8)), GFP_ATOMIC);
  2647. if (!stats)
  2648. return NULL;
  2649. tcp_get_info_chrono_stats(tp, &info);
  2650. nla_put_u64_64bit(stats, TCP_NLA_BUSY,
  2651. info.tcpi_busy_time, TCP_NLA_PAD);
  2652. nla_put_u64_64bit(stats, TCP_NLA_RWND_LIMITED,
  2653. info.tcpi_rwnd_limited, TCP_NLA_PAD);
  2654. nla_put_u64_64bit(stats, TCP_NLA_SNDBUF_LIMITED,
  2655. info.tcpi_sndbuf_limited, TCP_NLA_PAD);
  2656. nla_put_u64_64bit(stats, TCP_NLA_DATA_SEGS_OUT,
  2657. tp->data_segs_out, TCP_NLA_PAD);
  2658. nla_put_u64_64bit(stats, TCP_NLA_TOTAL_RETRANS,
  2659. tp->total_retrans, TCP_NLA_PAD);
  2660. rate = READ_ONCE(sk->sk_pacing_rate);
  2661. rate64 = rate != ~0U ? rate : ~0ULL;
  2662. nla_put_u64_64bit(stats, TCP_NLA_PACING_RATE, rate64, TCP_NLA_PAD);
  2663. rate64 = tcp_compute_delivery_rate(tp);
  2664. nla_put_u64_64bit(stats, TCP_NLA_DELIVERY_RATE, rate64, TCP_NLA_PAD);
  2665. nla_put_u32(stats, TCP_NLA_SND_CWND, tp->snd_cwnd);
  2666. nla_put_u32(stats, TCP_NLA_REORDERING, tp->reordering);
  2667. nla_put_u32(stats, TCP_NLA_MIN_RTT, tcp_min_rtt(tp));
  2668. nla_put_u8(stats, TCP_NLA_RECUR_RETRANS, inet_csk(sk)->icsk_retransmits);
  2669. nla_put_u8(stats, TCP_NLA_DELIVERY_RATE_APP_LMT, !!tp->rate_app_limited);
  2670. return stats;
  2671. }
  2672. static int do_tcp_getsockopt(struct sock *sk, int level,
  2673. int optname, char __user *optval, int __user *optlen)
  2674. {
  2675. struct inet_connection_sock *icsk = inet_csk(sk);
  2676. struct tcp_sock *tp = tcp_sk(sk);
  2677. struct net *net = sock_net(sk);
  2678. int val, len;
  2679. if (get_user(len, optlen))
  2680. return -EFAULT;
  2681. len = min_t(unsigned int, len, sizeof(int));
  2682. if (len < 0)
  2683. return -EINVAL;
  2684. switch (optname) {
  2685. case TCP_MAXSEG:
  2686. val = tp->mss_cache;
  2687. if (!val && ((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN)))
  2688. val = tp->rx_opt.user_mss;
  2689. if (tp->repair)
  2690. val = tp->rx_opt.mss_clamp;
  2691. break;
  2692. case TCP_NODELAY:
  2693. val = !!(tp->nonagle&TCP_NAGLE_OFF);
  2694. break;
  2695. case TCP_CORK:
  2696. val = !!(tp->nonagle&TCP_NAGLE_CORK);
  2697. break;
  2698. case TCP_KEEPIDLE:
  2699. val = keepalive_time_when(tp) / HZ;
  2700. break;
  2701. case TCP_KEEPINTVL:
  2702. val = keepalive_intvl_when(tp) / HZ;
  2703. break;
  2704. case TCP_KEEPCNT:
  2705. val = keepalive_probes(tp);
  2706. break;
  2707. case TCP_SYNCNT:
  2708. val = icsk->icsk_syn_retries ? : net->ipv4.sysctl_tcp_syn_retries;
  2709. break;
  2710. case TCP_LINGER2:
  2711. val = tp->linger2;
  2712. if (val >= 0)
  2713. val = (val ? : net->ipv4.sysctl_tcp_fin_timeout) / HZ;
  2714. break;
  2715. case TCP_DEFER_ACCEPT:
  2716. val = retrans_to_secs(icsk->icsk_accept_queue.rskq_defer_accept,
  2717. TCP_TIMEOUT_INIT / HZ, TCP_RTO_MAX / HZ);
  2718. break;
  2719. case TCP_WINDOW_CLAMP:
  2720. val = tp->window_clamp;
  2721. break;
  2722. case TCP_INFO: {
  2723. struct tcp_info info;
  2724. if (get_user(len, optlen))
  2725. return -EFAULT;
  2726. tcp_get_info(sk, &info);
  2727. len = min_t(unsigned int, len, sizeof(info));
  2728. if (put_user(len, optlen))
  2729. return -EFAULT;
  2730. if (copy_to_user(optval, &info, len))
  2731. return -EFAULT;
  2732. return 0;
  2733. }
  2734. case TCP_CC_INFO: {
  2735. const struct tcp_congestion_ops *ca_ops;
  2736. union tcp_cc_info info;
  2737. size_t sz = 0;
  2738. int attr;
  2739. if (get_user(len, optlen))
  2740. return -EFAULT;
  2741. ca_ops = icsk->icsk_ca_ops;
  2742. if (ca_ops && ca_ops->get_info)
  2743. sz = ca_ops->get_info(sk, ~0U, &attr, &info);
  2744. len = min_t(unsigned int, len, sz);
  2745. if (put_user(len, optlen))
  2746. return -EFAULT;
  2747. if (copy_to_user(optval, &info, len))
  2748. return -EFAULT;
  2749. return 0;
  2750. }
  2751. case TCP_QUICKACK:
  2752. val = !icsk->icsk_ack.pingpong;
  2753. break;
  2754. case TCP_CONGESTION:
  2755. if (get_user(len, optlen))
  2756. return -EFAULT;
  2757. len = min_t(unsigned int, len, TCP_CA_NAME_MAX);
  2758. if (put_user(len, optlen))
  2759. return -EFAULT;
  2760. if (copy_to_user(optval, icsk->icsk_ca_ops->name, len))
  2761. return -EFAULT;
  2762. return 0;
  2763. case TCP_ULP:
  2764. if (get_user(len, optlen))
  2765. return -EFAULT;
  2766. len = min_t(unsigned int, len, TCP_ULP_NAME_MAX);
  2767. if (!icsk->icsk_ulp_ops) {
  2768. if (put_user(0, optlen))
  2769. return -EFAULT;
  2770. return 0;
  2771. }
  2772. if (put_user(len, optlen))
  2773. return -EFAULT;
  2774. if (copy_to_user(optval, icsk->icsk_ulp_ops->name, len))
  2775. return -EFAULT;
  2776. return 0;
  2777. case TCP_FASTOPEN_KEY: {
  2778. __u8 key[TCP_FASTOPEN_KEY_LENGTH];
  2779. struct tcp_fastopen_context *ctx;
  2780. if (get_user(len, optlen))
  2781. return -EFAULT;
  2782. rcu_read_lock();
  2783. ctx = rcu_dereference(icsk->icsk_accept_queue.fastopenq.ctx);
  2784. if (ctx)
  2785. memcpy(key, ctx->key, sizeof(key));
  2786. else
  2787. len = 0;
  2788. rcu_read_unlock();
  2789. len = min_t(unsigned int, len, sizeof(key));
  2790. if (put_user(len, optlen))
  2791. return -EFAULT;
  2792. if (copy_to_user(optval, key, len))
  2793. return -EFAULT;
  2794. return 0;
  2795. }
  2796. case TCP_THIN_LINEAR_TIMEOUTS:
  2797. val = tp->thin_lto;
  2798. break;
  2799. case TCP_THIN_DUPACK:
  2800. val = 0;
  2801. break;
  2802. case TCP_REPAIR:
  2803. val = tp->repair;
  2804. break;
  2805. case TCP_REPAIR_QUEUE:
  2806. if (tp->repair)
  2807. val = tp->repair_queue;
  2808. else
  2809. return -EINVAL;
  2810. break;
  2811. case TCP_REPAIR_WINDOW: {
  2812. struct tcp_repair_window opt;
  2813. if (get_user(len, optlen))
  2814. return -EFAULT;
  2815. if (len != sizeof(opt))
  2816. return -EINVAL;
  2817. if (!tp->repair)
  2818. return -EPERM;
  2819. opt.snd_wl1 = tp->snd_wl1;
  2820. opt.snd_wnd = tp->snd_wnd;
  2821. opt.max_window = tp->max_window;
  2822. opt.rcv_wnd = tp->rcv_wnd;
  2823. opt.rcv_wup = tp->rcv_wup;
  2824. if (copy_to_user(optval, &opt, len))
  2825. return -EFAULT;
  2826. return 0;
  2827. }
  2828. case TCP_QUEUE_SEQ:
  2829. if (tp->repair_queue == TCP_SEND_QUEUE)
  2830. val = tp->write_seq;
  2831. else if (tp->repair_queue == TCP_RECV_QUEUE)
  2832. val = tp->rcv_nxt;
  2833. else
  2834. return -EINVAL;
  2835. break;
  2836. case TCP_USER_TIMEOUT:
  2837. val = jiffies_to_msecs(icsk->icsk_user_timeout);
  2838. break;
  2839. case TCP_FASTOPEN:
  2840. val = icsk->icsk_accept_queue.fastopenq.max_qlen;
  2841. break;
  2842. case TCP_FASTOPEN_CONNECT:
  2843. val = tp->fastopen_connect;
  2844. break;
  2845. case TCP_FASTOPEN_NO_COOKIE:
  2846. val = tp->fastopen_no_cookie;
  2847. break;
  2848. case TCP_TIMESTAMP:
  2849. val = tcp_time_stamp_raw() + tp->tsoffset;
  2850. break;
  2851. case TCP_NOTSENT_LOWAT:
  2852. val = tp->notsent_lowat;
  2853. break;
  2854. case TCP_SAVE_SYN:
  2855. val = tp->save_syn;
  2856. break;
  2857. case TCP_SAVED_SYN: {
  2858. if (get_user(len, optlen))
  2859. return -EFAULT;
  2860. lock_sock(sk);
  2861. if (tp->saved_syn) {
  2862. if (len < tp->saved_syn[0]) {
  2863. if (put_user(tp->saved_syn[0], optlen)) {
  2864. release_sock(sk);
  2865. return -EFAULT;
  2866. }
  2867. release_sock(sk);
  2868. return -EINVAL;
  2869. }
  2870. len = tp->saved_syn[0];
  2871. if (put_user(len, optlen)) {
  2872. release_sock(sk);
  2873. return -EFAULT;
  2874. }
  2875. if (copy_to_user(optval, tp->saved_syn + 1, len)) {
  2876. release_sock(sk);
  2877. return -EFAULT;
  2878. }
  2879. tcp_saved_syn_free(tp);
  2880. release_sock(sk);
  2881. } else {
  2882. release_sock(sk);
  2883. len = 0;
  2884. if (put_user(len, optlen))
  2885. return -EFAULT;
  2886. }
  2887. return 0;
  2888. }
  2889. default:
  2890. return -ENOPROTOOPT;
  2891. }
  2892. if (put_user(len, optlen))
  2893. return -EFAULT;
  2894. if (copy_to_user(optval, &val, len))
  2895. return -EFAULT;
  2896. return 0;
  2897. }
  2898. int tcp_getsockopt(struct sock *sk, int level, int optname, char __user *optval,
  2899. int __user *optlen)
  2900. {
  2901. struct inet_connection_sock *icsk = inet_csk(sk);
  2902. if (level != SOL_TCP)
  2903. return icsk->icsk_af_ops->getsockopt(sk, level, optname,
  2904. optval, optlen);
  2905. return do_tcp_getsockopt(sk, level, optname, optval, optlen);
  2906. }
  2907. EXPORT_SYMBOL(tcp_getsockopt);
  2908. #ifdef CONFIG_COMPAT
  2909. int compat_tcp_getsockopt(struct sock *sk, int level, int optname,
  2910. char __user *optval, int __user *optlen)
  2911. {
  2912. if (level != SOL_TCP)
  2913. return inet_csk_compat_getsockopt(sk, level, optname,
  2914. optval, optlen);
  2915. return do_tcp_getsockopt(sk, level, optname, optval, optlen);
  2916. }
  2917. EXPORT_SYMBOL(compat_tcp_getsockopt);
  2918. #endif
  2919. #ifdef CONFIG_TCP_MD5SIG
  2920. static DEFINE_PER_CPU(struct tcp_md5sig_pool, tcp_md5sig_pool);
  2921. static DEFINE_MUTEX(tcp_md5sig_mutex);
  2922. static bool tcp_md5sig_pool_populated = false;
  2923. static void __tcp_alloc_md5sig_pool(void)
  2924. {
  2925. struct crypto_ahash *hash;
  2926. int cpu;
  2927. hash = crypto_alloc_ahash("md5", 0, CRYPTO_ALG_ASYNC);
  2928. if (IS_ERR(hash))
  2929. return;
  2930. for_each_possible_cpu(cpu) {
  2931. void *scratch = per_cpu(tcp_md5sig_pool, cpu).scratch;
  2932. struct ahash_request *req;
  2933. if (!scratch) {
  2934. scratch = kmalloc_node(sizeof(union tcp_md5sum_block) +
  2935. sizeof(struct tcphdr),
  2936. GFP_KERNEL,
  2937. cpu_to_node(cpu));
  2938. if (!scratch)
  2939. return;
  2940. per_cpu(tcp_md5sig_pool, cpu).scratch = scratch;
  2941. }
  2942. if (per_cpu(tcp_md5sig_pool, cpu).md5_req)
  2943. continue;
  2944. req = ahash_request_alloc(hash, GFP_KERNEL);
  2945. if (!req)
  2946. return;
  2947. ahash_request_set_callback(req, 0, NULL, NULL);
  2948. per_cpu(tcp_md5sig_pool, cpu).md5_req = req;
  2949. }
  2950. /* before setting tcp_md5sig_pool_populated, we must commit all writes
  2951. * to memory. See smp_rmb() in tcp_get_md5sig_pool()
  2952. */
  2953. smp_wmb();
  2954. tcp_md5sig_pool_populated = true;
  2955. }
  2956. bool tcp_alloc_md5sig_pool(void)
  2957. {
  2958. if (unlikely(!tcp_md5sig_pool_populated)) {
  2959. mutex_lock(&tcp_md5sig_mutex);
  2960. if (!tcp_md5sig_pool_populated)
  2961. __tcp_alloc_md5sig_pool();
  2962. mutex_unlock(&tcp_md5sig_mutex);
  2963. }
  2964. return tcp_md5sig_pool_populated;
  2965. }
  2966. EXPORT_SYMBOL(tcp_alloc_md5sig_pool);
  2967. /**
  2968. * tcp_get_md5sig_pool - get md5sig_pool for this user
  2969. *
  2970. * We use percpu structure, so if we succeed, we exit with preemption
  2971. * and BH disabled, to make sure another thread or softirq handling
  2972. * wont try to get same context.
  2973. */
  2974. struct tcp_md5sig_pool *tcp_get_md5sig_pool(void)
  2975. {
  2976. local_bh_disable();
  2977. if (tcp_md5sig_pool_populated) {
  2978. /* coupled with smp_wmb() in __tcp_alloc_md5sig_pool() */
  2979. smp_rmb();
  2980. return this_cpu_ptr(&tcp_md5sig_pool);
  2981. }
  2982. local_bh_enable();
  2983. return NULL;
  2984. }
  2985. EXPORT_SYMBOL(tcp_get_md5sig_pool);
  2986. int tcp_md5_hash_skb_data(struct tcp_md5sig_pool *hp,
  2987. const struct sk_buff *skb, unsigned int header_len)
  2988. {
  2989. struct scatterlist sg;
  2990. const struct tcphdr *tp = tcp_hdr(skb);
  2991. struct ahash_request *req = hp->md5_req;
  2992. unsigned int i;
  2993. const unsigned int head_data_len = skb_headlen(skb) > header_len ?
  2994. skb_headlen(skb) - header_len : 0;
  2995. const struct skb_shared_info *shi = skb_shinfo(skb);
  2996. struct sk_buff *frag_iter;
  2997. sg_init_table(&sg, 1);
  2998. sg_set_buf(&sg, ((u8 *) tp) + header_len, head_data_len);
  2999. ahash_request_set_crypt(req, &sg, NULL, head_data_len);
  3000. if (crypto_ahash_update(req))
  3001. return 1;
  3002. for (i = 0; i < shi->nr_frags; ++i) {
  3003. const struct skb_frag_struct *f = &shi->frags[i];
  3004. unsigned int offset = f->page_offset;
  3005. struct page *page = skb_frag_page(f) + (offset >> PAGE_SHIFT);
  3006. sg_set_page(&sg, page, skb_frag_size(f),
  3007. offset_in_page(offset));
  3008. ahash_request_set_crypt(req, &sg, NULL, skb_frag_size(f));
  3009. if (crypto_ahash_update(req))
  3010. return 1;
  3011. }
  3012. skb_walk_frags(skb, frag_iter)
  3013. if (tcp_md5_hash_skb_data(hp, frag_iter, 0))
  3014. return 1;
  3015. return 0;
  3016. }
  3017. EXPORT_SYMBOL(tcp_md5_hash_skb_data);
  3018. int tcp_md5_hash_key(struct tcp_md5sig_pool *hp, const struct tcp_md5sig_key *key)
  3019. {
  3020. struct scatterlist sg;
  3021. sg_init_one(&sg, key->key, key->keylen);
  3022. ahash_request_set_crypt(hp->md5_req, &sg, NULL, key->keylen);
  3023. return crypto_ahash_update(hp->md5_req);
  3024. }
  3025. EXPORT_SYMBOL(tcp_md5_hash_key);
  3026. #endif
  3027. void tcp_done(struct sock *sk)
  3028. {
  3029. struct request_sock *req = tcp_sk(sk)->fastopen_rsk;
  3030. if (sk->sk_state == TCP_SYN_SENT || sk->sk_state == TCP_SYN_RECV)
  3031. TCP_INC_STATS(sock_net(sk), TCP_MIB_ATTEMPTFAILS);
  3032. tcp_set_state(sk, TCP_CLOSE);
  3033. tcp_clear_xmit_timers(sk);
  3034. if (req)
  3035. reqsk_fastopen_remove(sk, req, false);
  3036. sk->sk_shutdown = SHUTDOWN_MASK;
  3037. if (!sock_flag(sk, SOCK_DEAD))
  3038. sk->sk_state_change(sk);
  3039. else
  3040. inet_csk_destroy_sock(sk);
  3041. }
  3042. EXPORT_SYMBOL_GPL(tcp_done);
  3043. int tcp_abort(struct sock *sk, int err)
  3044. {
  3045. if (!sk_fullsock(sk)) {
  3046. if (sk->sk_state == TCP_NEW_SYN_RECV) {
  3047. struct request_sock *req = inet_reqsk(sk);
  3048. local_bh_disable();
  3049. inet_csk_reqsk_queue_drop_and_put(req->rsk_listener,
  3050. req);
  3051. local_bh_enable();
  3052. return 0;
  3053. }
  3054. return -EOPNOTSUPP;
  3055. }
  3056. /* Don't race with userspace socket closes such as tcp_close. */
  3057. lock_sock(sk);
  3058. if (sk->sk_state == TCP_LISTEN) {
  3059. tcp_set_state(sk, TCP_CLOSE);
  3060. inet_csk_listen_stop(sk);
  3061. }
  3062. /* Don't race with BH socket closes such as inet_csk_listen_stop. */
  3063. local_bh_disable();
  3064. bh_lock_sock(sk);
  3065. if (!sock_flag(sk, SOCK_DEAD)) {
  3066. sk->sk_err = err;
  3067. /* This barrier is coupled with smp_rmb() in tcp_poll() */
  3068. smp_wmb();
  3069. sk->sk_error_report(sk);
  3070. if (tcp_need_reset(sk->sk_state))
  3071. tcp_send_active_reset(sk, GFP_ATOMIC);
  3072. tcp_done(sk);
  3073. }
  3074. bh_unlock_sock(sk);
  3075. local_bh_enable();
  3076. release_sock(sk);
  3077. return 0;
  3078. }
  3079. EXPORT_SYMBOL_GPL(tcp_abort);
  3080. extern struct tcp_congestion_ops tcp_reno;
  3081. static __initdata unsigned long thash_entries;
  3082. static int __init set_thash_entries(char *str)
  3083. {
  3084. ssize_t ret;
  3085. if (!str)
  3086. return 0;
  3087. ret = kstrtoul(str, 0, &thash_entries);
  3088. if (ret)
  3089. return 0;
  3090. return 1;
  3091. }
  3092. __setup("thash_entries=", set_thash_entries);
  3093. static void __init tcp_init_mem(void)
  3094. {
  3095. unsigned long limit = nr_free_buffer_pages() / 16;
  3096. limit = max(limit, 128UL);
  3097. sysctl_tcp_mem[0] = limit / 4 * 3; /* 4.68 % */
  3098. sysctl_tcp_mem[1] = limit; /* 6.25 % */
  3099. sysctl_tcp_mem[2] = sysctl_tcp_mem[0] * 2; /* 9.37 % */
  3100. }
  3101. void __init tcp_init(void)
  3102. {
  3103. int max_rshare, max_wshare, cnt;
  3104. unsigned long limit;
  3105. unsigned int i;
  3106. BUILD_BUG_ON(sizeof(struct tcp_skb_cb) >
  3107. FIELD_SIZEOF(struct sk_buff, cb));
  3108. percpu_counter_init(&tcp_sockets_allocated, 0, GFP_KERNEL);
  3109. percpu_counter_init(&tcp_orphan_count, 0, GFP_KERNEL);
  3110. inet_hashinfo_init(&tcp_hashinfo);
  3111. inet_hashinfo2_init(&tcp_hashinfo, "tcp_listen_portaddr_hash",
  3112. thash_entries, 21, /* one slot per 2 MB*/
  3113. 0, 64 * 1024);
  3114. tcp_hashinfo.bind_bucket_cachep =
  3115. kmem_cache_create("tcp_bind_bucket",
  3116. sizeof(struct inet_bind_bucket), 0,
  3117. SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL);
  3118. /* Size and allocate the main established and bind bucket
  3119. * hash tables.
  3120. *
  3121. * The methodology is similar to that of the buffer cache.
  3122. */
  3123. tcp_hashinfo.ehash =
  3124. alloc_large_system_hash("TCP established",
  3125. sizeof(struct inet_ehash_bucket),
  3126. thash_entries,
  3127. 17, /* one slot per 128 KB of memory */
  3128. 0,
  3129. NULL,
  3130. &tcp_hashinfo.ehash_mask,
  3131. 0,
  3132. thash_entries ? 0 : 512 * 1024);
  3133. for (i = 0; i <= tcp_hashinfo.ehash_mask; i++)
  3134. INIT_HLIST_NULLS_HEAD(&tcp_hashinfo.ehash[i].chain, i);
  3135. if (inet_ehash_locks_alloc(&tcp_hashinfo))
  3136. panic("TCP: failed to alloc ehash_locks");
  3137. tcp_hashinfo.bhash =
  3138. alloc_large_system_hash("TCP bind",
  3139. sizeof(struct inet_bind_hashbucket),
  3140. tcp_hashinfo.ehash_mask + 1,
  3141. 17, /* one slot per 128 KB of memory */
  3142. 0,
  3143. &tcp_hashinfo.bhash_size,
  3144. NULL,
  3145. 0,
  3146. 64 * 1024);
  3147. tcp_hashinfo.bhash_size = 1U << tcp_hashinfo.bhash_size;
  3148. for (i = 0; i < tcp_hashinfo.bhash_size; i++) {
  3149. spin_lock_init(&tcp_hashinfo.bhash[i].lock);
  3150. INIT_HLIST_HEAD(&tcp_hashinfo.bhash[i].chain);
  3151. }
  3152. cnt = tcp_hashinfo.ehash_mask + 1;
  3153. sysctl_tcp_max_orphans = cnt / 2;
  3154. tcp_init_mem();
  3155. /* Set per-socket limits to no more than 1/128 the pressure threshold */
  3156. limit = nr_free_buffer_pages() << (PAGE_SHIFT - 7);
  3157. max_wshare = min(4UL*1024*1024, limit);
  3158. max_rshare = min(6UL*1024*1024, limit);
  3159. init_net.ipv4.sysctl_tcp_wmem[0] = SK_MEM_QUANTUM;
  3160. init_net.ipv4.sysctl_tcp_wmem[1] = 16*1024;
  3161. init_net.ipv4.sysctl_tcp_wmem[2] = max(64*1024, max_wshare);
  3162. init_net.ipv4.sysctl_tcp_rmem[0] = SK_MEM_QUANTUM;
  3163. init_net.ipv4.sysctl_tcp_rmem[1] = 87380;
  3164. init_net.ipv4.sysctl_tcp_rmem[2] = max(87380, max_rshare);
  3165. pr_info("Hash tables configured (established %u bind %u)\n",
  3166. tcp_hashinfo.ehash_mask + 1, tcp_hashinfo.bhash_size);
  3167. tcp_v4_init();
  3168. tcp_metrics_init();
  3169. BUG_ON(tcp_register_congestion_control(&tcp_reno) != 0);
  3170. tcp_tasklet_init();
  3171. }