tcp.c 89 KB

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