tcp.c 80 KB

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