tcp_output.c 129 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * INET An implementation of the TCP/IP protocol suite for the LINUX
  4. * operating system. INET is implemented using the BSD Socket
  5. * interface as the means of communication with the user level.
  6. *
  7. * Implementation of the Transmission Control Protocol(TCP).
  8. *
  9. * Authors: Ross Biro
  10. * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
  11. * Mark Evans, <evansmp@uhura.aston.ac.uk>
  12. * Corey Minyard <wf-rch!minyard@relay.EU.net>
  13. * Florian La Roche, <flla@stud.uni-sb.de>
  14. * Charles Hedrick, <hedrick@klinzhai.rutgers.edu>
  15. * Linus Torvalds, <torvalds@cs.helsinki.fi>
  16. * Alan Cox, <gw4pts@gw4pts.ampr.org>
  17. * Matthew Dillon, <dillon@apollo.west.oic.com>
  18. * Arnt Gulbrandsen, <agulbra@nvg.unit.no>
  19. * Jorge Cwik, <jorge@laser.satlink.net>
  20. */
  21. /*
  22. * Changes: Pedro Roque : Retransmit queue handled by TCP.
  23. * : Fragmentation on mtu decrease
  24. * : Segment collapse on retransmit
  25. * : AF independence
  26. *
  27. * Linus Torvalds : send_delayed_ack
  28. * David S. Miller : Charge memory using the right skb
  29. * during syn/ack processing.
  30. * David S. Miller : Output engine completely rewritten.
  31. * Andrea Arcangeli: SYNACK carry ts_recent in tsecr.
  32. * Cacophonix Gaul : draft-minshall-nagle-01
  33. * J Hadi Salim : ECN support
  34. *
  35. */
  36. #define pr_fmt(fmt) "TCP: " fmt
  37. #include <net/tcp.h>
  38. #include <net/mptcp.h>
  39. #include <net/proto_memory.h>
  40. #include <linux/compiler.h>
  41. #include <linux/gfp.h>
  42. #include <linux/module.h>
  43. #include <linux/static_key.h>
  44. #include <linux/skbuff_ref.h>
  45. #include <trace/events/tcp.h>
  46. /* Refresh clocks of a TCP socket,
  47. * ensuring monotically increasing values.
  48. */
  49. void tcp_mstamp_refresh(struct tcp_sock *tp)
  50. {
  51. u64 val = tcp_clock_ns();
  52. tp->tcp_clock_cache = val;
  53. tp->tcp_mstamp = div_u64(val, NSEC_PER_USEC);
  54. }
  55. static bool tcp_write_xmit(struct sock *sk, unsigned int mss_now, int nonagle,
  56. int push_one, gfp_t gfp);
  57. /* Account for new data that has been sent to the network. */
  58. static void tcp_event_new_data_sent(struct sock *sk, struct sk_buff *skb)
  59. {
  60. struct inet_connection_sock *icsk = inet_csk(sk);
  61. struct tcp_sock *tp = tcp_sk(sk);
  62. unsigned int prior_packets = tp->packets_out;
  63. WRITE_ONCE(tp->snd_nxt, TCP_SKB_CB(skb)->end_seq);
  64. __skb_unlink(skb, &sk->sk_write_queue);
  65. tcp_rbtree_insert(&sk->tcp_rtx_queue, skb);
  66. if (tp->highest_sack == NULL)
  67. tp->highest_sack = skb;
  68. tp->packets_out += tcp_skb_pcount(skb);
  69. if (!prior_packets || icsk->icsk_pending == ICSK_TIME_LOSS_PROBE)
  70. tcp_rearm_rto(sk);
  71. NET_ADD_STATS(sock_net(sk), LINUX_MIB_TCPORIGDATASENT,
  72. tcp_skb_pcount(skb));
  73. tcp_check_space(sk);
  74. }
  75. /* SND.NXT, if window was not shrunk or the amount of shrunk was less than one
  76. * window scaling factor due to loss of precision.
  77. * If window has been shrunk, what should we make? It is not clear at all.
  78. * Using SND.UNA we will fail to open window, SND.NXT is out of window. :-(
  79. * Anything in between SND.UNA...SND.UNA+SND.WND also can be already
  80. * invalid. OK, let's make this for now:
  81. */
  82. static inline __u32 tcp_acceptable_seq(const struct sock *sk)
  83. {
  84. const struct tcp_sock *tp = tcp_sk(sk);
  85. if (!before(tcp_wnd_end(tp), tp->snd_nxt) ||
  86. (tp->rx_opt.wscale_ok &&
  87. ((tp->snd_nxt - tcp_wnd_end(tp)) < (1 << tp->rx_opt.rcv_wscale))))
  88. return tp->snd_nxt;
  89. else
  90. return tcp_wnd_end(tp);
  91. }
  92. /* Calculate mss to advertise in SYN segment.
  93. * RFC1122, RFC1063, draft-ietf-tcpimpl-pmtud-01 state that:
  94. *
  95. * 1. It is independent of path mtu.
  96. * 2. Ideally, it is maximal possible segment size i.e. 65535-40.
  97. * 3. For IPv4 it is reasonable to calculate it from maximal MTU of
  98. * attached devices, because some buggy hosts are confused by
  99. * large MSS.
  100. * 4. We do not make 3, we advertise MSS, calculated from first
  101. * hop device mtu, but allow to raise it to ip_rt_min_advmss.
  102. * This may be overridden via information stored in routing table.
  103. * 5. Value 65535 for MSS is valid in IPv6 and means "as large as possible,
  104. * probably even Jumbo".
  105. */
  106. static __u16 tcp_advertise_mss(struct sock *sk)
  107. {
  108. struct tcp_sock *tp = tcp_sk(sk);
  109. const struct dst_entry *dst = __sk_dst_get(sk);
  110. int mss = tp->advmss;
  111. if (dst) {
  112. unsigned int metric = dst_metric_advmss(dst);
  113. if (metric < mss) {
  114. mss = metric;
  115. tp->advmss = mss;
  116. }
  117. }
  118. return (__u16)mss;
  119. }
  120. /* RFC2861. Reset CWND after idle period longer RTO to "restart window".
  121. * This is the first part of cwnd validation mechanism.
  122. */
  123. void tcp_cwnd_restart(struct sock *sk, s32 delta)
  124. {
  125. struct tcp_sock *tp = tcp_sk(sk);
  126. u32 restart_cwnd = tcp_init_cwnd(tp, __sk_dst_get(sk));
  127. u32 cwnd = tcp_snd_cwnd(tp);
  128. tcp_ca_event(sk, CA_EVENT_CWND_RESTART);
  129. tp->snd_ssthresh = tcp_current_ssthresh(sk);
  130. restart_cwnd = min(restart_cwnd, cwnd);
  131. while ((delta -= inet_csk(sk)->icsk_rto) > 0 && cwnd > restart_cwnd)
  132. cwnd >>= 1;
  133. tcp_snd_cwnd_set(tp, max(cwnd, restart_cwnd));
  134. tp->snd_cwnd_stamp = tcp_jiffies32;
  135. tp->snd_cwnd_used = 0;
  136. }
  137. /* Congestion state accounting after a packet has been sent. */
  138. static void tcp_event_data_sent(struct tcp_sock *tp,
  139. struct sock *sk)
  140. {
  141. struct inet_connection_sock *icsk = inet_csk(sk);
  142. const u32 now = tcp_jiffies32;
  143. if (tcp_packets_in_flight(tp) == 0)
  144. tcp_ca_event(sk, CA_EVENT_TX_START);
  145. tp->lsndtime = now;
  146. /* If it is a reply for ato after last received
  147. * packet, increase pingpong count.
  148. */
  149. if ((u32)(now - icsk->icsk_ack.lrcvtime) < icsk->icsk_ack.ato)
  150. inet_csk_inc_pingpong_cnt(sk);
  151. }
  152. /* Account for an ACK we sent. */
  153. static inline void tcp_event_ack_sent(struct sock *sk, u32 rcv_nxt)
  154. {
  155. struct tcp_sock *tp = tcp_sk(sk);
  156. if (unlikely(tp->compressed_ack)) {
  157. NET_ADD_STATS(sock_net(sk), LINUX_MIB_TCPACKCOMPRESSED,
  158. tp->compressed_ack);
  159. tp->compressed_ack = 0;
  160. if (hrtimer_try_to_cancel(&tp->compressed_ack_timer) == 1)
  161. __sock_put(sk);
  162. }
  163. if (unlikely(rcv_nxt != tp->rcv_nxt))
  164. return; /* Special ACK sent by DCTCP to reflect ECN */
  165. tcp_dec_quickack_mode(sk);
  166. inet_csk_clear_xmit_timer(sk, ICSK_TIME_DACK);
  167. }
  168. /* Determine a window scaling and initial window to offer.
  169. * Based on the assumption that the given amount of space
  170. * will be offered. Store the results in the tp structure.
  171. * NOTE: for smooth operation initial space offering should
  172. * be a multiple of mss if possible. We assume here that mss >= 1.
  173. * This MUST be enforced by all callers.
  174. */
  175. void tcp_select_initial_window(const struct sock *sk, int __space, __u32 mss,
  176. __u32 *rcv_wnd, __u32 *__window_clamp,
  177. int wscale_ok, __u8 *rcv_wscale,
  178. __u32 init_rcv_wnd)
  179. {
  180. unsigned int space = (__space < 0 ? 0 : __space);
  181. u32 window_clamp = READ_ONCE(*__window_clamp);
  182. /* If no clamp set the clamp to the max possible scaled window */
  183. if (window_clamp == 0)
  184. window_clamp = (U16_MAX << TCP_MAX_WSCALE);
  185. space = min(window_clamp, space);
  186. /* Quantize space offering to a multiple of mss if possible. */
  187. if (space > mss)
  188. space = rounddown(space, mss);
  189. /* NOTE: offering an initial window larger than 32767
  190. * will break some buggy TCP stacks. If the admin tells us
  191. * it is likely we could be speaking with such a buggy stack
  192. * we will truncate our initial window offering to 32K-1
  193. * unless the remote has sent us a window scaling option,
  194. * which we interpret as a sign the remote TCP is not
  195. * misinterpreting the window field as a signed quantity.
  196. */
  197. if (READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_workaround_signed_windows))
  198. (*rcv_wnd) = min(space, MAX_TCP_WINDOW);
  199. else
  200. (*rcv_wnd) = space;
  201. if (init_rcv_wnd)
  202. *rcv_wnd = min(*rcv_wnd, init_rcv_wnd * mss);
  203. *rcv_wscale = 0;
  204. if (wscale_ok) {
  205. /* Set window scaling on max possible window */
  206. space = max_t(u32, space, READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_rmem[2]));
  207. space = max_t(u32, space, READ_ONCE(sysctl_rmem_max));
  208. space = min_t(u32, space, window_clamp);
  209. *rcv_wscale = clamp_t(int, ilog2(space) - 15,
  210. 0, TCP_MAX_WSCALE);
  211. }
  212. /* Set the clamp no higher than max representable value */
  213. WRITE_ONCE(*__window_clamp,
  214. min_t(__u32, U16_MAX << (*rcv_wscale), window_clamp));
  215. }
  216. EXPORT_SYMBOL(tcp_select_initial_window);
  217. /* Chose a new window to advertise, update state in tcp_sock for the
  218. * socket, and return result with RFC1323 scaling applied. The return
  219. * value can be stuffed directly into th->window for an outgoing
  220. * frame.
  221. */
  222. static u16 tcp_select_window(struct sock *sk)
  223. {
  224. struct tcp_sock *tp = tcp_sk(sk);
  225. struct net *net = sock_net(sk);
  226. u32 old_win = tp->rcv_wnd;
  227. u32 cur_win, new_win;
  228. /* Make the window 0 if we failed to queue the data because we
  229. * are out of memory.
  230. */
  231. if (unlikely(inet_csk(sk)->icsk_ack.pending & ICSK_ACK_NOMEM)) {
  232. tp->pred_flags = 0;
  233. tp->rcv_wnd = 0;
  234. tp->rcv_wup = tp->rcv_nxt;
  235. return 0;
  236. }
  237. cur_win = tcp_receive_window(tp);
  238. new_win = __tcp_select_window(sk);
  239. if (new_win < cur_win) {
  240. /* Danger Will Robinson!
  241. * Don't update rcv_wup/rcv_wnd here or else
  242. * we will not be able to advertise a zero
  243. * window in time. --DaveM
  244. *
  245. * Relax Will Robinson.
  246. */
  247. if (!READ_ONCE(net->ipv4.sysctl_tcp_shrink_window) || !tp->rx_opt.rcv_wscale) {
  248. /* Never shrink the offered window */
  249. if (new_win == 0)
  250. NET_INC_STATS(net, LINUX_MIB_TCPWANTZEROWINDOWADV);
  251. new_win = ALIGN(cur_win, 1 << tp->rx_opt.rcv_wscale);
  252. }
  253. }
  254. tp->rcv_wnd = new_win;
  255. tp->rcv_wup = tp->rcv_nxt;
  256. /* Make sure we do not exceed the maximum possible
  257. * scaled window.
  258. */
  259. if (!tp->rx_opt.rcv_wscale &&
  260. READ_ONCE(net->ipv4.sysctl_tcp_workaround_signed_windows))
  261. new_win = min(new_win, MAX_TCP_WINDOW);
  262. else
  263. new_win = min(new_win, (65535U << tp->rx_opt.rcv_wscale));
  264. /* RFC1323 scaling applied */
  265. new_win >>= tp->rx_opt.rcv_wscale;
  266. /* If we advertise zero window, disable fast path. */
  267. if (new_win == 0) {
  268. tp->pred_flags = 0;
  269. if (old_win)
  270. NET_INC_STATS(net, LINUX_MIB_TCPTOZEROWINDOWADV);
  271. } else if (old_win == 0) {
  272. NET_INC_STATS(net, LINUX_MIB_TCPFROMZEROWINDOWADV);
  273. }
  274. return new_win;
  275. }
  276. /* Packet ECN state for a SYN-ACK */
  277. static void tcp_ecn_send_synack(struct sock *sk, struct sk_buff *skb)
  278. {
  279. const struct tcp_sock *tp = tcp_sk(sk);
  280. TCP_SKB_CB(skb)->tcp_flags &= ~TCPHDR_CWR;
  281. if (!(tp->ecn_flags & TCP_ECN_OK))
  282. TCP_SKB_CB(skb)->tcp_flags &= ~TCPHDR_ECE;
  283. else if (tcp_ca_needs_ecn(sk) ||
  284. tcp_bpf_ca_needs_ecn(sk))
  285. INET_ECN_xmit(sk);
  286. }
  287. /* Packet ECN state for a SYN. */
  288. static void tcp_ecn_send_syn(struct sock *sk, struct sk_buff *skb)
  289. {
  290. struct tcp_sock *tp = tcp_sk(sk);
  291. bool bpf_needs_ecn = tcp_bpf_ca_needs_ecn(sk);
  292. bool use_ecn = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_ecn) == 1 ||
  293. tcp_ca_needs_ecn(sk) || bpf_needs_ecn;
  294. if (!use_ecn) {
  295. const struct dst_entry *dst = __sk_dst_get(sk);
  296. if (dst && dst_feature(dst, RTAX_FEATURE_ECN))
  297. use_ecn = true;
  298. }
  299. tp->ecn_flags = 0;
  300. if (use_ecn) {
  301. TCP_SKB_CB(skb)->tcp_flags |= TCPHDR_ECE | TCPHDR_CWR;
  302. tp->ecn_flags = TCP_ECN_OK;
  303. if (tcp_ca_needs_ecn(sk) || bpf_needs_ecn)
  304. INET_ECN_xmit(sk);
  305. }
  306. }
  307. static void tcp_ecn_clear_syn(struct sock *sk, struct sk_buff *skb)
  308. {
  309. if (READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_ecn_fallback))
  310. /* tp->ecn_flags are cleared at a later point in time when
  311. * SYN ACK is ultimatively being received.
  312. */
  313. TCP_SKB_CB(skb)->tcp_flags &= ~(TCPHDR_ECE | TCPHDR_CWR);
  314. }
  315. static void
  316. tcp_ecn_make_synack(const struct request_sock *req, struct tcphdr *th)
  317. {
  318. if (inet_rsk(req)->ecn_ok)
  319. th->ece = 1;
  320. }
  321. /* Set up ECN state for a packet on a ESTABLISHED socket that is about to
  322. * be sent.
  323. */
  324. static void tcp_ecn_send(struct sock *sk, struct sk_buff *skb,
  325. struct tcphdr *th, int tcp_header_len)
  326. {
  327. struct tcp_sock *tp = tcp_sk(sk);
  328. if (tp->ecn_flags & TCP_ECN_OK) {
  329. /* Not-retransmitted data segment: set ECT and inject CWR. */
  330. if (skb->len != tcp_header_len &&
  331. !before(TCP_SKB_CB(skb)->seq, tp->snd_nxt)) {
  332. INET_ECN_xmit(sk);
  333. if (tp->ecn_flags & TCP_ECN_QUEUE_CWR) {
  334. tp->ecn_flags &= ~TCP_ECN_QUEUE_CWR;
  335. th->cwr = 1;
  336. skb_shinfo(skb)->gso_type |= SKB_GSO_TCP_ECN;
  337. }
  338. } else if (!tcp_ca_needs_ecn(sk)) {
  339. /* ACK or retransmitted segment: clear ECT|CE */
  340. INET_ECN_dontxmit(sk);
  341. }
  342. if (tp->ecn_flags & TCP_ECN_DEMAND_CWR)
  343. th->ece = 1;
  344. }
  345. }
  346. /* Constructs common control bits of non-data skb. If SYN/FIN is present,
  347. * auto increment end seqno.
  348. */
  349. static void tcp_init_nondata_skb(struct sk_buff *skb, u32 seq, u8 flags)
  350. {
  351. skb->ip_summed = CHECKSUM_PARTIAL;
  352. TCP_SKB_CB(skb)->tcp_flags = flags;
  353. tcp_skb_pcount_set(skb, 1);
  354. TCP_SKB_CB(skb)->seq = seq;
  355. if (flags & (TCPHDR_SYN | TCPHDR_FIN))
  356. seq++;
  357. TCP_SKB_CB(skb)->end_seq = seq;
  358. }
  359. static inline bool tcp_urg_mode(const struct tcp_sock *tp)
  360. {
  361. return tp->snd_una != tp->snd_up;
  362. }
  363. #define OPTION_SACK_ADVERTISE BIT(0)
  364. #define OPTION_TS BIT(1)
  365. #define OPTION_MD5 BIT(2)
  366. #define OPTION_WSCALE BIT(3)
  367. #define OPTION_FAST_OPEN_COOKIE BIT(8)
  368. #define OPTION_SMC BIT(9)
  369. #define OPTION_MPTCP BIT(10)
  370. #define OPTION_AO BIT(11)
  371. static void smc_options_write(__be32 *ptr, u16 *options)
  372. {
  373. #if IS_ENABLED(CONFIG_SMC)
  374. if (static_branch_unlikely(&tcp_have_smc)) {
  375. if (unlikely(OPTION_SMC & *options)) {
  376. *ptr++ = htonl((TCPOPT_NOP << 24) |
  377. (TCPOPT_NOP << 16) |
  378. (TCPOPT_EXP << 8) |
  379. (TCPOLEN_EXP_SMC_BASE));
  380. *ptr++ = htonl(TCPOPT_SMC_MAGIC);
  381. }
  382. }
  383. #endif
  384. }
  385. struct tcp_out_options {
  386. u16 options; /* bit field of OPTION_* */
  387. u16 mss; /* 0 to disable */
  388. u8 ws; /* window scale, 0 to disable */
  389. u8 num_sack_blocks; /* number of SACK blocks to include */
  390. u8 hash_size; /* bytes in hash_location */
  391. u8 bpf_opt_len; /* length of BPF hdr option */
  392. __u8 *hash_location; /* temporary pointer, overloaded */
  393. __u32 tsval, tsecr; /* need to include OPTION_TS */
  394. struct tcp_fastopen_cookie *fastopen_cookie; /* Fast open cookie */
  395. struct mptcp_out_options mptcp;
  396. };
  397. static void mptcp_options_write(struct tcphdr *th, __be32 *ptr,
  398. struct tcp_sock *tp,
  399. struct tcp_out_options *opts)
  400. {
  401. #if IS_ENABLED(CONFIG_MPTCP)
  402. if (unlikely(OPTION_MPTCP & opts->options))
  403. mptcp_write_options(th, ptr, tp, &opts->mptcp);
  404. #endif
  405. }
  406. #ifdef CONFIG_CGROUP_BPF
  407. static int bpf_skops_write_hdr_opt_arg0(struct sk_buff *skb,
  408. enum tcp_synack_type synack_type)
  409. {
  410. if (unlikely(!skb))
  411. return BPF_WRITE_HDR_TCP_CURRENT_MSS;
  412. if (unlikely(synack_type == TCP_SYNACK_COOKIE))
  413. return BPF_WRITE_HDR_TCP_SYNACK_COOKIE;
  414. return 0;
  415. }
  416. /* req, syn_skb and synack_type are used when writing synack */
  417. static void bpf_skops_hdr_opt_len(struct sock *sk, struct sk_buff *skb,
  418. struct request_sock *req,
  419. struct sk_buff *syn_skb,
  420. enum tcp_synack_type synack_type,
  421. struct tcp_out_options *opts,
  422. unsigned int *remaining)
  423. {
  424. struct bpf_sock_ops_kern sock_ops;
  425. int err;
  426. if (likely(!BPF_SOCK_OPS_TEST_FLAG(tcp_sk(sk),
  427. BPF_SOCK_OPS_WRITE_HDR_OPT_CB_FLAG)) ||
  428. !*remaining)
  429. return;
  430. /* *remaining has already been aligned to 4 bytes, so *remaining >= 4 */
  431. /* init sock_ops */
  432. memset(&sock_ops, 0, offsetof(struct bpf_sock_ops_kern, temp));
  433. sock_ops.op = BPF_SOCK_OPS_HDR_OPT_LEN_CB;
  434. if (req) {
  435. /* The listen "sk" cannot be passed here because
  436. * it is not locked. It would not make too much
  437. * sense to do bpf_setsockopt(listen_sk) based
  438. * on individual connection request also.
  439. *
  440. * Thus, "req" is passed here and the cgroup-bpf-progs
  441. * of the listen "sk" will be run.
  442. *
  443. * "req" is also used here for fastopen even the "sk" here is
  444. * a fullsock "child" sk. It is to keep the behavior
  445. * consistent between fastopen and non-fastopen on
  446. * the bpf programming side.
  447. */
  448. sock_ops.sk = (struct sock *)req;
  449. sock_ops.syn_skb = syn_skb;
  450. } else {
  451. sock_owned_by_me(sk);
  452. sock_ops.is_fullsock = 1;
  453. sock_ops.sk = sk;
  454. }
  455. sock_ops.args[0] = bpf_skops_write_hdr_opt_arg0(skb, synack_type);
  456. sock_ops.remaining_opt_len = *remaining;
  457. /* tcp_current_mss() does not pass a skb */
  458. if (skb)
  459. bpf_skops_init_skb(&sock_ops, skb, 0);
  460. err = BPF_CGROUP_RUN_PROG_SOCK_OPS_SK(&sock_ops, sk);
  461. if (err || sock_ops.remaining_opt_len == *remaining)
  462. return;
  463. opts->bpf_opt_len = *remaining - sock_ops.remaining_opt_len;
  464. /* round up to 4 bytes */
  465. opts->bpf_opt_len = (opts->bpf_opt_len + 3) & ~3;
  466. *remaining -= opts->bpf_opt_len;
  467. }
  468. static void bpf_skops_write_hdr_opt(struct sock *sk, struct sk_buff *skb,
  469. struct request_sock *req,
  470. struct sk_buff *syn_skb,
  471. enum tcp_synack_type synack_type,
  472. struct tcp_out_options *opts)
  473. {
  474. u8 first_opt_off, nr_written, max_opt_len = opts->bpf_opt_len;
  475. struct bpf_sock_ops_kern sock_ops;
  476. int err;
  477. if (likely(!max_opt_len))
  478. return;
  479. memset(&sock_ops, 0, offsetof(struct bpf_sock_ops_kern, temp));
  480. sock_ops.op = BPF_SOCK_OPS_WRITE_HDR_OPT_CB;
  481. if (req) {
  482. sock_ops.sk = (struct sock *)req;
  483. sock_ops.syn_skb = syn_skb;
  484. } else {
  485. sock_owned_by_me(sk);
  486. sock_ops.is_fullsock = 1;
  487. sock_ops.sk = sk;
  488. }
  489. sock_ops.args[0] = bpf_skops_write_hdr_opt_arg0(skb, synack_type);
  490. sock_ops.remaining_opt_len = max_opt_len;
  491. first_opt_off = tcp_hdrlen(skb) - max_opt_len;
  492. bpf_skops_init_skb(&sock_ops, skb, first_opt_off);
  493. err = BPF_CGROUP_RUN_PROG_SOCK_OPS_SK(&sock_ops, sk);
  494. if (err)
  495. nr_written = 0;
  496. else
  497. nr_written = max_opt_len - sock_ops.remaining_opt_len;
  498. if (nr_written < max_opt_len)
  499. memset(skb->data + first_opt_off + nr_written, TCPOPT_NOP,
  500. max_opt_len - nr_written);
  501. }
  502. #else
  503. static void bpf_skops_hdr_opt_len(struct sock *sk, struct sk_buff *skb,
  504. struct request_sock *req,
  505. struct sk_buff *syn_skb,
  506. enum tcp_synack_type synack_type,
  507. struct tcp_out_options *opts,
  508. unsigned int *remaining)
  509. {
  510. }
  511. static void bpf_skops_write_hdr_opt(struct sock *sk, struct sk_buff *skb,
  512. struct request_sock *req,
  513. struct sk_buff *syn_skb,
  514. enum tcp_synack_type synack_type,
  515. struct tcp_out_options *opts)
  516. {
  517. }
  518. #endif
  519. static __be32 *process_tcp_ao_options(struct tcp_sock *tp,
  520. const struct tcp_request_sock *tcprsk,
  521. struct tcp_out_options *opts,
  522. struct tcp_key *key, __be32 *ptr)
  523. {
  524. #ifdef CONFIG_TCP_AO
  525. u8 maclen = tcp_ao_maclen(key->ao_key);
  526. if (tcprsk) {
  527. u8 aolen = maclen + sizeof(struct tcp_ao_hdr);
  528. *ptr++ = htonl((TCPOPT_AO << 24) | (aolen << 16) |
  529. (tcprsk->ao_keyid << 8) |
  530. (tcprsk->ao_rcv_next));
  531. } else {
  532. struct tcp_ao_key *rnext_key;
  533. struct tcp_ao_info *ao_info;
  534. ao_info = rcu_dereference_check(tp->ao_info,
  535. lockdep_sock_is_held(&tp->inet_conn.icsk_inet.sk));
  536. rnext_key = READ_ONCE(ao_info->rnext_key);
  537. if (WARN_ON_ONCE(!rnext_key))
  538. return ptr;
  539. *ptr++ = htonl((TCPOPT_AO << 24) |
  540. (tcp_ao_len(key->ao_key) << 16) |
  541. (key->ao_key->sndid << 8) |
  542. (rnext_key->rcvid));
  543. }
  544. opts->hash_location = (__u8 *)ptr;
  545. ptr += maclen / sizeof(*ptr);
  546. if (unlikely(maclen % sizeof(*ptr))) {
  547. memset(ptr, TCPOPT_NOP, sizeof(*ptr));
  548. ptr++;
  549. }
  550. #endif
  551. return ptr;
  552. }
  553. /* Write previously computed TCP options to the packet.
  554. *
  555. * Beware: Something in the Internet is very sensitive to the ordering of
  556. * TCP options, we learned this through the hard way, so be careful here.
  557. * Luckily we can at least blame others for their non-compliance but from
  558. * inter-operability perspective it seems that we're somewhat stuck with
  559. * the ordering which we have been using if we want to keep working with
  560. * those broken things (not that it currently hurts anybody as there isn't
  561. * particular reason why the ordering would need to be changed).
  562. *
  563. * At least SACK_PERM as the first option is known to lead to a disaster
  564. * (but it may well be that other scenarios fail similarly).
  565. */
  566. static void tcp_options_write(struct tcphdr *th, struct tcp_sock *tp,
  567. const struct tcp_request_sock *tcprsk,
  568. struct tcp_out_options *opts,
  569. struct tcp_key *key)
  570. {
  571. __be32 *ptr = (__be32 *)(th + 1);
  572. u16 options = opts->options; /* mungable copy */
  573. if (tcp_key_is_md5(key)) {
  574. *ptr++ = htonl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) |
  575. (TCPOPT_MD5SIG << 8) | TCPOLEN_MD5SIG);
  576. /* overload cookie hash location */
  577. opts->hash_location = (__u8 *)ptr;
  578. ptr += 4;
  579. } else if (tcp_key_is_ao(key)) {
  580. ptr = process_tcp_ao_options(tp, tcprsk, opts, key, ptr);
  581. }
  582. if (unlikely(opts->mss)) {
  583. *ptr++ = htonl((TCPOPT_MSS << 24) |
  584. (TCPOLEN_MSS << 16) |
  585. opts->mss);
  586. }
  587. if (likely(OPTION_TS & options)) {
  588. if (unlikely(OPTION_SACK_ADVERTISE & options)) {
  589. *ptr++ = htonl((TCPOPT_SACK_PERM << 24) |
  590. (TCPOLEN_SACK_PERM << 16) |
  591. (TCPOPT_TIMESTAMP << 8) |
  592. TCPOLEN_TIMESTAMP);
  593. options &= ~OPTION_SACK_ADVERTISE;
  594. } else {
  595. *ptr++ = htonl((TCPOPT_NOP << 24) |
  596. (TCPOPT_NOP << 16) |
  597. (TCPOPT_TIMESTAMP << 8) |
  598. TCPOLEN_TIMESTAMP);
  599. }
  600. *ptr++ = htonl(opts->tsval);
  601. *ptr++ = htonl(opts->tsecr);
  602. }
  603. if (unlikely(OPTION_SACK_ADVERTISE & options)) {
  604. *ptr++ = htonl((TCPOPT_NOP << 24) |
  605. (TCPOPT_NOP << 16) |
  606. (TCPOPT_SACK_PERM << 8) |
  607. TCPOLEN_SACK_PERM);
  608. }
  609. if (unlikely(OPTION_WSCALE & options)) {
  610. *ptr++ = htonl((TCPOPT_NOP << 24) |
  611. (TCPOPT_WINDOW << 16) |
  612. (TCPOLEN_WINDOW << 8) |
  613. opts->ws);
  614. }
  615. if (unlikely(opts->num_sack_blocks)) {
  616. struct tcp_sack_block *sp = tp->rx_opt.dsack ?
  617. tp->duplicate_sack : tp->selective_acks;
  618. int this_sack;
  619. *ptr++ = htonl((TCPOPT_NOP << 24) |
  620. (TCPOPT_NOP << 16) |
  621. (TCPOPT_SACK << 8) |
  622. (TCPOLEN_SACK_BASE + (opts->num_sack_blocks *
  623. TCPOLEN_SACK_PERBLOCK)));
  624. for (this_sack = 0; this_sack < opts->num_sack_blocks;
  625. ++this_sack) {
  626. *ptr++ = htonl(sp[this_sack].start_seq);
  627. *ptr++ = htonl(sp[this_sack].end_seq);
  628. }
  629. tp->rx_opt.dsack = 0;
  630. }
  631. if (unlikely(OPTION_FAST_OPEN_COOKIE & options)) {
  632. struct tcp_fastopen_cookie *foc = opts->fastopen_cookie;
  633. u8 *p = (u8 *)ptr;
  634. u32 len; /* Fast Open option length */
  635. if (foc->exp) {
  636. len = TCPOLEN_EXP_FASTOPEN_BASE + foc->len;
  637. *ptr = htonl((TCPOPT_EXP << 24) | (len << 16) |
  638. TCPOPT_FASTOPEN_MAGIC);
  639. p += TCPOLEN_EXP_FASTOPEN_BASE;
  640. } else {
  641. len = TCPOLEN_FASTOPEN_BASE + foc->len;
  642. *p++ = TCPOPT_FASTOPEN;
  643. *p++ = len;
  644. }
  645. memcpy(p, foc->val, foc->len);
  646. if ((len & 3) == 2) {
  647. p[foc->len] = TCPOPT_NOP;
  648. p[foc->len + 1] = TCPOPT_NOP;
  649. }
  650. ptr += (len + 3) >> 2;
  651. }
  652. smc_options_write(ptr, &options);
  653. mptcp_options_write(th, ptr, tp, opts);
  654. }
  655. static void smc_set_option(const struct tcp_sock *tp,
  656. struct tcp_out_options *opts,
  657. unsigned int *remaining)
  658. {
  659. #if IS_ENABLED(CONFIG_SMC)
  660. if (static_branch_unlikely(&tcp_have_smc)) {
  661. if (tp->syn_smc) {
  662. if (*remaining >= TCPOLEN_EXP_SMC_BASE_ALIGNED) {
  663. opts->options |= OPTION_SMC;
  664. *remaining -= TCPOLEN_EXP_SMC_BASE_ALIGNED;
  665. }
  666. }
  667. }
  668. #endif
  669. }
  670. static void smc_set_option_cond(const struct tcp_sock *tp,
  671. const struct inet_request_sock *ireq,
  672. struct tcp_out_options *opts,
  673. unsigned int *remaining)
  674. {
  675. #if IS_ENABLED(CONFIG_SMC)
  676. if (static_branch_unlikely(&tcp_have_smc)) {
  677. if (tp->syn_smc && ireq->smc_ok) {
  678. if (*remaining >= TCPOLEN_EXP_SMC_BASE_ALIGNED) {
  679. opts->options |= OPTION_SMC;
  680. *remaining -= TCPOLEN_EXP_SMC_BASE_ALIGNED;
  681. }
  682. }
  683. }
  684. #endif
  685. }
  686. static void mptcp_set_option_cond(const struct request_sock *req,
  687. struct tcp_out_options *opts,
  688. unsigned int *remaining)
  689. {
  690. if (rsk_is_mptcp(req)) {
  691. unsigned int size;
  692. if (mptcp_synack_options(req, &size, &opts->mptcp)) {
  693. if (*remaining >= size) {
  694. opts->options |= OPTION_MPTCP;
  695. *remaining -= size;
  696. }
  697. }
  698. }
  699. }
  700. /* Compute TCP options for SYN packets. This is not the final
  701. * network wire format yet.
  702. */
  703. static unsigned int tcp_syn_options(struct sock *sk, struct sk_buff *skb,
  704. struct tcp_out_options *opts,
  705. struct tcp_key *key)
  706. {
  707. struct tcp_sock *tp = tcp_sk(sk);
  708. unsigned int remaining = MAX_TCP_OPTION_SPACE;
  709. struct tcp_fastopen_request *fastopen = tp->fastopen_req;
  710. bool timestamps;
  711. /* Better than switch (key.type) as it has static branches */
  712. if (tcp_key_is_md5(key)) {
  713. timestamps = false;
  714. opts->options |= OPTION_MD5;
  715. remaining -= TCPOLEN_MD5SIG_ALIGNED;
  716. } else {
  717. timestamps = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_timestamps);
  718. if (tcp_key_is_ao(key)) {
  719. opts->options |= OPTION_AO;
  720. remaining -= tcp_ao_len_aligned(key->ao_key);
  721. }
  722. }
  723. /* We always get an MSS option. The option bytes which will be seen in
  724. * normal data packets should timestamps be used, must be in the MSS
  725. * advertised. But we subtract them from tp->mss_cache so that
  726. * calculations in tcp_sendmsg are simpler etc. So account for this
  727. * fact here if necessary. If we don't do this correctly, as a
  728. * receiver we won't recognize data packets as being full sized when we
  729. * should, and thus we won't abide by the delayed ACK rules correctly.
  730. * SACKs don't matter, we never delay an ACK when we have any of those
  731. * going out. */
  732. opts->mss = tcp_advertise_mss(sk);
  733. remaining -= TCPOLEN_MSS_ALIGNED;
  734. if (likely(timestamps)) {
  735. opts->options |= OPTION_TS;
  736. opts->tsval = tcp_skb_timestamp_ts(tp->tcp_usec_ts, skb) + tp->tsoffset;
  737. opts->tsecr = tp->rx_opt.ts_recent;
  738. remaining -= TCPOLEN_TSTAMP_ALIGNED;
  739. }
  740. if (likely(READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_window_scaling))) {
  741. opts->ws = tp->rx_opt.rcv_wscale;
  742. opts->options |= OPTION_WSCALE;
  743. remaining -= TCPOLEN_WSCALE_ALIGNED;
  744. }
  745. if (likely(READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_sack))) {
  746. opts->options |= OPTION_SACK_ADVERTISE;
  747. if (unlikely(!(OPTION_TS & opts->options)))
  748. remaining -= TCPOLEN_SACKPERM_ALIGNED;
  749. }
  750. if (fastopen && fastopen->cookie.len >= 0) {
  751. u32 need = fastopen->cookie.len;
  752. need += fastopen->cookie.exp ? TCPOLEN_EXP_FASTOPEN_BASE :
  753. TCPOLEN_FASTOPEN_BASE;
  754. need = (need + 3) & ~3U; /* Align to 32 bits */
  755. if (remaining >= need) {
  756. opts->options |= OPTION_FAST_OPEN_COOKIE;
  757. opts->fastopen_cookie = &fastopen->cookie;
  758. remaining -= need;
  759. tp->syn_fastopen = 1;
  760. tp->syn_fastopen_exp = fastopen->cookie.exp ? 1 : 0;
  761. }
  762. }
  763. smc_set_option(tp, opts, &remaining);
  764. if (sk_is_mptcp(sk)) {
  765. unsigned int size;
  766. if (mptcp_syn_options(sk, skb, &size, &opts->mptcp)) {
  767. if (remaining >= size) {
  768. opts->options |= OPTION_MPTCP;
  769. remaining -= size;
  770. }
  771. }
  772. }
  773. bpf_skops_hdr_opt_len(sk, skb, NULL, NULL, 0, opts, &remaining);
  774. return MAX_TCP_OPTION_SPACE - remaining;
  775. }
  776. /* Set up TCP options for SYN-ACKs. */
  777. static unsigned int tcp_synack_options(const struct sock *sk,
  778. struct request_sock *req,
  779. unsigned int mss, struct sk_buff *skb,
  780. struct tcp_out_options *opts,
  781. const struct tcp_key *key,
  782. struct tcp_fastopen_cookie *foc,
  783. enum tcp_synack_type synack_type,
  784. struct sk_buff *syn_skb)
  785. {
  786. struct inet_request_sock *ireq = inet_rsk(req);
  787. unsigned int remaining = MAX_TCP_OPTION_SPACE;
  788. if (tcp_key_is_md5(key)) {
  789. opts->options |= OPTION_MD5;
  790. remaining -= TCPOLEN_MD5SIG_ALIGNED;
  791. /* We can't fit any SACK blocks in a packet with MD5 + TS
  792. * options. There was discussion about disabling SACK
  793. * rather than TS in order to fit in better with old,
  794. * buggy kernels, but that was deemed to be unnecessary.
  795. */
  796. if (synack_type != TCP_SYNACK_COOKIE)
  797. ireq->tstamp_ok &= !ireq->sack_ok;
  798. } else if (tcp_key_is_ao(key)) {
  799. opts->options |= OPTION_AO;
  800. remaining -= tcp_ao_len_aligned(key->ao_key);
  801. ireq->tstamp_ok &= !ireq->sack_ok;
  802. }
  803. /* We always send an MSS option. */
  804. opts->mss = mss;
  805. remaining -= TCPOLEN_MSS_ALIGNED;
  806. if (likely(ireq->wscale_ok)) {
  807. opts->ws = ireq->rcv_wscale;
  808. opts->options |= OPTION_WSCALE;
  809. remaining -= TCPOLEN_WSCALE_ALIGNED;
  810. }
  811. if (likely(ireq->tstamp_ok)) {
  812. opts->options |= OPTION_TS;
  813. opts->tsval = tcp_skb_timestamp_ts(tcp_rsk(req)->req_usec_ts, skb) +
  814. tcp_rsk(req)->ts_off;
  815. opts->tsecr = READ_ONCE(req->ts_recent);
  816. remaining -= TCPOLEN_TSTAMP_ALIGNED;
  817. }
  818. if (likely(ireq->sack_ok)) {
  819. opts->options |= OPTION_SACK_ADVERTISE;
  820. if (unlikely(!ireq->tstamp_ok))
  821. remaining -= TCPOLEN_SACKPERM_ALIGNED;
  822. }
  823. if (foc != NULL && foc->len >= 0) {
  824. u32 need = foc->len;
  825. need += foc->exp ? TCPOLEN_EXP_FASTOPEN_BASE :
  826. TCPOLEN_FASTOPEN_BASE;
  827. need = (need + 3) & ~3U; /* Align to 32 bits */
  828. if (remaining >= need) {
  829. opts->options |= OPTION_FAST_OPEN_COOKIE;
  830. opts->fastopen_cookie = foc;
  831. remaining -= need;
  832. }
  833. }
  834. mptcp_set_option_cond(req, opts, &remaining);
  835. smc_set_option_cond(tcp_sk(sk), ireq, opts, &remaining);
  836. bpf_skops_hdr_opt_len((struct sock *)sk, skb, req, syn_skb,
  837. synack_type, opts, &remaining);
  838. return MAX_TCP_OPTION_SPACE - remaining;
  839. }
  840. /* Compute TCP options for ESTABLISHED sockets. This is not the
  841. * final wire format yet.
  842. */
  843. static unsigned int tcp_established_options(struct sock *sk, struct sk_buff *skb,
  844. struct tcp_out_options *opts,
  845. struct tcp_key *key)
  846. {
  847. struct tcp_sock *tp = tcp_sk(sk);
  848. unsigned int size = 0;
  849. unsigned int eff_sacks;
  850. opts->options = 0;
  851. /* Better than switch (key.type) as it has static branches */
  852. if (tcp_key_is_md5(key)) {
  853. opts->options |= OPTION_MD5;
  854. size += TCPOLEN_MD5SIG_ALIGNED;
  855. } else if (tcp_key_is_ao(key)) {
  856. opts->options |= OPTION_AO;
  857. size += tcp_ao_len_aligned(key->ao_key);
  858. }
  859. if (likely(tp->rx_opt.tstamp_ok)) {
  860. opts->options |= OPTION_TS;
  861. opts->tsval = skb ? tcp_skb_timestamp_ts(tp->tcp_usec_ts, skb) +
  862. tp->tsoffset : 0;
  863. opts->tsecr = tp->rx_opt.ts_recent;
  864. size += TCPOLEN_TSTAMP_ALIGNED;
  865. }
  866. /* MPTCP options have precedence over SACK for the limited TCP
  867. * option space because a MPTCP connection would be forced to
  868. * fall back to regular TCP if a required multipath option is
  869. * missing. SACK still gets a chance to use whatever space is
  870. * left.
  871. */
  872. if (sk_is_mptcp(sk)) {
  873. unsigned int remaining = MAX_TCP_OPTION_SPACE - size;
  874. unsigned int opt_size = 0;
  875. if (mptcp_established_options(sk, skb, &opt_size, remaining,
  876. &opts->mptcp)) {
  877. opts->options |= OPTION_MPTCP;
  878. size += opt_size;
  879. }
  880. }
  881. eff_sacks = tp->rx_opt.num_sacks + tp->rx_opt.dsack;
  882. if (unlikely(eff_sacks)) {
  883. const unsigned int remaining = MAX_TCP_OPTION_SPACE - size;
  884. if (unlikely(remaining < TCPOLEN_SACK_BASE_ALIGNED +
  885. TCPOLEN_SACK_PERBLOCK))
  886. return size;
  887. opts->num_sack_blocks =
  888. min_t(unsigned int, eff_sacks,
  889. (remaining - TCPOLEN_SACK_BASE_ALIGNED) /
  890. TCPOLEN_SACK_PERBLOCK);
  891. size += TCPOLEN_SACK_BASE_ALIGNED +
  892. opts->num_sack_blocks * TCPOLEN_SACK_PERBLOCK;
  893. }
  894. if (unlikely(BPF_SOCK_OPS_TEST_FLAG(tp,
  895. BPF_SOCK_OPS_WRITE_HDR_OPT_CB_FLAG))) {
  896. unsigned int remaining = MAX_TCP_OPTION_SPACE - size;
  897. bpf_skops_hdr_opt_len(sk, skb, NULL, NULL, 0, opts, &remaining);
  898. size = MAX_TCP_OPTION_SPACE - remaining;
  899. }
  900. return size;
  901. }
  902. /* TCP SMALL QUEUES (TSQ)
  903. *
  904. * TSQ goal is to keep small amount of skbs per tcp flow in tx queues (qdisc+dev)
  905. * to reduce RTT and bufferbloat.
  906. * We do this using a special skb destructor (tcp_wfree).
  907. *
  908. * Its important tcp_wfree() can be replaced by sock_wfree() in the event skb
  909. * needs to be reallocated in a driver.
  910. * The invariant being skb->truesize subtracted from sk->sk_wmem_alloc
  911. *
  912. * Since transmit from skb destructor is forbidden, we use a tasklet
  913. * to process all sockets that eventually need to send more skbs.
  914. * We use one tasklet per cpu, with its own queue of sockets.
  915. */
  916. struct tsq_tasklet {
  917. struct tasklet_struct tasklet;
  918. struct list_head head; /* queue of tcp sockets */
  919. };
  920. static DEFINE_PER_CPU(struct tsq_tasklet, tsq_tasklet);
  921. static void tcp_tsq_write(struct sock *sk)
  922. {
  923. if ((1 << sk->sk_state) &
  924. (TCPF_ESTABLISHED | TCPF_FIN_WAIT1 | TCPF_CLOSING |
  925. TCPF_CLOSE_WAIT | TCPF_LAST_ACK)) {
  926. struct tcp_sock *tp = tcp_sk(sk);
  927. if (tp->lost_out > tp->retrans_out &&
  928. tcp_snd_cwnd(tp) > tcp_packets_in_flight(tp)) {
  929. tcp_mstamp_refresh(tp);
  930. tcp_xmit_retransmit_queue(sk);
  931. }
  932. tcp_write_xmit(sk, tcp_current_mss(sk), tp->nonagle,
  933. 0, GFP_ATOMIC);
  934. }
  935. }
  936. static void tcp_tsq_handler(struct sock *sk)
  937. {
  938. bh_lock_sock(sk);
  939. if (!sock_owned_by_user(sk))
  940. tcp_tsq_write(sk);
  941. else if (!test_and_set_bit(TCP_TSQ_DEFERRED, &sk->sk_tsq_flags))
  942. sock_hold(sk);
  943. bh_unlock_sock(sk);
  944. }
  945. /*
  946. * One tasklet per cpu tries to send more skbs.
  947. * We run in tasklet context but need to disable irqs when
  948. * transferring tsq->head because tcp_wfree() might
  949. * interrupt us (non NAPI drivers)
  950. */
  951. static void tcp_tasklet_func(struct tasklet_struct *t)
  952. {
  953. struct tsq_tasklet *tsq = from_tasklet(tsq, t, tasklet);
  954. LIST_HEAD(list);
  955. unsigned long flags;
  956. struct list_head *q, *n;
  957. struct tcp_sock *tp;
  958. struct sock *sk;
  959. local_irq_save(flags);
  960. list_splice_init(&tsq->head, &list);
  961. local_irq_restore(flags);
  962. list_for_each_safe(q, n, &list) {
  963. tp = list_entry(q, struct tcp_sock, tsq_node);
  964. list_del(&tp->tsq_node);
  965. sk = (struct sock *)tp;
  966. smp_mb__before_atomic();
  967. clear_bit(TSQ_QUEUED, &sk->sk_tsq_flags);
  968. tcp_tsq_handler(sk);
  969. sk_free(sk);
  970. }
  971. }
  972. #define TCP_DEFERRED_ALL (TCPF_TSQ_DEFERRED | \
  973. TCPF_WRITE_TIMER_DEFERRED | \
  974. TCPF_DELACK_TIMER_DEFERRED | \
  975. TCPF_MTU_REDUCED_DEFERRED | \
  976. TCPF_ACK_DEFERRED)
  977. /**
  978. * tcp_release_cb - tcp release_sock() callback
  979. * @sk: socket
  980. *
  981. * called from release_sock() to perform protocol dependent
  982. * actions before socket release.
  983. */
  984. void tcp_release_cb(struct sock *sk)
  985. {
  986. unsigned long flags = smp_load_acquire(&sk->sk_tsq_flags);
  987. unsigned long nflags;
  988. /* perform an atomic operation only if at least one flag is set */
  989. do {
  990. if (!(flags & TCP_DEFERRED_ALL))
  991. return;
  992. nflags = flags & ~TCP_DEFERRED_ALL;
  993. } while (!try_cmpxchg(&sk->sk_tsq_flags, &flags, nflags));
  994. if (flags & TCPF_TSQ_DEFERRED) {
  995. tcp_tsq_write(sk);
  996. __sock_put(sk);
  997. }
  998. if (flags & TCPF_WRITE_TIMER_DEFERRED) {
  999. tcp_write_timer_handler(sk);
  1000. __sock_put(sk);
  1001. }
  1002. if (flags & TCPF_DELACK_TIMER_DEFERRED) {
  1003. tcp_delack_timer_handler(sk);
  1004. __sock_put(sk);
  1005. }
  1006. if (flags & TCPF_MTU_REDUCED_DEFERRED) {
  1007. inet_csk(sk)->icsk_af_ops->mtu_reduced(sk);
  1008. __sock_put(sk);
  1009. }
  1010. if ((flags & TCPF_ACK_DEFERRED) && inet_csk_ack_scheduled(sk))
  1011. tcp_send_ack(sk);
  1012. }
  1013. EXPORT_SYMBOL(tcp_release_cb);
  1014. void __init tcp_tasklet_init(void)
  1015. {
  1016. int i;
  1017. for_each_possible_cpu(i) {
  1018. struct tsq_tasklet *tsq = &per_cpu(tsq_tasklet, i);
  1019. INIT_LIST_HEAD(&tsq->head);
  1020. tasklet_setup(&tsq->tasklet, tcp_tasklet_func);
  1021. }
  1022. }
  1023. /*
  1024. * Write buffer destructor automatically called from kfree_skb.
  1025. * We can't xmit new skbs from this context, as we might already
  1026. * hold qdisc lock.
  1027. */
  1028. void tcp_wfree(struct sk_buff *skb)
  1029. {
  1030. struct sock *sk = skb->sk;
  1031. struct tcp_sock *tp = tcp_sk(sk);
  1032. unsigned long flags, nval, oval;
  1033. struct tsq_tasklet *tsq;
  1034. bool empty;
  1035. /* Keep one reference on sk_wmem_alloc.
  1036. * Will be released by sk_free() from here or tcp_tasklet_func()
  1037. */
  1038. WARN_ON(refcount_sub_and_test(skb->truesize - 1, &sk->sk_wmem_alloc));
  1039. /* If this softirq is serviced by ksoftirqd, we are likely under stress.
  1040. * Wait until our queues (qdisc + devices) are drained.
  1041. * This gives :
  1042. * - less callbacks to tcp_write_xmit(), reducing stress (batches)
  1043. * - chance for incoming ACK (processed by another cpu maybe)
  1044. * to migrate this flow (skb->ooo_okay will be eventually set)
  1045. */
  1046. if (refcount_read(&sk->sk_wmem_alloc) >= SKB_TRUESIZE(1) && this_cpu_ksoftirqd() == current)
  1047. goto out;
  1048. oval = smp_load_acquire(&sk->sk_tsq_flags);
  1049. do {
  1050. if (!(oval & TSQF_THROTTLED) || (oval & TSQF_QUEUED))
  1051. goto out;
  1052. nval = (oval & ~TSQF_THROTTLED) | TSQF_QUEUED;
  1053. } while (!try_cmpxchg(&sk->sk_tsq_flags, &oval, nval));
  1054. /* queue this socket to tasklet queue */
  1055. local_irq_save(flags);
  1056. tsq = this_cpu_ptr(&tsq_tasklet);
  1057. empty = list_empty(&tsq->head);
  1058. list_add(&tp->tsq_node, &tsq->head);
  1059. if (empty)
  1060. tasklet_schedule(&tsq->tasklet);
  1061. local_irq_restore(flags);
  1062. return;
  1063. out:
  1064. sk_free(sk);
  1065. }
  1066. /* Note: Called under soft irq.
  1067. * We can call TCP stack right away, unless socket is owned by user.
  1068. */
  1069. enum hrtimer_restart tcp_pace_kick(struct hrtimer *timer)
  1070. {
  1071. struct tcp_sock *tp = container_of(timer, struct tcp_sock, pacing_timer);
  1072. struct sock *sk = (struct sock *)tp;
  1073. tcp_tsq_handler(sk);
  1074. sock_put(sk);
  1075. return HRTIMER_NORESTART;
  1076. }
  1077. static void tcp_update_skb_after_send(struct sock *sk, struct sk_buff *skb,
  1078. u64 prior_wstamp)
  1079. {
  1080. struct tcp_sock *tp = tcp_sk(sk);
  1081. if (sk->sk_pacing_status != SK_PACING_NONE) {
  1082. unsigned long rate = READ_ONCE(sk->sk_pacing_rate);
  1083. /* Original sch_fq does not pace first 10 MSS
  1084. * Note that tp->data_segs_out overflows after 2^32 packets,
  1085. * this is a minor annoyance.
  1086. */
  1087. if (rate != ~0UL && rate && tp->data_segs_out >= 10) {
  1088. u64 len_ns = div64_ul((u64)skb->len * NSEC_PER_SEC, rate);
  1089. u64 credit = tp->tcp_wstamp_ns - prior_wstamp;
  1090. /* take into account OS jitter */
  1091. len_ns -= min_t(u64, len_ns / 2, credit);
  1092. tp->tcp_wstamp_ns += len_ns;
  1093. }
  1094. }
  1095. list_move_tail(&skb->tcp_tsorted_anchor, &tp->tsorted_sent_queue);
  1096. }
  1097. INDIRECT_CALLABLE_DECLARE(int ip_queue_xmit(struct sock *sk, struct sk_buff *skb, struct flowi *fl));
  1098. INDIRECT_CALLABLE_DECLARE(int inet6_csk_xmit(struct sock *sk, struct sk_buff *skb, struct flowi *fl));
  1099. INDIRECT_CALLABLE_DECLARE(void tcp_v4_send_check(struct sock *sk, struct sk_buff *skb));
  1100. /* This routine actually transmits TCP packets queued in by
  1101. * tcp_do_sendmsg(). This is used by both the initial
  1102. * transmission and possible later retransmissions.
  1103. * All SKB's seen here are completely headerless. It is our
  1104. * job to build the TCP header, and pass the packet down to
  1105. * IP so it can do the same plus pass the packet off to the
  1106. * device.
  1107. *
  1108. * We are working here with either a clone of the original
  1109. * SKB, or a fresh unique copy made by the retransmit engine.
  1110. */
  1111. static int __tcp_transmit_skb(struct sock *sk, struct sk_buff *skb,
  1112. int clone_it, gfp_t gfp_mask, u32 rcv_nxt)
  1113. {
  1114. const struct inet_connection_sock *icsk = inet_csk(sk);
  1115. struct inet_sock *inet;
  1116. struct tcp_sock *tp;
  1117. struct tcp_skb_cb *tcb;
  1118. struct tcp_out_options opts;
  1119. unsigned int tcp_options_size, tcp_header_size;
  1120. struct sk_buff *oskb = NULL;
  1121. struct tcp_key key;
  1122. struct tcphdr *th;
  1123. u64 prior_wstamp;
  1124. int err;
  1125. BUG_ON(!skb || !tcp_skb_pcount(skb));
  1126. tp = tcp_sk(sk);
  1127. prior_wstamp = tp->tcp_wstamp_ns;
  1128. tp->tcp_wstamp_ns = max(tp->tcp_wstamp_ns, tp->tcp_clock_cache);
  1129. skb_set_delivery_time(skb, tp->tcp_wstamp_ns, SKB_CLOCK_MONOTONIC);
  1130. if (clone_it) {
  1131. oskb = skb;
  1132. tcp_skb_tsorted_save(oskb) {
  1133. if (unlikely(skb_cloned(oskb)))
  1134. skb = pskb_copy(oskb, gfp_mask);
  1135. else
  1136. skb = skb_clone(oskb, gfp_mask);
  1137. } tcp_skb_tsorted_restore(oskb);
  1138. if (unlikely(!skb))
  1139. return -ENOBUFS;
  1140. /* retransmit skbs might have a non zero value in skb->dev
  1141. * because skb->dev is aliased with skb->rbnode.rb_left
  1142. */
  1143. skb->dev = NULL;
  1144. }
  1145. inet = inet_sk(sk);
  1146. tcb = TCP_SKB_CB(skb);
  1147. memset(&opts, 0, sizeof(opts));
  1148. tcp_get_current_key(sk, &key);
  1149. if (unlikely(tcb->tcp_flags & TCPHDR_SYN)) {
  1150. tcp_options_size = tcp_syn_options(sk, skb, &opts, &key);
  1151. } else {
  1152. tcp_options_size = tcp_established_options(sk, skb, &opts, &key);
  1153. /* Force a PSH flag on all (GSO) packets to expedite GRO flush
  1154. * at receiver : This slightly improve GRO performance.
  1155. * Note that we do not force the PSH flag for non GSO packets,
  1156. * because they might be sent under high congestion events,
  1157. * and in this case it is better to delay the delivery of 1-MSS
  1158. * packets and thus the corresponding ACK packet that would
  1159. * release the following packet.
  1160. */
  1161. if (tcp_skb_pcount(skb) > 1)
  1162. tcb->tcp_flags |= TCPHDR_PSH;
  1163. }
  1164. tcp_header_size = tcp_options_size + sizeof(struct tcphdr);
  1165. /* We set skb->ooo_okay to one if this packet can select
  1166. * a different TX queue than prior packets of this flow,
  1167. * to avoid self inflicted reorders.
  1168. * The 'other' queue decision is based on current cpu number
  1169. * if XPS is enabled, or sk->sk_txhash otherwise.
  1170. * We can switch to another (and better) queue if:
  1171. * 1) No packet with payload is in qdisc/device queues.
  1172. * Delays in TX completion can defeat the test
  1173. * even if packets were already sent.
  1174. * 2) Or rtx queue is empty.
  1175. * This mitigates above case if ACK packets for
  1176. * all prior packets were already processed.
  1177. */
  1178. skb->ooo_okay = sk_wmem_alloc_get(sk) < SKB_TRUESIZE(1) ||
  1179. tcp_rtx_queue_empty(sk);
  1180. /* If we had to use memory reserve to allocate this skb,
  1181. * this might cause drops if packet is looped back :
  1182. * Other socket might not have SOCK_MEMALLOC.
  1183. * Packets not looped back do not care about pfmemalloc.
  1184. */
  1185. skb->pfmemalloc = 0;
  1186. skb_push(skb, tcp_header_size);
  1187. skb_reset_transport_header(skb);
  1188. skb_orphan(skb);
  1189. skb->sk = sk;
  1190. skb->destructor = skb_is_tcp_pure_ack(skb) ? __sock_wfree : tcp_wfree;
  1191. refcount_add(skb->truesize, &sk->sk_wmem_alloc);
  1192. skb_set_dst_pending_confirm(skb, READ_ONCE(sk->sk_dst_pending_confirm));
  1193. /* Build TCP header and checksum it. */
  1194. th = (struct tcphdr *)skb->data;
  1195. th->source = inet->inet_sport;
  1196. th->dest = inet->inet_dport;
  1197. th->seq = htonl(tcb->seq);
  1198. th->ack_seq = htonl(rcv_nxt);
  1199. *(((__be16 *)th) + 6) = htons(((tcp_header_size >> 2) << 12) |
  1200. tcb->tcp_flags);
  1201. th->check = 0;
  1202. th->urg_ptr = 0;
  1203. /* The urg_mode check is necessary during a below snd_una win probe */
  1204. if (unlikely(tcp_urg_mode(tp) && before(tcb->seq, tp->snd_up))) {
  1205. if (before(tp->snd_up, tcb->seq + 0x10000)) {
  1206. th->urg_ptr = htons(tp->snd_up - tcb->seq);
  1207. th->urg = 1;
  1208. } else if (after(tcb->seq + 0xFFFF, tp->snd_nxt)) {
  1209. th->urg_ptr = htons(0xFFFF);
  1210. th->urg = 1;
  1211. }
  1212. }
  1213. skb_shinfo(skb)->gso_type = sk->sk_gso_type;
  1214. if (likely(!(tcb->tcp_flags & TCPHDR_SYN))) {
  1215. th->window = htons(tcp_select_window(sk));
  1216. tcp_ecn_send(sk, skb, th, tcp_header_size);
  1217. } else {
  1218. /* RFC1323: The window in SYN & SYN/ACK segments
  1219. * is never scaled.
  1220. */
  1221. th->window = htons(min(tp->rcv_wnd, 65535U));
  1222. }
  1223. tcp_options_write(th, tp, NULL, &opts, &key);
  1224. if (tcp_key_is_md5(&key)) {
  1225. #ifdef CONFIG_TCP_MD5SIG
  1226. /* Calculate the MD5 hash, as we have all we need now */
  1227. sk_gso_disable(sk);
  1228. tp->af_specific->calc_md5_hash(opts.hash_location,
  1229. key.md5_key, sk, skb);
  1230. #endif
  1231. } else if (tcp_key_is_ao(&key)) {
  1232. int err;
  1233. err = tcp_ao_transmit_skb(sk, skb, key.ao_key, th,
  1234. opts.hash_location);
  1235. if (err) {
  1236. kfree_skb_reason(skb, SKB_DROP_REASON_NOT_SPECIFIED);
  1237. return -ENOMEM;
  1238. }
  1239. }
  1240. /* BPF prog is the last one writing header option */
  1241. bpf_skops_write_hdr_opt(sk, skb, NULL, NULL, 0, &opts);
  1242. INDIRECT_CALL_INET(icsk->icsk_af_ops->send_check,
  1243. tcp_v6_send_check, tcp_v4_send_check,
  1244. sk, skb);
  1245. if (likely(tcb->tcp_flags & TCPHDR_ACK))
  1246. tcp_event_ack_sent(sk, rcv_nxt);
  1247. if (skb->len != tcp_header_size) {
  1248. tcp_event_data_sent(tp, sk);
  1249. tp->data_segs_out += tcp_skb_pcount(skb);
  1250. tp->bytes_sent += skb->len - tcp_header_size;
  1251. }
  1252. if (after(tcb->end_seq, tp->snd_nxt) || tcb->seq == tcb->end_seq)
  1253. TCP_ADD_STATS(sock_net(sk), TCP_MIB_OUTSEGS,
  1254. tcp_skb_pcount(skb));
  1255. tp->segs_out += tcp_skb_pcount(skb);
  1256. skb_set_hash_from_sk(skb, sk);
  1257. /* OK, its time to fill skb_shinfo(skb)->gso_{segs|size} */
  1258. skb_shinfo(skb)->gso_segs = tcp_skb_pcount(skb);
  1259. skb_shinfo(skb)->gso_size = tcp_skb_mss(skb);
  1260. /* Leave earliest departure time in skb->tstamp (skb->skb_mstamp_ns) */
  1261. /* Cleanup our debris for IP stacks */
  1262. memset(skb->cb, 0, max(sizeof(struct inet_skb_parm),
  1263. sizeof(struct inet6_skb_parm)));
  1264. tcp_add_tx_delay(skb, tp);
  1265. err = INDIRECT_CALL_INET(icsk->icsk_af_ops->queue_xmit,
  1266. inet6_csk_xmit, ip_queue_xmit,
  1267. sk, skb, &inet->cork.fl);
  1268. if (unlikely(err > 0)) {
  1269. tcp_enter_cwr(sk);
  1270. err = net_xmit_eval(err);
  1271. }
  1272. if (!err && oskb) {
  1273. tcp_update_skb_after_send(sk, oskb, prior_wstamp);
  1274. tcp_rate_skb_sent(sk, oskb);
  1275. }
  1276. return err;
  1277. }
  1278. static int tcp_transmit_skb(struct sock *sk, struct sk_buff *skb, int clone_it,
  1279. gfp_t gfp_mask)
  1280. {
  1281. return __tcp_transmit_skb(sk, skb, clone_it, gfp_mask,
  1282. tcp_sk(sk)->rcv_nxt);
  1283. }
  1284. /* This routine just queues the buffer for sending.
  1285. *
  1286. * NOTE: probe0 timer is not checked, do not forget tcp_push_pending_frames,
  1287. * otherwise socket can stall.
  1288. */
  1289. static void tcp_queue_skb(struct sock *sk, struct sk_buff *skb)
  1290. {
  1291. struct tcp_sock *tp = tcp_sk(sk);
  1292. /* Advance write_seq and place onto the write_queue. */
  1293. WRITE_ONCE(tp->write_seq, TCP_SKB_CB(skb)->end_seq);
  1294. __skb_header_release(skb);
  1295. tcp_add_write_queue_tail(sk, skb);
  1296. sk_wmem_queued_add(sk, skb->truesize);
  1297. sk_mem_charge(sk, skb->truesize);
  1298. }
  1299. /* Initialize TSO segments for a packet. */
  1300. static int tcp_set_skb_tso_segs(struct sk_buff *skb, unsigned int mss_now)
  1301. {
  1302. int tso_segs;
  1303. if (skb->len <= mss_now) {
  1304. /* Avoid the costly divide in the normal
  1305. * non-TSO case.
  1306. */
  1307. TCP_SKB_CB(skb)->tcp_gso_size = 0;
  1308. tcp_skb_pcount_set(skb, 1);
  1309. return 1;
  1310. }
  1311. TCP_SKB_CB(skb)->tcp_gso_size = mss_now;
  1312. tso_segs = DIV_ROUND_UP(skb->len, mss_now);
  1313. tcp_skb_pcount_set(skb, tso_segs);
  1314. return tso_segs;
  1315. }
  1316. /* Pcount in the middle of the write queue got changed, we need to do various
  1317. * tweaks to fix counters
  1318. */
  1319. static void tcp_adjust_pcount(struct sock *sk, const struct sk_buff *skb, int decr)
  1320. {
  1321. struct tcp_sock *tp = tcp_sk(sk);
  1322. tp->packets_out -= decr;
  1323. if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED)
  1324. tp->sacked_out -= decr;
  1325. if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_RETRANS)
  1326. tp->retrans_out -= decr;
  1327. if (TCP_SKB_CB(skb)->sacked & TCPCB_LOST)
  1328. tp->lost_out -= decr;
  1329. /* Reno case is special. Sigh... */
  1330. if (tcp_is_reno(tp) && decr > 0)
  1331. tp->sacked_out -= min_t(u32, tp->sacked_out, decr);
  1332. if (tp->lost_skb_hint &&
  1333. before(TCP_SKB_CB(skb)->seq, TCP_SKB_CB(tp->lost_skb_hint)->seq) &&
  1334. (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED))
  1335. tp->lost_cnt_hint -= decr;
  1336. tcp_verify_left_out(tp);
  1337. }
  1338. static bool tcp_has_tx_tstamp(const struct sk_buff *skb)
  1339. {
  1340. return TCP_SKB_CB(skb)->txstamp_ack ||
  1341. (skb_shinfo(skb)->tx_flags & SKBTX_ANY_TSTAMP);
  1342. }
  1343. static void tcp_fragment_tstamp(struct sk_buff *skb, struct sk_buff *skb2)
  1344. {
  1345. struct skb_shared_info *shinfo = skb_shinfo(skb);
  1346. if (unlikely(tcp_has_tx_tstamp(skb)) &&
  1347. !before(shinfo->tskey, TCP_SKB_CB(skb2)->seq)) {
  1348. struct skb_shared_info *shinfo2 = skb_shinfo(skb2);
  1349. u8 tsflags = shinfo->tx_flags & SKBTX_ANY_TSTAMP;
  1350. shinfo->tx_flags &= ~tsflags;
  1351. shinfo2->tx_flags |= tsflags;
  1352. swap(shinfo->tskey, shinfo2->tskey);
  1353. TCP_SKB_CB(skb2)->txstamp_ack = TCP_SKB_CB(skb)->txstamp_ack;
  1354. TCP_SKB_CB(skb)->txstamp_ack = 0;
  1355. }
  1356. }
  1357. static void tcp_skb_fragment_eor(struct sk_buff *skb, struct sk_buff *skb2)
  1358. {
  1359. TCP_SKB_CB(skb2)->eor = TCP_SKB_CB(skb)->eor;
  1360. TCP_SKB_CB(skb)->eor = 0;
  1361. }
  1362. /* Insert buff after skb on the write or rtx queue of sk. */
  1363. static void tcp_insert_write_queue_after(struct sk_buff *skb,
  1364. struct sk_buff *buff,
  1365. struct sock *sk,
  1366. enum tcp_queue tcp_queue)
  1367. {
  1368. if (tcp_queue == TCP_FRAG_IN_WRITE_QUEUE)
  1369. __skb_queue_after(&sk->sk_write_queue, skb, buff);
  1370. else
  1371. tcp_rbtree_insert(&sk->tcp_rtx_queue, buff);
  1372. }
  1373. /* Function to create two new TCP segments. Shrinks the given segment
  1374. * to the specified size and appends a new segment with the rest of the
  1375. * packet to the list. This won't be called frequently, I hope.
  1376. * Remember, these are still headerless SKBs at this point.
  1377. */
  1378. int tcp_fragment(struct sock *sk, enum tcp_queue tcp_queue,
  1379. struct sk_buff *skb, u32 len,
  1380. unsigned int mss_now, gfp_t gfp)
  1381. {
  1382. struct tcp_sock *tp = tcp_sk(sk);
  1383. struct sk_buff *buff;
  1384. int old_factor;
  1385. long limit;
  1386. int nlen;
  1387. u8 flags;
  1388. if (WARN_ON(len > skb->len))
  1389. return -EINVAL;
  1390. DEBUG_NET_WARN_ON_ONCE(skb_headlen(skb));
  1391. /* tcp_sendmsg() can overshoot sk_wmem_queued by one full size skb.
  1392. * We need some allowance to not penalize applications setting small
  1393. * SO_SNDBUF values.
  1394. * Also allow first and last skb in retransmit queue to be split.
  1395. */
  1396. limit = sk->sk_sndbuf + 2 * SKB_TRUESIZE(GSO_LEGACY_MAX_SIZE);
  1397. if (unlikely((sk->sk_wmem_queued >> 1) > limit &&
  1398. tcp_queue != TCP_FRAG_IN_WRITE_QUEUE &&
  1399. skb != tcp_rtx_queue_head(sk) &&
  1400. skb != tcp_rtx_queue_tail(sk))) {
  1401. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPWQUEUETOOBIG);
  1402. return -ENOMEM;
  1403. }
  1404. if (skb_unclone_keeptruesize(skb, gfp))
  1405. return -ENOMEM;
  1406. /* Get a new skb... force flag on. */
  1407. buff = tcp_stream_alloc_skb(sk, gfp, true);
  1408. if (!buff)
  1409. return -ENOMEM; /* We'll just try again later. */
  1410. skb_copy_decrypted(buff, skb);
  1411. mptcp_skb_ext_copy(buff, skb);
  1412. sk_wmem_queued_add(sk, buff->truesize);
  1413. sk_mem_charge(sk, buff->truesize);
  1414. nlen = skb->len - len;
  1415. buff->truesize += nlen;
  1416. skb->truesize -= nlen;
  1417. /* Correct the sequence numbers. */
  1418. TCP_SKB_CB(buff)->seq = TCP_SKB_CB(skb)->seq + len;
  1419. TCP_SKB_CB(buff)->end_seq = TCP_SKB_CB(skb)->end_seq;
  1420. TCP_SKB_CB(skb)->end_seq = TCP_SKB_CB(buff)->seq;
  1421. /* PSH and FIN should only be set in the second packet. */
  1422. flags = TCP_SKB_CB(skb)->tcp_flags;
  1423. TCP_SKB_CB(skb)->tcp_flags = flags & ~(TCPHDR_FIN | TCPHDR_PSH);
  1424. TCP_SKB_CB(buff)->tcp_flags = flags;
  1425. TCP_SKB_CB(buff)->sacked = TCP_SKB_CB(skb)->sacked;
  1426. tcp_skb_fragment_eor(skb, buff);
  1427. skb_split(skb, buff, len);
  1428. skb_set_delivery_time(buff, skb->tstamp, SKB_CLOCK_MONOTONIC);
  1429. tcp_fragment_tstamp(skb, buff);
  1430. old_factor = tcp_skb_pcount(skb);
  1431. /* Fix up tso_factor for both original and new SKB. */
  1432. tcp_set_skb_tso_segs(skb, mss_now);
  1433. tcp_set_skb_tso_segs(buff, mss_now);
  1434. /* Update delivered info for the new segment */
  1435. TCP_SKB_CB(buff)->tx = TCP_SKB_CB(skb)->tx;
  1436. /* If this packet has been sent out already, we must
  1437. * adjust the various packet counters.
  1438. */
  1439. if (!before(tp->snd_nxt, TCP_SKB_CB(buff)->end_seq)) {
  1440. int diff = old_factor - tcp_skb_pcount(skb) -
  1441. tcp_skb_pcount(buff);
  1442. if (diff)
  1443. tcp_adjust_pcount(sk, skb, diff);
  1444. }
  1445. /* Link BUFF into the send queue. */
  1446. __skb_header_release(buff);
  1447. tcp_insert_write_queue_after(skb, buff, sk, tcp_queue);
  1448. if (tcp_queue == TCP_FRAG_IN_RTX_QUEUE)
  1449. list_add(&buff->tcp_tsorted_anchor, &skb->tcp_tsorted_anchor);
  1450. return 0;
  1451. }
  1452. /* This is similar to __pskb_pull_tail(). The difference is that pulled
  1453. * data is not copied, but immediately discarded.
  1454. */
  1455. static int __pskb_trim_head(struct sk_buff *skb, int len)
  1456. {
  1457. struct skb_shared_info *shinfo;
  1458. int i, k, eat;
  1459. DEBUG_NET_WARN_ON_ONCE(skb_headlen(skb));
  1460. eat = len;
  1461. k = 0;
  1462. shinfo = skb_shinfo(skb);
  1463. for (i = 0; i < shinfo->nr_frags; i++) {
  1464. int size = skb_frag_size(&shinfo->frags[i]);
  1465. if (size <= eat) {
  1466. skb_frag_unref(skb, i);
  1467. eat -= size;
  1468. } else {
  1469. shinfo->frags[k] = shinfo->frags[i];
  1470. if (eat) {
  1471. skb_frag_off_add(&shinfo->frags[k], eat);
  1472. skb_frag_size_sub(&shinfo->frags[k], eat);
  1473. eat = 0;
  1474. }
  1475. k++;
  1476. }
  1477. }
  1478. shinfo->nr_frags = k;
  1479. skb->data_len -= len;
  1480. skb->len = skb->data_len;
  1481. return len;
  1482. }
  1483. /* Remove acked data from a packet in the transmit queue. */
  1484. int tcp_trim_head(struct sock *sk, struct sk_buff *skb, u32 len)
  1485. {
  1486. u32 delta_truesize;
  1487. if (skb_unclone_keeptruesize(skb, GFP_ATOMIC))
  1488. return -ENOMEM;
  1489. delta_truesize = __pskb_trim_head(skb, len);
  1490. TCP_SKB_CB(skb)->seq += len;
  1491. skb->truesize -= delta_truesize;
  1492. sk_wmem_queued_add(sk, -delta_truesize);
  1493. if (!skb_zcopy_pure(skb))
  1494. sk_mem_uncharge(sk, delta_truesize);
  1495. /* Any change of skb->len requires recalculation of tso factor. */
  1496. if (tcp_skb_pcount(skb) > 1)
  1497. tcp_set_skb_tso_segs(skb, tcp_skb_mss(skb));
  1498. return 0;
  1499. }
  1500. /* Calculate MSS not accounting any TCP options. */
  1501. static inline int __tcp_mtu_to_mss(struct sock *sk, int pmtu)
  1502. {
  1503. const struct tcp_sock *tp = tcp_sk(sk);
  1504. const struct inet_connection_sock *icsk = inet_csk(sk);
  1505. int mss_now;
  1506. /* Calculate base mss without TCP options:
  1507. It is MMS_S - sizeof(tcphdr) of rfc1122
  1508. */
  1509. mss_now = pmtu - icsk->icsk_af_ops->net_header_len - sizeof(struct tcphdr);
  1510. /* Clamp it (mss_clamp does not include tcp options) */
  1511. if (mss_now > tp->rx_opt.mss_clamp)
  1512. mss_now = tp->rx_opt.mss_clamp;
  1513. /* Now subtract optional transport overhead */
  1514. mss_now -= icsk->icsk_ext_hdr_len;
  1515. /* Then reserve room for full set of TCP options and 8 bytes of data */
  1516. mss_now = max(mss_now,
  1517. READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_min_snd_mss));
  1518. return mss_now;
  1519. }
  1520. /* Calculate MSS. Not accounting for SACKs here. */
  1521. int tcp_mtu_to_mss(struct sock *sk, int pmtu)
  1522. {
  1523. /* Subtract TCP options size, not including SACKs */
  1524. return __tcp_mtu_to_mss(sk, pmtu) -
  1525. (tcp_sk(sk)->tcp_header_len - sizeof(struct tcphdr));
  1526. }
  1527. EXPORT_SYMBOL(tcp_mtu_to_mss);
  1528. /* Inverse of above */
  1529. int tcp_mss_to_mtu(struct sock *sk, int mss)
  1530. {
  1531. const struct tcp_sock *tp = tcp_sk(sk);
  1532. const struct inet_connection_sock *icsk = inet_csk(sk);
  1533. return mss +
  1534. tp->tcp_header_len +
  1535. icsk->icsk_ext_hdr_len +
  1536. icsk->icsk_af_ops->net_header_len;
  1537. }
  1538. EXPORT_SYMBOL(tcp_mss_to_mtu);
  1539. /* MTU probing init per socket */
  1540. void tcp_mtup_init(struct sock *sk)
  1541. {
  1542. struct tcp_sock *tp = tcp_sk(sk);
  1543. struct inet_connection_sock *icsk = inet_csk(sk);
  1544. struct net *net = sock_net(sk);
  1545. icsk->icsk_mtup.enabled = READ_ONCE(net->ipv4.sysctl_tcp_mtu_probing) > 1;
  1546. icsk->icsk_mtup.search_high = tp->rx_opt.mss_clamp + sizeof(struct tcphdr) +
  1547. icsk->icsk_af_ops->net_header_len;
  1548. icsk->icsk_mtup.search_low = tcp_mss_to_mtu(sk, READ_ONCE(net->ipv4.sysctl_tcp_base_mss));
  1549. icsk->icsk_mtup.probe_size = 0;
  1550. if (icsk->icsk_mtup.enabled)
  1551. icsk->icsk_mtup.probe_timestamp = tcp_jiffies32;
  1552. }
  1553. EXPORT_SYMBOL(tcp_mtup_init);
  1554. /* This function synchronize snd mss to current pmtu/exthdr set.
  1555. tp->rx_opt.user_mss is mss set by user by TCP_MAXSEG. It does NOT counts
  1556. for TCP options, but includes only bare TCP header.
  1557. tp->rx_opt.mss_clamp is mss negotiated at connection setup.
  1558. It is minimum of user_mss and mss received with SYN.
  1559. It also does not include TCP options.
  1560. inet_csk(sk)->icsk_pmtu_cookie is last pmtu, seen by this function.
  1561. tp->mss_cache is current effective sending mss, including
  1562. all tcp options except for SACKs. It is evaluated,
  1563. taking into account current pmtu, but never exceeds
  1564. tp->rx_opt.mss_clamp.
  1565. NOTE1. rfc1122 clearly states that advertised MSS
  1566. DOES NOT include either tcp or ip options.
  1567. NOTE2. inet_csk(sk)->icsk_pmtu_cookie and tp->mss_cache
  1568. are READ ONLY outside this function. --ANK (980731)
  1569. */
  1570. unsigned int tcp_sync_mss(struct sock *sk, u32 pmtu)
  1571. {
  1572. struct tcp_sock *tp = tcp_sk(sk);
  1573. struct inet_connection_sock *icsk = inet_csk(sk);
  1574. int mss_now;
  1575. if (icsk->icsk_mtup.search_high > pmtu)
  1576. icsk->icsk_mtup.search_high = pmtu;
  1577. mss_now = tcp_mtu_to_mss(sk, pmtu);
  1578. mss_now = tcp_bound_to_half_wnd(tp, mss_now);
  1579. /* And store cached results */
  1580. icsk->icsk_pmtu_cookie = pmtu;
  1581. if (icsk->icsk_mtup.enabled)
  1582. mss_now = min(mss_now, tcp_mtu_to_mss(sk, icsk->icsk_mtup.search_low));
  1583. tp->mss_cache = mss_now;
  1584. return mss_now;
  1585. }
  1586. EXPORT_SYMBOL(tcp_sync_mss);
  1587. /* Compute the current effective MSS, taking SACKs and IP options,
  1588. * and even PMTU discovery events into account.
  1589. */
  1590. unsigned int tcp_current_mss(struct sock *sk)
  1591. {
  1592. const struct tcp_sock *tp = tcp_sk(sk);
  1593. const struct dst_entry *dst = __sk_dst_get(sk);
  1594. u32 mss_now;
  1595. unsigned int header_len;
  1596. struct tcp_out_options opts;
  1597. struct tcp_key key;
  1598. mss_now = tp->mss_cache;
  1599. if (dst) {
  1600. u32 mtu = dst_mtu(dst);
  1601. if (mtu != inet_csk(sk)->icsk_pmtu_cookie)
  1602. mss_now = tcp_sync_mss(sk, mtu);
  1603. }
  1604. tcp_get_current_key(sk, &key);
  1605. header_len = tcp_established_options(sk, NULL, &opts, &key) +
  1606. sizeof(struct tcphdr);
  1607. /* The mss_cache is sized based on tp->tcp_header_len, which assumes
  1608. * some common options. If this is an odd packet (because we have SACK
  1609. * blocks etc) then our calculated header_len will be different, and
  1610. * we have to adjust mss_now correspondingly */
  1611. if (header_len != tp->tcp_header_len) {
  1612. int delta = (int) header_len - tp->tcp_header_len;
  1613. mss_now -= delta;
  1614. }
  1615. return mss_now;
  1616. }
  1617. /* RFC2861, slow part. Adjust cwnd, after it was not full during one rto.
  1618. * As additional protections, we do not touch cwnd in retransmission phases,
  1619. * and if application hit its sndbuf limit recently.
  1620. */
  1621. static void tcp_cwnd_application_limited(struct sock *sk)
  1622. {
  1623. struct tcp_sock *tp = tcp_sk(sk);
  1624. if (inet_csk(sk)->icsk_ca_state == TCP_CA_Open &&
  1625. sk->sk_socket && !test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) {
  1626. /* Limited by application or receiver window. */
  1627. u32 init_win = tcp_init_cwnd(tp, __sk_dst_get(sk));
  1628. u32 win_used = max(tp->snd_cwnd_used, init_win);
  1629. if (win_used < tcp_snd_cwnd(tp)) {
  1630. tp->snd_ssthresh = tcp_current_ssthresh(sk);
  1631. tcp_snd_cwnd_set(tp, (tcp_snd_cwnd(tp) + win_used) >> 1);
  1632. }
  1633. tp->snd_cwnd_used = 0;
  1634. }
  1635. tp->snd_cwnd_stamp = tcp_jiffies32;
  1636. }
  1637. static void tcp_cwnd_validate(struct sock *sk, bool is_cwnd_limited)
  1638. {
  1639. const struct tcp_congestion_ops *ca_ops = inet_csk(sk)->icsk_ca_ops;
  1640. struct tcp_sock *tp = tcp_sk(sk);
  1641. /* Track the strongest available signal of the degree to which the cwnd
  1642. * is fully utilized. If cwnd-limited then remember that fact for the
  1643. * current window. If not cwnd-limited then track the maximum number of
  1644. * outstanding packets in the current window. (If cwnd-limited then we
  1645. * chose to not update tp->max_packets_out to avoid an extra else
  1646. * clause with no functional impact.)
  1647. */
  1648. if (!before(tp->snd_una, tp->cwnd_usage_seq) ||
  1649. is_cwnd_limited ||
  1650. (!tp->is_cwnd_limited &&
  1651. tp->packets_out > tp->max_packets_out)) {
  1652. tp->is_cwnd_limited = is_cwnd_limited;
  1653. tp->max_packets_out = tp->packets_out;
  1654. tp->cwnd_usage_seq = tp->snd_nxt;
  1655. }
  1656. if (tcp_is_cwnd_limited(sk)) {
  1657. /* Network is feed fully. */
  1658. tp->snd_cwnd_used = 0;
  1659. tp->snd_cwnd_stamp = tcp_jiffies32;
  1660. } else {
  1661. /* Network starves. */
  1662. if (tp->packets_out > tp->snd_cwnd_used)
  1663. tp->snd_cwnd_used = tp->packets_out;
  1664. if (READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_slow_start_after_idle) &&
  1665. (s32)(tcp_jiffies32 - tp->snd_cwnd_stamp) >= inet_csk(sk)->icsk_rto &&
  1666. !ca_ops->cong_control)
  1667. tcp_cwnd_application_limited(sk);
  1668. /* The following conditions together indicate the starvation
  1669. * is caused by insufficient sender buffer:
  1670. * 1) just sent some data (see tcp_write_xmit)
  1671. * 2) not cwnd limited (this else condition)
  1672. * 3) no more data to send (tcp_write_queue_empty())
  1673. * 4) application is hitting buffer limit (SOCK_NOSPACE)
  1674. */
  1675. if (tcp_write_queue_empty(sk) && sk->sk_socket &&
  1676. test_bit(SOCK_NOSPACE, &sk->sk_socket->flags) &&
  1677. (1 << sk->sk_state) & (TCPF_ESTABLISHED | TCPF_CLOSE_WAIT))
  1678. tcp_chrono_start(sk, TCP_CHRONO_SNDBUF_LIMITED);
  1679. }
  1680. }
  1681. /* Minshall's variant of the Nagle send check. */
  1682. static bool tcp_minshall_check(const struct tcp_sock *tp)
  1683. {
  1684. return after(tp->snd_sml, tp->snd_una) &&
  1685. !after(tp->snd_sml, tp->snd_nxt);
  1686. }
  1687. /* Update snd_sml if this skb is under mss
  1688. * Note that a TSO packet might end with a sub-mss segment
  1689. * The test is really :
  1690. * if ((skb->len % mss) != 0)
  1691. * tp->snd_sml = TCP_SKB_CB(skb)->end_seq;
  1692. * But we can avoid doing the divide again given we already have
  1693. * skb_pcount = skb->len / mss_now
  1694. */
  1695. static void tcp_minshall_update(struct tcp_sock *tp, unsigned int mss_now,
  1696. const struct sk_buff *skb)
  1697. {
  1698. if (skb->len < tcp_skb_pcount(skb) * mss_now)
  1699. tp->snd_sml = TCP_SKB_CB(skb)->end_seq;
  1700. }
  1701. /* Return false, if packet can be sent now without violation Nagle's rules:
  1702. * 1. It is full sized. (provided by caller in %partial bool)
  1703. * 2. Or it contains FIN. (already checked by caller)
  1704. * 3. Or TCP_CORK is not set, and TCP_NODELAY is set.
  1705. * 4. Or TCP_CORK is not set, and all sent packets are ACKed.
  1706. * With Minshall's modification: all sent small packets are ACKed.
  1707. */
  1708. static bool tcp_nagle_check(bool partial, const struct tcp_sock *tp,
  1709. int nonagle)
  1710. {
  1711. return partial &&
  1712. ((nonagle & TCP_NAGLE_CORK) ||
  1713. (!nonagle && tp->packets_out && tcp_minshall_check(tp)));
  1714. }
  1715. /* Return how many segs we'd like on a TSO packet,
  1716. * depending on current pacing rate, and how close the peer is.
  1717. *
  1718. * Rationale is:
  1719. * - For close peers, we rather send bigger packets to reduce
  1720. * cpu costs, because occasional losses will be repaired fast.
  1721. * - For long distance/rtt flows, we would like to get ACK clocking
  1722. * with 1 ACK per ms.
  1723. *
  1724. * Use min_rtt to help adapt TSO burst size, with smaller min_rtt resulting
  1725. * in bigger TSO bursts. We we cut the RTT-based allowance in half
  1726. * for every 2^9 usec (aka 512 us) of RTT, so that the RTT-based allowance
  1727. * is below 1500 bytes after 6 * ~500 usec = 3ms.
  1728. */
  1729. static u32 tcp_tso_autosize(const struct sock *sk, unsigned int mss_now,
  1730. int min_tso_segs)
  1731. {
  1732. unsigned long bytes;
  1733. u32 r;
  1734. bytes = READ_ONCE(sk->sk_pacing_rate) >> READ_ONCE(sk->sk_pacing_shift);
  1735. r = tcp_min_rtt(tcp_sk(sk)) >> READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_tso_rtt_log);
  1736. if (r < BITS_PER_TYPE(sk->sk_gso_max_size))
  1737. bytes += sk->sk_gso_max_size >> r;
  1738. bytes = min_t(unsigned long, bytes, sk->sk_gso_max_size);
  1739. return max_t(u32, bytes / mss_now, min_tso_segs);
  1740. }
  1741. /* Return the number of segments we want in the skb we are transmitting.
  1742. * See if congestion control module wants to decide; otherwise, autosize.
  1743. */
  1744. static u32 tcp_tso_segs(struct sock *sk, unsigned int mss_now)
  1745. {
  1746. const struct tcp_congestion_ops *ca_ops = inet_csk(sk)->icsk_ca_ops;
  1747. u32 min_tso, tso_segs;
  1748. min_tso = ca_ops->min_tso_segs ?
  1749. ca_ops->min_tso_segs(sk) :
  1750. READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_min_tso_segs);
  1751. tso_segs = tcp_tso_autosize(sk, mss_now, min_tso);
  1752. return min_t(u32, tso_segs, sk->sk_gso_max_segs);
  1753. }
  1754. /* Returns the portion of skb which can be sent right away */
  1755. static unsigned int tcp_mss_split_point(const struct sock *sk,
  1756. const struct sk_buff *skb,
  1757. unsigned int mss_now,
  1758. unsigned int max_segs,
  1759. int nonagle)
  1760. {
  1761. const struct tcp_sock *tp = tcp_sk(sk);
  1762. u32 partial, needed, window, max_len;
  1763. window = tcp_wnd_end(tp) - TCP_SKB_CB(skb)->seq;
  1764. max_len = mss_now * max_segs;
  1765. if (likely(max_len <= window && skb != tcp_write_queue_tail(sk)))
  1766. return max_len;
  1767. needed = min(skb->len, window);
  1768. if (max_len <= needed)
  1769. return max_len;
  1770. partial = needed % mss_now;
  1771. /* If last segment is not a full MSS, check if Nagle rules allow us
  1772. * to include this last segment in this skb.
  1773. * Otherwise, we'll split the skb at last MSS boundary
  1774. */
  1775. if (tcp_nagle_check(partial != 0, tp, nonagle))
  1776. return needed - partial;
  1777. return needed;
  1778. }
  1779. /* Can at least one segment of SKB be sent right now, according to the
  1780. * congestion window rules? If so, return how many segments are allowed.
  1781. */
  1782. static u32 tcp_cwnd_test(const struct tcp_sock *tp)
  1783. {
  1784. u32 in_flight, cwnd, halfcwnd;
  1785. in_flight = tcp_packets_in_flight(tp);
  1786. cwnd = tcp_snd_cwnd(tp);
  1787. if (in_flight >= cwnd)
  1788. return 0;
  1789. /* For better scheduling, ensure we have at least
  1790. * 2 GSO packets in flight.
  1791. */
  1792. halfcwnd = max(cwnd >> 1, 1U);
  1793. return min(halfcwnd, cwnd - in_flight);
  1794. }
  1795. /* Initialize TSO state of a skb.
  1796. * This must be invoked the first time we consider transmitting
  1797. * SKB onto the wire.
  1798. */
  1799. static int tcp_init_tso_segs(struct sk_buff *skb, unsigned int mss_now)
  1800. {
  1801. int tso_segs = tcp_skb_pcount(skb);
  1802. if (!tso_segs || (tso_segs > 1 && tcp_skb_mss(skb) != mss_now))
  1803. return tcp_set_skb_tso_segs(skb, mss_now);
  1804. return tso_segs;
  1805. }
  1806. /* Return true if the Nagle test allows this packet to be
  1807. * sent now.
  1808. */
  1809. static inline bool tcp_nagle_test(const struct tcp_sock *tp, const struct sk_buff *skb,
  1810. unsigned int cur_mss, int nonagle)
  1811. {
  1812. /* Nagle rule does not apply to frames, which sit in the middle of the
  1813. * write_queue (they have no chances to get new data).
  1814. *
  1815. * This is implemented in the callers, where they modify the 'nonagle'
  1816. * argument based upon the location of SKB in the send queue.
  1817. */
  1818. if (nonagle & TCP_NAGLE_PUSH)
  1819. return true;
  1820. /* Don't use the nagle rule for urgent data (or for the final FIN). */
  1821. if (tcp_urg_mode(tp) || (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN))
  1822. return true;
  1823. if (!tcp_nagle_check(skb->len < cur_mss, tp, nonagle))
  1824. return true;
  1825. return false;
  1826. }
  1827. /* Does at least the first segment of SKB fit into the send window? */
  1828. static bool tcp_snd_wnd_test(const struct tcp_sock *tp,
  1829. const struct sk_buff *skb,
  1830. unsigned int cur_mss)
  1831. {
  1832. u32 end_seq = TCP_SKB_CB(skb)->end_seq;
  1833. if (skb->len > cur_mss)
  1834. end_seq = TCP_SKB_CB(skb)->seq + cur_mss;
  1835. return !after(end_seq, tcp_wnd_end(tp));
  1836. }
  1837. /* Trim TSO SKB to LEN bytes, put the remaining data into a new packet
  1838. * which is put after SKB on the list. It is very much like
  1839. * tcp_fragment() except that it may make several kinds of assumptions
  1840. * in order to speed up the splitting operation. In particular, we
  1841. * know that all the data is in scatter-gather pages, and that the
  1842. * packet has never been sent out before (and thus is not cloned).
  1843. */
  1844. static int tso_fragment(struct sock *sk, struct sk_buff *skb, unsigned int len,
  1845. unsigned int mss_now, gfp_t gfp)
  1846. {
  1847. int nlen = skb->len - len;
  1848. struct sk_buff *buff;
  1849. u8 flags;
  1850. /* All of a TSO frame must be composed of paged data. */
  1851. DEBUG_NET_WARN_ON_ONCE(skb->len != skb->data_len);
  1852. buff = tcp_stream_alloc_skb(sk, gfp, true);
  1853. if (unlikely(!buff))
  1854. return -ENOMEM;
  1855. skb_copy_decrypted(buff, skb);
  1856. mptcp_skb_ext_copy(buff, skb);
  1857. sk_wmem_queued_add(sk, buff->truesize);
  1858. sk_mem_charge(sk, buff->truesize);
  1859. buff->truesize += nlen;
  1860. skb->truesize -= nlen;
  1861. /* Correct the sequence numbers. */
  1862. TCP_SKB_CB(buff)->seq = TCP_SKB_CB(skb)->seq + len;
  1863. TCP_SKB_CB(buff)->end_seq = TCP_SKB_CB(skb)->end_seq;
  1864. TCP_SKB_CB(skb)->end_seq = TCP_SKB_CB(buff)->seq;
  1865. /* PSH and FIN should only be set in the second packet. */
  1866. flags = TCP_SKB_CB(skb)->tcp_flags;
  1867. TCP_SKB_CB(skb)->tcp_flags = flags & ~(TCPHDR_FIN | TCPHDR_PSH);
  1868. TCP_SKB_CB(buff)->tcp_flags = flags;
  1869. tcp_skb_fragment_eor(skb, buff);
  1870. skb_split(skb, buff, len);
  1871. tcp_fragment_tstamp(skb, buff);
  1872. /* Fix up tso_factor for both original and new SKB. */
  1873. tcp_set_skb_tso_segs(skb, mss_now);
  1874. tcp_set_skb_tso_segs(buff, mss_now);
  1875. /* Link BUFF into the send queue. */
  1876. __skb_header_release(buff);
  1877. tcp_insert_write_queue_after(skb, buff, sk, TCP_FRAG_IN_WRITE_QUEUE);
  1878. return 0;
  1879. }
  1880. /* Try to defer sending, if possible, in order to minimize the amount
  1881. * of TSO splitting we do. View it as a kind of TSO Nagle test.
  1882. *
  1883. * This algorithm is from John Heffner.
  1884. */
  1885. static bool tcp_tso_should_defer(struct sock *sk, struct sk_buff *skb,
  1886. bool *is_cwnd_limited,
  1887. bool *is_rwnd_limited,
  1888. u32 max_segs)
  1889. {
  1890. const struct inet_connection_sock *icsk = inet_csk(sk);
  1891. u32 send_win, cong_win, limit, in_flight, threshold;
  1892. u64 srtt_in_ns, expected_ack, how_far_is_the_ack;
  1893. struct tcp_sock *tp = tcp_sk(sk);
  1894. struct sk_buff *head;
  1895. int win_divisor;
  1896. s64 delta;
  1897. if (icsk->icsk_ca_state >= TCP_CA_Recovery)
  1898. goto send_now;
  1899. /* Avoid bursty behavior by allowing defer
  1900. * only if the last write was recent (1 ms).
  1901. * Note that tp->tcp_wstamp_ns can be in the future if we have
  1902. * packets waiting in a qdisc or device for EDT delivery.
  1903. */
  1904. delta = tp->tcp_clock_cache - tp->tcp_wstamp_ns - NSEC_PER_MSEC;
  1905. if (delta > 0)
  1906. goto send_now;
  1907. in_flight = tcp_packets_in_flight(tp);
  1908. BUG_ON(tcp_skb_pcount(skb) <= 1);
  1909. BUG_ON(tcp_snd_cwnd(tp) <= in_flight);
  1910. send_win = tcp_wnd_end(tp) - TCP_SKB_CB(skb)->seq;
  1911. /* From in_flight test above, we know that cwnd > in_flight. */
  1912. cong_win = (tcp_snd_cwnd(tp) - in_flight) * tp->mss_cache;
  1913. limit = min(send_win, cong_win);
  1914. /* If a full-sized TSO skb can be sent, do it. */
  1915. if (limit >= max_segs * tp->mss_cache)
  1916. goto send_now;
  1917. /* Middle in queue won't get any more data, full sendable already? */
  1918. if ((skb != tcp_write_queue_tail(sk)) && (limit >= skb->len))
  1919. goto send_now;
  1920. win_divisor = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_tso_win_divisor);
  1921. if (win_divisor) {
  1922. u32 chunk = min(tp->snd_wnd, tcp_snd_cwnd(tp) * tp->mss_cache);
  1923. /* If at least some fraction of a window is available,
  1924. * just use it.
  1925. */
  1926. chunk /= win_divisor;
  1927. if (limit >= chunk)
  1928. goto send_now;
  1929. } else {
  1930. /* Different approach, try not to defer past a single
  1931. * ACK. Receiver should ACK every other full sized
  1932. * frame, so if we have space for more than 3 frames
  1933. * then send now.
  1934. */
  1935. if (limit > tcp_max_tso_deferred_mss(tp) * tp->mss_cache)
  1936. goto send_now;
  1937. }
  1938. /* TODO : use tsorted_sent_queue ? */
  1939. head = tcp_rtx_queue_head(sk);
  1940. if (!head)
  1941. goto send_now;
  1942. srtt_in_ns = (u64)(NSEC_PER_USEC >> 3) * tp->srtt_us;
  1943. /* When is the ACK expected ? */
  1944. expected_ack = head->tstamp + srtt_in_ns;
  1945. /* How far from now is the ACK expected ? */
  1946. how_far_is_the_ack = expected_ack - tp->tcp_clock_cache;
  1947. /* If next ACK is likely to come too late,
  1948. * ie in more than min(1ms, half srtt), do not defer.
  1949. */
  1950. threshold = min(srtt_in_ns >> 1, NSEC_PER_MSEC);
  1951. if ((s64)(how_far_is_the_ack - threshold) > 0)
  1952. goto send_now;
  1953. /* Ok, it looks like it is advisable to defer.
  1954. * Three cases are tracked :
  1955. * 1) We are cwnd-limited
  1956. * 2) We are rwnd-limited
  1957. * 3) We are application limited.
  1958. */
  1959. if (cong_win < send_win) {
  1960. if (cong_win <= skb->len) {
  1961. *is_cwnd_limited = true;
  1962. return true;
  1963. }
  1964. } else {
  1965. if (send_win <= skb->len) {
  1966. *is_rwnd_limited = true;
  1967. return true;
  1968. }
  1969. }
  1970. /* If this packet won't get more data, do not wait. */
  1971. if ((TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN) ||
  1972. TCP_SKB_CB(skb)->eor)
  1973. goto send_now;
  1974. return true;
  1975. send_now:
  1976. return false;
  1977. }
  1978. static inline void tcp_mtu_check_reprobe(struct sock *sk)
  1979. {
  1980. struct inet_connection_sock *icsk = inet_csk(sk);
  1981. struct tcp_sock *tp = tcp_sk(sk);
  1982. struct net *net = sock_net(sk);
  1983. u32 interval;
  1984. s32 delta;
  1985. interval = READ_ONCE(net->ipv4.sysctl_tcp_probe_interval);
  1986. delta = tcp_jiffies32 - icsk->icsk_mtup.probe_timestamp;
  1987. if (unlikely(delta >= interval * HZ)) {
  1988. int mss = tcp_current_mss(sk);
  1989. /* Update current search range */
  1990. icsk->icsk_mtup.probe_size = 0;
  1991. icsk->icsk_mtup.search_high = tp->rx_opt.mss_clamp +
  1992. sizeof(struct tcphdr) +
  1993. icsk->icsk_af_ops->net_header_len;
  1994. icsk->icsk_mtup.search_low = tcp_mss_to_mtu(sk, mss);
  1995. /* Update probe time stamp */
  1996. icsk->icsk_mtup.probe_timestamp = tcp_jiffies32;
  1997. }
  1998. }
  1999. static bool tcp_can_coalesce_send_queue_head(struct sock *sk, int len)
  2000. {
  2001. struct sk_buff *skb, *next;
  2002. skb = tcp_send_head(sk);
  2003. tcp_for_write_queue_from_safe(skb, next, sk) {
  2004. if (len <= skb->len)
  2005. break;
  2006. if (tcp_has_tx_tstamp(skb) || !tcp_skb_can_collapse(skb, next))
  2007. return false;
  2008. len -= skb->len;
  2009. }
  2010. return true;
  2011. }
  2012. static int tcp_clone_payload(struct sock *sk, struct sk_buff *to,
  2013. int probe_size)
  2014. {
  2015. skb_frag_t *lastfrag = NULL, *fragto = skb_shinfo(to)->frags;
  2016. int i, todo, len = 0, nr_frags = 0;
  2017. const struct sk_buff *skb;
  2018. if (!sk_wmem_schedule(sk, to->truesize + probe_size))
  2019. return -ENOMEM;
  2020. skb_queue_walk(&sk->sk_write_queue, skb) {
  2021. const skb_frag_t *fragfrom = skb_shinfo(skb)->frags;
  2022. if (skb_headlen(skb))
  2023. return -EINVAL;
  2024. for (i = 0; i < skb_shinfo(skb)->nr_frags; i++, fragfrom++) {
  2025. if (len >= probe_size)
  2026. goto commit;
  2027. todo = min_t(int, skb_frag_size(fragfrom),
  2028. probe_size - len);
  2029. len += todo;
  2030. if (lastfrag &&
  2031. skb_frag_page(fragfrom) == skb_frag_page(lastfrag) &&
  2032. skb_frag_off(fragfrom) == skb_frag_off(lastfrag) +
  2033. skb_frag_size(lastfrag)) {
  2034. skb_frag_size_add(lastfrag, todo);
  2035. continue;
  2036. }
  2037. if (unlikely(nr_frags == MAX_SKB_FRAGS))
  2038. return -E2BIG;
  2039. skb_frag_page_copy(fragto, fragfrom);
  2040. skb_frag_off_copy(fragto, fragfrom);
  2041. skb_frag_size_set(fragto, todo);
  2042. nr_frags++;
  2043. lastfrag = fragto++;
  2044. }
  2045. }
  2046. commit:
  2047. WARN_ON_ONCE(len != probe_size);
  2048. for (i = 0; i < nr_frags; i++)
  2049. skb_frag_ref(to, i);
  2050. skb_shinfo(to)->nr_frags = nr_frags;
  2051. to->truesize += probe_size;
  2052. to->len += probe_size;
  2053. to->data_len += probe_size;
  2054. __skb_header_release(to);
  2055. return 0;
  2056. }
  2057. /* tcp_mtu_probe() and tcp_grow_skb() can both eat an skb (src) if
  2058. * all its payload was moved to another one (dst).
  2059. * Make sure to transfer tcp_flags, eor, and tstamp.
  2060. */
  2061. static void tcp_eat_one_skb(struct sock *sk,
  2062. struct sk_buff *dst,
  2063. struct sk_buff *src)
  2064. {
  2065. TCP_SKB_CB(dst)->tcp_flags |= TCP_SKB_CB(src)->tcp_flags;
  2066. TCP_SKB_CB(dst)->eor = TCP_SKB_CB(src)->eor;
  2067. tcp_skb_collapse_tstamp(dst, src);
  2068. tcp_unlink_write_queue(src, sk);
  2069. tcp_wmem_free_skb(sk, src);
  2070. }
  2071. /* Create a new MTU probe if we are ready.
  2072. * MTU probe is regularly attempting to increase the path MTU by
  2073. * deliberately sending larger packets. This discovers routing
  2074. * changes resulting in larger path MTUs.
  2075. *
  2076. * Returns 0 if we should wait to probe (no cwnd available),
  2077. * 1 if a probe was sent,
  2078. * -1 otherwise
  2079. */
  2080. static int tcp_mtu_probe(struct sock *sk)
  2081. {
  2082. struct inet_connection_sock *icsk = inet_csk(sk);
  2083. struct tcp_sock *tp = tcp_sk(sk);
  2084. struct sk_buff *skb, *nskb, *next;
  2085. struct net *net = sock_net(sk);
  2086. int probe_size;
  2087. int size_needed;
  2088. int copy, len;
  2089. int mss_now;
  2090. int interval;
  2091. /* Not currently probing/verifying,
  2092. * not in recovery,
  2093. * have enough cwnd, and
  2094. * not SACKing (the variable headers throw things off)
  2095. */
  2096. if (likely(!icsk->icsk_mtup.enabled ||
  2097. icsk->icsk_mtup.probe_size ||
  2098. inet_csk(sk)->icsk_ca_state != TCP_CA_Open ||
  2099. tcp_snd_cwnd(tp) < 11 ||
  2100. tp->rx_opt.num_sacks || tp->rx_opt.dsack))
  2101. return -1;
  2102. /* Use binary search for probe_size between tcp_mss_base,
  2103. * and current mss_clamp. if (search_high - search_low)
  2104. * smaller than a threshold, backoff from probing.
  2105. */
  2106. mss_now = tcp_current_mss(sk);
  2107. probe_size = tcp_mtu_to_mss(sk, (icsk->icsk_mtup.search_high +
  2108. icsk->icsk_mtup.search_low) >> 1);
  2109. size_needed = probe_size + (tp->reordering + 1) * tp->mss_cache;
  2110. interval = icsk->icsk_mtup.search_high - icsk->icsk_mtup.search_low;
  2111. /* When misfortune happens, we are reprobing actively,
  2112. * and then reprobe timer has expired. We stick with current
  2113. * probing process by not resetting search range to its orignal.
  2114. */
  2115. if (probe_size > tcp_mtu_to_mss(sk, icsk->icsk_mtup.search_high) ||
  2116. interval < READ_ONCE(net->ipv4.sysctl_tcp_probe_threshold)) {
  2117. /* Check whether enough time has elaplased for
  2118. * another round of probing.
  2119. */
  2120. tcp_mtu_check_reprobe(sk);
  2121. return -1;
  2122. }
  2123. /* Have enough data in the send queue to probe? */
  2124. if (tp->write_seq - tp->snd_nxt < size_needed)
  2125. return -1;
  2126. if (tp->snd_wnd < size_needed)
  2127. return -1;
  2128. if (after(tp->snd_nxt + size_needed, tcp_wnd_end(tp)))
  2129. return 0;
  2130. /* Do we need to wait to drain cwnd? With none in flight, don't stall */
  2131. if (tcp_packets_in_flight(tp) + 2 > tcp_snd_cwnd(tp)) {
  2132. if (!tcp_packets_in_flight(tp))
  2133. return -1;
  2134. else
  2135. return 0;
  2136. }
  2137. if (!tcp_can_coalesce_send_queue_head(sk, probe_size))
  2138. return -1;
  2139. /* We're allowed to probe. Build it now. */
  2140. nskb = tcp_stream_alloc_skb(sk, GFP_ATOMIC, false);
  2141. if (!nskb)
  2142. return -1;
  2143. /* build the payload, and be prepared to abort if this fails. */
  2144. if (tcp_clone_payload(sk, nskb, probe_size)) {
  2145. tcp_skb_tsorted_anchor_cleanup(nskb);
  2146. consume_skb(nskb);
  2147. return -1;
  2148. }
  2149. sk_wmem_queued_add(sk, nskb->truesize);
  2150. sk_mem_charge(sk, nskb->truesize);
  2151. skb = tcp_send_head(sk);
  2152. skb_copy_decrypted(nskb, skb);
  2153. mptcp_skb_ext_copy(nskb, skb);
  2154. TCP_SKB_CB(nskb)->seq = TCP_SKB_CB(skb)->seq;
  2155. TCP_SKB_CB(nskb)->end_seq = TCP_SKB_CB(skb)->seq + probe_size;
  2156. TCP_SKB_CB(nskb)->tcp_flags = TCPHDR_ACK;
  2157. tcp_insert_write_queue_before(nskb, skb, sk);
  2158. tcp_highest_sack_replace(sk, skb, nskb);
  2159. len = 0;
  2160. tcp_for_write_queue_from_safe(skb, next, sk) {
  2161. copy = min_t(int, skb->len, probe_size - len);
  2162. if (skb->len <= copy) {
  2163. tcp_eat_one_skb(sk, nskb, skb);
  2164. } else {
  2165. TCP_SKB_CB(nskb)->tcp_flags |= TCP_SKB_CB(skb)->tcp_flags &
  2166. ~(TCPHDR_FIN|TCPHDR_PSH);
  2167. __pskb_trim_head(skb, copy);
  2168. tcp_set_skb_tso_segs(skb, mss_now);
  2169. TCP_SKB_CB(skb)->seq += copy;
  2170. }
  2171. len += copy;
  2172. if (len >= probe_size)
  2173. break;
  2174. }
  2175. tcp_init_tso_segs(nskb, nskb->len);
  2176. /* We're ready to send. If this fails, the probe will
  2177. * be resegmented into mss-sized pieces by tcp_write_xmit().
  2178. */
  2179. if (!tcp_transmit_skb(sk, nskb, 1, GFP_ATOMIC)) {
  2180. /* Decrement cwnd here because we are sending
  2181. * effectively two packets. */
  2182. tcp_snd_cwnd_set(tp, tcp_snd_cwnd(tp) - 1);
  2183. tcp_event_new_data_sent(sk, nskb);
  2184. icsk->icsk_mtup.probe_size = tcp_mss_to_mtu(sk, nskb->len);
  2185. tp->mtu_probe.probe_seq_start = TCP_SKB_CB(nskb)->seq;
  2186. tp->mtu_probe.probe_seq_end = TCP_SKB_CB(nskb)->end_seq;
  2187. return 1;
  2188. }
  2189. return -1;
  2190. }
  2191. static bool tcp_pacing_check(struct sock *sk)
  2192. {
  2193. struct tcp_sock *tp = tcp_sk(sk);
  2194. if (!tcp_needs_internal_pacing(sk))
  2195. return false;
  2196. if (tp->tcp_wstamp_ns <= tp->tcp_clock_cache)
  2197. return false;
  2198. if (!hrtimer_is_queued(&tp->pacing_timer)) {
  2199. hrtimer_start(&tp->pacing_timer,
  2200. ns_to_ktime(tp->tcp_wstamp_ns),
  2201. HRTIMER_MODE_ABS_PINNED_SOFT);
  2202. sock_hold(sk);
  2203. }
  2204. return true;
  2205. }
  2206. static bool tcp_rtx_queue_empty_or_single_skb(const struct sock *sk)
  2207. {
  2208. const struct rb_node *node = sk->tcp_rtx_queue.rb_node;
  2209. /* No skb in the rtx queue. */
  2210. if (!node)
  2211. return true;
  2212. /* Only one skb in rtx queue. */
  2213. return !node->rb_left && !node->rb_right;
  2214. }
  2215. /* TCP Small Queues :
  2216. * Control number of packets in qdisc/devices to two packets / or ~1 ms.
  2217. * (These limits are doubled for retransmits)
  2218. * This allows for :
  2219. * - better RTT estimation and ACK scheduling
  2220. * - faster recovery
  2221. * - high rates
  2222. * Alas, some drivers / subsystems require a fair amount
  2223. * of queued bytes to ensure line rate.
  2224. * One example is wifi aggregation (802.11 AMPDU)
  2225. */
  2226. static bool tcp_small_queue_check(struct sock *sk, const struct sk_buff *skb,
  2227. unsigned int factor)
  2228. {
  2229. unsigned long limit;
  2230. limit = max_t(unsigned long,
  2231. 2 * skb->truesize,
  2232. READ_ONCE(sk->sk_pacing_rate) >> READ_ONCE(sk->sk_pacing_shift));
  2233. if (sk->sk_pacing_status == SK_PACING_NONE)
  2234. limit = min_t(unsigned long, limit,
  2235. READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_limit_output_bytes));
  2236. limit <<= factor;
  2237. if (static_branch_unlikely(&tcp_tx_delay_enabled) &&
  2238. tcp_sk(sk)->tcp_tx_delay) {
  2239. u64 extra_bytes = (u64)READ_ONCE(sk->sk_pacing_rate) *
  2240. tcp_sk(sk)->tcp_tx_delay;
  2241. /* TSQ is based on skb truesize sum (sk_wmem_alloc), so we
  2242. * approximate our needs assuming an ~100% skb->truesize overhead.
  2243. * USEC_PER_SEC is approximated by 2^20.
  2244. * do_div(extra_bytes, USEC_PER_SEC/2) is replaced by a right shift.
  2245. */
  2246. extra_bytes >>= (20 - 1);
  2247. limit += extra_bytes;
  2248. }
  2249. if (refcount_read(&sk->sk_wmem_alloc) > limit) {
  2250. /* Always send skb if rtx queue is empty or has one skb.
  2251. * No need to wait for TX completion to call us back,
  2252. * after softirq/tasklet schedule.
  2253. * This helps when TX completions are delayed too much.
  2254. */
  2255. if (tcp_rtx_queue_empty_or_single_skb(sk))
  2256. return false;
  2257. set_bit(TSQ_THROTTLED, &sk->sk_tsq_flags);
  2258. /* It is possible TX completion already happened
  2259. * before we set TSQ_THROTTLED, so we must
  2260. * test again the condition.
  2261. */
  2262. smp_mb__after_atomic();
  2263. if (refcount_read(&sk->sk_wmem_alloc) > limit)
  2264. return true;
  2265. }
  2266. return false;
  2267. }
  2268. static void tcp_chrono_set(struct tcp_sock *tp, const enum tcp_chrono new)
  2269. {
  2270. const u32 now = tcp_jiffies32;
  2271. enum tcp_chrono old = tp->chrono_type;
  2272. if (old > TCP_CHRONO_UNSPEC)
  2273. tp->chrono_stat[old - 1] += now - tp->chrono_start;
  2274. tp->chrono_start = now;
  2275. tp->chrono_type = new;
  2276. }
  2277. void tcp_chrono_start(struct sock *sk, const enum tcp_chrono type)
  2278. {
  2279. struct tcp_sock *tp = tcp_sk(sk);
  2280. /* If there are multiple conditions worthy of tracking in a
  2281. * chronograph then the highest priority enum takes precedence
  2282. * over the other conditions. So that if something "more interesting"
  2283. * starts happening, stop the previous chrono and start a new one.
  2284. */
  2285. if (type > tp->chrono_type)
  2286. tcp_chrono_set(tp, type);
  2287. }
  2288. void tcp_chrono_stop(struct sock *sk, const enum tcp_chrono type)
  2289. {
  2290. struct tcp_sock *tp = tcp_sk(sk);
  2291. /* There are multiple conditions worthy of tracking in a
  2292. * chronograph, so that the highest priority enum takes
  2293. * precedence over the other conditions (see tcp_chrono_start).
  2294. * If a condition stops, we only stop chrono tracking if
  2295. * it's the "most interesting" or current chrono we are
  2296. * tracking and starts busy chrono if we have pending data.
  2297. */
  2298. if (tcp_rtx_and_write_queues_empty(sk))
  2299. tcp_chrono_set(tp, TCP_CHRONO_UNSPEC);
  2300. else if (type == tp->chrono_type)
  2301. tcp_chrono_set(tp, TCP_CHRONO_BUSY);
  2302. }
  2303. /* First skb in the write queue is smaller than ideal packet size.
  2304. * Check if we can move payload from the second skb in the queue.
  2305. */
  2306. static void tcp_grow_skb(struct sock *sk, struct sk_buff *skb, int amount)
  2307. {
  2308. struct sk_buff *next_skb = skb->next;
  2309. unsigned int nlen;
  2310. if (tcp_skb_is_last(sk, skb))
  2311. return;
  2312. if (!tcp_skb_can_collapse(skb, next_skb))
  2313. return;
  2314. nlen = min_t(u32, amount, next_skb->len);
  2315. if (!nlen || !skb_shift(skb, next_skb, nlen))
  2316. return;
  2317. TCP_SKB_CB(skb)->end_seq += nlen;
  2318. TCP_SKB_CB(next_skb)->seq += nlen;
  2319. if (!next_skb->len) {
  2320. /* In case FIN is set, we need to update end_seq */
  2321. TCP_SKB_CB(skb)->end_seq = TCP_SKB_CB(next_skb)->end_seq;
  2322. tcp_eat_one_skb(sk, skb, next_skb);
  2323. }
  2324. }
  2325. /* This routine writes packets to the network. It advances the
  2326. * send_head. This happens as incoming acks open up the remote
  2327. * window for us.
  2328. *
  2329. * LARGESEND note: !tcp_urg_mode is overkill, only frames between
  2330. * snd_up-64k-mss .. snd_up cannot be large. However, taking into
  2331. * account rare use of URG, this is not a big flaw.
  2332. *
  2333. * Send at most one packet when push_one > 0. Temporarily ignore
  2334. * cwnd limit to force at most one packet out when push_one == 2.
  2335. * Returns true, if no segments are in flight and we have queued segments,
  2336. * but cannot send anything now because of SWS or another problem.
  2337. */
  2338. static bool tcp_write_xmit(struct sock *sk, unsigned int mss_now, int nonagle,
  2339. int push_one, gfp_t gfp)
  2340. {
  2341. struct tcp_sock *tp = tcp_sk(sk);
  2342. struct sk_buff *skb;
  2343. unsigned int tso_segs, sent_pkts;
  2344. u32 cwnd_quota, max_segs;
  2345. int result;
  2346. bool is_cwnd_limited = false, is_rwnd_limited = false;
  2347. sent_pkts = 0;
  2348. tcp_mstamp_refresh(tp);
  2349. if (!push_one) {
  2350. /* Do MTU probing. */
  2351. result = tcp_mtu_probe(sk);
  2352. if (!result) {
  2353. return false;
  2354. } else if (result > 0) {
  2355. sent_pkts = 1;
  2356. }
  2357. }
  2358. max_segs = tcp_tso_segs(sk, mss_now);
  2359. while ((skb = tcp_send_head(sk))) {
  2360. unsigned int limit;
  2361. int missing_bytes;
  2362. if (unlikely(tp->repair) && tp->repair_queue == TCP_SEND_QUEUE) {
  2363. /* "skb_mstamp_ns" is used as a start point for the retransmit timer */
  2364. tp->tcp_wstamp_ns = tp->tcp_clock_cache;
  2365. skb_set_delivery_time(skb, tp->tcp_wstamp_ns, SKB_CLOCK_MONOTONIC);
  2366. list_move_tail(&skb->tcp_tsorted_anchor, &tp->tsorted_sent_queue);
  2367. tcp_init_tso_segs(skb, mss_now);
  2368. goto repair; /* Skip network transmission */
  2369. }
  2370. if (tcp_pacing_check(sk))
  2371. break;
  2372. cwnd_quota = tcp_cwnd_test(tp);
  2373. if (!cwnd_quota) {
  2374. if (push_one == 2)
  2375. /* Force out a loss probe pkt. */
  2376. cwnd_quota = 1;
  2377. else
  2378. break;
  2379. }
  2380. cwnd_quota = min(cwnd_quota, max_segs);
  2381. missing_bytes = cwnd_quota * mss_now - skb->len;
  2382. if (missing_bytes > 0)
  2383. tcp_grow_skb(sk, skb, missing_bytes);
  2384. tso_segs = tcp_set_skb_tso_segs(skb, mss_now);
  2385. if (unlikely(!tcp_snd_wnd_test(tp, skb, mss_now))) {
  2386. is_rwnd_limited = true;
  2387. break;
  2388. }
  2389. if (tso_segs == 1) {
  2390. if (unlikely(!tcp_nagle_test(tp, skb, mss_now,
  2391. (tcp_skb_is_last(sk, skb) ?
  2392. nonagle : TCP_NAGLE_PUSH))))
  2393. break;
  2394. } else {
  2395. if (!push_one &&
  2396. tcp_tso_should_defer(sk, skb, &is_cwnd_limited,
  2397. &is_rwnd_limited, max_segs))
  2398. break;
  2399. }
  2400. limit = mss_now;
  2401. if (tso_segs > 1 && !tcp_urg_mode(tp))
  2402. limit = tcp_mss_split_point(sk, skb, mss_now,
  2403. cwnd_quota,
  2404. nonagle);
  2405. if (skb->len > limit &&
  2406. unlikely(tso_fragment(sk, skb, limit, mss_now, gfp)))
  2407. break;
  2408. if (tcp_small_queue_check(sk, skb, 0))
  2409. break;
  2410. /* Argh, we hit an empty skb(), presumably a thread
  2411. * is sleeping in sendmsg()/sk_stream_wait_memory().
  2412. * We do not want to send a pure-ack packet and have
  2413. * a strange looking rtx queue with empty packet(s).
  2414. */
  2415. if (TCP_SKB_CB(skb)->end_seq == TCP_SKB_CB(skb)->seq)
  2416. break;
  2417. if (unlikely(tcp_transmit_skb(sk, skb, 1, gfp)))
  2418. break;
  2419. repair:
  2420. /* Advance the send_head. This one is sent out.
  2421. * This call will increment packets_out.
  2422. */
  2423. tcp_event_new_data_sent(sk, skb);
  2424. tcp_minshall_update(tp, mss_now, skb);
  2425. sent_pkts += tcp_skb_pcount(skb);
  2426. if (push_one)
  2427. break;
  2428. }
  2429. if (is_rwnd_limited)
  2430. tcp_chrono_start(sk, TCP_CHRONO_RWND_LIMITED);
  2431. else
  2432. tcp_chrono_stop(sk, TCP_CHRONO_RWND_LIMITED);
  2433. is_cwnd_limited |= (tcp_packets_in_flight(tp) >= tcp_snd_cwnd(tp));
  2434. if (likely(sent_pkts || is_cwnd_limited))
  2435. tcp_cwnd_validate(sk, is_cwnd_limited);
  2436. if (likely(sent_pkts)) {
  2437. if (tcp_in_cwnd_reduction(sk))
  2438. tp->prr_out += sent_pkts;
  2439. /* Send one loss probe per tail loss episode. */
  2440. if (push_one != 2)
  2441. tcp_schedule_loss_probe(sk, false);
  2442. return false;
  2443. }
  2444. return !tp->packets_out && !tcp_write_queue_empty(sk);
  2445. }
  2446. bool tcp_schedule_loss_probe(struct sock *sk, bool advancing_rto)
  2447. {
  2448. struct inet_connection_sock *icsk = inet_csk(sk);
  2449. struct tcp_sock *tp = tcp_sk(sk);
  2450. u32 timeout, timeout_us, rto_delta_us;
  2451. int early_retrans;
  2452. /* Don't do any loss probe on a Fast Open connection before 3WHS
  2453. * finishes.
  2454. */
  2455. if (rcu_access_pointer(tp->fastopen_rsk))
  2456. return false;
  2457. early_retrans = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_early_retrans);
  2458. /* Schedule a loss probe in 2*RTT for SACK capable connections
  2459. * not in loss recovery, that are either limited by cwnd or application.
  2460. */
  2461. if ((early_retrans != 3 && early_retrans != 4) ||
  2462. !tp->packets_out || !tcp_is_sack(tp) ||
  2463. (icsk->icsk_ca_state != TCP_CA_Open &&
  2464. icsk->icsk_ca_state != TCP_CA_CWR))
  2465. return false;
  2466. /* Probe timeout is 2*rtt. Add minimum RTO to account
  2467. * for delayed ack when there's one outstanding packet. If no RTT
  2468. * sample is available then probe after TCP_TIMEOUT_INIT.
  2469. */
  2470. if (tp->srtt_us) {
  2471. timeout_us = tp->srtt_us >> 2;
  2472. if (tp->packets_out == 1)
  2473. timeout_us += tcp_rto_min_us(sk);
  2474. else
  2475. timeout_us += TCP_TIMEOUT_MIN_US;
  2476. timeout = usecs_to_jiffies(timeout_us);
  2477. } else {
  2478. timeout = TCP_TIMEOUT_INIT;
  2479. }
  2480. /* If the RTO formula yields an earlier time, then use that time. */
  2481. rto_delta_us = advancing_rto ?
  2482. jiffies_to_usecs(inet_csk(sk)->icsk_rto) :
  2483. tcp_rto_delta_us(sk); /* How far in future is RTO? */
  2484. if (rto_delta_us > 0)
  2485. timeout = min_t(u32, timeout, usecs_to_jiffies(rto_delta_us));
  2486. tcp_reset_xmit_timer(sk, ICSK_TIME_LOSS_PROBE, timeout, TCP_RTO_MAX);
  2487. return true;
  2488. }
  2489. /* Thanks to skb fast clones, we can detect if a prior transmit of
  2490. * a packet is still in a qdisc or driver queue.
  2491. * In this case, there is very little point doing a retransmit !
  2492. */
  2493. static bool skb_still_in_host_queue(struct sock *sk,
  2494. const struct sk_buff *skb)
  2495. {
  2496. if (unlikely(skb_fclone_busy(sk, skb))) {
  2497. set_bit(TSQ_THROTTLED, &sk->sk_tsq_flags);
  2498. smp_mb__after_atomic();
  2499. if (skb_fclone_busy(sk, skb)) {
  2500. NET_INC_STATS(sock_net(sk),
  2501. LINUX_MIB_TCPSPURIOUS_RTX_HOSTQUEUES);
  2502. return true;
  2503. }
  2504. }
  2505. return false;
  2506. }
  2507. /* When probe timeout (PTO) fires, try send a new segment if possible, else
  2508. * retransmit the last segment.
  2509. */
  2510. void tcp_send_loss_probe(struct sock *sk)
  2511. {
  2512. struct tcp_sock *tp = tcp_sk(sk);
  2513. struct sk_buff *skb;
  2514. int pcount;
  2515. int mss = tcp_current_mss(sk);
  2516. /* At most one outstanding TLP */
  2517. if (tp->tlp_high_seq)
  2518. goto rearm_timer;
  2519. tp->tlp_retrans = 0;
  2520. skb = tcp_send_head(sk);
  2521. if (skb && tcp_snd_wnd_test(tp, skb, mss)) {
  2522. pcount = tp->packets_out;
  2523. tcp_write_xmit(sk, mss, TCP_NAGLE_OFF, 2, GFP_ATOMIC);
  2524. if (tp->packets_out > pcount)
  2525. goto probe_sent;
  2526. goto rearm_timer;
  2527. }
  2528. skb = skb_rb_last(&sk->tcp_rtx_queue);
  2529. if (unlikely(!skb)) {
  2530. WARN_ONCE(tp->packets_out,
  2531. "invalid inflight: %u state %u cwnd %u mss %d\n",
  2532. tp->packets_out, sk->sk_state, tcp_snd_cwnd(tp), mss);
  2533. inet_csk(sk)->icsk_pending = 0;
  2534. return;
  2535. }
  2536. if (skb_still_in_host_queue(sk, skb))
  2537. goto rearm_timer;
  2538. pcount = tcp_skb_pcount(skb);
  2539. if (WARN_ON(!pcount))
  2540. goto rearm_timer;
  2541. if ((pcount > 1) && (skb->len > (pcount - 1) * mss)) {
  2542. if (unlikely(tcp_fragment(sk, TCP_FRAG_IN_RTX_QUEUE, skb,
  2543. (pcount - 1) * mss, mss,
  2544. GFP_ATOMIC)))
  2545. goto rearm_timer;
  2546. skb = skb_rb_next(skb);
  2547. }
  2548. if (WARN_ON(!skb || !tcp_skb_pcount(skb)))
  2549. goto rearm_timer;
  2550. if (__tcp_retransmit_skb(sk, skb, 1))
  2551. goto rearm_timer;
  2552. tp->tlp_retrans = 1;
  2553. probe_sent:
  2554. /* Record snd_nxt for loss detection. */
  2555. tp->tlp_high_seq = tp->snd_nxt;
  2556. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPLOSSPROBES);
  2557. /* Reset s.t. tcp_rearm_rto will restart timer from now */
  2558. inet_csk(sk)->icsk_pending = 0;
  2559. rearm_timer:
  2560. tcp_rearm_rto(sk);
  2561. }
  2562. /* Push out any pending frames which were held back due to
  2563. * TCP_CORK or attempt at coalescing tiny packets.
  2564. * The socket must be locked by the caller.
  2565. */
  2566. void __tcp_push_pending_frames(struct sock *sk, unsigned int cur_mss,
  2567. int nonagle)
  2568. {
  2569. /* If we are closed, the bytes will have to remain here.
  2570. * In time closedown will finish, we empty the write queue and
  2571. * all will be happy.
  2572. */
  2573. if (unlikely(sk->sk_state == TCP_CLOSE))
  2574. return;
  2575. if (tcp_write_xmit(sk, cur_mss, nonagle, 0,
  2576. sk_gfp_mask(sk, GFP_ATOMIC)))
  2577. tcp_check_probe_timer(sk);
  2578. }
  2579. /* Send _single_ skb sitting at the send head. This function requires
  2580. * true push pending frames to setup probe timer etc.
  2581. */
  2582. void tcp_push_one(struct sock *sk, unsigned int mss_now)
  2583. {
  2584. struct sk_buff *skb = tcp_send_head(sk);
  2585. BUG_ON(!skb || skb->len < mss_now);
  2586. tcp_write_xmit(sk, mss_now, TCP_NAGLE_PUSH, 1, sk->sk_allocation);
  2587. }
  2588. /* This function returns the amount that we can raise the
  2589. * usable window based on the following constraints
  2590. *
  2591. * 1. The window can never be shrunk once it is offered (RFC 793)
  2592. * 2. We limit memory per socket
  2593. *
  2594. * RFC 1122:
  2595. * "the suggested [SWS] avoidance algorithm for the receiver is to keep
  2596. * RECV.NEXT + RCV.WIN fixed until:
  2597. * RCV.BUFF - RCV.USER - RCV.WINDOW >= min(1/2 RCV.BUFF, MSS)"
  2598. *
  2599. * i.e. don't raise the right edge of the window until you can raise
  2600. * it at least MSS bytes.
  2601. *
  2602. * Unfortunately, the recommended algorithm breaks header prediction,
  2603. * since header prediction assumes th->window stays fixed.
  2604. *
  2605. * Strictly speaking, keeping th->window fixed violates the receiver
  2606. * side SWS prevention criteria. The problem is that under this rule
  2607. * a stream of single byte packets will cause the right side of the
  2608. * window to always advance by a single byte.
  2609. *
  2610. * Of course, if the sender implements sender side SWS prevention
  2611. * then this will not be a problem.
  2612. *
  2613. * BSD seems to make the following compromise:
  2614. *
  2615. * If the free space is less than the 1/4 of the maximum
  2616. * space available and the free space is less than 1/2 mss,
  2617. * then set the window to 0.
  2618. * [ Actually, bsd uses MSS and 1/4 of maximal _window_ ]
  2619. * Otherwise, just prevent the window from shrinking
  2620. * and from being larger than the largest representable value.
  2621. *
  2622. * This prevents incremental opening of the window in the regime
  2623. * where TCP is limited by the speed of the reader side taking
  2624. * data out of the TCP receive queue. It does nothing about
  2625. * those cases where the window is constrained on the sender side
  2626. * because the pipeline is full.
  2627. *
  2628. * BSD also seems to "accidentally" limit itself to windows that are a
  2629. * multiple of MSS, at least until the free space gets quite small.
  2630. * This would appear to be a side effect of the mbuf implementation.
  2631. * Combining these two algorithms results in the observed behavior
  2632. * of having a fixed window size at almost all times.
  2633. *
  2634. * Below we obtain similar behavior by forcing the offered window to
  2635. * a multiple of the mss when it is feasible to do so.
  2636. *
  2637. * Note, we don't "adjust" for TIMESTAMP or SACK option bytes.
  2638. * Regular options like TIMESTAMP are taken into account.
  2639. */
  2640. u32 __tcp_select_window(struct sock *sk)
  2641. {
  2642. struct inet_connection_sock *icsk = inet_csk(sk);
  2643. struct tcp_sock *tp = tcp_sk(sk);
  2644. struct net *net = sock_net(sk);
  2645. /* MSS for the peer's data. Previous versions used mss_clamp
  2646. * here. I don't know if the value based on our guesses
  2647. * of peer's MSS is better for the performance. It's more correct
  2648. * but may be worse for the performance because of rcv_mss
  2649. * fluctuations. --SAW 1998/11/1
  2650. */
  2651. int mss = icsk->icsk_ack.rcv_mss;
  2652. int free_space = tcp_space(sk);
  2653. int allowed_space = tcp_full_space(sk);
  2654. int full_space, window;
  2655. if (sk_is_mptcp(sk))
  2656. mptcp_space(sk, &free_space, &allowed_space);
  2657. full_space = min_t(int, tp->window_clamp, allowed_space);
  2658. if (unlikely(mss > full_space)) {
  2659. mss = full_space;
  2660. if (mss <= 0)
  2661. return 0;
  2662. }
  2663. /* Only allow window shrink if the sysctl is enabled and we have
  2664. * a non-zero scaling factor in effect.
  2665. */
  2666. if (READ_ONCE(net->ipv4.sysctl_tcp_shrink_window) && tp->rx_opt.rcv_wscale)
  2667. goto shrink_window_allowed;
  2668. /* do not allow window to shrink */
  2669. if (free_space < (full_space >> 1)) {
  2670. icsk->icsk_ack.quick = 0;
  2671. if (tcp_under_memory_pressure(sk))
  2672. tcp_adjust_rcv_ssthresh(sk);
  2673. /* free_space might become our new window, make sure we don't
  2674. * increase it due to wscale.
  2675. */
  2676. free_space = round_down(free_space, 1 << tp->rx_opt.rcv_wscale);
  2677. /* if free space is less than mss estimate, or is below 1/16th
  2678. * of the maximum allowed, try to move to zero-window, else
  2679. * tcp_clamp_window() will grow rcv buf up to tcp_rmem[2], and
  2680. * new incoming data is dropped due to memory limits.
  2681. * With large window, mss test triggers way too late in order
  2682. * to announce zero window in time before rmem limit kicks in.
  2683. */
  2684. if (free_space < (allowed_space >> 4) || free_space < mss)
  2685. return 0;
  2686. }
  2687. if (free_space > tp->rcv_ssthresh)
  2688. free_space = tp->rcv_ssthresh;
  2689. /* Don't do rounding if we are using window scaling, since the
  2690. * scaled window will not line up with the MSS boundary anyway.
  2691. */
  2692. if (tp->rx_opt.rcv_wscale) {
  2693. window = free_space;
  2694. /* Advertise enough space so that it won't get scaled away.
  2695. * Import case: prevent zero window announcement if
  2696. * 1<<rcv_wscale > mss.
  2697. */
  2698. window = ALIGN(window, (1 << tp->rx_opt.rcv_wscale));
  2699. } else {
  2700. window = tp->rcv_wnd;
  2701. /* Get the largest window that is a nice multiple of mss.
  2702. * Window clamp already applied above.
  2703. * If our current window offering is within 1 mss of the
  2704. * free space we just keep it. This prevents the divide
  2705. * and multiply from happening most of the time.
  2706. * We also don't do any window rounding when the free space
  2707. * is too small.
  2708. */
  2709. if (window <= free_space - mss || window > free_space)
  2710. window = rounddown(free_space, mss);
  2711. else if (mss == full_space &&
  2712. free_space > window + (full_space >> 1))
  2713. window = free_space;
  2714. }
  2715. return window;
  2716. shrink_window_allowed:
  2717. /* new window should always be an exact multiple of scaling factor */
  2718. free_space = round_down(free_space, 1 << tp->rx_opt.rcv_wscale);
  2719. if (free_space < (full_space >> 1)) {
  2720. icsk->icsk_ack.quick = 0;
  2721. if (tcp_under_memory_pressure(sk))
  2722. tcp_adjust_rcv_ssthresh(sk);
  2723. /* if free space is too low, return a zero window */
  2724. if (free_space < (allowed_space >> 4) || free_space < mss ||
  2725. free_space < (1 << tp->rx_opt.rcv_wscale))
  2726. return 0;
  2727. }
  2728. if (free_space > tp->rcv_ssthresh) {
  2729. free_space = tp->rcv_ssthresh;
  2730. /* new window should always be an exact multiple of scaling factor
  2731. *
  2732. * For this case, we ALIGN "up" (increase free_space) because
  2733. * we know free_space is not zero here, it has been reduced from
  2734. * the memory-based limit, and rcv_ssthresh is not a hard limit
  2735. * (unlike sk_rcvbuf).
  2736. */
  2737. free_space = ALIGN(free_space, (1 << tp->rx_opt.rcv_wscale));
  2738. }
  2739. return free_space;
  2740. }
  2741. void tcp_skb_collapse_tstamp(struct sk_buff *skb,
  2742. const struct sk_buff *next_skb)
  2743. {
  2744. if (unlikely(tcp_has_tx_tstamp(next_skb))) {
  2745. const struct skb_shared_info *next_shinfo =
  2746. skb_shinfo(next_skb);
  2747. struct skb_shared_info *shinfo = skb_shinfo(skb);
  2748. shinfo->tx_flags |= next_shinfo->tx_flags & SKBTX_ANY_TSTAMP;
  2749. shinfo->tskey = next_shinfo->tskey;
  2750. TCP_SKB_CB(skb)->txstamp_ack |=
  2751. TCP_SKB_CB(next_skb)->txstamp_ack;
  2752. }
  2753. }
  2754. /* Collapses two adjacent SKB's during retransmission. */
  2755. static bool tcp_collapse_retrans(struct sock *sk, struct sk_buff *skb)
  2756. {
  2757. struct tcp_sock *tp = tcp_sk(sk);
  2758. struct sk_buff *next_skb = skb_rb_next(skb);
  2759. int next_skb_size;
  2760. next_skb_size = next_skb->len;
  2761. BUG_ON(tcp_skb_pcount(skb) != 1 || tcp_skb_pcount(next_skb) != 1);
  2762. if (next_skb_size && !tcp_skb_shift(skb, next_skb, 1, next_skb_size))
  2763. return false;
  2764. tcp_highest_sack_replace(sk, next_skb, skb);
  2765. /* Update sequence range on original skb. */
  2766. TCP_SKB_CB(skb)->end_seq = TCP_SKB_CB(next_skb)->end_seq;
  2767. /* Merge over control information. This moves PSH/FIN etc. over */
  2768. TCP_SKB_CB(skb)->tcp_flags |= TCP_SKB_CB(next_skb)->tcp_flags;
  2769. /* All done, get rid of second SKB and account for it so
  2770. * packet counting does not break.
  2771. */
  2772. TCP_SKB_CB(skb)->sacked |= TCP_SKB_CB(next_skb)->sacked & TCPCB_EVER_RETRANS;
  2773. TCP_SKB_CB(skb)->eor = TCP_SKB_CB(next_skb)->eor;
  2774. /* changed transmit queue under us so clear hints */
  2775. tcp_clear_retrans_hints_partial(tp);
  2776. if (next_skb == tp->retransmit_skb_hint)
  2777. tp->retransmit_skb_hint = skb;
  2778. tcp_adjust_pcount(sk, next_skb, tcp_skb_pcount(next_skb));
  2779. tcp_skb_collapse_tstamp(skb, next_skb);
  2780. tcp_rtx_queue_unlink_and_free(next_skb, sk);
  2781. return true;
  2782. }
  2783. /* Check if coalescing SKBs is legal. */
  2784. static bool tcp_can_collapse(const struct sock *sk, const struct sk_buff *skb)
  2785. {
  2786. if (tcp_skb_pcount(skb) > 1)
  2787. return false;
  2788. if (skb_cloned(skb))
  2789. return false;
  2790. if (!skb_frags_readable(skb))
  2791. return false;
  2792. /* Some heuristics for collapsing over SACK'd could be invented */
  2793. if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED)
  2794. return false;
  2795. return true;
  2796. }
  2797. /* Collapse packets in the retransmit queue to make to create
  2798. * less packets on the wire. This is only done on retransmission.
  2799. */
  2800. static void tcp_retrans_try_collapse(struct sock *sk, struct sk_buff *to,
  2801. int space)
  2802. {
  2803. struct tcp_sock *tp = tcp_sk(sk);
  2804. struct sk_buff *skb = to, *tmp;
  2805. bool first = true;
  2806. if (!READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_retrans_collapse))
  2807. return;
  2808. if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN)
  2809. return;
  2810. skb_rbtree_walk_from_safe(skb, tmp) {
  2811. if (!tcp_can_collapse(sk, skb))
  2812. break;
  2813. if (!tcp_skb_can_collapse(to, skb))
  2814. break;
  2815. space -= skb->len;
  2816. if (first) {
  2817. first = false;
  2818. continue;
  2819. }
  2820. if (space < 0)
  2821. break;
  2822. if (after(TCP_SKB_CB(skb)->end_seq, tcp_wnd_end(tp)))
  2823. break;
  2824. if (!tcp_collapse_retrans(sk, to))
  2825. break;
  2826. }
  2827. }
  2828. /* This retransmits one SKB. Policy decisions and retransmit queue
  2829. * state updates are done by the caller. Returns non-zero if an
  2830. * error occurred which prevented the send.
  2831. */
  2832. int __tcp_retransmit_skb(struct sock *sk, struct sk_buff *skb, int segs)
  2833. {
  2834. struct inet_connection_sock *icsk = inet_csk(sk);
  2835. struct tcp_sock *tp = tcp_sk(sk);
  2836. unsigned int cur_mss;
  2837. int diff, len, err;
  2838. int avail_wnd;
  2839. /* Inconclusive MTU probe */
  2840. if (icsk->icsk_mtup.probe_size)
  2841. icsk->icsk_mtup.probe_size = 0;
  2842. if (skb_still_in_host_queue(sk, skb))
  2843. return -EBUSY;
  2844. start:
  2845. if (before(TCP_SKB_CB(skb)->seq, tp->snd_una)) {
  2846. if (unlikely(TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN)) {
  2847. TCP_SKB_CB(skb)->tcp_flags &= ~TCPHDR_SYN;
  2848. TCP_SKB_CB(skb)->seq++;
  2849. goto start;
  2850. }
  2851. if (unlikely(before(TCP_SKB_CB(skb)->end_seq, tp->snd_una))) {
  2852. WARN_ON_ONCE(1);
  2853. return -EINVAL;
  2854. }
  2855. if (tcp_trim_head(sk, skb, tp->snd_una - TCP_SKB_CB(skb)->seq))
  2856. return -ENOMEM;
  2857. }
  2858. if (inet_csk(sk)->icsk_af_ops->rebuild_header(sk))
  2859. return -EHOSTUNREACH; /* Routing failure or similar. */
  2860. cur_mss = tcp_current_mss(sk);
  2861. avail_wnd = tcp_wnd_end(tp) - TCP_SKB_CB(skb)->seq;
  2862. /* If receiver has shrunk his window, and skb is out of
  2863. * new window, do not retransmit it. The exception is the
  2864. * case, when window is shrunk to zero. In this case
  2865. * our retransmit of one segment serves as a zero window probe.
  2866. */
  2867. if (avail_wnd <= 0) {
  2868. if (TCP_SKB_CB(skb)->seq != tp->snd_una)
  2869. return -EAGAIN;
  2870. avail_wnd = cur_mss;
  2871. }
  2872. len = cur_mss * segs;
  2873. if (len > avail_wnd) {
  2874. len = rounddown(avail_wnd, cur_mss);
  2875. if (!len)
  2876. len = avail_wnd;
  2877. }
  2878. if (skb->len > len) {
  2879. if (tcp_fragment(sk, TCP_FRAG_IN_RTX_QUEUE, skb, len,
  2880. cur_mss, GFP_ATOMIC))
  2881. return -ENOMEM; /* We'll try again later. */
  2882. } else {
  2883. if (skb_unclone_keeptruesize(skb, GFP_ATOMIC))
  2884. return -ENOMEM;
  2885. diff = tcp_skb_pcount(skb);
  2886. tcp_set_skb_tso_segs(skb, cur_mss);
  2887. diff -= tcp_skb_pcount(skb);
  2888. if (diff)
  2889. tcp_adjust_pcount(sk, skb, diff);
  2890. avail_wnd = min_t(int, avail_wnd, cur_mss);
  2891. if (skb->len < avail_wnd)
  2892. tcp_retrans_try_collapse(sk, skb, avail_wnd);
  2893. }
  2894. /* RFC3168, section 6.1.1.1. ECN fallback */
  2895. if ((TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN_ECN) == TCPHDR_SYN_ECN)
  2896. tcp_ecn_clear_syn(sk, skb);
  2897. /* Update global and local TCP statistics. */
  2898. segs = tcp_skb_pcount(skb);
  2899. TCP_ADD_STATS(sock_net(sk), TCP_MIB_RETRANSSEGS, segs);
  2900. if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN)
  2901. __NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPSYNRETRANS);
  2902. tp->total_retrans += segs;
  2903. tp->bytes_retrans += skb->len;
  2904. /* make sure skb->data is aligned on arches that require it
  2905. * and check if ack-trimming & collapsing extended the headroom
  2906. * beyond what csum_start can cover.
  2907. */
  2908. if (unlikely((NET_IP_ALIGN && ((unsigned long)skb->data & 3)) ||
  2909. skb_headroom(skb) >= 0xFFFF)) {
  2910. struct sk_buff *nskb;
  2911. tcp_skb_tsorted_save(skb) {
  2912. nskb = __pskb_copy(skb, MAX_TCP_HEADER, GFP_ATOMIC);
  2913. if (nskb) {
  2914. nskb->dev = NULL;
  2915. err = tcp_transmit_skb(sk, nskb, 0, GFP_ATOMIC);
  2916. } else {
  2917. err = -ENOBUFS;
  2918. }
  2919. } tcp_skb_tsorted_restore(skb);
  2920. if (!err) {
  2921. tcp_update_skb_after_send(sk, skb, tp->tcp_wstamp_ns);
  2922. tcp_rate_skb_sent(sk, skb);
  2923. }
  2924. } else {
  2925. err = tcp_transmit_skb(sk, skb, 1, GFP_ATOMIC);
  2926. }
  2927. if (BPF_SOCK_OPS_TEST_FLAG(tp, BPF_SOCK_OPS_RETRANS_CB_FLAG))
  2928. tcp_call_bpf_3arg(sk, BPF_SOCK_OPS_RETRANS_CB,
  2929. TCP_SKB_CB(skb)->seq, segs, err);
  2930. if (likely(!err)) {
  2931. trace_tcp_retransmit_skb(sk, skb);
  2932. } else if (err != -EBUSY) {
  2933. NET_ADD_STATS(sock_net(sk), LINUX_MIB_TCPRETRANSFAIL, segs);
  2934. }
  2935. /* To avoid taking spuriously low RTT samples based on a timestamp
  2936. * for a transmit that never happened, always mark EVER_RETRANS
  2937. */
  2938. TCP_SKB_CB(skb)->sacked |= TCPCB_EVER_RETRANS;
  2939. return err;
  2940. }
  2941. int tcp_retransmit_skb(struct sock *sk, struct sk_buff *skb, int segs)
  2942. {
  2943. struct tcp_sock *tp = tcp_sk(sk);
  2944. int err = __tcp_retransmit_skb(sk, skb, segs);
  2945. if (err == 0) {
  2946. #if FASTRETRANS_DEBUG > 0
  2947. if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_RETRANS) {
  2948. net_dbg_ratelimited("retrans_out leaked\n");
  2949. }
  2950. #endif
  2951. TCP_SKB_CB(skb)->sacked |= TCPCB_RETRANS;
  2952. tp->retrans_out += tcp_skb_pcount(skb);
  2953. }
  2954. /* Save stamp of the first (attempted) retransmit. */
  2955. if (!tp->retrans_stamp)
  2956. tp->retrans_stamp = tcp_skb_timestamp_ts(tp->tcp_usec_ts, skb);
  2957. if (tp->undo_retrans < 0)
  2958. tp->undo_retrans = 0;
  2959. tp->undo_retrans += tcp_skb_pcount(skb);
  2960. return err;
  2961. }
  2962. /* This gets called after a retransmit timeout, and the initially
  2963. * retransmitted data is acknowledged. It tries to continue
  2964. * resending the rest of the retransmit queue, until either
  2965. * we've sent it all or the congestion window limit is reached.
  2966. */
  2967. void tcp_xmit_retransmit_queue(struct sock *sk)
  2968. {
  2969. const struct inet_connection_sock *icsk = inet_csk(sk);
  2970. struct sk_buff *skb, *rtx_head, *hole = NULL;
  2971. struct tcp_sock *tp = tcp_sk(sk);
  2972. bool rearm_timer = false;
  2973. u32 max_segs;
  2974. int mib_idx;
  2975. if (!tp->packets_out)
  2976. return;
  2977. rtx_head = tcp_rtx_queue_head(sk);
  2978. skb = tp->retransmit_skb_hint ?: rtx_head;
  2979. max_segs = tcp_tso_segs(sk, tcp_current_mss(sk));
  2980. skb_rbtree_walk_from(skb) {
  2981. __u8 sacked;
  2982. int segs;
  2983. if (tcp_pacing_check(sk))
  2984. break;
  2985. /* we could do better than to assign each time */
  2986. if (!hole)
  2987. tp->retransmit_skb_hint = skb;
  2988. segs = tcp_snd_cwnd(tp) - tcp_packets_in_flight(tp);
  2989. if (segs <= 0)
  2990. break;
  2991. sacked = TCP_SKB_CB(skb)->sacked;
  2992. /* In case tcp_shift_skb_data() have aggregated large skbs,
  2993. * we need to make sure not sending too bigs TSO packets
  2994. */
  2995. segs = min_t(int, segs, max_segs);
  2996. if (tp->retrans_out >= tp->lost_out) {
  2997. break;
  2998. } else if (!(sacked & TCPCB_LOST)) {
  2999. if (!hole && !(sacked & (TCPCB_SACKED_RETRANS|TCPCB_SACKED_ACKED)))
  3000. hole = skb;
  3001. continue;
  3002. } else {
  3003. if (icsk->icsk_ca_state != TCP_CA_Loss)
  3004. mib_idx = LINUX_MIB_TCPFASTRETRANS;
  3005. else
  3006. mib_idx = LINUX_MIB_TCPSLOWSTARTRETRANS;
  3007. }
  3008. if (sacked & (TCPCB_SACKED_ACKED|TCPCB_SACKED_RETRANS))
  3009. continue;
  3010. if (tcp_small_queue_check(sk, skb, 1))
  3011. break;
  3012. if (tcp_retransmit_skb(sk, skb, segs))
  3013. break;
  3014. NET_ADD_STATS(sock_net(sk), mib_idx, tcp_skb_pcount(skb));
  3015. if (tcp_in_cwnd_reduction(sk))
  3016. tp->prr_out += tcp_skb_pcount(skb);
  3017. if (skb == rtx_head &&
  3018. icsk->icsk_pending != ICSK_TIME_REO_TIMEOUT)
  3019. rearm_timer = true;
  3020. }
  3021. if (rearm_timer)
  3022. tcp_reset_xmit_timer(sk, ICSK_TIME_RETRANS,
  3023. inet_csk(sk)->icsk_rto,
  3024. TCP_RTO_MAX);
  3025. }
  3026. /* We allow to exceed memory limits for FIN packets to expedite
  3027. * connection tear down and (memory) recovery.
  3028. * Otherwise tcp_send_fin() could be tempted to either delay FIN
  3029. * or even be forced to close flow without any FIN.
  3030. * In general, we want to allow one skb per socket to avoid hangs
  3031. * with edge trigger epoll()
  3032. */
  3033. void sk_forced_mem_schedule(struct sock *sk, int size)
  3034. {
  3035. int delta, amt;
  3036. delta = size - sk->sk_forward_alloc;
  3037. if (delta <= 0)
  3038. return;
  3039. amt = sk_mem_pages(delta);
  3040. sk_forward_alloc_add(sk, amt << PAGE_SHIFT);
  3041. sk_memory_allocated_add(sk, amt);
  3042. if (mem_cgroup_sockets_enabled && sk->sk_memcg)
  3043. mem_cgroup_charge_skmem(sk->sk_memcg, amt,
  3044. gfp_memcg_charge() | __GFP_NOFAIL);
  3045. }
  3046. /* Send a FIN. The caller locks the socket for us.
  3047. * We should try to send a FIN packet really hard, but eventually give up.
  3048. */
  3049. void tcp_send_fin(struct sock *sk)
  3050. {
  3051. struct sk_buff *skb, *tskb, *tail = tcp_write_queue_tail(sk);
  3052. struct tcp_sock *tp = tcp_sk(sk);
  3053. /* Optimization, tack on the FIN if we have one skb in write queue and
  3054. * this skb was not yet sent, or we are under memory pressure.
  3055. * Note: in the latter case, FIN packet will be sent after a timeout,
  3056. * as TCP stack thinks it has already been transmitted.
  3057. */
  3058. tskb = tail;
  3059. if (!tskb && tcp_under_memory_pressure(sk))
  3060. tskb = skb_rb_last(&sk->tcp_rtx_queue);
  3061. if (tskb) {
  3062. TCP_SKB_CB(tskb)->tcp_flags |= TCPHDR_FIN;
  3063. TCP_SKB_CB(tskb)->end_seq++;
  3064. tp->write_seq++;
  3065. if (!tail) {
  3066. /* This means tskb was already sent.
  3067. * Pretend we included the FIN on previous transmit.
  3068. * We need to set tp->snd_nxt to the value it would have
  3069. * if FIN had been sent. This is because retransmit path
  3070. * does not change tp->snd_nxt.
  3071. */
  3072. WRITE_ONCE(tp->snd_nxt, tp->snd_nxt + 1);
  3073. return;
  3074. }
  3075. } else {
  3076. skb = alloc_skb_fclone(MAX_TCP_HEADER,
  3077. sk_gfp_mask(sk, GFP_ATOMIC |
  3078. __GFP_NOWARN));
  3079. if (unlikely(!skb))
  3080. return;
  3081. INIT_LIST_HEAD(&skb->tcp_tsorted_anchor);
  3082. skb_reserve(skb, MAX_TCP_HEADER);
  3083. sk_forced_mem_schedule(sk, skb->truesize);
  3084. /* FIN eats a sequence byte, write_seq advanced by tcp_queue_skb(). */
  3085. tcp_init_nondata_skb(skb, tp->write_seq,
  3086. TCPHDR_ACK | TCPHDR_FIN);
  3087. tcp_queue_skb(sk, skb);
  3088. }
  3089. __tcp_push_pending_frames(sk, tcp_current_mss(sk), TCP_NAGLE_OFF);
  3090. }
  3091. /* We get here when a process closes a file descriptor (either due to
  3092. * an explicit close() or as a byproduct of exit()'ing) and there
  3093. * was unread data in the receive queue. This behavior is recommended
  3094. * by RFC 2525, section 2.17. -DaveM
  3095. */
  3096. void tcp_send_active_reset(struct sock *sk, gfp_t priority,
  3097. enum sk_rst_reason reason)
  3098. {
  3099. struct sk_buff *skb;
  3100. TCP_INC_STATS(sock_net(sk), TCP_MIB_OUTRSTS);
  3101. /* NOTE: No TCP options attached and we never retransmit this. */
  3102. skb = alloc_skb(MAX_TCP_HEADER, priority);
  3103. if (!skb) {
  3104. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTFAILED);
  3105. return;
  3106. }
  3107. /* Reserve space for headers and prepare control bits. */
  3108. skb_reserve(skb, MAX_TCP_HEADER);
  3109. tcp_init_nondata_skb(skb, tcp_acceptable_seq(sk),
  3110. TCPHDR_ACK | TCPHDR_RST);
  3111. tcp_mstamp_refresh(tcp_sk(sk));
  3112. /* Send it off. */
  3113. if (tcp_transmit_skb(sk, skb, 0, priority))
  3114. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTFAILED);
  3115. /* skb of trace_tcp_send_reset() keeps the skb that caused RST,
  3116. * skb here is different to the troublesome skb, so use NULL
  3117. */
  3118. trace_tcp_send_reset(sk, NULL, reason);
  3119. }
  3120. /* Send a crossed SYN-ACK during socket establishment.
  3121. * WARNING: This routine must only be called when we have already sent
  3122. * a SYN packet that crossed the incoming SYN that caused this routine
  3123. * to get called. If this assumption fails then the initial rcv_wnd
  3124. * and rcv_wscale values will not be correct.
  3125. */
  3126. int tcp_send_synack(struct sock *sk)
  3127. {
  3128. struct sk_buff *skb;
  3129. skb = tcp_rtx_queue_head(sk);
  3130. if (!skb || !(TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN)) {
  3131. pr_err("%s: wrong queue state\n", __func__);
  3132. return -EFAULT;
  3133. }
  3134. if (!(TCP_SKB_CB(skb)->tcp_flags & TCPHDR_ACK)) {
  3135. if (skb_cloned(skb)) {
  3136. struct sk_buff *nskb;
  3137. tcp_skb_tsorted_save(skb) {
  3138. nskb = skb_copy(skb, GFP_ATOMIC);
  3139. } tcp_skb_tsorted_restore(skb);
  3140. if (!nskb)
  3141. return -ENOMEM;
  3142. INIT_LIST_HEAD(&nskb->tcp_tsorted_anchor);
  3143. tcp_highest_sack_replace(sk, skb, nskb);
  3144. tcp_rtx_queue_unlink_and_free(skb, sk);
  3145. __skb_header_release(nskb);
  3146. tcp_rbtree_insert(&sk->tcp_rtx_queue, nskb);
  3147. sk_wmem_queued_add(sk, nskb->truesize);
  3148. sk_mem_charge(sk, nskb->truesize);
  3149. skb = nskb;
  3150. }
  3151. TCP_SKB_CB(skb)->tcp_flags |= TCPHDR_ACK;
  3152. tcp_ecn_send_synack(sk, skb);
  3153. }
  3154. return tcp_transmit_skb(sk, skb, 1, GFP_ATOMIC);
  3155. }
  3156. /**
  3157. * tcp_make_synack - Allocate one skb and build a SYNACK packet.
  3158. * @sk: listener socket
  3159. * @dst: dst entry attached to the SYNACK. It is consumed and caller
  3160. * should not use it again.
  3161. * @req: request_sock pointer
  3162. * @foc: cookie for tcp fast open
  3163. * @synack_type: Type of synack to prepare
  3164. * @syn_skb: SYN packet just received. It could be NULL for rtx case.
  3165. */
  3166. struct sk_buff *tcp_make_synack(const struct sock *sk, struct dst_entry *dst,
  3167. struct request_sock *req,
  3168. struct tcp_fastopen_cookie *foc,
  3169. enum tcp_synack_type synack_type,
  3170. struct sk_buff *syn_skb)
  3171. {
  3172. struct inet_request_sock *ireq = inet_rsk(req);
  3173. const struct tcp_sock *tp = tcp_sk(sk);
  3174. struct tcp_out_options opts;
  3175. struct tcp_key key = {};
  3176. struct sk_buff *skb;
  3177. int tcp_header_size;
  3178. struct tcphdr *th;
  3179. int mss;
  3180. u64 now;
  3181. skb = alloc_skb(MAX_TCP_HEADER, GFP_ATOMIC);
  3182. if (unlikely(!skb)) {
  3183. dst_release(dst);
  3184. return NULL;
  3185. }
  3186. /* Reserve space for headers. */
  3187. skb_reserve(skb, MAX_TCP_HEADER);
  3188. switch (synack_type) {
  3189. case TCP_SYNACK_NORMAL:
  3190. skb_set_owner_w(skb, req_to_sk(req));
  3191. break;
  3192. case TCP_SYNACK_COOKIE:
  3193. /* Under synflood, we do not attach skb to a socket,
  3194. * to avoid false sharing.
  3195. */
  3196. break;
  3197. case TCP_SYNACK_FASTOPEN:
  3198. /* sk is a const pointer, because we want to express multiple
  3199. * cpu might call us concurrently.
  3200. * sk->sk_wmem_alloc in an atomic, we can promote to rw.
  3201. */
  3202. skb_set_owner_w(skb, (struct sock *)sk);
  3203. break;
  3204. }
  3205. skb_dst_set(skb, dst);
  3206. mss = tcp_mss_clamp(tp, dst_metric_advmss(dst));
  3207. memset(&opts, 0, sizeof(opts));
  3208. now = tcp_clock_ns();
  3209. #ifdef CONFIG_SYN_COOKIES
  3210. if (unlikely(synack_type == TCP_SYNACK_COOKIE && ireq->tstamp_ok))
  3211. skb_set_delivery_time(skb, cookie_init_timestamp(req, now),
  3212. SKB_CLOCK_MONOTONIC);
  3213. else
  3214. #endif
  3215. {
  3216. skb_set_delivery_time(skb, now, SKB_CLOCK_MONOTONIC);
  3217. if (!tcp_rsk(req)->snt_synack) /* Timestamp first SYNACK */
  3218. tcp_rsk(req)->snt_synack = tcp_skb_timestamp_us(skb);
  3219. }
  3220. #if defined(CONFIG_TCP_MD5SIG) || defined(CONFIG_TCP_AO)
  3221. rcu_read_lock();
  3222. #endif
  3223. if (tcp_rsk_used_ao(req)) {
  3224. #ifdef CONFIG_TCP_AO
  3225. struct tcp_ao_key *ao_key = NULL;
  3226. u8 keyid = tcp_rsk(req)->ao_keyid;
  3227. u8 rnext = tcp_rsk(req)->ao_rcv_next;
  3228. ao_key = tcp_sk(sk)->af_specific->ao_lookup(sk, req_to_sk(req),
  3229. keyid, -1);
  3230. /* If there is no matching key - avoid sending anything,
  3231. * especially usigned segments. It could try harder and lookup
  3232. * for another peer-matching key, but the peer has requested
  3233. * ao_keyid (RFC5925 RNextKeyID), so let's keep it simple here.
  3234. */
  3235. if (unlikely(!ao_key)) {
  3236. trace_tcp_ao_synack_no_key(sk, keyid, rnext);
  3237. rcu_read_unlock();
  3238. kfree_skb(skb);
  3239. net_warn_ratelimited("TCP-AO: the keyid %u from SYN packet is not present - not sending SYNACK\n",
  3240. keyid);
  3241. return NULL;
  3242. }
  3243. key.ao_key = ao_key;
  3244. key.type = TCP_KEY_AO;
  3245. #endif
  3246. } else {
  3247. #ifdef CONFIG_TCP_MD5SIG
  3248. key.md5_key = tcp_rsk(req)->af_specific->req_md5_lookup(sk,
  3249. req_to_sk(req));
  3250. if (key.md5_key)
  3251. key.type = TCP_KEY_MD5;
  3252. #endif
  3253. }
  3254. skb_set_hash(skb, READ_ONCE(tcp_rsk(req)->txhash), PKT_HASH_TYPE_L4);
  3255. /* bpf program will be interested in the tcp_flags */
  3256. TCP_SKB_CB(skb)->tcp_flags = TCPHDR_SYN | TCPHDR_ACK;
  3257. tcp_header_size = tcp_synack_options(sk, req, mss, skb, &opts,
  3258. &key, foc, synack_type, syn_skb)
  3259. + sizeof(*th);
  3260. skb_push(skb, tcp_header_size);
  3261. skb_reset_transport_header(skb);
  3262. th = (struct tcphdr *)skb->data;
  3263. memset(th, 0, sizeof(struct tcphdr));
  3264. th->syn = 1;
  3265. th->ack = 1;
  3266. tcp_ecn_make_synack(req, th);
  3267. th->source = htons(ireq->ir_num);
  3268. th->dest = ireq->ir_rmt_port;
  3269. skb->mark = ireq->ir_mark;
  3270. skb->ip_summed = CHECKSUM_PARTIAL;
  3271. th->seq = htonl(tcp_rsk(req)->snt_isn);
  3272. /* XXX data is queued and acked as is. No buffer/window check */
  3273. th->ack_seq = htonl(tcp_rsk(req)->rcv_nxt);
  3274. /* RFC1323: The window in SYN & SYN/ACK segments is never scaled. */
  3275. th->window = htons(min(req->rsk_rcv_wnd, 65535U));
  3276. tcp_options_write(th, NULL, tcp_rsk(req), &opts, &key);
  3277. th->doff = (tcp_header_size >> 2);
  3278. TCP_INC_STATS(sock_net(sk), TCP_MIB_OUTSEGS);
  3279. /* Okay, we have all we need - do the md5 hash if needed */
  3280. if (tcp_key_is_md5(&key)) {
  3281. #ifdef CONFIG_TCP_MD5SIG
  3282. tcp_rsk(req)->af_specific->calc_md5_hash(opts.hash_location,
  3283. key.md5_key, req_to_sk(req), skb);
  3284. #endif
  3285. } else if (tcp_key_is_ao(&key)) {
  3286. #ifdef CONFIG_TCP_AO
  3287. tcp_rsk(req)->af_specific->ao_synack_hash(opts.hash_location,
  3288. key.ao_key, req, skb,
  3289. opts.hash_location - (u8 *)th, 0);
  3290. #endif
  3291. }
  3292. #if defined(CONFIG_TCP_MD5SIG) || defined(CONFIG_TCP_AO)
  3293. rcu_read_unlock();
  3294. #endif
  3295. bpf_skops_write_hdr_opt((struct sock *)sk, skb, req, syn_skb,
  3296. synack_type, &opts);
  3297. skb_set_delivery_time(skb, now, SKB_CLOCK_MONOTONIC);
  3298. tcp_add_tx_delay(skb, tp);
  3299. return skb;
  3300. }
  3301. EXPORT_SYMBOL(tcp_make_synack);
  3302. static void tcp_ca_dst_init(struct sock *sk, const struct dst_entry *dst)
  3303. {
  3304. struct inet_connection_sock *icsk = inet_csk(sk);
  3305. const struct tcp_congestion_ops *ca;
  3306. u32 ca_key = dst_metric(dst, RTAX_CC_ALGO);
  3307. if (ca_key == TCP_CA_UNSPEC)
  3308. return;
  3309. rcu_read_lock();
  3310. ca = tcp_ca_find_key(ca_key);
  3311. if (likely(ca && bpf_try_module_get(ca, ca->owner))) {
  3312. bpf_module_put(icsk->icsk_ca_ops, icsk->icsk_ca_ops->owner);
  3313. icsk->icsk_ca_dst_locked = tcp_ca_dst_locked(dst);
  3314. icsk->icsk_ca_ops = ca;
  3315. }
  3316. rcu_read_unlock();
  3317. }
  3318. /* Do all connect socket setups that can be done AF independent. */
  3319. static void tcp_connect_init(struct sock *sk)
  3320. {
  3321. const struct dst_entry *dst = __sk_dst_get(sk);
  3322. struct tcp_sock *tp = tcp_sk(sk);
  3323. __u8 rcv_wscale;
  3324. u32 rcv_wnd;
  3325. /* We'll fix this up when we get a response from the other end.
  3326. * See tcp_input.c:tcp_rcv_state_process case TCP_SYN_SENT.
  3327. */
  3328. tp->tcp_header_len = sizeof(struct tcphdr);
  3329. if (READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_timestamps))
  3330. tp->tcp_header_len += TCPOLEN_TSTAMP_ALIGNED;
  3331. tcp_ao_connect_init(sk);
  3332. /* If user gave his TCP_MAXSEG, record it to clamp */
  3333. if (tp->rx_opt.user_mss)
  3334. tp->rx_opt.mss_clamp = tp->rx_opt.user_mss;
  3335. tp->max_window = 0;
  3336. tcp_mtup_init(sk);
  3337. tcp_sync_mss(sk, dst_mtu(dst));
  3338. tcp_ca_dst_init(sk, dst);
  3339. if (!tp->window_clamp)
  3340. WRITE_ONCE(tp->window_clamp, dst_metric(dst, RTAX_WINDOW));
  3341. tp->advmss = tcp_mss_clamp(tp, dst_metric_advmss(dst));
  3342. tcp_initialize_rcv_mss(sk);
  3343. /* limit the window selection if the user enforce a smaller rx buffer */
  3344. if (sk->sk_userlocks & SOCK_RCVBUF_LOCK &&
  3345. (tp->window_clamp > tcp_full_space(sk) || tp->window_clamp == 0))
  3346. WRITE_ONCE(tp->window_clamp, tcp_full_space(sk));
  3347. rcv_wnd = tcp_rwnd_init_bpf(sk);
  3348. if (rcv_wnd == 0)
  3349. rcv_wnd = dst_metric(dst, RTAX_INITRWND);
  3350. tcp_select_initial_window(sk, tcp_full_space(sk),
  3351. tp->advmss - (tp->rx_opt.ts_recent_stamp ? tp->tcp_header_len - sizeof(struct tcphdr) : 0),
  3352. &tp->rcv_wnd,
  3353. &tp->window_clamp,
  3354. READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_window_scaling),
  3355. &rcv_wscale,
  3356. rcv_wnd);
  3357. tp->rx_opt.rcv_wscale = rcv_wscale;
  3358. tp->rcv_ssthresh = tp->rcv_wnd;
  3359. WRITE_ONCE(sk->sk_err, 0);
  3360. sock_reset_flag(sk, SOCK_DONE);
  3361. tp->snd_wnd = 0;
  3362. tcp_init_wl(tp, 0);
  3363. tcp_write_queue_purge(sk);
  3364. tp->snd_una = tp->write_seq;
  3365. tp->snd_sml = tp->write_seq;
  3366. tp->snd_up = tp->write_seq;
  3367. WRITE_ONCE(tp->snd_nxt, tp->write_seq);
  3368. if (likely(!tp->repair))
  3369. tp->rcv_nxt = 0;
  3370. else
  3371. tp->rcv_tstamp = tcp_jiffies32;
  3372. tp->rcv_wup = tp->rcv_nxt;
  3373. WRITE_ONCE(tp->copied_seq, tp->rcv_nxt);
  3374. inet_csk(sk)->icsk_rto = tcp_timeout_init(sk);
  3375. inet_csk(sk)->icsk_retransmits = 0;
  3376. tcp_clear_retrans(tp);
  3377. }
  3378. static void tcp_connect_queue_skb(struct sock *sk, struct sk_buff *skb)
  3379. {
  3380. struct tcp_sock *tp = tcp_sk(sk);
  3381. struct tcp_skb_cb *tcb = TCP_SKB_CB(skb);
  3382. tcb->end_seq += skb->len;
  3383. __skb_header_release(skb);
  3384. sk_wmem_queued_add(sk, skb->truesize);
  3385. sk_mem_charge(sk, skb->truesize);
  3386. WRITE_ONCE(tp->write_seq, tcb->end_seq);
  3387. tp->packets_out += tcp_skb_pcount(skb);
  3388. }
  3389. /* Build and send a SYN with data and (cached) Fast Open cookie. However,
  3390. * queue a data-only packet after the regular SYN, such that regular SYNs
  3391. * are retransmitted on timeouts. Also if the remote SYN-ACK acknowledges
  3392. * only the SYN sequence, the data are retransmitted in the first ACK.
  3393. * If cookie is not cached or other error occurs, falls back to send a
  3394. * regular SYN with Fast Open cookie request option.
  3395. */
  3396. static int tcp_send_syn_data(struct sock *sk, struct sk_buff *syn)
  3397. {
  3398. struct inet_connection_sock *icsk = inet_csk(sk);
  3399. struct tcp_sock *tp = tcp_sk(sk);
  3400. struct tcp_fastopen_request *fo = tp->fastopen_req;
  3401. struct page_frag *pfrag = sk_page_frag(sk);
  3402. struct sk_buff *syn_data;
  3403. int space, err = 0;
  3404. tp->rx_opt.mss_clamp = tp->advmss; /* If MSS is not cached */
  3405. if (!tcp_fastopen_cookie_check(sk, &tp->rx_opt.mss_clamp, &fo->cookie))
  3406. goto fallback;
  3407. /* MSS for SYN-data is based on cached MSS and bounded by PMTU and
  3408. * user-MSS. Reserve maximum option space for middleboxes that add
  3409. * private TCP options. The cost is reduced data space in SYN :(
  3410. */
  3411. tp->rx_opt.mss_clamp = tcp_mss_clamp(tp, tp->rx_opt.mss_clamp);
  3412. /* Sync mss_cache after updating the mss_clamp */
  3413. tcp_sync_mss(sk, icsk->icsk_pmtu_cookie);
  3414. space = __tcp_mtu_to_mss(sk, icsk->icsk_pmtu_cookie) -
  3415. MAX_TCP_OPTION_SPACE;
  3416. space = min_t(size_t, space, fo->size);
  3417. if (space &&
  3418. !skb_page_frag_refill(min_t(size_t, space, PAGE_SIZE),
  3419. pfrag, sk->sk_allocation))
  3420. goto fallback;
  3421. syn_data = tcp_stream_alloc_skb(sk, sk->sk_allocation, false);
  3422. if (!syn_data)
  3423. goto fallback;
  3424. memcpy(syn_data->cb, syn->cb, sizeof(syn->cb));
  3425. if (space) {
  3426. space = min_t(size_t, space, pfrag->size - pfrag->offset);
  3427. space = tcp_wmem_schedule(sk, space);
  3428. }
  3429. if (space) {
  3430. space = copy_page_from_iter(pfrag->page, pfrag->offset,
  3431. space, &fo->data->msg_iter);
  3432. if (unlikely(!space)) {
  3433. tcp_skb_tsorted_anchor_cleanup(syn_data);
  3434. kfree_skb(syn_data);
  3435. goto fallback;
  3436. }
  3437. skb_fill_page_desc(syn_data, 0, pfrag->page,
  3438. pfrag->offset, space);
  3439. page_ref_inc(pfrag->page);
  3440. pfrag->offset += space;
  3441. skb_len_add(syn_data, space);
  3442. skb_zcopy_set(syn_data, fo->uarg, NULL);
  3443. }
  3444. /* No more data pending in inet_wait_for_connect() */
  3445. if (space == fo->size)
  3446. fo->data = NULL;
  3447. fo->copied = space;
  3448. tcp_connect_queue_skb(sk, syn_data);
  3449. if (syn_data->len)
  3450. tcp_chrono_start(sk, TCP_CHRONO_BUSY);
  3451. err = tcp_transmit_skb(sk, syn_data, 1, sk->sk_allocation);
  3452. skb_set_delivery_time(syn, syn_data->skb_mstamp_ns, SKB_CLOCK_MONOTONIC);
  3453. /* Now full SYN+DATA was cloned and sent (or not),
  3454. * remove the SYN from the original skb (syn_data)
  3455. * we keep in write queue in case of a retransmit, as we
  3456. * also have the SYN packet (with no data) in the same queue.
  3457. */
  3458. TCP_SKB_CB(syn_data)->seq++;
  3459. TCP_SKB_CB(syn_data)->tcp_flags = TCPHDR_ACK | TCPHDR_PSH;
  3460. if (!err) {
  3461. tp->syn_data = (fo->copied > 0);
  3462. tcp_rbtree_insert(&sk->tcp_rtx_queue, syn_data);
  3463. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPORIGDATASENT);
  3464. goto done;
  3465. }
  3466. /* data was not sent, put it in write_queue */
  3467. __skb_queue_tail(&sk->sk_write_queue, syn_data);
  3468. tp->packets_out -= tcp_skb_pcount(syn_data);
  3469. fallback:
  3470. /* Send a regular SYN with Fast Open cookie request option */
  3471. if (fo->cookie.len > 0)
  3472. fo->cookie.len = 0;
  3473. err = tcp_transmit_skb(sk, syn, 1, sk->sk_allocation);
  3474. if (err)
  3475. tp->syn_fastopen = 0;
  3476. done:
  3477. fo->cookie.len = -1; /* Exclude Fast Open option for SYN retries */
  3478. return err;
  3479. }
  3480. /* Build a SYN and send it off. */
  3481. int tcp_connect(struct sock *sk)
  3482. {
  3483. struct tcp_sock *tp = tcp_sk(sk);
  3484. struct sk_buff *buff;
  3485. int err;
  3486. tcp_call_bpf(sk, BPF_SOCK_OPS_TCP_CONNECT_CB, 0, NULL);
  3487. #if defined(CONFIG_TCP_MD5SIG) && defined(CONFIG_TCP_AO)
  3488. /* Has to be checked late, after setting daddr/saddr/ops.
  3489. * Return error if the peer has both a md5 and a tcp-ao key
  3490. * configured as this is ambiguous.
  3491. */
  3492. if (unlikely(rcu_dereference_protected(tp->md5sig_info,
  3493. lockdep_sock_is_held(sk)))) {
  3494. bool needs_ao = !!tp->af_specific->ao_lookup(sk, sk, -1, -1);
  3495. bool needs_md5 = !!tp->af_specific->md5_lookup(sk, sk);
  3496. struct tcp_ao_info *ao_info;
  3497. ao_info = rcu_dereference_check(tp->ao_info,
  3498. lockdep_sock_is_held(sk));
  3499. if (ao_info) {
  3500. /* This is an extra check: tcp_ao_required() in
  3501. * tcp_v{4,6}_parse_md5_keys() should prevent adding
  3502. * md5 keys on ao_required socket.
  3503. */
  3504. needs_ao |= ao_info->ao_required;
  3505. WARN_ON_ONCE(ao_info->ao_required && needs_md5);
  3506. }
  3507. if (needs_md5 && needs_ao)
  3508. return -EKEYREJECTED;
  3509. /* If we have a matching md5 key and no matching tcp-ao key
  3510. * then free up ao_info if allocated.
  3511. */
  3512. if (needs_md5) {
  3513. tcp_ao_destroy_sock(sk, false);
  3514. } else if (needs_ao) {
  3515. tcp_clear_md5_list(sk);
  3516. kfree(rcu_replace_pointer(tp->md5sig_info, NULL,
  3517. lockdep_sock_is_held(sk)));
  3518. }
  3519. }
  3520. #endif
  3521. #ifdef CONFIG_TCP_AO
  3522. if (unlikely(rcu_dereference_protected(tp->ao_info,
  3523. lockdep_sock_is_held(sk)))) {
  3524. /* Don't allow connecting if ao is configured but no
  3525. * matching key is found.
  3526. */
  3527. if (!tp->af_specific->ao_lookup(sk, sk, -1, -1))
  3528. return -EKEYREJECTED;
  3529. }
  3530. #endif
  3531. if (inet_csk(sk)->icsk_af_ops->rebuild_header(sk))
  3532. return -EHOSTUNREACH; /* Routing failure or similar. */
  3533. tcp_connect_init(sk);
  3534. if (unlikely(tp->repair)) {
  3535. tcp_finish_connect(sk, NULL);
  3536. return 0;
  3537. }
  3538. buff = tcp_stream_alloc_skb(sk, sk->sk_allocation, true);
  3539. if (unlikely(!buff))
  3540. return -ENOBUFS;
  3541. tcp_init_nondata_skb(buff, tp->write_seq++, TCPHDR_SYN);
  3542. tcp_mstamp_refresh(tp);
  3543. tp->retrans_stamp = tcp_time_stamp_ts(tp);
  3544. tcp_connect_queue_skb(sk, buff);
  3545. tcp_ecn_send_syn(sk, buff);
  3546. tcp_rbtree_insert(&sk->tcp_rtx_queue, buff);
  3547. /* Send off SYN; include data in Fast Open. */
  3548. err = tp->fastopen_req ? tcp_send_syn_data(sk, buff) :
  3549. tcp_transmit_skb(sk, buff, 1, sk->sk_allocation);
  3550. if (err == -ECONNREFUSED)
  3551. return err;
  3552. /* We change tp->snd_nxt after the tcp_transmit_skb() call
  3553. * in order to make this packet get counted in tcpOutSegs.
  3554. */
  3555. WRITE_ONCE(tp->snd_nxt, tp->write_seq);
  3556. tp->pushed_seq = tp->write_seq;
  3557. buff = tcp_send_head(sk);
  3558. if (unlikely(buff)) {
  3559. WRITE_ONCE(tp->snd_nxt, TCP_SKB_CB(buff)->seq);
  3560. tp->pushed_seq = TCP_SKB_CB(buff)->seq;
  3561. }
  3562. TCP_INC_STATS(sock_net(sk), TCP_MIB_ACTIVEOPENS);
  3563. /* Timer for repeating the SYN until an answer. */
  3564. inet_csk_reset_xmit_timer(sk, ICSK_TIME_RETRANS,
  3565. inet_csk(sk)->icsk_rto, TCP_RTO_MAX);
  3566. return 0;
  3567. }
  3568. EXPORT_SYMBOL(tcp_connect);
  3569. u32 tcp_delack_max(const struct sock *sk)
  3570. {
  3571. u32 delack_from_rto_min = max(tcp_rto_min(sk), 2) - 1;
  3572. return min(inet_csk(sk)->icsk_delack_max, delack_from_rto_min);
  3573. }
  3574. /* Send out a delayed ack, the caller does the policy checking
  3575. * to see if we should even be here. See tcp_input.c:tcp_ack_snd_check()
  3576. * for details.
  3577. */
  3578. void tcp_send_delayed_ack(struct sock *sk)
  3579. {
  3580. struct inet_connection_sock *icsk = inet_csk(sk);
  3581. int ato = icsk->icsk_ack.ato;
  3582. unsigned long timeout;
  3583. if (ato > TCP_DELACK_MIN) {
  3584. const struct tcp_sock *tp = tcp_sk(sk);
  3585. int max_ato = HZ / 2;
  3586. if (inet_csk_in_pingpong_mode(sk) ||
  3587. (icsk->icsk_ack.pending & ICSK_ACK_PUSHED))
  3588. max_ato = TCP_DELACK_MAX;
  3589. /* Slow path, intersegment interval is "high". */
  3590. /* If some rtt estimate is known, use it to bound delayed ack.
  3591. * Do not use inet_csk(sk)->icsk_rto here, use results of rtt measurements
  3592. * directly.
  3593. */
  3594. if (tp->srtt_us) {
  3595. int rtt = max_t(int, usecs_to_jiffies(tp->srtt_us >> 3),
  3596. TCP_DELACK_MIN);
  3597. if (rtt < max_ato)
  3598. max_ato = rtt;
  3599. }
  3600. ato = min(ato, max_ato);
  3601. }
  3602. ato = min_t(u32, ato, tcp_delack_max(sk));
  3603. /* Stay within the limit we were given */
  3604. timeout = jiffies + ato;
  3605. /* Use new timeout only if there wasn't a older one earlier. */
  3606. if (icsk->icsk_ack.pending & ICSK_ACK_TIMER) {
  3607. /* If delack timer is about to expire, send ACK now. */
  3608. if (time_before_eq(icsk->icsk_ack.timeout, jiffies + (ato >> 2))) {
  3609. tcp_send_ack(sk);
  3610. return;
  3611. }
  3612. if (!time_before(timeout, icsk->icsk_ack.timeout))
  3613. timeout = icsk->icsk_ack.timeout;
  3614. }
  3615. icsk->icsk_ack.pending |= ICSK_ACK_SCHED | ICSK_ACK_TIMER;
  3616. icsk->icsk_ack.timeout = timeout;
  3617. sk_reset_timer(sk, &icsk->icsk_delack_timer, timeout);
  3618. }
  3619. /* This routine sends an ack and also updates the window. */
  3620. void __tcp_send_ack(struct sock *sk, u32 rcv_nxt)
  3621. {
  3622. struct sk_buff *buff;
  3623. /* If we have been reset, we may not send again. */
  3624. if (sk->sk_state == TCP_CLOSE)
  3625. return;
  3626. /* We are not putting this on the write queue, so
  3627. * tcp_transmit_skb() will set the ownership to this
  3628. * sock.
  3629. */
  3630. buff = alloc_skb(MAX_TCP_HEADER,
  3631. sk_gfp_mask(sk, GFP_ATOMIC | __GFP_NOWARN));
  3632. if (unlikely(!buff)) {
  3633. struct inet_connection_sock *icsk = inet_csk(sk);
  3634. unsigned long delay;
  3635. delay = TCP_DELACK_MAX << icsk->icsk_ack.retry;
  3636. if (delay < TCP_RTO_MAX)
  3637. icsk->icsk_ack.retry++;
  3638. inet_csk_schedule_ack(sk);
  3639. icsk->icsk_ack.ato = TCP_ATO_MIN;
  3640. inet_csk_reset_xmit_timer(sk, ICSK_TIME_DACK, delay, TCP_RTO_MAX);
  3641. return;
  3642. }
  3643. /* Reserve space for headers and prepare control bits. */
  3644. skb_reserve(buff, MAX_TCP_HEADER);
  3645. tcp_init_nondata_skb(buff, tcp_acceptable_seq(sk), TCPHDR_ACK);
  3646. /* We do not want pure acks influencing TCP Small Queues or fq/pacing
  3647. * too much.
  3648. * SKB_TRUESIZE(max(1 .. 66, MAX_TCP_HEADER)) is unfortunately ~784
  3649. */
  3650. skb_set_tcp_pure_ack(buff);
  3651. /* Send it off, this clears delayed acks for us. */
  3652. __tcp_transmit_skb(sk, buff, 0, (__force gfp_t)0, rcv_nxt);
  3653. }
  3654. EXPORT_SYMBOL_GPL(__tcp_send_ack);
  3655. void tcp_send_ack(struct sock *sk)
  3656. {
  3657. __tcp_send_ack(sk, tcp_sk(sk)->rcv_nxt);
  3658. }
  3659. /* This routine sends a packet with an out of date sequence
  3660. * number. It assumes the other end will try to ack it.
  3661. *
  3662. * Question: what should we make while urgent mode?
  3663. * 4.4BSD forces sending single byte of data. We cannot send
  3664. * out of window data, because we have SND.NXT==SND.MAX...
  3665. *
  3666. * Current solution: to send TWO zero-length segments in urgent mode:
  3667. * one is with SEG.SEQ=SND.UNA to deliver urgent pointer, another is
  3668. * out-of-date with SND.UNA-1 to probe window.
  3669. */
  3670. static int tcp_xmit_probe_skb(struct sock *sk, int urgent, int mib)
  3671. {
  3672. struct tcp_sock *tp = tcp_sk(sk);
  3673. struct sk_buff *skb;
  3674. /* We don't queue it, tcp_transmit_skb() sets ownership. */
  3675. skb = alloc_skb(MAX_TCP_HEADER,
  3676. sk_gfp_mask(sk, GFP_ATOMIC | __GFP_NOWARN));
  3677. if (!skb)
  3678. return -1;
  3679. /* Reserve space for headers and set control bits. */
  3680. skb_reserve(skb, MAX_TCP_HEADER);
  3681. /* Use a previous sequence. This should cause the other
  3682. * end to send an ack. Don't queue or clone SKB, just
  3683. * send it.
  3684. */
  3685. tcp_init_nondata_skb(skb, tp->snd_una - !urgent, TCPHDR_ACK);
  3686. NET_INC_STATS(sock_net(sk), mib);
  3687. return tcp_transmit_skb(sk, skb, 0, (__force gfp_t)0);
  3688. }
  3689. /* Called from setsockopt( ... TCP_REPAIR ) */
  3690. void tcp_send_window_probe(struct sock *sk)
  3691. {
  3692. if (sk->sk_state == TCP_ESTABLISHED) {
  3693. tcp_sk(sk)->snd_wl1 = tcp_sk(sk)->rcv_nxt - 1;
  3694. tcp_mstamp_refresh(tcp_sk(sk));
  3695. tcp_xmit_probe_skb(sk, 0, LINUX_MIB_TCPWINPROBE);
  3696. }
  3697. }
  3698. /* Initiate keepalive or window probe from timer. */
  3699. int tcp_write_wakeup(struct sock *sk, int mib)
  3700. {
  3701. struct tcp_sock *tp = tcp_sk(sk);
  3702. struct sk_buff *skb;
  3703. if (sk->sk_state == TCP_CLOSE)
  3704. return -1;
  3705. skb = tcp_send_head(sk);
  3706. if (skb && before(TCP_SKB_CB(skb)->seq, tcp_wnd_end(tp))) {
  3707. int err;
  3708. unsigned int mss = tcp_current_mss(sk);
  3709. unsigned int seg_size = tcp_wnd_end(tp) - TCP_SKB_CB(skb)->seq;
  3710. if (before(tp->pushed_seq, TCP_SKB_CB(skb)->end_seq))
  3711. tp->pushed_seq = TCP_SKB_CB(skb)->end_seq;
  3712. /* We are probing the opening of a window
  3713. * but the window size is != 0
  3714. * must have been a result SWS avoidance ( sender )
  3715. */
  3716. if (seg_size < TCP_SKB_CB(skb)->end_seq - TCP_SKB_CB(skb)->seq ||
  3717. skb->len > mss) {
  3718. seg_size = min(seg_size, mss);
  3719. TCP_SKB_CB(skb)->tcp_flags |= TCPHDR_PSH;
  3720. if (tcp_fragment(sk, TCP_FRAG_IN_WRITE_QUEUE,
  3721. skb, seg_size, mss, GFP_ATOMIC))
  3722. return -1;
  3723. } else if (!tcp_skb_pcount(skb))
  3724. tcp_set_skb_tso_segs(skb, mss);
  3725. TCP_SKB_CB(skb)->tcp_flags |= TCPHDR_PSH;
  3726. err = tcp_transmit_skb(sk, skb, 1, GFP_ATOMIC);
  3727. if (!err)
  3728. tcp_event_new_data_sent(sk, skb);
  3729. return err;
  3730. } else {
  3731. if (between(tp->snd_up, tp->snd_una + 1, tp->snd_una + 0xFFFF))
  3732. tcp_xmit_probe_skb(sk, 1, mib);
  3733. return tcp_xmit_probe_skb(sk, 0, mib);
  3734. }
  3735. }
  3736. /* A window probe timeout has occurred. If window is not closed send
  3737. * a partial packet else a zero probe.
  3738. */
  3739. void tcp_send_probe0(struct sock *sk)
  3740. {
  3741. struct inet_connection_sock *icsk = inet_csk(sk);
  3742. struct tcp_sock *tp = tcp_sk(sk);
  3743. struct net *net = sock_net(sk);
  3744. unsigned long timeout;
  3745. int err;
  3746. err = tcp_write_wakeup(sk, LINUX_MIB_TCPWINPROBE);
  3747. if (tp->packets_out || tcp_write_queue_empty(sk)) {
  3748. /* Cancel probe timer, if it is not required. */
  3749. icsk->icsk_probes_out = 0;
  3750. icsk->icsk_backoff = 0;
  3751. icsk->icsk_probes_tstamp = 0;
  3752. return;
  3753. }
  3754. icsk->icsk_probes_out++;
  3755. if (err <= 0) {
  3756. if (icsk->icsk_backoff < READ_ONCE(net->ipv4.sysctl_tcp_retries2))
  3757. icsk->icsk_backoff++;
  3758. timeout = tcp_probe0_when(sk, TCP_RTO_MAX);
  3759. } else {
  3760. /* If packet was not sent due to local congestion,
  3761. * Let senders fight for local resources conservatively.
  3762. */
  3763. timeout = TCP_RESOURCE_PROBE_INTERVAL;
  3764. }
  3765. timeout = tcp_clamp_probe0_to_user_timeout(sk, timeout);
  3766. tcp_reset_xmit_timer(sk, ICSK_TIME_PROBE0, timeout, TCP_RTO_MAX);
  3767. }
  3768. int tcp_rtx_synack(const struct sock *sk, struct request_sock *req)
  3769. {
  3770. const struct tcp_request_sock_ops *af_ops = tcp_rsk(req)->af_specific;
  3771. struct flowi fl;
  3772. int res;
  3773. /* Paired with WRITE_ONCE() in sock_setsockopt() */
  3774. if (READ_ONCE(sk->sk_txrehash) == SOCK_TXREHASH_ENABLED)
  3775. WRITE_ONCE(tcp_rsk(req)->txhash, net_tx_rndhash());
  3776. res = af_ops->send_synack(sk, NULL, &fl, req, NULL, TCP_SYNACK_NORMAL,
  3777. NULL);
  3778. if (!res) {
  3779. TCP_INC_STATS(sock_net(sk), TCP_MIB_RETRANSSEGS);
  3780. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPSYNRETRANS);
  3781. if (unlikely(tcp_passive_fastopen(sk))) {
  3782. /* sk has const attribute because listeners are lockless.
  3783. * However in this case, we are dealing with a passive fastopen
  3784. * socket thus we can change total_retrans value.
  3785. */
  3786. tcp_sk_rw(sk)->total_retrans++;
  3787. }
  3788. trace_tcp_retransmit_synack(sk, req);
  3789. }
  3790. return res;
  3791. }
  3792. EXPORT_SYMBOL(tcp_rtx_synack);