tcp.c 102 KB

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