tcp.c 101 KB

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