tcp.c 93 KB

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