tcp.c 101 KB

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