tcp.c 91 KB

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