tcp.c 93 KB

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