1
0

tcp_input.c 227 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * INET An implementation of the TCP/IP protocol suite for the LINUX
  4. * operating system. INET is implemented using the BSD Socket
  5. * interface as the means of communication with the user level.
  6. *
  7. * Implementation of the Transmission Control Protocol(TCP).
  8. *
  9. * Authors: Ross Biro
  10. * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
  11. * Mark Evans, <evansmp@uhura.aston.ac.uk>
  12. * Corey Minyard <wf-rch!minyard@relay.EU.net>
  13. * Florian La Roche, <flla@stud.uni-sb.de>
  14. * Charles Hedrick, <hedrick@klinzhai.rutgers.edu>
  15. * Linus Torvalds, <torvalds@cs.helsinki.fi>
  16. * Alan Cox, <gw4pts@gw4pts.ampr.org>
  17. * Matthew Dillon, <dillon@apollo.west.oic.com>
  18. * Arnt Gulbrandsen, <agulbra@nvg.unit.no>
  19. * Jorge Cwik, <jorge@laser.satlink.net>
  20. */
  21. /*
  22. * Changes:
  23. * Pedro Roque : Fast Retransmit/Recovery.
  24. * Two receive queues.
  25. * Retransmit queue handled by TCP.
  26. * Better retransmit timer handling.
  27. * New congestion avoidance.
  28. * Header prediction.
  29. * Variable renaming.
  30. *
  31. * Eric : Fast Retransmit.
  32. * Randy Scott : MSS option defines.
  33. * Eric Schenk : Fixes to slow start algorithm.
  34. * Eric Schenk : Yet another double ACK bug.
  35. * Eric Schenk : Delayed ACK bug fixes.
  36. * Eric Schenk : Floyd style fast retrans war avoidance.
  37. * David S. Miller : Don't allow zero congestion window.
  38. * Eric Schenk : Fix retransmitter so that it sends
  39. * next packet on ack of previous packet.
  40. * Andi Kleen : Moved open_request checking here
  41. * and process RSTs for open_requests.
  42. * Andi Kleen : Better prune_queue, and other fixes.
  43. * Andrey Savochkin: Fix RTT measurements in the presence of
  44. * timestamps.
  45. * Andrey Savochkin: Check sequence numbers correctly when
  46. * removing SACKs due to in sequence incoming
  47. * data segments.
  48. * Andi Kleen: Make sure we never ack data there is not
  49. * enough room for. Also make this condition
  50. * a fatal error if it might still happen.
  51. * Andi Kleen: Add tcp_measure_rcv_mss to make
  52. * connections with MSS<min(MTU,ann. MSS)
  53. * work without delayed acks.
  54. * Andi Kleen: Process packets with PSH set in the
  55. * fast path.
  56. * J Hadi Salim: ECN support
  57. * Andrei Gurtov,
  58. * Pasi Sarolahti,
  59. * Panu Kuhlberg: Experimental audit of TCP (re)transmission
  60. * engine. Lots of bugs are found.
  61. * Pasi Sarolahti: F-RTO for dealing with spurious RTOs
  62. */
  63. #define pr_fmt(fmt) "TCP: " fmt
  64. #include <linux/mm.h>
  65. #include <linux/slab.h>
  66. #include <linux/module.h>
  67. #include <linux/sysctl.h>
  68. #include <linux/kernel.h>
  69. #include <linux/prefetch.h>
  70. #include <linux/bitops.h>
  71. #include <net/dst.h>
  72. #include <net/tcp.h>
  73. #include <net/tcp_ecn.h>
  74. #include <net/proto_memory.h>
  75. #include <net/inet_common.h>
  76. #include <linux/ipsec.h>
  77. #include <linux/unaligned.h>
  78. #include <linux/errqueue.h>
  79. #include <trace/events/tcp.h>
  80. #include <linux/jump_label_ratelimit.h>
  81. #include <net/busy_poll.h>
  82. #include <net/mptcp.h>
  83. int sysctl_tcp_max_orphans __read_mostly = NR_FILE;
  84. #define FLAG_DATA 0x01 /* Incoming frame contained data. */
  85. #define FLAG_WIN_UPDATE 0x02 /* Incoming ACK was a window update. */
  86. #define FLAG_DATA_ACKED 0x04 /* This ACK acknowledged new data. */
  87. #define FLAG_RETRANS_DATA_ACKED 0x08 /* "" "" some of which was retransmitted. */
  88. #define FLAG_SYN_ACKED 0x10 /* This ACK acknowledged SYN. */
  89. #define FLAG_DATA_SACKED 0x20 /* New SACK. */
  90. #define FLAG_ECE 0x40 /* ECE in this ACK */
  91. #define FLAG_LOST_RETRANS 0x80 /* This ACK marks some retransmission lost */
  92. #define FLAG_SLOWPATH 0x100 /* Do not skip RFC checks for window update.*/
  93. #define FLAG_ORIG_SACK_ACKED 0x200 /* Never retransmitted data are (s)acked */
  94. #define FLAG_SND_UNA_ADVANCED 0x400 /* Snd_una was changed (!= FLAG_DATA_ACKED) */
  95. #define FLAG_DSACKING_ACK 0x800 /* SACK blocks contained D-SACK info */
  96. #define FLAG_SET_XMIT_TIMER 0x1000 /* Set TLP or RTO timer */
  97. #define FLAG_SACK_RENEGING 0x2000 /* snd_una advanced to a sacked seq */
  98. #define FLAG_UPDATE_TS_RECENT 0x4000 /* tcp_replace_ts_recent() */
  99. #define FLAG_NO_CHALLENGE_ACK 0x8000 /* do not call tcp_send_challenge_ack() */
  100. #define FLAG_ACK_MAYBE_DELAYED 0x10000 /* Likely a delayed ACK */
  101. #define FLAG_DSACK_TLP 0x20000 /* DSACK for tail loss probe */
  102. #define FLAG_TS_PROGRESS 0x40000 /* Positive timestamp delta */
  103. #define FLAG_ACKED (FLAG_DATA_ACKED|FLAG_SYN_ACKED)
  104. #define FLAG_NOT_DUP (FLAG_DATA|FLAG_WIN_UPDATE|FLAG_ACKED)
  105. #define FLAG_CA_ALERT (FLAG_DATA_SACKED|FLAG_ECE|FLAG_DSACKING_ACK)
  106. #define FLAG_FORWARD_PROGRESS (FLAG_ACKED|FLAG_DATA_SACKED)
  107. #define TCP_REMNANT (TCP_FLAG_FIN|TCP_FLAG_URG|TCP_FLAG_SYN|TCP_FLAG_PSH)
  108. #define TCP_HP_BITS (~(TCP_RESERVED_BITS|TCP_FLAG_PSH))
  109. #define REXMIT_NONE 0 /* no loss recovery to do */
  110. #define REXMIT_LOST 1 /* retransmit packets marked lost */
  111. #define REXMIT_NEW 2 /* FRTO-style transmit of unsent/new packets */
  112. #if IS_ENABLED(CONFIG_TLS_DEVICE)
  113. static DEFINE_STATIC_KEY_DEFERRED_FALSE(clean_acked_data_enabled, HZ);
  114. void clean_acked_data_enable(struct tcp_sock *tp,
  115. void (*cad)(struct sock *sk, u32 ack_seq))
  116. {
  117. tp->tcp_clean_acked = cad;
  118. static_branch_deferred_inc(&clean_acked_data_enabled);
  119. }
  120. EXPORT_SYMBOL_GPL(clean_acked_data_enable);
  121. void clean_acked_data_disable(struct tcp_sock *tp)
  122. {
  123. static_branch_slow_dec_deferred(&clean_acked_data_enabled);
  124. tp->tcp_clean_acked = NULL;
  125. }
  126. EXPORT_SYMBOL_GPL(clean_acked_data_disable);
  127. void clean_acked_data_flush(void)
  128. {
  129. static_key_deferred_flush(&clean_acked_data_enabled);
  130. }
  131. EXPORT_SYMBOL_GPL(clean_acked_data_flush);
  132. #endif
  133. #ifdef CONFIG_CGROUP_BPF
  134. static void bpf_skops_parse_hdr(struct sock *sk, struct sk_buff *skb)
  135. {
  136. bool unknown_opt = tcp_sk(sk)->rx_opt.saw_unknown &&
  137. BPF_SOCK_OPS_TEST_FLAG(tcp_sk(sk),
  138. BPF_SOCK_OPS_PARSE_UNKNOWN_HDR_OPT_CB_FLAG);
  139. bool parse_all_opt = BPF_SOCK_OPS_TEST_FLAG(tcp_sk(sk),
  140. BPF_SOCK_OPS_PARSE_ALL_HDR_OPT_CB_FLAG);
  141. struct bpf_sock_ops_kern sock_ops;
  142. if (likely(!unknown_opt && !parse_all_opt))
  143. return;
  144. /* The skb will be handled in the
  145. * bpf_skops_established() or
  146. * bpf_skops_write_hdr_opt().
  147. */
  148. switch (sk->sk_state) {
  149. case TCP_SYN_RECV:
  150. case TCP_SYN_SENT:
  151. case TCP_LISTEN:
  152. return;
  153. }
  154. sock_owned_by_me(sk);
  155. memset(&sock_ops, 0, offsetof(struct bpf_sock_ops_kern, temp));
  156. sock_ops.op = BPF_SOCK_OPS_PARSE_HDR_OPT_CB;
  157. sock_ops.is_fullsock = 1;
  158. sock_ops.is_locked_tcp_sock = 1;
  159. sock_ops.sk = sk;
  160. bpf_skops_init_skb(&sock_ops, skb, tcp_hdrlen(skb));
  161. BPF_CGROUP_RUN_PROG_SOCK_OPS(&sock_ops);
  162. }
  163. static void bpf_skops_established(struct sock *sk, int bpf_op,
  164. struct sk_buff *skb)
  165. {
  166. struct bpf_sock_ops_kern sock_ops;
  167. sock_owned_by_me(sk);
  168. memset(&sock_ops, 0, offsetof(struct bpf_sock_ops_kern, temp));
  169. sock_ops.op = bpf_op;
  170. sock_ops.is_fullsock = 1;
  171. sock_ops.is_locked_tcp_sock = 1;
  172. sock_ops.sk = sk;
  173. /* sk with TCP_REPAIR_ON does not have skb in tcp_finish_connect */
  174. if (skb)
  175. bpf_skops_init_skb(&sock_ops, skb, tcp_hdrlen(skb));
  176. BPF_CGROUP_RUN_PROG_SOCK_OPS(&sock_ops);
  177. }
  178. #else
  179. static void bpf_skops_parse_hdr(struct sock *sk, struct sk_buff *skb)
  180. {
  181. }
  182. static void bpf_skops_established(struct sock *sk, int bpf_op,
  183. struct sk_buff *skb)
  184. {
  185. }
  186. #endif
  187. static __cold void tcp_gro_dev_warn(const struct sock *sk, const struct sk_buff *skb,
  188. unsigned int len)
  189. {
  190. struct net_device *dev;
  191. rcu_read_lock();
  192. dev = dev_get_by_index_rcu(sock_net(sk), skb->skb_iif);
  193. if (!dev || len >= READ_ONCE(dev->mtu))
  194. pr_warn("%s: Driver has suspect GRO implementation, TCP performance may be compromised.\n",
  195. dev ? dev->name : "Unknown driver");
  196. rcu_read_unlock();
  197. }
  198. /* Adapt the MSS value used to make delayed ack decision to the
  199. * real world.
  200. */
  201. static void tcp_measure_rcv_mss(struct sock *sk, const struct sk_buff *skb)
  202. {
  203. struct inet_connection_sock *icsk = inet_csk(sk);
  204. const unsigned int lss = icsk->icsk_ack.last_seg_size;
  205. unsigned int len;
  206. icsk->icsk_ack.last_seg_size = 0;
  207. /* skb->len may jitter because of SACKs, even if peer
  208. * sends good full-sized frames.
  209. */
  210. len = skb_shinfo(skb)->gso_size ? : skb->len;
  211. if (len >= icsk->icsk_ack.rcv_mss) {
  212. /* Note: divides are still a bit expensive.
  213. * For the moment, only adjust scaling_ratio
  214. * when we update icsk_ack.rcv_mss.
  215. */
  216. if (unlikely(len != icsk->icsk_ack.rcv_mss)) {
  217. u64 val = (u64)skb->len << TCP_RMEM_TO_WIN_SCALE;
  218. u8 old_ratio = tcp_sk(sk)->scaling_ratio;
  219. do_div(val, skb->truesize);
  220. tcp_sk(sk)->scaling_ratio = val ? val : 1;
  221. if (old_ratio != tcp_sk(sk)->scaling_ratio) {
  222. struct tcp_sock *tp = tcp_sk(sk);
  223. val = tcp_win_from_space(sk, sk->sk_rcvbuf);
  224. tcp_set_window_clamp(sk, val);
  225. if (tp->window_clamp < tp->rcvq_space.space)
  226. tp->rcvq_space.space = tp->window_clamp;
  227. }
  228. }
  229. icsk->icsk_ack.rcv_mss = min_t(unsigned int, len,
  230. tcp_sk(sk)->advmss);
  231. /* Account for possibly-removed options */
  232. DO_ONCE_LITE_IF(len > icsk->icsk_ack.rcv_mss + MAX_TCP_OPTION_SPACE,
  233. tcp_gro_dev_warn, sk, skb, len);
  234. /* If the skb has a len of exactly 1*MSS and has the PSH bit
  235. * set then it is likely the end of an application write. So
  236. * more data may not be arriving soon, and yet the data sender
  237. * may be waiting for an ACK if cwnd-bound or using TX zero
  238. * copy. So we set ICSK_ACK_PUSHED here so that
  239. * tcp_cleanup_rbuf() will send an ACK immediately if the app
  240. * reads all of the data and is not ping-pong. If len > MSS
  241. * then this logic does not matter (and does not hurt) because
  242. * tcp_cleanup_rbuf() will always ACK immediately if the app
  243. * reads data and there is more than an MSS of unACKed data.
  244. */
  245. if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_PSH)
  246. icsk->icsk_ack.pending |= ICSK_ACK_PUSHED;
  247. } else {
  248. /* Otherwise, we make more careful check taking into account,
  249. * that SACKs block is variable.
  250. *
  251. * "len" is invariant segment length, including TCP header.
  252. */
  253. len += skb->data - skb_transport_header(skb);
  254. if (len >= TCP_MSS_DEFAULT + sizeof(struct tcphdr) ||
  255. /* If PSH is not set, packet should be
  256. * full sized, provided peer TCP is not badly broken.
  257. * This observation (if it is correct 8)) allows
  258. * to handle super-low mtu links fairly.
  259. */
  260. (len >= TCP_MIN_MSS + sizeof(struct tcphdr) &&
  261. !(tcp_flag_word(tcp_hdr(skb)) & TCP_REMNANT))) {
  262. /* Subtract also invariant (if peer is RFC compliant),
  263. * tcp header plus fixed timestamp option length.
  264. * Resulting "len" is MSS free of SACK jitter.
  265. */
  266. len -= tcp_sk(sk)->tcp_header_len;
  267. icsk->icsk_ack.last_seg_size = len;
  268. if (len == lss) {
  269. icsk->icsk_ack.rcv_mss = len;
  270. return;
  271. }
  272. }
  273. if (icsk->icsk_ack.pending & ICSK_ACK_PUSHED)
  274. icsk->icsk_ack.pending |= ICSK_ACK_PUSHED2;
  275. icsk->icsk_ack.pending |= ICSK_ACK_PUSHED;
  276. }
  277. }
  278. static void tcp_incr_quickack(struct sock *sk, unsigned int max_quickacks)
  279. {
  280. struct inet_connection_sock *icsk = inet_csk(sk);
  281. unsigned int quickacks = tcp_sk(sk)->rcv_wnd / (2 * icsk->icsk_ack.rcv_mss);
  282. if (quickacks == 0)
  283. quickacks = 2;
  284. quickacks = min(quickacks, max_quickacks);
  285. if (quickacks > icsk->icsk_ack.quick)
  286. icsk->icsk_ack.quick = quickacks;
  287. }
  288. static void tcp_enter_quickack_mode(struct sock *sk, unsigned int max_quickacks)
  289. {
  290. struct inet_connection_sock *icsk = inet_csk(sk);
  291. tcp_incr_quickack(sk, max_quickacks);
  292. inet_csk_exit_pingpong_mode(sk);
  293. icsk->icsk_ack.ato = TCP_ATO_MIN;
  294. }
  295. /* Send ACKs quickly, if "quick" count is not exhausted
  296. * and the session is not interactive.
  297. */
  298. static bool tcp_in_quickack_mode(struct sock *sk)
  299. {
  300. const struct inet_connection_sock *icsk = inet_csk(sk);
  301. return icsk->icsk_ack.dst_quick_ack ||
  302. (icsk->icsk_ack.quick && !inet_csk_in_pingpong_mode(sk));
  303. }
  304. static void tcp_data_ecn_check(struct sock *sk, const struct sk_buff *skb)
  305. {
  306. struct tcp_sock *tp = tcp_sk(sk);
  307. if (tcp_ecn_disabled(tp))
  308. return;
  309. switch (TCP_SKB_CB(skb)->ip_dsfield & INET_ECN_MASK) {
  310. case INET_ECN_NOT_ECT:
  311. /* Funny extension: if ECT is not set on a segment,
  312. * and we already seen ECT on a previous segment,
  313. * it is probably a retransmit.
  314. */
  315. if (tp->ecn_flags & TCP_ECN_SEEN)
  316. tcp_enter_quickack_mode(sk, 2);
  317. break;
  318. case INET_ECN_CE:
  319. if (tcp_ca_needs_ecn(sk))
  320. tcp_ca_event(sk, CA_EVENT_ECN_IS_CE);
  321. if (!(tp->ecn_flags & TCP_ECN_DEMAND_CWR) &&
  322. tcp_ecn_mode_rfc3168(tp)) {
  323. /* Better not delay acks, sender can have a very low cwnd */
  324. tcp_enter_quickack_mode(sk, 2);
  325. tp->ecn_flags |= TCP_ECN_DEMAND_CWR;
  326. }
  327. /* As for RFC3168 ECN, the TCP_ECN_SEEN flag is set by
  328. * tcp_data_ecn_check() when the ECN codepoint of
  329. * received TCP data contains ECT(0), ECT(1), or CE.
  330. */
  331. if (!tcp_ecn_mode_rfc3168(tp))
  332. break;
  333. tp->ecn_flags |= TCP_ECN_SEEN;
  334. break;
  335. default:
  336. if (tcp_ca_needs_ecn(sk))
  337. tcp_ca_event(sk, CA_EVENT_ECN_NO_CE);
  338. if (!tcp_ecn_mode_rfc3168(tp))
  339. break;
  340. tp->ecn_flags |= TCP_ECN_SEEN;
  341. break;
  342. }
  343. }
  344. /* Returns true if the byte counters can be used */
  345. static bool tcp_accecn_process_option(struct tcp_sock *tp,
  346. const struct sk_buff *skb,
  347. u32 delivered_bytes, int flag)
  348. {
  349. u8 estimate_ecnfield = tp->est_ecnfield;
  350. bool ambiguous_ecn_bytes_incr = false;
  351. bool first_changed = false;
  352. unsigned int optlen;
  353. bool order1, res;
  354. unsigned int i;
  355. u8 *ptr;
  356. if (tcp_accecn_opt_fail_recv(tp))
  357. return false;
  358. if (!(flag & FLAG_SLOWPATH) || !tp->rx_opt.accecn) {
  359. if (!tp->saw_accecn_opt) {
  360. /* Too late to enable after this point due to
  361. * potential counter wraps
  362. */
  363. if (tp->bytes_sent >= (1 << 23) - 1) {
  364. u8 saw_opt = TCP_ACCECN_OPT_FAIL_SEEN;
  365. tcp_accecn_saw_opt_fail_recv(tp, saw_opt);
  366. }
  367. return false;
  368. }
  369. if (estimate_ecnfield) {
  370. u8 ecnfield = estimate_ecnfield - 1;
  371. tp->delivered_ecn_bytes[ecnfield] += delivered_bytes;
  372. return true;
  373. }
  374. return false;
  375. }
  376. ptr = skb_transport_header(skb) + tp->rx_opt.accecn;
  377. optlen = ptr[1] - 2;
  378. if (WARN_ON_ONCE(ptr[0] != TCPOPT_ACCECN0 && ptr[0] != TCPOPT_ACCECN1))
  379. return false;
  380. order1 = (ptr[0] == TCPOPT_ACCECN1);
  381. ptr += 2;
  382. if (tp->saw_accecn_opt < TCP_ACCECN_OPT_COUNTER_SEEN) {
  383. tp->saw_accecn_opt = tcp_accecn_option_init(skb,
  384. tp->rx_opt.accecn);
  385. if (tp->saw_accecn_opt == TCP_ACCECN_OPT_FAIL_SEEN)
  386. tcp_accecn_fail_mode_set(tp, TCP_ACCECN_OPT_FAIL_RECV);
  387. }
  388. res = !!estimate_ecnfield;
  389. for (i = 0; i < 3; i++) {
  390. u32 init_offset;
  391. u8 ecnfield;
  392. s32 delta;
  393. u32 *cnt;
  394. if (optlen < TCPOLEN_ACCECN_PERFIELD)
  395. break;
  396. ecnfield = tcp_accecn_optfield_to_ecnfield(i, order1);
  397. init_offset = tcp_accecn_field_init_offset(ecnfield);
  398. cnt = &tp->delivered_ecn_bytes[ecnfield - 1];
  399. delta = tcp_update_ecn_bytes(cnt, ptr, init_offset);
  400. if (delta && delta < 0) {
  401. res = false;
  402. ambiguous_ecn_bytes_incr = true;
  403. }
  404. if (delta && ecnfield != estimate_ecnfield) {
  405. if (!first_changed) {
  406. tp->est_ecnfield = ecnfield;
  407. first_changed = true;
  408. } else {
  409. res = false;
  410. ambiguous_ecn_bytes_incr = true;
  411. }
  412. }
  413. optlen -= TCPOLEN_ACCECN_PERFIELD;
  414. ptr += TCPOLEN_ACCECN_PERFIELD;
  415. }
  416. if (ambiguous_ecn_bytes_incr)
  417. tp->est_ecnfield = 0;
  418. return res;
  419. }
  420. static void tcp_count_delivered_ce(struct tcp_sock *tp, u32 ecn_count)
  421. {
  422. tp->delivered_ce += ecn_count;
  423. }
  424. /* Updates the delivered and delivered_ce counts */
  425. static void tcp_count_delivered(struct tcp_sock *tp, u32 delivered,
  426. bool ece_ack)
  427. {
  428. tp->delivered += delivered;
  429. if (tcp_ecn_mode_rfc3168(tp) && ece_ack)
  430. tcp_count_delivered_ce(tp, delivered);
  431. }
  432. #define PKTS_ACKED_WEIGHT 6
  433. #define PKTS_ACKED_PREC 6
  434. #define ACK_COMP_THRESH 4
  435. /* Returns the ECN CE delta */
  436. static u32 __tcp_accecn_process(struct sock *sk, const struct sk_buff *skb,
  437. u32 delivered_pkts, u32 delivered_bytes,
  438. int flag)
  439. {
  440. u32 old_ceb = tcp_sk(sk)->delivered_ecn_bytes[INET_ECN_CE - 1];
  441. const struct tcphdr *th = tcp_hdr(skb);
  442. struct tcp_sock *tp = tcp_sk(sk);
  443. u32 delta, safe_delta, d_ceb;
  444. bool opt_deltas_valid;
  445. u32 corrected_ace;
  446. u32 ewma;
  447. /* Reordered ACK or uncertain due to lack of data to send and ts */
  448. if (!(flag & (FLAG_FORWARD_PROGRESS | FLAG_TS_PROGRESS)))
  449. return 0;
  450. opt_deltas_valid = tcp_accecn_process_option(tp, skb,
  451. delivered_bytes, flag);
  452. if (delivered_pkts) {
  453. if (!tp->pkts_acked_ewma) {
  454. ewma = delivered_pkts << PKTS_ACKED_PREC;
  455. } else {
  456. ewma = tp->pkts_acked_ewma;
  457. ewma = (((ewma << PKTS_ACKED_WEIGHT) - ewma) +
  458. (delivered_pkts << PKTS_ACKED_PREC)) >>
  459. PKTS_ACKED_WEIGHT;
  460. }
  461. tp->pkts_acked_ewma = min_t(u32, ewma, 0xFFFFU);
  462. }
  463. if (!(flag & FLAG_SLOWPATH)) {
  464. /* AccECN counter might overflow on large ACKs */
  465. if (delivered_pkts <= TCP_ACCECN_CEP_ACE_MASK)
  466. return 0;
  467. }
  468. /* ACE field is not available during handshake */
  469. if (flag & FLAG_SYN_ACKED)
  470. return 0;
  471. if (tp->received_ce_pending >= TCP_ACCECN_ACE_MAX_DELTA)
  472. inet_csk(sk)->icsk_ack.pending |= ICSK_ACK_NOW;
  473. corrected_ace = tcp_accecn_ace(th) - TCP_ACCECN_CEP_INIT_OFFSET;
  474. delta = (corrected_ace - tp->delivered_ce) & TCP_ACCECN_CEP_ACE_MASK;
  475. if (delivered_pkts <= TCP_ACCECN_CEP_ACE_MASK)
  476. return delta;
  477. safe_delta = delivered_pkts -
  478. ((delivered_pkts - delta) & TCP_ACCECN_CEP_ACE_MASK);
  479. if (opt_deltas_valid) {
  480. d_ceb = tp->delivered_ecn_bytes[INET_ECN_CE - 1] - old_ceb;
  481. if (!d_ceb)
  482. return delta;
  483. if ((delivered_pkts >= (TCP_ACCECN_CEP_ACE_MASK + 1) * 2) &&
  484. (tcp_is_sack(tp) ||
  485. ((1 << inet_csk(sk)->icsk_ca_state) &
  486. (TCPF_CA_Open | TCPF_CA_CWR)))) {
  487. u32 est_d_cep;
  488. if (delivered_bytes <= d_ceb)
  489. return safe_delta;
  490. est_d_cep = DIV_ROUND_UP_ULL((u64)d_ceb *
  491. delivered_pkts,
  492. delivered_bytes);
  493. return min(safe_delta,
  494. delta +
  495. (est_d_cep & ~TCP_ACCECN_CEP_ACE_MASK));
  496. }
  497. if (d_ceb > delta * tp->mss_cache)
  498. return safe_delta;
  499. if (d_ceb <
  500. safe_delta * tp->mss_cache >> TCP_ACCECN_SAFETY_SHIFT)
  501. return delta;
  502. } else if (tp->pkts_acked_ewma > (ACK_COMP_THRESH << PKTS_ACKED_PREC))
  503. return delta;
  504. return safe_delta;
  505. }
  506. static u32 tcp_accecn_process(struct sock *sk, const struct sk_buff *skb,
  507. u32 delivered_pkts, u32 delivered_bytes,
  508. int *flag)
  509. {
  510. struct tcp_sock *tp = tcp_sk(sk);
  511. u32 delta;
  512. delta = __tcp_accecn_process(sk, skb, delivered_pkts,
  513. delivered_bytes, *flag);
  514. if (delta > 0) {
  515. tcp_count_delivered_ce(tp, delta);
  516. *flag |= FLAG_ECE;
  517. /* Recalculate header predictor */
  518. if (tp->pred_flags)
  519. tcp_fast_path_on(tp);
  520. }
  521. return delta;
  522. }
  523. /* Buffer size and advertised window tuning.
  524. *
  525. * 1. Tuning sk->sk_sndbuf, when connection enters established state.
  526. */
  527. static void tcp_sndbuf_expand(struct sock *sk)
  528. {
  529. const struct tcp_sock *tp = tcp_sk(sk);
  530. const struct tcp_congestion_ops *ca_ops = inet_csk(sk)->icsk_ca_ops;
  531. int sndmem, per_mss;
  532. u32 nr_segs;
  533. /* Worst case is non GSO/TSO : each frame consumes one skb
  534. * and skb->head is kmalloced using power of two area of memory
  535. */
  536. per_mss = max_t(u32, tp->rx_opt.mss_clamp, tp->mss_cache) +
  537. MAX_TCP_HEADER +
  538. SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
  539. per_mss = roundup_pow_of_two(per_mss) +
  540. SKB_DATA_ALIGN(sizeof(struct sk_buff));
  541. nr_segs = max_t(u32, TCP_INIT_CWND, tcp_snd_cwnd(tp));
  542. nr_segs = max_t(u32, nr_segs, tp->reordering + 1);
  543. /* Fast Recovery (RFC 5681 3.2) :
  544. * Cubic needs 1.7 factor, rounded to 2 to include
  545. * extra cushion (application might react slowly to EPOLLOUT)
  546. */
  547. sndmem = ca_ops->sndbuf_expand ? ca_ops->sndbuf_expand(sk) : 2;
  548. sndmem *= nr_segs * per_mss;
  549. if (sk->sk_sndbuf < sndmem)
  550. WRITE_ONCE(sk->sk_sndbuf,
  551. min(sndmem, READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_wmem[2])));
  552. }
  553. /* 2. Tuning advertised window (window_clamp, rcv_ssthresh)
  554. *
  555. * All tcp_full_space() is split to two parts: "network" buffer, allocated
  556. * forward and advertised in receiver window (tp->rcv_wnd) and
  557. * "application buffer", required to isolate scheduling/application
  558. * latencies from network.
  559. * window_clamp is maximal advertised window. It can be less than
  560. * tcp_full_space(), in this case tcp_full_space() - window_clamp
  561. * is reserved for "application" buffer. The less window_clamp is
  562. * the smoother our behaviour from viewpoint of network, but the lower
  563. * throughput and the higher sensitivity of the connection to losses. 8)
  564. *
  565. * rcv_ssthresh is more strict window_clamp used at "slow start"
  566. * phase to predict further behaviour of this connection.
  567. * It is used for two goals:
  568. * - to enforce header prediction at sender, even when application
  569. * requires some significant "application buffer". It is check #1.
  570. * - to prevent pruning of receive queue because of misprediction
  571. * of receiver window. Check #2.
  572. *
  573. * The scheme does not work when sender sends good segments opening
  574. * window and then starts to feed us spaghetti. But it should work
  575. * in common situations. Otherwise, we have to rely on queue collapsing.
  576. */
  577. /* Slow part of check#2. */
  578. static int __tcp_grow_window(const struct sock *sk, const struct sk_buff *skb,
  579. unsigned int skbtruesize)
  580. {
  581. const struct tcp_sock *tp = tcp_sk(sk);
  582. /* Optimize this! */
  583. int truesize = tcp_win_from_space(sk, skbtruesize) >> 1;
  584. int window = tcp_win_from_space(sk, READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_rmem[2])) >> 1;
  585. while (tp->rcv_ssthresh <= window) {
  586. if (truesize <= skb->len)
  587. return 2 * inet_csk(sk)->icsk_ack.rcv_mss;
  588. truesize >>= 1;
  589. window >>= 1;
  590. }
  591. return 0;
  592. }
  593. /* Even if skb appears to have a bad len/truesize ratio, TCP coalescing
  594. * can play nice with us, as sk_buff and skb->head might be either
  595. * freed or shared with up to MAX_SKB_FRAGS segments.
  596. * Only give a boost to drivers using page frag(s) to hold the frame(s),
  597. * and if no payload was pulled in skb->head before reaching us.
  598. */
  599. static u32 truesize_adjust(bool adjust, const struct sk_buff *skb)
  600. {
  601. u32 truesize = skb->truesize;
  602. if (adjust && !skb_headlen(skb)) {
  603. truesize -= SKB_TRUESIZE(skb_end_offset(skb));
  604. /* paranoid check, some drivers might be buggy */
  605. if (unlikely((int)truesize < (int)skb->len))
  606. truesize = skb->truesize;
  607. }
  608. return truesize;
  609. }
  610. static void tcp_grow_window(struct sock *sk, const struct sk_buff *skb,
  611. bool adjust)
  612. {
  613. struct tcp_sock *tp = tcp_sk(sk);
  614. int room;
  615. room = min_t(int, tp->window_clamp, tcp_space(sk)) - tp->rcv_ssthresh;
  616. if (room <= 0)
  617. return;
  618. /* Check #1 */
  619. if (!tcp_under_memory_pressure(sk)) {
  620. unsigned int truesize = truesize_adjust(adjust, skb);
  621. int incr;
  622. /* Check #2. Increase window, if skb with such overhead
  623. * will fit to rcvbuf in future.
  624. */
  625. if (tcp_win_from_space(sk, truesize) <= skb->len)
  626. incr = 2 * tp->advmss;
  627. else
  628. incr = __tcp_grow_window(sk, skb, truesize);
  629. if (incr) {
  630. incr = max_t(int, incr, 2 * skb->len);
  631. tp->rcv_ssthresh += min(room, incr);
  632. inet_csk(sk)->icsk_ack.quick |= 1;
  633. }
  634. } else {
  635. /* Under pressure:
  636. * Adjust rcv_ssthresh according to reserved mem
  637. */
  638. tcp_adjust_rcv_ssthresh(sk);
  639. }
  640. }
  641. /* 3. Try to fixup all. It is made immediately after connection enters
  642. * established state.
  643. */
  644. static void tcp_init_buffer_space(struct sock *sk)
  645. {
  646. int tcp_app_win = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_app_win);
  647. struct tcp_sock *tp = tcp_sk(sk);
  648. int maxwin;
  649. if (!(sk->sk_userlocks & SOCK_SNDBUF_LOCK))
  650. tcp_sndbuf_expand(sk);
  651. tcp_mstamp_refresh(tp);
  652. tp->rcvq_space.time = tp->tcp_mstamp;
  653. tp->rcvq_space.seq = tp->copied_seq;
  654. maxwin = tcp_full_space(sk);
  655. if (tp->window_clamp >= maxwin) {
  656. WRITE_ONCE(tp->window_clamp, maxwin);
  657. if (tcp_app_win && maxwin > 4 * tp->advmss)
  658. WRITE_ONCE(tp->window_clamp,
  659. max(maxwin - (maxwin >> tcp_app_win),
  660. 4 * tp->advmss));
  661. }
  662. /* Force reservation of one segment. */
  663. if (tcp_app_win &&
  664. tp->window_clamp > 2 * tp->advmss &&
  665. tp->window_clamp + tp->advmss > maxwin)
  666. WRITE_ONCE(tp->window_clamp,
  667. max(2 * tp->advmss, maxwin - tp->advmss));
  668. tp->rcv_ssthresh = min(tp->rcv_ssthresh, tp->window_clamp);
  669. tp->snd_cwnd_stamp = tcp_jiffies32;
  670. tp->rcvq_space.space = min3(tp->rcv_ssthresh, tp->rcv_wnd,
  671. (u32)TCP_INIT_CWND * tp->advmss);
  672. }
  673. /* 4. Recalculate window clamp after socket hit its memory bounds. */
  674. static void tcp_clamp_window(struct sock *sk)
  675. {
  676. struct tcp_sock *tp = tcp_sk(sk);
  677. struct inet_connection_sock *icsk = inet_csk(sk);
  678. struct net *net = sock_net(sk);
  679. int rmem2;
  680. icsk->icsk_ack.quick = 0;
  681. rmem2 = READ_ONCE(net->ipv4.sysctl_tcp_rmem[2]);
  682. if (sk->sk_rcvbuf < rmem2 &&
  683. !(sk->sk_userlocks & SOCK_RCVBUF_LOCK) &&
  684. !tcp_under_memory_pressure(sk) &&
  685. sk_memory_allocated(sk) < sk_prot_mem_limits(sk, 0)) {
  686. WRITE_ONCE(sk->sk_rcvbuf,
  687. min(atomic_read(&sk->sk_rmem_alloc), rmem2));
  688. }
  689. if (atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf)
  690. tp->rcv_ssthresh = min(tp->window_clamp, 2U * tp->advmss);
  691. }
  692. /* Initialize RCV_MSS value.
  693. * RCV_MSS is an our guess about MSS used by the peer.
  694. * We haven't any direct information about the MSS.
  695. * It's better to underestimate the RCV_MSS rather than overestimate.
  696. * Overestimations make us ACKing less frequently than needed.
  697. * Underestimations are more easy to detect and fix by tcp_measure_rcv_mss().
  698. */
  699. void tcp_initialize_rcv_mss(struct sock *sk)
  700. {
  701. const struct tcp_sock *tp = tcp_sk(sk);
  702. unsigned int hint = min_t(unsigned int, tp->advmss, tp->mss_cache);
  703. hint = min(hint, tp->rcv_wnd / 2);
  704. hint = min(hint, TCP_MSS_DEFAULT);
  705. hint = max(hint, TCP_MIN_MSS);
  706. inet_csk(sk)->icsk_ack.rcv_mss = hint;
  707. }
  708. EXPORT_IPV6_MOD(tcp_initialize_rcv_mss);
  709. /* Receiver "autotuning" code.
  710. *
  711. * The algorithm for RTT estimation w/o timestamps is based on
  712. * Dynamic Right-Sizing (DRS) by Wu Feng and Mike Fisk of LANL.
  713. * <https://public.lanl.gov/radiant/pubs.html#DRS>
  714. *
  715. * More detail on this code can be found at
  716. * <http://staff.psc.edu/jheffner/>,
  717. * though this reference is out of date. A new paper
  718. * is pending.
  719. */
  720. static void tcp_rcv_rtt_update(struct tcp_sock *tp, u32 sample, int win_dep)
  721. {
  722. u32 new_sample, old_sample = tp->rcv_rtt_est.rtt_us;
  723. long m = sample << 3;
  724. if (old_sample == 0 || m < old_sample) {
  725. new_sample = m;
  726. } else {
  727. /* If we sample in larger samples in the non-timestamp
  728. * case, we could grossly overestimate the RTT especially
  729. * with chatty applications or bulk transfer apps which
  730. * are stalled on filesystem I/O.
  731. *
  732. * Also, since we are only going for a minimum in the
  733. * non-timestamp case, we do not smooth things out
  734. * else with timestamps disabled convergence takes too
  735. * long.
  736. */
  737. if (win_dep)
  738. return;
  739. /* Do not use this sample if receive queue is not empty. */
  740. if (tp->rcv_nxt != tp->copied_seq)
  741. return;
  742. new_sample = old_sample - (old_sample >> 3) + sample;
  743. }
  744. tp->rcv_rtt_est.rtt_us = new_sample;
  745. }
  746. static inline void tcp_rcv_rtt_measure(struct tcp_sock *tp)
  747. {
  748. u32 delta_us;
  749. if (tp->rcv_rtt_est.time == 0)
  750. goto new_measure;
  751. if (before(tp->rcv_nxt, tp->rcv_rtt_est.seq))
  752. return;
  753. delta_us = tcp_stamp_us_delta(tp->tcp_mstamp, tp->rcv_rtt_est.time);
  754. if (!delta_us)
  755. delta_us = 1;
  756. tcp_rcv_rtt_update(tp, delta_us, 1);
  757. new_measure:
  758. tp->rcv_rtt_est.seq = tp->rcv_nxt + tp->rcv_wnd;
  759. tp->rcv_rtt_est.time = tp->tcp_mstamp;
  760. }
  761. static s32 tcp_rtt_tsopt_us(const struct tcp_sock *tp, u32 min_delta)
  762. {
  763. u32 delta, delta_us;
  764. delta = tcp_time_stamp_ts(tp) - tp->rx_opt.rcv_tsecr;
  765. if (tp->tcp_usec_ts)
  766. return delta;
  767. if (likely(delta < INT_MAX / (USEC_PER_SEC / TCP_TS_HZ))) {
  768. if (!delta)
  769. delta = min_delta;
  770. delta_us = delta * (USEC_PER_SEC / TCP_TS_HZ);
  771. return delta_us;
  772. }
  773. return -1;
  774. }
  775. static inline void tcp_rcv_rtt_measure_ts(struct sock *sk,
  776. const struct sk_buff *skb)
  777. {
  778. struct tcp_sock *tp = tcp_sk(sk);
  779. if (tp->rx_opt.rcv_tsecr == tp->rcv_rtt_last_tsecr)
  780. return;
  781. tp->rcv_rtt_last_tsecr = tp->rx_opt.rcv_tsecr;
  782. if (TCP_SKB_CB(skb)->end_seq -
  783. TCP_SKB_CB(skb)->seq >= inet_csk(sk)->icsk_ack.rcv_mss) {
  784. s32 delta = tcp_rtt_tsopt_us(tp, 0);
  785. if (delta > 0)
  786. tcp_rcv_rtt_update(tp, delta, 0);
  787. }
  788. }
  789. void tcp_rcvbuf_grow(struct sock *sk, u32 newval)
  790. {
  791. const struct net *net = sock_net(sk);
  792. struct tcp_sock *tp = tcp_sk(sk);
  793. u32 rcvwin, rcvbuf, cap, oldval;
  794. u32 rtt_threshold, rtt_us;
  795. u64 grow;
  796. oldval = tp->rcvq_space.space;
  797. tp->rcvq_space.space = newval;
  798. if (!READ_ONCE(net->ipv4.sysctl_tcp_moderate_rcvbuf) ||
  799. (sk->sk_userlocks & SOCK_RCVBUF_LOCK))
  800. return;
  801. /* DRS is always one RTT late. */
  802. rcvwin = newval << 1;
  803. rtt_us = tp->rcv_rtt_est.rtt_us >> 3;
  804. rtt_threshold = READ_ONCE(net->ipv4.sysctl_tcp_rcvbuf_low_rtt);
  805. if (rtt_us < rtt_threshold) {
  806. /* For small RTT, we set @grow to rcvwin * rtt_us/rtt_threshold.
  807. * It might take few additional ms to reach 'line rate',
  808. * but will avoid sk_rcvbuf inflation and poor cache use.
  809. */
  810. grow = div_u64((u64)rcvwin * rtt_us, rtt_threshold);
  811. } else {
  812. /* slow start: allow the sender to double its rate. */
  813. grow = div_u64(((u64)rcvwin << 1) * (newval - oldval), oldval);
  814. }
  815. rcvwin += grow;
  816. if (!RB_EMPTY_ROOT(&tp->out_of_order_queue))
  817. rcvwin += TCP_SKB_CB(tp->ooo_last_skb)->end_seq - tp->rcv_nxt;
  818. cap = READ_ONCE(net->ipv4.sysctl_tcp_rmem[2]);
  819. rcvbuf = min_t(u32, tcp_space_from_win(sk, rcvwin), cap);
  820. if (rcvbuf > sk->sk_rcvbuf) {
  821. WRITE_ONCE(sk->sk_rcvbuf, rcvbuf);
  822. /* Make the window clamp follow along. */
  823. WRITE_ONCE(tp->window_clamp,
  824. tcp_win_from_space(sk, rcvbuf));
  825. }
  826. }
  827. /*
  828. * This function should be called every time data is copied to user space.
  829. * It calculates the appropriate TCP receive buffer space.
  830. */
  831. void tcp_rcv_space_adjust(struct sock *sk)
  832. {
  833. struct tcp_sock *tp = tcp_sk(sk);
  834. int time, inq, copied;
  835. trace_tcp_rcv_space_adjust(sk);
  836. if (unlikely(!tp->rcv_rtt_est.rtt_us))
  837. return;
  838. /* We do not refresh tp->tcp_mstamp here.
  839. * Some platforms have expensive ktime_get() implementations.
  840. * Using the last cached value is enough for DRS.
  841. */
  842. time = tcp_stamp_us_delta(tp->tcp_mstamp, tp->rcvq_space.time);
  843. if (time < (tp->rcv_rtt_est.rtt_us >> 3))
  844. return;
  845. /* Number of bytes copied to user in last RTT */
  846. copied = tp->copied_seq - tp->rcvq_space.seq;
  847. /* Number of bytes in receive queue. */
  848. inq = tp->rcv_nxt - tp->copied_seq;
  849. copied -= inq;
  850. if (copied <= tp->rcvq_space.space)
  851. goto new_measure;
  852. trace_tcp_rcvbuf_grow(sk, time);
  853. tcp_rcvbuf_grow(sk, copied);
  854. new_measure:
  855. tp->rcvq_space.seq = tp->copied_seq;
  856. tp->rcvq_space.time = tp->tcp_mstamp;
  857. }
  858. static void tcp_save_lrcv_flowlabel(struct sock *sk, const struct sk_buff *skb)
  859. {
  860. #if IS_ENABLED(CONFIG_IPV6)
  861. struct inet_connection_sock *icsk = inet_csk(sk);
  862. if (skb->protocol == htons(ETH_P_IPV6))
  863. icsk->icsk_ack.lrcv_flowlabel = ntohl(ip6_flowlabel(ipv6_hdr(skb)));
  864. #endif
  865. }
  866. /* There is something which you must keep in mind when you analyze the
  867. * behavior of the tp->ato delayed ack timeout interval. When a
  868. * connection starts up, we want to ack as quickly as possible. The
  869. * problem is that "good" TCP's do slow start at the beginning of data
  870. * transmission. The means that until we send the first few ACK's the
  871. * sender will sit on his end and only queue most of his data, because
  872. * he can only send snd_cwnd unacked packets at any given time. For
  873. * each ACK we send, he increments snd_cwnd and transmits more of his
  874. * queue. -DaveM
  875. */
  876. static void tcp_event_data_recv(struct sock *sk, struct sk_buff *skb)
  877. {
  878. struct tcp_sock *tp = tcp_sk(sk);
  879. struct inet_connection_sock *icsk = inet_csk(sk);
  880. u32 now;
  881. inet_csk_schedule_ack(sk);
  882. tcp_measure_rcv_mss(sk, skb);
  883. tcp_rcv_rtt_measure(tp);
  884. now = tcp_jiffies32;
  885. if (!icsk->icsk_ack.ato) {
  886. /* The _first_ data packet received, initialize
  887. * delayed ACK engine.
  888. */
  889. tcp_incr_quickack(sk, TCP_MAX_QUICKACKS);
  890. icsk->icsk_ack.ato = TCP_ATO_MIN;
  891. } else {
  892. int m = now - icsk->icsk_ack.lrcvtime;
  893. if (m <= TCP_ATO_MIN / 2) {
  894. /* The fastest case is the first. */
  895. icsk->icsk_ack.ato = (icsk->icsk_ack.ato >> 1) + TCP_ATO_MIN / 2;
  896. } else if (m < icsk->icsk_ack.ato) {
  897. icsk->icsk_ack.ato = (icsk->icsk_ack.ato >> 1) + m;
  898. if (icsk->icsk_ack.ato > icsk->icsk_rto)
  899. icsk->icsk_ack.ato = icsk->icsk_rto;
  900. } else if (m > icsk->icsk_rto) {
  901. /* Too long gap. Apparently sender failed to
  902. * restart window, so that we send ACKs quickly.
  903. */
  904. tcp_incr_quickack(sk, TCP_MAX_QUICKACKS);
  905. }
  906. }
  907. icsk->icsk_ack.lrcvtime = now;
  908. tcp_save_lrcv_flowlabel(sk, skb);
  909. tcp_data_ecn_check(sk, skb);
  910. if (skb->len >= 128)
  911. tcp_grow_window(sk, skb, true);
  912. }
  913. /* Called to compute a smoothed rtt estimate. The data fed to this
  914. * routine either comes from timestamps, or from segments that were
  915. * known _not_ to have been retransmitted [see Karn/Partridge
  916. * Proceedings SIGCOMM 87]. The algorithm is from the SIGCOMM 88
  917. * piece by Van Jacobson.
  918. * NOTE: the next three routines used to be one big routine.
  919. * To save cycles in the RFC 1323 implementation it was better to break
  920. * it up into three procedures. -- erics
  921. */
  922. static void tcp_rtt_estimator(struct sock *sk, long mrtt_us)
  923. {
  924. struct tcp_sock *tp = tcp_sk(sk);
  925. long m = mrtt_us; /* RTT */
  926. u32 srtt = tp->srtt_us;
  927. /* The following amusing code comes from Jacobson's
  928. * article in SIGCOMM '88. Note that rtt and mdev
  929. * are scaled versions of rtt and mean deviation.
  930. * This is designed to be as fast as possible
  931. * m stands for "measurement".
  932. *
  933. * On a 1990 paper the rto value is changed to:
  934. * RTO = rtt + 4 * mdev
  935. *
  936. * Funny. This algorithm seems to be very broken.
  937. * These formulae increase RTO, when it should be decreased, increase
  938. * too slowly, when it should be increased quickly, decrease too quickly
  939. * etc. I guess in BSD RTO takes ONE value, so that it is absolutely
  940. * does not matter how to _calculate_ it. Seems, it was trap
  941. * that VJ failed to avoid. 8)
  942. */
  943. if (srtt != 0) {
  944. m -= (srtt >> 3); /* m is now error in rtt est */
  945. srtt += m; /* rtt = 7/8 rtt + 1/8 new */
  946. if (m < 0) {
  947. m = -m; /* m is now abs(error) */
  948. m -= (tp->mdev_us >> 2); /* similar update on mdev */
  949. /* This is similar to one of Eifel findings.
  950. * Eifel blocks mdev updates when rtt decreases.
  951. * This solution is a bit different: we use finer gain
  952. * for mdev in this case (alpha*beta).
  953. * Like Eifel it also prevents growth of rto,
  954. * but also it limits too fast rto decreases,
  955. * happening in pure Eifel.
  956. */
  957. if (m > 0)
  958. m >>= 3;
  959. } else {
  960. m -= (tp->mdev_us >> 2); /* similar update on mdev */
  961. }
  962. tp->mdev_us += m; /* mdev = 3/4 mdev + 1/4 new */
  963. if (tp->mdev_us > tp->mdev_max_us) {
  964. tp->mdev_max_us = tp->mdev_us;
  965. if (tp->mdev_max_us > tp->rttvar_us)
  966. tp->rttvar_us = tp->mdev_max_us;
  967. }
  968. if (after(tp->snd_una, tp->rtt_seq)) {
  969. if (tp->mdev_max_us < tp->rttvar_us)
  970. tp->rttvar_us -= (tp->rttvar_us - tp->mdev_max_us) >> 2;
  971. tp->rtt_seq = tp->snd_nxt;
  972. tp->mdev_max_us = tcp_rto_min_us(sk);
  973. tcp_bpf_rtt(sk, mrtt_us, srtt);
  974. }
  975. } else {
  976. /* no previous measure. */
  977. srtt = m << 3; /* take the measured time to be rtt */
  978. tp->mdev_us = m << 1; /* make sure rto = 3*rtt */
  979. tp->rttvar_us = max(tp->mdev_us, tcp_rto_min_us(sk));
  980. tp->mdev_max_us = tp->rttvar_us;
  981. tp->rtt_seq = tp->snd_nxt;
  982. tcp_bpf_rtt(sk, mrtt_us, srtt);
  983. }
  984. tp->srtt_us = max(1U, srtt);
  985. }
  986. void tcp_update_pacing_rate(struct sock *sk)
  987. {
  988. const struct tcp_sock *tp = tcp_sk(sk);
  989. u64 rate;
  990. /* set sk_pacing_rate to 200 % of current rate (mss * cwnd / srtt) */
  991. rate = (u64)tp->mss_cache * ((USEC_PER_SEC / 100) << 3);
  992. /* current rate is (cwnd * mss) / srtt
  993. * In Slow Start [1], set sk_pacing_rate to 200 % the current rate.
  994. * In Congestion Avoidance phase, set it to 120 % the current rate.
  995. *
  996. * [1] : Normal Slow Start condition is (tp->snd_cwnd < tp->snd_ssthresh)
  997. * If snd_cwnd >= (tp->snd_ssthresh / 2), we are approaching
  998. * end of slow start and should slow down.
  999. */
  1000. if (tcp_snd_cwnd(tp) < tp->snd_ssthresh / 2)
  1001. rate *= READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_pacing_ss_ratio);
  1002. else
  1003. rate *= READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_pacing_ca_ratio);
  1004. rate *= max(tcp_snd_cwnd(tp), tp->packets_out);
  1005. if (likely(tp->srtt_us))
  1006. do_div(rate, tp->srtt_us);
  1007. /* WRITE_ONCE() is needed because sch_fq fetches sk_pacing_rate
  1008. * without any lock. We want to make sure compiler wont store
  1009. * intermediate values in this location.
  1010. */
  1011. WRITE_ONCE(sk->sk_pacing_rate,
  1012. min_t(u64, rate, READ_ONCE(sk->sk_max_pacing_rate)));
  1013. }
  1014. /* Calculate rto without backoff. This is the second half of Van Jacobson's
  1015. * routine referred to above.
  1016. */
  1017. void tcp_set_rto(struct sock *sk)
  1018. {
  1019. const struct tcp_sock *tp = tcp_sk(sk);
  1020. /* Old crap is replaced with new one. 8)
  1021. *
  1022. * More seriously:
  1023. * 1. If rtt variance happened to be less 50msec, it is hallucination.
  1024. * It cannot be less due to utterly erratic ACK generation made
  1025. * at least by solaris and freebsd. "Erratic ACKs" has _nothing_
  1026. * to do with delayed acks, because at cwnd>2 true delack timeout
  1027. * is invisible. Actually, Linux-2.4 also generates erratic
  1028. * ACKs in some circumstances.
  1029. */
  1030. inet_csk(sk)->icsk_rto = __tcp_set_rto(tp);
  1031. /* 2. Fixups made earlier cannot be right.
  1032. * If we do not estimate RTO correctly without them,
  1033. * all the algo is pure shit and should be replaced
  1034. * with correct one. It is exactly, which we pretend to do.
  1035. */
  1036. /* NOTE: clamping at TCP_RTO_MIN is not required, current algo
  1037. * guarantees that rto is higher.
  1038. */
  1039. tcp_bound_rto(sk);
  1040. }
  1041. __u32 tcp_init_cwnd(const struct tcp_sock *tp, const struct dst_entry *dst)
  1042. {
  1043. __u32 cwnd = (dst ? dst_metric(dst, RTAX_INITCWND) : 0);
  1044. if (!cwnd)
  1045. cwnd = TCP_INIT_CWND;
  1046. return min_t(__u32, cwnd, tp->snd_cwnd_clamp);
  1047. }
  1048. struct tcp_sacktag_state {
  1049. /* Timestamps for earliest and latest never-retransmitted segment
  1050. * that was SACKed. RTO needs the earliest RTT to stay conservative,
  1051. * but congestion control should still get an accurate delay signal.
  1052. */
  1053. u64 first_sackt;
  1054. u64 last_sackt;
  1055. u32 reord;
  1056. u32 sack_delivered;
  1057. u32 delivered_bytes;
  1058. int flag;
  1059. unsigned int mss_now;
  1060. struct rate_sample *rate;
  1061. };
  1062. /* Take a notice that peer is sending D-SACKs. Skip update of data delivery
  1063. * and spurious retransmission information if this DSACK is unlikely caused by
  1064. * sender's action:
  1065. * - DSACKed sequence range is larger than maximum receiver's window.
  1066. * - Total no. of DSACKed segments exceed the total no. of retransmitted segs.
  1067. */
  1068. static u32 tcp_dsack_seen(struct tcp_sock *tp, u32 start_seq,
  1069. u32 end_seq, struct tcp_sacktag_state *state)
  1070. {
  1071. u32 seq_len, dup_segs = 1;
  1072. if (!before(start_seq, end_seq))
  1073. return 0;
  1074. seq_len = end_seq - start_seq;
  1075. /* Dubious DSACK: DSACKed range greater than maximum advertised rwnd */
  1076. if (seq_len > tp->max_window)
  1077. return 0;
  1078. if (seq_len > tp->mss_cache)
  1079. dup_segs = DIV_ROUND_UP(seq_len, tp->mss_cache);
  1080. else if (tp->tlp_high_seq && tp->tlp_high_seq == end_seq)
  1081. state->flag |= FLAG_DSACK_TLP;
  1082. tp->dsack_dups += dup_segs;
  1083. /* Skip the DSACK if dup segs weren't retransmitted by sender */
  1084. if (tp->dsack_dups > tp->total_retrans)
  1085. return 0;
  1086. tp->rx_opt.sack_ok |= TCP_DSACK_SEEN;
  1087. /* We increase the RACK ordering window in rounds where we receive
  1088. * DSACKs that may have been due to reordering causing RACK to trigger
  1089. * a spurious fast recovery. Thus RACK ignores DSACKs that happen
  1090. * without having seen reordering, or that match TLP probes (TLP
  1091. * is timer-driven, not triggered by RACK).
  1092. */
  1093. if (tp->reord_seen && !(state->flag & FLAG_DSACK_TLP))
  1094. tp->rack.dsack_seen = 1;
  1095. state->flag |= FLAG_DSACKING_ACK;
  1096. /* A spurious retransmission is delivered */
  1097. state->sack_delivered += dup_segs;
  1098. return dup_segs;
  1099. }
  1100. /* It's reordering when higher sequence was delivered (i.e. sacked) before
  1101. * some lower never-retransmitted sequence ("low_seq"). The maximum reordering
  1102. * distance is approximated in full-mss packet distance ("reordering").
  1103. */
  1104. static void tcp_check_sack_reordering(struct sock *sk, const u32 low_seq,
  1105. const int ts)
  1106. {
  1107. struct tcp_sock *tp = tcp_sk(sk);
  1108. const u32 mss = tp->mss_cache;
  1109. u32 fack, metric;
  1110. fack = tcp_highest_sack_seq(tp);
  1111. if (!before(low_seq, fack))
  1112. return;
  1113. metric = fack - low_seq;
  1114. if ((metric > tp->reordering * mss) && mss) {
  1115. #if FASTRETRANS_DEBUG > 1
  1116. pr_debug("Disorder%d %d %u f%u s%u rr%d\n",
  1117. tp->rx_opt.sack_ok, inet_csk(sk)->icsk_ca_state,
  1118. tp->reordering,
  1119. 0,
  1120. tp->sacked_out,
  1121. tp->undo_marker ? tp->undo_retrans : 0);
  1122. #endif
  1123. tp->reordering = min_t(u32, (metric + mss - 1) / mss,
  1124. READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_max_reordering));
  1125. }
  1126. /* This exciting event is worth to be remembered. 8) */
  1127. tp->reord_seen++;
  1128. NET_INC_STATS(sock_net(sk),
  1129. ts ? LINUX_MIB_TCPTSREORDER : LINUX_MIB_TCPSACKREORDER);
  1130. }
  1131. /* This must be called before lost_out or retrans_out are updated
  1132. * on a new loss, because we want to know if all skbs previously
  1133. * known to be lost have already been retransmitted, indicating
  1134. * that this newly lost skb is our next skb to retransmit.
  1135. */
  1136. static void tcp_verify_retransmit_hint(struct tcp_sock *tp, struct sk_buff *skb)
  1137. {
  1138. if ((!tp->retransmit_skb_hint && tp->retrans_out >= tp->lost_out) ||
  1139. (tp->retransmit_skb_hint &&
  1140. before(TCP_SKB_CB(skb)->seq,
  1141. TCP_SKB_CB(tp->retransmit_skb_hint)->seq)))
  1142. tp->retransmit_skb_hint = skb;
  1143. }
  1144. /* Sum the number of packets on the wire we have marked as lost, and
  1145. * notify the congestion control module that the given skb was marked lost.
  1146. */
  1147. static void tcp_notify_skb_loss_event(struct tcp_sock *tp, const struct sk_buff *skb)
  1148. {
  1149. tp->lost += tcp_skb_pcount(skb);
  1150. }
  1151. void tcp_mark_skb_lost(struct sock *sk, struct sk_buff *skb)
  1152. {
  1153. __u8 sacked = TCP_SKB_CB(skb)->sacked;
  1154. struct tcp_sock *tp = tcp_sk(sk);
  1155. if (sacked & TCPCB_SACKED_ACKED)
  1156. return;
  1157. tcp_verify_retransmit_hint(tp, skb);
  1158. if (sacked & TCPCB_LOST) {
  1159. if (sacked & TCPCB_SACKED_RETRANS) {
  1160. /* Account for retransmits that are lost again */
  1161. TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_RETRANS;
  1162. tp->retrans_out -= tcp_skb_pcount(skb);
  1163. NET_ADD_STATS(sock_net(sk), LINUX_MIB_TCPLOSTRETRANSMIT,
  1164. tcp_skb_pcount(skb));
  1165. tcp_notify_skb_loss_event(tp, skb);
  1166. }
  1167. } else {
  1168. tp->lost_out += tcp_skb_pcount(skb);
  1169. TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
  1170. tcp_notify_skb_loss_event(tp, skb);
  1171. }
  1172. }
  1173. /* This procedure tags the retransmission queue when SACKs arrive.
  1174. *
  1175. * We have three tag bits: SACKED(S), RETRANS(R) and LOST(L).
  1176. * Packets in queue with these bits set are counted in variables
  1177. * sacked_out, retrans_out and lost_out, correspondingly.
  1178. *
  1179. * Valid combinations are:
  1180. * Tag InFlight Description
  1181. * 0 1 - orig segment is in flight.
  1182. * S 0 - nothing flies, orig reached receiver.
  1183. * L 0 - nothing flies, orig lost by net.
  1184. * R 2 - both orig and retransmit are in flight.
  1185. * L|R 1 - orig is lost, retransmit is in flight.
  1186. * S|R 1 - orig reached receiver, retrans is still in flight.
  1187. * (L|S|R is logically valid, it could occur when L|R is sacked,
  1188. * but it is equivalent to plain S and code short-circuits it to S.
  1189. * L|S is logically invalid, it would mean -1 packet in flight 8))
  1190. *
  1191. * These 6 states form finite state machine, controlled by the following events:
  1192. * 1. New ACK (+SACK) arrives. (tcp_sacktag_write_queue())
  1193. * 2. Retransmission. (tcp_retransmit_skb(), tcp_xmit_retransmit_queue())
  1194. * 3. Loss detection event of two flavors:
  1195. * A. Scoreboard estimator decided the packet is lost.
  1196. * A'. Reno "three dupacks" marks head of queue lost.
  1197. * B. SACK arrives sacking SND.NXT at the moment, when the
  1198. * segment was retransmitted.
  1199. * 4. D-SACK added new rule: D-SACK changes any tag to S.
  1200. *
  1201. * It is pleasant to note, that state diagram turns out to be commutative,
  1202. * so that we are allowed not to be bothered by order of our actions,
  1203. * when multiple events arrive simultaneously. (see the function below).
  1204. *
  1205. * Reordering detection.
  1206. * --------------------
  1207. * Reordering metric is maximal distance, which a packet can be displaced
  1208. * in packet stream. With SACKs we can estimate it:
  1209. *
  1210. * 1. SACK fills old hole and the corresponding segment was not
  1211. * ever retransmitted -> reordering. Alas, we cannot use it
  1212. * when segment was retransmitted.
  1213. * 2. The last flaw is solved with D-SACK. D-SACK arrives
  1214. * for retransmitted and already SACKed segment -> reordering..
  1215. * Both of these heuristics are not used in Loss state, when we cannot
  1216. * account for retransmits accurately.
  1217. *
  1218. * SACK block validation.
  1219. * ----------------------
  1220. *
  1221. * SACK block range validation checks that the received SACK block fits to
  1222. * the expected sequence limits, i.e., it is between SND.UNA and SND.NXT.
  1223. * Note that SND.UNA is not included to the range though being valid because
  1224. * it means that the receiver is rather inconsistent with itself reporting
  1225. * SACK reneging when it should advance SND.UNA. Such SACK block this is
  1226. * perfectly valid, however, in light of RFC2018 which explicitly states
  1227. * that "SACK block MUST reflect the newest segment. Even if the newest
  1228. * segment is going to be discarded ...", not that it looks very clever
  1229. * in case of head skb. Due to potentional receiver driven attacks, we
  1230. * choose to avoid immediate execution of a walk in write queue due to
  1231. * reneging and defer head skb's loss recovery to standard loss recovery
  1232. * procedure that will eventually trigger (nothing forbids us doing this).
  1233. *
  1234. * Implements also blockage to start_seq wrap-around. Problem lies in the
  1235. * fact that though start_seq (s) is before end_seq (i.e., not reversed),
  1236. * there's no guarantee that it will be before snd_nxt (n). The problem
  1237. * happens when start_seq resides between end_seq wrap (e_w) and snd_nxt
  1238. * wrap (s_w):
  1239. *
  1240. * <- outs wnd -> <- wrapzone ->
  1241. * u e n u_w e_w s n_w
  1242. * | | | | | | |
  1243. * |<------------+------+----- TCP seqno space --------------+---------->|
  1244. * ...-- <2^31 ->| |<--------...
  1245. * ...---- >2^31 ------>| |<--------...
  1246. *
  1247. * Current code wouldn't be vulnerable but it's better still to discard such
  1248. * crazy SACK blocks. Doing this check for start_seq alone closes somewhat
  1249. * similar case (end_seq after snd_nxt wrap) as earlier reversed check in
  1250. * snd_nxt wrap -> snd_una region will then become "well defined", i.e.,
  1251. * equal to the ideal case (infinite seqno space without wrap caused issues).
  1252. *
  1253. * With D-SACK the lower bound is extended to cover sequence space below
  1254. * SND.UNA down to undo_marker, which is the last point of interest. Yet
  1255. * again, D-SACK block must not to go across snd_una (for the same reason as
  1256. * for the normal SACK blocks, explained above). But there all simplicity
  1257. * ends, TCP might receive valid D-SACKs below that. As long as they reside
  1258. * fully below undo_marker they do not affect behavior in anyway and can
  1259. * therefore be safely ignored. In rare cases (which are more or less
  1260. * theoretical ones), the D-SACK will nicely cross that boundary due to skb
  1261. * fragmentation and packet reordering past skb's retransmission. To consider
  1262. * them correctly, the acceptable range must be extended even more though
  1263. * the exact amount is rather hard to quantify. However, tp->max_window can
  1264. * be used as an exaggerated estimate.
  1265. */
  1266. static bool tcp_is_sackblock_valid(struct tcp_sock *tp, bool is_dsack,
  1267. u32 start_seq, u32 end_seq)
  1268. {
  1269. /* Too far in future, or reversed (interpretation is ambiguous) */
  1270. if (after(end_seq, tp->snd_nxt) || !before(start_seq, end_seq))
  1271. return false;
  1272. /* Nasty start_seq wrap-around check (see comments above) */
  1273. if (!before(start_seq, tp->snd_nxt))
  1274. return false;
  1275. /* In outstanding window? ...This is valid exit for D-SACKs too.
  1276. * start_seq == snd_una is non-sensical (see comments above)
  1277. */
  1278. if (after(start_seq, tp->snd_una))
  1279. return true;
  1280. if (!is_dsack || !tp->undo_marker)
  1281. return false;
  1282. /* ...Then it's D-SACK, and must reside below snd_una completely */
  1283. if (after(end_seq, tp->snd_una))
  1284. return false;
  1285. if (!before(start_seq, tp->undo_marker))
  1286. return true;
  1287. /* Too old */
  1288. if (!after(end_seq, tp->undo_marker))
  1289. return false;
  1290. /* Undo_marker boundary crossing (overestimates a lot). Known already:
  1291. * start_seq < undo_marker and end_seq >= undo_marker.
  1292. */
  1293. return !before(start_seq, end_seq - tp->max_window);
  1294. }
  1295. static bool tcp_check_dsack(struct sock *sk, const struct sk_buff *ack_skb,
  1296. struct tcp_sack_block_wire *sp, int num_sacks,
  1297. u32 prior_snd_una, struct tcp_sacktag_state *state)
  1298. {
  1299. struct tcp_sock *tp = tcp_sk(sk);
  1300. u32 start_seq_0 = get_unaligned_be32(&sp[0].start_seq);
  1301. u32 end_seq_0 = get_unaligned_be32(&sp[0].end_seq);
  1302. u32 dup_segs;
  1303. if (before(start_seq_0, TCP_SKB_CB(ack_skb)->ack_seq)) {
  1304. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPDSACKRECV);
  1305. } else if (num_sacks > 1) {
  1306. u32 end_seq_1 = get_unaligned_be32(&sp[1].end_seq);
  1307. u32 start_seq_1 = get_unaligned_be32(&sp[1].start_seq);
  1308. if (after(end_seq_0, end_seq_1) || before(start_seq_0, start_seq_1))
  1309. return false;
  1310. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPDSACKOFORECV);
  1311. } else {
  1312. return false;
  1313. }
  1314. dup_segs = tcp_dsack_seen(tp, start_seq_0, end_seq_0, state);
  1315. if (!dup_segs) { /* Skip dubious DSACK */
  1316. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPDSACKIGNOREDDUBIOUS);
  1317. return false;
  1318. }
  1319. NET_ADD_STATS(sock_net(sk), LINUX_MIB_TCPDSACKRECVSEGS, dup_segs);
  1320. /* D-SACK for already forgotten data... Do dumb counting. */
  1321. if (tp->undo_marker && tp->undo_retrans > 0 &&
  1322. !after(end_seq_0, prior_snd_una) &&
  1323. after(end_seq_0, tp->undo_marker))
  1324. tp->undo_retrans = max_t(int, 0, tp->undo_retrans - dup_segs);
  1325. return true;
  1326. }
  1327. /* Check if skb is fully within the SACK block. In presence of GSO skbs,
  1328. * the incoming SACK may not exactly match but we can find smaller MSS
  1329. * aligned portion of it that matches. Therefore we might need to fragment
  1330. * which may fail and creates some hassle (caller must handle error case
  1331. * returns).
  1332. *
  1333. * FIXME: this could be merged to shift decision code
  1334. */
  1335. static int tcp_match_skb_to_sack(struct sock *sk, struct sk_buff *skb,
  1336. u32 start_seq, u32 end_seq)
  1337. {
  1338. int err;
  1339. bool in_sack;
  1340. unsigned int pkt_len;
  1341. unsigned int mss;
  1342. in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq) &&
  1343. !before(end_seq, TCP_SKB_CB(skb)->end_seq);
  1344. if (tcp_skb_pcount(skb) > 1 && !in_sack &&
  1345. after(TCP_SKB_CB(skb)->end_seq, start_seq)) {
  1346. mss = tcp_skb_mss(skb);
  1347. in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq);
  1348. if (!in_sack) {
  1349. pkt_len = start_seq - TCP_SKB_CB(skb)->seq;
  1350. if (pkt_len < mss)
  1351. pkt_len = mss;
  1352. } else {
  1353. pkt_len = end_seq - TCP_SKB_CB(skb)->seq;
  1354. if (pkt_len < mss)
  1355. return -EINVAL;
  1356. }
  1357. /* Round if necessary so that SACKs cover only full MSSes
  1358. * and/or the remaining small portion (if present)
  1359. */
  1360. if (pkt_len > mss) {
  1361. unsigned int new_len = (pkt_len / mss) * mss;
  1362. if (!in_sack && new_len < pkt_len)
  1363. new_len += mss;
  1364. pkt_len = new_len;
  1365. }
  1366. if (pkt_len >= skb->len && !in_sack)
  1367. return 0;
  1368. err = tcp_fragment(sk, TCP_FRAG_IN_RTX_QUEUE, skb,
  1369. pkt_len, mss, GFP_ATOMIC);
  1370. if (err < 0)
  1371. return err;
  1372. }
  1373. return in_sack;
  1374. }
  1375. /* Record the most recently (re)sent time among the (s)acked packets
  1376. * This is "Step 3: Advance RACK.xmit_time and update RACK.RTT" from
  1377. * draft-cheng-tcpm-rack-00.txt
  1378. */
  1379. static void tcp_rack_advance(struct tcp_sock *tp, u8 sacked,
  1380. u32 end_seq, u64 xmit_time)
  1381. {
  1382. u32 rtt_us;
  1383. rtt_us = tcp_stamp_us_delta(tp->tcp_mstamp, xmit_time);
  1384. if (rtt_us < tcp_min_rtt(tp) && (sacked & TCPCB_RETRANS)) {
  1385. /* If the sacked packet was retransmitted, it's ambiguous
  1386. * whether the retransmission or the original (or the prior
  1387. * retransmission) was sacked.
  1388. *
  1389. * If the original is lost, there is no ambiguity. Otherwise
  1390. * we assume the original can be delayed up to aRTT + min_rtt.
  1391. * the aRTT term is bounded by the fast recovery or timeout,
  1392. * so it's at least one RTT (i.e., retransmission is at least
  1393. * an RTT later).
  1394. */
  1395. return;
  1396. }
  1397. tp->rack.advanced = 1;
  1398. tp->rack.rtt_us = rtt_us;
  1399. if (tcp_skb_sent_after(xmit_time, tp->rack.mstamp,
  1400. end_seq, tp->rack.end_seq)) {
  1401. tp->rack.mstamp = xmit_time;
  1402. tp->rack.end_seq = end_seq;
  1403. }
  1404. }
  1405. /* Mark the given newly-SACKed range as such, adjusting counters and hints. */
  1406. static u8 tcp_sacktag_one(struct sock *sk,
  1407. struct tcp_sacktag_state *state, u8 sacked,
  1408. u32 start_seq, u32 end_seq,
  1409. int dup_sack, int pcount, u32 plen,
  1410. u64 xmit_time)
  1411. {
  1412. struct tcp_sock *tp = tcp_sk(sk);
  1413. /* Account D-SACK for retransmitted packet. */
  1414. if (dup_sack && (sacked & TCPCB_RETRANS)) {
  1415. if (tp->undo_marker && tp->undo_retrans > 0 &&
  1416. after(end_seq, tp->undo_marker))
  1417. tp->undo_retrans = max_t(int, 0, tp->undo_retrans - pcount);
  1418. if ((sacked & TCPCB_SACKED_ACKED) &&
  1419. before(start_seq, state->reord))
  1420. state->reord = start_seq;
  1421. }
  1422. /* Nothing to do; acked frame is about to be dropped (was ACKed). */
  1423. if (!after(end_seq, tp->snd_una))
  1424. return sacked;
  1425. if (!(sacked & TCPCB_SACKED_ACKED)) {
  1426. tcp_rack_advance(tp, sacked, end_seq, xmit_time);
  1427. if (sacked & TCPCB_SACKED_RETRANS) {
  1428. /* If the segment is not tagged as lost,
  1429. * we do not clear RETRANS, believing
  1430. * that retransmission is still in flight.
  1431. */
  1432. if (sacked & TCPCB_LOST) {
  1433. sacked &= ~(TCPCB_LOST|TCPCB_SACKED_RETRANS);
  1434. tp->lost_out -= pcount;
  1435. tp->retrans_out -= pcount;
  1436. }
  1437. } else {
  1438. if (!(sacked & TCPCB_RETRANS)) {
  1439. /* New sack for not retransmitted frame,
  1440. * which was in hole. It is reordering.
  1441. */
  1442. if (before(start_seq,
  1443. tcp_highest_sack_seq(tp)) &&
  1444. before(start_seq, state->reord))
  1445. state->reord = start_seq;
  1446. if (!after(end_seq, tp->high_seq))
  1447. state->flag |= FLAG_ORIG_SACK_ACKED;
  1448. if (state->first_sackt == 0)
  1449. state->first_sackt = xmit_time;
  1450. state->last_sackt = xmit_time;
  1451. }
  1452. if (sacked & TCPCB_LOST) {
  1453. sacked &= ~TCPCB_LOST;
  1454. tp->lost_out -= pcount;
  1455. }
  1456. }
  1457. sacked |= TCPCB_SACKED_ACKED;
  1458. state->flag |= FLAG_DATA_SACKED;
  1459. tp->sacked_out += pcount;
  1460. /* Out-of-order packets delivered */
  1461. state->sack_delivered += pcount;
  1462. state->delivered_bytes += plen;
  1463. }
  1464. /* D-SACK. We can detect redundant retransmission in S|R and plain R
  1465. * frames and clear it. undo_retrans is decreased above, L|R frames
  1466. * are accounted above as well.
  1467. */
  1468. if (dup_sack && (sacked & TCPCB_SACKED_RETRANS)) {
  1469. sacked &= ~TCPCB_SACKED_RETRANS;
  1470. tp->retrans_out -= pcount;
  1471. }
  1472. return sacked;
  1473. }
  1474. /* The bandwidth estimator estimates the rate at which the network
  1475. * can currently deliver outbound data packets for this flow. At a high
  1476. * level, it operates by taking a delivery rate sample for each ACK.
  1477. *
  1478. * A rate sample records the rate at which the network delivered packets
  1479. * for this flow, calculated over the time interval between the transmission
  1480. * of a data packet and the acknowledgment of that packet.
  1481. *
  1482. * Specifically, over the interval between each transmit and corresponding ACK,
  1483. * the estimator generates a delivery rate sample. Typically it uses the rate
  1484. * at which packets were acknowledged. However, the approach of using only the
  1485. * acknowledgment rate faces a challenge under the prevalent ACK decimation or
  1486. * compression: packets can temporarily appear to be delivered much quicker
  1487. * than the bottleneck rate. Since it is physically impossible to do that in a
  1488. * sustained fashion, when the estimator notices that the ACK rate is faster
  1489. * than the transmit rate, it uses the latter:
  1490. *
  1491. * send_rate = #pkts_delivered/(last_snd_time - first_snd_time)
  1492. * ack_rate = #pkts_delivered/(last_ack_time - first_ack_time)
  1493. * bw = min(send_rate, ack_rate)
  1494. *
  1495. * Notice the estimator essentially estimates the goodput, not always the
  1496. * network bottleneck link rate when the sending or receiving is limited by
  1497. * other factors like applications or receiver window limits. The estimator
  1498. * deliberately avoids using the inter-packet spacing approach because that
  1499. * approach requires a large number of samples and sophisticated filtering.
  1500. *
  1501. * TCP flows can often be application-limited in request/response workloads.
  1502. * The estimator marks a bandwidth sample as application-limited if there
  1503. * was some moment during the sampled window of packets when there was no data
  1504. * ready to send in the write queue.
  1505. */
  1506. /* Update the connection delivery information and generate a rate sample. */
  1507. static void tcp_rate_gen(struct sock *sk, u32 delivered, u32 lost,
  1508. bool is_sack_reneg, struct rate_sample *rs)
  1509. {
  1510. struct tcp_sock *tp = tcp_sk(sk);
  1511. u32 snd_us, ack_us;
  1512. /* Clear app limited if bubble is acked and gone. */
  1513. if (tp->app_limited && after(tp->delivered, tp->app_limited))
  1514. tp->app_limited = 0;
  1515. /* TODO: there are multiple places throughout tcp_ack() to get
  1516. * current time. Refactor the code using a new "tcp_acktag_state"
  1517. * to carry current time, flags, stats like "tcp_sacktag_state".
  1518. */
  1519. if (delivered)
  1520. tp->delivered_mstamp = tp->tcp_mstamp;
  1521. rs->acked_sacked = delivered; /* freshly ACKed or SACKed */
  1522. rs->losses = lost; /* freshly marked lost */
  1523. /* Return an invalid sample if no timing information is available or
  1524. * in recovery from loss with SACK reneging. Rate samples taken during
  1525. * a SACK reneging event may overestimate bw by including packets that
  1526. * were SACKed before the reneg.
  1527. */
  1528. if (!rs->prior_mstamp || is_sack_reneg) {
  1529. rs->delivered = -1;
  1530. rs->interval_us = -1;
  1531. return;
  1532. }
  1533. rs->delivered = tp->delivered - rs->prior_delivered;
  1534. rs->delivered_ce = tp->delivered_ce - rs->prior_delivered_ce;
  1535. /* delivered_ce occupies less than 32 bits in the skb control block */
  1536. rs->delivered_ce &= TCPCB_DELIVERED_CE_MASK;
  1537. /* Model sending data and receiving ACKs as separate pipeline phases
  1538. * for a window. Usually the ACK phase is longer, but with ACK
  1539. * compression the send phase can be longer. To be safe we use the
  1540. * longer phase.
  1541. */
  1542. snd_us = rs->interval_us; /* send phase */
  1543. ack_us = tcp_stamp_us_delta(tp->tcp_mstamp,
  1544. rs->prior_mstamp); /* ack phase */
  1545. rs->interval_us = max(snd_us, ack_us);
  1546. /* Record both segment send and ack receive intervals */
  1547. rs->snd_interval_us = snd_us;
  1548. rs->rcv_interval_us = ack_us;
  1549. /* Normally we expect interval_us >= min-rtt.
  1550. * Note that rate may still be over-estimated when a spuriously
  1551. * retransmistted skb was first (s)acked because "interval_us"
  1552. * is under-estimated (up to an RTT). However continuously
  1553. * measuring the delivery rate during loss recovery is crucial
  1554. * for connections suffer heavy or prolonged losses.
  1555. */
  1556. if (unlikely(rs->interval_us < tcp_min_rtt(tp))) {
  1557. if (!rs->is_retrans)
  1558. pr_debug("tcp rate: %ld %d %u %u %u\n",
  1559. rs->interval_us, rs->delivered,
  1560. inet_csk(sk)->icsk_ca_state,
  1561. tp->rx_opt.sack_ok, tcp_min_rtt(tp));
  1562. rs->interval_us = -1;
  1563. return;
  1564. }
  1565. /* Record the last non-app-limited or the highest app-limited bw */
  1566. if (!rs->is_app_limited ||
  1567. ((u64)rs->delivered * tp->rate_interval_us >=
  1568. (u64)tp->rate_delivered * rs->interval_us)) {
  1569. tp->rate_delivered = rs->delivered;
  1570. tp->rate_interval_us = rs->interval_us;
  1571. tp->rate_app_limited = rs->is_app_limited;
  1572. }
  1573. }
  1574. /* When an skb is sacked or acked, we fill in the rate sample with the (prior)
  1575. * delivery information when the skb was last transmitted.
  1576. *
  1577. * If an ACK (s)acks multiple skbs (e.g., stretched-acks), this function is
  1578. * called multiple times. We favor the information from the most recently
  1579. * sent skb, i.e., the skb with the most recently sent time and the highest
  1580. * sequence.
  1581. */
  1582. static void tcp_rate_skb_delivered(struct sock *sk, struct sk_buff *skb,
  1583. struct rate_sample *rs)
  1584. {
  1585. struct tcp_skb_cb *scb = TCP_SKB_CB(skb);
  1586. struct tcp_sock *tp = tcp_sk(sk);
  1587. u64 tx_tstamp;
  1588. if (!scb->tx.delivered_mstamp)
  1589. return;
  1590. tx_tstamp = tcp_skb_timestamp_us(skb);
  1591. if (!rs->prior_delivered ||
  1592. tcp_skb_sent_after(tx_tstamp, tp->first_tx_mstamp,
  1593. scb->end_seq, rs->last_end_seq)) {
  1594. rs->prior_delivered_ce = scb->tx.delivered_ce;
  1595. rs->prior_delivered = scb->tx.delivered;
  1596. rs->prior_mstamp = scb->tx.delivered_mstamp;
  1597. rs->is_app_limited = scb->tx.is_app_limited;
  1598. rs->is_retrans = scb->sacked & TCPCB_RETRANS;
  1599. rs->last_end_seq = scb->end_seq;
  1600. /* Record send time of most recently ACKed packet: */
  1601. tp->first_tx_mstamp = tx_tstamp;
  1602. /* Find the duration of the "send phase" of this window: */
  1603. rs->interval_us = tcp_stamp_us_delta(tp->first_tx_mstamp,
  1604. scb->tx.first_tx_mstamp);
  1605. }
  1606. /* Mark off the skb delivered once it's sacked to avoid being
  1607. * used again when it's cumulatively acked. For acked packets
  1608. * we don't need to reset since it'll be freed soon.
  1609. */
  1610. if (scb->sacked & TCPCB_SACKED_ACKED)
  1611. scb->tx.delivered_mstamp = 0;
  1612. }
  1613. /* Shift newly-SACKed bytes from this skb to the immediately previous
  1614. * already-SACKed sk_buff. Mark the newly-SACKed bytes as such.
  1615. */
  1616. static bool tcp_shifted_skb(struct sock *sk, struct sk_buff *prev,
  1617. struct sk_buff *skb,
  1618. struct tcp_sacktag_state *state,
  1619. unsigned int pcount, int shifted, int mss,
  1620. bool dup_sack)
  1621. {
  1622. struct tcp_sock *tp = tcp_sk(sk);
  1623. u32 start_seq = TCP_SKB_CB(skb)->seq; /* start of newly-SACKed */
  1624. u32 end_seq = start_seq + shifted; /* end of newly-SACKed */
  1625. BUG_ON(!pcount);
  1626. /* Adjust counters and hints for the newly sacked sequence
  1627. * range but discard the return value since prev is already
  1628. * marked. We must tag the range first because the seq
  1629. * advancement below implicitly advances
  1630. * tcp_highest_sack_seq() when skb is highest_sack.
  1631. */
  1632. tcp_sacktag_one(sk, state, TCP_SKB_CB(skb)->sacked,
  1633. start_seq, end_seq, dup_sack, pcount, skb->len,
  1634. tcp_skb_timestamp_us(skb));
  1635. tcp_rate_skb_delivered(sk, skb, state->rate);
  1636. TCP_SKB_CB(prev)->end_seq += shifted;
  1637. TCP_SKB_CB(skb)->seq += shifted;
  1638. tcp_skb_pcount_add(prev, pcount);
  1639. WARN_ON_ONCE(tcp_skb_pcount(skb) < pcount);
  1640. tcp_skb_pcount_add(skb, -pcount);
  1641. /* When we're adding to gso_segs == 1, gso_size will be zero,
  1642. * in theory this shouldn't be necessary but as long as DSACK
  1643. * code can come after this skb later on it's better to keep
  1644. * setting gso_size to something.
  1645. */
  1646. if (!TCP_SKB_CB(prev)->tcp_gso_size)
  1647. TCP_SKB_CB(prev)->tcp_gso_size = mss;
  1648. /* CHECKME: To clear or not to clear? Mimics normal skb currently */
  1649. if (tcp_skb_pcount(skb) <= 1)
  1650. TCP_SKB_CB(skb)->tcp_gso_size = 0;
  1651. /* Difference in this won't matter, both ACKed by the same cumul. ACK */
  1652. TCP_SKB_CB(prev)->sacked |= (TCP_SKB_CB(skb)->sacked & TCPCB_EVER_RETRANS);
  1653. if (skb->len > 0) {
  1654. BUG_ON(!tcp_skb_pcount(skb));
  1655. NET_INC_STATS(sock_net(sk), LINUX_MIB_SACKSHIFTED);
  1656. return false;
  1657. }
  1658. /* Whole SKB was eaten :-) */
  1659. if (skb == tp->retransmit_skb_hint)
  1660. tp->retransmit_skb_hint = prev;
  1661. TCP_SKB_CB(prev)->tcp_flags |= TCP_SKB_CB(skb)->tcp_flags;
  1662. TCP_SKB_CB(prev)->eor = TCP_SKB_CB(skb)->eor;
  1663. if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)
  1664. TCP_SKB_CB(prev)->end_seq++;
  1665. if (skb == tcp_highest_sack(sk))
  1666. tcp_advance_highest_sack(sk, skb);
  1667. tcp_skb_collapse_tstamp(prev, skb);
  1668. if (unlikely(TCP_SKB_CB(prev)->tx.delivered_mstamp))
  1669. TCP_SKB_CB(prev)->tx.delivered_mstamp = 0;
  1670. tcp_rtx_queue_unlink_and_free(skb, sk);
  1671. NET_INC_STATS(sock_net(sk), LINUX_MIB_SACKMERGED);
  1672. return true;
  1673. }
  1674. /* I wish gso_size would have a bit more sane initialization than
  1675. * something-or-zero which complicates things
  1676. */
  1677. static int tcp_skb_seglen(const struct sk_buff *skb)
  1678. {
  1679. return tcp_skb_pcount(skb) == 1 ? skb->len : tcp_skb_mss(skb);
  1680. }
  1681. /* Shifting pages past head area doesn't work */
  1682. static int skb_can_shift(const struct sk_buff *skb)
  1683. {
  1684. return !skb_headlen(skb) && skb_is_nonlinear(skb);
  1685. }
  1686. int tcp_skb_shift(struct sk_buff *to, struct sk_buff *from,
  1687. int pcount, int shiftlen)
  1688. {
  1689. /* TCP min gso_size is 8 bytes (TCP_MIN_GSO_SIZE)
  1690. * Since TCP_SKB_CB(skb)->tcp_gso_segs is 16 bits, we need
  1691. * to make sure not storing more than 65535 * 8 bytes per skb,
  1692. * even if current MSS is bigger.
  1693. */
  1694. if (unlikely(to->len + shiftlen >= 65535 * TCP_MIN_GSO_SIZE))
  1695. return 0;
  1696. if (unlikely(tcp_skb_pcount(to) + pcount > 65535))
  1697. return 0;
  1698. return skb_shift(to, from, shiftlen);
  1699. }
  1700. /* Try collapsing SACK blocks spanning across multiple skbs to a single
  1701. * skb.
  1702. */
  1703. static struct sk_buff *tcp_shift_skb_data(struct sock *sk, struct sk_buff *skb,
  1704. struct tcp_sacktag_state *state,
  1705. u32 start_seq, u32 end_seq,
  1706. bool dup_sack)
  1707. {
  1708. struct tcp_sock *tp = tcp_sk(sk);
  1709. struct sk_buff *prev;
  1710. int mss;
  1711. int pcount = 0;
  1712. int len;
  1713. int in_sack;
  1714. /* Normally R but no L won't result in plain S */
  1715. if (!dup_sack &&
  1716. (TCP_SKB_CB(skb)->sacked & (TCPCB_LOST|TCPCB_SACKED_RETRANS)) == TCPCB_SACKED_RETRANS)
  1717. goto fallback;
  1718. if (!skb_can_shift(skb))
  1719. goto fallback;
  1720. /* This frame is about to be dropped (was ACKed). */
  1721. if (!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una))
  1722. goto fallback;
  1723. /* Can only happen with delayed DSACK + discard craziness */
  1724. prev = skb_rb_prev(skb);
  1725. if (!prev)
  1726. goto fallback;
  1727. if ((TCP_SKB_CB(prev)->sacked & TCPCB_TAGBITS) != TCPCB_SACKED_ACKED)
  1728. goto fallback;
  1729. if (!tcp_skb_can_collapse(prev, skb))
  1730. goto fallback;
  1731. in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq) &&
  1732. !before(end_seq, TCP_SKB_CB(skb)->end_seq);
  1733. if (in_sack) {
  1734. len = skb->len;
  1735. pcount = tcp_skb_pcount(skb);
  1736. mss = tcp_skb_seglen(skb);
  1737. /* TODO: Fix DSACKs to not fragment already SACKed and we can
  1738. * drop this restriction as unnecessary
  1739. */
  1740. if (mss != tcp_skb_seglen(prev))
  1741. goto fallback;
  1742. } else {
  1743. if (!after(TCP_SKB_CB(skb)->end_seq, start_seq))
  1744. goto noop;
  1745. /* CHECKME: This is non-MSS split case only?, this will
  1746. * cause skipped skbs due to advancing loop btw, original
  1747. * has that feature too
  1748. */
  1749. if (tcp_skb_pcount(skb) <= 1)
  1750. goto noop;
  1751. in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq);
  1752. if (!in_sack) {
  1753. /* TODO: head merge to next could be attempted here
  1754. * if (!after(TCP_SKB_CB(skb)->end_seq, end_seq)),
  1755. * though it might not be worth of the additional hassle
  1756. *
  1757. * ...we can probably just fallback to what was done
  1758. * previously. We could try merging non-SACKed ones
  1759. * as well but it probably isn't going to buy off
  1760. * because later SACKs might again split them, and
  1761. * it would make skb timestamp tracking considerably
  1762. * harder problem.
  1763. */
  1764. goto fallback;
  1765. }
  1766. len = end_seq - TCP_SKB_CB(skb)->seq;
  1767. BUG_ON(len < 0);
  1768. BUG_ON(len > skb->len);
  1769. /* MSS boundaries should be honoured or else pcount will
  1770. * severely break even though it makes things bit trickier.
  1771. * Optimize common case to avoid most of the divides
  1772. */
  1773. mss = tcp_skb_mss(skb);
  1774. /* TODO: Fix DSACKs to not fragment already SACKed and we can
  1775. * drop this restriction as unnecessary
  1776. */
  1777. if (mss != tcp_skb_seglen(prev))
  1778. goto fallback;
  1779. if (len == mss) {
  1780. pcount = 1;
  1781. } else if (len < mss) {
  1782. goto noop;
  1783. } else {
  1784. pcount = len / mss;
  1785. len = pcount * mss;
  1786. }
  1787. }
  1788. /* tcp_sacktag_one() won't SACK-tag ranges below snd_una */
  1789. if (!after(TCP_SKB_CB(skb)->seq + len, tp->snd_una))
  1790. goto fallback;
  1791. if (!tcp_skb_shift(prev, skb, pcount, len))
  1792. goto fallback;
  1793. if (!tcp_shifted_skb(sk, prev, skb, state, pcount, len, mss, dup_sack))
  1794. goto out;
  1795. /* Hole filled allows collapsing with the next as well, this is very
  1796. * useful when hole on every nth skb pattern happens
  1797. */
  1798. skb = skb_rb_next(prev);
  1799. if (!skb)
  1800. goto out;
  1801. if (!skb_can_shift(skb) ||
  1802. ((TCP_SKB_CB(skb)->sacked & TCPCB_TAGBITS) != TCPCB_SACKED_ACKED) ||
  1803. (mss != tcp_skb_seglen(skb)))
  1804. goto out;
  1805. if (!tcp_skb_can_collapse(prev, skb))
  1806. goto out;
  1807. len = skb->len;
  1808. pcount = tcp_skb_pcount(skb);
  1809. if (tcp_skb_shift(prev, skb, pcount, len))
  1810. tcp_shifted_skb(sk, prev, skb, state, pcount,
  1811. len, mss, 0);
  1812. out:
  1813. return prev;
  1814. noop:
  1815. return skb;
  1816. fallback:
  1817. NET_INC_STATS(sock_net(sk), LINUX_MIB_SACKSHIFTFALLBACK);
  1818. return NULL;
  1819. }
  1820. static struct sk_buff *tcp_sacktag_walk(struct sk_buff *skb, struct sock *sk,
  1821. struct tcp_sack_block *next_dup,
  1822. struct tcp_sacktag_state *state,
  1823. u32 start_seq, u32 end_seq,
  1824. bool dup_sack_in)
  1825. {
  1826. struct tcp_sock *tp = tcp_sk(sk);
  1827. struct sk_buff *tmp;
  1828. skb_rbtree_walk_from(skb) {
  1829. int in_sack = 0;
  1830. bool dup_sack = dup_sack_in;
  1831. /* queue is in-order => we can short-circuit the walk early */
  1832. if (!before(TCP_SKB_CB(skb)->seq, end_seq))
  1833. break;
  1834. if (next_dup &&
  1835. before(TCP_SKB_CB(skb)->seq, next_dup->end_seq)) {
  1836. in_sack = tcp_match_skb_to_sack(sk, skb,
  1837. next_dup->start_seq,
  1838. next_dup->end_seq);
  1839. if (in_sack > 0)
  1840. dup_sack = true;
  1841. }
  1842. /* skb reference here is a bit tricky to get right, since
  1843. * shifting can eat and free both this skb and the next,
  1844. * so not even _safe variant of the loop is enough.
  1845. */
  1846. if (in_sack <= 0) {
  1847. tmp = tcp_shift_skb_data(sk, skb, state,
  1848. start_seq, end_seq, dup_sack);
  1849. if (tmp) {
  1850. if (tmp != skb) {
  1851. skb = tmp;
  1852. continue;
  1853. }
  1854. in_sack = 0;
  1855. } else {
  1856. in_sack = tcp_match_skb_to_sack(sk, skb,
  1857. start_seq,
  1858. end_seq);
  1859. }
  1860. }
  1861. if (unlikely(in_sack < 0))
  1862. break;
  1863. if (in_sack) {
  1864. TCP_SKB_CB(skb)->sacked =
  1865. tcp_sacktag_one(sk,
  1866. state,
  1867. TCP_SKB_CB(skb)->sacked,
  1868. TCP_SKB_CB(skb)->seq,
  1869. TCP_SKB_CB(skb)->end_seq,
  1870. dup_sack,
  1871. tcp_skb_pcount(skb),
  1872. skb->len,
  1873. tcp_skb_timestamp_us(skb));
  1874. tcp_rate_skb_delivered(sk, skb, state->rate);
  1875. if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED)
  1876. list_del_init(&skb->tcp_tsorted_anchor);
  1877. if (!before(TCP_SKB_CB(skb)->seq,
  1878. tcp_highest_sack_seq(tp)))
  1879. tcp_advance_highest_sack(sk, skb);
  1880. }
  1881. }
  1882. return skb;
  1883. }
  1884. static struct sk_buff *tcp_sacktag_bsearch(struct sock *sk, u32 seq)
  1885. {
  1886. struct rb_node *parent, **p = &sk->tcp_rtx_queue.rb_node;
  1887. struct sk_buff *skb;
  1888. while (*p) {
  1889. parent = *p;
  1890. skb = rb_to_skb(parent);
  1891. if (before(seq, TCP_SKB_CB(skb)->seq)) {
  1892. p = &parent->rb_left;
  1893. continue;
  1894. }
  1895. if (!before(seq, TCP_SKB_CB(skb)->end_seq)) {
  1896. p = &parent->rb_right;
  1897. continue;
  1898. }
  1899. return skb;
  1900. }
  1901. return NULL;
  1902. }
  1903. static struct sk_buff *tcp_sacktag_skip(struct sk_buff *skb, struct sock *sk,
  1904. u32 skip_to_seq)
  1905. {
  1906. if (skb && after(TCP_SKB_CB(skb)->seq, skip_to_seq))
  1907. return skb;
  1908. return tcp_sacktag_bsearch(sk, skip_to_seq);
  1909. }
  1910. static struct sk_buff *tcp_maybe_skipping_dsack(struct sk_buff *skb,
  1911. struct sock *sk,
  1912. struct tcp_sack_block *next_dup,
  1913. struct tcp_sacktag_state *state,
  1914. u32 skip_to_seq)
  1915. {
  1916. if (!next_dup)
  1917. return skb;
  1918. if (before(next_dup->start_seq, skip_to_seq)) {
  1919. skb = tcp_sacktag_skip(skb, sk, next_dup->start_seq);
  1920. skb = tcp_sacktag_walk(skb, sk, NULL, state,
  1921. next_dup->start_seq, next_dup->end_seq,
  1922. 1);
  1923. }
  1924. return skb;
  1925. }
  1926. static int tcp_sack_cache_ok(const struct tcp_sock *tp, const struct tcp_sack_block *cache)
  1927. {
  1928. return cache < tp->recv_sack_cache + ARRAY_SIZE(tp->recv_sack_cache);
  1929. }
  1930. static int
  1931. tcp_sacktag_write_queue(struct sock *sk, const struct sk_buff *ack_skb,
  1932. u32 prior_snd_una, struct tcp_sacktag_state *state)
  1933. {
  1934. struct tcp_sock *tp = tcp_sk(sk);
  1935. const unsigned char *ptr = (skb_transport_header(ack_skb) +
  1936. TCP_SKB_CB(ack_skb)->sacked);
  1937. struct tcp_sack_block_wire *sp_wire = (struct tcp_sack_block_wire *)(ptr+2);
  1938. struct tcp_sack_block sp[TCP_NUM_SACKS];
  1939. struct tcp_sack_block *cache;
  1940. struct sk_buff *skb;
  1941. int num_sacks = min(TCP_NUM_SACKS, (ptr[1] - TCPOLEN_SACK_BASE) >> 3);
  1942. int used_sacks;
  1943. bool found_dup_sack = false;
  1944. int i, j;
  1945. int first_sack_index;
  1946. state->flag = 0;
  1947. state->reord = tp->snd_nxt;
  1948. if (!tp->sacked_out)
  1949. tcp_highest_sack_reset(sk);
  1950. found_dup_sack = tcp_check_dsack(sk, ack_skb, sp_wire,
  1951. num_sacks, prior_snd_una, state);
  1952. /* Eliminate too old ACKs, but take into
  1953. * account more or less fresh ones, they can
  1954. * contain valid SACK info.
  1955. */
  1956. if (before(TCP_SKB_CB(ack_skb)->ack_seq, prior_snd_una - tp->max_window))
  1957. return 0;
  1958. if (!tp->packets_out)
  1959. goto out;
  1960. used_sacks = 0;
  1961. first_sack_index = 0;
  1962. for (i = 0; i < num_sacks; i++) {
  1963. bool dup_sack = !i && found_dup_sack;
  1964. sp[used_sacks].start_seq = get_unaligned_be32(&sp_wire[i].start_seq);
  1965. sp[used_sacks].end_seq = get_unaligned_be32(&sp_wire[i].end_seq);
  1966. if (!tcp_is_sackblock_valid(tp, dup_sack,
  1967. sp[used_sacks].start_seq,
  1968. sp[used_sacks].end_seq)) {
  1969. int mib_idx;
  1970. if (dup_sack) {
  1971. if (!tp->undo_marker)
  1972. mib_idx = LINUX_MIB_TCPDSACKIGNOREDNOUNDO;
  1973. else
  1974. mib_idx = LINUX_MIB_TCPDSACKIGNOREDOLD;
  1975. } else {
  1976. /* Don't count olds caused by ACK reordering */
  1977. if ((TCP_SKB_CB(ack_skb)->ack_seq != tp->snd_una) &&
  1978. !after(sp[used_sacks].end_seq, tp->snd_una))
  1979. continue;
  1980. mib_idx = LINUX_MIB_TCPSACKDISCARD;
  1981. }
  1982. NET_INC_STATS(sock_net(sk), mib_idx);
  1983. if (i == 0)
  1984. first_sack_index = -1;
  1985. continue;
  1986. }
  1987. /* Ignore very old stuff early */
  1988. if (!after(sp[used_sacks].end_seq, prior_snd_una)) {
  1989. if (i == 0)
  1990. first_sack_index = -1;
  1991. continue;
  1992. }
  1993. used_sacks++;
  1994. }
  1995. /* order SACK blocks to allow in order walk of the retrans queue */
  1996. for (i = used_sacks - 1; i > 0; i--) {
  1997. for (j = 0; j < i; j++) {
  1998. if (after(sp[j].start_seq, sp[j + 1].start_seq)) {
  1999. swap(sp[j], sp[j + 1]);
  2000. /* Track where the first SACK block goes to */
  2001. if (j == first_sack_index)
  2002. first_sack_index = j + 1;
  2003. }
  2004. }
  2005. }
  2006. state->mss_now = tcp_current_mss(sk);
  2007. skb = NULL;
  2008. i = 0;
  2009. if (!tp->sacked_out) {
  2010. /* It's already past, so skip checking against it */
  2011. cache = tp->recv_sack_cache + ARRAY_SIZE(tp->recv_sack_cache);
  2012. } else {
  2013. cache = tp->recv_sack_cache;
  2014. /* Skip empty blocks in at head of the cache */
  2015. while (tcp_sack_cache_ok(tp, cache) && !cache->start_seq &&
  2016. !cache->end_seq)
  2017. cache++;
  2018. }
  2019. while (i < used_sacks) {
  2020. u32 start_seq = sp[i].start_seq;
  2021. u32 end_seq = sp[i].end_seq;
  2022. bool dup_sack = (found_dup_sack && (i == first_sack_index));
  2023. struct tcp_sack_block *next_dup = NULL;
  2024. if (found_dup_sack && ((i + 1) == first_sack_index))
  2025. next_dup = &sp[i + 1];
  2026. /* Skip too early cached blocks */
  2027. while (tcp_sack_cache_ok(tp, cache) &&
  2028. !before(start_seq, cache->end_seq))
  2029. cache++;
  2030. /* Can skip some work by looking recv_sack_cache? */
  2031. if (tcp_sack_cache_ok(tp, cache) && !dup_sack &&
  2032. after(end_seq, cache->start_seq)) {
  2033. /* Head todo? */
  2034. if (before(start_seq, cache->start_seq)) {
  2035. skb = tcp_sacktag_skip(skb, sk, start_seq);
  2036. skb = tcp_sacktag_walk(skb, sk, next_dup,
  2037. state,
  2038. start_seq,
  2039. cache->start_seq,
  2040. dup_sack);
  2041. }
  2042. /* Rest of the block already fully processed? */
  2043. if (!after(end_seq, cache->end_seq))
  2044. goto advance_sp;
  2045. skb = tcp_maybe_skipping_dsack(skb, sk, next_dup,
  2046. state,
  2047. cache->end_seq);
  2048. /* ...tail remains todo... */
  2049. if (tcp_highest_sack_seq(tp) == cache->end_seq) {
  2050. /* ...but better entrypoint exists! */
  2051. skb = tcp_highest_sack(sk);
  2052. if (!skb)
  2053. break;
  2054. cache++;
  2055. goto walk;
  2056. }
  2057. skb = tcp_sacktag_skip(skb, sk, cache->end_seq);
  2058. /* Check overlap against next cached too (past this one already) */
  2059. cache++;
  2060. continue;
  2061. }
  2062. if (!before(start_seq, tcp_highest_sack_seq(tp))) {
  2063. skb = tcp_highest_sack(sk);
  2064. if (!skb)
  2065. break;
  2066. }
  2067. skb = tcp_sacktag_skip(skb, sk, start_seq);
  2068. walk:
  2069. skb = tcp_sacktag_walk(skb, sk, next_dup, state,
  2070. start_seq, end_seq, dup_sack);
  2071. advance_sp:
  2072. i++;
  2073. }
  2074. /* Clear the head of the cache sack blocks so we can skip it next time */
  2075. for (i = 0; i < ARRAY_SIZE(tp->recv_sack_cache) - used_sacks; i++) {
  2076. tp->recv_sack_cache[i].start_seq = 0;
  2077. tp->recv_sack_cache[i].end_seq = 0;
  2078. }
  2079. for (j = 0; j < used_sacks; j++)
  2080. tp->recv_sack_cache[i++] = sp[j];
  2081. if (inet_csk(sk)->icsk_ca_state != TCP_CA_Loss || tp->undo_marker)
  2082. tcp_check_sack_reordering(sk, state->reord, 0);
  2083. tcp_verify_left_out(tp);
  2084. out:
  2085. #if FASTRETRANS_DEBUG > 0
  2086. WARN_ON((int)tp->sacked_out < 0);
  2087. WARN_ON((int)tp->lost_out < 0);
  2088. WARN_ON((int)tp->retrans_out < 0);
  2089. WARN_ON((int)tcp_packets_in_flight(tp) < 0);
  2090. #endif
  2091. return state->flag;
  2092. }
  2093. /* Limits sacked_out so that sum with lost_out isn't ever larger than
  2094. * packets_out. Returns false if sacked_out adjustement wasn't necessary.
  2095. */
  2096. static bool tcp_limit_reno_sacked(struct tcp_sock *tp)
  2097. {
  2098. u32 holes;
  2099. holes = max(tp->lost_out, 1U);
  2100. holes = min(holes, tp->packets_out);
  2101. if ((tp->sacked_out + holes) > tp->packets_out) {
  2102. tp->sacked_out = tp->packets_out - holes;
  2103. return true;
  2104. }
  2105. return false;
  2106. }
  2107. /* If we receive more dupacks than we expected counting segments
  2108. * in assumption of absent reordering, interpret this as reordering.
  2109. * The only another reason could be bug in receiver TCP.
  2110. */
  2111. static void tcp_check_reno_reordering(struct sock *sk, const int addend)
  2112. {
  2113. struct tcp_sock *tp = tcp_sk(sk);
  2114. if (!tcp_limit_reno_sacked(tp))
  2115. return;
  2116. tp->reordering = min_t(u32, tp->packets_out + addend,
  2117. READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_max_reordering));
  2118. tp->reord_seen++;
  2119. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPRENOREORDER);
  2120. }
  2121. /* Emulate SACKs for SACKless connection: account for a new dupack. */
  2122. static void tcp_add_reno_sack(struct sock *sk, int num_dupack, bool ece_ack)
  2123. {
  2124. if (num_dupack) {
  2125. struct tcp_sock *tp = tcp_sk(sk);
  2126. u32 prior_sacked = tp->sacked_out;
  2127. s32 delivered;
  2128. tp->sacked_out += num_dupack;
  2129. tcp_check_reno_reordering(sk, 0);
  2130. delivered = tp->sacked_out - prior_sacked;
  2131. if (delivered > 0)
  2132. tcp_count_delivered(tp, delivered, ece_ack);
  2133. tcp_verify_left_out(tp);
  2134. }
  2135. }
  2136. /* Account for ACK, ACKing some data in Reno Recovery phase. */
  2137. static void tcp_remove_reno_sacks(struct sock *sk, int acked, bool ece_ack)
  2138. {
  2139. struct tcp_sock *tp = tcp_sk(sk);
  2140. if (acked > 0) {
  2141. /* One ACK acked hole. The rest eat duplicate ACKs. */
  2142. tcp_count_delivered(tp, max_t(int, acked - tp->sacked_out, 1),
  2143. ece_ack);
  2144. if (acked - 1 >= tp->sacked_out)
  2145. tp->sacked_out = 0;
  2146. else
  2147. tp->sacked_out -= acked - 1;
  2148. }
  2149. tcp_check_reno_reordering(sk, acked);
  2150. tcp_verify_left_out(tp);
  2151. }
  2152. static inline void tcp_reset_reno_sack(struct tcp_sock *tp)
  2153. {
  2154. tp->sacked_out = 0;
  2155. }
  2156. void tcp_clear_retrans(struct tcp_sock *tp)
  2157. {
  2158. tp->retrans_out = 0;
  2159. tp->lost_out = 0;
  2160. tp->undo_marker = 0;
  2161. tp->undo_retrans = -1;
  2162. tp->sacked_out = 0;
  2163. tp->rto_stamp = 0;
  2164. tp->total_rto = 0;
  2165. tp->total_rto_recoveries = 0;
  2166. tp->total_rto_time = 0;
  2167. }
  2168. static inline void tcp_init_undo(struct tcp_sock *tp)
  2169. {
  2170. tp->undo_marker = tp->snd_una;
  2171. /* Retransmission still in flight may cause DSACKs later. */
  2172. /* First, account for regular retransmits in flight: */
  2173. tp->undo_retrans = tp->retrans_out;
  2174. /* Next, account for TLP retransmits in flight: */
  2175. if (tp->tlp_high_seq && tp->tlp_retrans)
  2176. tp->undo_retrans++;
  2177. /* Finally, avoid 0, because undo_retrans==0 means "can undo now": */
  2178. if (!tp->undo_retrans)
  2179. tp->undo_retrans = -1;
  2180. }
  2181. /* If we detect SACK reneging, forget all SACK information
  2182. * and reset tags completely, otherwise preserve SACKs. If receiver
  2183. * dropped its ofo queue, we will know this due to reneging detection.
  2184. */
  2185. static void tcp_timeout_mark_lost(struct sock *sk)
  2186. {
  2187. struct tcp_sock *tp = tcp_sk(sk);
  2188. struct sk_buff *skb, *head;
  2189. bool is_reneg; /* is receiver reneging on SACKs? */
  2190. head = tcp_rtx_queue_head(sk);
  2191. is_reneg = head && (TCP_SKB_CB(head)->sacked & TCPCB_SACKED_ACKED);
  2192. if (is_reneg) {
  2193. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPSACKRENEGING);
  2194. tp->sacked_out = 0;
  2195. /* Mark SACK reneging until we recover from this loss event. */
  2196. tp->is_sack_reneg = 1;
  2197. } else if (tcp_is_reno(tp)) {
  2198. tcp_reset_reno_sack(tp);
  2199. }
  2200. skb = head;
  2201. skb_rbtree_walk_from(skb) {
  2202. if (is_reneg)
  2203. TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_ACKED;
  2204. else if (skb != head && tcp_rack_skb_timeout(tp, skb, 0) > 0)
  2205. continue; /* Don't mark recently sent ones lost yet */
  2206. tcp_mark_skb_lost(sk, skb);
  2207. }
  2208. tcp_verify_left_out(tp);
  2209. tcp_clear_all_retrans_hints(tp);
  2210. }
  2211. /* Enter Loss state. */
  2212. void tcp_enter_loss(struct sock *sk)
  2213. {
  2214. const struct inet_connection_sock *icsk = inet_csk(sk);
  2215. struct tcp_sock *tp = tcp_sk(sk);
  2216. struct net *net = sock_net(sk);
  2217. bool new_recovery = icsk->icsk_ca_state < TCP_CA_Recovery;
  2218. u8 reordering;
  2219. tcp_timeout_mark_lost(sk);
  2220. /* Reduce ssthresh if it has not yet been made inside this window. */
  2221. if (icsk->icsk_ca_state <= TCP_CA_Disorder ||
  2222. !after(tp->high_seq, tp->snd_una) ||
  2223. (icsk->icsk_ca_state == TCP_CA_Loss && !icsk->icsk_retransmits)) {
  2224. tp->prior_ssthresh = tcp_current_ssthresh(sk);
  2225. tp->prior_cwnd = tcp_snd_cwnd(tp);
  2226. tp->snd_ssthresh = icsk->icsk_ca_ops->ssthresh(sk);
  2227. tcp_ca_event(sk, CA_EVENT_LOSS);
  2228. tcp_init_undo(tp);
  2229. }
  2230. tcp_snd_cwnd_set(tp, tcp_packets_in_flight(tp) + 1);
  2231. tp->snd_cwnd_cnt = 0;
  2232. tp->snd_cwnd_stamp = tcp_jiffies32;
  2233. /* Timeout in disordered state after receiving substantial DUPACKs
  2234. * suggests that the degree of reordering is over-estimated.
  2235. */
  2236. reordering = READ_ONCE(net->ipv4.sysctl_tcp_reordering);
  2237. if (icsk->icsk_ca_state <= TCP_CA_Disorder &&
  2238. tp->sacked_out >= reordering)
  2239. tp->reordering = min_t(unsigned int, tp->reordering,
  2240. reordering);
  2241. tcp_set_ca_state(sk, TCP_CA_Loss);
  2242. tp->high_seq = tp->snd_nxt;
  2243. tp->tlp_high_seq = 0;
  2244. tcp_ecn_queue_cwr(tp);
  2245. /* F-RTO RFC5682 sec 3.1 step 1: retransmit SND.UNA if no previous
  2246. * loss recovery is underway except recurring timeout(s) on
  2247. * the same SND.UNA (sec 3.2). Disable F-RTO on path MTU probing
  2248. */
  2249. tp->frto = READ_ONCE(net->ipv4.sysctl_tcp_frto) &&
  2250. (new_recovery || icsk->icsk_retransmits) &&
  2251. !inet_csk(sk)->icsk_mtup.probe_size;
  2252. }
  2253. /* If ACK arrived pointing to a remembered SACK, it means that our
  2254. * remembered SACKs do not reflect real state of receiver i.e.
  2255. * receiver _host_ is heavily congested (or buggy).
  2256. *
  2257. * To avoid big spurious retransmission bursts due to transient SACK
  2258. * scoreboard oddities that look like reneging, we give the receiver a
  2259. * little time (max(RTT/2, 10ms)) to send us some more ACKs that will
  2260. * restore sanity to the SACK scoreboard. If the apparent reneging
  2261. * persists until this RTO then we'll clear the SACK scoreboard.
  2262. */
  2263. static bool tcp_check_sack_reneging(struct sock *sk, int *ack_flag)
  2264. {
  2265. if (*ack_flag & FLAG_SACK_RENEGING &&
  2266. *ack_flag & FLAG_SND_UNA_ADVANCED) {
  2267. struct tcp_sock *tp = tcp_sk(sk);
  2268. unsigned long delay = max(usecs_to_jiffies(tp->srtt_us >> 4),
  2269. msecs_to_jiffies(10));
  2270. tcp_reset_xmit_timer(sk, ICSK_TIME_RETRANS, delay, false);
  2271. *ack_flag &= ~FLAG_SET_XMIT_TIMER;
  2272. return true;
  2273. }
  2274. return false;
  2275. }
  2276. /* Linux NewReno/SACK/ECN state machine.
  2277. * --------------------------------------
  2278. *
  2279. * "Open" Normal state, no dubious events, fast path.
  2280. * "Disorder" In all the respects it is "Open",
  2281. * but requires a bit more attention. It is entered when
  2282. * we see some SACKs or dupacks. It is split of "Open"
  2283. * mainly to move some processing from fast path to slow one.
  2284. * "CWR" CWND was reduced due to some Congestion Notification event.
  2285. * It can be ECN, ICMP source quench, local device congestion.
  2286. * "Recovery" CWND was reduced, we are fast-retransmitting.
  2287. * "Loss" CWND was reduced due to RTO timeout or SACK reneging.
  2288. *
  2289. * tcp_fastretrans_alert() is entered:
  2290. * - each incoming ACK, if state is not "Open"
  2291. * - when arrived ACK is unusual, namely:
  2292. * * SACK
  2293. * * Duplicate ACK.
  2294. * * ECN ECE.
  2295. *
  2296. * Counting packets in flight is pretty simple.
  2297. *
  2298. * in_flight = packets_out - left_out + retrans_out
  2299. *
  2300. * packets_out is SND.NXT-SND.UNA counted in packets.
  2301. *
  2302. * retrans_out is number of retransmitted segments.
  2303. *
  2304. * left_out is number of segments left network, but not ACKed yet.
  2305. *
  2306. * left_out = sacked_out + lost_out
  2307. *
  2308. * sacked_out: Packets, which arrived to receiver out of order
  2309. * and hence not ACKed. With SACKs this number is simply
  2310. * amount of SACKed data. Even without SACKs
  2311. * it is easy to give pretty reliable estimate of this number,
  2312. * counting duplicate ACKs.
  2313. *
  2314. * lost_out: Packets lost by network. TCP has no explicit
  2315. * "loss notification" feedback from network (for now).
  2316. * It means that this number can be only _guessed_.
  2317. * Actually, it is the heuristics to predict lossage that
  2318. * distinguishes different algorithms.
  2319. *
  2320. * F.e. after RTO, when all the queue is considered as lost,
  2321. * lost_out = packets_out and in_flight = retrans_out.
  2322. *
  2323. * Essentially, we have now a few algorithms detecting
  2324. * lost packets.
  2325. *
  2326. * If the receiver supports SACK:
  2327. *
  2328. * RACK (RFC8985): RACK is a newer loss detection algorithm
  2329. * (2017-) that checks timing instead of counting DUPACKs.
  2330. * Essentially a packet is considered lost if it's not S/ACKed
  2331. * after RTT + reordering_window, where both metrics are
  2332. * dynamically measured and adjusted. This is implemented in
  2333. * tcp_rack_mark_lost.
  2334. *
  2335. * If the receiver does not support SACK:
  2336. *
  2337. * NewReno (RFC6582): in Recovery we assume that one segment
  2338. * is lost (classic Reno). While we are in Recovery and
  2339. * a partial ACK arrives, we assume that one more packet
  2340. * is lost (NewReno). This heuristics are the same in NewReno
  2341. * and SACK.
  2342. *
  2343. * The really tricky (and requiring careful tuning) part of the algorithm
  2344. * is hidden in the RACK code in tcp_recovery.c and tcp_xmit_retransmit_queue().
  2345. * The first determines the moment _when_ we should reduce CWND and,
  2346. * hence, slow down forward transmission. In fact, it determines the moment
  2347. * when we decide that hole is caused by loss, rather than by a reorder.
  2348. *
  2349. * tcp_xmit_retransmit_queue() decides, _what_ we should retransmit to fill
  2350. * holes, caused by lost packets.
  2351. *
  2352. * And the most logically complicated part of algorithm is undo
  2353. * heuristics. We detect false retransmits due to both too early
  2354. * fast retransmit (reordering) and underestimated RTO, analyzing
  2355. * timestamps and D-SACKs. When we detect that some segments were
  2356. * retransmitted by mistake and CWND reduction was wrong, we undo
  2357. * window reduction and abort recovery phase. This logic is hidden
  2358. * inside several functions named tcp_try_undo_<something>.
  2359. */
  2360. /* This function decides, when we should leave Disordered state
  2361. * and enter Recovery phase, reducing congestion window.
  2362. *
  2363. * Main question: may we further continue forward transmission
  2364. * with the same cwnd?
  2365. */
  2366. static bool tcp_time_to_recover(const struct tcp_sock *tp)
  2367. {
  2368. /* Has loss detection marked at least one packet lost? */
  2369. return tp->lost_out != 0;
  2370. }
  2371. static bool tcp_tsopt_ecr_before(const struct tcp_sock *tp, u32 when)
  2372. {
  2373. return tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr &&
  2374. before(tp->rx_opt.rcv_tsecr, when);
  2375. }
  2376. /* skb is spurious retransmitted if the returned timestamp echo
  2377. * reply is prior to the skb transmission time
  2378. */
  2379. static bool tcp_skb_spurious_retrans(const struct tcp_sock *tp,
  2380. const struct sk_buff *skb)
  2381. {
  2382. return (TCP_SKB_CB(skb)->sacked & TCPCB_RETRANS) &&
  2383. tcp_tsopt_ecr_before(tp, tcp_skb_timestamp_ts(tp->tcp_usec_ts, skb));
  2384. }
  2385. /* Nothing was retransmitted or returned timestamp is less
  2386. * than timestamp of the first retransmission.
  2387. */
  2388. static inline bool tcp_packet_delayed(const struct tcp_sock *tp)
  2389. {
  2390. const struct sock *sk = (const struct sock *)tp;
  2391. /* Received an echoed timestamp before the first retransmission? */
  2392. if (tp->retrans_stamp)
  2393. return tcp_tsopt_ecr_before(tp, tp->retrans_stamp);
  2394. /* We set tp->retrans_stamp upon the first retransmission of a loss
  2395. * recovery episode, so normally if tp->retrans_stamp is 0 then no
  2396. * retransmission has happened yet (likely due to TSQ, which can cause
  2397. * fast retransmits to be delayed). So if snd_una advanced while
  2398. * (tp->retrans_stamp is 0 then apparently a packet was merely delayed,
  2399. * not lost. But there are exceptions where we retransmit but then
  2400. * clear tp->retrans_stamp, so we check for those exceptions.
  2401. */
  2402. /* (1) For non-SACK connections, tcp_is_non_sack_preventing_reopen()
  2403. * clears tp->retrans_stamp when snd_una == high_seq.
  2404. */
  2405. if (!tcp_is_sack(tp) && !before(tp->snd_una, tp->high_seq))
  2406. return false;
  2407. /* (2) In TCP_SYN_SENT tcp_clean_rtx_queue() clears tp->retrans_stamp
  2408. * when setting FLAG_SYN_ACKED is set, even if the SYN was
  2409. * retransmitted.
  2410. */
  2411. if (sk->sk_state == TCP_SYN_SENT)
  2412. return false;
  2413. return true; /* tp->retrans_stamp is zero; no retransmit yet */
  2414. }
  2415. /* Undo procedures. */
  2416. /* We can clear retrans_stamp when there are no retransmissions in the
  2417. * window. It would seem that it is trivially available for us in
  2418. * tp->retrans_out, however, that kind of assumptions doesn't consider
  2419. * what will happen if errors occur when sending retransmission for the
  2420. * second time. ...It could the that such segment has only
  2421. * TCPCB_EVER_RETRANS set at the present time. It seems that checking
  2422. * the head skb is enough except for some reneging corner cases that
  2423. * are not worth the effort.
  2424. *
  2425. * Main reason for all this complexity is the fact that connection dying
  2426. * time now depends on the validity of the retrans_stamp, in particular,
  2427. * that successive retransmissions of a segment must not advance
  2428. * retrans_stamp under any conditions.
  2429. */
  2430. static bool tcp_any_retrans_done(const struct sock *sk)
  2431. {
  2432. const struct tcp_sock *tp = tcp_sk(sk);
  2433. struct sk_buff *skb;
  2434. if (tp->retrans_out)
  2435. return true;
  2436. skb = tcp_rtx_queue_head(sk);
  2437. if (unlikely(skb && TCP_SKB_CB(skb)->sacked & TCPCB_EVER_RETRANS))
  2438. return true;
  2439. return false;
  2440. }
  2441. /* If loss recovery is finished and there are no retransmits out in the
  2442. * network, then we clear retrans_stamp so that upon the next loss recovery
  2443. * retransmits_timed_out() and timestamp-undo are using the correct value.
  2444. */
  2445. static void tcp_retrans_stamp_cleanup(struct sock *sk)
  2446. {
  2447. if (!tcp_any_retrans_done(sk))
  2448. tcp_sk(sk)->retrans_stamp = 0;
  2449. }
  2450. static void DBGUNDO(struct sock *sk, const char *msg)
  2451. {
  2452. #if FASTRETRANS_DEBUG > 1
  2453. struct tcp_sock *tp = tcp_sk(sk);
  2454. struct inet_sock *inet = inet_sk(sk);
  2455. if (sk->sk_family == AF_INET) {
  2456. pr_debug("Undo %s %pI4/%u c%u l%u ss%u/%u p%u\n",
  2457. msg,
  2458. &inet->inet_daddr, ntohs(inet->inet_dport),
  2459. tcp_snd_cwnd(tp), tcp_left_out(tp),
  2460. tp->snd_ssthresh, tp->prior_ssthresh,
  2461. tp->packets_out);
  2462. }
  2463. #if IS_ENABLED(CONFIG_IPV6)
  2464. else if (sk->sk_family == AF_INET6) {
  2465. pr_debug("Undo %s %pI6/%u c%u l%u ss%u/%u p%u\n",
  2466. msg,
  2467. &sk->sk_v6_daddr, ntohs(inet->inet_dport),
  2468. tcp_snd_cwnd(tp), tcp_left_out(tp),
  2469. tp->snd_ssthresh, tp->prior_ssthresh,
  2470. tp->packets_out);
  2471. }
  2472. #endif
  2473. #endif
  2474. }
  2475. static void tcp_undo_cwnd_reduction(struct sock *sk, bool unmark_loss)
  2476. {
  2477. struct tcp_sock *tp = tcp_sk(sk);
  2478. if (unmark_loss) {
  2479. struct sk_buff *skb;
  2480. skb_rbtree_walk(skb, &sk->tcp_rtx_queue) {
  2481. TCP_SKB_CB(skb)->sacked &= ~TCPCB_LOST;
  2482. }
  2483. tp->lost_out = 0;
  2484. tcp_clear_all_retrans_hints(tp);
  2485. }
  2486. if (tp->prior_ssthresh) {
  2487. const struct inet_connection_sock *icsk = inet_csk(sk);
  2488. tcp_snd_cwnd_set(tp, icsk->icsk_ca_ops->undo_cwnd(sk));
  2489. if (tp->prior_ssthresh > tp->snd_ssthresh) {
  2490. tp->snd_ssthresh = tp->prior_ssthresh;
  2491. tcp_ecn_withdraw_cwr(tp);
  2492. }
  2493. }
  2494. tp->snd_cwnd_stamp = tcp_jiffies32;
  2495. tp->undo_marker = 0;
  2496. tp->rack.advanced = 1; /* Force RACK to re-exam losses */
  2497. }
  2498. static inline bool tcp_may_undo(const struct tcp_sock *tp)
  2499. {
  2500. return tp->undo_marker && (!tp->undo_retrans || tcp_packet_delayed(tp));
  2501. }
  2502. static bool tcp_is_non_sack_preventing_reopen(struct sock *sk)
  2503. {
  2504. struct tcp_sock *tp = tcp_sk(sk);
  2505. if (tp->snd_una == tp->high_seq && tcp_is_reno(tp)) {
  2506. /* Hold old state until something *above* high_seq
  2507. * is ACKed. For Reno it is MUST to prevent false
  2508. * fast retransmits (RFC2582). SACK TCP is safe. */
  2509. if (!tcp_any_retrans_done(sk))
  2510. tp->retrans_stamp = 0;
  2511. return true;
  2512. }
  2513. return false;
  2514. }
  2515. /* People celebrate: "We love our President!" */
  2516. static bool tcp_try_undo_recovery(struct sock *sk)
  2517. {
  2518. struct tcp_sock *tp = tcp_sk(sk);
  2519. if (tcp_may_undo(tp)) {
  2520. int mib_idx;
  2521. /* Happy end! We did not retransmit anything
  2522. * or our original transmission succeeded.
  2523. */
  2524. DBGUNDO(sk, inet_csk(sk)->icsk_ca_state == TCP_CA_Loss ? "loss" : "retrans");
  2525. tcp_undo_cwnd_reduction(sk, false);
  2526. if (inet_csk(sk)->icsk_ca_state == TCP_CA_Loss)
  2527. mib_idx = LINUX_MIB_TCPLOSSUNDO;
  2528. else
  2529. mib_idx = LINUX_MIB_TCPFULLUNDO;
  2530. NET_INC_STATS(sock_net(sk), mib_idx);
  2531. } else if (tp->rack.reo_wnd_persist) {
  2532. tp->rack.reo_wnd_persist--;
  2533. }
  2534. if (tcp_is_non_sack_preventing_reopen(sk))
  2535. return true;
  2536. tcp_set_ca_state(sk, TCP_CA_Open);
  2537. tp->is_sack_reneg = 0;
  2538. return false;
  2539. }
  2540. /* Try to undo cwnd reduction, because D-SACKs acked all retransmitted data */
  2541. static bool tcp_try_undo_dsack(struct sock *sk)
  2542. {
  2543. struct tcp_sock *tp = tcp_sk(sk);
  2544. if (tp->undo_marker && !tp->undo_retrans) {
  2545. tp->rack.reo_wnd_persist = min(TCP_RACK_RECOVERY_THRESH,
  2546. tp->rack.reo_wnd_persist + 1);
  2547. DBGUNDO(sk, "D-SACK");
  2548. tcp_undo_cwnd_reduction(sk, false);
  2549. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPDSACKUNDO);
  2550. return true;
  2551. }
  2552. return false;
  2553. }
  2554. /* Undo during loss recovery after partial ACK or using F-RTO. */
  2555. static bool tcp_try_undo_loss(struct sock *sk, bool frto_undo)
  2556. {
  2557. struct tcp_sock *tp = tcp_sk(sk);
  2558. if (frto_undo || tcp_may_undo(tp)) {
  2559. tcp_undo_cwnd_reduction(sk, true);
  2560. DBGUNDO(sk, "partial loss");
  2561. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPLOSSUNDO);
  2562. if (frto_undo)
  2563. NET_INC_STATS(sock_net(sk),
  2564. LINUX_MIB_TCPSPURIOUSRTOS);
  2565. WRITE_ONCE(inet_csk(sk)->icsk_retransmits, 0);
  2566. if (tcp_is_non_sack_preventing_reopen(sk))
  2567. return true;
  2568. if (frto_undo || tcp_is_sack(tp)) {
  2569. tcp_set_ca_state(sk, TCP_CA_Open);
  2570. tp->is_sack_reneg = 0;
  2571. }
  2572. return true;
  2573. }
  2574. return false;
  2575. }
  2576. /* The cwnd reduction in CWR and Recovery uses the PRR algorithm in RFC 6937.
  2577. * It computes the number of packets to send (sndcnt) based on packets newly
  2578. * delivered:
  2579. * 1) If the packets in flight is larger than ssthresh, PRR spreads the
  2580. * cwnd reductions across a full RTT.
  2581. * 2) Otherwise PRR uses packet conservation to send as much as delivered.
  2582. * But when SND_UNA is acked without further losses,
  2583. * slow starts cwnd up to ssthresh to speed up the recovery.
  2584. */
  2585. static void tcp_init_cwnd_reduction(struct sock *sk)
  2586. {
  2587. struct tcp_sock *tp = tcp_sk(sk);
  2588. tp->high_seq = tp->snd_nxt;
  2589. tp->tlp_high_seq = 0;
  2590. tp->snd_cwnd_cnt = 0;
  2591. tp->prior_cwnd = tcp_snd_cwnd(tp);
  2592. tp->prr_delivered = 0;
  2593. tp->prr_out = 0;
  2594. tp->snd_ssthresh = inet_csk(sk)->icsk_ca_ops->ssthresh(sk);
  2595. tcp_ecn_queue_cwr(tp);
  2596. }
  2597. void tcp_cwnd_reduction(struct sock *sk, int newly_acked_sacked, int newly_lost, int flag)
  2598. {
  2599. struct tcp_sock *tp = tcp_sk(sk);
  2600. int sndcnt = 0;
  2601. int delta = tp->snd_ssthresh - tcp_packets_in_flight(tp);
  2602. if (newly_acked_sacked <= 0 || WARN_ON_ONCE(!tp->prior_cwnd))
  2603. return;
  2604. trace_tcp_cwnd_reduction_tp(sk, newly_acked_sacked, newly_lost, flag);
  2605. tp->prr_delivered += newly_acked_sacked;
  2606. if (delta < 0) {
  2607. u64 dividend = (u64)tp->snd_ssthresh * tp->prr_delivered +
  2608. tp->prior_cwnd - 1;
  2609. sndcnt = div_u64(dividend, tp->prior_cwnd) - tp->prr_out;
  2610. } else {
  2611. sndcnt = max_t(int, tp->prr_delivered - tp->prr_out,
  2612. newly_acked_sacked);
  2613. if (flag & FLAG_SND_UNA_ADVANCED && !newly_lost)
  2614. sndcnt++;
  2615. sndcnt = min(delta, sndcnt);
  2616. }
  2617. /* Force a fast retransmit upon entering fast recovery */
  2618. sndcnt = max(sndcnt, (tp->prr_out ? 0 : 1));
  2619. tcp_snd_cwnd_set(tp, tcp_packets_in_flight(tp) + sndcnt);
  2620. }
  2621. static inline void tcp_end_cwnd_reduction(struct sock *sk)
  2622. {
  2623. struct tcp_sock *tp = tcp_sk(sk);
  2624. if (inet_csk(sk)->icsk_ca_ops->cong_control)
  2625. return;
  2626. /* Reset cwnd to ssthresh in CWR or Recovery (unless it's undone) */
  2627. if (tp->snd_ssthresh < TCP_INFINITE_SSTHRESH &&
  2628. (inet_csk(sk)->icsk_ca_state == TCP_CA_CWR || tp->undo_marker)) {
  2629. tcp_snd_cwnd_set(tp, tp->snd_ssthresh);
  2630. tp->snd_cwnd_stamp = tcp_jiffies32;
  2631. }
  2632. tcp_ca_event(sk, CA_EVENT_COMPLETE_CWR);
  2633. }
  2634. /* Enter CWR state. Disable cwnd undo since congestion is proven with ECN */
  2635. void tcp_enter_cwr(struct sock *sk)
  2636. {
  2637. struct tcp_sock *tp = tcp_sk(sk);
  2638. tp->prior_ssthresh = 0;
  2639. if (inet_csk(sk)->icsk_ca_state < TCP_CA_CWR) {
  2640. tp->undo_marker = 0;
  2641. tcp_init_cwnd_reduction(sk);
  2642. tcp_set_ca_state(sk, TCP_CA_CWR);
  2643. }
  2644. }
  2645. EXPORT_SYMBOL(tcp_enter_cwr);
  2646. static void tcp_try_keep_open(struct sock *sk)
  2647. {
  2648. struct tcp_sock *tp = tcp_sk(sk);
  2649. int state = TCP_CA_Open;
  2650. if (tcp_left_out(tp) || tcp_any_retrans_done(sk))
  2651. state = TCP_CA_Disorder;
  2652. if (inet_csk(sk)->icsk_ca_state != state) {
  2653. tcp_set_ca_state(sk, state);
  2654. tp->high_seq = tp->snd_nxt;
  2655. }
  2656. }
  2657. static void tcp_try_to_open(struct sock *sk, int flag)
  2658. {
  2659. struct tcp_sock *tp = tcp_sk(sk);
  2660. tcp_verify_left_out(tp);
  2661. if (!tcp_any_retrans_done(sk))
  2662. tp->retrans_stamp = 0;
  2663. if (flag & FLAG_ECE)
  2664. tcp_enter_cwr(sk);
  2665. if (inet_csk(sk)->icsk_ca_state != TCP_CA_CWR) {
  2666. tcp_try_keep_open(sk);
  2667. }
  2668. }
  2669. static void tcp_mtup_probe_failed(struct sock *sk)
  2670. {
  2671. struct inet_connection_sock *icsk = inet_csk(sk);
  2672. icsk->icsk_mtup.search_high = icsk->icsk_mtup.probe_size - 1;
  2673. icsk->icsk_mtup.probe_size = 0;
  2674. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMTUPFAIL);
  2675. }
  2676. static void tcp_mtup_probe_success(struct sock *sk)
  2677. {
  2678. struct tcp_sock *tp = tcp_sk(sk);
  2679. struct inet_connection_sock *icsk = inet_csk(sk);
  2680. u64 val;
  2681. tp->prior_ssthresh = tcp_current_ssthresh(sk);
  2682. val = (u64)tcp_snd_cwnd(tp) * tcp_mss_to_mtu(sk, tp->mss_cache);
  2683. do_div(val, icsk->icsk_mtup.probe_size);
  2684. DEBUG_NET_WARN_ON_ONCE((u32)val != val);
  2685. tcp_snd_cwnd_set(tp, max_t(u32, 1U, val));
  2686. tp->snd_cwnd_cnt = 0;
  2687. tp->snd_cwnd_stamp = tcp_jiffies32;
  2688. tp->snd_ssthresh = tcp_current_ssthresh(sk);
  2689. icsk->icsk_mtup.search_low = icsk->icsk_mtup.probe_size;
  2690. icsk->icsk_mtup.probe_size = 0;
  2691. tcp_sync_mss(sk, icsk->icsk_pmtu_cookie);
  2692. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMTUPSUCCESS);
  2693. }
  2694. /* Sometimes we deduce that packets have been dropped due to reasons other than
  2695. * congestion, like path MTU reductions or failed client TFO attempts. In these
  2696. * cases we call this function to retransmit as many packets as cwnd allows,
  2697. * without reducing cwnd. Given that retransmits will set retrans_stamp to a
  2698. * non-zero value (and may do so in a later calling context due to TSQ), we
  2699. * also enter CA_Loss so that we track when all retransmitted packets are ACKed
  2700. * and clear retrans_stamp when that happens (to ensure later recurring RTOs
  2701. * are using the correct retrans_stamp and don't declare ETIMEDOUT
  2702. * prematurely).
  2703. */
  2704. static void tcp_non_congestion_loss_retransmit(struct sock *sk)
  2705. {
  2706. const struct inet_connection_sock *icsk = inet_csk(sk);
  2707. struct tcp_sock *tp = tcp_sk(sk);
  2708. if (icsk->icsk_ca_state != TCP_CA_Loss) {
  2709. tp->high_seq = tp->snd_nxt;
  2710. tp->snd_ssthresh = tcp_current_ssthresh(sk);
  2711. tp->prior_ssthresh = 0;
  2712. tp->undo_marker = 0;
  2713. tcp_set_ca_state(sk, TCP_CA_Loss);
  2714. }
  2715. tcp_xmit_retransmit_queue(sk);
  2716. }
  2717. /* Do a simple retransmit without using the backoff mechanisms in
  2718. * tcp_timer. This is used for path mtu discovery.
  2719. * The socket is already locked here.
  2720. */
  2721. void tcp_simple_retransmit(struct sock *sk)
  2722. {
  2723. struct tcp_sock *tp = tcp_sk(sk);
  2724. struct sk_buff *skb;
  2725. int mss;
  2726. /* A fastopen SYN request is stored as two separate packets within
  2727. * the retransmit queue, this is done by tcp_send_syn_data().
  2728. * As a result simply checking the MSS of the frames in the queue
  2729. * will not work for the SYN packet.
  2730. *
  2731. * Us being here is an indication of a path MTU issue so we can
  2732. * assume that the fastopen SYN was lost and just mark all the
  2733. * frames in the retransmit queue as lost. We will use an MSS of
  2734. * -1 to mark all frames as lost, otherwise compute the current MSS.
  2735. */
  2736. if (tp->syn_data && sk->sk_state == TCP_SYN_SENT)
  2737. mss = -1;
  2738. else
  2739. mss = tcp_current_mss(sk);
  2740. skb_rbtree_walk(skb, &sk->tcp_rtx_queue) {
  2741. if (tcp_skb_seglen(skb) > mss)
  2742. tcp_mark_skb_lost(sk, skb);
  2743. }
  2744. if (!tp->lost_out)
  2745. return;
  2746. if (tcp_is_reno(tp))
  2747. tcp_limit_reno_sacked(tp);
  2748. tcp_verify_left_out(tp);
  2749. /* Don't muck with the congestion window here.
  2750. * Reason is that we do not increase amount of _data_
  2751. * in network, but units changed and effective
  2752. * cwnd/ssthresh really reduced now.
  2753. */
  2754. tcp_non_congestion_loss_retransmit(sk);
  2755. }
  2756. EXPORT_IPV6_MOD(tcp_simple_retransmit);
  2757. void tcp_enter_recovery(struct sock *sk, bool ece_ack)
  2758. {
  2759. struct tcp_sock *tp = tcp_sk(sk);
  2760. int mib_idx;
  2761. /* Start the clock with our fast retransmit, for undo and ETIMEDOUT. */
  2762. tcp_retrans_stamp_cleanup(sk);
  2763. if (tcp_is_reno(tp))
  2764. mib_idx = LINUX_MIB_TCPRENORECOVERY;
  2765. else
  2766. mib_idx = LINUX_MIB_TCPSACKRECOVERY;
  2767. NET_INC_STATS(sock_net(sk), mib_idx);
  2768. tp->prior_ssthresh = 0;
  2769. tcp_init_undo(tp);
  2770. if (!tcp_in_cwnd_reduction(sk)) {
  2771. if (!ece_ack)
  2772. tp->prior_ssthresh = tcp_current_ssthresh(sk);
  2773. tcp_init_cwnd_reduction(sk);
  2774. }
  2775. tcp_set_ca_state(sk, TCP_CA_Recovery);
  2776. }
  2777. static void tcp_update_rto_time(struct tcp_sock *tp)
  2778. {
  2779. if (tp->rto_stamp) {
  2780. tp->total_rto_time += tcp_time_stamp_ms(tp) - tp->rto_stamp;
  2781. tp->rto_stamp = 0;
  2782. }
  2783. }
  2784. /* Process an ACK in CA_Loss state. Move to CA_Open if lost data are
  2785. * recovered or spurious. Otherwise retransmits more on partial ACKs.
  2786. */
  2787. static void tcp_process_loss(struct sock *sk, int flag, int num_dupack,
  2788. int *rexmit)
  2789. {
  2790. struct tcp_sock *tp = tcp_sk(sk);
  2791. bool recovered = !before(tp->snd_una, tp->high_seq);
  2792. if ((flag & FLAG_SND_UNA_ADVANCED || rcu_access_pointer(tp->fastopen_rsk)) &&
  2793. tcp_try_undo_loss(sk, false))
  2794. return;
  2795. if (tp->frto) { /* F-RTO RFC5682 sec 3.1 (sack enhanced version). */
  2796. /* Step 3.b. A timeout is spurious if not all data are
  2797. * lost, i.e., never-retransmitted data are (s)acked.
  2798. */
  2799. if ((flag & FLAG_ORIG_SACK_ACKED) &&
  2800. tcp_try_undo_loss(sk, true))
  2801. return;
  2802. if (after(tp->snd_nxt, tp->high_seq)) {
  2803. if (flag & FLAG_DATA_SACKED || num_dupack)
  2804. tp->frto = 0; /* Step 3.a. loss was real */
  2805. } else if (flag & FLAG_SND_UNA_ADVANCED && !recovered) {
  2806. tp->high_seq = tp->snd_nxt;
  2807. /* Step 2.b. Try send new data (but deferred until cwnd
  2808. * is updated in tcp_ack()). Otherwise fall back to
  2809. * the conventional recovery.
  2810. */
  2811. if (!tcp_write_queue_empty(sk) &&
  2812. after(tcp_wnd_end(tp), tp->snd_nxt)) {
  2813. *rexmit = REXMIT_NEW;
  2814. return;
  2815. }
  2816. tp->frto = 0;
  2817. }
  2818. }
  2819. if (recovered) {
  2820. /* F-RTO RFC5682 sec 3.1 step 2.a and 1st part of step 3.a */
  2821. tcp_try_undo_recovery(sk);
  2822. return;
  2823. }
  2824. if (tcp_is_reno(tp)) {
  2825. /* A Reno DUPACK means new data in F-RTO step 2.b above are
  2826. * delivered. Lower inflight to clock out (re)transmissions.
  2827. */
  2828. if (after(tp->snd_nxt, tp->high_seq) && num_dupack)
  2829. tcp_add_reno_sack(sk, num_dupack, flag & FLAG_ECE);
  2830. else if (flag & FLAG_SND_UNA_ADVANCED)
  2831. tcp_reset_reno_sack(tp);
  2832. }
  2833. *rexmit = REXMIT_LOST;
  2834. }
  2835. /* Undo during fast recovery after partial ACK. */
  2836. static bool tcp_try_undo_partial(struct sock *sk, u32 prior_snd_una)
  2837. {
  2838. struct tcp_sock *tp = tcp_sk(sk);
  2839. if (tp->undo_marker && tcp_packet_delayed(tp)) {
  2840. /* Plain luck! Hole if filled with delayed
  2841. * packet, rather than with a retransmit. Check reordering.
  2842. */
  2843. tcp_check_sack_reordering(sk, prior_snd_una, 1);
  2844. /* We are getting evidence that the reordering degree is higher
  2845. * than we realized. If there are no retransmits out then we
  2846. * can undo. Otherwise we clock out new packets but do not
  2847. * mark more packets lost or retransmit more.
  2848. */
  2849. if (tp->retrans_out)
  2850. return true;
  2851. if (!tcp_any_retrans_done(sk))
  2852. tp->retrans_stamp = 0;
  2853. DBGUNDO(sk, "partial recovery");
  2854. tcp_undo_cwnd_reduction(sk, true);
  2855. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPPARTIALUNDO);
  2856. tcp_try_keep_open(sk);
  2857. }
  2858. return false;
  2859. }
  2860. static void tcp_identify_packet_loss(struct sock *sk, int *ack_flag)
  2861. {
  2862. struct tcp_sock *tp = tcp_sk(sk);
  2863. if (tcp_rtx_queue_empty(sk))
  2864. return;
  2865. if (unlikely(tcp_is_reno(tp))) {
  2866. tcp_newreno_mark_lost(sk, *ack_flag & FLAG_SND_UNA_ADVANCED);
  2867. } else {
  2868. u32 prior_retrans = tp->retrans_out;
  2869. if (tcp_rack_mark_lost(sk))
  2870. *ack_flag &= ~FLAG_SET_XMIT_TIMER;
  2871. if (prior_retrans > tp->retrans_out)
  2872. *ack_flag |= FLAG_LOST_RETRANS;
  2873. }
  2874. }
  2875. /* Process an event, which can update packets-in-flight not trivially.
  2876. * Main goal of this function is to calculate new estimate for left_out,
  2877. * taking into account both packets sitting in receiver's buffer and
  2878. * packets lost by network.
  2879. *
  2880. * Besides that it updates the congestion state when packet loss or ECN
  2881. * is detected. But it does not reduce the cwnd, it is done by the
  2882. * congestion control later.
  2883. *
  2884. * It does _not_ decide what to send, it is made in function
  2885. * tcp_xmit_retransmit_queue().
  2886. */
  2887. static void tcp_fastretrans_alert(struct sock *sk, const u32 prior_snd_una,
  2888. int num_dupack, int *ack_flag, int *rexmit)
  2889. {
  2890. struct inet_connection_sock *icsk = inet_csk(sk);
  2891. struct tcp_sock *tp = tcp_sk(sk);
  2892. int flag = *ack_flag;
  2893. bool ece_ack = flag & FLAG_ECE;
  2894. if (!tp->packets_out && tp->sacked_out)
  2895. tp->sacked_out = 0;
  2896. /* Now state machine starts.
  2897. * A. ECE, hence prohibit cwnd undoing, the reduction is required. */
  2898. if (ece_ack)
  2899. tp->prior_ssthresh = 0;
  2900. /* B. In all the states check for reneging SACKs. */
  2901. if (tcp_check_sack_reneging(sk, ack_flag))
  2902. return;
  2903. /* C. Check consistency of the current state. */
  2904. tcp_verify_left_out(tp);
  2905. /* D. Check state exit conditions. State can be terminated
  2906. * when high_seq is ACKed. */
  2907. if (icsk->icsk_ca_state == TCP_CA_Open) {
  2908. WARN_ON(tp->retrans_out != 0 && !tp->syn_data);
  2909. tp->retrans_stamp = 0;
  2910. } else if (!before(tp->snd_una, tp->high_seq)) {
  2911. switch (icsk->icsk_ca_state) {
  2912. case TCP_CA_CWR:
  2913. /* CWR is to be held something *above* high_seq
  2914. * is ACKed for CWR bit to reach receiver. */
  2915. if (tp->snd_una != tp->high_seq) {
  2916. tcp_end_cwnd_reduction(sk);
  2917. tcp_set_ca_state(sk, TCP_CA_Open);
  2918. }
  2919. break;
  2920. case TCP_CA_Recovery:
  2921. if (tcp_is_reno(tp))
  2922. tcp_reset_reno_sack(tp);
  2923. if (tcp_try_undo_recovery(sk))
  2924. return;
  2925. tcp_end_cwnd_reduction(sk);
  2926. break;
  2927. }
  2928. }
  2929. /* E. Process state. */
  2930. switch (icsk->icsk_ca_state) {
  2931. case TCP_CA_Recovery:
  2932. if (!(flag & FLAG_SND_UNA_ADVANCED)) {
  2933. if (tcp_is_reno(tp))
  2934. tcp_add_reno_sack(sk, num_dupack, ece_ack);
  2935. } else if (tcp_try_undo_partial(sk, prior_snd_una))
  2936. return;
  2937. if (tcp_try_undo_dsack(sk))
  2938. tcp_try_to_open(sk, flag);
  2939. tcp_identify_packet_loss(sk, ack_flag);
  2940. if (icsk->icsk_ca_state != TCP_CA_Recovery) {
  2941. if (!tcp_time_to_recover(tp))
  2942. return;
  2943. /* Undo reverts the recovery state. If loss is evident,
  2944. * starts a new recovery (e.g. reordering then loss);
  2945. */
  2946. tcp_enter_recovery(sk, ece_ack);
  2947. }
  2948. break;
  2949. case TCP_CA_Loss:
  2950. tcp_process_loss(sk, flag, num_dupack, rexmit);
  2951. if (icsk->icsk_ca_state != TCP_CA_Loss)
  2952. tcp_update_rto_time(tp);
  2953. tcp_identify_packet_loss(sk, ack_flag);
  2954. if (!(icsk->icsk_ca_state == TCP_CA_Open ||
  2955. (*ack_flag & FLAG_LOST_RETRANS)))
  2956. return;
  2957. /* Change state if cwnd is undone or retransmits are lost */
  2958. fallthrough;
  2959. default:
  2960. if (tcp_is_reno(tp)) {
  2961. if (flag & FLAG_SND_UNA_ADVANCED)
  2962. tcp_reset_reno_sack(tp);
  2963. tcp_add_reno_sack(sk, num_dupack, ece_ack);
  2964. }
  2965. if (icsk->icsk_ca_state <= TCP_CA_Disorder)
  2966. tcp_try_undo_dsack(sk);
  2967. tcp_identify_packet_loss(sk, ack_flag);
  2968. if (!tcp_time_to_recover(tp)) {
  2969. tcp_try_to_open(sk, flag);
  2970. return;
  2971. }
  2972. /* MTU probe failure: don't reduce cwnd */
  2973. if (icsk->icsk_ca_state < TCP_CA_CWR &&
  2974. icsk->icsk_mtup.probe_size &&
  2975. tp->snd_una == tp->mtu_probe.probe_seq_start) {
  2976. tcp_mtup_probe_failed(sk);
  2977. /* Restores the reduction we did in tcp_mtup_probe() */
  2978. tcp_snd_cwnd_set(tp, tcp_snd_cwnd(tp) + 1);
  2979. tcp_simple_retransmit(sk);
  2980. return;
  2981. }
  2982. /* Otherwise enter Recovery state */
  2983. tcp_enter_recovery(sk, ece_ack);
  2984. }
  2985. *rexmit = REXMIT_LOST;
  2986. }
  2987. static void tcp_update_rtt_min(struct sock *sk, u32 rtt_us, const int flag)
  2988. {
  2989. u32 wlen = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_min_rtt_wlen) * HZ;
  2990. struct tcp_sock *tp = tcp_sk(sk);
  2991. if ((flag & FLAG_ACK_MAYBE_DELAYED) && rtt_us > tcp_min_rtt(tp)) {
  2992. /* If the remote keeps returning delayed ACKs, eventually
  2993. * the min filter would pick it up and overestimate the
  2994. * prop. delay when it expires. Skip suspected delayed ACKs.
  2995. */
  2996. return;
  2997. }
  2998. minmax_running_min(&tp->rtt_min, wlen, tcp_jiffies32,
  2999. rtt_us ? : jiffies_to_usecs(1));
  3000. }
  3001. static bool tcp_ack_update_rtt(struct sock *sk, const int flag,
  3002. long seq_rtt_us, long sack_rtt_us,
  3003. long ca_rtt_us, struct rate_sample *rs)
  3004. {
  3005. const struct tcp_sock *tp = tcp_sk(sk);
  3006. /* Prefer RTT measured from ACK's timing to TS-ECR. This is because
  3007. * broken middle-boxes or peers may corrupt TS-ECR fields. But
  3008. * Karn's algorithm forbids taking RTT if some retransmitted data
  3009. * is acked (RFC6298).
  3010. */
  3011. if (seq_rtt_us < 0)
  3012. seq_rtt_us = sack_rtt_us;
  3013. /* RTTM Rule: A TSecr value received in a segment is used to
  3014. * update the averaged RTT measurement only if the segment
  3015. * acknowledges some new data, i.e., only if it advances the
  3016. * left edge of the send window.
  3017. * See draft-ietf-tcplw-high-performance-00, section 3.3.
  3018. */
  3019. if (seq_rtt_us < 0 && tp->rx_opt.saw_tstamp &&
  3020. tp->rx_opt.rcv_tsecr && flag & FLAG_ACKED)
  3021. seq_rtt_us = ca_rtt_us = tcp_rtt_tsopt_us(tp, 1);
  3022. rs->rtt_us = ca_rtt_us; /* RTT of last (S)ACKed packet (or -1) */
  3023. if (seq_rtt_us < 0)
  3024. return false;
  3025. /* ca_rtt_us >= 0 is counting on the invariant that ca_rtt_us is
  3026. * always taken together with ACK, SACK, or TS-opts. Any negative
  3027. * values will be skipped with the seq_rtt_us < 0 check above.
  3028. */
  3029. tcp_update_rtt_min(sk, ca_rtt_us, flag);
  3030. tcp_rtt_estimator(sk, seq_rtt_us);
  3031. tcp_set_rto(sk);
  3032. /* RFC6298: only reset backoff on valid RTT measurement. */
  3033. inet_csk(sk)->icsk_backoff = 0;
  3034. return true;
  3035. }
  3036. /* Compute time elapsed between (last) SYNACK and the ACK completing 3WHS. */
  3037. void tcp_synack_rtt_meas(struct sock *sk, struct request_sock *req)
  3038. {
  3039. struct rate_sample rs;
  3040. long rtt_us = -1L;
  3041. if (req && !req->num_retrans && tcp_rsk(req)->snt_synack)
  3042. rtt_us = tcp_stamp_us_delta(tcp_clock_us(), tcp_rsk(req)->snt_synack);
  3043. tcp_ack_update_rtt(sk, FLAG_SYN_ACKED, rtt_us, -1L, rtt_us, &rs);
  3044. }
  3045. static void tcp_cong_avoid(struct sock *sk, u32 ack, u32 acked)
  3046. {
  3047. const struct inet_connection_sock *icsk = inet_csk(sk);
  3048. icsk->icsk_ca_ops->cong_avoid(sk, ack, acked);
  3049. tcp_sk(sk)->snd_cwnd_stamp = tcp_jiffies32;
  3050. }
  3051. /* Restart timer after forward progress on connection.
  3052. * RFC2988 recommends to restart timer to now+rto.
  3053. */
  3054. void tcp_rearm_rto(struct sock *sk)
  3055. {
  3056. const struct inet_connection_sock *icsk = inet_csk(sk);
  3057. struct tcp_sock *tp = tcp_sk(sk);
  3058. /* If the retrans timer is currently being used by Fast Open
  3059. * for SYN-ACK retrans purpose, stay put.
  3060. */
  3061. if (rcu_access_pointer(tp->fastopen_rsk))
  3062. return;
  3063. if (!tp->packets_out) {
  3064. inet_csk_clear_xmit_timer(sk, ICSK_TIME_RETRANS);
  3065. } else {
  3066. u32 rto = inet_csk(sk)->icsk_rto;
  3067. /* Offset the time elapsed after installing regular RTO */
  3068. if (icsk->icsk_pending == ICSK_TIME_REO_TIMEOUT ||
  3069. icsk->icsk_pending == ICSK_TIME_LOSS_PROBE) {
  3070. s64 delta_us = tcp_rto_delta_us(sk);
  3071. /* delta_us may not be positive if the socket is locked
  3072. * when the retrans timer fires and is rescheduled.
  3073. */
  3074. rto = usecs_to_jiffies(max_t(int, delta_us, 1));
  3075. }
  3076. tcp_reset_xmit_timer(sk, ICSK_TIME_RETRANS, rto, true);
  3077. }
  3078. }
  3079. /* Try to schedule a loss probe; if that doesn't work, then schedule an RTO. */
  3080. static void tcp_set_xmit_timer(struct sock *sk)
  3081. {
  3082. if (!tcp_schedule_loss_probe(sk, true))
  3083. tcp_rearm_rto(sk);
  3084. }
  3085. /* If we get here, the whole TSO packet has not been acked. */
  3086. static u32 tcp_tso_acked(struct sock *sk, struct sk_buff *skb)
  3087. {
  3088. struct tcp_sock *tp = tcp_sk(sk);
  3089. u32 packets_acked;
  3090. BUG_ON(!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una));
  3091. packets_acked = tcp_skb_pcount(skb);
  3092. if (tcp_trim_head(sk, skb, tp->snd_una - TCP_SKB_CB(skb)->seq))
  3093. return 0;
  3094. packets_acked -= tcp_skb_pcount(skb);
  3095. if (packets_acked) {
  3096. BUG_ON(tcp_skb_pcount(skb) == 0);
  3097. BUG_ON(!before(TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq));
  3098. }
  3099. return packets_acked;
  3100. }
  3101. static void tcp_ack_tstamp(struct sock *sk, struct sk_buff *skb,
  3102. const struct sk_buff *ack_skb, u32 prior_snd_una)
  3103. {
  3104. const struct skb_shared_info *shinfo;
  3105. /* Avoid cache line misses to get skb_shinfo() and shinfo->tx_flags */
  3106. if (likely(!TCP_SKB_CB(skb)->txstamp_ack))
  3107. return;
  3108. shinfo = skb_shinfo(skb);
  3109. if (!before(shinfo->tskey, prior_snd_una) &&
  3110. before(shinfo->tskey, tcp_sk(sk)->snd_una)) {
  3111. tcp_skb_tsorted_save(skb) {
  3112. __skb_tstamp_tx(skb, ack_skb, NULL, sk, SCM_TSTAMP_ACK);
  3113. } tcp_skb_tsorted_restore(skb);
  3114. }
  3115. }
  3116. /* Remove acknowledged frames from the retransmission queue. If our packet
  3117. * is before the ack sequence we can discard it as it's confirmed to have
  3118. * arrived at the other end.
  3119. */
  3120. static int tcp_clean_rtx_queue(struct sock *sk, const struct sk_buff *ack_skb,
  3121. u32 prior_fack, u32 prior_snd_una,
  3122. struct tcp_sacktag_state *sack, bool ece_ack)
  3123. {
  3124. const struct inet_connection_sock *icsk = inet_csk(sk);
  3125. u64 first_ackt, last_ackt;
  3126. struct tcp_sock *tp = tcp_sk(sk);
  3127. u32 prior_sacked = tp->sacked_out;
  3128. u32 reord = tp->snd_nxt; /* lowest acked un-retx un-sacked seq */
  3129. struct sk_buff *skb, *next;
  3130. bool fully_acked = true;
  3131. long sack_rtt_us = -1L;
  3132. long seq_rtt_us = -1L;
  3133. long ca_rtt_us = -1L;
  3134. u32 pkts_acked = 0;
  3135. bool rtt_update;
  3136. int flag = 0;
  3137. first_ackt = 0;
  3138. for (skb = skb_rb_first(&sk->tcp_rtx_queue); skb; skb = next) {
  3139. struct tcp_skb_cb *scb = TCP_SKB_CB(skb);
  3140. const u32 start_seq = scb->seq;
  3141. u8 sacked = scb->sacked;
  3142. u32 acked_pcount;
  3143. /* Determine how many packets and what bytes were acked, tso and else */
  3144. if (after(scb->end_seq, tp->snd_una)) {
  3145. if (tcp_skb_pcount(skb) == 1 ||
  3146. !after(tp->snd_una, scb->seq))
  3147. break;
  3148. acked_pcount = tcp_tso_acked(sk, skb);
  3149. if (!acked_pcount)
  3150. break;
  3151. fully_acked = false;
  3152. } else {
  3153. acked_pcount = tcp_skb_pcount(skb);
  3154. }
  3155. if (unlikely(sacked & TCPCB_RETRANS)) {
  3156. if (sacked & TCPCB_SACKED_RETRANS)
  3157. tp->retrans_out -= acked_pcount;
  3158. flag |= FLAG_RETRANS_DATA_ACKED;
  3159. } else if (!(sacked & TCPCB_SACKED_ACKED)) {
  3160. last_ackt = tcp_skb_timestamp_us(skb);
  3161. WARN_ON_ONCE(last_ackt == 0);
  3162. if (!first_ackt)
  3163. first_ackt = last_ackt;
  3164. if (before(start_seq, reord))
  3165. reord = start_seq;
  3166. if (!after(scb->end_seq, tp->high_seq))
  3167. flag |= FLAG_ORIG_SACK_ACKED;
  3168. }
  3169. if (sacked & TCPCB_SACKED_ACKED) {
  3170. tp->sacked_out -= acked_pcount;
  3171. /* snd_una delta covers these skbs */
  3172. sack->delivered_bytes -= skb->len;
  3173. } else if (tcp_is_sack(tp)) {
  3174. tcp_count_delivered(tp, acked_pcount, ece_ack);
  3175. if (!tcp_skb_spurious_retrans(tp, skb))
  3176. tcp_rack_advance(tp, sacked, scb->end_seq,
  3177. tcp_skb_timestamp_us(skb));
  3178. }
  3179. if (sacked & TCPCB_LOST)
  3180. tp->lost_out -= acked_pcount;
  3181. tp->packets_out -= acked_pcount;
  3182. pkts_acked += acked_pcount;
  3183. tcp_rate_skb_delivered(sk, skb, sack->rate);
  3184. /* Initial outgoing SYN's get put onto the write_queue
  3185. * just like anything else we transmit. It is not
  3186. * true data, and if we misinform our callers that
  3187. * this ACK acks real data, we will erroneously exit
  3188. * connection startup slow start one packet too
  3189. * quickly. This is severely frowned upon behavior.
  3190. */
  3191. if (likely(!(scb->tcp_flags & TCPHDR_SYN))) {
  3192. flag |= FLAG_DATA_ACKED;
  3193. } else {
  3194. flag |= FLAG_SYN_ACKED;
  3195. tp->retrans_stamp = 0;
  3196. }
  3197. if (!fully_acked)
  3198. break;
  3199. tcp_ack_tstamp(sk, skb, ack_skb, prior_snd_una);
  3200. next = skb_rb_next(skb);
  3201. if (unlikely(skb == tp->retransmit_skb_hint))
  3202. tp->retransmit_skb_hint = NULL;
  3203. tcp_highest_sack_replace(sk, skb, next);
  3204. tcp_rtx_queue_unlink_and_free(skb, sk);
  3205. }
  3206. if (!skb)
  3207. tcp_chrono_stop(sk, TCP_CHRONO_BUSY);
  3208. if (likely(between(tp->snd_up, prior_snd_una, tp->snd_una)))
  3209. tp->snd_up = tp->snd_una;
  3210. if (skb) {
  3211. tcp_ack_tstamp(sk, skb, ack_skb, prior_snd_una);
  3212. if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED)
  3213. flag |= FLAG_SACK_RENEGING;
  3214. }
  3215. if (likely(first_ackt) && !(flag & FLAG_RETRANS_DATA_ACKED)) {
  3216. seq_rtt_us = tcp_stamp_us_delta(tp->tcp_mstamp, first_ackt);
  3217. ca_rtt_us = tcp_stamp_us_delta(tp->tcp_mstamp, last_ackt);
  3218. if (pkts_acked == 1 && fully_acked && !prior_sacked &&
  3219. (tp->snd_una - prior_snd_una) < tp->mss_cache &&
  3220. sack->rate->prior_delivered + 1 == tp->delivered &&
  3221. !(flag & (FLAG_CA_ALERT | FLAG_SYN_ACKED))) {
  3222. /* Conservatively mark a delayed ACK. It's typically
  3223. * from a lone runt packet over the round trip to
  3224. * a receiver w/o out-of-order or CE events.
  3225. */
  3226. flag |= FLAG_ACK_MAYBE_DELAYED;
  3227. }
  3228. }
  3229. if (sack->first_sackt) {
  3230. sack_rtt_us = tcp_stamp_us_delta(tp->tcp_mstamp, sack->first_sackt);
  3231. ca_rtt_us = tcp_stamp_us_delta(tp->tcp_mstamp, sack->last_sackt);
  3232. }
  3233. rtt_update = tcp_ack_update_rtt(sk, flag, seq_rtt_us, sack_rtt_us,
  3234. ca_rtt_us, sack->rate);
  3235. if (flag & FLAG_ACKED) {
  3236. flag |= FLAG_SET_XMIT_TIMER; /* set TLP or RTO timer */
  3237. if (unlikely(icsk->icsk_mtup.probe_size &&
  3238. !after(tp->mtu_probe.probe_seq_end, tp->snd_una))) {
  3239. tcp_mtup_probe_success(sk);
  3240. }
  3241. if (tcp_is_reno(tp)) {
  3242. tcp_remove_reno_sacks(sk, pkts_acked, ece_ack);
  3243. /* If any of the cumulatively ACKed segments was
  3244. * retransmitted, non-SACK case cannot confirm that
  3245. * progress was due to original transmission due to
  3246. * lack of TCPCB_SACKED_ACKED bits even if some of
  3247. * the packets may have been never retransmitted.
  3248. */
  3249. if (flag & FLAG_RETRANS_DATA_ACKED)
  3250. flag &= ~FLAG_ORIG_SACK_ACKED;
  3251. } else {
  3252. /* Non-retransmitted hole got filled? That's reordering */
  3253. if (before(reord, prior_fack))
  3254. tcp_check_sack_reordering(sk, reord, 0);
  3255. }
  3256. sack->delivered_bytes = (skb ?
  3257. TCP_SKB_CB(skb)->seq : tp->snd_una) -
  3258. prior_snd_una;
  3259. } else if (skb && rtt_update && sack_rtt_us >= 0 &&
  3260. sack_rtt_us > tcp_stamp_us_delta(tp->tcp_mstamp,
  3261. tcp_skb_timestamp_us(skb))) {
  3262. /* Do not re-arm RTO if the sack RTT is measured from data sent
  3263. * after when the head was last (re)transmitted. Otherwise the
  3264. * timeout may continue to extend in loss recovery.
  3265. */
  3266. flag |= FLAG_SET_XMIT_TIMER; /* set TLP or RTO timer */
  3267. }
  3268. if (icsk->icsk_ca_ops->pkts_acked) {
  3269. struct ack_sample sample = { .pkts_acked = pkts_acked,
  3270. .rtt_us = sack->rate->rtt_us };
  3271. sample.in_flight = tp->mss_cache *
  3272. (tp->delivered - sack->rate->prior_delivered);
  3273. icsk->icsk_ca_ops->pkts_acked(sk, &sample);
  3274. }
  3275. #if FASTRETRANS_DEBUG > 0
  3276. WARN_ON((int)tp->sacked_out < 0);
  3277. WARN_ON((int)tp->lost_out < 0);
  3278. WARN_ON((int)tp->retrans_out < 0);
  3279. if (!tp->packets_out && tcp_is_sack(tp)) {
  3280. icsk = inet_csk(sk);
  3281. if (tp->lost_out) {
  3282. pr_debug("Leak l=%u %d\n",
  3283. tp->lost_out, icsk->icsk_ca_state);
  3284. tp->lost_out = 0;
  3285. }
  3286. if (tp->sacked_out) {
  3287. pr_debug("Leak s=%u %d\n",
  3288. tp->sacked_out, icsk->icsk_ca_state);
  3289. tp->sacked_out = 0;
  3290. }
  3291. if (tp->retrans_out) {
  3292. pr_debug("Leak r=%u %d\n",
  3293. tp->retrans_out, icsk->icsk_ca_state);
  3294. tp->retrans_out = 0;
  3295. }
  3296. }
  3297. #endif
  3298. return flag;
  3299. }
  3300. static void tcp_ack_probe(struct sock *sk)
  3301. {
  3302. struct inet_connection_sock *icsk = inet_csk(sk);
  3303. struct sk_buff *head = tcp_send_head(sk);
  3304. const struct tcp_sock *tp = tcp_sk(sk);
  3305. /* Was it a usable window open? */
  3306. if (!head)
  3307. return;
  3308. if (!after(TCP_SKB_CB(head)->end_seq, tcp_wnd_end(tp))) {
  3309. icsk->icsk_backoff = 0;
  3310. icsk->icsk_probes_tstamp = 0;
  3311. inet_csk_clear_xmit_timer(sk, ICSK_TIME_PROBE0);
  3312. /* Socket must be waked up by subsequent tcp_data_snd_check().
  3313. * This function is not for random using!
  3314. */
  3315. } else {
  3316. unsigned long when = tcp_probe0_when(sk, tcp_rto_max(sk));
  3317. when = tcp_clamp_probe0_to_user_timeout(sk, when);
  3318. tcp_reset_xmit_timer(sk, ICSK_TIME_PROBE0, when, true);
  3319. }
  3320. }
  3321. static inline bool tcp_ack_is_dubious(const struct sock *sk, const int flag)
  3322. {
  3323. return !(flag & FLAG_NOT_DUP) || (flag & FLAG_CA_ALERT) ||
  3324. inet_csk(sk)->icsk_ca_state != TCP_CA_Open;
  3325. }
  3326. /* Decide wheather to run the increase function of congestion control. */
  3327. static inline bool tcp_may_raise_cwnd(const struct sock *sk, const int flag)
  3328. {
  3329. /* If reordering is high then always grow cwnd whenever data is
  3330. * delivered regardless of its ordering. Otherwise stay conservative
  3331. * and only grow cwnd on in-order delivery (RFC5681). A stretched ACK w/
  3332. * new SACK or ECE mark may first advance cwnd here and later reduce
  3333. * cwnd in tcp_fastretrans_alert() based on more states.
  3334. */
  3335. if (tcp_sk(sk)->reordering >
  3336. READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_reordering))
  3337. return flag & FLAG_FORWARD_PROGRESS;
  3338. return flag & FLAG_DATA_ACKED;
  3339. }
  3340. /* The "ultimate" congestion control function that aims to replace the rigid
  3341. * cwnd increase and decrease control (tcp_cong_avoid,tcp_*cwnd_reduction).
  3342. * It's called toward the end of processing an ACK with precise rate
  3343. * information. All transmission or retransmission are delayed afterwards.
  3344. */
  3345. static void tcp_cong_control(struct sock *sk, u32 ack, u32 acked_sacked,
  3346. int flag, const struct rate_sample *rs)
  3347. {
  3348. const struct inet_connection_sock *icsk = inet_csk(sk);
  3349. if (icsk->icsk_ca_ops->cong_control) {
  3350. icsk->icsk_ca_ops->cong_control(sk, ack, flag, rs);
  3351. return;
  3352. }
  3353. if (tcp_in_cwnd_reduction(sk)) {
  3354. /* Reduce cwnd if state mandates */
  3355. tcp_cwnd_reduction(sk, acked_sacked, rs->losses, flag);
  3356. } else if (tcp_may_raise_cwnd(sk, flag)) {
  3357. /* Advance cwnd if state allows */
  3358. tcp_cong_avoid(sk, ack, acked_sacked);
  3359. }
  3360. tcp_update_pacing_rate(sk);
  3361. }
  3362. /* Check that window update is acceptable.
  3363. * The function assumes that snd_una<=ack<=snd_next.
  3364. */
  3365. static inline bool tcp_may_update_window(const struct tcp_sock *tp,
  3366. const u32 ack, const u32 ack_seq,
  3367. const u32 nwin)
  3368. {
  3369. return after(ack, tp->snd_una) ||
  3370. after(ack_seq, tp->snd_wl1) ||
  3371. (ack_seq == tp->snd_wl1 && (nwin > tp->snd_wnd || !nwin));
  3372. }
  3373. static void tcp_snd_sne_update(struct tcp_sock *tp, u32 ack)
  3374. {
  3375. #ifdef CONFIG_TCP_AO
  3376. struct tcp_ao_info *ao;
  3377. if (!static_branch_unlikely(&tcp_ao_needed.key))
  3378. return;
  3379. ao = rcu_dereference_protected(tp->ao_info,
  3380. lockdep_sock_is_held((struct sock *)tp));
  3381. if (ao && ack < tp->snd_una) {
  3382. ao->snd_sne++;
  3383. trace_tcp_ao_snd_sne_update((struct sock *)tp, ao->snd_sne);
  3384. }
  3385. #endif
  3386. }
  3387. /* If we update tp->snd_una, also update tp->bytes_acked */
  3388. static void tcp_snd_una_update(struct tcp_sock *tp, u32 ack)
  3389. {
  3390. u32 delta = ack - tp->snd_una;
  3391. sock_owned_by_me((struct sock *)tp);
  3392. tp->bytes_acked += delta;
  3393. tcp_snd_sne_update(tp, ack);
  3394. tp->snd_una = ack;
  3395. }
  3396. static void tcp_rcv_sne_update(struct tcp_sock *tp, u32 seq)
  3397. {
  3398. #ifdef CONFIG_TCP_AO
  3399. struct tcp_ao_info *ao;
  3400. if (!static_branch_unlikely(&tcp_ao_needed.key))
  3401. return;
  3402. ao = rcu_dereference_protected(tp->ao_info,
  3403. lockdep_sock_is_held((struct sock *)tp));
  3404. if (ao && seq < tp->rcv_nxt) {
  3405. ao->rcv_sne++;
  3406. trace_tcp_ao_rcv_sne_update((struct sock *)tp, ao->rcv_sne);
  3407. }
  3408. #endif
  3409. }
  3410. /* If we update tp->rcv_nxt, also update tp->bytes_received */
  3411. static void tcp_rcv_nxt_update(struct tcp_sock *tp, u32 seq)
  3412. {
  3413. u32 delta = seq - tp->rcv_nxt;
  3414. sock_owned_by_me((struct sock *)tp);
  3415. tp->bytes_received += delta;
  3416. tcp_rcv_sne_update(tp, seq);
  3417. WRITE_ONCE(tp->rcv_nxt, seq);
  3418. }
  3419. /* Update our send window.
  3420. *
  3421. * Window update algorithm, described in RFC793/RFC1122 (used in linux-2.2
  3422. * and in FreeBSD. NetBSD's one is even worse.) is wrong.
  3423. */
  3424. static int tcp_ack_update_window(struct sock *sk, const struct sk_buff *skb, u32 ack,
  3425. u32 ack_seq)
  3426. {
  3427. struct tcp_sock *tp = tcp_sk(sk);
  3428. int flag = 0;
  3429. u32 nwin = ntohs(tcp_hdr(skb)->window);
  3430. if (likely(!tcp_hdr(skb)->syn))
  3431. nwin <<= tp->rx_opt.snd_wscale;
  3432. if (tcp_may_update_window(tp, ack, ack_seq, nwin)) {
  3433. flag |= FLAG_WIN_UPDATE;
  3434. tcp_update_wl(tp, ack_seq);
  3435. if (tp->snd_wnd != nwin) {
  3436. tp->snd_wnd = nwin;
  3437. /* Note, it is the only place, where
  3438. * fast path is recovered for sending TCP.
  3439. */
  3440. tp->pred_flags = 0;
  3441. tcp_fast_path_check(sk);
  3442. if (!tcp_write_queue_empty(sk))
  3443. tcp_slow_start_after_idle_check(sk);
  3444. if (nwin > tp->max_window) {
  3445. tp->max_window = nwin;
  3446. tcp_sync_mss(sk, inet_csk(sk)->icsk_pmtu_cookie);
  3447. }
  3448. }
  3449. }
  3450. tcp_snd_una_update(tp, ack);
  3451. return flag;
  3452. }
  3453. static bool __tcp_oow_rate_limited(struct net *net, int mib_idx,
  3454. u32 *last_oow_ack_time)
  3455. {
  3456. /* Paired with the WRITE_ONCE() in this function. */
  3457. u32 val = READ_ONCE(*last_oow_ack_time);
  3458. if (val) {
  3459. s32 elapsed = (s32)(tcp_jiffies32 - val);
  3460. if (0 <= elapsed &&
  3461. elapsed < READ_ONCE(net->ipv4.sysctl_tcp_invalid_ratelimit)) {
  3462. NET_INC_STATS(net, mib_idx);
  3463. return true; /* rate-limited: don't send yet! */
  3464. }
  3465. }
  3466. /* Paired with the prior READ_ONCE() and with itself,
  3467. * as we might be lockless.
  3468. */
  3469. WRITE_ONCE(*last_oow_ack_time, tcp_jiffies32);
  3470. return false; /* not rate-limited: go ahead, send dupack now! */
  3471. }
  3472. /* Return true if we're currently rate-limiting out-of-window ACKs and
  3473. * thus shouldn't send a dupack right now. We rate-limit dupacks in
  3474. * response to out-of-window SYNs or ACKs to mitigate ACK loops or DoS
  3475. * attacks that send repeated SYNs or ACKs for the same connection. To
  3476. * do this, we do not send a duplicate SYNACK or ACK if the remote
  3477. * endpoint is sending out-of-window SYNs or pure ACKs at a high rate.
  3478. */
  3479. bool tcp_oow_rate_limited(struct net *net, const struct sk_buff *skb,
  3480. int mib_idx, u32 *last_oow_ack_time)
  3481. {
  3482. /* Data packets without SYNs are not likely part of an ACK loop. */
  3483. if ((TCP_SKB_CB(skb)->seq != TCP_SKB_CB(skb)->end_seq) &&
  3484. !tcp_hdr(skb)->syn)
  3485. return false;
  3486. return __tcp_oow_rate_limited(net, mib_idx, last_oow_ack_time);
  3487. }
  3488. static void tcp_send_ack_reflect_ect(struct sock *sk, bool accecn_reflector)
  3489. {
  3490. struct tcp_sock *tp = tcp_sk(sk);
  3491. u16 flags = 0;
  3492. if (accecn_reflector)
  3493. flags = tcp_accecn_reflector_flags(tp->syn_ect_rcv);
  3494. __tcp_send_ack(sk, tp->rcv_nxt, flags);
  3495. }
  3496. /* RFC 5961 7 [ACK Throttling] */
  3497. static void tcp_send_challenge_ack(struct sock *sk, bool accecn_reflector)
  3498. {
  3499. struct tcp_sock *tp = tcp_sk(sk);
  3500. struct net *net = sock_net(sk);
  3501. u32 count, now, ack_limit;
  3502. /* First check our per-socket dupack rate limit. */
  3503. if (__tcp_oow_rate_limited(net,
  3504. LINUX_MIB_TCPACKSKIPPEDCHALLENGE,
  3505. &tp->last_oow_ack_time))
  3506. return;
  3507. ack_limit = READ_ONCE(net->ipv4.sysctl_tcp_challenge_ack_limit);
  3508. if (ack_limit == INT_MAX)
  3509. goto send_ack;
  3510. /* Then check host-wide RFC 5961 rate limit. */
  3511. now = jiffies / HZ;
  3512. if (now != READ_ONCE(net->ipv4.tcp_challenge_timestamp)) {
  3513. u32 half = (ack_limit + 1) >> 1;
  3514. WRITE_ONCE(net->ipv4.tcp_challenge_timestamp, now);
  3515. WRITE_ONCE(net->ipv4.tcp_challenge_count,
  3516. get_random_u32_inclusive(half, ack_limit + half - 1));
  3517. }
  3518. count = READ_ONCE(net->ipv4.tcp_challenge_count);
  3519. if (count > 0) {
  3520. WRITE_ONCE(net->ipv4.tcp_challenge_count, count - 1);
  3521. send_ack:
  3522. NET_INC_STATS(net, LINUX_MIB_TCPCHALLENGEACK);
  3523. tcp_send_ack_reflect_ect(sk, accecn_reflector);
  3524. }
  3525. }
  3526. static void tcp_store_ts_recent(struct tcp_sock *tp)
  3527. {
  3528. tp->rx_opt.ts_recent = tp->rx_opt.rcv_tsval;
  3529. tp->rx_opt.ts_recent_stamp = ktime_get_seconds();
  3530. }
  3531. static int __tcp_replace_ts_recent(struct tcp_sock *tp, s32 tstamp_delta)
  3532. {
  3533. tcp_store_ts_recent(tp);
  3534. return tstamp_delta > 0 ? FLAG_TS_PROGRESS : 0;
  3535. }
  3536. static int tcp_replace_ts_recent(struct tcp_sock *tp, u32 seq)
  3537. {
  3538. s32 delta;
  3539. if (tp->rx_opt.saw_tstamp && !after(seq, tp->rcv_wup)) {
  3540. /* PAWS bug workaround wrt. ACK frames, the PAWS discard
  3541. * extra check below makes sure this can only happen
  3542. * for pure ACK frames. -DaveM
  3543. *
  3544. * Not only, also it occurs for expired timestamps.
  3545. */
  3546. if (tcp_paws_check(&tp->rx_opt, 0)) {
  3547. delta = tp->rx_opt.rcv_tsval - tp->rx_opt.ts_recent;
  3548. return __tcp_replace_ts_recent(tp, delta);
  3549. }
  3550. }
  3551. return 0;
  3552. }
  3553. /* This routine deals with acks during a TLP episode and ends an episode by
  3554. * resetting tlp_high_seq. Ref: TLP algorithm in RFC8985
  3555. */
  3556. static void tcp_process_tlp_ack(struct sock *sk, u32 ack, int flag)
  3557. {
  3558. struct tcp_sock *tp = tcp_sk(sk);
  3559. if (before(ack, tp->tlp_high_seq))
  3560. return;
  3561. if (!tp->tlp_retrans) {
  3562. /* TLP of new data has been acknowledged */
  3563. tp->tlp_high_seq = 0;
  3564. } else if (flag & FLAG_DSACK_TLP) {
  3565. /* This DSACK means original and TLP probe arrived; no loss */
  3566. tp->tlp_high_seq = 0;
  3567. } else if (after(ack, tp->tlp_high_seq)) {
  3568. /* ACK advances: there was a loss, so reduce cwnd. Reset
  3569. * tlp_high_seq in tcp_init_cwnd_reduction()
  3570. */
  3571. tcp_init_cwnd_reduction(sk);
  3572. tcp_set_ca_state(sk, TCP_CA_CWR);
  3573. tcp_end_cwnd_reduction(sk);
  3574. tcp_try_keep_open(sk);
  3575. NET_INC_STATS(sock_net(sk),
  3576. LINUX_MIB_TCPLOSSPROBERECOVERY);
  3577. } else if (!(flag & (FLAG_SND_UNA_ADVANCED |
  3578. FLAG_NOT_DUP | FLAG_DATA_SACKED))) {
  3579. /* Pure dupack: original and TLP probe arrived; no loss */
  3580. tp->tlp_high_seq = 0;
  3581. }
  3582. }
  3583. static void tcp_in_ack_event(struct sock *sk, int flag)
  3584. {
  3585. const struct inet_connection_sock *icsk = inet_csk(sk);
  3586. if (icsk->icsk_ca_ops->in_ack_event) {
  3587. u32 ack_ev_flags = 0;
  3588. if (flag & FLAG_WIN_UPDATE)
  3589. ack_ev_flags |= CA_ACK_WIN_UPDATE;
  3590. if (flag & FLAG_SLOWPATH) {
  3591. ack_ev_flags |= CA_ACK_SLOWPATH;
  3592. if (flag & FLAG_ECE)
  3593. ack_ev_flags |= CA_ACK_ECE;
  3594. }
  3595. icsk->icsk_ca_ops->in_ack_event(sk, ack_ev_flags);
  3596. }
  3597. }
  3598. /* Congestion control has updated the cwnd already. So if we're in
  3599. * loss recovery then now we do any new sends (for FRTO) or
  3600. * retransmits (for CA_Loss or CA_recovery) that make sense.
  3601. */
  3602. static void tcp_xmit_recovery(struct sock *sk, int rexmit)
  3603. {
  3604. struct tcp_sock *tp = tcp_sk(sk);
  3605. if (rexmit == REXMIT_NONE || sk->sk_state == TCP_SYN_SENT)
  3606. return;
  3607. if (unlikely(rexmit == REXMIT_NEW)) {
  3608. __tcp_push_pending_frames(sk, tcp_current_mss(sk),
  3609. TCP_NAGLE_OFF);
  3610. if (after(tp->snd_nxt, tp->high_seq))
  3611. return;
  3612. tp->frto = 0;
  3613. }
  3614. tcp_xmit_retransmit_queue(sk);
  3615. }
  3616. /* Returns the number of packets newly acked or sacked by the current ACK */
  3617. static u32 tcp_newly_delivered(struct sock *sk, u32 prior_delivered,
  3618. u32 ecn_count, int flag)
  3619. {
  3620. const struct net *net = sock_net(sk);
  3621. struct tcp_sock *tp = tcp_sk(sk);
  3622. u32 delivered;
  3623. delivered = tp->delivered - prior_delivered;
  3624. NET_ADD_STATS(net, LINUX_MIB_TCPDELIVERED, delivered);
  3625. if (flag & FLAG_ECE) {
  3626. if (tcp_ecn_mode_rfc3168(tp))
  3627. ecn_count = delivered;
  3628. NET_ADD_STATS(net, LINUX_MIB_TCPDELIVEREDCE, ecn_count);
  3629. }
  3630. return delivered;
  3631. }
  3632. /* Updates the RACK's reo_wnd based on DSACK and no. of recoveries.
  3633. *
  3634. * If a DSACK is received that seems like it may have been due to reordering
  3635. * triggering fast recovery, increment reo_wnd by min_rtt/4 (upper bounded
  3636. * by srtt), since there is possibility that spurious retransmission was
  3637. * due to reordering delay longer than reo_wnd.
  3638. *
  3639. * Persist the current reo_wnd value for TCP_RACK_RECOVERY_THRESH (16)
  3640. * no. of successful recoveries (accounts for full DSACK-based loss
  3641. * recovery undo). After that, reset it to default (min_rtt/4).
  3642. *
  3643. * At max, reo_wnd is incremented only once per rtt. So that the new
  3644. * DSACK on which we are reacting, is due to the spurious retx (approx)
  3645. * after the reo_wnd has been updated last time.
  3646. *
  3647. * reo_wnd is tracked in terms of steps (of min_rtt/4), rather than
  3648. * absolute value to account for change in rtt.
  3649. */
  3650. static void tcp_rack_update_reo_wnd(struct sock *sk, struct rate_sample *rs)
  3651. {
  3652. struct tcp_sock *tp = tcp_sk(sk);
  3653. if ((READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_recovery) &
  3654. TCP_RACK_STATIC_REO_WND) ||
  3655. !rs->prior_delivered)
  3656. return;
  3657. /* Disregard DSACK if a rtt has not passed since we adjusted reo_wnd */
  3658. if (before(rs->prior_delivered, tp->rack.last_delivered))
  3659. tp->rack.dsack_seen = 0;
  3660. /* Adjust the reo_wnd if update is pending */
  3661. if (tp->rack.dsack_seen) {
  3662. tp->rack.reo_wnd_steps = min_t(u32, 0xFF,
  3663. tp->rack.reo_wnd_steps + 1);
  3664. tp->rack.dsack_seen = 0;
  3665. tp->rack.last_delivered = tp->delivered;
  3666. tp->rack.reo_wnd_persist = TCP_RACK_RECOVERY_THRESH;
  3667. } else if (!tp->rack.reo_wnd_persist) {
  3668. tp->rack.reo_wnd_steps = 1;
  3669. }
  3670. }
  3671. /* This routine deals with incoming acks, but not outgoing ones. */
  3672. static int tcp_ack(struct sock *sk, const struct sk_buff *skb, int flag)
  3673. {
  3674. struct inet_connection_sock *icsk = inet_csk(sk);
  3675. struct tcp_sock *tp = tcp_sk(sk);
  3676. struct tcp_sacktag_state sack_state;
  3677. struct rate_sample rs = { .prior_delivered = 0 };
  3678. u32 prior_snd_una = tp->snd_una;
  3679. bool is_sack_reneg = tp->is_sack_reneg;
  3680. u32 ack_seq = TCP_SKB_CB(skb)->seq;
  3681. u32 ack = TCP_SKB_CB(skb)->ack_seq;
  3682. int num_dupack = 0;
  3683. int prior_packets = tp->packets_out;
  3684. u32 delivered = tp->delivered;
  3685. u32 lost = tp->lost;
  3686. int rexmit = REXMIT_NONE; /* Flag to (re)transmit to recover losses */
  3687. u32 ecn_count = 0; /* Did we receive ECE/an AccECN ACE update? */
  3688. u32 prior_fack;
  3689. sack_state.first_sackt = 0;
  3690. sack_state.rate = &rs;
  3691. sack_state.sack_delivered = 0;
  3692. sack_state.delivered_bytes = 0;
  3693. /* We very likely will need to access rtx queue. */
  3694. prefetch(sk->tcp_rtx_queue.rb_node);
  3695. /* If the ack is older than previous acks
  3696. * then we can probably ignore it.
  3697. */
  3698. if (before(ack, prior_snd_una)) {
  3699. u32 max_window;
  3700. /* do not accept ACK for bytes we never sent. */
  3701. max_window = min_t(u64, tp->max_window, tp->bytes_acked);
  3702. /* RFC 5961 5.2 [Blind Data Injection Attack].[Mitigation] */
  3703. if (before(ack, prior_snd_una - max_window)) {
  3704. if (!(flag & FLAG_NO_CHALLENGE_ACK))
  3705. tcp_send_challenge_ack(sk, false);
  3706. return -SKB_DROP_REASON_TCP_TOO_OLD_ACK;
  3707. }
  3708. goto old_ack;
  3709. }
  3710. /* If the ack includes data we haven't sent yet, discard
  3711. * this segment (RFC793 Section 3.9).
  3712. */
  3713. if (after(ack, tp->snd_nxt))
  3714. return -SKB_DROP_REASON_TCP_ACK_UNSENT_DATA;
  3715. if (after(ack, prior_snd_una)) {
  3716. flag |= FLAG_SND_UNA_ADVANCED;
  3717. WRITE_ONCE(icsk->icsk_retransmits, 0);
  3718. #if IS_ENABLED(CONFIG_TLS_DEVICE)
  3719. if (static_branch_unlikely(&clean_acked_data_enabled.key))
  3720. if (tp->tcp_clean_acked)
  3721. tp->tcp_clean_acked(sk, ack);
  3722. #endif
  3723. }
  3724. prior_fack = tcp_is_sack(tp) ? tcp_highest_sack_seq(tp) : tp->snd_una;
  3725. rs.prior_in_flight = tcp_packets_in_flight(tp);
  3726. /* ts_recent update must be made after we are sure that the packet
  3727. * is in window.
  3728. */
  3729. if (flag & FLAG_UPDATE_TS_RECENT)
  3730. flag |= tcp_replace_ts_recent(tp, TCP_SKB_CB(skb)->seq);
  3731. if ((flag & (FLAG_SLOWPATH | FLAG_SND_UNA_ADVANCED)) ==
  3732. FLAG_SND_UNA_ADVANCED) {
  3733. /* Window is constant, pure forward advance.
  3734. * No more checks are required.
  3735. * Note, we use the fact that SND.UNA>=SND.WL2.
  3736. */
  3737. tcp_update_wl(tp, ack_seq);
  3738. tcp_snd_una_update(tp, ack);
  3739. flag |= FLAG_WIN_UPDATE;
  3740. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPHPACKS);
  3741. } else {
  3742. if (ack_seq != TCP_SKB_CB(skb)->end_seq)
  3743. flag |= FLAG_DATA;
  3744. else
  3745. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPPUREACKS);
  3746. flag |= tcp_ack_update_window(sk, skb, ack, ack_seq);
  3747. if (TCP_SKB_CB(skb)->sacked)
  3748. flag |= tcp_sacktag_write_queue(sk, skb, prior_snd_una,
  3749. &sack_state);
  3750. if (tcp_ecn_rcv_ecn_echo(tp, tcp_hdr(skb)))
  3751. flag |= FLAG_ECE;
  3752. if (sack_state.sack_delivered)
  3753. tcp_count_delivered(tp, sack_state.sack_delivered,
  3754. flag & FLAG_ECE);
  3755. }
  3756. /* This is a deviation from RFC3168 since it states that:
  3757. * "When the TCP data sender is ready to set the CWR bit after reducing
  3758. * the congestion window, it SHOULD set the CWR bit only on the first
  3759. * new data packet that it transmits."
  3760. * We accept CWR on pure ACKs to be more robust
  3761. * with widely-deployed TCP implementations that do this.
  3762. */
  3763. tcp_ecn_accept_cwr(sk, skb);
  3764. /* We passed data and got it acked, remove any soft error
  3765. * log. Something worked...
  3766. */
  3767. if (READ_ONCE(sk->sk_err_soft))
  3768. WRITE_ONCE(sk->sk_err_soft, 0);
  3769. WRITE_ONCE(icsk->icsk_probes_out, 0);
  3770. tp->rcv_tstamp = tcp_jiffies32;
  3771. if (!prior_packets)
  3772. goto no_queue;
  3773. /* See if we can take anything off of the retransmit queue. */
  3774. flag |= tcp_clean_rtx_queue(sk, skb, prior_fack, prior_snd_una,
  3775. &sack_state, flag & FLAG_ECE);
  3776. tcp_rack_update_reo_wnd(sk, &rs);
  3777. if (tcp_ecn_mode_accecn(tp))
  3778. ecn_count = tcp_accecn_process(sk, skb,
  3779. tp->delivered - delivered,
  3780. sack_state.delivered_bytes,
  3781. &flag);
  3782. tcp_in_ack_event(sk, flag);
  3783. if (unlikely(tp->tlp_high_seq))
  3784. tcp_process_tlp_ack(sk, ack, flag);
  3785. if (tcp_ack_is_dubious(sk, flag)) {
  3786. if (!(flag & (FLAG_SND_UNA_ADVANCED |
  3787. FLAG_NOT_DUP | FLAG_DSACKING_ACK))) {
  3788. num_dupack = 1;
  3789. /* Consider if pure acks were aggregated in tcp_add_backlog() */
  3790. if (!(flag & FLAG_DATA))
  3791. num_dupack = max_t(u16, 1, skb_shinfo(skb)->gso_segs);
  3792. }
  3793. tcp_fastretrans_alert(sk, prior_snd_una, num_dupack, &flag,
  3794. &rexmit);
  3795. }
  3796. /* If needed, reset TLP/RTO timer when RACK doesn't set. */
  3797. if (flag & FLAG_SET_XMIT_TIMER)
  3798. tcp_set_xmit_timer(sk);
  3799. if ((flag & FLAG_FORWARD_PROGRESS) || !(flag & FLAG_NOT_DUP))
  3800. sk_dst_confirm(sk);
  3801. delivered = tcp_newly_delivered(sk, delivered, ecn_count, flag);
  3802. lost = tp->lost - lost; /* freshly marked lost */
  3803. rs.is_ack_delayed = !!(flag & FLAG_ACK_MAYBE_DELAYED);
  3804. tcp_rate_gen(sk, delivered, lost, is_sack_reneg, sack_state.rate);
  3805. tcp_cong_control(sk, ack, delivered, flag, sack_state.rate);
  3806. tcp_xmit_recovery(sk, rexmit);
  3807. return 1;
  3808. no_queue:
  3809. if (tcp_ecn_mode_accecn(tp))
  3810. ecn_count = tcp_accecn_process(sk, skb,
  3811. tp->delivered - delivered,
  3812. sack_state.delivered_bytes,
  3813. &flag);
  3814. tcp_in_ack_event(sk, flag);
  3815. /* If data was DSACKed, see if we can undo a cwnd reduction. */
  3816. if (flag & FLAG_DSACKING_ACK) {
  3817. tcp_fastretrans_alert(sk, prior_snd_una, num_dupack, &flag,
  3818. &rexmit);
  3819. tcp_newly_delivered(sk, delivered, ecn_count, flag);
  3820. }
  3821. /* If this ack opens up a zero window, clear backoff. It was
  3822. * being used to time the probes, and is probably far higher than
  3823. * it needs to be for normal retransmission.
  3824. */
  3825. tcp_ack_probe(sk);
  3826. if (unlikely(tp->tlp_high_seq))
  3827. tcp_process_tlp_ack(sk, ack, flag);
  3828. return 1;
  3829. old_ack:
  3830. /* If data was SACKed, tag it and see if we should send more data.
  3831. * If data was DSACKed, see if we can undo a cwnd reduction.
  3832. */
  3833. if (TCP_SKB_CB(skb)->sacked) {
  3834. flag |= tcp_sacktag_write_queue(sk, skb, prior_snd_una,
  3835. &sack_state);
  3836. tcp_fastretrans_alert(sk, prior_snd_una, num_dupack, &flag,
  3837. &rexmit);
  3838. tcp_newly_delivered(sk, delivered, ecn_count, flag);
  3839. tcp_xmit_recovery(sk, rexmit);
  3840. }
  3841. return 0;
  3842. }
  3843. static void tcp_parse_fastopen_option(int len, const unsigned char *cookie,
  3844. bool syn, struct tcp_fastopen_cookie *foc,
  3845. bool exp_opt)
  3846. {
  3847. /* Valid only in SYN or SYN-ACK with an even length. */
  3848. if (!foc || !syn || len < 0 || (len & 1))
  3849. return;
  3850. if (len >= TCP_FASTOPEN_COOKIE_MIN &&
  3851. len <= TCP_FASTOPEN_COOKIE_MAX)
  3852. memcpy(foc->val, cookie, len);
  3853. else if (len != 0)
  3854. len = -1;
  3855. foc->len = len;
  3856. foc->exp = exp_opt;
  3857. }
  3858. static bool smc_parse_options(const struct tcphdr *th,
  3859. struct tcp_options_received *opt_rx,
  3860. const unsigned char *ptr,
  3861. int opsize)
  3862. {
  3863. #if IS_ENABLED(CONFIG_SMC)
  3864. if (static_branch_unlikely(&tcp_have_smc)) {
  3865. if (th->syn && !(opsize & 1) &&
  3866. opsize >= TCPOLEN_EXP_SMC_BASE &&
  3867. get_unaligned_be32(ptr) == TCPOPT_SMC_MAGIC) {
  3868. opt_rx->smc_ok = 1;
  3869. return true;
  3870. }
  3871. }
  3872. #endif
  3873. return false;
  3874. }
  3875. /* Try to parse the MSS option from the TCP header. Return 0 on failure, clamped
  3876. * value on success.
  3877. */
  3878. u16 tcp_parse_mss_option(const struct tcphdr *th, u16 user_mss)
  3879. {
  3880. const unsigned char *ptr = (const unsigned char *)(th + 1);
  3881. int length = (th->doff * 4) - sizeof(struct tcphdr);
  3882. u16 mss = 0;
  3883. while (length > 0) {
  3884. int opcode = *ptr++;
  3885. int opsize;
  3886. switch (opcode) {
  3887. case TCPOPT_EOL:
  3888. return mss;
  3889. case TCPOPT_NOP: /* Ref: RFC 793 section 3.1 */
  3890. length--;
  3891. continue;
  3892. default:
  3893. if (length < 2)
  3894. return mss;
  3895. opsize = *ptr++;
  3896. if (opsize < 2) /* "silly options" */
  3897. return mss;
  3898. if (opsize > length)
  3899. return mss; /* fail on partial options */
  3900. if (opcode == TCPOPT_MSS && opsize == TCPOLEN_MSS) {
  3901. u16 in_mss = get_unaligned_be16(ptr);
  3902. if (in_mss) {
  3903. if (user_mss && user_mss < in_mss)
  3904. in_mss = user_mss;
  3905. mss = in_mss;
  3906. }
  3907. }
  3908. ptr += opsize - 2;
  3909. length -= opsize;
  3910. }
  3911. }
  3912. return mss;
  3913. }
  3914. /* Look for tcp options. Normally only called on SYN and SYNACK packets.
  3915. * But, this can also be called on packets in the established flow when
  3916. * the fast version below fails.
  3917. */
  3918. void tcp_parse_options(const struct net *net,
  3919. const struct sk_buff *skb,
  3920. struct tcp_options_received *opt_rx, int estab,
  3921. struct tcp_fastopen_cookie *foc)
  3922. {
  3923. const unsigned char *ptr;
  3924. const struct tcphdr *th = tcp_hdr(skb);
  3925. int length = (th->doff * 4) - sizeof(struct tcphdr);
  3926. ptr = (const unsigned char *)(th + 1);
  3927. opt_rx->saw_tstamp = 0;
  3928. opt_rx->accecn = 0;
  3929. opt_rx->saw_unknown = 0;
  3930. while (length > 0) {
  3931. int opcode = *ptr++;
  3932. int opsize;
  3933. switch (opcode) {
  3934. case TCPOPT_EOL:
  3935. return;
  3936. case TCPOPT_NOP: /* Ref: RFC 793 section 3.1 */
  3937. length--;
  3938. continue;
  3939. default:
  3940. if (length < 2)
  3941. return;
  3942. opsize = *ptr++;
  3943. if (opsize < 2) /* "silly options" */
  3944. return;
  3945. if (opsize > length)
  3946. return; /* don't parse partial options */
  3947. switch (opcode) {
  3948. case TCPOPT_MSS:
  3949. if (opsize == TCPOLEN_MSS && th->syn && !estab) {
  3950. u16 in_mss = get_unaligned_be16(ptr);
  3951. if (in_mss) {
  3952. if (opt_rx->user_mss &&
  3953. opt_rx->user_mss < in_mss)
  3954. in_mss = opt_rx->user_mss;
  3955. opt_rx->mss_clamp = in_mss;
  3956. }
  3957. }
  3958. break;
  3959. case TCPOPT_WINDOW:
  3960. if (opsize == TCPOLEN_WINDOW && th->syn &&
  3961. !estab && READ_ONCE(net->ipv4.sysctl_tcp_window_scaling)) {
  3962. __u8 snd_wscale = *(__u8 *)ptr;
  3963. opt_rx->wscale_ok = 1;
  3964. if (snd_wscale > TCP_MAX_WSCALE) {
  3965. net_info_ratelimited("%s: Illegal window scaling value %d > %u received\n",
  3966. __func__,
  3967. snd_wscale,
  3968. TCP_MAX_WSCALE);
  3969. snd_wscale = TCP_MAX_WSCALE;
  3970. }
  3971. opt_rx->snd_wscale = snd_wscale;
  3972. }
  3973. break;
  3974. case TCPOPT_TIMESTAMP:
  3975. if ((opsize == TCPOLEN_TIMESTAMP) &&
  3976. ((estab && opt_rx->tstamp_ok) ||
  3977. (!estab && READ_ONCE(net->ipv4.sysctl_tcp_timestamps)))) {
  3978. opt_rx->saw_tstamp = 1;
  3979. opt_rx->rcv_tsval = get_unaligned_be32(ptr);
  3980. opt_rx->rcv_tsecr = get_unaligned_be32(ptr + 4);
  3981. }
  3982. break;
  3983. case TCPOPT_SACK_PERM:
  3984. if (opsize == TCPOLEN_SACK_PERM && th->syn &&
  3985. !estab && READ_ONCE(net->ipv4.sysctl_tcp_sack)) {
  3986. opt_rx->sack_ok = TCP_SACK_SEEN;
  3987. tcp_sack_reset(opt_rx);
  3988. }
  3989. break;
  3990. case TCPOPT_SACK:
  3991. if ((opsize >= (TCPOLEN_SACK_BASE + TCPOLEN_SACK_PERBLOCK)) &&
  3992. !((opsize - TCPOLEN_SACK_BASE) % TCPOLEN_SACK_PERBLOCK) &&
  3993. opt_rx->sack_ok) {
  3994. TCP_SKB_CB(skb)->sacked = (ptr - 2) - (unsigned char *)th;
  3995. }
  3996. break;
  3997. #ifdef CONFIG_TCP_MD5SIG
  3998. case TCPOPT_MD5SIG:
  3999. /* The MD5 Hash has already been
  4000. * checked (see tcp_v{4,6}_rcv()).
  4001. */
  4002. break;
  4003. #endif
  4004. #ifdef CONFIG_TCP_AO
  4005. case TCPOPT_AO:
  4006. /* TCP AO has already been checked
  4007. * (see tcp_inbound_ao_hash()).
  4008. */
  4009. break;
  4010. #endif
  4011. case TCPOPT_FASTOPEN:
  4012. tcp_parse_fastopen_option(
  4013. opsize - TCPOLEN_FASTOPEN_BASE,
  4014. ptr, th->syn, foc, false);
  4015. break;
  4016. case TCPOPT_ACCECN0:
  4017. case TCPOPT_ACCECN1:
  4018. /* Save offset of AccECN option in TCP header */
  4019. opt_rx->accecn = (ptr - 2) - (__u8 *)th;
  4020. break;
  4021. case TCPOPT_EXP:
  4022. /* Fast Open option shares code 254 using a
  4023. * 16 bits magic number.
  4024. */
  4025. if (opsize >= TCPOLEN_EXP_FASTOPEN_BASE &&
  4026. get_unaligned_be16(ptr) ==
  4027. TCPOPT_FASTOPEN_MAGIC) {
  4028. tcp_parse_fastopen_option(opsize -
  4029. TCPOLEN_EXP_FASTOPEN_BASE,
  4030. ptr + 2, th->syn, foc, true);
  4031. break;
  4032. }
  4033. if (smc_parse_options(th, opt_rx, ptr, opsize))
  4034. break;
  4035. opt_rx->saw_unknown = 1;
  4036. break;
  4037. default:
  4038. opt_rx->saw_unknown = 1;
  4039. }
  4040. ptr += opsize-2;
  4041. length -= opsize;
  4042. }
  4043. }
  4044. }
  4045. EXPORT_SYMBOL(tcp_parse_options);
  4046. static bool tcp_parse_aligned_timestamp(struct tcp_sock *tp, const struct tcphdr *th)
  4047. {
  4048. const __be32 *ptr = (const __be32 *)(th + 1);
  4049. if (*ptr == htonl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16)
  4050. | (TCPOPT_TIMESTAMP << 8) | TCPOLEN_TIMESTAMP)) {
  4051. tp->rx_opt.saw_tstamp = 1;
  4052. ++ptr;
  4053. tp->rx_opt.rcv_tsval = ntohl(*ptr);
  4054. ++ptr;
  4055. if (*ptr)
  4056. tp->rx_opt.rcv_tsecr = ntohl(*ptr) - tp->tsoffset;
  4057. else
  4058. tp->rx_opt.rcv_tsecr = 0;
  4059. return true;
  4060. }
  4061. return false;
  4062. }
  4063. /* Fast parse options. This hopes to only see timestamps.
  4064. * If it is wrong it falls back on tcp_parse_options().
  4065. */
  4066. static bool tcp_fast_parse_options(const struct net *net,
  4067. const struct sk_buff *skb,
  4068. const struct tcphdr *th, struct tcp_sock *tp)
  4069. {
  4070. /* In the spirit of fast parsing, compare doff directly to constant
  4071. * values. Because equality is used, short doff can be ignored here.
  4072. */
  4073. if (th->doff == (sizeof(*th) / 4)) {
  4074. tp->rx_opt.saw_tstamp = 0;
  4075. tp->rx_opt.accecn = 0;
  4076. return false;
  4077. } else if (tp->rx_opt.tstamp_ok &&
  4078. th->doff == ((sizeof(*th) + TCPOLEN_TSTAMP_ALIGNED) / 4)) {
  4079. if (tcp_parse_aligned_timestamp(tp, th)) {
  4080. tp->rx_opt.accecn = 0;
  4081. return true;
  4082. }
  4083. }
  4084. tcp_parse_options(net, skb, &tp->rx_opt, 1, NULL);
  4085. if (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr)
  4086. tp->rx_opt.rcv_tsecr -= tp->tsoffset;
  4087. return true;
  4088. }
  4089. #if defined(CONFIG_TCP_MD5SIG) || defined(CONFIG_TCP_AO)
  4090. /*
  4091. * Parse Signature options
  4092. */
  4093. int tcp_do_parse_auth_options(const struct tcphdr *th,
  4094. const u8 **md5_hash, const u8 **ao_hash)
  4095. {
  4096. int length = (th->doff << 2) - sizeof(*th);
  4097. const u8 *ptr = (const u8 *)(th + 1);
  4098. unsigned int minlen = TCPOLEN_MD5SIG;
  4099. if (IS_ENABLED(CONFIG_TCP_AO))
  4100. minlen = sizeof(struct tcp_ao_hdr) + 1;
  4101. *md5_hash = NULL;
  4102. *ao_hash = NULL;
  4103. /* If not enough data remaining, we can short cut */
  4104. while (length >= minlen) {
  4105. int opcode = *ptr++;
  4106. int opsize;
  4107. switch (opcode) {
  4108. case TCPOPT_EOL:
  4109. return 0;
  4110. case TCPOPT_NOP:
  4111. length--;
  4112. continue;
  4113. default:
  4114. opsize = *ptr++;
  4115. if (opsize < 2 || opsize > length)
  4116. return -EINVAL;
  4117. if (opcode == TCPOPT_MD5SIG) {
  4118. if (opsize != TCPOLEN_MD5SIG)
  4119. return -EINVAL;
  4120. if (unlikely(*md5_hash || *ao_hash))
  4121. return -EEXIST;
  4122. *md5_hash = ptr;
  4123. } else if (opcode == TCPOPT_AO) {
  4124. if (opsize <= sizeof(struct tcp_ao_hdr))
  4125. return -EINVAL;
  4126. if (unlikely(*md5_hash || *ao_hash))
  4127. return -EEXIST;
  4128. *ao_hash = ptr;
  4129. }
  4130. }
  4131. ptr += opsize - 2;
  4132. length -= opsize;
  4133. }
  4134. return 0;
  4135. }
  4136. EXPORT_SYMBOL(tcp_do_parse_auth_options);
  4137. #endif
  4138. /* Sorry, PAWS as specified is broken wrt. pure-ACKs -DaveM
  4139. *
  4140. * It is not fatal. If this ACK does _not_ change critical state (seqs, window)
  4141. * it can pass through stack. So, the following predicate verifies that
  4142. * this segment is not used for anything but congestion avoidance or
  4143. * fast retransmit. Moreover, we even are able to eliminate most of such
  4144. * second order effects, if we apply some small "replay" window (~RTO)
  4145. * to timestamp space.
  4146. *
  4147. * All these measures still do not guarantee that we reject wrapped ACKs
  4148. * on networks with high bandwidth, when sequence space is recycled fastly,
  4149. * but it guarantees that such events will be very rare and do not affect
  4150. * connection seriously. This doesn't look nice, but alas, PAWS is really
  4151. * buggy extension.
  4152. *
  4153. * [ Later note. Even worse! It is buggy for segments _with_ data. RFC
  4154. * states that events when retransmit arrives after original data are rare.
  4155. * It is a blatant lie. VJ forgot about fast retransmit! 8)8) It is
  4156. * the biggest problem on large power networks even with minor reordering.
  4157. * OK, let's give it small replay window. If peer clock is even 1hz, it is safe
  4158. * up to bandwidth of 18Gigabit/sec. 8) ]
  4159. */
  4160. /* Estimates max number of increments of remote peer TSval in
  4161. * a replay window (based on our current RTO estimation).
  4162. */
  4163. static u32 tcp_tsval_replay(const struct sock *sk)
  4164. {
  4165. /* If we use usec TS resolution,
  4166. * then expect the remote peer to use the same resolution.
  4167. */
  4168. if (tcp_sk(sk)->tcp_usec_ts)
  4169. return inet_csk(sk)->icsk_rto * (USEC_PER_SEC / HZ);
  4170. /* RFC 7323 recommends a TSval clock between 1ms and 1sec.
  4171. * We know that some OS (including old linux) can use 1200 Hz.
  4172. */
  4173. return inet_csk(sk)->icsk_rto * 1200 / HZ;
  4174. }
  4175. static enum skb_drop_reason tcp_disordered_ack_check(const struct sock *sk,
  4176. const struct sk_buff *skb)
  4177. {
  4178. const struct tcp_sock *tp = tcp_sk(sk);
  4179. const struct tcphdr *th = tcp_hdr(skb);
  4180. SKB_DR_INIT(reason, TCP_RFC7323_PAWS);
  4181. u32 ack = TCP_SKB_CB(skb)->ack_seq;
  4182. u32 seq = TCP_SKB_CB(skb)->seq;
  4183. /* 1. Is this not a pure ACK ? */
  4184. if (!th->ack || seq != TCP_SKB_CB(skb)->end_seq)
  4185. return reason;
  4186. /* 2. Is its sequence not the expected one ? */
  4187. if (seq != tp->rcv_nxt)
  4188. return before(seq, tp->rcv_nxt) ?
  4189. SKB_DROP_REASON_TCP_RFC7323_PAWS_ACK :
  4190. reason;
  4191. /* 3. Is this not a duplicate ACK ? */
  4192. if (ack != tp->snd_una)
  4193. return reason;
  4194. /* 4. Is this updating the window ? */
  4195. if (tcp_may_update_window(tp, ack, seq, ntohs(th->window) <<
  4196. tp->rx_opt.snd_wscale))
  4197. return reason;
  4198. /* 5. Is this not in the replay window ? */
  4199. if ((s32)(tp->rx_opt.ts_recent - tp->rx_opt.rcv_tsval) >
  4200. tcp_tsval_replay(sk))
  4201. return reason;
  4202. return 0;
  4203. }
  4204. /* Check segment sequence number for validity.
  4205. *
  4206. * Segment controls are considered valid, if the segment
  4207. * fits to the window after truncation to the window. Acceptability
  4208. * of data (and SYN, FIN, of course) is checked separately.
  4209. * See tcp_data_queue(), for example.
  4210. *
  4211. * Also, controls (RST is main one) are accepted using RCV.WUP instead
  4212. * of RCV.NXT. Peer still did not advance his SND.UNA when we
  4213. * delayed ACK, so that hisSND.UNA<=ourRCV.WUP.
  4214. * (borrowed from freebsd)
  4215. */
  4216. static enum skb_drop_reason tcp_sequence(const struct sock *sk,
  4217. u32 seq, u32 end_seq,
  4218. const struct tcphdr *th)
  4219. {
  4220. const struct tcp_sock *tp = tcp_sk(sk);
  4221. u32 seq_limit;
  4222. if (before(end_seq, tp->rcv_wup))
  4223. return SKB_DROP_REASON_TCP_OLD_SEQUENCE;
  4224. seq_limit = tp->rcv_nxt + tcp_receive_window(tp);
  4225. if (unlikely(after(end_seq, seq_limit))) {
  4226. /* Some stacks are known to handle FIN incorrectly; allow the
  4227. * FIN to extend beyond the window and check it in detail later.
  4228. */
  4229. if (!after(end_seq - th->fin, seq_limit))
  4230. return SKB_NOT_DROPPED_YET;
  4231. if (after(seq, seq_limit))
  4232. return SKB_DROP_REASON_TCP_INVALID_SEQUENCE;
  4233. /* Only accept this packet if receive queue is empty. */
  4234. if (skb_queue_len(&sk->sk_receive_queue))
  4235. return SKB_DROP_REASON_TCP_INVALID_END_SEQUENCE;
  4236. }
  4237. return SKB_NOT_DROPPED_YET;
  4238. }
  4239. void tcp_done_with_error(struct sock *sk, int err)
  4240. {
  4241. /* This barrier is coupled with smp_rmb() in tcp_poll() */
  4242. WRITE_ONCE(sk->sk_err, err);
  4243. smp_wmb();
  4244. tcp_write_queue_purge(sk);
  4245. tcp_done(sk);
  4246. if (!sock_flag(sk, SOCK_DEAD))
  4247. sk_error_report(sk);
  4248. }
  4249. EXPORT_IPV6_MOD(tcp_done_with_error);
  4250. /* When we get a reset we do this. */
  4251. void tcp_reset(struct sock *sk, struct sk_buff *skb)
  4252. {
  4253. int err;
  4254. trace_tcp_receive_reset(sk);
  4255. /* mptcp can't tell us to ignore reset pkts,
  4256. * so just ignore the return value of mptcp_incoming_options().
  4257. */
  4258. if (sk_is_mptcp(sk))
  4259. mptcp_incoming_options(sk, skb);
  4260. /* We want the right error as BSD sees it (and indeed as we do). */
  4261. switch (sk->sk_state) {
  4262. case TCP_SYN_SENT:
  4263. err = ECONNREFUSED;
  4264. break;
  4265. case TCP_CLOSE_WAIT:
  4266. err = EPIPE;
  4267. break;
  4268. case TCP_CLOSE:
  4269. return;
  4270. default:
  4271. err = ECONNRESET;
  4272. }
  4273. tcp_done_with_error(sk, err);
  4274. }
  4275. /*
  4276. * Process the FIN bit. This now behaves as it is supposed to work
  4277. * and the FIN takes effect when it is validly part of sequence
  4278. * space. Not before when we get holes.
  4279. *
  4280. * If we are ESTABLISHED, a received fin moves us to CLOSE-WAIT
  4281. * (and thence onto LAST-ACK and finally, CLOSE, we never enter
  4282. * TIME-WAIT)
  4283. *
  4284. * If we are in FINWAIT-1, a received FIN indicates simultaneous
  4285. * close and we go into CLOSING (and later onto TIME-WAIT)
  4286. *
  4287. * If we are in FINWAIT-2, a received FIN moves us to TIME-WAIT.
  4288. */
  4289. void tcp_fin(struct sock *sk)
  4290. {
  4291. struct tcp_sock *tp = tcp_sk(sk);
  4292. inet_csk_schedule_ack(sk);
  4293. WRITE_ONCE(sk->sk_shutdown, sk->sk_shutdown | RCV_SHUTDOWN);
  4294. sock_set_flag(sk, SOCK_DONE);
  4295. switch (sk->sk_state) {
  4296. case TCP_SYN_RECV:
  4297. case TCP_ESTABLISHED:
  4298. /* Move to CLOSE_WAIT */
  4299. tcp_set_state(sk, TCP_CLOSE_WAIT);
  4300. inet_csk_enter_pingpong_mode(sk);
  4301. break;
  4302. case TCP_CLOSE_WAIT:
  4303. case TCP_CLOSING:
  4304. /* Received a retransmission of the FIN, do
  4305. * nothing.
  4306. */
  4307. break;
  4308. case TCP_LAST_ACK:
  4309. /* RFC793: Remain in the LAST-ACK state. */
  4310. break;
  4311. case TCP_FIN_WAIT1:
  4312. /* This case occurs when a simultaneous close
  4313. * happens, we must ack the received FIN and
  4314. * enter the CLOSING state.
  4315. */
  4316. tcp_send_ack(sk);
  4317. tcp_set_state(sk, TCP_CLOSING);
  4318. break;
  4319. case TCP_FIN_WAIT2:
  4320. /* Received a FIN -- send ACK and enter TIME_WAIT. */
  4321. tcp_send_ack(sk);
  4322. tcp_time_wait(sk, TCP_TIME_WAIT, 0);
  4323. break;
  4324. default:
  4325. /* Only TCP_LISTEN and TCP_CLOSE are left, in these
  4326. * cases we should never reach this piece of code.
  4327. */
  4328. pr_err("%s: Impossible, sk->sk_state=%d\n",
  4329. __func__, sk->sk_state);
  4330. break;
  4331. }
  4332. /* It _is_ possible, that we have something out-of-order _after_ FIN.
  4333. * Probably, we should reset in this case. For now drop them.
  4334. */
  4335. skb_rbtree_purge(&tp->out_of_order_queue);
  4336. if (tcp_is_sack(tp))
  4337. tcp_sack_reset(&tp->rx_opt);
  4338. if (!sock_flag(sk, SOCK_DEAD)) {
  4339. sk->sk_state_change(sk);
  4340. /* Do not send POLL_HUP for half duplex close. */
  4341. if (sk->sk_shutdown == SHUTDOWN_MASK ||
  4342. sk->sk_state == TCP_CLOSE)
  4343. sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_HUP);
  4344. else
  4345. sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN);
  4346. }
  4347. }
  4348. static inline bool tcp_sack_extend(struct tcp_sack_block *sp, u32 seq,
  4349. u32 end_seq)
  4350. {
  4351. if (!after(seq, sp->end_seq) && !after(sp->start_seq, end_seq)) {
  4352. if (before(seq, sp->start_seq))
  4353. sp->start_seq = seq;
  4354. if (after(end_seq, sp->end_seq))
  4355. sp->end_seq = end_seq;
  4356. return true;
  4357. }
  4358. return false;
  4359. }
  4360. static void tcp_dsack_set(struct sock *sk, u32 seq, u32 end_seq)
  4361. {
  4362. struct tcp_sock *tp = tcp_sk(sk);
  4363. if (tcp_is_sack(tp) && READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_dsack)) {
  4364. int mib_idx;
  4365. if (before(seq, tp->rcv_nxt))
  4366. mib_idx = LINUX_MIB_TCPDSACKOLDSENT;
  4367. else
  4368. mib_idx = LINUX_MIB_TCPDSACKOFOSENT;
  4369. NET_INC_STATS(sock_net(sk), mib_idx);
  4370. tp->rx_opt.dsack = 1;
  4371. tp->duplicate_sack[0].start_seq = seq;
  4372. tp->duplicate_sack[0].end_seq = end_seq;
  4373. }
  4374. }
  4375. static void tcp_dsack_extend(struct sock *sk, u32 seq, u32 end_seq)
  4376. {
  4377. struct tcp_sock *tp = tcp_sk(sk);
  4378. if (!tp->rx_opt.dsack)
  4379. tcp_dsack_set(sk, seq, end_seq);
  4380. else
  4381. tcp_sack_extend(tp->duplicate_sack, seq, end_seq);
  4382. }
  4383. static void tcp_rcv_spurious_retrans(struct sock *sk,
  4384. const struct sk_buff *skb)
  4385. {
  4386. struct tcp_sock *tp = tcp_sk(sk);
  4387. /* When the ACK path fails or drops most ACKs, the sender would
  4388. * timeout and spuriously retransmit the same segment repeatedly.
  4389. * If it seems our ACKs are not reaching the other side,
  4390. * based on receiving a duplicate data segment with new flowlabel
  4391. * (suggesting the sender suffered an RTO), and we are not already
  4392. * repathing due to our own RTO, then rehash the socket to repath our
  4393. * packets.
  4394. */
  4395. #if IS_ENABLED(CONFIG_IPV6)
  4396. if (inet_csk(sk)->icsk_ca_state != TCP_CA_Loss &&
  4397. skb->protocol == htons(ETH_P_IPV6) &&
  4398. (tcp_sk(sk)->inet_conn.icsk_ack.lrcv_flowlabel !=
  4399. ntohl(ip6_flowlabel(ipv6_hdr(skb)))) &&
  4400. sk_rethink_txhash(sk))
  4401. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPDUPLICATEDATAREHASH);
  4402. /* Save last flowlabel after a spurious retrans. */
  4403. tcp_save_lrcv_flowlabel(sk, skb);
  4404. #endif
  4405. /* Check DSACK info to detect that the previous ACK carrying the
  4406. * AccECN option was lost after the second retransmision, and then
  4407. * stop sending AccECN option in all subsequent ACKs.
  4408. */
  4409. if (tcp_ecn_mode_accecn(tp) &&
  4410. tp->accecn_opt_sent_w_dsack &&
  4411. TCP_SKB_CB(skb)->seq == tp->duplicate_sack[0].start_seq)
  4412. tcp_accecn_fail_mode_set(tp, TCP_ACCECN_OPT_FAIL_SEND);
  4413. }
  4414. static void tcp_send_dupack(struct sock *sk, const struct sk_buff *skb)
  4415. {
  4416. struct tcp_sock *tp = tcp_sk(sk);
  4417. if (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq &&
  4418. before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) {
  4419. NET_INC_STATS(sock_net(sk), LINUX_MIB_DELAYEDACKLOST);
  4420. tcp_enter_quickack_mode(sk, TCP_MAX_QUICKACKS);
  4421. if (tcp_is_sack(tp) && READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_dsack)) {
  4422. u32 end_seq = TCP_SKB_CB(skb)->end_seq;
  4423. tcp_rcv_spurious_retrans(sk, skb);
  4424. if (after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt))
  4425. end_seq = tp->rcv_nxt;
  4426. tcp_dsack_set(sk, TCP_SKB_CB(skb)->seq, end_seq);
  4427. }
  4428. }
  4429. tcp_send_ack(sk);
  4430. }
  4431. /* These routines update the SACK block as out-of-order packets arrive or
  4432. * in-order packets close up the sequence space.
  4433. */
  4434. static void tcp_sack_maybe_coalesce(struct tcp_sock *tp)
  4435. {
  4436. int this_sack;
  4437. struct tcp_sack_block *sp = &tp->selective_acks[0];
  4438. struct tcp_sack_block *swalk = sp + 1;
  4439. /* See if the recent change to the first SACK eats into
  4440. * or hits the sequence space of other SACK blocks, if so coalesce.
  4441. */
  4442. for (this_sack = 1; this_sack < tp->rx_opt.num_sacks;) {
  4443. if (tcp_sack_extend(sp, swalk->start_seq, swalk->end_seq)) {
  4444. int i;
  4445. /* Zap SWALK, by moving every further SACK up by one slot.
  4446. * Decrease num_sacks.
  4447. */
  4448. tp->rx_opt.num_sacks--;
  4449. for (i = this_sack; i < tp->rx_opt.num_sacks; i++)
  4450. sp[i] = sp[i + 1];
  4451. continue;
  4452. }
  4453. this_sack++;
  4454. swalk++;
  4455. }
  4456. }
  4457. void tcp_sack_compress_send_ack(struct sock *sk)
  4458. {
  4459. struct tcp_sock *tp = tcp_sk(sk);
  4460. if (!tp->compressed_ack)
  4461. return;
  4462. if (hrtimer_try_to_cancel(&tp->compressed_ack_timer) == 1)
  4463. __sock_put(sk);
  4464. /* Since we have to send one ack finally,
  4465. * substract one from tp->compressed_ack to keep
  4466. * LINUX_MIB_TCPACKCOMPRESSED accurate.
  4467. */
  4468. NET_ADD_STATS(sock_net(sk), LINUX_MIB_TCPACKCOMPRESSED,
  4469. tp->compressed_ack - 1);
  4470. tp->compressed_ack = 0;
  4471. tcp_send_ack(sk);
  4472. }
  4473. /* Reasonable amount of sack blocks included in TCP SACK option
  4474. * The max is 4, but this becomes 3 if TCP timestamps are there.
  4475. * Given that SACK packets might be lost, be conservative and use 2.
  4476. */
  4477. #define TCP_SACK_BLOCKS_EXPECTED 2
  4478. static void tcp_sack_new_ofo_skb(struct sock *sk, u32 seq, u32 end_seq)
  4479. {
  4480. struct tcp_sock *tp = tcp_sk(sk);
  4481. struct tcp_sack_block *sp = &tp->selective_acks[0];
  4482. int cur_sacks = tp->rx_opt.num_sacks;
  4483. int this_sack;
  4484. if (!cur_sacks)
  4485. goto new_sack;
  4486. for (this_sack = 0; this_sack < cur_sacks; this_sack++, sp++) {
  4487. if (tcp_sack_extend(sp, seq, end_seq)) {
  4488. if (this_sack >= TCP_SACK_BLOCKS_EXPECTED)
  4489. tcp_sack_compress_send_ack(sk);
  4490. /* Rotate this_sack to the first one. */
  4491. for (; this_sack > 0; this_sack--, sp--)
  4492. swap(*sp, *(sp - 1));
  4493. if (cur_sacks > 1)
  4494. tcp_sack_maybe_coalesce(tp);
  4495. return;
  4496. }
  4497. }
  4498. if (this_sack >= TCP_SACK_BLOCKS_EXPECTED)
  4499. tcp_sack_compress_send_ack(sk);
  4500. /* Could not find an adjacent existing SACK, build a new one,
  4501. * put it at the front, and shift everyone else down. We
  4502. * always know there is at least one SACK present already here.
  4503. *
  4504. * If the sack array is full, forget about the last one.
  4505. */
  4506. if (this_sack >= TCP_NUM_SACKS) {
  4507. this_sack--;
  4508. tp->rx_opt.num_sacks--;
  4509. sp--;
  4510. }
  4511. for (; this_sack > 0; this_sack--, sp--)
  4512. *sp = *(sp - 1);
  4513. new_sack:
  4514. /* Build the new head SACK, and we're done. */
  4515. sp->start_seq = seq;
  4516. sp->end_seq = end_seq;
  4517. tp->rx_opt.num_sacks++;
  4518. }
  4519. /* RCV.NXT advances, some SACKs should be eaten. */
  4520. static void tcp_sack_remove(struct tcp_sock *tp)
  4521. {
  4522. struct tcp_sack_block *sp = &tp->selective_acks[0];
  4523. int num_sacks = tp->rx_opt.num_sacks;
  4524. int this_sack;
  4525. /* Empty ofo queue, hence, all the SACKs are eaten. Clear. */
  4526. if (RB_EMPTY_ROOT(&tp->out_of_order_queue)) {
  4527. tp->rx_opt.num_sacks = 0;
  4528. return;
  4529. }
  4530. for (this_sack = 0; this_sack < num_sacks;) {
  4531. /* Check if the start of the sack is covered by RCV.NXT. */
  4532. if (!before(tp->rcv_nxt, sp->start_seq)) {
  4533. int i;
  4534. /* RCV.NXT must cover all the block! */
  4535. WARN_ON(before(tp->rcv_nxt, sp->end_seq));
  4536. /* Zap this SACK, by moving forward any other SACKS. */
  4537. for (i = this_sack+1; i < num_sacks; i++)
  4538. tp->selective_acks[i-1] = tp->selective_acks[i];
  4539. num_sacks--;
  4540. continue;
  4541. }
  4542. this_sack++;
  4543. sp++;
  4544. }
  4545. tp->rx_opt.num_sacks = num_sacks;
  4546. }
  4547. /**
  4548. * tcp_try_coalesce - try to merge skb to prior one
  4549. * @sk: socket
  4550. * @to: prior buffer
  4551. * @from: buffer to add in queue
  4552. * @fragstolen: pointer to boolean
  4553. *
  4554. * Before queueing skb @from after @to, try to merge them
  4555. * to reduce overall memory use and queue lengths, if cost is small.
  4556. * Packets in ofo or receive queues can stay a long time.
  4557. * Better try to coalesce them right now to avoid future collapses.
  4558. * Returns true if caller should free @from instead of queueing it
  4559. */
  4560. static bool tcp_try_coalesce(struct sock *sk,
  4561. struct sk_buff *to,
  4562. struct sk_buff *from,
  4563. bool *fragstolen)
  4564. {
  4565. int delta;
  4566. *fragstolen = false;
  4567. /* Its possible this segment overlaps with prior segment in queue */
  4568. if (TCP_SKB_CB(from)->seq != TCP_SKB_CB(to)->end_seq)
  4569. return false;
  4570. if (!tcp_skb_can_collapse_rx(to, from))
  4571. return false;
  4572. if (!skb_try_coalesce(to, from, fragstolen, &delta))
  4573. return false;
  4574. atomic_add(delta, &sk->sk_rmem_alloc);
  4575. sk_mem_charge(sk, delta);
  4576. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPRCVCOALESCE);
  4577. TCP_SKB_CB(to)->end_seq = TCP_SKB_CB(from)->end_seq;
  4578. TCP_SKB_CB(to)->ack_seq = TCP_SKB_CB(from)->ack_seq;
  4579. TCP_SKB_CB(to)->tcp_flags |= TCP_SKB_CB(from)->tcp_flags;
  4580. if (TCP_SKB_CB(from)->has_rxtstamp) {
  4581. TCP_SKB_CB(to)->has_rxtstamp = true;
  4582. to->tstamp = from->tstamp;
  4583. skb_hwtstamps(to)->hwtstamp = skb_hwtstamps(from)->hwtstamp;
  4584. }
  4585. return true;
  4586. }
  4587. static bool tcp_ooo_try_coalesce(struct sock *sk,
  4588. struct sk_buff *to,
  4589. struct sk_buff *from,
  4590. bool *fragstolen)
  4591. {
  4592. bool res = tcp_try_coalesce(sk, to, from, fragstolen);
  4593. /* In case tcp_drop_reason() is called later, update to->gso_segs */
  4594. if (res) {
  4595. u32 gso_segs = max_t(u16, 1, skb_shinfo(to)->gso_segs) +
  4596. max_t(u16, 1, skb_shinfo(from)->gso_segs);
  4597. skb_shinfo(to)->gso_segs = min_t(u32, gso_segs, 0xFFFF);
  4598. }
  4599. return res;
  4600. }
  4601. noinline_for_tracing static void
  4602. tcp_drop_reason(struct sock *sk, struct sk_buff *skb, enum skb_drop_reason reason)
  4603. {
  4604. sk_drops_skbadd(sk, skb);
  4605. sk_skb_reason_drop(sk, skb, reason);
  4606. }
  4607. /* This one checks to see if we can put data from the
  4608. * out_of_order queue into the receive_queue.
  4609. */
  4610. static void tcp_ofo_queue(struct sock *sk)
  4611. {
  4612. struct tcp_sock *tp = tcp_sk(sk);
  4613. __u32 dsack_high = tp->rcv_nxt;
  4614. bool fin, fragstolen, eaten;
  4615. struct sk_buff *skb, *tail;
  4616. struct rb_node *p;
  4617. p = rb_first(&tp->out_of_order_queue);
  4618. while (p) {
  4619. skb = rb_to_skb(p);
  4620. if (after(TCP_SKB_CB(skb)->seq, tp->rcv_nxt))
  4621. break;
  4622. if (before(TCP_SKB_CB(skb)->seq, dsack_high)) {
  4623. __u32 dsack = dsack_high;
  4624. if (before(TCP_SKB_CB(skb)->end_seq, dsack_high))
  4625. dsack = TCP_SKB_CB(skb)->end_seq;
  4626. tcp_dsack_extend(sk, TCP_SKB_CB(skb)->seq, dsack);
  4627. }
  4628. p = rb_next(p);
  4629. rb_erase(&skb->rbnode, &tp->out_of_order_queue);
  4630. if (unlikely(!after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt))) {
  4631. tcp_drop_reason(sk, skb, SKB_DROP_REASON_TCP_OFO_DROP);
  4632. continue;
  4633. }
  4634. tail = skb_peek_tail(&sk->sk_receive_queue);
  4635. eaten = tail && tcp_try_coalesce(sk, tail, skb, &fragstolen);
  4636. tcp_rcv_nxt_update(tp, TCP_SKB_CB(skb)->end_seq);
  4637. fin = TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN;
  4638. if (!eaten)
  4639. tcp_add_receive_queue(sk, skb);
  4640. else
  4641. kfree_skb_partial(skb, fragstolen);
  4642. if (unlikely(fin)) {
  4643. tcp_fin(sk);
  4644. /* tcp_fin() purges tp->out_of_order_queue,
  4645. * so we must end this loop right now.
  4646. */
  4647. break;
  4648. }
  4649. }
  4650. }
  4651. static bool tcp_prune_ofo_queue(struct sock *sk, const struct sk_buff *in_skb);
  4652. static int tcp_prune_queue(struct sock *sk, const struct sk_buff *in_skb);
  4653. static bool tcp_can_ingest(const struct sock *sk, const struct sk_buff *skb)
  4654. {
  4655. unsigned int rmem = atomic_read(&sk->sk_rmem_alloc);
  4656. return rmem <= sk->sk_rcvbuf;
  4657. }
  4658. static int tcp_try_rmem_schedule(struct sock *sk, const struct sk_buff *skb,
  4659. unsigned int size)
  4660. {
  4661. if (!tcp_can_ingest(sk, skb) ||
  4662. !sk_rmem_schedule(sk, skb, size)) {
  4663. if (tcp_prune_queue(sk, skb) < 0)
  4664. return -1;
  4665. while (!sk_rmem_schedule(sk, skb, size)) {
  4666. if (!tcp_prune_ofo_queue(sk, skb))
  4667. return -1;
  4668. }
  4669. }
  4670. return 0;
  4671. }
  4672. static void tcp_data_queue_ofo(struct sock *sk, struct sk_buff *skb)
  4673. {
  4674. struct tcp_sock *tp = tcp_sk(sk);
  4675. struct rb_node **p, *parent;
  4676. struct sk_buff *skb1;
  4677. u32 seq, end_seq;
  4678. bool fragstolen;
  4679. tcp_save_lrcv_flowlabel(sk, skb);
  4680. tcp_data_ecn_check(sk, skb);
  4681. if (unlikely(tcp_try_rmem_schedule(sk, skb, skb->truesize))) {
  4682. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPOFODROP);
  4683. READ_ONCE(sk->sk_data_ready)(sk);
  4684. tcp_drop_reason(sk, skb, SKB_DROP_REASON_PROTO_MEM);
  4685. return;
  4686. }
  4687. tcp_measure_rcv_mss(sk, skb);
  4688. /* Disable header prediction. */
  4689. tp->pred_flags = 0;
  4690. inet_csk_schedule_ack(sk);
  4691. tp->rcv_ooopack += max_t(u16, 1, skb_shinfo(skb)->gso_segs);
  4692. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPOFOQUEUE);
  4693. seq = TCP_SKB_CB(skb)->seq;
  4694. end_seq = TCP_SKB_CB(skb)->end_seq;
  4695. p = &tp->out_of_order_queue.rb_node;
  4696. if (RB_EMPTY_ROOT(&tp->out_of_order_queue)) {
  4697. /* Initial out of order segment, build 1 SACK. */
  4698. if (tcp_is_sack(tp)) {
  4699. tp->rx_opt.num_sacks = 1;
  4700. tp->selective_acks[0].start_seq = seq;
  4701. tp->selective_acks[0].end_seq = end_seq;
  4702. }
  4703. rb_link_node(&skb->rbnode, NULL, p);
  4704. rb_insert_color(&skb->rbnode, &tp->out_of_order_queue);
  4705. tp->ooo_last_skb = skb;
  4706. goto end;
  4707. }
  4708. /* In the typical case, we are adding an skb to the end of the list.
  4709. * Use of ooo_last_skb avoids the O(Log(N)) rbtree lookup.
  4710. */
  4711. if (tcp_ooo_try_coalesce(sk, tp->ooo_last_skb,
  4712. skb, &fragstolen)) {
  4713. coalesce_done:
  4714. /* For non sack flows, do not grow window to force DUPACK
  4715. * and trigger fast retransmit.
  4716. */
  4717. if (tcp_is_sack(tp))
  4718. tcp_grow_window(sk, skb, true);
  4719. kfree_skb_partial(skb, fragstolen);
  4720. skb = NULL;
  4721. goto add_sack;
  4722. }
  4723. /* Can avoid an rbtree lookup if we are adding skb after ooo_last_skb */
  4724. if (!before(seq, TCP_SKB_CB(tp->ooo_last_skb)->end_seq)) {
  4725. parent = &tp->ooo_last_skb->rbnode;
  4726. p = &parent->rb_right;
  4727. goto insert;
  4728. }
  4729. /* Find place to insert this segment. Handle overlaps on the way. */
  4730. parent = NULL;
  4731. while (*p) {
  4732. parent = *p;
  4733. skb1 = rb_to_skb(parent);
  4734. if (before(seq, TCP_SKB_CB(skb1)->seq)) {
  4735. p = &parent->rb_left;
  4736. continue;
  4737. }
  4738. if (before(seq, TCP_SKB_CB(skb1)->end_seq)) {
  4739. if (!after(end_seq, TCP_SKB_CB(skb1)->end_seq)) {
  4740. /* All the bits are present. Drop. */
  4741. NET_INC_STATS(sock_net(sk),
  4742. LINUX_MIB_TCPOFOMERGE);
  4743. tcp_drop_reason(sk, skb,
  4744. SKB_DROP_REASON_TCP_OFOMERGE);
  4745. skb = NULL;
  4746. tcp_dsack_set(sk, seq, end_seq);
  4747. goto add_sack;
  4748. }
  4749. if (after(seq, TCP_SKB_CB(skb1)->seq)) {
  4750. /* Partial overlap. */
  4751. tcp_dsack_set(sk, seq, TCP_SKB_CB(skb1)->end_seq);
  4752. } else {
  4753. /* skb's seq == skb1's seq and skb covers skb1.
  4754. * Replace skb1 with skb.
  4755. */
  4756. rb_replace_node(&skb1->rbnode, &skb->rbnode,
  4757. &tp->out_of_order_queue);
  4758. tcp_dsack_extend(sk,
  4759. TCP_SKB_CB(skb1)->seq,
  4760. TCP_SKB_CB(skb1)->end_seq);
  4761. NET_INC_STATS(sock_net(sk),
  4762. LINUX_MIB_TCPOFOMERGE);
  4763. tcp_drop_reason(sk, skb1,
  4764. SKB_DROP_REASON_TCP_OFOMERGE);
  4765. goto merge_right;
  4766. }
  4767. } else if (tcp_ooo_try_coalesce(sk, skb1,
  4768. skb, &fragstolen)) {
  4769. goto coalesce_done;
  4770. }
  4771. p = &parent->rb_right;
  4772. }
  4773. insert:
  4774. /* Insert segment into RB tree. */
  4775. rb_link_node(&skb->rbnode, parent, p);
  4776. rb_insert_color(&skb->rbnode, &tp->out_of_order_queue);
  4777. merge_right:
  4778. /* Remove other segments covered by skb. */
  4779. while ((skb1 = skb_rb_next(skb)) != NULL) {
  4780. if (!after(end_seq, TCP_SKB_CB(skb1)->seq))
  4781. break;
  4782. if (before(end_seq, TCP_SKB_CB(skb1)->end_seq)) {
  4783. tcp_dsack_extend(sk, TCP_SKB_CB(skb1)->seq,
  4784. end_seq);
  4785. break;
  4786. }
  4787. rb_erase(&skb1->rbnode, &tp->out_of_order_queue);
  4788. tcp_dsack_extend(sk, TCP_SKB_CB(skb1)->seq,
  4789. TCP_SKB_CB(skb1)->end_seq);
  4790. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPOFOMERGE);
  4791. tcp_drop_reason(sk, skb1, SKB_DROP_REASON_TCP_OFOMERGE);
  4792. }
  4793. /* If there is no skb after us, we are the last_skb ! */
  4794. if (!skb1)
  4795. tp->ooo_last_skb = skb;
  4796. add_sack:
  4797. if (tcp_is_sack(tp))
  4798. tcp_sack_new_ofo_skb(sk, seq, end_seq);
  4799. end:
  4800. if (skb) {
  4801. /* For non sack flows, do not grow window to force DUPACK
  4802. * and trigger fast retransmit.
  4803. */
  4804. if (tcp_is_sack(tp))
  4805. tcp_grow_window(sk, skb, false);
  4806. skb_condense(skb);
  4807. skb_set_owner_r(skb, sk);
  4808. }
  4809. /* do not grow rcvbuf for not-yet-accepted or orphaned sockets. */
  4810. if (sk->sk_socket)
  4811. tcp_rcvbuf_grow(sk, tp->rcvq_space.space);
  4812. }
  4813. static int __must_check tcp_queue_rcv(struct sock *sk, struct sk_buff *skb,
  4814. bool *fragstolen)
  4815. {
  4816. int eaten;
  4817. struct sk_buff *tail = skb_peek_tail(&sk->sk_receive_queue);
  4818. eaten = (tail &&
  4819. tcp_try_coalesce(sk, tail,
  4820. skb, fragstolen)) ? 1 : 0;
  4821. tcp_rcv_nxt_update(tcp_sk(sk), TCP_SKB_CB(skb)->end_seq);
  4822. if (!eaten) {
  4823. tcp_add_receive_queue(sk, skb);
  4824. skb_set_owner_r(skb, sk);
  4825. }
  4826. return eaten;
  4827. }
  4828. int tcp_send_rcvq(struct sock *sk, struct msghdr *msg, size_t size)
  4829. {
  4830. struct sk_buff *skb;
  4831. int err = -ENOMEM;
  4832. int data_len = 0;
  4833. bool fragstolen;
  4834. if (size == 0)
  4835. return 0;
  4836. if (size > PAGE_SIZE) {
  4837. int npages = min_t(size_t, size >> PAGE_SHIFT, MAX_SKB_FRAGS);
  4838. data_len = npages << PAGE_SHIFT;
  4839. size = data_len + (size & ~PAGE_MASK);
  4840. }
  4841. skb = alloc_skb_with_frags(size - data_len, data_len,
  4842. PAGE_ALLOC_COSTLY_ORDER,
  4843. &err, sk->sk_allocation);
  4844. if (!skb)
  4845. goto err;
  4846. skb_put(skb, size - data_len);
  4847. skb->data_len = data_len;
  4848. skb->len = size;
  4849. if (tcp_try_rmem_schedule(sk, skb, skb->truesize)) {
  4850. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPRCVQDROP);
  4851. goto err_free;
  4852. }
  4853. err = skb_copy_datagram_from_iter(skb, 0, &msg->msg_iter, size);
  4854. if (err)
  4855. goto err_free;
  4856. TCP_SKB_CB(skb)->seq = tcp_sk(sk)->rcv_nxt;
  4857. TCP_SKB_CB(skb)->end_seq = TCP_SKB_CB(skb)->seq + size;
  4858. TCP_SKB_CB(skb)->ack_seq = tcp_sk(sk)->snd_una - 1;
  4859. if (tcp_queue_rcv(sk, skb, &fragstolen)) {
  4860. WARN_ON_ONCE(fragstolen); /* should not happen */
  4861. __kfree_skb(skb);
  4862. }
  4863. return size;
  4864. err_free:
  4865. kfree_skb(skb);
  4866. err:
  4867. return err;
  4868. }
  4869. void tcp_data_ready(struct sock *sk)
  4870. {
  4871. if (tcp_epollin_ready(sk, sk->sk_rcvlowat) || sock_flag(sk, SOCK_DONE))
  4872. READ_ONCE(sk->sk_data_ready)(sk);
  4873. }
  4874. static void tcp_data_queue(struct sock *sk, struct sk_buff *skb)
  4875. {
  4876. struct tcp_sock *tp = tcp_sk(sk);
  4877. enum skb_drop_reason reason;
  4878. bool fragstolen;
  4879. int eaten;
  4880. /* If a subflow has been reset, the packet should not continue
  4881. * to be processed, drop the packet.
  4882. */
  4883. if (sk_is_mptcp(sk) && !mptcp_incoming_options(sk, skb)) {
  4884. __kfree_skb(skb);
  4885. return;
  4886. }
  4887. if (TCP_SKB_CB(skb)->seq == TCP_SKB_CB(skb)->end_seq) {
  4888. __kfree_skb(skb);
  4889. return;
  4890. }
  4891. tcp_cleanup_skb(skb);
  4892. __skb_pull(skb, tcp_hdr(skb)->doff * 4);
  4893. reason = SKB_DROP_REASON_NOT_SPECIFIED;
  4894. tp->rx_opt.dsack = 0;
  4895. /* Queue data for delivery to the user.
  4896. * Packets in sequence go to the receive queue.
  4897. * Out of sequence packets to the out_of_order_queue.
  4898. */
  4899. if (TCP_SKB_CB(skb)->seq == tp->rcv_nxt) {
  4900. if (tcp_receive_window(tp) == 0) {
  4901. /* Some stacks are known to send bare FIN packets
  4902. * in a loop even if we send RWIN 0 in our ACK.
  4903. * Accepting this FIN does not hurt memory pressure
  4904. * because the FIN flag will simply be merged to the
  4905. * receive queue tail skb in most cases.
  4906. */
  4907. if (!skb->len &&
  4908. (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN))
  4909. goto queue_and_out;
  4910. reason = SKB_DROP_REASON_TCP_ZEROWINDOW;
  4911. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPZEROWINDOWDROP);
  4912. goto out_of_window;
  4913. }
  4914. /* Ok. In sequence. In window. */
  4915. queue_and_out:
  4916. if (tcp_try_rmem_schedule(sk, skb, skb->truesize)) {
  4917. /* TODO: maybe ratelimit these WIN 0 ACK ? */
  4918. inet_csk(sk)->icsk_ack.pending |=
  4919. (ICSK_ACK_NOMEM | ICSK_ACK_NOW);
  4920. inet_csk_schedule_ack(sk);
  4921. READ_ONCE(sk->sk_data_ready)(sk);
  4922. if (skb_queue_len(&sk->sk_receive_queue) && skb->len) {
  4923. reason = SKB_DROP_REASON_PROTO_MEM;
  4924. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPRCVQDROP);
  4925. goto drop;
  4926. }
  4927. sk_forced_mem_schedule(sk, skb->truesize);
  4928. }
  4929. eaten = tcp_queue_rcv(sk, skb, &fragstolen);
  4930. if (skb->len)
  4931. tcp_event_data_recv(sk, skb);
  4932. if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)
  4933. tcp_fin(sk);
  4934. if (!RB_EMPTY_ROOT(&tp->out_of_order_queue)) {
  4935. tcp_ofo_queue(sk);
  4936. /* RFC5681. 4.2. SHOULD send immediate ACK, when
  4937. * gap in queue is filled.
  4938. */
  4939. if (RB_EMPTY_ROOT(&tp->out_of_order_queue))
  4940. inet_csk(sk)->icsk_ack.pending |= ICSK_ACK_NOW;
  4941. }
  4942. if (tp->rx_opt.num_sacks)
  4943. tcp_sack_remove(tp);
  4944. tcp_fast_path_check(sk);
  4945. if (eaten > 0)
  4946. kfree_skb_partial(skb, fragstolen);
  4947. if (!sock_flag(sk, SOCK_DEAD))
  4948. tcp_data_ready(sk);
  4949. return;
  4950. }
  4951. if (!after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt)) {
  4952. tcp_rcv_spurious_retrans(sk, skb);
  4953. /* A retransmit, 2nd most common case. Force an immediate ack. */
  4954. reason = SKB_DROP_REASON_TCP_OLD_DATA;
  4955. NET_INC_STATS(sock_net(sk), LINUX_MIB_DELAYEDACKLOST);
  4956. tcp_dsack_set(sk, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq);
  4957. out_of_window:
  4958. tcp_enter_quickack_mode(sk, TCP_MAX_QUICKACKS);
  4959. inet_csk_schedule_ack(sk);
  4960. drop:
  4961. tcp_drop_reason(sk, skb, reason);
  4962. return;
  4963. }
  4964. /* Out of window. F.e. zero window probe. */
  4965. if (!before(TCP_SKB_CB(skb)->seq,
  4966. tp->rcv_nxt + tcp_receive_window(tp))) {
  4967. reason = SKB_DROP_REASON_TCP_OVERWINDOW;
  4968. goto out_of_window;
  4969. }
  4970. if (before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) {
  4971. /* Partial packet, seq < rcv_next < end_seq */
  4972. tcp_dsack_set(sk, TCP_SKB_CB(skb)->seq, tp->rcv_nxt);
  4973. /* If window is closed, drop tail of packet. But after
  4974. * remembering D-SACK for its head made in previous line.
  4975. */
  4976. if (!tcp_receive_window(tp)) {
  4977. reason = SKB_DROP_REASON_TCP_ZEROWINDOW;
  4978. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPZEROWINDOWDROP);
  4979. goto out_of_window;
  4980. }
  4981. goto queue_and_out;
  4982. }
  4983. tcp_data_queue_ofo(sk, skb);
  4984. }
  4985. static struct sk_buff *tcp_skb_next(struct sk_buff *skb, struct sk_buff_head *list)
  4986. {
  4987. if (list)
  4988. return !skb_queue_is_last(list, skb) ? skb->next : NULL;
  4989. return skb_rb_next(skb);
  4990. }
  4991. static struct sk_buff *tcp_collapse_one(struct sock *sk, struct sk_buff *skb,
  4992. struct sk_buff_head *list,
  4993. struct rb_root *root)
  4994. {
  4995. struct sk_buff *next = tcp_skb_next(skb, list);
  4996. if (list)
  4997. __skb_unlink(skb, list);
  4998. else
  4999. rb_erase(&skb->rbnode, root);
  5000. __kfree_skb(skb);
  5001. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPRCVCOLLAPSED);
  5002. return next;
  5003. }
  5004. /* Collapse contiguous sequence of skbs head..tail with
  5005. * sequence numbers start..end.
  5006. *
  5007. * If tail is NULL, this means until the end of the queue.
  5008. *
  5009. * Segments with FIN/SYN are not collapsed (only because this
  5010. * simplifies code)
  5011. */
  5012. static void
  5013. tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root,
  5014. struct sk_buff *head, struct sk_buff *tail, u32 start, u32 end)
  5015. {
  5016. struct sk_buff *skb = head, *n;
  5017. struct sk_buff_head tmp;
  5018. bool end_of_skbs;
  5019. /* First, check that queue is collapsible and find
  5020. * the point where collapsing can be useful.
  5021. */
  5022. restart:
  5023. for (end_of_skbs = true; skb != NULL && skb != tail; skb = n) {
  5024. n = tcp_skb_next(skb, list);
  5025. if (!skb_frags_readable(skb))
  5026. goto skip_this;
  5027. /* No new bits? It is possible on ofo queue. */
  5028. if (!before(start, TCP_SKB_CB(skb)->end_seq)) {
  5029. skb = tcp_collapse_one(sk, skb, list, root);
  5030. if (!skb)
  5031. break;
  5032. goto restart;
  5033. }
  5034. /* The first skb to collapse is:
  5035. * - not SYN/FIN and
  5036. * - bloated or contains data before "start" or
  5037. * overlaps to the next one and mptcp allow collapsing.
  5038. */
  5039. if (!(TCP_SKB_CB(skb)->tcp_flags & (TCPHDR_SYN | TCPHDR_FIN)) &&
  5040. (tcp_win_from_space(sk, skb->truesize) > skb->len ||
  5041. before(TCP_SKB_CB(skb)->seq, start))) {
  5042. end_of_skbs = false;
  5043. break;
  5044. }
  5045. if (n && n != tail && skb_frags_readable(n) &&
  5046. tcp_skb_can_collapse_rx(skb, n) &&
  5047. TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(n)->seq) {
  5048. end_of_skbs = false;
  5049. break;
  5050. }
  5051. skip_this:
  5052. /* Decided to skip this, advance start seq. */
  5053. start = TCP_SKB_CB(skb)->end_seq;
  5054. }
  5055. if (end_of_skbs ||
  5056. (TCP_SKB_CB(skb)->tcp_flags & (TCPHDR_SYN | TCPHDR_FIN)) ||
  5057. !skb_frags_readable(skb))
  5058. return;
  5059. __skb_queue_head_init(&tmp);
  5060. while (before(start, end)) {
  5061. int copy = min_t(int, SKB_MAX_ORDER(0, 0), end - start);
  5062. struct sk_buff *nskb;
  5063. nskb = alloc_skb(copy, GFP_ATOMIC);
  5064. if (!nskb)
  5065. break;
  5066. memcpy(nskb->cb, skb->cb, sizeof(skb->cb));
  5067. skb_copy_decrypted(nskb, skb);
  5068. TCP_SKB_CB(nskb)->seq = TCP_SKB_CB(nskb)->end_seq = start;
  5069. if (list)
  5070. __skb_queue_before(list, skb, nskb);
  5071. else
  5072. __skb_queue_tail(&tmp, nskb); /* defer rbtree insertion */
  5073. skb_set_owner_r(nskb, sk);
  5074. mptcp_skb_ext_move(nskb, skb);
  5075. /* Copy data, releasing collapsed skbs. */
  5076. while (copy > 0) {
  5077. int offset = start - TCP_SKB_CB(skb)->seq;
  5078. int size = TCP_SKB_CB(skb)->end_seq - start;
  5079. BUG_ON(offset < 0);
  5080. if (size > 0) {
  5081. size = min(copy, size);
  5082. if (skb_copy_bits(skb, offset, skb_put(nskb, size), size))
  5083. BUG();
  5084. TCP_SKB_CB(nskb)->end_seq += size;
  5085. copy -= size;
  5086. start += size;
  5087. }
  5088. if (!before(start, TCP_SKB_CB(skb)->end_seq)) {
  5089. skb = tcp_collapse_one(sk, skb, list, root);
  5090. if (!skb ||
  5091. skb == tail ||
  5092. !tcp_skb_can_collapse_rx(nskb, skb) ||
  5093. (TCP_SKB_CB(skb)->tcp_flags & (TCPHDR_SYN | TCPHDR_FIN)) ||
  5094. !skb_frags_readable(skb))
  5095. goto end;
  5096. }
  5097. }
  5098. }
  5099. end:
  5100. skb_queue_walk_safe(&tmp, skb, n)
  5101. tcp_rbtree_insert(root, skb);
  5102. }
  5103. /* Collapse ofo queue. Algorithm: select contiguous sequence of skbs
  5104. * and tcp_collapse() them until all the queue is collapsed.
  5105. */
  5106. static void tcp_collapse_ofo_queue(struct sock *sk)
  5107. {
  5108. struct tcp_sock *tp = tcp_sk(sk);
  5109. u32 range_truesize, sum_tiny = 0;
  5110. struct sk_buff *skb, *head;
  5111. u32 start, end;
  5112. skb = skb_rb_first(&tp->out_of_order_queue);
  5113. new_range:
  5114. if (!skb) {
  5115. tp->ooo_last_skb = skb_rb_last(&tp->out_of_order_queue);
  5116. return;
  5117. }
  5118. start = TCP_SKB_CB(skb)->seq;
  5119. end = TCP_SKB_CB(skb)->end_seq;
  5120. range_truesize = skb->truesize;
  5121. for (head = skb;;) {
  5122. skb = skb_rb_next(skb);
  5123. /* Range is terminated when we see a gap or when
  5124. * we are at the queue end.
  5125. */
  5126. if (!skb ||
  5127. after(TCP_SKB_CB(skb)->seq, end) ||
  5128. before(TCP_SKB_CB(skb)->end_seq, start)) {
  5129. /* Do not attempt collapsing tiny skbs */
  5130. if (range_truesize != head->truesize ||
  5131. end - start >= SKB_WITH_OVERHEAD(PAGE_SIZE)) {
  5132. tcp_collapse(sk, NULL, &tp->out_of_order_queue,
  5133. head, skb, start, end);
  5134. } else {
  5135. sum_tiny += range_truesize;
  5136. if (sum_tiny > sk->sk_rcvbuf >> 3)
  5137. return;
  5138. }
  5139. goto new_range;
  5140. }
  5141. range_truesize += skb->truesize;
  5142. if (unlikely(before(TCP_SKB_CB(skb)->seq, start)))
  5143. start = TCP_SKB_CB(skb)->seq;
  5144. if (after(TCP_SKB_CB(skb)->end_seq, end))
  5145. end = TCP_SKB_CB(skb)->end_seq;
  5146. }
  5147. }
  5148. /*
  5149. * Clean the out-of-order queue to make room.
  5150. * We drop high sequences packets to :
  5151. * 1) Let a chance for holes to be filled.
  5152. * This means we do not drop packets from ooo queue if their sequence
  5153. * is before incoming packet sequence.
  5154. * 2) not add too big latencies if thousands of packets sit there.
  5155. * (But if application shrinks SO_RCVBUF, we could still end up
  5156. * freeing whole queue here)
  5157. * 3) Drop at least 12.5 % of sk_rcvbuf to avoid malicious attacks.
  5158. *
  5159. * Return true if queue has shrunk.
  5160. */
  5161. static bool tcp_prune_ofo_queue(struct sock *sk, const struct sk_buff *in_skb)
  5162. {
  5163. struct tcp_sock *tp = tcp_sk(sk);
  5164. struct rb_node *node, *prev;
  5165. bool pruned = false;
  5166. int goal;
  5167. if (RB_EMPTY_ROOT(&tp->out_of_order_queue))
  5168. return false;
  5169. goal = sk->sk_rcvbuf >> 3;
  5170. node = &tp->ooo_last_skb->rbnode;
  5171. do {
  5172. struct sk_buff *skb = rb_to_skb(node);
  5173. /* If incoming skb would land last in ofo queue, stop pruning. */
  5174. if (after(TCP_SKB_CB(in_skb)->seq, TCP_SKB_CB(skb)->seq))
  5175. break;
  5176. pruned = true;
  5177. prev = rb_prev(node);
  5178. rb_erase(node, &tp->out_of_order_queue);
  5179. goal -= skb->truesize;
  5180. tcp_drop_reason(sk, skb, SKB_DROP_REASON_TCP_OFO_QUEUE_PRUNE);
  5181. tp->ooo_last_skb = rb_to_skb(prev);
  5182. if (!prev || goal <= 0) {
  5183. if (tcp_can_ingest(sk, in_skb) &&
  5184. !tcp_under_memory_pressure(sk))
  5185. break;
  5186. goal = sk->sk_rcvbuf >> 3;
  5187. }
  5188. node = prev;
  5189. } while (node);
  5190. if (pruned) {
  5191. NET_INC_STATS(sock_net(sk), LINUX_MIB_OFOPRUNED);
  5192. /* Reset SACK state. A conforming SACK implementation will
  5193. * do the same at a timeout based retransmit. When a connection
  5194. * is in a sad state like this, we care only about integrity
  5195. * of the connection not performance.
  5196. */
  5197. if (tp->rx_opt.sack_ok)
  5198. tcp_sack_reset(&tp->rx_opt);
  5199. }
  5200. return pruned;
  5201. }
  5202. /* Reduce allocated memory if we can, trying to get
  5203. * the socket within its memory limits again.
  5204. *
  5205. * Return less than zero if we should start dropping frames
  5206. * until the socket owning process reads some of the data
  5207. * to stabilize the situation.
  5208. */
  5209. static int tcp_prune_queue(struct sock *sk, const struct sk_buff *in_skb)
  5210. {
  5211. struct tcp_sock *tp = tcp_sk(sk);
  5212. /* Do nothing if our queues are empty. */
  5213. if (!atomic_read(&sk->sk_rmem_alloc))
  5214. return -1;
  5215. NET_INC_STATS(sock_net(sk), LINUX_MIB_PRUNECALLED);
  5216. if (!tcp_can_ingest(sk, in_skb))
  5217. tcp_clamp_window(sk);
  5218. else if (tcp_under_memory_pressure(sk))
  5219. tcp_adjust_rcv_ssthresh(sk);
  5220. if (tcp_can_ingest(sk, in_skb))
  5221. return 0;
  5222. tcp_collapse_ofo_queue(sk);
  5223. if (!skb_queue_empty(&sk->sk_receive_queue))
  5224. tcp_collapse(sk, &sk->sk_receive_queue, NULL,
  5225. skb_peek(&sk->sk_receive_queue),
  5226. NULL,
  5227. tp->copied_seq, tp->rcv_nxt);
  5228. if (tcp_can_ingest(sk, in_skb))
  5229. return 0;
  5230. /* Collapsing did not help, destructive actions follow.
  5231. * This must not ever occur. */
  5232. tcp_prune_ofo_queue(sk, in_skb);
  5233. if (tcp_can_ingest(sk, in_skb))
  5234. return 0;
  5235. /* If we are really being abused, tell the caller to silently
  5236. * drop receive data on the floor. It will get retransmitted
  5237. * and hopefully then we'll have sufficient space.
  5238. */
  5239. NET_INC_STATS(sock_net(sk), LINUX_MIB_RCVPRUNED);
  5240. /* Massive buffer overcommit. */
  5241. tp->pred_flags = 0;
  5242. return -1;
  5243. }
  5244. static bool tcp_should_expand_sndbuf(struct sock *sk)
  5245. {
  5246. const struct tcp_sock *tp = tcp_sk(sk);
  5247. /* If the user specified a specific send buffer setting, do
  5248. * not modify it.
  5249. */
  5250. if (sk->sk_userlocks & SOCK_SNDBUF_LOCK)
  5251. return false;
  5252. /* If we are under global TCP memory pressure, do not expand. */
  5253. if (tcp_under_memory_pressure(sk)) {
  5254. int unused_mem = sk_unused_reserved_mem(sk);
  5255. /* Adjust sndbuf according to reserved mem. But make sure
  5256. * it never goes below SOCK_MIN_SNDBUF.
  5257. * See sk_stream_moderate_sndbuf() for more details.
  5258. */
  5259. if (unused_mem > SOCK_MIN_SNDBUF)
  5260. WRITE_ONCE(sk->sk_sndbuf, unused_mem);
  5261. return false;
  5262. }
  5263. /* If we are under soft global TCP memory pressure, do not expand. */
  5264. if (sk_memory_allocated(sk) >= sk_prot_mem_limits(sk, 0))
  5265. return false;
  5266. /* If we filled the congestion window, do not expand. */
  5267. if (tcp_packets_in_flight(tp) >= tcp_snd_cwnd(tp))
  5268. return false;
  5269. return true;
  5270. }
  5271. static void tcp_new_space(struct sock *sk)
  5272. {
  5273. struct tcp_sock *tp = tcp_sk(sk);
  5274. if (tcp_should_expand_sndbuf(sk)) {
  5275. tcp_sndbuf_expand(sk);
  5276. tp->snd_cwnd_stamp = tcp_jiffies32;
  5277. }
  5278. INDIRECT_CALL_1(READ_ONCE(sk->sk_write_space),
  5279. sk_stream_write_space,
  5280. sk);
  5281. }
  5282. /* Caller made space either from:
  5283. * 1) Freeing skbs in rtx queues (after tp->snd_una has advanced)
  5284. * 2) Sent skbs from output queue (and thus advancing tp->snd_nxt)
  5285. *
  5286. * We might be able to generate EPOLLOUT to the application if:
  5287. * 1) Space consumed in output/rtx queues is below sk->sk_sndbuf/2
  5288. * 2) notsent amount (tp->write_seq - tp->snd_nxt) became
  5289. * small enough that tcp_stream_memory_free() decides it
  5290. * is time to generate EPOLLOUT.
  5291. */
  5292. void __tcp_check_space(struct sock *sk)
  5293. {
  5294. tcp_new_space(sk);
  5295. if (!test_bit(SOCK_NOSPACE, &sk->sk_socket->flags))
  5296. tcp_chrono_stop(sk, TCP_CHRONO_SNDBUF_LIMITED);
  5297. }
  5298. static inline void tcp_data_snd_check(struct sock *sk)
  5299. {
  5300. tcp_push_pending_frames(sk);
  5301. tcp_check_space(sk);
  5302. }
  5303. /*
  5304. * Check if sending an ack is needed.
  5305. */
  5306. static void __tcp_ack_snd_check(struct sock *sk, int ofo_possible)
  5307. {
  5308. struct tcp_sock *tp = tcp_sk(sk);
  5309. struct net *net = sock_net(sk);
  5310. unsigned long rtt;
  5311. u64 delay;
  5312. /* More than one full frame received... */
  5313. if (((tp->rcv_nxt - tp->rcv_wup) > inet_csk(sk)->icsk_ack.rcv_mss &&
  5314. /* ... and right edge of window advances far enough.
  5315. * (tcp_recvmsg() will send ACK otherwise).
  5316. * If application uses SO_RCVLOWAT, we want send ack now if
  5317. * we have not received enough bytes to satisfy the condition.
  5318. */
  5319. (tp->rcv_nxt - tp->copied_seq < sk->sk_rcvlowat ||
  5320. __tcp_select_window(sk) >= tp->rcv_wnd)) ||
  5321. /* We ACK each frame or... */
  5322. tcp_in_quickack_mode(sk) ||
  5323. /* Protocol state mandates a one-time immediate ACK */
  5324. inet_csk(sk)->icsk_ack.pending & ICSK_ACK_NOW) {
  5325. /* If we are running from __release_sock() in user context,
  5326. * Defer the ack until tcp_release_cb().
  5327. */
  5328. if (sock_owned_by_user_nocheck(sk) &&
  5329. READ_ONCE(net->ipv4.sysctl_tcp_backlog_ack_defer)) {
  5330. set_bit(TCP_ACK_DEFERRED, &sk->sk_tsq_flags);
  5331. return;
  5332. }
  5333. send_now:
  5334. tcp_send_ack(sk);
  5335. return;
  5336. }
  5337. if (!ofo_possible || RB_EMPTY_ROOT(&tp->out_of_order_queue)) {
  5338. tcp_send_delayed_ack(sk);
  5339. return;
  5340. }
  5341. if (!tcp_is_sack(tp) ||
  5342. tp->compressed_ack >= READ_ONCE(net->ipv4.sysctl_tcp_comp_sack_nr))
  5343. goto send_now;
  5344. if (tp->compressed_ack_rcv_nxt != tp->rcv_nxt) {
  5345. tp->compressed_ack_rcv_nxt = tp->rcv_nxt;
  5346. tp->dup_ack_counter = 0;
  5347. }
  5348. if (tp->dup_ack_counter < TCP_FASTRETRANS_THRESH) {
  5349. tp->dup_ack_counter++;
  5350. goto send_now;
  5351. }
  5352. tp->compressed_ack++;
  5353. if (hrtimer_is_queued(&tp->compressed_ack_timer))
  5354. return;
  5355. /* compress ack timer : comp_sack_rtt_percent of rtt,
  5356. * but no more than tcp_comp_sack_delay_ns.
  5357. */
  5358. rtt = tp->rcv_rtt_est.rtt_us;
  5359. if (tp->srtt_us && tp->srtt_us < rtt)
  5360. rtt = tp->srtt_us;
  5361. /* delay = (rtt >> 3) * NSEC_PER_USEC * comp_sack_rtt_percent / 100
  5362. * ->
  5363. * delay = rtt * 1.25 * comp_sack_rtt_percent
  5364. */
  5365. delay = (u64)(rtt + (rtt >> 2)) *
  5366. READ_ONCE(net->ipv4.sysctl_tcp_comp_sack_rtt_percent);
  5367. delay = min(delay, READ_ONCE(net->ipv4.sysctl_tcp_comp_sack_delay_ns));
  5368. sock_hold(sk);
  5369. hrtimer_start_range_ns(&tp->compressed_ack_timer, ns_to_ktime(delay),
  5370. READ_ONCE(net->ipv4.sysctl_tcp_comp_sack_slack_ns),
  5371. HRTIMER_MODE_REL_PINNED_SOFT);
  5372. }
  5373. static inline void tcp_ack_snd_check(struct sock *sk)
  5374. {
  5375. if (!inet_csk_ack_scheduled(sk)) {
  5376. /* We sent a data segment already. */
  5377. return;
  5378. }
  5379. __tcp_ack_snd_check(sk, 1);
  5380. }
  5381. /*
  5382. * This routine is only called when we have urgent data
  5383. * signaled. Its the 'slow' part of tcp_urg. It could be
  5384. * moved inline now as tcp_urg is only called from one
  5385. * place. We handle URGent data wrong. We have to - as
  5386. * BSD still doesn't use the correction from RFC961.
  5387. * For 1003.1g we should support a new option TCP_STDURG to permit
  5388. * either form (or just set the sysctl tcp_stdurg).
  5389. */
  5390. static void tcp_check_urg(struct sock *sk, const struct tcphdr *th)
  5391. {
  5392. struct tcp_sock *tp = tcp_sk(sk);
  5393. u32 ptr = ntohs(th->urg_ptr);
  5394. if (ptr && !READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_stdurg))
  5395. ptr--;
  5396. ptr += ntohl(th->seq);
  5397. /* Ignore urgent data that we've already seen and read. */
  5398. if (after(tp->copied_seq, ptr))
  5399. return;
  5400. /* Do not replay urg ptr.
  5401. *
  5402. * NOTE: interesting situation not covered by specs.
  5403. * Misbehaving sender may send urg ptr, pointing to segment,
  5404. * which we already have in ofo queue. We are not able to fetch
  5405. * such data and will stay in TCP_URG_NOTYET until will be eaten
  5406. * by recvmsg(). Seems, we are not obliged to handle such wicked
  5407. * situations. But it is worth to think about possibility of some
  5408. * DoSes using some hypothetical application level deadlock.
  5409. */
  5410. if (before(ptr, tp->rcv_nxt))
  5411. return;
  5412. /* Do we already have a newer (or duplicate) urgent pointer? */
  5413. if (tp->urg_data && !after(ptr, tp->urg_seq))
  5414. return;
  5415. /* Tell the world about our new urgent pointer. */
  5416. sk_send_sigurg(sk);
  5417. /* We may be adding urgent data when the last byte read was
  5418. * urgent. To do this requires some care. We cannot just ignore
  5419. * tp->copied_seq since we would read the last urgent byte again
  5420. * as data, nor can we alter copied_seq until this data arrives
  5421. * or we break the semantics of SIOCATMARK (and thus sockatmark())
  5422. *
  5423. * NOTE. Double Dutch. Rendering to plain English: author of comment
  5424. * above did something sort of send("A", MSG_OOB); send("B", MSG_OOB);
  5425. * and expect that both A and B disappear from stream. This is _wrong_.
  5426. * Though this happens in BSD with high probability, this is occasional.
  5427. * Any application relying on this is buggy. Note also, that fix "works"
  5428. * only in this artificial test. Insert some normal data between A and B and we will
  5429. * decline of BSD again. Verdict: it is better to remove to trap
  5430. * buggy users.
  5431. */
  5432. if (tp->urg_seq == tp->copied_seq && tp->urg_data &&
  5433. !sock_flag(sk, SOCK_URGINLINE) && tp->copied_seq != tp->rcv_nxt) {
  5434. struct sk_buff *skb = skb_peek(&sk->sk_receive_queue);
  5435. tp->copied_seq++;
  5436. if (skb && !before(tp->copied_seq, TCP_SKB_CB(skb)->end_seq)) {
  5437. __skb_unlink(skb, &sk->sk_receive_queue);
  5438. __kfree_skb(skb);
  5439. }
  5440. }
  5441. WRITE_ONCE(tp->urg_data, TCP_URG_NOTYET);
  5442. WRITE_ONCE(tp->urg_seq, ptr);
  5443. /* Disable header prediction. */
  5444. tp->pred_flags = 0;
  5445. }
  5446. /* This is the 'fast' part of urgent handling. */
  5447. static void tcp_urg(struct sock *sk, struct sk_buff *skb, const struct tcphdr *th)
  5448. {
  5449. struct tcp_sock *tp = tcp_sk(sk);
  5450. /* Check if we get a new urgent pointer - normally not. */
  5451. if (unlikely(th->urg))
  5452. tcp_check_urg(sk, th);
  5453. /* Do we wait for any urgent data? - normally not... */
  5454. if (unlikely(tp->urg_data == TCP_URG_NOTYET)) {
  5455. u32 ptr = tp->urg_seq - ntohl(th->seq) + (th->doff * 4) -
  5456. th->syn;
  5457. /* Is the urgent pointer pointing into this packet? */
  5458. if (ptr < skb->len) {
  5459. u8 tmp;
  5460. if (skb_copy_bits(skb, ptr, &tmp, 1))
  5461. BUG();
  5462. WRITE_ONCE(tp->urg_data, TCP_URG_VALID | tmp);
  5463. if (!sock_flag(sk, SOCK_DEAD))
  5464. READ_ONCE(sk->sk_data_ready)(sk);
  5465. }
  5466. }
  5467. }
  5468. /* Accept RST for rcv_nxt - 1 after a FIN.
  5469. * When tcp connections are abruptly terminated from Mac OSX (via ^C), a
  5470. * FIN is sent followed by a RST packet. The RST is sent with the same
  5471. * sequence number as the FIN, and thus according to RFC 5961 a challenge
  5472. * ACK should be sent. However, Mac OSX rate limits replies to challenge
  5473. * ACKs on the closed socket. In addition middleboxes can drop either the
  5474. * challenge ACK or a subsequent RST.
  5475. */
  5476. static bool tcp_reset_check(const struct sock *sk, const struct sk_buff *skb)
  5477. {
  5478. const struct tcp_sock *tp = tcp_sk(sk);
  5479. return unlikely(TCP_SKB_CB(skb)->seq == (tp->rcv_nxt - 1) &&
  5480. (1 << sk->sk_state) & (TCPF_CLOSE_WAIT | TCPF_LAST_ACK |
  5481. TCPF_CLOSING));
  5482. }
  5483. /* Does PAWS and seqno based validation of an incoming segment, flags will
  5484. * play significant role here.
  5485. */
  5486. static bool tcp_validate_incoming(struct sock *sk, struct sk_buff *skb,
  5487. const struct tcphdr *th, int syn_inerr)
  5488. {
  5489. struct tcp_sock *tp = tcp_sk(sk);
  5490. bool accecn_reflector = false;
  5491. SKB_DR(reason);
  5492. /* RFC1323: H1. Apply PAWS check first. */
  5493. if (!tcp_fast_parse_options(sock_net(sk), skb, th, tp) ||
  5494. !tp->rx_opt.saw_tstamp ||
  5495. tcp_paws_check(&tp->rx_opt, TCP_PAWS_WINDOW))
  5496. goto step1;
  5497. reason = tcp_disordered_ack_check(sk, skb);
  5498. if (!reason)
  5499. goto step1;
  5500. /* Reset is accepted even if it did not pass PAWS. */
  5501. if (th->rst)
  5502. goto step1;
  5503. if (unlikely(th->syn))
  5504. goto syn_challenge;
  5505. /* Old ACK are common, increment PAWS_OLD_ACK
  5506. * and do not send a dupack.
  5507. */
  5508. if (reason == SKB_DROP_REASON_TCP_RFC7323_PAWS_ACK) {
  5509. NET_INC_STATS(sock_net(sk), LINUX_MIB_PAWS_OLD_ACK);
  5510. goto discard;
  5511. }
  5512. NET_INC_STATS(sock_net(sk), LINUX_MIB_PAWSESTABREJECTED);
  5513. if (!tcp_oow_rate_limited(sock_net(sk), skb,
  5514. LINUX_MIB_TCPACKSKIPPEDPAWS,
  5515. &tp->last_oow_ack_time))
  5516. tcp_send_dupack(sk, skb);
  5517. goto discard;
  5518. step1:
  5519. /* Step 1: check sequence number */
  5520. reason = tcp_sequence(sk, TCP_SKB_CB(skb)->seq,
  5521. TCP_SKB_CB(skb)->end_seq, th);
  5522. if (reason) {
  5523. /* RFC793, page 37: "In all states except SYN-SENT, all reset
  5524. * (RST) segments are validated by checking their SEQ-fields."
  5525. * And page 69: "If an incoming segment is not acceptable,
  5526. * an acknowledgment should be sent in reply (unless the RST
  5527. * bit is set, if so drop the segment and return)".
  5528. */
  5529. if (!th->rst) {
  5530. if (th->syn)
  5531. goto syn_challenge;
  5532. if (reason == SKB_DROP_REASON_TCP_INVALID_SEQUENCE ||
  5533. reason == SKB_DROP_REASON_TCP_INVALID_END_SEQUENCE)
  5534. NET_INC_STATS(sock_net(sk),
  5535. LINUX_MIB_BEYOND_WINDOW);
  5536. if (!tcp_oow_rate_limited(sock_net(sk), skb,
  5537. LINUX_MIB_TCPACKSKIPPEDSEQ,
  5538. &tp->last_oow_ack_time))
  5539. tcp_send_dupack(sk, skb);
  5540. } else if (tcp_reset_check(sk, skb)) {
  5541. goto reset;
  5542. }
  5543. goto discard;
  5544. }
  5545. /* Step 2: check RST bit */
  5546. if (th->rst) {
  5547. /* RFC 5961 3.2 (extend to match against (RCV.NXT - 1) after a
  5548. * FIN and SACK too if available):
  5549. * If seq num matches RCV.NXT or (RCV.NXT - 1) after a FIN, or
  5550. * the right-most SACK block,
  5551. * then
  5552. * RESET the connection
  5553. * else
  5554. * Send a challenge ACK
  5555. */
  5556. if (TCP_SKB_CB(skb)->seq == tp->rcv_nxt ||
  5557. tcp_reset_check(sk, skb))
  5558. goto reset;
  5559. if (tcp_is_sack(tp) && tp->rx_opt.num_sacks > 0) {
  5560. struct tcp_sack_block *sp = &tp->selective_acks[0];
  5561. int max_sack = sp[0].end_seq;
  5562. int this_sack;
  5563. for (this_sack = 1; this_sack < tp->rx_opt.num_sacks;
  5564. ++this_sack) {
  5565. max_sack = after(sp[this_sack].end_seq,
  5566. max_sack) ?
  5567. sp[this_sack].end_seq : max_sack;
  5568. }
  5569. if (TCP_SKB_CB(skb)->seq == max_sack)
  5570. goto reset;
  5571. }
  5572. /* Disable TFO if RST is out-of-order
  5573. * and no data has been received
  5574. * for current active TFO socket
  5575. */
  5576. if (tp->syn_fastopen && !tp->data_segs_in &&
  5577. sk->sk_state == TCP_ESTABLISHED)
  5578. tcp_fastopen_active_disable(sk);
  5579. tcp_send_challenge_ack(sk, false);
  5580. SKB_DR_SET(reason, TCP_RESET);
  5581. goto discard;
  5582. }
  5583. /* step 3: check security and precedence [ignored] */
  5584. /* step 4: Check for a SYN
  5585. * RFC 5961 4.2 : Send a challenge ack
  5586. */
  5587. if (th->syn) {
  5588. if (tcp_ecn_mode_accecn(tp)) {
  5589. accecn_reflector = true;
  5590. tp->syn_ect_rcv = TCP_SKB_CB(skb)->ip_dsfield &
  5591. INET_ECN_MASK;
  5592. if (tp->rx_opt.accecn &&
  5593. tp->saw_accecn_opt < TCP_ACCECN_OPT_COUNTER_SEEN) {
  5594. u8 saw_opt = tcp_accecn_option_init(skb, tp->rx_opt.accecn);
  5595. tcp_accecn_saw_opt_fail_recv(tp, saw_opt);
  5596. tcp_accecn_opt_demand_min(sk, 1);
  5597. }
  5598. }
  5599. if (sk->sk_state == TCP_SYN_RECV && sk->sk_socket && th->ack &&
  5600. TCP_SKB_CB(skb)->seq + 1 == TCP_SKB_CB(skb)->end_seq &&
  5601. TCP_SKB_CB(skb)->seq + 1 == tp->rcv_nxt &&
  5602. TCP_SKB_CB(skb)->ack_seq == tp->snd_nxt)
  5603. goto pass;
  5604. syn_challenge:
  5605. if (syn_inerr)
  5606. TCP_INC_STATS(sock_net(sk), TCP_MIB_INERRS);
  5607. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPSYNCHALLENGE);
  5608. tcp_send_challenge_ack(sk, accecn_reflector);
  5609. SKB_DR_SET(reason, TCP_INVALID_SYN);
  5610. goto discard;
  5611. }
  5612. pass:
  5613. bpf_skops_parse_hdr(sk, skb);
  5614. return true;
  5615. discard:
  5616. tcp_drop_reason(sk, skb, reason);
  5617. return false;
  5618. reset:
  5619. tcp_reset(sk, skb);
  5620. __kfree_skb(skb);
  5621. return false;
  5622. }
  5623. /*
  5624. * TCP receive function for the ESTABLISHED state.
  5625. *
  5626. * It is split into a fast path and a slow path. The fast path is
  5627. * disabled when:
  5628. * - A zero window was announced from us - zero window probing
  5629. * is only handled properly in the slow path.
  5630. * - Out of order segments arrived.
  5631. * - Urgent data is expected.
  5632. * - There is no buffer space left
  5633. * - Unexpected TCP flags/window values/header lengths are received
  5634. * (detected by checking the TCP header against pred_flags)
  5635. * - Data is sent in both directions. Fast path only supports pure senders
  5636. * or pure receivers (this means either the sequence number or the ack
  5637. * value must stay constant)
  5638. * - Unexpected TCP option.
  5639. *
  5640. * When these conditions are not satisfied it drops into a standard
  5641. * receive procedure patterned after RFC793 to handle all cases.
  5642. * The first three cases are guaranteed by proper pred_flags setting,
  5643. * the rest is checked inline. Fast processing is turned on in
  5644. * tcp_data_queue when everything is OK.
  5645. */
  5646. void tcp_rcv_established(struct sock *sk, struct sk_buff *skb)
  5647. {
  5648. enum skb_drop_reason reason = SKB_DROP_REASON_NOT_SPECIFIED;
  5649. const struct tcphdr *th = (const struct tcphdr *)skb->data;
  5650. struct tcp_sock *tp = tcp_sk(sk);
  5651. unsigned int len = skb->len;
  5652. /* TCP congestion window tracking */
  5653. trace_tcp_probe(sk, skb);
  5654. tcp_mstamp_refresh(tp);
  5655. if (unlikely(!rcu_access_pointer(sk->sk_rx_dst)))
  5656. inet_csk(sk)->icsk_af_ops->sk_rx_dst_set(sk, skb);
  5657. /*
  5658. * Header prediction.
  5659. * The code loosely follows the one in the famous
  5660. * "30 instruction TCP receive" Van Jacobson mail.
  5661. *
  5662. * Van's trick is to deposit buffers into socket queue
  5663. * on a device interrupt, to call tcp_recv function
  5664. * on the receive process context and checksum and copy
  5665. * the buffer to user space. smart...
  5666. *
  5667. * Our current scheme is not silly either but we take the
  5668. * extra cost of the net_bh soft interrupt processing...
  5669. * We do checksum and copy also but from device to kernel.
  5670. */
  5671. tp->rx_opt.saw_tstamp = 0;
  5672. tp->rx_opt.accecn = 0;
  5673. /* pred_flags is 0xS?10 << 16 + snd_wnd
  5674. * if header_prediction is to be made
  5675. * 'S' will always be tp->tcp_header_len >> 2
  5676. * '?' will be 0 for the fast path, otherwise pred_flags is 0 to
  5677. * turn it off (when there are holes in the receive
  5678. * space for instance)
  5679. * PSH flag is ignored.
  5680. */
  5681. if ((tcp_flag_word(th) & TCP_HP_BITS) == tp->pred_flags &&
  5682. TCP_SKB_CB(skb)->seq == tp->rcv_nxt &&
  5683. !after(TCP_SKB_CB(skb)->ack_seq, tp->snd_nxt)) {
  5684. int tcp_header_len = tp->tcp_header_len;
  5685. s32 delta = 0;
  5686. int flag = 0;
  5687. /* Timestamp header prediction: tcp_header_len
  5688. * is automatically equal to th->doff*4 due to pred_flags
  5689. * match.
  5690. */
  5691. /* Check timestamp */
  5692. if (tcp_header_len == sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED) {
  5693. /* No? Slow path! */
  5694. if (!tcp_parse_aligned_timestamp(tp, th))
  5695. goto slow_path;
  5696. delta = tp->rx_opt.rcv_tsval -
  5697. tp->rx_opt.ts_recent;
  5698. /* If PAWS failed, check it more carefully in slow path */
  5699. if (delta < 0)
  5700. goto slow_path;
  5701. /* DO NOT update ts_recent here, if checksum fails
  5702. * and timestamp was corrupted part, it will result
  5703. * in a hung connection since we will drop all
  5704. * future packets due to the PAWS test.
  5705. */
  5706. }
  5707. if (len <= tcp_header_len) {
  5708. /* Bulk data transfer: sender */
  5709. if (len == tcp_header_len) {
  5710. /* Predicted packet is in window by definition.
  5711. * seq == rcv_nxt and rcv_wup <= rcv_nxt.
  5712. * Hence, check seq<=rcv_wup reduces to:
  5713. */
  5714. if (tcp_header_len ==
  5715. (sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED) &&
  5716. tp->rcv_nxt == tp->rcv_wup)
  5717. flag |= __tcp_replace_ts_recent(tp,
  5718. delta);
  5719. tcp_ecn_received_counters(sk, skb, 0);
  5720. /* We know that such packets are checksummed
  5721. * on entry.
  5722. */
  5723. tcp_ack(sk, skb, flag);
  5724. __kfree_skb(skb);
  5725. tcp_data_snd_check(sk);
  5726. /* When receiving pure ack in fast path, update
  5727. * last ts ecr directly instead of calling
  5728. * tcp_rcv_rtt_measure_ts()
  5729. */
  5730. tp->rcv_rtt_last_tsecr = tp->rx_opt.rcv_tsecr;
  5731. return;
  5732. } else { /* Header too small */
  5733. reason = SKB_DROP_REASON_PKT_TOO_SMALL;
  5734. TCP_INC_STATS(sock_net(sk), TCP_MIB_INERRS);
  5735. goto discard;
  5736. }
  5737. } else {
  5738. int eaten = 0;
  5739. bool fragstolen = false;
  5740. if (tcp_checksum_complete(skb))
  5741. goto csum_error;
  5742. if (after(TCP_SKB_CB(skb)->end_seq,
  5743. tp->rcv_nxt + tcp_receive_window(tp)))
  5744. goto validate;
  5745. if ((int)skb->truesize > sk->sk_forward_alloc)
  5746. goto step5;
  5747. /* Predicted packet is in window by definition.
  5748. * seq == rcv_nxt and rcv_wup <= rcv_nxt.
  5749. * Hence, check seq<=rcv_wup reduces to:
  5750. */
  5751. if (tcp_header_len ==
  5752. (sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED) &&
  5753. tp->rcv_nxt == tp->rcv_wup)
  5754. flag |= __tcp_replace_ts_recent(tp,
  5755. delta);
  5756. tcp_rcv_rtt_measure_ts(sk, skb);
  5757. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPHPHITS);
  5758. /* Bulk data transfer: receiver */
  5759. tcp_cleanup_skb(skb);
  5760. __skb_pull(skb, tcp_header_len);
  5761. tcp_ecn_received_counters(sk, skb,
  5762. len - tcp_header_len);
  5763. eaten = tcp_queue_rcv(sk, skb, &fragstolen);
  5764. tcp_event_data_recv(sk, skb);
  5765. if (TCP_SKB_CB(skb)->ack_seq != tp->snd_una) {
  5766. /* Well, only one small jumplet in fast path... */
  5767. tcp_ack(sk, skb, flag | FLAG_DATA);
  5768. tcp_data_snd_check(sk);
  5769. if (!inet_csk_ack_scheduled(sk))
  5770. goto no_ack;
  5771. } else {
  5772. tcp_update_wl(tp, TCP_SKB_CB(skb)->seq);
  5773. }
  5774. __tcp_ack_snd_check(sk, 0);
  5775. no_ack:
  5776. if (eaten)
  5777. kfree_skb_partial(skb, fragstolen);
  5778. tcp_data_ready(sk);
  5779. return;
  5780. }
  5781. }
  5782. slow_path:
  5783. if (len < (th->doff << 2) || tcp_checksum_complete(skb))
  5784. goto csum_error;
  5785. if (!th->ack && !th->rst && !th->syn) {
  5786. reason = SKB_DROP_REASON_TCP_FLAGS;
  5787. goto discard;
  5788. }
  5789. /*
  5790. * Standard slow path.
  5791. */
  5792. validate:
  5793. if (!tcp_validate_incoming(sk, skb, th, 1))
  5794. return;
  5795. step5:
  5796. tcp_ecn_received_counters_payload(sk, skb);
  5797. reason = tcp_ack(sk, skb, FLAG_SLOWPATH | FLAG_UPDATE_TS_RECENT);
  5798. if ((int)reason < 0) {
  5799. reason = -reason;
  5800. goto discard;
  5801. }
  5802. tcp_rcv_rtt_measure_ts(sk, skb);
  5803. /* Process urgent data. */
  5804. tcp_urg(sk, skb, th);
  5805. /* step 7: process the segment text */
  5806. tcp_data_queue(sk, skb);
  5807. tcp_data_snd_check(sk);
  5808. tcp_ack_snd_check(sk);
  5809. return;
  5810. csum_error:
  5811. reason = SKB_DROP_REASON_TCP_CSUM;
  5812. trace_tcp_bad_csum(skb);
  5813. TCP_INC_STATS(sock_net(sk), TCP_MIB_CSUMERRORS);
  5814. TCP_INC_STATS(sock_net(sk), TCP_MIB_INERRS);
  5815. discard:
  5816. tcp_drop_reason(sk, skb, reason);
  5817. }
  5818. EXPORT_IPV6_MOD(tcp_rcv_established);
  5819. void tcp_init_transfer(struct sock *sk, int bpf_op, struct sk_buff *skb)
  5820. {
  5821. struct inet_connection_sock *icsk = inet_csk(sk);
  5822. struct tcp_sock *tp = tcp_sk(sk);
  5823. tcp_mtup_init(sk);
  5824. icsk->icsk_af_ops->rebuild_header(sk);
  5825. tcp_init_metrics(sk);
  5826. /* Initialize the congestion window to start the transfer.
  5827. * Cut cwnd down to 1 per RFC5681 if SYN or SYN-ACK has been
  5828. * retransmitted. In light of RFC6298 more aggressive 1sec
  5829. * initRTO, we only reset cwnd when more than 1 SYN/SYN-ACK
  5830. * retransmission has occurred.
  5831. */
  5832. if (tp->total_retrans > 1 && tp->undo_marker)
  5833. tcp_snd_cwnd_set(tp, 1);
  5834. else
  5835. tcp_snd_cwnd_set(tp, tcp_init_cwnd(tp, __sk_dst_get(sk)));
  5836. tp->snd_cwnd_stamp = tcp_jiffies32;
  5837. bpf_skops_established(sk, bpf_op, skb);
  5838. /* Initialize congestion control unless BPF initialized it already: */
  5839. if (!icsk->icsk_ca_initialized)
  5840. tcp_init_congestion_control(sk);
  5841. tcp_init_buffer_space(sk);
  5842. }
  5843. void tcp_finish_connect(struct sock *sk, struct sk_buff *skb)
  5844. {
  5845. struct tcp_sock *tp = tcp_sk(sk);
  5846. struct inet_connection_sock *icsk = inet_csk(sk);
  5847. tcp_ao_finish_connect(sk, skb);
  5848. tcp_set_state(sk, TCP_ESTABLISHED);
  5849. icsk->icsk_ack.lrcvtime = tcp_jiffies32;
  5850. if (skb) {
  5851. icsk->icsk_af_ops->sk_rx_dst_set(sk, skb);
  5852. security_inet_conn_established(sk, skb);
  5853. sk_mark_napi_id(sk, skb);
  5854. }
  5855. tcp_init_transfer(sk, BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB, skb);
  5856. /* Prevent spurious tcp_cwnd_restart() on first data
  5857. * packet.
  5858. */
  5859. tp->lsndtime = tcp_jiffies32;
  5860. if (sock_flag(sk, SOCK_KEEPOPEN))
  5861. tcp_reset_keepalive_timer(sk, keepalive_time_when(tp));
  5862. if (!tp->rx_opt.snd_wscale)
  5863. __tcp_fast_path_on(tp, tp->snd_wnd);
  5864. else
  5865. tp->pred_flags = 0;
  5866. }
  5867. static bool tcp_rcv_fastopen_synack(struct sock *sk, struct sk_buff *synack,
  5868. struct tcp_fastopen_cookie *cookie)
  5869. {
  5870. struct tcp_sock *tp = tcp_sk(sk);
  5871. struct sk_buff *data = tp->syn_data ? tcp_rtx_queue_head(sk) : NULL;
  5872. u16 mss = tp->rx_opt.mss_clamp, try_exp = 0;
  5873. bool syn_drop = false;
  5874. if (mss == READ_ONCE(tp->rx_opt.user_mss)) {
  5875. struct tcp_options_received opt;
  5876. /* Get original SYNACK MSS value if user MSS sets mss_clamp */
  5877. tcp_clear_options(&opt);
  5878. opt.user_mss = opt.mss_clamp = 0;
  5879. tcp_parse_options(sock_net(sk), synack, &opt, 0, NULL);
  5880. mss = opt.mss_clamp;
  5881. }
  5882. if (!tp->syn_fastopen) {
  5883. /* Ignore an unsolicited cookie */
  5884. cookie->len = -1;
  5885. } else if (tp->total_retrans) {
  5886. /* SYN timed out and the SYN-ACK neither has a cookie nor
  5887. * acknowledges data. Presumably the remote received only
  5888. * the retransmitted (regular) SYNs: either the original
  5889. * SYN-data or the corresponding SYN-ACK was dropped.
  5890. */
  5891. syn_drop = (cookie->len < 0 && data);
  5892. } else if (cookie->len < 0 && !tp->syn_data) {
  5893. /* We requested a cookie but didn't get it. If we did not use
  5894. * the (old) exp opt format then try so next time (try_exp=1).
  5895. * Otherwise we go back to use the RFC7413 opt (try_exp=2).
  5896. */
  5897. try_exp = tp->syn_fastopen_exp ? 2 : 1;
  5898. }
  5899. tcp_fastopen_cache_set(sk, mss, cookie, syn_drop, try_exp);
  5900. if (data) { /* Retransmit unacked data in SYN */
  5901. if (tp->total_retrans)
  5902. tp->fastopen_client_fail = TFO_SYN_RETRANSMITTED;
  5903. else
  5904. tp->fastopen_client_fail = TFO_DATA_NOT_ACKED;
  5905. skb_rbtree_walk_from(data)
  5906. tcp_mark_skb_lost(sk, data);
  5907. tcp_non_congestion_loss_retransmit(sk);
  5908. NET_INC_STATS(sock_net(sk),
  5909. LINUX_MIB_TCPFASTOPENACTIVEFAIL);
  5910. return true;
  5911. }
  5912. tp->syn_data_acked = tp->syn_data;
  5913. if (tp->syn_data_acked) {
  5914. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPFASTOPENACTIVE);
  5915. /* SYN-data is counted as two separate packets in tcp_ack() */
  5916. if (tp->delivered > 1)
  5917. --tp->delivered;
  5918. }
  5919. tcp_fastopen_add_skb(sk, synack);
  5920. return false;
  5921. }
  5922. static void smc_check_reset_syn(struct tcp_sock *tp)
  5923. {
  5924. #if IS_ENABLED(CONFIG_SMC)
  5925. if (static_branch_unlikely(&tcp_have_smc)) {
  5926. if (tp->syn_smc && !tp->rx_opt.smc_ok)
  5927. tp->syn_smc = 0;
  5928. }
  5929. #endif
  5930. }
  5931. static void tcp_try_undo_spurious_syn(struct sock *sk)
  5932. {
  5933. struct tcp_sock *tp = tcp_sk(sk);
  5934. u32 syn_stamp;
  5935. /* undo_marker is set when SYN or SYNACK times out. The timeout is
  5936. * spurious if the ACK's timestamp option echo value matches the
  5937. * original SYN timestamp.
  5938. */
  5939. syn_stamp = tp->retrans_stamp;
  5940. if (tp->undo_marker && syn_stamp && tp->rx_opt.saw_tstamp &&
  5941. syn_stamp == tp->rx_opt.rcv_tsecr)
  5942. tp->undo_marker = 0;
  5943. }
  5944. static int tcp_rcv_synsent_state_process(struct sock *sk, struct sk_buff *skb,
  5945. const struct tcphdr *th)
  5946. {
  5947. struct inet_connection_sock *icsk = inet_csk(sk);
  5948. struct tcp_sock *tp = tcp_sk(sk);
  5949. struct tcp_fastopen_cookie foc = { .len = -1 };
  5950. int saved_clamp = tp->rx_opt.mss_clamp;
  5951. bool fastopen_fail;
  5952. SKB_DR(reason);
  5953. tcp_parse_options(sock_net(sk), skb, &tp->rx_opt, 0, &foc);
  5954. if (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr)
  5955. tp->rx_opt.rcv_tsecr -= tp->tsoffset;
  5956. if (th->ack) {
  5957. /* rfc793:
  5958. * "If the state is SYN-SENT then
  5959. * first check the ACK bit
  5960. * If the ACK bit is set
  5961. * If SEG.ACK =< ISS, or SEG.ACK > SND.NXT, send
  5962. * a reset (unless the RST bit is set, if so drop
  5963. * the segment and return)"
  5964. */
  5965. if (!after(TCP_SKB_CB(skb)->ack_seq, tp->snd_una) ||
  5966. after(TCP_SKB_CB(skb)->ack_seq, tp->snd_nxt)) {
  5967. /* Previous FIN/ACK or RST/ACK might be ignored. */
  5968. if (icsk->icsk_retransmits == 0)
  5969. tcp_reset_xmit_timer(sk, ICSK_TIME_RETRANS,
  5970. TCP_TIMEOUT_MIN, false);
  5971. SKB_DR_SET(reason, TCP_INVALID_ACK_SEQUENCE);
  5972. goto reset_and_undo;
  5973. }
  5974. if (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr &&
  5975. !between(tp->rx_opt.rcv_tsecr, tp->retrans_stamp,
  5976. tcp_time_stamp_ts(tp))) {
  5977. NET_INC_STATS(sock_net(sk),
  5978. LINUX_MIB_PAWSACTIVEREJECTED);
  5979. SKB_DR_SET(reason, TCP_RFC7323_PAWS);
  5980. goto reset_and_undo;
  5981. }
  5982. /* Now ACK is acceptable.
  5983. *
  5984. * "If the RST bit is set
  5985. * If the ACK was acceptable then signal the user "error:
  5986. * connection reset", drop the segment, enter CLOSED state,
  5987. * delete TCB, and return."
  5988. */
  5989. if (th->rst) {
  5990. tcp_reset(sk, skb);
  5991. consume:
  5992. __kfree_skb(skb);
  5993. return 0;
  5994. }
  5995. /* rfc793:
  5996. * "fifth, if neither of the SYN or RST bits is set then
  5997. * drop the segment and return."
  5998. *
  5999. * See note below!
  6000. * --ANK(990513)
  6001. */
  6002. if (!th->syn) {
  6003. SKB_DR_SET(reason, TCP_FLAGS);
  6004. goto discard_and_undo;
  6005. }
  6006. /* rfc793:
  6007. * "If the SYN bit is on ...
  6008. * are acceptable then ...
  6009. * (our SYN has been ACKed), change the connection
  6010. * state to ESTABLISHED..."
  6011. */
  6012. if (tcp_ecn_mode_any(tp))
  6013. tcp_ecn_rcv_synack(sk, skb, th,
  6014. TCP_SKB_CB(skb)->ip_dsfield);
  6015. tcp_init_wl(tp, TCP_SKB_CB(skb)->seq);
  6016. tcp_try_undo_spurious_syn(sk);
  6017. tcp_ack(sk, skb, FLAG_SLOWPATH);
  6018. /* Ok.. it's good. Set up sequence numbers and
  6019. * move to established.
  6020. */
  6021. WRITE_ONCE(tp->rcv_nxt, TCP_SKB_CB(skb)->seq + 1);
  6022. tp->rcv_wup = TCP_SKB_CB(skb)->seq + 1;
  6023. /* RFC1323: The window in SYN & SYN/ACK segments is
  6024. * never scaled.
  6025. */
  6026. tp->snd_wnd = ntohs(th->window);
  6027. if (!tp->rx_opt.wscale_ok) {
  6028. tp->rx_opt.snd_wscale = tp->rx_opt.rcv_wscale = 0;
  6029. WRITE_ONCE(tp->window_clamp,
  6030. min(tp->window_clamp, 65535U));
  6031. }
  6032. if (tp->rx_opt.saw_tstamp) {
  6033. tp->rx_opt.tstamp_ok = 1;
  6034. tp->tcp_header_len =
  6035. sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED;
  6036. tp->advmss -= TCPOLEN_TSTAMP_ALIGNED;
  6037. tcp_store_ts_recent(tp);
  6038. } else {
  6039. tp->tcp_header_len = sizeof(struct tcphdr);
  6040. }
  6041. tcp_sync_mss(sk, icsk->icsk_pmtu_cookie);
  6042. tcp_initialize_rcv_mss(sk);
  6043. /* Remember, tcp_poll() does not lock socket!
  6044. * Change state from SYN-SENT only after copied_seq
  6045. * is initialized. */
  6046. WRITE_ONCE(tp->copied_seq, tp->rcv_nxt);
  6047. smc_check_reset_syn(tp);
  6048. smp_mb();
  6049. tcp_finish_connect(sk, skb);
  6050. fastopen_fail = (tp->syn_fastopen || tp->syn_data) &&
  6051. tcp_rcv_fastopen_synack(sk, skb, &foc);
  6052. if (!sock_flag(sk, SOCK_DEAD)) {
  6053. sk->sk_state_change(sk);
  6054. sk_wake_async(sk, SOCK_WAKE_IO, POLL_OUT);
  6055. }
  6056. if (fastopen_fail)
  6057. return -1;
  6058. if (sk->sk_write_pending ||
  6059. READ_ONCE(icsk->icsk_accept_queue.rskq_defer_accept) ||
  6060. inet_csk_in_pingpong_mode(sk)) {
  6061. /* Save one ACK. Data will be ready after
  6062. * several ticks, if write_pending is set.
  6063. *
  6064. * It may be deleted, but with this feature tcpdumps
  6065. * look so _wonderfully_ clever, that I was not able
  6066. * to stand against the temptation 8) --ANK
  6067. */
  6068. inet_csk_schedule_ack(sk);
  6069. tcp_enter_quickack_mode(sk, TCP_MAX_QUICKACKS);
  6070. tcp_reset_xmit_timer(sk, ICSK_TIME_DACK,
  6071. TCP_DELACK_MAX, false);
  6072. goto consume;
  6073. }
  6074. tcp_send_ack_reflect_ect(sk, tcp_ecn_mode_accecn(tp));
  6075. return -1;
  6076. }
  6077. /* No ACK in the segment */
  6078. if (th->rst) {
  6079. /* rfc793:
  6080. * "If the RST bit is set
  6081. *
  6082. * Otherwise (no ACK) drop the segment and return."
  6083. */
  6084. SKB_DR_SET(reason, TCP_RESET);
  6085. goto discard_and_undo;
  6086. }
  6087. /* PAWS check. */
  6088. if (tp->rx_opt.ts_recent_stamp && tp->rx_opt.saw_tstamp &&
  6089. tcp_paws_reject(&tp->rx_opt, 0)) {
  6090. SKB_DR_SET(reason, TCP_RFC7323_PAWS);
  6091. goto discard_and_undo;
  6092. }
  6093. if (th->syn) {
  6094. /* We see SYN without ACK. It is attempt of
  6095. * simultaneous connect with crossed SYNs.
  6096. * Particularly, it can be connect to self.
  6097. */
  6098. #ifdef CONFIG_TCP_AO
  6099. struct tcp_ao_info *ao;
  6100. ao = rcu_dereference_protected(tp->ao_info,
  6101. lockdep_sock_is_held(sk));
  6102. if (ao) {
  6103. WRITE_ONCE(ao->risn, th->seq);
  6104. ao->rcv_sne = 0;
  6105. }
  6106. #endif
  6107. tcp_set_state(sk, TCP_SYN_RECV);
  6108. if (tp->rx_opt.saw_tstamp) {
  6109. tp->rx_opt.tstamp_ok = 1;
  6110. tcp_store_ts_recent(tp);
  6111. tp->tcp_header_len =
  6112. sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED;
  6113. } else {
  6114. tp->tcp_header_len = sizeof(struct tcphdr);
  6115. }
  6116. WRITE_ONCE(tp->rcv_nxt, TCP_SKB_CB(skb)->seq + 1);
  6117. WRITE_ONCE(tp->copied_seq, tp->rcv_nxt);
  6118. tp->rcv_wup = TCP_SKB_CB(skb)->seq + 1;
  6119. /* RFC1323: The window in SYN & SYN/ACK segments is
  6120. * never scaled.
  6121. */
  6122. tp->snd_wnd = ntohs(th->window);
  6123. tp->snd_wl1 = TCP_SKB_CB(skb)->seq;
  6124. tp->max_window = tp->snd_wnd;
  6125. tcp_ecn_rcv_syn(sk, th, skb);
  6126. tcp_mtup_init(sk);
  6127. tcp_sync_mss(sk, icsk->icsk_pmtu_cookie);
  6128. tcp_initialize_rcv_mss(sk);
  6129. tcp_send_synack(sk);
  6130. #if 0
  6131. /* Note, we could accept data and URG from this segment.
  6132. * There are no obstacles to make this (except that we must
  6133. * either change tcp_recvmsg() to prevent it from returning data
  6134. * before 3WHS completes per RFC793, or employ TCP Fast Open).
  6135. *
  6136. * However, if we ignore data in ACKless segments sometimes,
  6137. * we have no reasons to accept it sometimes.
  6138. * Also, seems the code doing it in step6 of tcp_rcv_state_process
  6139. * is not flawless. So, discard packet for sanity.
  6140. * Uncomment this return to process the data.
  6141. */
  6142. return -1;
  6143. #else
  6144. goto consume;
  6145. #endif
  6146. }
  6147. /* "fifth, if neither of the SYN or RST bits is set then
  6148. * drop the segment and return."
  6149. */
  6150. discard_and_undo:
  6151. tcp_clear_options(&tp->rx_opt);
  6152. tp->rx_opt.mss_clamp = saved_clamp;
  6153. tcp_drop_reason(sk, skb, reason);
  6154. return 0;
  6155. reset_and_undo:
  6156. tcp_clear_options(&tp->rx_opt);
  6157. tp->rx_opt.mss_clamp = saved_clamp;
  6158. /* we can reuse/return @reason to its caller to handle the exception */
  6159. return reason;
  6160. }
  6161. static void tcp_rcv_synrecv_state_fastopen(struct sock *sk)
  6162. {
  6163. struct tcp_sock *tp = tcp_sk(sk);
  6164. struct request_sock *req;
  6165. /* If we are still handling the SYNACK RTO, see if timestamp ECR allows
  6166. * undo. If peer SACKs triggered fast recovery, we can't undo here.
  6167. */
  6168. if (inet_csk(sk)->icsk_ca_state == TCP_CA_Loss && !tp->packets_out)
  6169. tcp_try_undo_recovery(sk);
  6170. tcp_update_rto_time(tp);
  6171. WRITE_ONCE(inet_csk(sk)->icsk_retransmits, 0);
  6172. /* In tcp_fastopen_synack_timer() on the first SYNACK RTO we set
  6173. * retrans_stamp but don't enter CA_Loss, so in case that happened we
  6174. * need to zero retrans_stamp here to prevent spurious
  6175. * retransmits_timed_out(). However, if the ACK of our SYNACK caused us
  6176. * to enter CA_Recovery then we need to leave retrans_stamp as it was
  6177. * set entering CA_Recovery, for correct retransmits_timed_out() and
  6178. * undo behavior.
  6179. */
  6180. tcp_retrans_stamp_cleanup(sk);
  6181. /* Once we leave TCP_SYN_RECV or TCP_FIN_WAIT_1,
  6182. * we no longer need req so release it.
  6183. */
  6184. req = rcu_dereference_protected(tp->fastopen_rsk,
  6185. lockdep_sock_is_held(sk));
  6186. reqsk_fastopen_remove(sk, req, false);
  6187. /* Re-arm the timer because data may have been sent out.
  6188. * This is similar to the regular data transmission case
  6189. * when new data has just been ack'ed.
  6190. *
  6191. * (TFO) - we could try to be more aggressive and
  6192. * retransmitting any data sooner based on when they
  6193. * are sent out.
  6194. */
  6195. tcp_rearm_rto(sk);
  6196. }
  6197. /*
  6198. * This function implements the receiving procedure of RFC 793 for
  6199. * all states except ESTABLISHED and TIME_WAIT.
  6200. * It's called from both tcp_v4_rcv and tcp_v6_rcv and should be
  6201. * address independent.
  6202. */
  6203. enum skb_drop_reason
  6204. tcp_rcv_state_process(struct sock *sk, struct sk_buff *skb)
  6205. {
  6206. struct tcp_sock *tp = tcp_sk(sk);
  6207. struct inet_connection_sock *icsk = inet_csk(sk);
  6208. const struct tcphdr *th = tcp_hdr(skb);
  6209. struct request_sock *req;
  6210. int queued = 0;
  6211. SKB_DR(reason);
  6212. switch (sk->sk_state) {
  6213. case TCP_CLOSE:
  6214. SKB_DR_SET(reason, TCP_CLOSE);
  6215. goto discard;
  6216. case TCP_LISTEN:
  6217. if (th->ack)
  6218. return SKB_DROP_REASON_TCP_FLAGS;
  6219. if (th->rst) {
  6220. SKB_DR_SET(reason, TCP_RESET);
  6221. goto discard;
  6222. }
  6223. if (th->syn) {
  6224. if (th->fin) {
  6225. SKB_DR_SET(reason, TCP_FLAGS);
  6226. goto discard;
  6227. }
  6228. /* It is possible that we process SYN packets from backlog,
  6229. * so we need to make sure to disable BH and RCU right there.
  6230. */
  6231. rcu_read_lock();
  6232. local_bh_disable();
  6233. icsk->icsk_af_ops->conn_request(sk, skb);
  6234. local_bh_enable();
  6235. rcu_read_unlock();
  6236. consume_skb(skb);
  6237. return 0;
  6238. }
  6239. SKB_DR_SET(reason, TCP_FLAGS);
  6240. goto discard;
  6241. case TCP_SYN_SENT:
  6242. tp->rx_opt.saw_tstamp = 0;
  6243. tcp_mstamp_refresh(tp);
  6244. queued = tcp_rcv_synsent_state_process(sk, skb, th);
  6245. if (queued >= 0)
  6246. return queued;
  6247. /* Do step6 onward by hand. */
  6248. tcp_urg(sk, skb, th);
  6249. __kfree_skb(skb);
  6250. tcp_data_snd_check(sk);
  6251. return 0;
  6252. }
  6253. tcp_mstamp_refresh(tp);
  6254. tp->rx_opt.saw_tstamp = 0;
  6255. req = rcu_dereference_protected(tp->fastopen_rsk,
  6256. lockdep_sock_is_held(sk));
  6257. if (req) {
  6258. bool req_stolen;
  6259. WARN_ON_ONCE(sk->sk_state != TCP_SYN_RECV &&
  6260. sk->sk_state != TCP_FIN_WAIT1);
  6261. SKB_DR_SET(reason, TCP_FASTOPEN);
  6262. if (!tcp_check_req(sk, skb, req, true, &req_stolen, &reason))
  6263. goto discard;
  6264. }
  6265. if (!th->ack && !th->rst && !th->syn) {
  6266. SKB_DR_SET(reason, TCP_FLAGS);
  6267. goto discard;
  6268. }
  6269. if (!tcp_validate_incoming(sk, skb, th, 0))
  6270. return 0;
  6271. /* step 5: check the ACK field */
  6272. reason = tcp_ack(sk, skb, FLAG_SLOWPATH |
  6273. FLAG_UPDATE_TS_RECENT |
  6274. FLAG_NO_CHALLENGE_ACK);
  6275. if ((int)reason <= 0) {
  6276. if (sk->sk_state == TCP_SYN_RECV) {
  6277. /* send one RST */
  6278. if (!reason)
  6279. return SKB_DROP_REASON_TCP_OLD_ACK;
  6280. return -reason;
  6281. }
  6282. /* accept old ack during closing */
  6283. if ((int)reason < 0) {
  6284. tcp_send_challenge_ack(sk, false);
  6285. reason = -reason;
  6286. goto discard;
  6287. }
  6288. }
  6289. SKB_DR_SET(reason, NOT_SPECIFIED);
  6290. switch (sk->sk_state) {
  6291. case TCP_SYN_RECV:
  6292. tp->delivered++; /* SYN-ACK delivery isn't tracked in tcp_ack */
  6293. if (!tp->srtt_us)
  6294. tcp_synack_rtt_meas(sk, req);
  6295. if (tp->rx_opt.tstamp_ok)
  6296. tp->advmss -= TCPOLEN_TSTAMP_ALIGNED;
  6297. if (req) {
  6298. tcp_rcv_synrecv_state_fastopen(sk);
  6299. } else {
  6300. tcp_try_undo_spurious_syn(sk);
  6301. tp->retrans_stamp = 0;
  6302. tcp_init_transfer(sk, BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB,
  6303. skb);
  6304. WRITE_ONCE(tp->copied_seq, tp->rcv_nxt);
  6305. }
  6306. tcp_ao_established(sk);
  6307. smp_mb();
  6308. tcp_set_state(sk, TCP_ESTABLISHED);
  6309. sk->sk_state_change(sk);
  6310. /* Note, that this wakeup is only for marginal crossed SYN case.
  6311. * Passively open sockets are not waked up, because
  6312. * sk->sk_sleep == NULL and sk->sk_socket == NULL.
  6313. */
  6314. if (sk->sk_socket)
  6315. sk_wake_async(sk, SOCK_WAKE_IO, POLL_OUT);
  6316. tp->snd_una = TCP_SKB_CB(skb)->ack_seq;
  6317. tp->snd_wnd = ntohs(th->window) << tp->rx_opt.snd_wscale;
  6318. tcp_init_wl(tp, TCP_SKB_CB(skb)->seq);
  6319. if (!inet_csk(sk)->icsk_ca_ops->cong_control)
  6320. tcp_update_pacing_rate(sk);
  6321. /* Prevent spurious tcp_cwnd_restart() on first data packet */
  6322. tp->lsndtime = tcp_jiffies32;
  6323. tcp_initialize_rcv_mss(sk);
  6324. if (tcp_ecn_mode_accecn(tp))
  6325. tcp_accecn_third_ack(sk, skb, tp->syn_ect_snt);
  6326. tcp_fast_path_on(tp);
  6327. if (sk->sk_shutdown & SEND_SHUTDOWN)
  6328. tcp_shutdown(sk, SEND_SHUTDOWN);
  6329. break;
  6330. case TCP_FIN_WAIT1: {
  6331. int tmo;
  6332. if (req)
  6333. tcp_rcv_synrecv_state_fastopen(sk);
  6334. if (tp->snd_una != tp->write_seq)
  6335. break;
  6336. tcp_set_state(sk, TCP_FIN_WAIT2);
  6337. WRITE_ONCE(sk->sk_shutdown, sk->sk_shutdown | SEND_SHUTDOWN);
  6338. sk_dst_confirm(sk);
  6339. if (!sock_flag(sk, SOCK_DEAD)) {
  6340. /* Wake up lingering close() */
  6341. sk->sk_state_change(sk);
  6342. break;
  6343. }
  6344. if (READ_ONCE(tp->linger2) < 0) {
  6345. tcp_done(sk);
  6346. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONDATA);
  6347. return SKB_DROP_REASON_TCP_ABORT_ON_DATA;
  6348. }
  6349. if (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq &&
  6350. after(TCP_SKB_CB(skb)->end_seq - th->fin, tp->rcv_nxt)) {
  6351. /* Receive out of order FIN after close() */
  6352. if (tp->syn_fastopen && th->fin)
  6353. tcp_fastopen_active_disable(sk);
  6354. tcp_done(sk);
  6355. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONDATA);
  6356. return SKB_DROP_REASON_TCP_ABORT_ON_DATA;
  6357. }
  6358. tmo = tcp_fin_time(sk);
  6359. if (tmo > TCP_TIMEWAIT_LEN) {
  6360. tcp_reset_keepalive_timer(sk, tmo - TCP_TIMEWAIT_LEN);
  6361. } else if (th->fin || sock_owned_by_user(sk)) {
  6362. /* Bad case. We could lose such FIN otherwise.
  6363. * It is not a big problem, but it looks confusing
  6364. * and not so rare event. We still can lose it now,
  6365. * if it spins in bh_lock_sock(), but it is really
  6366. * marginal case.
  6367. */
  6368. tcp_reset_keepalive_timer(sk, tmo);
  6369. } else {
  6370. tcp_time_wait(sk, TCP_FIN_WAIT2, tmo);
  6371. goto consume;
  6372. }
  6373. break;
  6374. }
  6375. case TCP_CLOSING:
  6376. if (tp->snd_una == tp->write_seq) {
  6377. tcp_time_wait(sk, TCP_TIME_WAIT, 0);
  6378. goto consume;
  6379. }
  6380. break;
  6381. case TCP_LAST_ACK:
  6382. if (tp->snd_una == tp->write_seq) {
  6383. tcp_update_metrics(sk);
  6384. tcp_done(sk);
  6385. goto consume;
  6386. }
  6387. break;
  6388. }
  6389. /* step 6: check the URG bit */
  6390. tcp_urg(sk, skb, th);
  6391. /* step 7: process the segment text */
  6392. switch (sk->sk_state) {
  6393. case TCP_CLOSE_WAIT:
  6394. case TCP_CLOSING:
  6395. case TCP_LAST_ACK:
  6396. if (!before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) {
  6397. /* If a subflow has been reset, the packet should not
  6398. * continue to be processed, drop the packet.
  6399. */
  6400. if (sk_is_mptcp(sk) && !mptcp_incoming_options(sk, skb))
  6401. goto discard;
  6402. break;
  6403. }
  6404. fallthrough;
  6405. case TCP_FIN_WAIT1:
  6406. case TCP_FIN_WAIT2:
  6407. /* RFC 793 says to queue data in these states,
  6408. * RFC 1122 says we MUST send a reset.
  6409. * BSD 4.4 also does reset.
  6410. */
  6411. if (sk->sk_shutdown & RCV_SHUTDOWN) {
  6412. if (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq &&
  6413. after(TCP_SKB_CB(skb)->end_seq - th->fin, tp->rcv_nxt)) {
  6414. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONDATA);
  6415. tcp_reset(sk, skb);
  6416. return SKB_DROP_REASON_TCP_ABORT_ON_DATA;
  6417. }
  6418. }
  6419. fallthrough;
  6420. case TCP_ESTABLISHED:
  6421. tcp_data_queue(sk, skb);
  6422. queued = 1;
  6423. break;
  6424. }
  6425. /* tcp_data could move socket to TIME-WAIT */
  6426. if (sk->sk_state != TCP_CLOSE) {
  6427. tcp_data_snd_check(sk);
  6428. tcp_ack_snd_check(sk);
  6429. }
  6430. if (!queued) {
  6431. discard:
  6432. tcp_drop_reason(sk, skb, reason);
  6433. }
  6434. return 0;
  6435. consume:
  6436. __kfree_skb(skb);
  6437. return 0;
  6438. }
  6439. EXPORT_IPV6_MOD(tcp_rcv_state_process);
  6440. static inline void pr_drop_req(struct request_sock *req, __u16 port, int family)
  6441. {
  6442. struct inet_request_sock *ireq = inet_rsk(req);
  6443. if (family == AF_INET)
  6444. net_dbg_ratelimited("drop open request from %pI4/%u\n",
  6445. &ireq->ir_rmt_addr, port);
  6446. #if IS_ENABLED(CONFIG_IPV6)
  6447. else if (family == AF_INET6)
  6448. net_dbg_ratelimited("drop open request from %pI6/%u\n",
  6449. &ireq->ir_v6_rmt_addr, port);
  6450. #endif
  6451. }
  6452. /* RFC3168 : 6.1.1 SYN packets must not have ECT/ECN bits set
  6453. *
  6454. * If we receive a SYN packet with these bits set, it means a
  6455. * network is playing bad games with TOS bits. In order to
  6456. * avoid possible false congestion notifications, we disable
  6457. * TCP ECN negotiation.
  6458. *
  6459. * Exception: tcp_ca wants ECN. This is required for DCTCP
  6460. * congestion control: Linux DCTCP asserts ECT on all packets,
  6461. * including SYN, which is most optimal solution; however,
  6462. * others, such as FreeBSD do not.
  6463. *
  6464. * Exception: At least one of the reserved bits of the TCP header (th->res1) is
  6465. * set, indicating the use of a future TCP extension (such as AccECN). See
  6466. * RFC8311 §4.3 which updates RFC3168 to allow the development of such
  6467. * extensions.
  6468. */
  6469. static void tcp_ecn_create_request(struct request_sock *req,
  6470. const struct sk_buff *skb,
  6471. const struct sock *listen_sk,
  6472. const struct dst_entry *dst)
  6473. {
  6474. const struct tcphdr *th = tcp_hdr(skb);
  6475. const struct net *net = sock_net(listen_sk);
  6476. bool th_ecn = th->ece && th->cwr;
  6477. bool ect, ecn_ok;
  6478. u32 ecn_ok_dst;
  6479. if (tcp_accecn_syn_requested(th) &&
  6480. (READ_ONCE(net->ipv4.sysctl_tcp_ecn) >= 3 ||
  6481. tcp_ca_needs_accecn(listen_sk))) {
  6482. inet_rsk(req)->ecn_ok = 1;
  6483. tcp_rsk(req)->accecn_ok = 1;
  6484. tcp_rsk(req)->syn_ect_rcv = TCP_SKB_CB(skb)->ip_dsfield &
  6485. INET_ECN_MASK;
  6486. return;
  6487. }
  6488. if (!th_ecn)
  6489. return;
  6490. ect = !INET_ECN_is_not_ect(TCP_SKB_CB(skb)->ip_dsfield);
  6491. ecn_ok_dst = dst_feature(dst, DST_FEATURE_ECN_MASK);
  6492. ecn_ok = READ_ONCE(net->ipv4.sysctl_tcp_ecn) || ecn_ok_dst;
  6493. if (((!ect || th->res1 || th->ae) && ecn_ok) ||
  6494. tcp_ca_needs_ecn(listen_sk) ||
  6495. (ecn_ok_dst & DST_FEATURE_ECN_CA) ||
  6496. tcp_bpf_ca_needs_ecn((struct sock *)req))
  6497. inet_rsk(req)->ecn_ok = 1;
  6498. }
  6499. static void tcp_openreq_init(struct request_sock *req,
  6500. const struct tcp_options_received *rx_opt,
  6501. struct sk_buff *skb, const struct sock *sk)
  6502. {
  6503. struct inet_request_sock *ireq = inet_rsk(req);
  6504. req->rsk_rcv_wnd = 0; /* So that tcp_send_synack() knows! */
  6505. tcp_rsk(req)->rcv_isn = TCP_SKB_CB(skb)->seq;
  6506. tcp_rsk(req)->rcv_nxt = TCP_SKB_CB(skb)->seq + 1;
  6507. tcp_rsk(req)->snt_synack = 0;
  6508. tcp_rsk(req)->snt_tsval_first = 0;
  6509. tcp_rsk(req)->last_oow_ack_time = 0;
  6510. tcp_rsk(req)->accecn_ok = 0;
  6511. tcp_rsk(req)->saw_accecn_opt = TCP_ACCECN_OPT_NOT_SEEN;
  6512. tcp_rsk(req)->accecn_fail_mode = 0;
  6513. tcp_rsk(req)->syn_ect_rcv = 0;
  6514. tcp_rsk(req)->syn_ect_snt = 0;
  6515. req->mss = rx_opt->mss_clamp;
  6516. req->ts_recent = rx_opt->saw_tstamp ? rx_opt->rcv_tsval : 0;
  6517. ireq->tstamp_ok = rx_opt->tstamp_ok;
  6518. ireq->sack_ok = rx_opt->sack_ok;
  6519. ireq->snd_wscale = rx_opt->snd_wscale;
  6520. ireq->wscale_ok = rx_opt->wscale_ok;
  6521. ireq->acked = 0;
  6522. ireq->ecn_ok = 0;
  6523. ireq->ir_rmt_port = tcp_hdr(skb)->source;
  6524. ireq->ir_num = ntohs(tcp_hdr(skb)->dest);
  6525. ireq->ir_mark = inet_request_mark(sk, skb);
  6526. #if IS_ENABLED(CONFIG_SMC)
  6527. ireq->smc_ok = rx_opt->smc_ok && !(tcp_sk(sk)->smc_hs_congested &&
  6528. tcp_sk(sk)->smc_hs_congested(sk));
  6529. #endif
  6530. }
  6531. /*
  6532. * Return true if a syncookie should be sent
  6533. */
  6534. static bool tcp_syn_flood_action(struct sock *sk, const char *proto)
  6535. {
  6536. struct request_sock_queue *queue = &inet_csk(sk)->icsk_accept_queue;
  6537. const char *msg = "Dropping request";
  6538. struct net *net = sock_net(sk);
  6539. bool want_cookie = false;
  6540. u8 syncookies;
  6541. syncookies = READ_ONCE(net->ipv4.sysctl_tcp_syncookies);
  6542. #ifdef CONFIG_SYN_COOKIES
  6543. if (syncookies) {
  6544. msg = "Sending cookies";
  6545. want_cookie = true;
  6546. __NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPREQQFULLDOCOOKIES);
  6547. } else
  6548. #endif
  6549. __NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPREQQFULLDROP);
  6550. if (syncookies != 2 && !READ_ONCE(queue->synflood_warned)) {
  6551. WRITE_ONCE(queue->synflood_warned, 1);
  6552. if (IS_ENABLED(CONFIG_IPV6) && sk->sk_family == AF_INET6) {
  6553. net_info_ratelimited("%s: Possible SYN flooding on port [%pI6c]:%u. %s.\n",
  6554. proto, inet6_rcv_saddr(sk),
  6555. sk->sk_num, msg);
  6556. } else {
  6557. net_info_ratelimited("%s: Possible SYN flooding on port %pI4:%u. %s.\n",
  6558. proto, &sk->sk_rcv_saddr,
  6559. sk->sk_num, msg);
  6560. }
  6561. }
  6562. return want_cookie;
  6563. }
  6564. static void tcp_reqsk_record_syn(const struct sock *sk,
  6565. struct request_sock *req,
  6566. const struct sk_buff *skb)
  6567. {
  6568. if (tcp_sk(sk)->save_syn) {
  6569. u32 len = skb_network_header_len(skb) + tcp_hdrlen(skb);
  6570. struct saved_syn *saved_syn;
  6571. u32 mac_hdrlen;
  6572. void *base;
  6573. if (tcp_sk(sk)->save_syn == 2) { /* Save full header. */
  6574. base = skb_mac_header(skb);
  6575. mac_hdrlen = skb_mac_header_len(skb);
  6576. len += mac_hdrlen;
  6577. } else {
  6578. base = skb_network_header(skb);
  6579. mac_hdrlen = 0;
  6580. }
  6581. saved_syn = kmalloc_flex(*saved_syn, data, len, GFP_ATOMIC);
  6582. if (saved_syn) {
  6583. saved_syn->mac_hdrlen = mac_hdrlen;
  6584. saved_syn->network_hdrlen = skb_network_header_len(skb);
  6585. saved_syn->tcp_hdrlen = tcp_hdrlen(skb);
  6586. memcpy(saved_syn->data, base, len);
  6587. req->saved_syn = saved_syn;
  6588. }
  6589. }
  6590. }
  6591. /* If a SYN cookie is required and supported, returns a clamped MSS value to be
  6592. * used for SYN cookie generation.
  6593. */
  6594. u16 tcp_get_syncookie_mss(struct request_sock_ops *rsk_ops,
  6595. const struct tcp_request_sock_ops *af_ops,
  6596. struct sock *sk, struct tcphdr *th)
  6597. {
  6598. struct tcp_sock *tp = tcp_sk(sk);
  6599. u16 mss;
  6600. if (READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_syncookies) != 2 &&
  6601. !inet_csk_reqsk_queue_is_full(sk))
  6602. return 0;
  6603. if (!tcp_syn_flood_action(sk, rsk_ops->slab_name))
  6604. return 0;
  6605. if (sk_acceptq_is_full(sk)) {
  6606. NET_INC_STATS(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS);
  6607. return 0;
  6608. }
  6609. mss = tcp_parse_mss_option(th, READ_ONCE(tp->rx_opt.user_mss));
  6610. if (!mss)
  6611. mss = af_ops->mss_clamp;
  6612. return mss;
  6613. }
  6614. EXPORT_IPV6_MOD_GPL(tcp_get_syncookie_mss);
  6615. int tcp_conn_request(struct request_sock_ops *rsk_ops,
  6616. const struct tcp_request_sock_ops *af_ops,
  6617. struct sock *sk, struct sk_buff *skb)
  6618. {
  6619. struct tcp_fastopen_cookie foc = { .len = -1 };
  6620. struct tcp_options_received tmp_opt;
  6621. const struct tcp_sock *tp = tcp_sk(sk);
  6622. struct net *net = sock_net(sk);
  6623. struct sock *fastopen_sk = NULL;
  6624. union tcp_seq_and_ts_off st;
  6625. struct request_sock *req;
  6626. bool want_cookie = false;
  6627. struct dst_entry *dst;
  6628. struct flowi fl;
  6629. u8 syncookies;
  6630. u32 isn;
  6631. #ifdef CONFIG_TCP_AO
  6632. const struct tcp_ao_hdr *aoh;
  6633. #endif
  6634. isn = __this_cpu_read(tcp_tw_isn);
  6635. if (isn) {
  6636. /* TW buckets are converted to open requests without
  6637. * limitations, they conserve resources and peer is
  6638. * evidently real one.
  6639. */
  6640. __this_cpu_write(tcp_tw_isn, 0);
  6641. } else {
  6642. syncookies = READ_ONCE(net->ipv4.sysctl_tcp_syncookies);
  6643. if (syncookies == 2 || inet_csk_reqsk_queue_is_full(sk)) {
  6644. want_cookie = tcp_syn_flood_action(sk,
  6645. rsk_ops->slab_name);
  6646. if (!want_cookie)
  6647. goto drop;
  6648. }
  6649. }
  6650. if (sk_acceptq_is_full(sk)) {
  6651. NET_INC_STATS(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS);
  6652. goto drop;
  6653. }
  6654. req = inet_reqsk_alloc(rsk_ops, sk, !want_cookie);
  6655. if (!req)
  6656. goto drop;
  6657. req->syncookie = want_cookie;
  6658. tcp_rsk(req)->af_specific = af_ops;
  6659. tcp_rsk(req)->ts_off = 0;
  6660. tcp_rsk(req)->req_usec_ts = false;
  6661. #if IS_ENABLED(CONFIG_MPTCP)
  6662. tcp_rsk(req)->is_mptcp = 0;
  6663. #endif
  6664. tcp_clear_options(&tmp_opt);
  6665. tmp_opt.mss_clamp = af_ops->mss_clamp;
  6666. tmp_opt.user_mss = READ_ONCE(tp->rx_opt.user_mss);
  6667. tcp_parse_options(sock_net(sk), skb, &tmp_opt, 0,
  6668. want_cookie ? NULL : &foc);
  6669. if (want_cookie && !tmp_opt.saw_tstamp)
  6670. tcp_clear_options(&tmp_opt);
  6671. if (IS_ENABLED(CONFIG_SMC) && want_cookie)
  6672. tmp_opt.smc_ok = 0;
  6673. tmp_opt.tstamp_ok = tmp_opt.saw_tstamp;
  6674. tcp_openreq_init(req, &tmp_opt, skb, sk);
  6675. inet_rsk(req)->no_srccheck = inet_test_bit(TRANSPARENT, sk);
  6676. /* Note: tcp_v6_init_req() might override ir_iif for link locals */
  6677. inet_rsk(req)->ir_iif = inet_request_bound_dev_if(sk, skb);
  6678. dst = af_ops->route_req(sk, skb, &fl, req, isn);
  6679. if (!dst)
  6680. goto drop_and_free;
  6681. if (tmp_opt.tstamp_ok || (!want_cookie && !isn))
  6682. st = af_ops->init_seq_and_ts_off(net, skb);
  6683. if (tmp_opt.tstamp_ok) {
  6684. tcp_rsk(req)->req_usec_ts = dst_tcp_usec_ts(dst);
  6685. tcp_rsk(req)->ts_off = st.ts_off;
  6686. }
  6687. if (!want_cookie && !isn) {
  6688. int max_syn_backlog = READ_ONCE(net->ipv4.sysctl_max_syn_backlog);
  6689. /* Kill the following clause, if you dislike this way. */
  6690. if (!syncookies &&
  6691. (max_syn_backlog - inet_csk_reqsk_queue_len(sk) <
  6692. (max_syn_backlog >> 2)) &&
  6693. !tcp_peer_is_proven(req, dst)) {
  6694. /* Without syncookies last quarter of
  6695. * backlog is filled with destinations,
  6696. * proven to be alive.
  6697. * It means that we continue to communicate
  6698. * to destinations, already remembered
  6699. * to the moment of synflood.
  6700. */
  6701. pr_drop_req(req, ntohs(tcp_hdr(skb)->source),
  6702. rsk_ops->family);
  6703. goto drop_and_release;
  6704. }
  6705. isn = st.seq;
  6706. }
  6707. tcp_ecn_create_request(req, skb, sk, dst);
  6708. if (want_cookie) {
  6709. isn = cookie_init_sequence(af_ops, sk, skb, &req->mss);
  6710. if (!tmp_opt.tstamp_ok)
  6711. inet_rsk(req)->ecn_ok = 0;
  6712. }
  6713. #ifdef CONFIG_TCP_AO
  6714. if (tcp_parse_auth_options(tcp_hdr(skb), NULL, &aoh))
  6715. goto drop_and_release; /* Invalid TCP options */
  6716. if (aoh) {
  6717. tcp_rsk(req)->used_tcp_ao = true;
  6718. tcp_rsk(req)->ao_rcv_next = aoh->keyid;
  6719. tcp_rsk(req)->ao_keyid = aoh->rnext_keyid;
  6720. } else {
  6721. tcp_rsk(req)->used_tcp_ao = false;
  6722. }
  6723. #endif
  6724. tcp_rsk(req)->snt_isn = isn;
  6725. tcp_rsk(req)->txhash = net_tx_rndhash();
  6726. tcp_rsk(req)->syn_tos = TCP_SKB_CB(skb)->ip_dsfield;
  6727. tcp_openreq_init_rwin(req, sk, dst);
  6728. sk_rx_queue_set(req_to_sk(req), skb);
  6729. if (!want_cookie) {
  6730. tcp_reqsk_record_syn(sk, req, skb);
  6731. fastopen_sk = tcp_try_fastopen(sk, skb, req, &foc, dst);
  6732. }
  6733. if (fastopen_sk) {
  6734. af_ops->send_synack(fastopen_sk, dst, &fl, req,
  6735. &foc, TCP_SYNACK_FASTOPEN, skb);
  6736. /* Add the child socket directly into the accept queue */
  6737. if (!inet_csk_reqsk_queue_add(sk, req, fastopen_sk)) {
  6738. bh_unlock_sock(fastopen_sk);
  6739. sock_put(fastopen_sk);
  6740. goto drop_and_free;
  6741. }
  6742. READ_ONCE(sk->sk_data_ready)(sk);
  6743. bh_unlock_sock(fastopen_sk);
  6744. sock_put(fastopen_sk);
  6745. } else {
  6746. tcp_rsk(req)->tfo_listener = false;
  6747. if (!want_cookie &&
  6748. unlikely(!inet_csk_reqsk_queue_hash_add(sk, req))) {
  6749. reqsk_free(req);
  6750. dst_release(dst);
  6751. return 0;
  6752. }
  6753. af_ops->send_synack(sk, dst, &fl, req, &foc,
  6754. !want_cookie ? TCP_SYNACK_NORMAL :
  6755. TCP_SYNACK_COOKIE,
  6756. skb);
  6757. if (want_cookie) {
  6758. reqsk_free(req);
  6759. return 0;
  6760. }
  6761. }
  6762. reqsk_put(req);
  6763. return 0;
  6764. drop_and_release:
  6765. dst_release(dst);
  6766. drop_and_free:
  6767. __reqsk_free(req);
  6768. drop:
  6769. tcp_listendrop(sk);
  6770. return 0;
  6771. }
  6772. EXPORT_IPV6_MOD(tcp_conn_request);