tcp_input.c 186 KB

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