tcp_input.c 170 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039
  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. void tcp_clear_retrans(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. tp->fackets_out = 0;
  1641. tp->sacked_out = 0;
  1642. }
  1643. static inline void tcp_init_undo(struct tcp_sock *tp)
  1644. {
  1645. tp->undo_marker = tp->snd_una;
  1646. /* Retransmission still in flight may cause DSACKs later. */
  1647. tp->undo_retrans = tp->retrans_out ? : -1;
  1648. }
  1649. /* Enter Loss state. If we detect SACK reneging, forget all SACK information
  1650. * and reset tags completely, otherwise preserve SACKs. If receiver
  1651. * dropped its ofo queue, we will know this due to reneging detection.
  1652. */
  1653. void tcp_enter_loss(struct sock *sk)
  1654. {
  1655. const struct inet_connection_sock *icsk = inet_csk(sk);
  1656. struct tcp_sock *tp = tcp_sk(sk);
  1657. struct sk_buff *skb;
  1658. bool new_recovery = false;
  1659. bool is_reneg; /* is receiver reneging on SACKs? */
  1660. /* Reduce ssthresh if it has not yet been made inside this window. */
  1661. if (icsk->icsk_ca_state <= TCP_CA_Disorder ||
  1662. !after(tp->high_seq, tp->snd_una) ||
  1663. (icsk->icsk_ca_state == TCP_CA_Loss && !icsk->icsk_retransmits)) {
  1664. new_recovery = true;
  1665. tp->prior_ssthresh = tcp_current_ssthresh(sk);
  1666. tp->snd_ssthresh = icsk->icsk_ca_ops->ssthresh(sk);
  1667. tcp_ca_event(sk, CA_EVENT_LOSS);
  1668. tcp_init_undo(tp);
  1669. }
  1670. tp->snd_cwnd = 1;
  1671. tp->snd_cwnd_cnt = 0;
  1672. tp->snd_cwnd_stamp = tcp_time_stamp;
  1673. tp->retrans_out = 0;
  1674. tp->lost_out = 0;
  1675. if (tcp_is_reno(tp))
  1676. tcp_reset_reno_sack(tp);
  1677. skb = tcp_write_queue_head(sk);
  1678. is_reneg = skb && (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED);
  1679. if (is_reneg) {
  1680. NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPSACKRENEGING);
  1681. tp->sacked_out = 0;
  1682. tp->fackets_out = 0;
  1683. }
  1684. tcp_clear_all_retrans_hints(tp);
  1685. tcp_for_write_queue(skb, sk) {
  1686. if (skb == tcp_send_head(sk))
  1687. break;
  1688. TCP_SKB_CB(skb)->sacked &= (~TCPCB_TAGBITS)|TCPCB_SACKED_ACKED;
  1689. if (!(TCP_SKB_CB(skb)->sacked&TCPCB_SACKED_ACKED) || is_reneg) {
  1690. TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_ACKED;
  1691. TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
  1692. tp->lost_out += tcp_skb_pcount(skb);
  1693. tp->retransmit_high = TCP_SKB_CB(skb)->end_seq;
  1694. }
  1695. }
  1696. tcp_verify_left_out(tp);
  1697. /* Timeout in disordered state after receiving substantial DUPACKs
  1698. * suggests that the degree of reordering is over-estimated.
  1699. */
  1700. if (icsk->icsk_ca_state <= TCP_CA_Disorder &&
  1701. tp->sacked_out >= sysctl_tcp_reordering)
  1702. tp->reordering = min_t(unsigned int, tp->reordering,
  1703. sysctl_tcp_reordering);
  1704. tcp_set_ca_state(sk, TCP_CA_Loss);
  1705. tp->high_seq = tp->snd_nxt;
  1706. TCP_ECN_queue_cwr(tp);
  1707. /* F-RTO RFC5682 sec 3.1 step 1: retransmit SND.UNA if no previous
  1708. * loss recovery is underway except recurring timeout(s) on
  1709. * the same SND.UNA (sec 3.2). Disable F-RTO on path MTU probing
  1710. */
  1711. tp->frto = sysctl_tcp_frto &&
  1712. (new_recovery || icsk->icsk_retransmits) &&
  1713. !inet_csk(sk)->icsk_mtup.probe_size;
  1714. }
  1715. /* If ACK arrived pointing to a remembered SACK, it means that our
  1716. * remembered SACKs do not reflect real state of receiver i.e.
  1717. * receiver _host_ is heavily congested (or buggy).
  1718. *
  1719. * To avoid big spurious retransmission bursts due to transient SACK
  1720. * scoreboard oddities that look like reneging, we give the receiver a
  1721. * little time (max(RTT/2, 10ms)) to send us some more ACKs that will
  1722. * restore sanity to the SACK scoreboard. If the apparent reneging
  1723. * persists until this RTO then we'll clear the SACK scoreboard.
  1724. */
  1725. static bool tcp_check_sack_reneging(struct sock *sk, int flag)
  1726. {
  1727. if (flag & FLAG_SACK_RENEGING) {
  1728. struct tcp_sock *tp = tcp_sk(sk);
  1729. unsigned long delay = max(usecs_to_jiffies(tp->srtt_us >> 4),
  1730. msecs_to_jiffies(10));
  1731. inet_csk_reset_xmit_timer(sk, ICSK_TIME_RETRANS,
  1732. delay, TCP_RTO_MAX);
  1733. return true;
  1734. }
  1735. return false;
  1736. }
  1737. static inline int tcp_fackets_out(const struct tcp_sock *tp)
  1738. {
  1739. return tcp_is_reno(tp) ? tp->sacked_out + 1 : tp->fackets_out;
  1740. }
  1741. /* Heurestics to calculate number of duplicate ACKs. There's no dupACKs
  1742. * counter when SACK is enabled (without SACK, sacked_out is used for
  1743. * that purpose).
  1744. *
  1745. * Instead, with FACK TCP uses fackets_out that includes both SACKed
  1746. * segments up to the highest received SACK block so far and holes in
  1747. * between them.
  1748. *
  1749. * With reordering, holes may still be in flight, so RFC3517 recovery
  1750. * uses pure sacked_out (total number of SACKed segments) even though
  1751. * it violates the RFC that uses duplicate ACKs, often these are equal
  1752. * but when e.g. out-of-window ACKs or packet duplication occurs,
  1753. * they differ. Since neither occurs due to loss, TCP should really
  1754. * ignore them.
  1755. */
  1756. static inline int tcp_dupack_heuristics(const struct tcp_sock *tp)
  1757. {
  1758. return tcp_is_fack(tp) ? tp->fackets_out : tp->sacked_out + 1;
  1759. }
  1760. static bool tcp_pause_early_retransmit(struct sock *sk, int flag)
  1761. {
  1762. struct tcp_sock *tp = tcp_sk(sk);
  1763. unsigned long delay;
  1764. /* Delay early retransmit and entering fast recovery for
  1765. * max(RTT/4, 2msec) unless ack has ECE mark, no RTT samples
  1766. * available, or RTO is scheduled to fire first.
  1767. */
  1768. if (sysctl_tcp_early_retrans < 2 || sysctl_tcp_early_retrans > 3 ||
  1769. (flag & FLAG_ECE) || !tp->srtt_us)
  1770. return false;
  1771. delay = max(usecs_to_jiffies(tp->srtt_us >> 5),
  1772. msecs_to_jiffies(2));
  1773. if (!time_after(inet_csk(sk)->icsk_timeout, (jiffies + delay)))
  1774. return false;
  1775. inet_csk_reset_xmit_timer(sk, ICSK_TIME_EARLY_RETRANS, delay,
  1776. TCP_RTO_MAX);
  1777. return true;
  1778. }
  1779. /* Linux NewReno/SACK/FACK/ECN state machine.
  1780. * --------------------------------------
  1781. *
  1782. * "Open" Normal state, no dubious events, fast path.
  1783. * "Disorder" In all the respects it is "Open",
  1784. * but requires a bit more attention. It is entered when
  1785. * we see some SACKs or dupacks. It is split of "Open"
  1786. * mainly to move some processing from fast path to slow one.
  1787. * "CWR" CWND was reduced due to some Congestion Notification event.
  1788. * It can be ECN, ICMP source quench, local device congestion.
  1789. * "Recovery" CWND was reduced, we are fast-retransmitting.
  1790. * "Loss" CWND was reduced due to RTO timeout or SACK reneging.
  1791. *
  1792. * tcp_fastretrans_alert() is entered:
  1793. * - each incoming ACK, if state is not "Open"
  1794. * - when arrived ACK is unusual, namely:
  1795. * * SACK
  1796. * * Duplicate ACK.
  1797. * * ECN ECE.
  1798. *
  1799. * Counting packets in flight is pretty simple.
  1800. *
  1801. * in_flight = packets_out - left_out + retrans_out
  1802. *
  1803. * packets_out is SND.NXT-SND.UNA counted in packets.
  1804. *
  1805. * retrans_out is number of retransmitted segments.
  1806. *
  1807. * left_out is number of segments left network, but not ACKed yet.
  1808. *
  1809. * left_out = sacked_out + lost_out
  1810. *
  1811. * sacked_out: Packets, which arrived to receiver out of order
  1812. * and hence not ACKed. With SACKs this number is simply
  1813. * amount of SACKed data. Even without SACKs
  1814. * it is easy to give pretty reliable estimate of this number,
  1815. * counting duplicate ACKs.
  1816. *
  1817. * lost_out: Packets lost by network. TCP has no explicit
  1818. * "loss notification" feedback from network (for now).
  1819. * It means that this number can be only _guessed_.
  1820. * Actually, it is the heuristics to predict lossage that
  1821. * distinguishes different algorithms.
  1822. *
  1823. * F.e. after RTO, when all the queue is considered as lost,
  1824. * lost_out = packets_out and in_flight = retrans_out.
  1825. *
  1826. * Essentially, we have now two algorithms counting
  1827. * lost packets.
  1828. *
  1829. * FACK: It is the simplest heuristics. As soon as we decided
  1830. * that something is lost, we decide that _all_ not SACKed
  1831. * packets until the most forward SACK are lost. I.e.
  1832. * lost_out = fackets_out - sacked_out and left_out = fackets_out.
  1833. * It is absolutely correct estimate, if network does not reorder
  1834. * packets. And it loses any connection to reality when reordering
  1835. * takes place. We use FACK by default until reordering
  1836. * is suspected on the path to this destination.
  1837. *
  1838. * NewReno: when Recovery is entered, we assume that one segment
  1839. * is lost (classic Reno). While we are in Recovery and
  1840. * a partial ACK arrives, we assume that one more packet
  1841. * is lost (NewReno). This heuristics are the same in NewReno
  1842. * and SACK.
  1843. *
  1844. * Imagine, that's all! Forget about all this shamanism about CWND inflation
  1845. * deflation etc. CWND is real congestion window, never inflated, changes
  1846. * only according to classic VJ rules.
  1847. *
  1848. * Really tricky (and requiring careful tuning) part of algorithm
  1849. * is hidden in functions tcp_time_to_recover() and tcp_xmit_retransmit_queue().
  1850. * The first determines the moment _when_ we should reduce CWND and,
  1851. * hence, slow down forward transmission. In fact, it determines the moment
  1852. * when we decide that hole is caused by loss, rather than by a reorder.
  1853. *
  1854. * tcp_xmit_retransmit_queue() decides, _what_ we should retransmit to fill
  1855. * holes, caused by lost packets.
  1856. *
  1857. * And the most logically complicated part of algorithm is undo
  1858. * heuristics. We detect false retransmits due to both too early
  1859. * fast retransmit (reordering) and underestimated RTO, analyzing
  1860. * timestamps and D-SACKs. When we detect that some segments were
  1861. * retransmitted by mistake and CWND reduction was wrong, we undo
  1862. * window reduction and abort recovery phase. This logic is hidden
  1863. * inside several functions named tcp_try_undo_<something>.
  1864. */
  1865. /* This function decides, when we should leave Disordered state
  1866. * and enter Recovery phase, reducing congestion window.
  1867. *
  1868. * Main question: may we further continue forward transmission
  1869. * with the same cwnd?
  1870. */
  1871. static bool tcp_time_to_recover(struct sock *sk, int flag)
  1872. {
  1873. struct tcp_sock *tp = tcp_sk(sk);
  1874. __u32 packets_out;
  1875. /* Trick#1: The loss is proven. */
  1876. if (tp->lost_out)
  1877. return true;
  1878. /* Not-A-Trick#2 : Classic rule... */
  1879. if (tcp_dupack_heuristics(tp) > tp->reordering)
  1880. return true;
  1881. /* Trick#4: It is still not OK... But will it be useful to delay
  1882. * recovery more?
  1883. */
  1884. packets_out = tp->packets_out;
  1885. if (packets_out <= tp->reordering &&
  1886. tp->sacked_out >= max_t(__u32, packets_out/2, sysctl_tcp_reordering) &&
  1887. !tcp_may_send_now(sk)) {
  1888. /* We have nothing to send. This connection is limited
  1889. * either by receiver window or by application.
  1890. */
  1891. return true;
  1892. }
  1893. /* If a thin stream is detected, retransmit after first
  1894. * received dupack. Employ only if SACK is supported in order
  1895. * to avoid possible corner-case series of spurious retransmissions
  1896. * Use only if there are no unsent data.
  1897. */
  1898. if ((tp->thin_dupack || sysctl_tcp_thin_dupack) &&
  1899. tcp_stream_is_thin(tp) && tcp_dupack_heuristics(tp) > 1 &&
  1900. tcp_is_sack(tp) && !tcp_send_head(sk))
  1901. return true;
  1902. /* Trick#6: TCP early retransmit, per RFC5827. To avoid spurious
  1903. * retransmissions due to small network reorderings, we implement
  1904. * Mitigation A.3 in the RFC and delay the retransmission for a short
  1905. * interval if appropriate.
  1906. */
  1907. if (tp->do_early_retrans && !tp->retrans_out && tp->sacked_out &&
  1908. (tp->packets_out >= (tp->sacked_out + 1) && tp->packets_out < 4) &&
  1909. !tcp_may_send_now(sk))
  1910. return !tcp_pause_early_retransmit(sk, flag);
  1911. return false;
  1912. }
  1913. /* Detect loss in event "A" above by marking head of queue up as lost.
  1914. * For FACK or non-SACK(Reno) senders, the first "packets" number of segments
  1915. * are considered lost. For RFC3517 SACK, a segment is considered lost if it
  1916. * has at least tp->reordering SACKed seqments above it; "packets" refers to
  1917. * the maximum SACKed segments to pass before reaching this limit.
  1918. */
  1919. static void tcp_mark_head_lost(struct sock *sk, int packets, int mark_head)
  1920. {
  1921. struct tcp_sock *tp = tcp_sk(sk);
  1922. struct sk_buff *skb;
  1923. int cnt, oldcnt;
  1924. int err;
  1925. unsigned int mss;
  1926. /* Use SACK to deduce losses of new sequences sent during recovery */
  1927. const u32 loss_high = tcp_is_sack(tp) ? tp->snd_nxt : tp->high_seq;
  1928. WARN_ON(packets > tp->packets_out);
  1929. if (tp->lost_skb_hint) {
  1930. skb = tp->lost_skb_hint;
  1931. cnt = tp->lost_cnt_hint;
  1932. /* Head already handled? */
  1933. if (mark_head && skb != tcp_write_queue_head(sk))
  1934. return;
  1935. } else {
  1936. skb = tcp_write_queue_head(sk);
  1937. cnt = 0;
  1938. }
  1939. tcp_for_write_queue_from(skb, sk) {
  1940. if (skb == tcp_send_head(sk))
  1941. break;
  1942. /* TODO: do this better */
  1943. /* this is not the most efficient way to do this... */
  1944. tp->lost_skb_hint = skb;
  1945. tp->lost_cnt_hint = cnt;
  1946. if (after(TCP_SKB_CB(skb)->end_seq, loss_high))
  1947. break;
  1948. oldcnt = cnt;
  1949. if (tcp_is_fack(tp) || tcp_is_reno(tp) ||
  1950. (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED))
  1951. cnt += tcp_skb_pcount(skb);
  1952. if (cnt > packets) {
  1953. if ((tcp_is_sack(tp) && !tcp_is_fack(tp)) ||
  1954. (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED) ||
  1955. (oldcnt >= packets))
  1956. break;
  1957. mss = skb_shinfo(skb)->gso_size;
  1958. err = tcp_fragment(sk, skb, (packets - oldcnt) * mss,
  1959. mss, GFP_ATOMIC);
  1960. if (err < 0)
  1961. break;
  1962. cnt = packets;
  1963. }
  1964. tcp_skb_mark_lost(tp, skb);
  1965. if (mark_head)
  1966. break;
  1967. }
  1968. tcp_verify_left_out(tp);
  1969. }
  1970. /* Account newly detected lost packet(s) */
  1971. static void tcp_update_scoreboard(struct sock *sk, int fast_rexmit)
  1972. {
  1973. struct tcp_sock *tp = tcp_sk(sk);
  1974. if (tcp_is_reno(tp)) {
  1975. tcp_mark_head_lost(sk, 1, 1);
  1976. } else if (tcp_is_fack(tp)) {
  1977. int lost = tp->fackets_out - tp->reordering;
  1978. if (lost <= 0)
  1979. lost = 1;
  1980. tcp_mark_head_lost(sk, lost, 0);
  1981. } else {
  1982. int sacked_upto = tp->sacked_out - tp->reordering;
  1983. if (sacked_upto >= 0)
  1984. tcp_mark_head_lost(sk, sacked_upto, 0);
  1985. else if (fast_rexmit)
  1986. tcp_mark_head_lost(sk, 1, 1);
  1987. }
  1988. }
  1989. /* CWND moderation, preventing bursts due to too big ACKs
  1990. * in dubious situations.
  1991. */
  1992. static inline void tcp_moderate_cwnd(struct tcp_sock *tp)
  1993. {
  1994. tp->snd_cwnd = min(tp->snd_cwnd,
  1995. tcp_packets_in_flight(tp) + tcp_max_burst(tp));
  1996. tp->snd_cwnd_stamp = tcp_time_stamp;
  1997. }
  1998. /* Nothing was retransmitted or returned timestamp is less
  1999. * than timestamp of the first retransmission.
  2000. */
  2001. static inline bool tcp_packet_delayed(const struct tcp_sock *tp)
  2002. {
  2003. return !tp->retrans_stamp ||
  2004. (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr &&
  2005. before(tp->rx_opt.rcv_tsecr, tp->retrans_stamp));
  2006. }
  2007. /* Undo procedures. */
  2008. #if FASTRETRANS_DEBUG > 1
  2009. static void DBGUNDO(struct sock *sk, const char *msg)
  2010. {
  2011. struct tcp_sock *tp = tcp_sk(sk);
  2012. struct inet_sock *inet = inet_sk(sk);
  2013. if (sk->sk_family == AF_INET) {
  2014. pr_debug("Undo %s %pI4/%u c%u l%u ss%u/%u p%u\n",
  2015. msg,
  2016. &inet->inet_daddr, ntohs(inet->inet_dport),
  2017. tp->snd_cwnd, tcp_left_out(tp),
  2018. tp->snd_ssthresh, tp->prior_ssthresh,
  2019. tp->packets_out);
  2020. }
  2021. #if IS_ENABLED(CONFIG_IPV6)
  2022. else if (sk->sk_family == AF_INET6) {
  2023. struct ipv6_pinfo *np = inet6_sk(sk);
  2024. pr_debug("Undo %s %pI6/%u c%u l%u ss%u/%u p%u\n",
  2025. msg,
  2026. &np->daddr, ntohs(inet->inet_dport),
  2027. tp->snd_cwnd, tcp_left_out(tp),
  2028. tp->snd_ssthresh, tp->prior_ssthresh,
  2029. tp->packets_out);
  2030. }
  2031. #endif
  2032. }
  2033. #else
  2034. #define DBGUNDO(x...) do { } while (0)
  2035. #endif
  2036. static void tcp_undo_cwnd_reduction(struct sock *sk, bool unmark_loss)
  2037. {
  2038. struct tcp_sock *tp = tcp_sk(sk);
  2039. if (unmark_loss) {
  2040. struct sk_buff *skb;
  2041. tcp_for_write_queue(skb, sk) {
  2042. if (skb == tcp_send_head(sk))
  2043. break;
  2044. TCP_SKB_CB(skb)->sacked &= ~TCPCB_LOST;
  2045. }
  2046. tp->lost_out = 0;
  2047. tcp_clear_all_retrans_hints(tp);
  2048. }
  2049. if (tp->prior_ssthresh) {
  2050. const struct inet_connection_sock *icsk = inet_csk(sk);
  2051. if (icsk->icsk_ca_ops->undo_cwnd)
  2052. tp->snd_cwnd = icsk->icsk_ca_ops->undo_cwnd(sk);
  2053. else
  2054. tp->snd_cwnd = max(tp->snd_cwnd, tp->snd_ssthresh << 1);
  2055. if (tp->prior_ssthresh > tp->snd_ssthresh) {
  2056. tp->snd_ssthresh = tp->prior_ssthresh;
  2057. TCP_ECN_withdraw_cwr(tp);
  2058. }
  2059. } else {
  2060. tp->snd_cwnd = max(tp->snd_cwnd, tp->snd_ssthresh);
  2061. }
  2062. tp->snd_cwnd_stamp = tcp_time_stamp;
  2063. tp->undo_marker = 0;
  2064. }
  2065. static inline bool tcp_may_undo(const struct tcp_sock *tp)
  2066. {
  2067. return tp->undo_marker && (!tp->undo_retrans || tcp_packet_delayed(tp));
  2068. }
  2069. /* People celebrate: "We love our President!" */
  2070. static bool tcp_try_undo_recovery(struct sock *sk)
  2071. {
  2072. struct tcp_sock *tp = tcp_sk(sk);
  2073. if (tcp_may_undo(tp)) {
  2074. int mib_idx;
  2075. /* Happy end! We did not retransmit anything
  2076. * or our original transmission succeeded.
  2077. */
  2078. DBGUNDO(sk, inet_csk(sk)->icsk_ca_state == TCP_CA_Loss ? "loss" : "retrans");
  2079. tcp_undo_cwnd_reduction(sk, false);
  2080. if (inet_csk(sk)->icsk_ca_state == TCP_CA_Loss)
  2081. mib_idx = LINUX_MIB_TCPLOSSUNDO;
  2082. else
  2083. mib_idx = LINUX_MIB_TCPFULLUNDO;
  2084. NET_INC_STATS_BH(sock_net(sk), mib_idx);
  2085. }
  2086. if (tp->snd_una == tp->high_seq && tcp_is_reno(tp)) {
  2087. /* Hold old state until something *above* high_seq
  2088. * is ACKed. For Reno it is MUST to prevent false
  2089. * fast retransmits (RFC2582). SACK TCP is safe. */
  2090. tcp_moderate_cwnd(tp);
  2091. return true;
  2092. }
  2093. tcp_set_ca_state(sk, TCP_CA_Open);
  2094. return false;
  2095. }
  2096. /* Try to undo cwnd reduction, because D-SACKs acked all retransmitted data */
  2097. static bool tcp_try_undo_dsack(struct sock *sk)
  2098. {
  2099. struct tcp_sock *tp = tcp_sk(sk);
  2100. if (tp->undo_marker && !tp->undo_retrans) {
  2101. DBGUNDO(sk, "D-SACK");
  2102. tcp_undo_cwnd_reduction(sk, false);
  2103. NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPDSACKUNDO);
  2104. return true;
  2105. }
  2106. return false;
  2107. }
  2108. /* We can clear retrans_stamp when there are no retransmissions in the
  2109. * window. It would seem that it is trivially available for us in
  2110. * tp->retrans_out, however, that kind of assumptions doesn't consider
  2111. * what will happen if errors occur when sending retransmission for the
  2112. * second time. ...It could the that such segment has only
  2113. * TCPCB_EVER_RETRANS set at the present time. It seems that checking
  2114. * the head skb is enough except for some reneging corner cases that
  2115. * are not worth the effort.
  2116. *
  2117. * Main reason for all this complexity is the fact that connection dying
  2118. * time now depends on the validity of the retrans_stamp, in particular,
  2119. * that successive retransmissions of a segment must not advance
  2120. * retrans_stamp under any conditions.
  2121. */
  2122. static bool tcp_any_retrans_done(const struct sock *sk)
  2123. {
  2124. const struct tcp_sock *tp = tcp_sk(sk);
  2125. struct sk_buff *skb;
  2126. if (tp->retrans_out)
  2127. return true;
  2128. skb = tcp_write_queue_head(sk);
  2129. if (unlikely(skb && TCP_SKB_CB(skb)->sacked & TCPCB_EVER_RETRANS))
  2130. return true;
  2131. return false;
  2132. }
  2133. /* Undo during loss recovery after partial ACK or using F-RTO. */
  2134. static bool tcp_try_undo_loss(struct sock *sk, bool frto_undo)
  2135. {
  2136. struct tcp_sock *tp = tcp_sk(sk);
  2137. if (frto_undo || tcp_may_undo(tp)) {
  2138. tcp_undo_cwnd_reduction(sk, true);
  2139. DBGUNDO(sk, "partial loss");
  2140. NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPLOSSUNDO);
  2141. if (frto_undo)
  2142. NET_INC_STATS_BH(sock_net(sk),
  2143. LINUX_MIB_TCPSPURIOUSRTOS);
  2144. inet_csk(sk)->icsk_retransmits = 0;
  2145. if (frto_undo || tcp_is_sack(tp))
  2146. tcp_set_ca_state(sk, TCP_CA_Open);
  2147. return true;
  2148. }
  2149. return false;
  2150. }
  2151. /* The cwnd reduction in CWR and Recovery use the PRR algorithm
  2152. * https://datatracker.ietf.org/doc/draft-ietf-tcpm-proportional-rate-reduction/
  2153. * It computes the number of packets to send (sndcnt) based on packets newly
  2154. * delivered:
  2155. * 1) If the packets in flight is larger than ssthresh, PRR spreads the
  2156. * cwnd reductions across a full RTT.
  2157. * 2) If packets in flight is lower than ssthresh (such as due to excess
  2158. * losses and/or application stalls), do not perform any further cwnd
  2159. * reductions, but instead slow start up to ssthresh.
  2160. */
  2161. static void tcp_init_cwnd_reduction(struct sock *sk)
  2162. {
  2163. struct tcp_sock *tp = tcp_sk(sk);
  2164. tp->high_seq = tp->snd_nxt;
  2165. tp->tlp_high_seq = 0;
  2166. tp->snd_cwnd_cnt = 0;
  2167. tp->prior_cwnd = tp->snd_cwnd;
  2168. tp->prr_delivered = 0;
  2169. tp->prr_out = 0;
  2170. tp->snd_ssthresh = inet_csk(sk)->icsk_ca_ops->ssthresh(sk);
  2171. TCP_ECN_queue_cwr(tp);
  2172. }
  2173. static void tcp_cwnd_reduction(struct sock *sk, const int prior_unsacked,
  2174. int fast_rexmit)
  2175. {
  2176. struct tcp_sock *tp = tcp_sk(sk);
  2177. int sndcnt = 0;
  2178. int delta = tp->snd_ssthresh - tcp_packets_in_flight(tp);
  2179. int newly_acked_sacked = prior_unsacked -
  2180. (tp->packets_out - tp->sacked_out);
  2181. tp->prr_delivered += newly_acked_sacked;
  2182. if (tcp_packets_in_flight(tp) > tp->snd_ssthresh) {
  2183. u64 dividend = (u64)tp->snd_ssthresh * tp->prr_delivered +
  2184. tp->prior_cwnd - 1;
  2185. sndcnt = div_u64(dividend, tp->prior_cwnd) - tp->prr_out;
  2186. } else {
  2187. sndcnt = min_t(int, delta,
  2188. max_t(int, tp->prr_delivered - tp->prr_out,
  2189. newly_acked_sacked) + 1);
  2190. }
  2191. sndcnt = max(sndcnt, (fast_rexmit ? 1 : 0));
  2192. tp->snd_cwnd = tcp_packets_in_flight(tp) + sndcnt;
  2193. }
  2194. static inline void tcp_end_cwnd_reduction(struct sock *sk)
  2195. {
  2196. struct tcp_sock *tp = tcp_sk(sk);
  2197. /* Reset cwnd to ssthresh in CWR or Recovery (unless it's undone) */
  2198. if (inet_csk(sk)->icsk_ca_state == TCP_CA_CWR ||
  2199. (tp->undo_marker && tp->snd_ssthresh < TCP_INFINITE_SSTHRESH)) {
  2200. tp->snd_cwnd = tp->snd_ssthresh;
  2201. tp->snd_cwnd_stamp = tcp_time_stamp;
  2202. }
  2203. tcp_ca_event(sk, CA_EVENT_COMPLETE_CWR);
  2204. }
  2205. /* Enter CWR state. Disable cwnd undo since congestion is proven with ECN */
  2206. void tcp_enter_cwr(struct sock *sk)
  2207. {
  2208. struct tcp_sock *tp = tcp_sk(sk);
  2209. tp->prior_ssthresh = 0;
  2210. if (inet_csk(sk)->icsk_ca_state < TCP_CA_CWR) {
  2211. tp->undo_marker = 0;
  2212. tcp_init_cwnd_reduction(sk);
  2213. tcp_set_ca_state(sk, TCP_CA_CWR);
  2214. }
  2215. }
  2216. static void tcp_try_keep_open(struct sock *sk)
  2217. {
  2218. struct tcp_sock *tp = tcp_sk(sk);
  2219. int state = TCP_CA_Open;
  2220. if (tcp_left_out(tp) || tcp_any_retrans_done(sk))
  2221. state = TCP_CA_Disorder;
  2222. if (inet_csk(sk)->icsk_ca_state != state) {
  2223. tcp_set_ca_state(sk, state);
  2224. tp->high_seq = tp->snd_nxt;
  2225. }
  2226. }
  2227. static void tcp_try_to_open(struct sock *sk, int flag, const int prior_unsacked)
  2228. {
  2229. struct tcp_sock *tp = tcp_sk(sk);
  2230. tcp_verify_left_out(tp);
  2231. if (!tcp_any_retrans_done(sk))
  2232. tp->retrans_stamp = 0;
  2233. if (flag & FLAG_ECE)
  2234. tcp_enter_cwr(sk);
  2235. if (inet_csk(sk)->icsk_ca_state != TCP_CA_CWR) {
  2236. tcp_try_keep_open(sk);
  2237. } else {
  2238. tcp_cwnd_reduction(sk, prior_unsacked, 0);
  2239. }
  2240. }
  2241. static void tcp_mtup_probe_failed(struct sock *sk)
  2242. {
  2243. struct inet_connection_sock *icsk = inet_csk(sk);
  2244. icsk->icsk_mtup.search_high = icsk->icsk_mtup.probe_size - 1;
  2245. icsk->icsk_mtup.probe_size = 0;
  2246. }
  2247. static void tcp_mtup_probe_success(struct sock *sk)
  2248. {
  2249. struct tcp_sock *tp = tcp_sk(sk);
  2250. struct inet_connection_sock *icsk = inet_csk(sk);
  2251. /* FIXME: breaks with very large cwnd */
  2252. tp->prior_ssthresh = tcp_current_ssthresh(sk);
  2253. tp->snd_cwnd = tp->snd_cwnd *
  2254. tcp_mss_to_mtu(sk, tp->mss_cache) /
  2255. icsk->icsk_mtup.probe_size;
  2256. tp->snd_cwnd_cnt = 0;
  2257. tp->snd_cwnd_stamp = tcp_time_stamp;
  2258. tp->snd_ssthresh = tcp_current_ssthresh(sk);
  2259. icsk->icsk_mtup.search_low = icsk->icsk_mtup.probe_size;
  2260. icsk->icsk_mtup.probe_size = 0;
  2261. tcp_sync_mss(sk, icsk->icsk_pmtu_cookie);
  2262. }
  2263. /* Do a simple retransmit without using the backoff mechanisms in
  2264. * tcp_timer. This is used for path mtu discovery.
  2265. * The socket is already locked here.
  2266. */
  2267. void tcp_simple_retransmit(struct sock *sk)
  2268. {
  2269. const struct inet_connection_sock *icsk = inet_csk(sk);
  2270. struct tcp_sock *tp = tcp_sk(sk);
  2271. struct sk_buff *skb;
  2272. unsigned int mss = tcp_current_mss(sk);
  2273. u32 prior_lost = tp->lost_out;
  2274. tcp_for_write_queue(skb, sk) {
  2275. if (skb == tcp_send_head(sk))
  2276. break;
  2277. if (tcp_skb_seglen(skb) > mss &&
  2278. !(TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED)) {
  2279. if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_RETRANS) {
  2280. TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_RETRANS;
  2281. tp->retrans_out -= tcp_skb_pcount(skb);
  2282. }
  2283. tcp_skb_mark_lost_uncond_verify(tp, skb);
  2284. }
  2285. }
  2286. tcp_clear_retrans_hints_partial(tp);
  2287. if (prior_lost == tp->lost_out)
  2288. return;
  2289. if (tcp_is_reno(tp))
  2290. tcp_limit_reno_sacked(tp);
  2291. tcp_verify_left_out(tp);
  2292. /* Don't muck with the congestion window here.
  2293. * Reason is that we do not increase amount of _data_
  2294. * in network, but units changed and effective
  2295. * cwnd/ssthresh really reduced now.
  2296. */
  2297. if (icsk->icsk_ca_state != TCP_CA_Loss) {
  2298. tp->high_seq = tp->snd_nxt;
  2299. tp->snd_ssthresh = tcp_current_ssthresh(sk);
  2300. tp->prior_ssthresh = 0;
  2301. tp->undo_marker = 0;
  2302. tcp_set_ca_state(sk, TCP_CA_Loss);
  2303. }
  2304. tcp_xmit_retransmit_queue(sk);
  2305. }
  2306. EXPORT_SYMBOL(tcp_simple_retransmit);
  2307. static void tcp_enter_recovery(struct sock *sk, bool ece_ack)
  2308. {
  2309. struct tcp_sock *tp = tcp_sk(sk);
  2310. int mib_idx;
  2311. if (tcp_is_reno(tp))
  2312. mib_idx = LINUX_MIB_TCPRENORECOVERY;
  2313. else
  2314. mib_idx = LINUX_MIB_TCPSACKRECOVERY;
  2315. NET_INC_STATS_BH(sock_net(sk), mib_idx);
  2316. tp->prior_ssthresh = 0;
  2317. tcp_init_undo(tp);
  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 =
  2579. tcp_skb_timestamp(skb) + rto;
  2580. s32 delta = (s32)(rto_time_stamp - tcp_time_stamp);
  2581. /* delta may not be positive if the socket is locked
  2582. * when the retrans timer fires and is rescheduled.
  2583. */
  2584. if (delta > 0)
  2585. rto = delta;
  2586. }
  2587. inet_csk_reset_xmit_timer(sk, ICSK_TIME_RETRANS, rto,
  2588. TCP_RTO_MAX);
  2589. }
  2590. }
  2591. /* This function is called when the delayed ER timer fires. TCP enters
  2592. * fast recovery and performs fast-retransmit.
  2593. */
  2594. void tcp_resume_early_retransmit(struct sock *sk)
  2595. {
  2596. struct tcp_sock *tp = tcp_sk(sk);
  2597. tcp_rearm_rto(sk);
  2598. /* Stop if ER is disabled after the delayed ER timer is scheduled */
  2599. if (!tp->do_early_retrans)
  2600. return;
  2601. tcp_enter_recovery(sk, false);
  2602. tcp_update_scoreboard(sk, 1);
  2603. tcp_xmit_retransmit_queue(sk);
  2604. }
  2605. /* If we get here, the whole TSO packet has not been acked. */
  2606. static u32 tcp_tso_acked(struct sock *sk, struct sk_buff *skb)
  2607. {
  2608. struct tcp_sock *tp = tcp_sk(sk);
  2609. u32 packets_acked;
  2610. BUG_ON(!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una));
  2611. packets_acked = tcp_skb_pcount(skb);
  2612. if (tcp_trim_head(sk, skb, tp->snd_una - TCP_SKB_CB(skb)->seq))
  2613. return 0;
  2614. packets_acked -= tcp_skb_pcount(skb);
  2615. if (packets_acked) {
  2616. BUG_ON(tcp_skb_pcount(skb) == 0);
  2617. BUG_ON(!before(TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq));
  2618. }
  2619. return packets_acked;
  2620. }
  2621. /* Remove acknowledged frames from the retransmission queue. If our packet
  2622. * is before the ack sequence we can discard it as it's confirmed to have
  2623. * arrived at the other end.
  2624. */
  2625. static int tcp_clean_rtx_queue(struct sock *sk, int prior_fackets,
  2626. u32 prior_snd_una, long sack_rtt_us)
  2627. {
  2628. const struct inet_connection_sock *icsk = inet_csk(sk);
  2629. struct skb_mstamp first_ackt, last_ackt, now;
  2630. struct tcp_sock *tp = tcp_sk(sk);
  2631. u32 prior_sacked = tp->sacked_out;
  2632. u32 reord = tp->packets_out;
  2633. bool fully_acked = true;
  2634. long ca_seq_rtt_us = -1L;
  2635. long seq_rtt_us = -1L;
  2636. struct sk_buff *skb;
  2637. u32 pkts_acked = 0;
  2638. bool rtt_update;
  2639. int flag = 0;
  2640. first_ackt.v64 = 0;
  2641. while ((skb = tcp_write_queue_head(sk)) && skb != tcp_send_head(sk)) {
  2642. struct skb_shared_info *shinfo = skb_shinfo(skb);
  2643. struct tcp_skb_cb *scb = TCP_SKB_CB(skb);
  2644. u8 sacked = scb->sacked;
  2645. u32 acked_pcount;
  2646. if (unlikely(shinfo->tx_flags & SKBTX_ACK_TSTAMP) &&
  2647. between(shinfo->tskey, prior_snd_una, tp->snd_una - 1))
  2648. __skb_tstamp_tx(skb, NULL, sk, SCM_TSTAMP_ACK);
  2649. /* Determine how many packets and what bytes were acked, tso and else */
  2650. if (after(scb->end_seq, tp->snd_una)) {
  2651. if (tcp_skb_pcount(skb) == 1 ||
  2652. !after(tp->snd_una, scb->seq))
  2653. break;
  2654. acked_pcount = tcp_tso_acked(sk, skb);
  2655. if (!acked_pcount)
  2656. break;
  2657. fully_acked = false;
  2658. } else {
  2659. acked_pcount = tcp_skb_pcount(skb);
  2660. }
  2661. if (sacked & TCPCB_RETRANS) {
  2662. if (sacked & TCPCB_SACKED_RETRANS)
  2663. tp->retrans_out -= acked_pcount;
  2664. flag |= FLAG_RETRANS_DATA_ACKED;
  2665. } else {
  2666. last_ackt = skb->skb_mstamp;
  2667. WARN_ON_ONCE(last_ackt.v64 == 0);
  2668. if (!first_ackt.v64)
  2669. first_ackt = last_ackt;
  2670. if (!(sacked & TCPCB_SACKED_ACKED))
  2671. reord = min(pkts_acked, reord);
  2672. if (!after(scb->end_seq, tp->high_seq))
  2673. flag |= FLAG_ORIG_SACK_ACKED;
  2674. }
  2675. if (sacked & TCPCB_SACKED_ACKED)
  2676. tp->sacked_out -= acked_pcount;
  2677. if (sacked & TCPCB_LOST)
  2678. tp->lost_out -= acked_pcount;
  2679. tp->packets_out -= acked_pcount;
  2680. pkts_acked += acked_pcount;
  2681. /* Initial outgoing SYN's get put onto the write_queue
  2682. * just like anything else we transmit. It is not
  2683. * true data, and if we misinform our callers that
  2684. * this ACK acks real data, we will erroneously exit
  2685. * connection startup slow start one packet too
  2686. * quickly. This is severely frowned upon behavior.
  2687. */
  2688. if (!(scb->tcp_flags & TCPHDR_SYN)) {
  2689. flag |= FLAG_DATA_ACKED;
  2690. } else {
  2691. flag |= FLAG_SYN_ACKED;
  2692. tp->retrans_stamp = 0;
  2693. }
  2694. if (!fully_acked)
  2695. break;
  2696. tcp_unlink_write_queue(skb, sk);
  2697. sk_wmem_free_skb(sk, skb);
  2698. if (skb == tp->retransmit_skb_hint)
  2699. tp->retransmit_skb_hint = NULL;
  2700. if (skb == tp->lost_skb_hint)
  2701. tp->lost_skb_hint = NULL;
  2702. }
  2703. if (likely(between(tp->snd_up, prior_snd_una, tp->snd_una)))
  2704. tp->snd_up = tp->snd_una;
  2705. if (skb && (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED))
  2706. flag |= FLAG_SACK_RENEGING;
  2707. skb_mstamp_get(&now);
  2708. if (first_ackt.v64) {
  2709. seq_rtt_us = skb_mstamp_us_delta(&now, &first_ackt);
  2710. ca_seq_rtt_us = skb_mstamp_us_delta(&now, &last_ackt);
  2711. }
  2712. rtt_update = tcp_ack_update_rtt(sk, flag, seq_rtt_us, sack_rtt_us);
  2713. if (flag & FLAG_ACKED) {
  2714. const struct tcp_congestion_ops *ca_ops
  2715. = inet_csk(sk)->icsk_ca_ops;
  2716. tcp_rearm_rto(sk);
  2717. if (unlikely(icsk->icsk_mtup.probe_size &&
  2718. !after(tp->mtu_probe.probe_seq_end, tp->snd_una))) {
  2719. tcp_mtup_probe_success(sk);
  2720. }
  2721. if (tcp_is_reno(tp)) {
  2722. tcp_remove_reno_sacks(sk, pkts_acked);
  2723. } else {
  2724. int delta;
  2725. /* Non-retransmitted hole got filled? That's reordering */
  2726. if (reord < prior_fackets)
  2727. tcp_update_reordering(sk, tp->fackets_out - reord, 0);
  2728. delta = tcp_is_fack(tp) ? pkts_acked :
  2729. prior_sacked - tp->sacked_out;
  2730. tp->lost_cnt_hint -= min(tp->lost_cnt_hint, delta);
  2731. }
  2732. tp->fackets_out -= min(pkts_acked, tp->fackets_out);
  2733. if (ca_ops->pkts_acked)
  2734. ca_ops->pkts_acked(sk, pkts_acked, ca_seq_rtt_us);
  2735. } else if (skb && rtt_update && sack_rtt_us >= 0 &&
  2736. sack_rtt_us > skb_mstamp_us_delta(&now, &skb->skb_mstamp)) {
  2737. /* Do not re-arm RTO if the sack RTT is measured from data sent
  2738. * after when the head was last (re)transmitted. Otherwise the
  2739. * timeout may continue to extend in loss recovery.
  2740. */
  2741. tcp_rearm_rto(sk);
  2742. }
  2743. #if FASTRETRANS_DEBUG > 0
  2744. WARN_ON((int)tp->sacked_out < 0);
  2745. WARN_ON((int)tp->lost_out < 0);
  2746. WARN_ON((int)tp->retrans_out < 0);
  2747. if (!tp->packets_out && tcp_is_sack(tp)) {
  2748. icsk = inet_csk(sk);
  2749. if (tp->lost_out) {
  2750. pr_debug("Leak l=%u %d\n",
  2751. tp->lost_out, icsk->icsk_ca_state);
  2752. tp->lost_out = 0;
  2753. }
  2754. if (tp->sacked_out) {
  2755. pr_debug("Leak s=%u %d\n",
  2756. tp->sacked_out, icsk->icsk_ca_state);
  2757. tp->sacked_out = 0;
  2758. }
  2759. if (tp->retrans_out) {
  2760. pr_debug("Leak r=%u %d\n",
  2761. tp->retrans_out, icsk->icsk_ca_state);
  2762. tp->retrans_out = 0;
  2763. }
  2764. }
  2765. #endif
  2766. return flag;
  2767. }
  2768. static void tcp_ack_probe(struct sock *sk)
  2769. {
  2770. const struct tcp_sock *tp = tcp_sk(sk);
  2771. struct inet_connection_sock *icsk = inet_csk(sk);
  2772. /* Was it a usable window open? */
  2773. if (!after(TCP_SKB_CB(tcp_send_head(sk))->end_seq, tcp_wnd_end(tp))) {
  2774. icsk->icsk_backoff = 0;
  2775. inet_csk_clear_xmit_timer(sk, ICSK_TIME_PROBE0);
  2776. /* Socket must be waked up by subsequent tcp_data_snd_check().
  2777. * This function is not for random using!
  2778. */
  2779. } else {
  2780. inet_csk_reset_xmit_timer(sk, ICSK_TIME_PROBE0,
  2781. min(icsk->icsk_rto << icsk->icsk_backoff, TCP_RTO_MAX),
  2782. TCP_RTO_MAX);
  2783. }
  2784. }
  2785. static inline bool tcp_ack_is_dubious(const struct sock *sk, const int flag)
  2786. {
  2787. return !(flag & FLAG_NOT_DUP) || (flag & FLAG_CA_ALERT) ||
  2788. inet_csk(sk)->icsk_ca_state != TCP_CA_Open;
  2789. }
  2790. /* Decide wheather to run the increase function of congestion control. */
  2791. static inline bool tcp_may_raise_cwnd(const struct sock *sk, const int flag)
  2792. {
  2793. if (tcp_in_cwnd_reduction(sk))
  2794. return false;
  2795. /* If reordering is high then always grow cwnd whenever data is
  2796. * delivered regardless of its ordering. Otherwise stay conservative
  2797. * and only grow cwnd on in-order delivery (RFC5681). A stretched ACK w/
  2798. * new SACK or ECE mark may first advance cwnd here and later reduce
  2799. * cwnd in tcp_fastretrans_alert() based on more states.
  2800. */
  2801. if (tcp_sk(sk)->reordering > sysctl_tcp_reordering)
  2802. return flag & FLAG_FORWARD_PROGRESS;
  2803. return flag & FLAG_DATA_ACKED;
  2804. }
  2805. /* Check that window update is acceptable.
  2806. * The function assumes that snd_una<=ack<=snd_next.
  2807. */
  2808. static inline bool tcp_may_update_window(const struct tcp_sock *tp,
  2809. const u32 ack, const u32 ack_seq,
  2810. const u32 nwin)
  2811. {
  2812. return after(ack, tp->snd_una) ||
  2813. after(ack_seq, tp->snd_wl1) ||
  2814. (ack_seq == tp->snd_wl1 && nwin > tp->snd_wnd);
  2815. }
  2816. /* Update our send window.
  2817. *
  2818. * Window update algorithm, described in RFC793/RFC1122 (used in linux-2.2
  2819. * and in FreeBSD. NetBSD's one is even worse.) is wrong.
  2820. */
  2821. static int tcp_ack_update_window(struct sock *sk, const struct sk_buff *skb, u32 ack,
  2822. u32 ack_seq)
  2823. {
  2824. struct tcp_sock *tp = tcp_sk(sk);
  2825. int flag = 0;
  2826. u32 nwin = ntohs(tcp_hdr(skb)->window);
  2827. if (likely(!tcp_hdr(skb)->syn))
  2828. nwin <<= tp->rx_opt.snd_wscale;
  2829. if (tcp_may_update_window(tp, ack, ack_seq, nwin)) {
  2830. flag |= FLAG_WIN_UPDATE;
  2831. tcp_update_wl(tp, ack_seq);
  2832. if (tp->snd_wnd != nwin) {
  2833. tp->snd_wnd = nwin;
  2834. /* Note, it is the only place, where
  2835. * fast path is recovered for sending TCP.
  2836. */
  2837. tp->pred_flags = 0;
  2838. tcp_fast_path_check(sk);
  2839. if (nwin > tp->max_window) {
  2840. tp->max_window = nwin;
  2841. tcp_sync_mss(sk, inet_csk(sk)->icsk_pmtu_cookie);
  2842. }
  2843. }
  2844. }
  2845. tp->snd_una = ack;
  2846. return flag;
  2847. }
  2848. /* RFC 5961 7 [ACK Throttling] */
  2849. static void tcp_send_challenge_ack(struct sock *sk)
  2850. {
  2851. /* unprotected vars, we dont care of overwrites */
  2852. static u32 challenge_timestamp;
  2853. static unsigned int challenge_count;
  2854. u32 now = jiffies / HZ;
  2855. if (now != challenge_timestamp) {
  2856. challenge_timestamp = now;
  2857. challenge_count = 0;
  2858. }
  2859. if (++challenge_count <= sysctl_tcp_challenge_ack_limit) {
  2860. NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPCHALLENGEACK);
  2861. tcp_send_ack(sk);
  2862. }
  2863. }
  2864. static void tcp_store_ts_recent(struct tcp_sock *tp)
  2865. {
  2866. tp->rx_opt.ts_recent = tp->rx_opt.rcv_tsval;
  2867. tp->rx_opt.ts_recent_stamp = get_seconds();
  2868. }
  2869. static void tcp_replace_ts_recent(struct tcp_sock *tp, u32 seq)
  2870. {
  2871. if (tp->rx_opt.saw_tstamp && !after(seq, tp->rcv_wup)) {
  2872. /* PAWS bug workaround wrt. ACK frames, the PAWS discard
  2873. * extra check below makes sure this can only happen
  2874. * for pure ACK frames. -DaveM
  2875. *
  2876. * Not only, also it occurs for expired timestamps.
  2877. */
  2878. if (tcp_paws_check(&tp->rx_opt, 0))
  2879. tcp_store_ts_recent(tp);
  2880. }
  2881. }
  2882. /* This routine deals with acks during a TLP episode.
  2883. * Ref: loss detection algorithm in draft-dukkipati-tcpm-tcp-loss-probe.
  2884. */
  2885. static void tcp_process_tlp_ack(struct sock *sk, u32 ack, int flag)
  2886. {
  2887. struct tcp_sock *tp = tcp_sk(sk);
  2888. bool is_tlp_dupack = (ack == tp->tlp_high_seq) &&
  2889. !(flag & (FLAG_SND_UNA_ADVANCED |
  2890. FLAG_NOT_DUP | FLAG_DATA_SACKED));
  2891. /* Mark the end of TLP episode on receiving TLP dupack or when
  2892. * ack is after tlp_high_seq.
  2893. */
  2894. if (is_tlp_dupack) {
  2895. tp->tlp_high_seq = 0;
  2896. return;
  2897. }
  2898. if (after(ack, tp->tlp_high_seq)) {
  2899. tp->tlp_high_seq = 0;
  2900. /* Don't reduce cwnd if DSACK arrives for TLP retrans. */
  2901. if (!(flag & FLAG_DSACKING_ACK)) {
  2902. tcp_init_cwnd_reduction(sk);
  2903. tcp_set_ca_state(sk, TCP_CA_CWR);
  2904. tcp_end_cwnd_reduction(sk);
  2905. tcp_try_keep_open(sk);
  2906. NET_INC_STATS_BH(sock_net(sk),
  2907. LINUX_MIB_TCPLOSSPROBERECOVERY);
  2908. }
  2909. }
  2910. }
  2911. /* This routine deals with incoming acks, but not outgoing ones. */
  2912. static int tcp_ack(struct sock *sk, const struct sk_buff *skb, int flag)
  2913. {
  2914. struct inet_connection_sock *icsk = inet_csk(sk);
  2915. struct tcp_sock *tp = tcp_sk(sk);
  2916. u32 prior_snd_una = tp->snd_una;
  2917. u32 ack_seq = TCP_SKB_CB(skb)->seq;
  2918. u32 ack = TCP_SKB_CB(skb)->ack_seq;
  2919. bool is_dupack = false;
  2920. u32 prior_fackets;
  2921. int prior_packets = tp->packets_out;
  2922. const int prior_unsacked = tp->packets_out - tp->sacked_out;
  2923. int acked = 0; /* Number of packets newly acked */
  2924. long sack_rtt_us = -1L;
  2925. /* If the ack is older than previous acks
  2926. * then we can probably ignore it.
  2927. */
  2928. if (before(ack, prior_snd_una)) {
  2929. /* RFC 5961 5.2 [Blind Data Injection Attack].[Mitigation] */
  2930. if (before(ack, prior_snd_una - tp->max_window)) {
  2931. tcp_send_challenge_ack(sk);
  2932. return -1;
  2933. }
  2934. goto old_ack;
  2935. }
  2936. /* If the ack includes data we haven't sent yet, discard
  2937. * this segment (RFC793 Section 3.9).
  2938. */
  2939. if (after(ack, tp->snd_nxt))
  2940. goto invalid_ack;
  2941. if (icsk->icsk_pending == ICSK_TIME_EARLY_RETRANS ||
  2942. icsk->icsk_pending == ICSK_TIME_LOSS_PROBE)
  2943. tcp_rearm_rto(sk);
  2944. if (after(ack, prior_snd_una)) {
  2945. flag |= FLAG_SND_UNA_ADVANCED;
  2946. icsk->icsk_retransmits = 0;
  2947. }
  2948. prior_fackets = tp->fackets_out;
  2949. /* ts_recent update must be made after we are sure that the packet
  2950. * is in window.
  2951. */
  2952. if (flag & FLAG_UPDATE_TS_RECENT)
  2953. tcp_replace_ts_recent(tp, TCP_SKB_CB(skb)->seq);
  2954. if (!(flag & FLAG_SLOWPATH) && after(ack, prior_snd_una)) {
  2955. /* Window is constant, pure forward advance.
  2956. * No more checks are required.
  2957. * Note, we use the fact that SND.UNA>=SND.WL2.
  2958. */
  2959. tcp_update_wl(tp, ack_seq);
  2960. tp->snd_una = ack;
  2961. flag |= FLAG_WIN_UPDATE;
  2962. tcp_ca_event(sk, CA_EVENT_FAST_ACK);
  2963. NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPHPACKS);
  2964. } else {
  2965. if (ack_seq != TCP_SKB_CB(skb)->end_seq)
  2966. flag |= FLAG_DATA;
  2967. else
  2968. NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPPUREACKS);
  2969. flag |= tcp_ack_update_window(sk, skb, ack, ack_seq);
  2970. if (TCP_SKB_CB(skb)->sacked)
  2971. flag |= tcp_sacktag_write_queue(sk, skb, prior_snd_una,
  2972. &sack_rtt_us);
  2973. if (TCP_ECN_rcv_ecn_echo(tp, tcp_hdr(skb)))
  2974. flag |= FLAG_ECE;
  2975. tcp_ca_event(sk, CA_EVENT_SLOW_ACK);
  2976. }
  2977. /* We passed data and got it acked, remove any soft error
  2978. * log. Something worked...
  2979. */
  2980. sk->sk_err_soft = 0;
  2981. icsk->icsk_probes_out = 0;
  2982. tp->rcv_tstamp = tcp_time_stamp;
  2983. if (!prior_packets)
  2984. goto no_queue;
  2985. /* See if we can take anything off of the retransmit queue. */
  2986. acked = tp->packets_out;
  2987. flag |= tcp_clean_rtx_queue(sk, prior_fackets, prior_snd_una,
  2988. sack_rtt_us);
  2989. acked -= tp->packets_out;
  2990. /* Advance cwnd if state allows */
  2991. if (tcp_may_raise_cwnd(sk, flag))
  2992. tcp_cong_avoid(sk, ack, acked);
  2993. if (tcp_ack_is_dubious(sk, flag)) {
  2994. is_dupack = !(flag & (FLAG_SND_UNA_ADVANCED | FLAG_NOT_DUP));
  2995. tcp_fastretrans_alert(sk, acked, prior_unsacked,
  2996. is_dupack, flag);
  2997. }
  2998. if (tp->tlp_high_seq)
  2999. tcp_process_tlp_ack(sk, ack, flag);
  3000. if ((flag & FLAG_FORWARD_PROGRESS) || !(flag & FLAG_NOT_DUP)) {
  3001. struct dst_entry *dst = __sk_dst_get(sk);
  3002. if (dst)
  3003. dst_confirm(dst);
  3004. }
  3005. if (icsk->icsk_pending == ICSK_TIME_RETRANS)
  3006. tcp_schedule_loss_probe(sk);
  3007. tcp_update_pacing_rate(sk);
  3008. return 1;
  3009. no_queue:
  3010. /* If data was DSACKed, see if we can undo a cwnd reduction. */
  3011. if (flag & FLAG_DSACKING_ACK)
  3012. tcp_fastretrans_alert(sk, acked, prior_unsacked,
  3013. is_dupack, flag);
  3014. /* If this ack opens up a zero window, clear backoff. It was
  3015. * being used to time the probes, and is probably far higher than
  3016. * it needs to be for normal retransmission.
  3017. */
  3018. if (tcp_send_head(sk))
  3019. tcp_ack_probe(sk);
  3020. if (tp->tlp_high_seq)
  3021. tcp_process_tlp_ack(sk, ack, flag);
  3022. return 1;
  3023. invalid_ack:
  3024. SOCK_DEBUG(sk, "Ack %u after %u:%u\n", ack, tp->snd_una, tp->snd_nxt);
  3025. return -1;
  3026. old_ack:
  3027. /* If data was SACKed, tag it and see if we should send more data.
  3028. * If data was DSACKed, see if we can undo a cwnd reduction.
  3029. */
  3030. if (TCP_SKB_CB(skb)->sacked) {
  3031. flag |= tcp_sacktag_write_queue(sk, skb, prior_snd_una,
  3032. &sack_rtt_us);
  3033. tcp_fastretrans_alert(sk, acked, prior_unsacked,
  3034. is_dupack, flag);
  3035. }
  3036. SOCK_DEBUG(sk, "Ack %u before %u:%u\n", ack, tp->snd_una, tp->snd_nxt);
  3037. return 0;
  3038. }
  3039. /* Look for tcp options. Normally only called on SYN and SYNACK packets.
  3040. * But, this can also be called on packets in the established flow when
  3041. * the fast version below fails.
  3042. */
  3043. void tcp_parse_options(const struct sk_buff *skb,
  3044. struct tcp_options_received *opt_rx, int estab,
  3045. struct tcp_fastopen_cookie *foc)
  3046. {
  3047. const unsigned char *ptr;
  3048. const struct tcphdr *th = tcp_hdr(skb);
  3049. int length = (th->doff * 4) - sizeof(struct tcphdr);
  3050. ptr = (const unsigned char *)(th + 1);
  3051. opt_rx->saw_tstamp = 0;
  3052. while (length > 0) {
  3053. int opcode = *ptr++;
  3054. int opsize;
  3055. switch (opcode) {
  3056. case TCPOPT_EOL:
  3057. return;
  3058. case TCPOPT_NOP: /* Ref: RFC 793 section 3.1 */
  3059. length--;
  3060. continue;
  3061. default:
  3062. opsize = *ptr++;
  3063. if (opsize < 2) /* "silly options" */
  3064. return;
  3065. if (opsize > length)
  3066. return; /* don't parse partial options */
  3067. switch (opcode) {
  3068. case TCPOPT_MSS:
  3069. if (opsize == TCPOLEN_MSS && th->syn && !estab) {
  3070. u16 in_mss = get_unaligned_be16(ptr);
  3071. if (in_mss) {
  3072. if (opt_rx->user_mss &&
  3073. opt_rx->user_mss < in_mss)
  3074. in_mss = opt_rx->user_mss;
  3075. opt_rx->mss_clamp = in_mss;
  3076. }
  3077. }
  3078. break;
  3079. case TCPOPT_WINDOW:
  3080. if (opsize == TCPOLEN_WINDOW && th->syn &&
  3081. !estab && sysctl_tcp_window_scaling) {
  3082. __u8 snd_wscale = *(__u8 *)ptr;
  3083. opt_rx->wscale_ok = 1;
  3084. if (snd_wscale > 14) {
  3085. net_info_ratelimited("%s: Illegal window scaling value %d >14 received\n",
  3086. __func__,
  3087. snd_wscale);
  3088. snd_wscale = 14;
  3089. }
  3090. opt_rx->snd_wscale = snd_wscale;
  3091. }
  3092. break;
  3093. case TCPOPT_TIMESTAMP:
  3094. if ((opsize == TCPOLEN_TIMESTAMP) &&
  3095. ((estab && opt_rx->tstamp_ok) ||
  3096. (!estab && sysctl_tcp_timestamps))) {
  3097. opt_rx->saw_tstamp = 1;
  3098. opt_rx->rcv_tsval = get_unaligned_be32(ptr);
  3099. opt_rx->rcv_tsecr = get_unaligned_be32(ptr + 4);
  3100. }
  3101. break;
  3102. case TCPOPT_SACK_PERM:
  3103. if (opsize == TCPOLEN_SACK_PERM && th->syn &&
  3104. !estab && sysctl_tcp_sack) {
  3105. opt_rx->sack_ok = TCP_SACK_SEEN;
  3106. tcp_sack_reset(opt_rx);
  3107. }
  3108. break;
  3109. case TCPOPT_SACK:
  3110. if ((opsize >= (TCPOLEN_SACK_BASE + TCPOLEN_SACK_PERBLOCK)) &&
  3111. !((opsize - TCPOLEN_SACK_BASE) % TCPOLEN_SACK_PERBLOCK) &&
  3112. opt_rx->sack_ok) {
  3113. TCP_SKB_CB(skb)->sacked = (ptr - 2) - (unsigned char *)th;
  3114. }
  3115. break;
  3116. #ifdef CONFIG_TCP_MD5SIG
  3117. case TCPOPT_MD5SIG:
  3118. /*
  3119. * The MD5 Hash has already been
  3120. * checked (see tcp_v{4,6}_do_rcv()).
  3121. */
  3122. break;
  3123. #endif
  3124. case TCPOPT_EXP:
  3125. /* Fast Open option shares code 254 using a
  3126. * 16 bits magic number. It's valid only in
  3127. * SYN or SYN-ACK with an even size.
  3128. */
  3129. if (opsize < TCPOLEN_EXP_FASTOPEN_BASE ||
  3130. get_unaligned_be16(ptr) != TCPOPT_FASTOPEN_MAGIC ||
  3131. foc == NULL || !th->syn || (opsize & 1))
  3132. break;
  3133. foc->len = opsize - TCPOLEN_EXP_FASTOPEN_BASE;
  3134. if (foc->len >= TCP_FASTOPEN_COOKIE_MIN &&
  3135. foc->len <= TCP_FASTOPEN_COOKIE_MAX)
  3136. memcpy(foc->val, ptr + 2, foc->len);
  3137. else if (foc->len != 0)
  3138. foc->len = -1;
  3139. break;
  3140. }
  3141. ptr += opsize-2;
  3142. length -= opsize;
  3143. }
  3144. }
  3145. }
  3146. EXPORT_SYMBOL(tcp_parse_options);
  3147. static bool tcp_parse_aligned_timestamp(struct tcp_sock *tp, const struct tcphdr *th)
  3148. {
  3149. const __be32 *ptr = (const __be32 *)(th + 1);
  3150. if (*ptr == htonl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16)
  3151. | (TCPOPT_TIMESTAMP << 8) | TCPOLEN_TIMESTAMP)) {
  3152. tp->rx_opt.saw_tstamp = 1;
  3153. ++ptr;
  3154. tp->rx_opt.rcv_tsval = ntohl(*ptr);
  3155. ++ptr;
  3156. if (*ptr)
  3157. tp->rx_opt.rcv_tsecr = ntohl(*ptr) - tp->tsoffset;
  3158. else
  3159. tp->rx_opt.rcv_tsecr = 0;
  3160. return true;
  3161. }
  3162. return false;
  3163. }
  3164. /* Fast parse options. This hopes to only see timestamps.
  3165. * If it is wrong it falls back on tcp_parse_options().
  3166. */
  3167. static bool tcp_fast_parse_options(const struct sk_buff *skb,
  3168. const struct tcphdr *th, struct tcp_sock *tp)
  3169. {
  3170. /* In the spirit of fast parsing, compare doff directly to constant
  3171. * values. Because equality is used, short doff can be ignored here.
  3172. */
  3173. if (th->doff == (sizeof(*th) / 4)) {
  3174. tp->rx_opt.saw_tstamp = 0;
  3175. return false;
  3176. } else if (tp->rx_opt.tstamp_ok &&
  3177. th->doff == ((sizeof(*th) + TCPOLEN_TSTAMP_ALIGNED) / 4)) {
  3178. if (tcp_parse_aligned_timestamp(tp, th))
  3179. return true;
  3180. }
  3181. tcp_parse_options(skb, &tp->rx_opt, 1, NULL);
  3182. if (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr)
  3183. tp->rx_opt.rcv_tsecr -= tp->tsoffset;
  3184. return true;
  3185. }
  3186. #ifdef CONFIG_TCP_MD5SIG
  3187. /*
  3188. * Parse MD5 Signature option
  3189. */
  3190. const u8 *tcp_parse_md5sig_option(const struct tcphdr *th)
  3191. {
  3192. int length = (th->doff << 2) - sizeof(*th);
  3193. const u8 *ptr = (const u8 *)(th + 1);
  3194. /* If the TCP option is too short, we can short cut */
  3195. if (length < TCPOLEN_MD5SIG)
  3196. return NULL;
  3197. while (length > 0) {
  3198. int opcode = *ptr++;
  3199. int opsize;
  3200. switch (opcode) {
  3201. case TCPOPT_EOL:
  3202. return NULL;
  3203. case TCPOPT_NOP:
  3204. length--;
  3205. continue;
  3206. default:
  3207. opsize = *ptr++;
  3208. if (opsize < 2 || opsize > length)
  3209. return NULL;
  3210. if (opcode == TCPOPT_MD5SIG)
  3211. return opsize == TCPOLEN_MD5SIG ? ptr : NULL;
  3212. }
  3213. ptr += opsize - 2;
  3214. length -= opsize;
  3215. }
  3216. return NULL;
  3217. }
  3218. EXPORT_SYMBOL(tcp_parse_md5sig_option);
  3219. #endif
  3220. /* Sorry, PAWS as specified is broken wrt. pure-ACKs -DaveM
  3221. *
  3222. * It is not fatal. If this ACK does _not_ change critical state (seqs, window)
  3223. * it can pass through stack. So, the following predicate verifies that
  3224. * this segment is not used for anything but congestion avoidance or
  3225. * fast retransmit. Moreover, we even are able to eliminate most of such
  3226. * second order effects, if we apply some small "replay" window (~RTO)
  3227. * to timestamp space.
  3228. *
  3229. * All these measures still do not guarantee that we reject wrapped ACKs
  3230. * on networks with high bandwidth, when sequence space is recycled fastly,
  3231. * but it guarantees that such events will be very rare and do not affect
  3232. * connection seriously. This doesn't look nice, but alas, PAWS is really
  3233. * buggy extension.
  3234. *
  3235. * [ Later note. Even worse! It is buggy for segments _with_ data. RFC
  3236. * states that events when retransmit arrives after original data are rare.
  3237. * It is a blatant lie. VJ forgot about fast retransmit! 8)8) It is
  3238. * the biggest problem on large power networks even with minor reordering.
  3239. * OK, let's give it small replay window. If peer clock is even 1hz, it is safe
  3240. * up to bandwidth of 18Gigabit/sec. 8) ]
  3241. */
  3242. static int tcp_disordered_ack(const struct sock *sk, const struct sk_buff *skb)
  3243. {
  3244. const struct tcp_sock *tp = tcp_sk(sk);
  3245. const struct tcphdr *th = tcp_hdr(skb);
  3246. u32 seq = TCP_SKB_CB(skb)->seq;
  3247. u32 ack = TCP_SKB_CB(skb)->ack_seq;
  3248. return (/* 1. Pure ACK with correct sequence number. */
  3249. (th->ack && seq == TCP_SKB_CB(skb)->end_seq && seq == tp->rcv_nxt) &&
  3250. /* 2. ... and duplicate ACK. */
  3251. ack == tp->snd_una &&
  3252. /* 3. ... and does not update window. */
  3253. !tcp_may_update_window(tp, ack, seq, ntohs(th->window) << tp->rx_opt.snd_wscale) &&
  3254. /* 4. ... and sits in replay window. */
  3255. (s32)(tp->rx_opt.ts_recent - tp->rx_opt.rcv_tsval) <= (inet_csk(sk)->icsk_rto * 1024) / HZ);
  3256. }
  3257. static inline bool tcp_paws_discard(const struct sock *sk,
  3258. const struct sk_buff *skb)
  3259. {
  3260. const struct tcp_sock *tp = tcp_sk(sk);
  3261. return !tcp_paws_check(&tp->rx_opt, TCP_PAWS_WINDOW) &&
  3262. !tcp_disordered_ack(sk, skb);
  3263. }
  3264. /* Check segment sequence number for validity.
  3265. *
  3266. * Segment controls are considered valid, if the segment
  3267. * fits to the window after truncation to the window. Acceptability
  3268. * of data (and SYN, FIN, of course) is checked separately.
  3269. * See tcp_data_queue(), for example.
  3270. *
  3271. * Also, controls (RST is main one) are accepted using RCV.WUP instead
  3272. * of RCV.NXT. Peer still did not advance his SND.UNA when we
  3273. * delayed ACK, so that hisSND.UNA<=ourRCV.WUP.
  3274. * (borrowed from freebsd)
  3275. */
  3276. static inline bool tcp_sequence(const struct tcp_sock *tp, u32 seq, u32 end_seq)
  3277. {
  3278. return !before(end_seq, tp->rcv_wup) &&
  3279. !after(seq, tp->rcv_nxt + tcp_receive_window(tp));
  3280. }
  3281. /* When we get a reset we do this. */
  3282. void tcp_reset(struct sock *sk)
  3283. {
  3284. /* We want the right error as BSD sees it (and indeed as we do). */
  3285. switch (sk->sk_state) {
  3286. case TCP_SYN_SENT:
  3287. sk->sk_err = ECONNREFUSED;
  3288. break;
  3289. case TCP_CLOSE_WAIT:
  3290. sk->sk_err = EPIPE;
  3291. break;
  3292. case TCP_CLOSE:
  3293. return;
  3294. default:
  3295. sk->sk_err = ECONNRESET;
  3296. }
  3297. /* This barrier is coupled with smp_rmb() in tcp_poll() */
  3298. smp_wmb();
  3299. if (!sock_flag(sk, SOCK_DEAD))
  3300. sk->sk_error_report(sk);
  3301. tcp_done(sk);
  3302. }
  3303. /*
  3304. * Process the FIN bit. This now behaves as it is supposed to work
  3305. * and the FIN takes effect when it is validly part of sequence
  3306. * space. Not before when we get holes.
  3307. *
  3308. * If we are ESTABLISHED, a received fin moves us to CLOSE-WAIT
  3309. * (and thence onto LAST-ACK and finally, CLOSE, we never enter
  3310. * TIME-WAIT)
  3311. *
  3312. * If we are in FINWAIT-1, a received FIN indicates simultaneous
  3313. * close and we go into CLOSING (and later onto TIME-WAIT)
  3314. *
  3315. * If we are in FINWAIT-2, a received FIN moves us to TIME-WAIT.
  3316. */
  3317. static void tcp_fin(struct sock *sk)
  3318. {
  3319. struct tcp_sock *tp = tcp_sk(sk);
  3320. const struct dst_entry *dst;
  3321. inet_csk_schedule_ack(sk);
  3322. sk->sk_shutdown |= RCV_SHUTDOWN;
  3323. sock_set_flag(sk, SOCK_DONE);
  3324. switch (sk->sk_state) {
  3325. case TCP_SYN_RECV:
  3326. case TCP_ESTABLISHED:
  3327. /* Move to CLOSE_WAIT */
  3328. tcp_set_state(sk, TCP_CLOSE_WAIT);
  3329. dst = __sk_dst_get(sk);
  3330. if (!dst || !dst_metric(dst, RTAX_QUICKACK))
  3331. inet_csk(sk)->icsk_ack.pingpong = 1;
  3332. break;
  3333. case TCP_CLOSE_WAIT:
  3334. case TCP_CLOSING:
  3335. /* Received a retransmission of the FIN, do
  3336. * nothing.
  3337. */
  3338. break;
  3339. case TCP_LAST_ACK:
  3340. /* RFC793: Remain in the LAST-ACK state. */
  3341. break;
  3342. case TCP_FIN_WAIT1:
  3343. /* This case occurs when a simultaneous close
  3344. * happens, we must ack the received FIN and
  3345. * enter the CLOSING state.
  3346. */
  3347. tcp_send_ack(sk);
  3348. tcp_set_state(sk, TCP_CLOSING);
  3349. break;
  3350. case TCP_FIN_WAIT2:
  3351. /* Received a FIN -- send ACK and enter TIME_WAIT. */
  3352. tcp_send_ack(sk);
  3353. tcp_time_wait(sk, TCP_TIME_WAIT, 0);
  3354. break;
  3355. default:
  3356. /* Only TCP_LISTEN and TCP_CLOSE are left, in these
  3357. * cases we should never reach this piece of code.
  3358. */
  3359. pr_err("%s: Impossible, sk->sk_state=%d\n",
  3360. __func__, sk->sk_state);
  3361. break;
  3362. }
  3363. /* It _is_ possible, that we have something out-of-order _after_ FIN.
  3364. * Probably, we should reset in this case. For now drop them.
  3365. */
  3366. __skb_queue_purge(&tp->out_of_order_queue);
  3367. if (tcp_is_sack(tp))
  3368. tcp_sack_reset(&tp->rx_opt);
  3369. sk_mem_reclaim(sk);
  3370. if (!sock_flag(sk, SOCK_DEAD)) {
  3371. sk->sk_state_change(sk);
  3372. /* Do not send POLL_HUP for half duplex close. */
  3373. if (sk->sk_shutdown == SHUTDOWN_MASK ||
  3374. sk->sk_state == TCP_CLOSE)
  3375. sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_HUP);
  3376. else
  3377. sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN);
  3378. }
  3379. }
  3380. static inline bool tcp_sack_extend(struct tcp_sack_block *sp, u32 seq,
  3381. u32 end_seq)
  3382. {
  3383. if (!after(seq, sp->end_seq) && !after(sp->start_seq, end_seq)) {
  3384. if (before(seq, sp->start_seq))
  3385. sp->start_seq = seq;
  3386. if (after(end_seq, sp->end_seq))
  3387. sp->end_seq = end_seq;
  3388. return true;
  3389. }
  3390. return false;
  3391. }
  3392. static void tcp_dsack_set(struct sock *sk, u32 seq, u32 end_seq)
  3393. {
  3394. struct tcp_sock *tp = tcp_sk(sk);
  3395. if (tcp_is_sack(tp) && sysctl_tcp_dsack) {
  3396. int mib_idx;
  3397. if (before(seq, tp->rcv_nxt))
  3398. mib_idx = LINUX_MIB_TCPDSACKOLDSENT;
  3399. else
  3400. mib_idx = LINUX_MIB_TCPDSACKOFOSENT;
  3401. NET_INC_STATS_BH(sock_net(sk), mib_idx);
  3402. tp->rx_opt.dsack = 1;
  3403. tp->duplicate_sack[0].start_seq = seq;
  3404. tp->duplicate_sack[0].end_seq = end_seq;
  3405. }
  3406. }
  3407. static void tcp_dsack_extend(struct sock *sk, u32 seq, u32 end_seq)
  3408. {
  3409. struct tcp_sock *tp = tcp_sk(sk);
  3410. if (!tp->rx_opt.dsack)
  3411. tcp_dsack_set(sk, seq, end_seq);
  3412. else
  3413. tcp_sack_extend(tp->duplicate_sack, seq, end_seq);
  3414. }
  3415. static void tcp_send_dupack(struct sock *sk, const struct sk_buff *skb)
  3416. {
  3417. struct tcp_sock *tp = tcp_sk(sk);
  3418. if (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq &&
  3419. before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) {
  3420. NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_DELAYEDACKLOST);
  3421. tcp_enter_quickack_mode(sk);
  3422. if (tcp_is_sack(tp) && sysctl_tcp_dsack) {
  3423. u32 end_seq = TCP_SKB_CB(skb)->end_seq;
  3424. if (after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt))
  3425. end_seq = tp->rcv_nxt;
  3426. tcp_dsack_set(sk, TCP_SKB_CB(skb)->seq, end_seq);
  3427. }
  3428. }
  3429. tcp_send_ack(sk);
  3430. }
  3431. /* These routines update the SACK block as out-of-order packets arrive or
  3432. * in-order packets close up the sequence space.
  3433. */
  3434. static void tcp_sack_maybe_coalesce(struct tcp_sock *tp)
  3435. {
  3436. int this_sack;
  3437. struct tcp_sack_block *sp = &tp->selective_acks[0];
  3438. struct tcp_sack_block *swalk = sp + 1;
  3439. /* See if the recent change to the first SACK eats into
  3440. * or hits the sequence space of other SACK blocks, if so coalesce.
  3441. */
  3442. for (this_sack = 1; this_sack < tp->rx_opt.num_sacks;) {
  3443. if (tcp_sack_extend(sp, swalk->start_seq, swalk->end_seq)) {
  3444. int i;
  3445. /* Zap SWALK, by moving every further SACK up by one slot.
  3446. * Decrease num_sacks.
  3447. */
  3448. tp->rx_opt.num_sacks--;
  3449. for (i = this_sack; i < tp->rx_opt.num_sacks; i++)
  3450. sp[i] = sp[i + 1];
  3451. continue;
  3452. }
  3453. this_sack++, swalk++;
  3454. }
  3455. }
  3456. static void tcp_sack_new_ofo_skb(struct sock *sk, u32 seq, u32 end_seq)
  3457. {
  3458. struct tcp_sock *tp = tcp_sk(sk);
  3459. struct tcp_sack_block *sp = &tp->selective_acks[0];
  3460. int cur_sacks = tp->rx_opt.num_sacks;
  3461. int this_sack;
  3462. if (!cur_sacks)
  3463. goto new_sack;
  3464. for (this_sack = 0; this_sack < cur_sacks; this_sack++, sp++) {
  3465. if (tcp_sack_extend(sp, seq, end_seq)) {
  3466. /* Rotate this_sack to the first one. */
  3467. for (; this_sack > 0; this_sack--, sp--)
  3468. swap(*sp, *(sp - 1));
  3469. if (cur_sacks > 1)
  3470. tcp_sack_maybe_coalesce(tp);
  3471. return;
  3472. }
  3473. }
  3474. /* Could not find an adjacent existing SACK, build a new one,
  3475. * put it at the front, and shift everyone else down. We
  3476. * always know there is at least one SACK present already here.
  3477. *
  3478. * If the sack array is full, forget about the last one.
  3479. */
  3480. if (this_sack >= TCP_NUM_SACKS) {
  3481. this_sack--;
  3482. tp->rx_opt.num_sacks--;
  3483. sp--;
  3484. }
  3485. for (; this_sack > 0; this_sack--, sp--)
  3486. *sp = *(sp - 1);
  3487. new_sack:
  3488. /* Build the new head SACK, and we're done. */
  3489. sp->start_seq = seq;
  3490. sp->end_seq = end_seq;
  3491. tp->rx_opt.num_sacks++;
  3492. }
  3493. /* RCV.NXT advances, some SACKs should be eaten. */
  3494. static void tcp_sack_remove(struct tcp_sock *tp)
  3495. {
  3496. struct tcp_sack_block *sp = &tp->selective_acks[0];
  3497. int num_sacks = tp->rx_opt.num_sacks;
  3498. int this_sack;
  3499. /* Empty ofo queue, hence, all the SACKs are eaten. Clear. */
  3500. if (skb_queue_empty(&tp->out_of_order_queue)) {
  3501. tp->rx_opt.num_sacks = 0;
  3502. return;
  3503. }
  3504. for (this_sack = 0; this_sack < num_sacks;) {
  3505. /* Check if the start of the sack is covered by RCV.NXT. */
  3506. if (!before(tp->rcv_nxt, sp->start_seq)) {
  3507. int i;
  3508. /* RCV.NXT must cover all the block! */
  3509. WARN_ON(before(tp->rcv_nxt, sp->end_seq));
  3510. /* Zap this SACK, by moving forward any other SACKS. */
  3511. for (i = this_sack+1; i < num_sacks; i++)
  3512. tp->selective_acks[i-1] = tp->selective_acks[i];
  3513. num_sacks--;
  3514. continue;
  3515. }
  3516. this_sack++;
  3517. sp++;
  3518. }
  3519. tp->rx_opt.num_sacks = num_sacks;
  3520. }
  3521. /* This one checks to see if we can put data from the
  3522. * out_of_order queue into the receive_queue.
  3523. */
  3524. static void tcp_ofo_queue(struct sock *sk)
  3525. {
  3526. struct tcp_sock *tp = tcp_sk(sk);
  3527. __u32 dsack_high = tp->rcv_nxt;
  3528. struct sk_buff *skb;
  3529. while ((skb = skb_peek(&tp->out_of_order_queue)) != NULL) {
  3530. if (after(TCP_SKB_CB(skb)->seq, tp->rcv_nxt))
  3531. break;
  3532. if (before(TCP_SKB_CB(skb)->seq, dsack_high)) {
  3533. __u32 dsack = dsack_high;
  3534. if (before(TCP_SKB_CB(skb)->end_seq, dsack_high))
  3535. dsack_high = TCP_SKB_CB(skb)->end_seq;
  3536. tcp_dsack_extend(sk, TCP_SKB_CB(skb)->seq, dsack);
  3537. }
  3538. if (!after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt)) {
  3539. SOCK_DEBUG(sk, "ofo packet was already received\n");
  3540. __skb_unlink(skb, &tp->out_of_order_queue);
  3541. __kfree_skb(skb);
  3542. continue;
  3543. }
  3544. SOCK_DEBUG(sk, "ofo requeuing : rcv_next %X seq %X - %X\n",
  3545. tp->rcv_nxt, TCP_SKB_CB(skb)->seq,
  3546. TCP_SKB_CB(skb)->end_seq);
  3547. __skb_unlink(skb, &tp->out_of_order_queue);
  3548. __skb_queue_tail(&sk->sk_receive_queue, skb);
  3549. tp->rcv_nxt = TCP_SKB_CB(skb)->end_seq;
  3550. if (tcp_hdr(skb)->fin)
  3551. tcp_fin(sk);
  3552. }
  3553. }
  3554. static bool tcp_prune_ofo_queue(struct sock *sk);
  3555. static int tcp_prune_queue(struct sock *sk);
  3556. static int tcp_try_rmem_schedule(struct sock *sk, struct sk_buff *skb,
  3557. unsigned int size)
  3558. {
  3559. if (atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf ||
  3560. !sk_rmem_schedule(sk, skb, size)) {
  3561. if (tcp_prune_queue(sk) < 0)
  3562. return -1;
  3563. if (!sk_rmem_schedule(sk, skb, size)) {
  3564. if (!tcp_prune_ofo_queue(sk))
  3565. return -1;
  3566. if (!sk_rmem_schedule(sk, skb, size))
  3567. return -1;
  3568. }
  3569. }
  3570. return 0;
  3571. }
  3572. /**
  3573. * tcp_try_coalesce - try to merge skb to prior one
  3574. * @sk: socket
  3575. * @to: prior buffer
  3576. * @from: buffer to add in queue
  3577. * @fragstolen: pointer to boolean
  3578. *
  3579. * Before queueing skb @from after @to, try to merge them
  3580. * to reduce overall memory use and queue lengths, if cost is small.
  3581. * Packets in ofo or receive queues can stay a long time.
  3582. * Better try to coalesce them right now to avoid future collapses.
  3583. * Returns true if caller should free @from instead of queueing it
  3584. */
  3585. static bool tcp_try_coalesce(struct sock *sk,
  3586. struct sk_buff *to,
  3587. struct sk_buff *from,
  3588. bool *fragstolen)
  3589. {
  3590. int delta;
  3591. *fragstolen = false;
  3592. if (tcp_hdr(from)->fin)
  3593. return false;
  3594. /* Its possible this segment overlaps with prior segment in queue */
  3595. if (TCP_SKB_CB(from)->seq != TCP_SKB_CB(to)->end_seq)
  3596. return false;
  3597. if (!skb_try_coalesce(to, from, fragstolen, &delta))
  3598. return false;
  3599. atomic_add(delta, &sk->sk_rmem_alloc);
  3600. sk_mem_charge(sk, delta);
  3601. NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPRCVCOALESCE);
  3602. TCP_SKB_CB(to)->end_seq = TCP_SKB_CB(from)->end_seq;
  3603. TCP_SKB_CB(to)->ack_seq = TCP_SKB_CB(from)->ack_seq;
  3604. return true;
  3605. }
  3606. static void tcp_data_queue_ofo(struct sock *sk, struct sk_buff *skb)
  3607. {
  3608. struct tcp_sock *tp = tcp_sk(sk);
  3609. struct sk_buff *skb1;
  3610. u32 seq, end_seq;
  3611. TCP_ECN_check_ce(tp, skb);
  3612. if (unlikely(tcp_try_rmem_schedule(sk, skb, skb->truesize))) {
  3613. NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPOFODROP);
  3614. __kfree_skb(skb);
  3615. return;
  3616. }
  3617. /* Disable header prediction. */
  3618. tp->pred_flags = 0;
  3619. inet_csk_schedule_ack(sk);
  3620. NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPOFOQUEUE);
  3621. SOCK_DEBUG(sk, "out of order segment: rcv_next %X seq %X - %X\n",
  3622. tp->rcv_nxt, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq);
  3623. skb1 = skb_peek_tail(&tp->out_of_order_queue);
  3624. if (!skb1) {
  3625. /* Initial out of order segment, build 1 SACK. */
  3626. if (tcp_is_sack(tp)) {
  3627. tp->rx_opt.num_sacks = 1;
  3628. tp->selective_acks[0].start_seq = TCP_SKB_CB(skb)->seq;
  3629. tp->selective_acks[0].end_seq =
  3630. TCP_SKB_CB(skb)->end_seq;
  3631. }
  3632. __skb_queue_head(&tp->out_of_order_queue, skb);
  3633. goto end;
  3634. }
  3635. seq = TCP_SKB_CB(skb)->seq;
  3636. end_seq = TCP_SKB_CB(skb)->end_seq;
  3637. if (seq == TCP_SKB_CB(skb1)->end_seq) {
  3638. bool fragstolen;
  3639. if (!tcp_try_coalesce(sk, skb1, skb, &fragstolen)) {
  3640. __skb_queue_after(&tp->out_of_order_queue, skb1, skb);
  3641. } else {
  3642. tcp_grow_window(sk, skb);
  3643. kfree_skb_partial(skb, fragstolen);
  3644. skb = NULL;
  3645. }
  3646. if (!tp->rx_opt.num_sacks ||
  3647. tp->selective_acks[0].end_seq != seq)
  3648. goto add_sack;
  3649. /* Common case: data arrive in order after hole. */
  3650. tp->selective_acks[0].end_seq = end_seq;
  3651. goto end;
  3652. }
  3653. /* Find place to insert this segment. */
  3654. while (1) {
  3655. if (!after(TCP_SKB_CB(skb1)->seq, seq))
  3656. break;
  3657. if (skb_queue_is_first(&tp->out_of_order_queue, skb1)) {
  3658. skb1 = NULL;
  3659. break;
  3660. }
  3661. skb1 = skb_queue_prev(&tp->out_of_order_queue, skb1);
  3662. }
  3663. /* Do skb overlap to previous one? */
  3664. if (skb1 && before(seq, TCP_SKB_CB(skb1)->end_seq)) {
  3665. if (!after(end_seq, TCP_SKB_CB(skb1)->end_seq)) {
  3666. /* All the bits are present. Drop. */
  3667. NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPOFOMERGE);
  3668. __kfree_skb(skb);
  3669. skb = NULL;
  3670. tcp_dsack_set(sk, seq, end_seq);
  3671. goto add_sack;
  3672. }
  3673. if (after(seq, TCP_SKB_CB(skb1)->seq)) {
  3674. /* Partial overlap. */
  3675. tcp_dsack_set(sk, seq,
  3676. TCP_SKB_CB(skb1)->end_seq);
  3677. } else {
  3678. if (skb_queue_is_first(&tp->out_of_order_queue,
  3679. skb1))
  3680. skb1 = NULL;
  3681. else
  3682. skb1 = skb_queue_prev(
  3683. &tp->out_of_order_queue,
  3684. skb1);
  3685. }
  3686. }
  3687. if (!skb1)
  3688. __skb_queue_head(&tp->out_of_order_queue, skb);
  3689. else
  3690. __skb_queue_after(&tp->out_of_order_queue, skb1, skb);
  3691. /* And clean segments covered by new one as whole. */
  3692. while (!skb_queue_is_last(&tp->out_of_order_queue, skb)) {
  3693. skb1 = skb_queue_next(&tp->out_of_order_queue, skb);
  3694. if (!after(end_seq, TCP_SKB_CB(skb1)->seq))
  3695. break;
  3696. if (before(end_seq, TCP_SKB_CB(skb1)->end_seq)) {
  3697. tcp_dsack_extend(sk, TCP_SKB_CB(skb1)->seq,
  3698. end_seq);
  3699. break;
  3700. }
  3701. __skb_unlink(skb1, &tp->out_of_order_queue);
  3702. tcp_dsack_extend(sk, TCP_SKB_CB(skb1)->seq,
  3703. TCP_SKB_CB(skb1)->end_seq);
  3704. NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPOFOMERGE);
  3705. __kfree_skb(skb1);
  3706. }
  3707. add_sack:
  3708. if (tcp_is_sack(tp))
  3709. tcp_sack_new_ofo_skb(sk, seq, end_seq);
  3710. end:
  3711. if (skb) {
  3712. tcp_grow_window(sk, skb);
  3713. skb_set_owner_r(skb, sk);
  3714. }
  3715. }
  3716. static int __must_check tcp_queue_rcv(struct sock *sk, struct sk_buff *skb, int hdrlen,
  3717. bool *fragstolen)
  3718. {
  3719. int eaten;
  3720. struct sk_buff *tail = skb_peek_tail(&sk->sk_receive_queue);
  3721. __skb_pull(skb, hdrlen);
  3722. eaten = (tail &&
  3723. tcp_try_coalesce(sk, tail, skb, fragstolen)) ? 1 : 0;
  3724. tcp_sk(sk)->rcv_nxt = TCP_SKB_CB(skb)->end_seq;
  3725. if (!eaten) {
  3726. __skb_queue_tail(&sk->sk_receive_queue, skb);
  3727. skb_set_owner_r(skb, sk);
  3728. }
  3729. return eaten;
  3730. }
  3731. int tcp_send_rcvq(struct sock *sk, struct msghdr *msg, size_t size)
  3732. {
  3733. struct sk_buff *skb = NULL;
  3734. struct tcphdr *th;
  3735. bool fragstolen;
  3736. if (size == 0)
  3737. return 0;
  3738. skb = alloc_skb(size + sizeof(*th), sk->sk_allocation);
  3739. if (!skb)
  3740. goto err;
  3741. if (tcp_try_rmem_schedule(sk, skb, size + sizeof(*th)))
  3742. goto err_free;
  3743. th = (struct tcphdr *)skb_put(skb, sizeof(*th));
  3744. skb_reset_transport_header(skb);
  3745. memset(th, 0, sizeof(*th));
  3746. if (memcpy_fromiovec(skb_put(skb, size), msg->msg_iov, size))
  3747. goto err_free;
  3748. TCP_SKB_CB(skb)->seq = tcp_sk(sk)->rcv_nxt;
  3749. TCP_SKB_CB(skb)->end_seq = TCP_SKB_CB(skb)->seq + size;
  3750. TCP_SKB_CB(skb)->ack_seq = tcp_sk(sk)->snd_una - 1;
  3751. if (tcp_queue_rcv(sk, skb, sizeof(*th), &fragstolen)) {
  3752. WARN_ON_ONCE(fragstolen); /* should not happen */
  3753. __kfree_skb(skb);
  3754. }
  3755. return size;
  3756. err_free:
  3757. kfree_skb(skb);
  3758. err:
  3759. return -ENOMEM;
  3760. }
  3761. static void tcp_data_queue(struct sock *sk, struct sk_buff *skb)
  3762. {
  3763. const struct tcphdr *th = tcp_hdr(skb);
  3764. struct tcp_sock *tp = tcp_sk(sk);
  3765. int eaten = -1;
  3766. bool fragstolen = false;
  3767. if (TCP_SKB_CB(skb)->seq == TCP_SKB_CB(skb)->end_seq)
  3768. goto drop;
  3769. skb_dst_drop(skb);
  3770. __skb_pull(skb, th->doff * 4);
  3771. TCP_ECN_accept_cwr(tp, skb);
  3772. tp->rx_opt.dsack = 0;
  3773. /* Queue data for delivery to the user.
  3774. * Packets in sequence go to the receive queue.
  3775. * Out of sequence packets to the out_of_order_queue.
  3776. */
  3777. if (TCP_SKB_CB(skb)->seq == tp->rcv_nxt) {
  3778. if (tcp_receive_window(tp) == 0)
  3779. goto out_of_window;
  3780. /* Ok. In sequence. In window. */
  3781. if (tp->ucopy.task == current &&
  3782. tp->copied_seq == tp->rcv_nxt && tp->ucopy.len &&
  3783. sock_owned_by_user(sk) && !tp->urg_data) {
  3784. int chunk = min_t(unsigned int, skb->len,
  3785. tp->ucopy.len);
  3786. __set_current_state(TASK_RUNNING);
  3787. local_bh_enable();
  3788. if (!skb_copy_datagram_iovec(skb, 0, tp->ucopy.iov, chunk)) {
  3789. tp->ucopy.len -= chunk;
  3790. tp->copied_seq += chunk;
  3791. eaten = (chunk == skb->len);
  3792. tcp_rcv_space_adjust(sk);
  3793. }
  3794. local_bh_disable();
  3795. }
  3796. if (eaten <= 0) {
  3797. queue_and_out:
  3798. if (eaten < 0 &&
  3799. tcp_try_rmem_schedule(sk, skb, skb->truesize))
  3800. goto drop;
  3801. eaten = tcp_queue_rcv(sk, skb, 0, &fragstolen);
  3802. }
  3803. tp->rcv_nxt = TCP_SKB_CB(skb)->end_seq;
  3804. if (skb->len)
  3805. tcp_event_data_recv(sk, skb);
  3806. if (th->fin)
  3807. tcp_fin(sk);
  3808. if (!skb_queue_empty(&tp->out_of_order_queue)) {
  3809. tcp_ofo_queue(sk);
  3810. /* RFC2581. 4.2. SHOULD send immediate ACK, when
  3811. * gap in queue is filled.
  3812. */
  3813. if (skb_queue_empty(&tp->out_of_order_queue))
  3814. inet_csk(sk)->icsk_ack.pingpong = 0;
  3815. }
  3816. if (tp->rx_opt.num_sacks)
  3817. tcp_sack_remove(tp);
  3818. tcp_fast_path_check(sk);
  3819. if (eaten > 0)
  3820. kfree_skb_partial(skb, fragstolen);
  3821. if (!sock_flag(sk, SOCK_DEAD))
  3822. sk->sk_data_ready(sk);
  3823. return;
  3824. }
  3825. if (!after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt)) {
  3826. /* A retransmit, 2nd most common case. Force an immediate ack. */
  3827. NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_DELAYEDACKLOST);
  3828. tcp_dsack_set(sk, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq);
  3829. out_of_window:
  3830. tcp_enter_quickack_mode(sk);
  3831. inet_csk_schedule_ack(sk);
  3832. drop:
  3833. __kfree_skb(skb);
  3834. return;
  3835. }
  3836. /* Out of window. F.e. zero window probe. */
  3837. if (!before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt + tcp_receive_window(tp)))
  3838. goto out_of_window;
  3839. tcp_enter_quickack_mode(sk);
  3840. if (before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) {
  3841. /* Partial packet, seq < rcv_next < end_seq */
  3842. SOCK_DEBUG(sk, "partial packet: rcv_next %X seq %X - %X\n",
  3843. tp->rcv_nxt, TCP_SKB_CB(skb)->seq,
  3844. TCP_SKB_CB(skb)->end_seq);
  3845. tcp_dsack_set(sk, TCP_SKB_CB(skb)->seq, tp->rcv_nxt);
  3846. /* If window is closed, drop tail of packet. But after
  3847. * remembering D-SACK for its head made in previous line.
  3848. */
  3849. if (!tcp_receive_window(tp))
  3850. goto out_of_window;
  3851. goto queue_and_out;
  3852. }
  3853. tcp_data_queue_ofo(sk, skb);
  3854. }
  3855. static struct sk_buff *tcp_collapse_one(struct sock *sk, struct sk_buff *skb,
  3856. struct sk_buff_head *list)
  3857. {
  3858. struct sk_buff *next = NULL;
  3859. if (!skb_queue_is_last(list, skb))
  3860. next = skb_queue_next(list, skb);
  3861. __skb_unlink(skb, list);
  3862. __kfree_skb(skb);
  3863. NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPRCVCOLLAPSED);
  3864. return next;
  3865. }
  3866. /* Collapse contiguous sequence of skbs head..tail with
  3867. * sequence numbers start..end.
  3868. *
  3869. * If tail is NULL, this means until the end of the list.
  3870. *
  3871. * Segments with FIN/SYN are not collapsed (only because this
  3872. * simplifies code)
  3873. */
  3874. static void
  3875. tcp_collapse(struct sock *sk, struct sk_buff_head *list,
  3876. struct sk_buff *head, struct sk_buff *tail,
  3877. u32 start, u32 end)
  3878. {
  3879. struct sk_buff *skb, *n;
  3880. bool end_of_skbs;
  3881. /* First, check that queue is collapsible and find
  3882. * the point where collapsing can be useful. */
  3883. skb = head;
  3884. restart:
  3885. end_of_skbs = true;
  3886. skb_queue_walk_from_safe(list, skb, n) {
  3887. if (skb == tail)
  3888. break;
  3889. /* No new bits? It is possible on ofo queue. */
  3890. if (!before(start, TCP_SKB_CB(skb)->end_seq)) {
  3891. skb = tcp_collapse_one(sk, skb, list);
  3892. if (!skb)
  3893. break;
  3894. goto restart;
  3895. }
  3896. /* The first skb to collapse is:
  3897. * - not SYN/FIN and
  3898. * - bloated or contains data before "start" or
  3899. * overlaps to the next one.
  3900. */
  3901. if (!tcp_hdr(skb)->syn && !tcp_hdr(skb)->fin &&
  3902. (tcp_win_from_space(skb->truesize) > skb->len ||
  3903. before(TCP_SKB_CB(skb)->seq, start))) {
  3904. end_of_skbs = false;
  3905. break;
  3906. }
  3907. if (!skb_queue_is_last(list, skb)) {
  3908. struct sk_buff *next = skb_queue_next(list, skb);
  3909. if (next != tail &&
  3910. TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(next)->seq) {
  3911. end_of_skbs = false;
  3912. break;
  3913. }
  3914. }
  3915. /* Decided to skip this, advance start seq. */
  3916. start = TCP_SKB_CB(skb)->end_seq;
  3917. }
  3918. if (end_of_skbs || tcp_hdr(skb)->syn || tcp_hdr(skb)->fin)
  3919. return;
  3920. while (before(start, end)) {
  3921. struct sk_buff *nskb;
  3922. unsigned int header = skb_headroom(skb);
  3923. int copy = SKB_MAX_ORDER(header, 0);
  3924. /* Too big header? This can happen with IPv6. */
  3925. if (copy < 0)
  3926. return;
  3927. if (end - start < copy)
  3928. copy = end - start;
  3929. nskb = alloc_skb(copy + header, GFP_ATOMIC);
  3930. if (!nskb)
  3931. return;
  3932. skb_set_mac_header(nskb, skb_mac_header(skb) - skb->head);
  3933. skb_set_network_header(nskb, (skb_network_header(skb) -
  3934. skb->head));
  3935. skb_set_transport_header(nskb, (skb_transport_header(skb) -
  3936. skb->head));
  3937. skb_reserve(nskb, header);
  3938. memcpy(nskb->head, skb->head, header);
  3939. memcpy(nskb->cb, skb->cb, sizeof(skb->cb));
  3940. TCP_SKB_CB(nskb)->seq = TCP_SKB_CB(nskb)->end_seq = start;
  3941. __skb_queue_before(list, skb, nskb);
  3942. skb_set_owner_r(nskb, sk);
  3943. /* Copy data, releasing collapsed skbs. */
  3944. while (copy > 0) {
  3945. int offset = start - TCP_SKB_CB(skb)->seq;
  3946. int size = TCP_SKB_CB(skb)->end_seq - start;
  3947. BUG_ON(offset < 0);
  3948. if (size > 0) {
  3949. size = min(copy, size);
  3950. if (skb_copy_bits(skb, offset, skb_put(nskb, size), size))
  3951. BUG();
  3952. TCP_SKB_CB(nskb)->end_seq += size;
  3953. copy -= size;
  3954. start += size;
  3955. }
  3956. if (!before(start, TCP_SKB_CB(skb)->end_seq)) {
  3957. skb = tcp_collapse_one(sk, skb, list);
  3958. if (!skb ||
  3959. skb == tail ||
  3960. tcp_hdr(skb)->syn ||
  3961. tcp_hdr(skb)->fin)
  3962. return;
  3963. }
  3964. }
  3965. }
  3966. }
  3967. /* Collapse ofo queue. Algorithm: select contiguous sequence of skbs
  3968. * and tcp_collapse() them until all the queue is collapsed.
  3969. */
  3970. static void tcp_collapse_ofo_queue(struct sock *sk)
  3971. {
  3972. struct tcp_sock *tp = tcp_sk(sk);
  3973. struct sk_buff *skb = skb_peek(&tp->out_of_order_queue);
  3974. struct sk_buff *head;
  3975. u32 start, end;
  3976. if (skb == NULL)
  3977. return;
  3978. start = TCP_SKB_CB(skb)->seq;
  3979. end = TCP_SKB_CB(skb)->end_seq;
  3980. head = skb;
  3981. for (;;) {
  3982. struct sk_buff *next = NULL;
  3983. if (!skb_queue_is_last(&tp->out_of_order_queue, skb))
  3984. next = skb_queue_next(&tp->out_of_order_queue, skb);
  3985. skb = next;
  3986. /* Segment is terminated when we see gap or when
  3987. * we are at the end of all the queue. */
  3988. if (!skb ||
  3989. after(TCP_SKB_CB(skb)->seq, end) ||
  3990. before(TCP_SKB_CB(skb)->end_seq, start)) {
  3991. tcp_collapse(sk, &tp->out_of_order_queue,
  3992. head, skb, start, end);
  3993. head = skb;
  3994. if (!skb)
  3995. break;
  3996. /* Start new segment */
  3997. start = TCP_SKB_CB(skb)->seq;
  3998. end = TCP_SKB_CB(skb)->end_seq;
  3999. } else {
  4000. if (before(TCP_SKB_CB(skb)->seq, start))
  4001. start = TCP_SKB_CB(skb)->seq;
  4002. if (after(TCP_SKB_CB(skb)->end_seq, end))
  4003. end = TCP_SKB_CB(skb)->end_seq;
  4004. }
  4005. }
  4006. }
  4007. /*
  4008. * Purge the out-of-order queue.
  4009. * Return true if queue was pruned.
  4010. */
  4011. static bool tcp_prune_ofo_queue(struct sock *sk)
  4012. {
  4013. struct tcp_sock *tp = tcp_sk(sk);
  4014. bool res = false;
  4015. if (!skb_queue_empty(&tp->out_of_order_queue)) {
  4016. NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_OFOPRUNED);
  4017. __skb_queue_purge(&tp->out_of_order_queue);
  4018. /* Reset SACK state. A conforming SACK implementation will
  4019. * do the same at a timeout based retransmit. When a connection
  4020. * is in a sad state like this, we care only about integrity
  4021. * of the connection not performance.
  4022. */
  4023. if (tp->rx_opt.sack_ok)
  4024. tcp_sack_reset(&tp->rx_opt);
  4025. sk_mem_reclaim(sk);
  4026. res = true;
  4027. }
  4028. return res;
  4029. }
  4030. /* Reduce allocated memory if we can, trying to get
  4031. * the socket within its memory limits again.
  4032. *
  4033. * Return less than zero if we should start dropping frames
  4034. * until the socket owning process reads some of the data
  4035. * to stabilize the situation.
  4036. */
  4037. static int tcp_prune_queue(struct sock *sk)
  4038. {
  4039. struct tcp_sock *tp = tcp_sk(sk);
  4040. SOCK_DEBUG(sk, "prune_queue: c=%x\n", tp->copied_seq);
  4041. NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_PRUNECALLED);
  4042. if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf)
  4043. tcp_clamp_window(sk);
  4044. else if (sk_under_memory_pressure(sk))
  4045. tp->rcv_ssthresh = min(tp->rcv_ssthresh, 4U * tp->advmss);
  4046. tcp_collapse_ofo_queue(sk);
  4047. if (!skb_queue_empty(&sk->sk_receive_queue))
  4048. tcp_collapse(sk, &sk->sk_receive_queue,
  4049. skb_peek(&sk->sk_receive_queue),
  4050. NULL,
  4051. tp->copied_seq, tp->rcv_nxt);
  4052. sk_mem_reclaim(sk);
  4053. if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf)
  4054. return 0;
  4055. /* Collapsing did not help, destructive actions follow.
  4056. * This must not ever occur. */
  4057. tcp_prune_ofo_queue(sk);
  4058. if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf)
  4059. return 0;
  4060. /* If we are really being abused, tell the caller to silently
  4061. * drop receive data on the floor. It will get retransmitted
  4062. * and hopefully then we'll have sufficient space.
  4063. */
  4064. NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_RCVPRUNED);
  4065. /* Massive buffer overcommit. */
  4066. tp->pred_flags = 0;
  4067. return -1;
  4068. }
  4069. static bool tcp_should_expand_sndbuf(const struct sock *sk)
  4070. {
  4071. const struct tcp_sock *tp = tcp_sk(sk);
  4072. /* If the user specified a specific send buffer setting, do
  4073. * not modify it.
  4074. */
  4075. if (sk->sk_userlocks & SOCK_SNDBUF_LOCK)
  4076. return false;
  4077. /* If we are under global TCP memory pressure, do not expand. */
  4078. if (sk_under_memory_pressure(sk))
  4079. return false;
  4080. /* If we are under soft global TCP memory pressure, do not expand. */
  4081. if (sk_memory_allocated(sk) >= sk_prot_mem_limits(sk, 0))
  4082. return false;
  4083. /* If we filled the congestion window, do not expand. */
  4084. if (tp->packets_out >= tp->snd_cwnd)
  4085. return false;
  4086. return true;
  4087. }
  4088. /* When incoming ACK allowed to free some skb from write_queue,
  4089. * we remember this event in flag SOCK_QUEUE_SHRUNK and wake up socket
  4090. * on the exit from tcp input handler.
  4091. *
  4092. * PROBLEM: sndbuf expansion does not work well with largesend.
  4093. */
  4094. static void tcp_new_space(struct sock *sk)
  4095. {
  4096. struct tcp_sock *tp = tcp_sk(sk);
  4097. if (tcp_should_expand_sndbuf(sk)) {
  4098. tcp_sndbuf_expand(sk);
  4099. tp->snd_cwnd_stamp = tcp_time_stamp;
  4100. }
  4101. sk->sk_write_space(sk);
  4102. }
  4103. static void tcp_check_space(struct sock *sk)
  4104. {
  4105. if (sock_flag(sk, SOCK_QUEUE_SHRUNK)) {
  4106. sock_reset_flag(sk, SOCK_QUEUE_SHRUNK);
  4107. if (sk->sk_socket &&
  4108. test_bit(SOCK_NOSPACE, &sk->sk_socket->flags))
  4109. tcp_new_space(sk);
  4110. }
  4111. }
  4112. static inline void tcp_data_snd_check(struct sock *sk)
  4113. {
  4114. tcp_push_pending_frames(sk);
  4115. tcp_check_space(sk);
  4116. }
  4117. /*
  4118. * Check if sending an ack is needed.
  4119. */
  4120. static void __tcp_ack_snd_check(struct sock *sk, int ofo_possible)
  4121. {
  4122. struct tcp_sock *tp = tcp_sk(sk);
  4123. /* More than one full frame received... */
  4124. if (((tp->rcv_nxt - tp->rcv_wup) > inet_csk(sk)->icsk_ack.rcv_mss &&
  4125. /* ... and right edge of window advances far enough.
  4126. * (tcp_recvmsg() will send ACK otherwise). Or...
  4127. */
  4128. __tcp_select_window(sk) >= tp->rcv_wnd) ||
  4129. /* We ACK each frame or... */
  4130. tcp_in_quickack_mode(sk) ||
  4131. /* We have out of order data. */
  4132. (ofo_possible && skb_peek(&tp->out_of_order_queue))) {
  4133. /* Then ack it now */
  4134. tcp_send_ack(sk);
  4135. } else {
  4136. /* Else, send delayed ack. */
  4137. tcp_send_delayed_ack(sk);
  4138. }
  4139. }
  4140. static inline void tcp_ack_snd_check(struct sock *sk)
  4141. {
  4142. if (!inet_csk_ack_scheduled(sk)) {
  4143. /* We sent a data segment already. */
  4144. return;
  4145. }
  4146. __tcp_ack_snd_check(sk, 1);
  4147. }
  4148. /*
  4149. * This routine is only called when we have urgent data
  4150. * signaled. Its the 'slow' part of tcp_urg. It could be
  4151. * moved inline now as tcp_urg is only called from one
  4152. * place. We handle URGent data wrong. We have to - as
  4153. * BSD still doesn't use the correction from RFC961.
  4154. * For 1003.1g we should support a new option TCP_STDURG to permit
  4155. * either form (or just set the sysctl tcp_stdurg).
  4156. */
  4157. static void tcp_check_urg(struct sock *sk, const struct tcphdr *th)
  4158. {
  4159. struct tcp_sock *tp = tcp_sk(sk);
  4160. u32 ptr = ntohs(th->urg_ptr);
  4161. if (ptr && !sysctl_tcp_stdurg)
  4162. ptr--;
  4163. ptr += ntohl(th->seq);
  4164. /* Ignore urgent data that we've already seen and read. */
  4165. if (after(tp->copied_seq, ptr))
  4166. return;
  4167. /* Do not replay urg ptr.
  4168. *
  4169. * NOTE: interesting situation not covered by specs.
  4170. * Misbehaving sender may send urg ptr, pointing to segment,
  4171. * which we already have in ofo queue. We are not able to fetch
  4172. * such data and will stay in TCP_URG_NOTYET until will be eaten
  4173. * by recvmsg(). Seems, we are not obliged to handle such wicked
  4174. * situations. But it is worth to think about possibility of some
  4175. * DoSes using some hypothetical application level deadlock.
  4176. */
  4177. if (before(ptr, tp->rcv_nxt))
  4178. return;
  4179. /* Do we already have a newer (or duplicate) urgent pointer? */
  4180. if (tp->urg_data && !after(ptr, tp->urg_seq))
  4181. return;
  4182. /* Tell the world about our new urgent pointer. */
  4183. sk_send_sigurg(sk);
  4184. /* We may be adding urgent data when the last byte read was
  4185. * urgent. To do this requires some care. We cannot just ignore
  4186. * tp->copied_seq since we would read the last urgent byte again
  4187. * as data, nor can we alter copied_seq until this data arrives
  4188. * or we break the semantics of SIOCATMARK (and thus sockatmark())
  4189. *
  4190. * NOTE. Double Dutch. Rendering to plain English: author of comment
  4191. * above did something sort of send("A", MSG_OOB); send("B", MSG_OOB);
  4192. * and expect that both A and B disappear from stream. This is _wrong_.
  4193. * Though this happens in BSD with high probability, this is occasional.
  4194. * Any application relying on this is buggy. Note also, that fix "works"
  4195. * only in this artificial test. Insert some normal data between A and B and we will
  4196. * decline of BSD again. Verdict: it is better to remove to trap
  4197. * buggy users.
  4198. */
  4199. if (tp->urg_seq == tp->copied_seq && tp->urg_data &&
  4200. !sock_flag(sk, SOCK_URGINLINE) && tp->copied_seq != tp->rcv_nxt) {
  4201. struct sk_buff *skb = skb_peek(&sk->sk_receive_queue);
  4202. tp->copied_seq++;
  4203. if (skb && !before(tp->copied_seq, TCP_SKB_CB(skb)->end_seq)) {
  4204. __skb_unlink(skb, &sk->sk_receive_queue);
  4205. __kfree_skb(skb);
  4206. }
  4207. }
  4208. tp->urg_data = TCP_URG_NOTYET;
  4209. tp->urg_seq = ptr;
  4210. /* Disable header prediction. */
  4211. tp->pred_flags = 0;
  4212. }
  4213. /* This is the 'fast' part of urgent handling. */
  4214. static void tcp_urg(struct sock *sk, struct sk_buff *skb, const struct tcphdr *th)
  4215. {
  4216. struct tcp_sock *tp = tcp_sk(sk);
  4217. /* Check if we get a new urgent pointer - normally not. */
  4218. if (th->urg)
  4219. tcp_check_urg(sk, th);
  4220. /* Do we wait for any urgent data? - normally not... */
  4221. if (tp->urg_data == TCP_URG_NOTYET) {
  4222. u32 ptr = tp->urg_seq - ntohl(th->seq) + (th->doff * 4) -
  4223. th->syn;
  4224. /* Is the urgent pointer pointing into this packet? */
  4225. if (ptr < skb->len) {
  4226. u8 tmp;
  4227. if (skb_copy_bits(skb, ptr, &tmp, 1))
  4228. BUG();
  4229. tp->urg_data = TCP_URG_VALID | tmp;
  4230. if (!sock_flag(sk, SOCK_DEAD))
  4231. sk->sk_data_ready(sk);
  4232. }
  4233. }
  4234. }
  4235. static int tcp_copy_to_iovec(struct sock *sk, struct sk_buff *skb, int hlen)
  4236. {
  4237. struct tcp_sock *tp = tcp_sk(sk);
  4238. int chunk = skb->len - hlen;
  4239. int err;
  4240. local_bh_enable();
  4241. if (skb_csum_unnecessary(skb))
  4242. err = skb_copy_datagram_iovec(skb, hlen, tp->ucopy.iov, chunk);
  4243. else
  4244. err = skb_copy_and_csum_datagram_iovec(skb, hlen,
  4245. tp->ucopy.iov);
  4246. if (!err) {
  4247. tp->ucopy.len -= chunk;
  4248. tp->copied_seq += chunk;
  4249. tcp_rcv_space_adjust(sk);
  4250. }
  4251. local_bh_disable();
  4252. return err;
  4253. }
  4254. static __sum16 __tcp_checksum_complete_user(struct sock *sk,
  4255. struct sk_buff *skb)
  4256. {
  4257. __sum16 result;
  4258. if (sock_owned_by_user(sk)) {
  4259. local_bh_enable();
  4260. result = __tcp_checksum_complete(skb);
  4261. local_bh_disable();
  4262. } else {
  4263. result = __tcp_checksum_complete(skb);
  4264. }
  4265. return result;
  4266. }
  4267. static inline bool tcp_checksum_complete_user(struct sock *sk,
  4268. struct sk_buff *skb)
  4269. {
  4270. return !skb_csum_unnecessary(skb) &&
  4271. __tcp_checksum_complete_user(sk, skb);
  4272. }
  4273. #ifdef CONFIG_NET_DMA
  4274. static bool tcp_dma_try_early_copy(struct sock *sk, struct sk_buff *skb,
  4275. int hlen)
  4276. {
  4277. struct tcp_sock *tp = tcp_sk(sk);
  4278. int chunk = skb->len - hlen;
  4279. int dma_cookie;
  4280. bool copied_early = false;
  4281. if (tp->ucopy.wakeup)
  4282. return false;
  4283. if (!tp->ucopy.dma_chan && tp->ucopy.pinned_list)
  4284. tp->ucopy.dma_chan = net_dma_find_channel();
  4285. if (tp->ucopy.dma_chan && skb_csum_unnecessary(skb)) {
  4286. dma_cookie = dma_skb_copy_datagram_iovec(tp->ucopy.dma_chan,
  4287. skb, hlen,
  4288. tp->ucopy.iov, chunk,
  4289. tp->ucopy.pinned_list);
  4290. if (dma_cookie < 0)
  4291. goto out;
  4292. tp->ucopy.dma_cookie = dma_cookie;
  4293. copied_early = true;
  4294. tp->ucopy.len -= chunk;
  4295. tp->copied_seq += chunk;
  4296. tcp_rcv_space_adjust(sk);
  4297. if ((tp->ucopy.len == 0) ||
  4298. (tcp_flag_word(tcp_hdr(skb)) & TCP_FLAG_PSH) ||
  4299. (atomic_read(&sk->sk_rmem_alloc) > (sk->sk_rcvbuf >> 1))) {
  4300. tp->ucopy.wakeup = 1;
  4301. sk->sk_data_ready(sk);
  4302. }
  4303. } else if (chunk > 0) {
  4304. tp->ucopy.wakeup = 1;
  4305. sk->sk_data_ready(sk);
  4306. }
  4307. out:
  4308. return copied_early;
  4309. }
  4310. #endif /* CONFIG_NET_DMA */
  4311. /* Does PAWS and seqno based validation of an incoming segment, flags will
  4312. * play significant role here.
  4313. */
  4314. static bool tcp_validate_incoming(struct sock *sk, struct sk_buff *skb,
  4315. const struct tcphdr *th, int syn_inerr)
  4316. {
  4317. struct tcp_sock *tp = tcp_sk(sk);
  4318. /* RFC1323: H1. Apply PAWS check first. */
  4319. if (tcp_fast_parse_options(skb, th, tp) && tp->rx_opt.saw_tstamp &&
  4320. tcp_paws_discard(sk, skb)) {
  4321. if (!th->rst) {
  4322. NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_PAWSESTABREJECTED);
  4323. tcp_send_dupack(sk, skb);
  4324. goto discard;
  4325. }
  4326. /* Reset is accepted even if it did not pass PAWS. */
  4327. }
  4328. /* Step 1: check sequence number */
  4329. if (!tcp_sequence(tp, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq)) {
  4330. /* RFC793, page 37: "In all states except SYN-SENT, all reset
  4331. * (RST) segments are validated by checking their SEQ-fields."
  4332. * And page 69: "If an incoming segment is not acceptable,
  4333. * an acknowledgment should be sent in reply (unless the RST
  4334. * bit is set, if so drop the segment and return)".
  4335. */
  4336. if (!th->rst) {
  4337. if (th->syn)
  4338. goto syn_challenge;
  4339. tcp_send_dupack(sk, skb);
  4340. }
  4341. goto discard;
  4342. }
  4343. /* Step 2: check RST bit */
  4344. if (th->rst) {
  4345. /* RFC 5961 3.2 :
  4346. * If sequence number exactly matches RCV.NXT, then
  4347. * RESET the connection
  4348. * else
  4349. * Send a challenge ACK
  4350. */
  4351. if (TCP_SKB_CB(skb)->seq == tp->rcv_nxt)
  4352. tcp_reset(sk);
  4353. else
  4354. tcp_send_challenge_ack(sk);
  4355. goto discard;
  4356. }
  4357. /* step 3: check security and precedence [ignored] */
  4358. /* step 4: Check for a SYN
  4359. * RFC 5691 4.2 : Send a challenge ack
  4360. */
  4361. if (th->syn) {
  4362. syn_challenge:
  4363. if (syn_inerr)
  4364. TCP_INC_STATS_BH(sock_net(sk), TCP_MIB_INERRS);
  4365. NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPSYNCHALLENGE);
  4366. tcp_send_challenge_ack(sk);
  4367. goto discard;
  4368. }
  4369. return true;
  4370. discard:
  4371. __kfree_skb(skb);
  4372. return false;
  4373. }
  4374. /*
  4375. * TCP receive function for the ESTABLISHED state.
  4376. *
  4377. * It is split into a fast path and a slow path. The fast path is
  4378. * disabled when:
  4379. * - A zero window was announced from us - zero window probing
  4380. * is only handled properly in the slow path.
  4381. * - Out of order segments arrived.
  4382. * - Urgent data is expected.
  4383. * - There is no buffer space left
  4384. * - Unexpected TCP flags/window values/header lengths are received
  4385. * (detected by checking the TCP header against pred_flags)
  4386. * - Data is sent in both directions. Fast path only supports pure senders
  4387. * or pure receivers (this means either the sequence number or the ack
  4388. * value must stay constant)
  4389. * - Unexpected TCP option.
  4390. *
  4391. * When these conditions are not satisfied it drops into a standard
  4392. * receive procedure patterned after RFC793 to handle all cases.
  4393. * The first three cases are guaranteed by proper pred_flags setting,
  4394. * the rest is checked inline. Fast processing is turned on in
  4395. * tcp_data_queue when everything is OK.
  4396. */
  4397. void tcp_rcv_established(struct sock *sk, struct sk_buff *skb,
  4398. const struct tcphdr *th, unsigned int len)
  4399. {
  4400. struct tcp_sock *tp = tcp_sk(sk);
  4401. if (unlikely(sk->sk_rx_dst == NULL))
  4402. inet_csk(sk)->icsk_af_ops->sk_rx_dst_set(sk, skb);
  4403. /*
  4404. * Header prediction.
  4405. * The code loosely follows the one in the famous
  4406. * "30 instruction TCP receive" Van Jacobson mail.
  4407. *
  4408. * Van's trick is to deposit buffers into socket queue
  4409. * on a device interrupt, to call tcp_recv function
  4410. * on the receive process context and checksum and copy
  4411. * the buffer to user space. smart...
  4412. *
  4413. * Our current scheme is not silly either but we take the
  4414. * extra cost of the net_bh soft interrupt processing...
  4415. * We do checksum and copy also but from device to kernel.
  4416. */
  4417. tp->rx_opt.saw_tstamp = 0;
  4418. /* pred_flags is 0xS?10 << 16 + snd_wnd
  4419. * if header_prediction is to be made
  4420. * 'S' will always be tp->tcp_header_len >> 2
  4421. * '?' will be 0 for the fast path, otherwise pred_flags is 0 to
  4422. * turn it off (when there are holes in the receive
  4423. * space for instance)
  4424. * PSH flag is ignored.
  4425. */
  4426. if ((tcp_flag_word(th) & TCP_HP_BITS) == tp->pred_flags &&
  4427. TCP_SKB_CB(skb)->seq == tp->rcv_nxt &&
  4428. !after(TCP_SKB_CB(skb)->ack_seq, tp->snd_nxt)) {
  4429. int tcp_header_len = tp->tcp_header_len;
  4430. /* Timestamp header prediction: tcp_header_len
  4431. * is automatically equal to th->doff*4 due to pred_flags
  4432. * match.
  4433. */
  4434. /* Check timestamp */
  4435. if (tcp_header_len == sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED) {
  4436. /* No? Slow path! */
  4437. if (!tcp_parse_aligned_timestamp(tp, th))
  4438. goto slow_path;
  4439. /* If PAWS failed, check it more carefully in slow path */
  4440. if ((s32)(tp->rx_opt.rcv_tsval - tp->rx_opt.ts_recent) < 0)
  4441. goto slow_path;
  4442. /* DO NOT update ts_recent here, if checksum fails
  4443. * and timestamp was corrupted part, it will result
  4444. * in a hung connection since we will drop all
  4445. * future packets due to the PAWS test.
  4446. */
  4447. }
  4448. if (len <= tcp_header_len) {
  4449. /* Bulk data transfer: sender */
  4450. if (len == tcp_header_len) {
  4451. /* Predicted packet is in window by definition.
  4452. * seq == rcv_nxt and rcv_wup <= rcv_nxt.
  4453. * Hence, check seq<=rcv_wup reduces to:
  4454. */
  4455. if (tcp_header_len ==
  4456. (sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED) &&
  4457. tp->rcv_nxt == tp->rcv_wup)
  4458. tcp_store_ts_recent(tp);
  4459. /* We know that such packets are checksummed
  4460. * on entry.
  4461. */
  4462. tcp_ack(sk, skb, 0);
  4463. __kfree_skb(skb);
  4464. tcp_data_snd_check(sk);
  4465. return;
  4466. } else { /* Header too small */
  4467. TCP_INC_STATS_BH(sock_net(sk), TCP_MIB_INERRS);
  4468. goto discard;
  4469. }
  4470. } else {
  4471. int eaten = 0;
  4472. int copied_early = 0;
  4473. bool fragstolen = false;
  4474. if (tp->copied_seq == tp->rcv_nxt &&
  4475. len - tcp_header_len <= tp->ucopy.len) {
  4476. #ifdef CONFIG_NET_DMA
  4477. if (tp->ucopy.task == current &&
  4478. sock_owned_by_user(sk) &&
  4479. tcp_dma_try_early_copy(sk, skb, tcp_header_len)) {
  4480. copied_early = 1;
  4481. eaten = 1;
  4482. }
  4483. #endif
  4484. if (tp->ucopy.task == current &&
  4485. sock_owned_by_user(sk) && !copied_early) {
  4486. __set_current_state(TASK_RUNNING);
  4487. if (!tcp_copy_to_iovec(sk, skb, tcp_header_len))
  4488. eaten = 1;
  4489. }
  4490. if (eaten) {
  4491. /* Predicted packet is in window by definition.
  4492. * seq == rcv_nxt and rcv_wup <= rcv_nxt.
  4493. * Hence, check seq<=rcv_wup reduces to:
  4494. */
  4495. if (tcp_header_len ==
  4496. (sizeof(struct tcphdr) +
  4497. TCPOLEN_TSTAMP_ALIGNED) &&
  4498. tp->rcv_nxt == tp->rcv_wup)
  4499. tcp_store_ts_recent(tp);
  4500. tcp_rcv_rtt_measure_ts(sk, skb);
  4501. __skb_pull(skb, tcp_header_len);
  4502. tp->rcv_nxt = TCP_SKB_CB(skb)->end_seq;
  4503. NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPHPHITSTOUSER);
  4504. }
  4505. if (copied_early)
  4506. tcp_cleanup_rbuf(sk, skb->len);
  4507. }
  4508. if (!eaten) {
  4509. if (tcp_checksum_complete_user(sk, skb))
  4510. goto csum_error;
  4511. if ((int)skb->truesize > sk->sk_forward_alloc)
  4512. goto step5;
  4513. /* Predicted packet is in window by definition.
  4514. * seq == rcv_nxt and rcv_wup <= rcv_nxt.
  4515. * Hence, check seq<=rcv_wup reduces to:
  4516. */
  4517. if (tcp_header_len ==
  4518. (sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED) &&
  4519. tp->rcv_nxt == tp->rcv_wup)
  4520. tcp_store_ts_recent(tp);
  4521. tcp_rcv_rtt_measure_ts(sk, skb);
  4522. NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPHPHITS);
  4523. /* Bulk data transfer: receiver */
  4524. eaten = tcp_queue_rcv(sk, skb, tcp_header_len,
  4525. &fragstolen);
  4526. }
  4527. tcp_event_data_recv(sk, skb);
  4528. if (TCP_SKB_CB(skb)->ack_seq != tp->snd_una) {
  4529. /* Well, only one small jumplet in fast path... */
  4530. tcp_ack(sk, skb, FLAG_DATA);
  4531. tcp_data_snd_check(sk);
  4532. if (!inet_csk_ack_scheduled(sk))
  4533. goto no_ack;
  4534. }
  4535. if (!copied_early || tp->rcv_nxt != tp->rcv_wup)
  4536. __tcp_ack_snd_check(sk, 0);
  4537. no_ack:
  4538. #ifdef CONFIG_NET_DMA
  4539. if (copied_early)
  4540. __skb_queue_tail(&sk->sk_async_wait_queue, skb);
  4541. else
  4542. #endif
  4543. if (eaten)
  4544. kfree_skb_partial(skb, fragstolen);
  4545. sk->sk_data_ready(sk);
  4546. return;
  4547. }
  4548. }
  4549. slow_path:
  4550. if (len < (th->doff << 2) || tcp_checksum_complete_user(sk, skb))
  4551. goto csum_error;
  4552. if (!th->ack && !th->rst)
  4553. goto discard;
  4554. /*
  4555. * Standard slow path.
  4556. */
  4557. if (!tcp_validate_incoming(sk, skb, th, 1))
  4558. return;
  4559. step5:
  4560. if (tcp_ack(sk, skb, FLAG_SLOWPATH | FLAG_UPDATE_TS_RECENT) < 0)
  4561. goto discard;
  4562. tcp_rcv_rtt_measure_ts(sk, skb);
  4563. /* Process urgent data. */
  4564. tcp_urg(sk, skb, th);
  4565. /* step 7: process the segment text */
  4566. tcp_data_queue(sk, skb);
  4567. tcp_data_snd_check(sk);
  4568. tcp_ack_snd_check(sk);
  4569. return;
  4570. csum_error:
  4571. TCP_INC_STATS_BH(sock_net(sk), TCP_MIB_CSUMERRORS);
  4572. TCP_INC_STATS_BH(sock_net(sk), TCP_MIB_INERRS);
  4573. discard:
  4574. __kfree_skb(skb);
  4575. }
  4576. EXPORT_SYMBOL(tcp_rcv_established);
  4577. void tcp_finish_connect(struct sock *sk, struct sk_buff *skb)
  4578. {
  4579. struct tcp_sock *tp = tcp_sk(sk);
  4580. struct inet_connection_sock *icsk = inet_csk(sk);
  4581. tcp_set_state(sk, TCP_ESTABLISHED);
  4582. if (skb != NULL) {
  4583. icsk->icsk_af_ops->sk_rx_dst_set(sk, skb);
  4584. security_inet_conn_established(sk, skb);
  4585. }
  4586. /* Make sure socket is routed, for correct metrics. */
  4587. icsk->icsk_af_ops->rebuild_header(sk);
  4588. tcp_init_metrics(sk);
  4589. tcp_init_congestion_control(sk);
  4590. /* Prevent spurious tcp_cwnd_restart() on first data
  4591. * packet.
  4592. */
  4593. tp->lsndtime = tcp_time_stamp;
  4594. tcp_init_buffer_space(sk);
  4595. if (sock_flag(sk, SOCK_KEEPOPEN))
  4596. inet_csk_reset_keepalive_timer(sk, keepalive_time_when(tp));
  4597. if (!tp->rx_opt.snd_wscale)
  4598. __tcp_fast_path_on(tp, tp->snd_wnd);
  4599. else
  4600. tp->pred_flags = 0;
  4601. if (!sock_flag(sk, SOCK_DEAD)) {
  4602. sk->sk_state_change(sk);
  4603. sk_wake_async(sk, SOCK_WAKE_IO, POLL_OUT);
  4604. }
  4605. }
  4606. static bool tcp_rcv_fastopen_synack(struct sock *sk, struct sk_buff *synack,
  4607. struct tcp_fastopen_cookie *cookie)
  4608. {
  4609. struct tcp_sock *tp = tcp_sk(sk);
  4610. struct sk_buff *data = tp->syn_data ? tcp_write_queue_head(sk) : NULL;
  4611. u16 mss = tp->rx_opt.mss_clamp;
  4612. bool syn_drop;
  4613. if (mss == tp->rx_opt.user_mss) {
  4614. struct tcp_options_received opt;
  4615. /* Get original SYNACK MSS value if user MSS sets mss_clamp */
  4616. tcp_clear_options(&opt);
  4617. opt.user_mss = opt.mss_clamp = 0;
  4618. tcp_parse_options(synack, &opt, 0, NULL);
  4619. mss = opt.mss_clamp;
  4620. }
  4621. if (!tp->syn_fastopen) /* Ignore an unsolicited cookie */
  4622. cookie->len = -1;
  4623. /* The SYN-ACK neither has cookie nor acknowledges the data. Presumably
  4624. * the remote receives only the retransmitted (regular) SYNs: either
  4625. * the original SYN-data or the corresponding SYN-ACK is lost.
  4626. */
  4627. syn_drop = (cookie->len <= 0 && data && tp->total_retrans);
  4628. tcp_fastopen_cache_set(sk, mss, cookie, syn_drop);
  4629. if (data) { /* Retransmit unacked data in SYN */
  4630. tcp_for_write_queue_from(data, sk) {
  4631. if (data == tcp_send_head(sk) ||
  4632. __tcp_retransmit_skb(sk, data))
  4633. break;
  4634. }
  4635. tcp_rearm_rto(sk);
  4636. NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPFASTOPENACTIVEFAIL);
  4637. return true;
  4638. }
  4639. tp->syn_data_acked = tp->syn_data;
  4640. if (tp->syn_data_acked)
  4641. NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPFASTOPENACTIVE);
  4642. return false;
  4643. }
  4644. static int tcp_rcv_synsent_state_process(struct sock *sk, struct sk_buff *skb,
  4645. const struct tcphdr *th, unsigned int len)
  4646. {
  4647. struct inet_connection_sock *icsk = inet_csk(sk);
  4648. struct tcp_sock *tp = tcp_sk(sk);
  4649. struct tcp_fastopen_cookie foc = { .len = -1 };
  4650. int saved_clamp = tp->rx_opt.mss_clamp;
  4651. tcp_parse_options(skb, &tp->rx_opt, 0, &foc);
  4652. if (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr)
  4653. tp->rx_opt.rcv_tsecr -= tp->tsoffset;
  4654. if (th->ack) {
  4655. /* rfc793:
  4656. * "If the state is SYN-SENT then
  4657. * first check the ACK bit
  4658. * If the ACK bit is set
  4659. * If SEG.ACK =< ISS, or SEG.ACK > SND.NXT, send
  4660. * a reset (unless the RST bit is set, if so drop
  4661. * the segment and return)"
  4662. */
  4663. if (!after(TCP_SKB_CB(skb)->ack_seq, tp->snd_una) ||
  4664. after(TCP_SKB_CB(skb)->ack_seq, tp->snd_nxt))
  4665. goto reset_and_undo;
  4666. if (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr &&
  4667. !between(tp->rx_opt.rcv_tsecr, tp->retrans_stamp,
  4668. tcp_time_stamp)) {
  4669. NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_PAWSACTIVEREJECTED);
  4670. goto reset_and_undo;
  4671. }
  4672. /* Now ACK is acceptable.
  4673. *
  4674. * "If the RST bit is set
  4675. * If the ACK was acceptable then signal the user "error:
  4676. * connection reset", drop the segment, enter CLOSED state,
  4677. * delete TCB, and return."
  4678. */
  4679. if (th->rst) {
  4680. tcp_reset(sk);
  4681. goto discard;
  4682. }
  4683. /* rfc793:
  4684. * "fifth, if neither of the SYN or RST bits is set then
  4685. * drop the segment and return."
  4686. *
  4687. * See note below!
  4688. * --ANK(990513)
  4689. */
  4690. if (!th->syn)
  4691. goto discard_and_undo;
  4692. /* rfc793:
  4693. * "If the SYN bit is on ...
  4694. * are acceptable then ...
  4695. * (our SYN has been ACKed), change the connection
  4696. * state to ESTABLISHED..."
  4697. */
  4698. TCP_ECN_rcv_synack(tp, th);
  4699. tcp_init_wl(tp, TCP_SKB_CB(skb)->seq);
  4700. tcp_ack(sk, skb, FLAG_SLOWPATH);
  4701. /* Ok.. it's good. Set up sequence numbers and
  4702. * move to established.
  4703. */
  4704. tp->rcv_nxt = TCP_SKB_CB(skb)->seq + 1;
  4705. tp->rcv_wup = TCP_SKB_CB(skb)->seq + 1;
  4706. /* RFC1323: The window in SYN & SYN/ACK segments is
  4707. * never scaled.
  4708. */
  4709. tp->snd_wnd = ntohs(th->window);
  4710. if (!tp->rx_opt.wscale_ok) {
  4711. tp->rx_opt.snd_wscale = tp->rx_opt.rcv_wscale = 0;
  4712. tp->window_clamp = min(tp->window_clamp, 65535U);
  4713. }
  4714. if (tp->rx_opt.saw_tstamp) {
  4715. tp->rx_opt.tstamp_ok = 1;
  4716. tp->tcp_header_len =
  4717. sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED;
  4718. tp->advmss -= TCPOLEN_TSTAMP_ALIGNED;
  4719. tcp_store_ts_recent(tp);
  4720. } else {
  4721. tp->tcp_header_len = sizeof(struct tcphdr);
  4722. }
  4723. if (tcp_is_sack(tp) && sysctl_tcp_fack)
  4724. tcp_enable_fack(tp);
  4725. tcp_mtup_init(sk);
  4726. tcp_sync_mss(sk, icsk->icsk_pmtu_cookie);
  4727. tcp_initialize_rcv_mss(sk);
  4728. /* Remember, tcp_poll() does not lock socket!
  4729. * Change state from SYN-SENT only after copied_seq
  4730. * is initialized. */
  4731. tp->copied_seq = tp->rcv_nxt;
  4732. smp_mb();
  4733. tcp_finish_connect(sk, skb);
  4734. if ((tp->syn_fastopen || tp->syn_data) &&
  4735. tcp_rcv_fastopen_synack(sk, skb, &foc))
  4736. return -1;
  4737. if (sk->sk_write_pending ||
  4738. icsk->icsk_accept_queue.rskq_defer_accept ||
  4739. icsk->icsk_ack.pingpong) {
  4740. /* Save one ACK. Data will be ready after
  4741. * several ticks, if write_pending is set.
  4742. *
  4743. * It may be deleted, but with this feature tcpdumps
  4744. * look so _wonderfully_ clever, that I was not able
  4745. * to stand against the temptation 8) --ANK
  4746. */
  4747. inet_csk_schedule_ack(sk);
  4748. icsk->icsk_ack.lrcvtime = tcp_time_stamp;
  4749. tcp_enter_quickack_mode(sk);
  4750. inet_csk_reset_xmit_timer(sk, ICSK_TIME_DACK,
  4751. TCP_DELACK_MAX, TCP_RTO_MAX);
  4752. discard:
  4753. __kfree_skb(skb);
  4754. return 0;
  4755. } else {
  4756. tcp_send_ack(sk);
  4757. }
  4758. return -1;
  4759. }
  4760. /* No ACK in the segment */
  4761. if (th->rst) {
  4762. /* rfc793:
  4763. * "If the RST bit is set
  4764. *
  4765. * Otherwise (no ACK) drop the segment and return."
  4766. */
  4767. goto discard_and_undo;
  4768. }
  4769. /* PAWS check. */
  4770. if (tp->rx_opt.ts_recent_stamp && tp->rx_opt.saw_tstamp &&
  4771. tcp_paws_reject(&tp->rx_opt, 0))
  4772. goto discard_and_undo;
  4773. if (th->syn) {
  4774. /* We see SYN without ACK. It is attempt of
  4775. * simultaneous connect with crossed SYNs.
  4776. * Particularly, it can be connect to self.
  4777. */
  4778. tcp_set_state(sk, TCP_SYN_RECV);
  4779. if (tp->rx_opt.saw_tstamp) {
  4780. tp->rx_opt.tstamp_ok = 1;
  4781. tcp_store_ts_recent(tp);
  4782. tp->tcp_header_len =
  4783. sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED;
  4784. } else {
  4785. tp->tcp_header_len = sizeof(struct tcphdr);
  4786. }
  4787. tp->rcv_nxt = TCP_SKB_CB(skb)->seq + 1;
  4788. tp->rcv_wup = TCP_SKB_CB(skb)->seq + 1;
  4789. /* RFC1323: The window in SYN & SYN/ACK segments is
  4790. * never scaled.
  4791. */
  4792. tp->snd_wnd = ntohs(th->window);
  4793. tp->snd_wl1 = TCP_SKB_CB(skb)->seq;
  4794. tp->max_window = tp->snd_wnd;
  4795. TCP_ECN_rcv_syn(tp, th);
  4796. tcp_mtup_init(sk);
  4797. tcp_sync_mss(sk, icsk->icsk_pmtu_cookie);
  4798. tcp_initialize_rcv_mss(sk);
  4799. tcp_send_synack(sk);
  4800. #if 0
  4801. /* Note, we could accept data and URG from this segment.
  4802. * There are no obstacles to make this (except that we must
  4803. * either change tcp_recvmsg() to prevent it from returning data
  4804. * before 3WHS completes per RFC793, or employ TCP Fast Open).
  4805. *
  4806. * However, if we ignore data in ACKless segments sometimes,
  4807. * we have no reasons to accept it sometimes.
  4808. * Also, seems the code doing it in step6 of tcp_rcv_state_process
  4809. * is not flawless. So, discard packet for sanity.
  4810. * Uncomment this return to process the data.
  4811. */
  4812. return -1;
  4813. #else
  4814. goto discard;
  4815. #endif
  4816. }
  4817. /* "fifth, if neither of the SYN or RST bits is set then
  4818. * drop the segment and return."
  4819. */
  4820. discard_and_undo:
  4821. tcp_clear_options(&tp->rx_opt);
  4822. tp->rx_opt.mss_clamp = saved_clamp;
  4823. goto discard;
  4824. reset_and_undo:
  4825. tcp_clear_options(&tp->rx_opt);
  4826. tp->rx_opt.mss_clamp = saved_clamp;
  4827. return 1;
  4828. }
  4829. /*
  4830. * This function implements the receiving procedure of RFC 793 for
  4831. * all states except ESTABLISHED and TIME_WAIT.
  4832. * It's called from both tcp_v4_rcv and tcp_v6_rcv and should be
  4833. * address independent.
  4834. */
  4835. int tcp_rcv_state_process(struct sock *sk, struct sk_buff *skb,
  4836. const struct tcphdr *th, unsigned int len)
  4837. {
  4838. struct tcp_sock *tp = tcp_sk(sk);
  4839. struct inet_connection_sock *icsk = inet_csk(sk);
  4840. struct request_sock *req;
  4841. int queued = 0;
  4842. bool acceptable;
  4843. u32 synack_stamp;
  4844. tp->rx_opt.saw_tstamp = 0;
  4845. switch (sk->sk_state) {
  4846. case TCP_CLOSE:
  4847. goto discard;
  4848. case TCP_LISTEN:
  4849. if (th->ack)
  4850. return 1;
  4851. if (th->rst)
  4852. goto discard;
  4853. if (th->syn) {
  4854. if (th->fin)
  4855. goto discard;
  4856. if (icsk->icsk_af_ops->conn_request(sk, skb) < 0)
  4857. return 1;
  4858. /* Now we have several options: In theory there is
  4859. * nothing else in the frame. KA9Q has an option to
  4860. * send data with the syn, BSD accepts data with the
  4861. * syn up to the [to be] advertised window and
  4862. * Solaris 2.1 gives you a protocol error. For now
  4863. * we just ignore it, that fits the spec precisely
  4864. * and avoids incompatibilities. It would be nice in
  4865. * future to drop through and process the data.
  4866. *
  4867. * Now that TTCP is starting to be used we ought to
  4868. * queue this data.
  4869. * But, this leaves one open to an easy denial of
  4870. * service attack, and SYN cookies can't defend
  4871. * against this problem. So, we drop the data
  4872. * in the interest of security over speed unless
  4873. * it's still in use.
  4874. */
  4875. kfree_skb(skb);
  4876. return 0;
  4877. }
  4878. goto discard;
  4879. case TCP_SYN_SENT:
  4880. queued = tcp_rcv_synsent_state_process(sk, skb, th, len);
  4881. if (queued >= 0)
  4882. return queued;
  4883. /* Do step6 onward by hand. */
  4884. tcp_urg(sk, skb, th);
  4885. __kfree_skb(skb);
  4886. tcp_data_snd_check(sk);
  4887. return 0;
  4888. }
  4889. req = tp->fastopen_rsk;
  4890. if (req != NULL) {
  4891. WARN_ON_ONCE(sk->sk_state != TCP_SYN_RECV &&
  4892. sk->sk_state != TCP_FIN_WAIT1);
  4893. if (tcp_check_req(sk, skb, req, NULL, true) == NULL)
  4894. goto discard;
  4895. }
  4896. if (!th->ack && !th->rst)
  4897. goto discard;
  4898. if (!tcp_validate_incoming(sk, skb, th, 0))
  4899. return 0;
  4900. /* step 5: check the ACK field */
  4901. acceptable = tcp_ack(sk, skb, FLAG_SLOWPATH |
  4902. FLAG_UPDATE_TS_RECENT) > 0;
  4903. switch (sk->sk_state) {
  4904. case TCP_SYN_RECV:
  4905. if (!acceptable)
  4906. return 1;
  4907. /* Once we leave TCP_SYN_RECV, we no longer need req
  4908. * so release it.
  4909. */
  4910. if (req) {
  4911. synack_stamp = tcp_rsk(req)->snt_synack;
  4912. tp->total_retrans = req->num_retrans;
  4913. reqsk_fastopen_remove(sk, req, false);
  4914. } else {
  4915. synack_stamp = tp->lsndtime;
  4916. /* Make sure socket is routed, for correct metrics. */
  4917. icsk->icsk_af_ops->rebuild_header(sk);
  4918. tcp_init_congestion_control(sk);
  4919. tcp_mtup_init(sk);
  4920. tp->copied_seq = tp->rcv_nxt;
  4921. tcp_init_buffer_space(sk);
  4922. }
  4923. smp_mb();
  4924. tcp_set_state(sk, TCP_ESTABLISHED);
  4925. sk->sk_state_change(sk);
  4926. /* Note, that this wakeup is only for marginal crossed SYN case.
  4927. * Passively open sockets are not waked up, because
  4928. * sk->sk_sleep == NULL and sk->sk_socket == NULL.
  4929. */
  4930. if (sk->sk_socket)
  4931. sk_wake_async(sk, SOCK_WAKE_IO, POLL_OUT);
  4932. tp->snd_una = TCP_SKB_CB(skb)->ack_seq;
  4933. tp->snd_wnd = ntohs(th->window) << tp->rx_opt.snd_wscale;
  4934. tcp_init_wl(tp, TCP_SKB_CB(skb)->seq);
  4935. tcp_synack_rtt_meas(sk, synack_stamp);
  4936. if (tp->rx_opt.tstamp_ok)
  4937. tp->advmss -= TCPOLEN_TSTAMP_ALIGNED;
  4938. if (req) {
  4939. /* Re-arm the timer because data may have been sent out.
  4940. * This is similar to the regular data transmission case
  4941. * when new data has just been ack'ed.
  4942. *
  4943. * (TFO) - we could try to be more aggressive and
  4944. * retransmitting any data sooner based on when they
  4945. * are sent out.
  4946. */
  4947. tcp_rearm_rto(sk);
  4948. } else
  4949. tcp_init_metrics(sk);
  4950. tcp_update_pacing_rate(sk);
  4951. /* Prevent spurious tcp_cwnd_restart() on first data packet */
  4952. tp->lsndtime = tcp_time_stamp;
  4953. tcp_initialize_rcv_mss(sk);
  4954. tcp_fast_path_on(tp);
  4955. break;
  4956. case TCP_FIN_WAIT1: {
  4957. struct dst_entry *dst;
  4958. int tmo;
  4959. /* If we enter the TCP_FIN_WAIT1 state and we are a
  4960. * Fast Open socket and this is the first acceptable
  4961. * ACK we have received, this would have acknowledged
  4962. * our SYNACK so stop the SYNACK timer.
  4963. */
  4964. if (req != NULL) {
  4965. /* Return RST if ack_seq is invalid.
  4966. * Note that RFC793 only says to generate a
  4967. * DUPACK for it but for TCP Fast Open it seems
  4968. * better to treat this case like TCP_SYN_RECV
  4969. * above.
  4970. */
  4971. if (!acceptable)
  4972. return 1;
  4973. /* We no longer need the request sock. */
  4974. reqsk_fastopen_remove(sk, req, false);
  4975. tcp_rearm_rto(sk);
  4976. }
  4977. if (tp->snd_una != tp->write_seq)
  4978. break;
  4979. tcp_set_state(sk, TCP_FIN_WAIT2);
  4980. sk->sk_shutdown |= SEND_SHUTDOWN;
  4981. dst = __sk_dst_get(sk);
  4982. if (dst)
  4983. dst_confirm(dst);
  4984. if (!sock_flag(sk, SOCK_DEAD)) {
  4985. /* Wake up lingering close() */
  4986. sk->sk_state_change(sk);
  4987. break;
  4988. }
  4989. if (tp->linger2 < 0 ||
  4990. (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq &&
  4991. after(TCP_SKB_CB(skb)->end_seq - th->fin, tp->rcv_nxt))) {
  4992. tcp_done(sk);
  4993. NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPABORTONDATA);
  4994. return 1;
  4995. }
  4996. tmo = tcp_fin_time(sk);
  4997. if (tmo > TCP_TIMEWAIT_LEN) {
  4998. inet_csk_reset_keepalive_timer(sk, tmo - TCP_TIMEWAIT_LEN);
  4999. } else if (th->fin || sock_owned_by_user(sk)) {
  5000. /* Bad case. We could lose such FIN otherwise.
  5001. * It is not a big problem, but it looks confusing
  5002. * and not so rare event. We still can lose it now,
  5003. * if it spins in bh_lock_sock(), but it is really
  5004. * marginal case.
  5005. */
  5006. inet_csk_reset_keepalive_timer(sk, tmo);
  5007. } else {
  5008. tcp_time_wait(sk, TCP_FIN_WAIT2, tmo);
  5009. goto discard;
  5010. }
  5011. break;
  5012. }
  5013. case TCP_CLOSING:
  5014. if (tp->snd_una == tp->write_seq) {
  5015. tcp_time_wait(sk, TCP_TIME_WAIT, 0);
  5016. goto discard;
  5017. }
  5018. break;
  5019. case TCP_LAST_ACK:
  5020. if (tp->snd_una == tp->write_seq) {
  5021. tcp_update_metrics(sk);
  5022. tcp_done(sk);
  5023. goto discard;
  5024. }
  5025. break;
  5026. }
  5027. /* step 6: check the URG bit */
  5028. tcp_urg(sk, skb, th);
  5029. /* step 7: process the segment text */
  5030. switch (sk->sk_state) {
  5031. case TCP_CLOSE_WAIT:
  5032. case TCP_CLOSING:
  5033. case TCP_LAST_ACK:
  5034. if (!before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt))
  5035. break;
  5036. case TCP_FIN_WAIT1:
  5037. case TCP_FIN_WAIT2:
  5038. /* RFC 793 says to queue data in these states,
  5039. * RFC 1122 says we MUST send a reset.
  5040. * BSD 4.4 also does reset.
  5041. */
  5042. if (sk->sk_shutdown & RCV_SHUTDOWN) {
  5043. if (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq &&
  5044. after(TCP_SKB_CB(skb)->end_seq - th->fin, tp->rcv_nxt)) {
  5045. NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPABORTONDATA);
  5046. tcp_reset(sk);
  5047. return 1;
  5048. }
  5049. }
  5050. /* Fall through */
  5051. case TCP_ESTABLISHED:
  5052. tcp_data_queue(sk, skb);
  5053. queued = 1;
  5054. break;
  5055. }
  5056. /* tcp_data could move socket to TIME-WAIT */
  5057. if (sk->sk_state != TCP_CLOSE) {
  5058. tcp_data_snd_check(sk);
  5059. tcp_ack_snd_check(sk);
  5060. }
  5061. if (!queued) {
  5062. discard:
  5063. __kfree_skb(skb);
  5064. }
  5065. return 0;
  5066. }
  5067. EXPORT_SYMBOL(tcp_rcv_state_process);
  5068. static inline void pr_drop_req(struct request_sock *req, __u16 port, int family)
  5069. {
  5070. struct inet_request_sock *ireq = inet_rsk(req);
  5071. if (family == AF_INET)
  5072. LIMIT_NETDEBUG(KERN_DEBUG pr_fmt("drop open request from %pI4/%u\n"),
  5073. &ireq->ir_rmt_addr, port);
  5074. #if IS_ENABLED(CONFIG_IPV6)
  5075. else if (family == AF_INET6)
  5076. LIMIT_NETDEBUG(KERN_DEBUG pr_fmt("drop open request from %pI6/%u\n"),
  5077. &ireq->ir_v6_rmt_addr, port);
  5078. #endif
  5079. }
  5080. int tcp_conn_request(struct request_sock_ops *rsk_ops,
  5081. const struct tcp_request_sock_ops *af_ops,
  5082. struct sock *sk, struct sk_buff *skb)
  5083. {
  5084. struct tcp_options_received tmp_opt;
  5085. struct request_sock *req;
  5086. struct tcp_sock *tp = tcp_sk(sk);
  5087. struct dst_entry *dst = NULL;
  5088. __u32 isn = TCP_SKB_CB(skb)->tcp_tw_isn;
  5089. bool want_cookie = false, fastopen;
  5090. struct flowi fl;
  5091. struct tcp_fastopen_cookie foc = { .len = -1 };
  5092. int err;
  5093. /* TW buckets are converted to open requests without
  5094. * limitations, they conserve resources and peer is
  5095. * evidently real one.
  5096. */
  5097. if ((sysctl_tcp_syncookies == 2 ||
  5098. inet_csk_reqsk_queue_is_full(sk)) && !isn) {
  5099. want_cookie = tcp_syn_flood_action(sk, skb, rsk_ops->slab_name);
  5100. if (!want_cookie)
  5101. goto drop;
  5102. }
  5103. /* Accept backlog is full. If we have already queued enough
  5104. * of warm entries in syn queue, drop request. It is better than
  5105. * clogging syn queue with openreqs with exponentially increasing
  5106. * timeout.
  5107. */
  5108. if (sk_acceptq_is_full(sk) && inet_csk_reqsk_queue_young(sk) > 1) {
  5109. NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS);
  5110. goto drop;
  5111. }
  5112. req = inet_reqsk_alloc(rsk_ops);
  5113. if (!req)
  5114. goto drop;
  5115. tcp_rsk(req)->af_specific = af_ops;
  5116. tcp_clear_options(&tmp_opt);
  5117. tmp_opt.mss_clamp = af_ops->mss_clamp;
  5118. tmp_opt.user_mss = tp->rx_opt.user_mss;
  5119. tcp_parse_options(skb, &tmp_opt, 0, want_cookie ? NULL : &foc);
  5120. if (want_cookie && !tmp_opt.saw_tstamp)
  5121. tcp_clear_options(&tmp_opt);
  5122. tmp_opt.tstamp_ok = tmp_opt.saw_tstamp;
  5123. tcp_openreq_init(req, &tmp_opt, skb, sk);
  5124. af_ops->init_req(req, sk, skb);
  5125. if (security_inet_conn_request(sk, skb, req))
  5126. goto drop_and_free;
  5127. if (!want_cookie || tmp_opt.tstamp_ok)
  5128. TCP_ECN_create_request(req, skb, sock_net(sk));
  5129. if (want_cookie) {
  5130. isn = cookie_init_sequence(af_ops, sk, skb, &req->mss);
  5131. req->cookie_ts = tmp_opt.tstamp_ok;
  5132. } else if (!isn) {
  5133. /* VJ's idea. We save last timestamp seen
  5134. * from the destination in peer table, when entering
  5135. * state TIME-WAIT, and check against it before
  5136. * accepting new connection request.
  5137. *
  5138. * If "isn" is not zero, this request hit alive
  5139. * timewait bucket, so that all the necessary checks
  5140. * are made in the function processing timewait state.
  5141. */
  5142. if (tcp_death_row.sysctl_tw_recycle) {
  5143. bool strict;
  5144. dst = af_ops->route_req(sk, &fl, req, &strict);
  5145. if (dst && strict &&
  5146. !tcp_peer_is_proven(req, dst, true,
  5147. tmp_opt.saw_tstamp)) {
  5148. NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_PAWSPASSIVEREJECTED);
  5149. goto drop_and_release;
  5150. }
  5151. }
  5152. /* Kill the following clause, if you dislike this way. */
  5153. else if (!sysctl_tcp_syncookies &&
  5154. (sysctl_max_syn_backlog - inet_csk_reqsk_queue_len(sk) <
  5155. (sysctl_max_syn_backlog >> 2)) &&
  5156. !tcp_peer_is_proven(req, dst, false,
  5157. tmp_opt.saw_tstamp)) {
  5158. /* Without syncookies last quarter of
  5159. * backlog is filled with destinations,
  5160. * proven to be alive.
  5161. * It means that we continue to communicate
  5162. * to destinations, already remembered
  5163. * to the moment of synflood.
  5164. */
  5165. pr_drop_req(req, ntohs(tcp_hdr(skb)->source),
  5166. rsk_ops->family);
  5167. goto drop_and_release;
  5168. }
  5169. isn = af_ops->init_seq(skb);
  5170. }
  5171. if (!dst) {
  5172. dst = af_ops->route_req(sk, &fl, req, NULL);
  5173. if (!dst)
  5174. goto drop_and_free;
  5175. }
  5176. tcp_rsk(req)->snt_isn = isn;
  5177. tcp_openreq_init_rwin(req, sk, dst);
  5178. fastopen = !want_cookie &&
  5179. tcp_try_fastopen(sk, skb, req, &foc, dst);
  5180. err = af_ops->send_synack(sk, dst, &fl, req,
  5181. skb_get_queue_mapping(skb), &foc);
  5182. if (!fastopen) {
  5183. if (err || want_cookie)
  5184. goto drop_and_free;
  5185. tcp_rsk(req)->listener = NULL;
  5186. af_ops->queue_hash_add(sk, req, TCP_TIMEOUT_INIT);
  5187. }
  5188. return 0;
  5189. drop_and_release:
  5190. dst_release(dst);
  5191. drop_and_free:
  5192. reqsk_free(req);
  5193. drop:
  5194. NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENDROPS);
  5195. return 0;
  5196. }
  5197. EXPORT_SYMBOL(tcp_conn_request);