tcp_input.c 170 KB

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