tcp.c 93 KB

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