tcp_output.c 120 KB

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