tcp_input.c 171 KB

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