tcp_input.c 203 KB

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