tcp.c 83 KB

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