fair.c 368 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Completely Fair Scheduling (CFS) Class (SCHED_NORMAL/SCHED_BATCH)
  4. *
  5. * Copyright (C) 2007 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
  6. *
  7. * Interactivity improvements by Mike Galbraith
  8. * (C) 2007 Mike Galbraith <efault@gmx.de>
  9. *
  10. * Various enhancements by Dmitry Adamushko.
  11. * (C) 2007 Dmitry Adamushko <dmitry.adamushko@gmail.com>
  12. *
  13. * Group scheduling enhancements by Srivatsa Vaddagiri
  14. * Copyright IBM Corporation, 2007
  15. * Author: Srivatsa Vaddagiri <vatsa@linux.vnet.ibm.com>
  16. *
  17. * Scaled math optimizations by Thomas Gleixner
  18. * Copyright (C) 2007, Thomas Gleixner <tglx@linutronix.de>
  19. *
  20. * Adaptive scheduling granularity, math enhancements by Peter Zijlstra
  21. * Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra
  22. */
  23. #include <linux/energy_model.h>
  24. #include <linux/mmap_lock.h>
  25. #include <linux/hugetlb_inline.h>
  26. #include <linux/jiffies.h>
  27. #include <linux/mm_api.h>
  28. #include <linux/highmem.h>
  29. #include <linux/spinlock_api.h>
  30. #include <linux/cpumask_api.h>
  31. #include <linux/lockdep_api.h>
  32. #include <linux/softirq.h>
  33. #include <linux/refcount_api.h>
  34. #include <linux/topology.h>
  35. #include <linux/sched/clock.h>
  36. #include <linux/sched/cond_resched.h>
  37. #include <linux/sched/cputime.h>
  38. #include <linux/sched/isolation.h>
  39. #include <linux/sched/nohz.h>
  40. #include <linux/cpuidle.h>
  41. #include <linux/interrupt.h>
  42. #include <linux/memory-tiers.h>
  43. #include <linux/mempolicy.h>
  44. #include <linux/mutex_api.h>
  45. #include <linux/profile.h>
  46. #include <linux/psi.h>
  47. #include <linux/ratelimit.h>
  48. #include <linux/task_work.h>
  49. #include <linux/rbtree_augmented.h>
  50. #include <asm/switch_to.h>
  51. #include "sched.h"
  52. #include "stats.h"
  53. #include "autogroup.h"
  54. /*
  55. * The initial- and re-scaling of tunables is configurable
  56. *
  57. * Options are:
  58. *
  59. * SCHED_TUNABLESCALING_NONE - unscaled, always *1
  60. * SCHED_TUNABLESCALING_LOG - scaled logarithmically, *1+ilog(ncpus)
  61. * SCHED_TUNABLESCALING_LINEAR - scaled linear, *ncpus
  62. *
  63. * (default SCHED_TUNABLESCALING_LOG = *(1+ilog(ncpus))
  64. */
  65. unsigned int sysctl_sched_tunable_scaling = SCHED_TUNABLESCALING_LOG;
  66. /*
  67. * Minimal preemption granularity for CPU-bound tasks:
  68. *
  69. * (default: 0.70 msec * (1 + ilog(ncpus)), units: nanoseconds)
  70. */
  71. unsigned int sysctl_sched_base_slice = 700000ULL;
  72. static unsigned int normalized_sysctl_sched_base_slice = 700000ULL;
  73. const_debug unsigned int sysctl_sched_migration_cost = 500000UL;
  74. static int __init setup_sched_thermal_decay_shift(char *str)
  75. {
  76. pr_warn("Ignoring the deprecated sched_thermal_decay_shift= option\n");
  77. return 1;
  78. }
  79. __setup("sched_thermal_decay_shift=", setup_sched_thermal_decay_shift);
  80. #ifdef CONFIG_SMP
  81. /*
  82. * For asym packing, by default the lower numbered CPU has higher priority.
  83. */
  84. int __weak arch_asym_cpu_priority(int cpu)
  85. {
  86. return -cpu;
  87. }
  88. /*
  89. * The margin used when comparing utilization with CPU capacity.
  90. *
  91. * (default: ~20%)
  92. */
  93. #define fits_capacity(cap, max) ((cap) * 1280 < (max) * 1024)
  94. /*
  95. * The margin used when comparing CPU capacities.
  96. * is 'cap1' noticeably greater than 'cap2'
  97. *
  98. * (default: ~5%)
  99. */
  100. #define capacity_greater(cap1, cap2) ((cap1) * 1024 > (cap2) * 1078)
  101. #endif
  102. #ifdef CONFIG_CFS_BANDWIDTH
  103. /*
  104. * Amount of runtime to allocate from global (tg) to local (per-cfs_rq) pool
  105. * each time a cfs_rq requests quota.
  106. *
  107. * Note: in the case that the slice exceeds the runtime remaining (either due
  108. * to consumption or the quota being specified to be smaller than the slice)
  109. * we will always only issue the remaining available time.
  110. *
  111. * (default: 5 msec, units: microseconds)
  112. */
  113. static unsigned int sysctl_sched_cfs_bandwidth_slice = 5000UL;
  114. #endif
  115. #ifdef CONFIG_NUMA_BALANCING
  116. /* Restrict the NUMA promotion throughput (MB/s) for each target node. */
  117. static unsigned int sysctl_numa_balancing_promote_rate_limit = 65536;
  118. #endif
  119. #ifdef CONFIG_SYSCTL
  120. static struct ctl_table sched_fair_sysctls[] = {
  121. #ifdef CONFIG_CFS_BANDWIDTH
  122. {
  123. .procname = "sched_cfs_bandwidth_slice_us",
  124. .data = &sysctl_sched_cfs_bandwidth_slice,
  125. .maxlen = sizeof(unsigned int),
  126. .mode = 0644,
  127. .proc_handler = proc_dointvec_minmax,
  128. .extra1 = SYSCTL_ONE,
  129. },
  130. #endif
  131. #ifdef CONFIG_NUMA_BALANCING
  132. {
  133. .procname = "numa_balancing_promote_rate_limit_MBps",
  134. .data = &sysctl_numa_balancing_promote_rate_limit,
  135. .maxlen = sizeof(unsigned int),
  136. .mode = 0644,
  137. .proc_handler = proc_dointvec_minmax,
  138. .extra1 = SYSCTL_ZERO,
  139. },
  140. #endif /* CONFIG_NUMA_BALANCING */
  141. };
  142. static int __init sched_fair_sysctl_init(void)
  143. {
  144. register_sysctl_init("kernel", sched_fair_sysctls);
  145. return 0;
  146. }
  147. late_initcall(sched_fair_sysctl_init);
  148. #endif
  149. static inline void update_load_add(struct load_weight *lw, unsigned long inc)
  150. {
  151. lw->weight += inc;
  152. lw->inv_weight = 0;
  153. }
  154. static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
  155. {
  156. lw->weight -= dec;
  157. lw->inv_weight = 0;
  158. }
  159. static inline void update_load_set(struct load_weight *lw, unsigned long w)
  160. {
  161. lw->weight = w;
  162. lw->inv_weight = 0;
  163. }
  164. /*
  165. * Increase the granularity value when there are more CPUs,
  166. * because with more CPUs the 'effective latency' as visible
  167. * to users decreases. But the relationship is not linear,
  168. * so pick a second-best guess by going with the log2 of the
  169. * number of CPUs.
  170. *
  171. * This idea comes from the SD scheduler of Con Kolivas:
  172. */
  173. static unsigned int get_update_sysctl_factor(void)
  174. {
  175. unsigned int cpus = min_t(unsigned int, num_online_cpus(), 8);
  176. unsigned int factor;
  177. switch (sysctl_sched_tunable_scaling) {
  178. case SCHED_TUNABLESCALING_NONE:
  179. factor = 1;
  180. break;
  181. case SCHED_TUNABLESCALING_LINEAR:
  182. factor = cpus;
  183. break;
  184. case SCHED_TUNABLESCALING_LOG:
  185. default:
  186. factor = 1 + ilog2(cpus);
  187. break;
  188. }
  189. return factor;
  190. }
  191. static void update_sysctl(void)
  192. {
  193. unsigned int factor = get_update_sysctl_factor();
  194. #define SET_SYSCTL(name) \
  195. (sysctl_##name = (factor) * normalized_sysctl_##name)
  196. SET_SYSCTL(sched_base_slice);
  197. #undef SET_SYSCTL
  198. }
  199. void __init sched_init_granularity(void)
  200. {
  201. update_sysctl();
  202. }
  203. #define WMULT_CONST (~0U)
  204. #define WMULT_SHIFT 32
  205. static void __update_inv_weight(struct load_weight *lw)
  206. {
  207. unsigned long w;
  208. if (likely(lw->inv_weight))
  209. return;
  210. w = scale_load_down(lw->weight);
  211. if (BITS_PER_LONG > 32 && unlikely(w >= WMULT_CONST))
  212. lw->inv_weight = 1;
  213. else if (unlikely(!w))
  214. lw->inv_weight = WMULT_CONST;
  215. else
  216. lw->inv_weight = WMULT_CONST / w;
  217. }
  218. /*
  219. * delta_exec * weight / lw.weight
  220. * OR
  221. * (delta_exec * (weight * lw->inv_weight)) >> WMULT_SHIFT
  222. *
  223. * Either weight := NICE_0_LOAD and lw \e sched_prio_to_wmult[], in which case
  224. * we're guaranteed shift stays positive because inv_weight is guaranteed to
  225. * fit 32 bits, and NICE_0_LOAD gives another 10 bits; therefore shift >= 22.
  226. *
  227. * Or, weight =< lw.weight (because lw.weight is the runqueue weight), thus
  228. * weight/lw.weight <= 1, and therefore our shift will also be positive.
  229. */
  230. static u64 __calc_delta(u64 delta_exec, unsigned long weight, struct load_weight *lw)
  231. {
  232. u64 fact = scale_load_down(weight);
  233. u32 fact_hi = (u32)(fact >> 32);
  234. int shift = WMULT_SHIFT;
  235. int fs;
  236. __update_inv_weight(lw);
  237. if (unlikely(fact_hi)) {
  238. fs = fls(fact_hi);
  239. shift -= fs;
  240. fact >>= fs;
  241. }
  242. fact = mul_u32_u32(fact, lw->inv_weight);
  243. fact_hi = (u32)(fact >> 32);
  244. if (fact_hi) {
  245. fs = fls(fact_hi);
  246. shift -= fs;
  247. fact >>= fs;
  248. }
  249. return mul_u64_u32_shr(delta_exec, fact, shift);
  250. }
  251. /*
  252. * delta /= w
  253. */
  254. static inline u64 calc_delta_fair(u64 delta, struct sched_entity *se)
  255. {
  256. if (unlikely(se->load.weight != NICE_0_LOAD))
  257. delta = __calc_delta(delta, NICE_0_LOAD, &se->load);
  258. return delta;
  259. }
  260. const struct sched_class fair_sched_class;
  261. /**************************************************************
  262. * CFS operations on generic schedulable entities:
  263. */
  264. #ifdef CONFIG_FAIR_GROUP_SCHED
  265. /* Walk up scheduling entities hierarchy */
  266. #define for_each_sched_entity(se) \
  267. for (; se; se = se->parent)
  268. static inline bool list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
  269. {
  270. struct rq *rq = rq_of(cfs_rq);
  271. int cpu = cpu_of(rq);
  272. if (cfs_rq->on_list)
  273. return rq->tmp_alone_branch == &rq->leaf_cfs_rq_list;
  274. cfs_rq->on_list = 1;
  275. /*
  276. * Ensure we either appear before our parent (if already
  277. * enqueued) or force our parent to appear after us when it is
  278. * enqueued. The fact that we always enqueue bottom-up
  279. * reduces this to two cases and a special case for the root
  280. * cfs_rq. Furthermore, it also means that we will always reset
  281. * tmp_alone_branch either when the branch is connected
  282. * to a tree or when we reach the top of the tree
  283. */
  284. if (cfs_rq->tg->parent &&
  285. cfs_rq->tg->parent->cfs_rq[cpu]->on_list) {
  286. /*
  287. * If parent is already on the list, we add the child
  288. * just before. Thanks to circular linked property of
  289. * the list, this means to put the child at the tail
  290. * of the list that starts by parent.
  291. */
  292. list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
  293. &(cfs_rq->tg->parent->cfs_rq[cpu]->leaf_cfs_rq_list));
  294. /*
  295. * The branch is now connected to its tree so we can
  296. * reset tmp_alone_branch to the beginning of the
  297. * list.
  298. */
  299. rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
  300. return true;
  301. }
  302. if (!cfs_rq->tg->parent) {
  303. /*
  304. * cfs rq without parent should be put
  305. * at the tail of the list.
  306. */
  307. list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
  308. &rq->leaf_cfs_rq_list);
  309. /*
  310. * We have reach the top of a tree so we can reset
  311. * tmp_alone_branch to the beginning of the list.
  312. */
  313. rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
  314. return true;
  315. }
  316. /*
  317. * The parent has not already been added so we want to
  318. * make sure that it will be put after us.
  319. * tmp_alone_branch points to the begin of the branch
  320. * where we will add parent.
  321. */
  322. list_add_rcu(&cfs_rq->leaf_cfs_rq_list, rq->tmp_alone_branch);
  323. /*
  324. * update tmp_alone_branch to points to the new begin
  325. * of the branch
  326. */
  327. rq->tmp_alone_branch = &cfs_rq->leaf_cfs_rq_list;
  328. return false;
  329. }
  330. static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
  331. {
  332. if (cfs_rq->on_list) {
  333. struct rq *rq = rq_of(cfs_rq);
  334. /*
  335. * With cfs_rq being unthrottled/throttled during an enqueue,
  336. * it can happen the tmp_alone_branch points to the leaf that
  337. * we finally want to delete. In this case, tmp_alone_branch moves
  338. * to the prev element but it will point to rq->leaf_cfs_rq_list
  339. * at the end of the enqueue.
  340. */
  341. if (rq->tmp_alone_branch == &cfs_rq->leaf_cfs_rq_list)
  342. rq->tmp_alone_branch = cfs_rq->leaf_cfs_rq_list.prev;
  343. list_del_rcu(&cfs_rq->leaf_cfs_rq_list);
  344. cfs_rq->on_list = 0;
  345. }
  346. }
  347. static inline void assert_list_leaf_cfs_rq(struct rq *rq)
  348. {
  349. SCHED_WARN_ON(rq->tmp_alone_branch != &rq->leaf_cfs_rq_list);
  350. }
  351. /* Iterate through all leaf cfs_rq's on a runqueue */
  352. #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) \
  353. list_for_each_entry_safe(cfs_rq, pos, &rq->leaf_cfs_rq_list, \
  354. leaf_cfs_rq_list)
  355. /* Do the two (enqueued) entities belong to the same group ? */
  356. static inline struct cfs_rq *
  357. is_same_group(struct sched_entity *se, struct sched_entity *pse)
  358. {
  359. if (se->cfs_rq == pse->cfs_rq)
  360. return se->cfs_rq;
  361. return NULL;
  362. }
  363. static inline struct sched_entity *parent_entity(const struct sched_entity *se)
  364. {
  365. return se->parent;
  366. }
  367. static void
  368. find_matching_se(struct sched_entity **se, struct sched_entity **pse)
  369. {
  370. int se_depth, pse_depth;
  371. /*
  372. * preemption test can be made between sibling entities who are in the
  373. * same cfs_rq i.e who have a common parent. Walk up the hierarchy of
  374. * both tasks until we find their ancestors who are siblings of common
  375. * parent.
  376. */
  377. /* First walk up until both entities are at same depth */
  378. se_depth = (*se)->depth;
  379. pse_depth = (*pse)->depth;
  380. while (se_depth > pse_depth) {
  381. se_depth--;
  382. *se = parent_entity(*se);
  383. }
  384. while (pse_depth > se_depth) {
  385. pse_depth--;
  386. *pse = parent_entity(*pse);
  387. }
  388. while (!is_same_group(*se, *pse)) {
  389. *se = parent_entity(*se);
  390. *pse = parent_entity(*pse);
  391. }
  392. }
  393. static int tg_is_idle(struct task_group *tg)
  394. {
  395. return tg->idle > 0;
  396. }
  397. static int cfs_rq_is_idle(struct cfs_rq *cfs_rq)
  398. {
  399. return cfs_rq->idle > 0;
  400. }
  401. static int se_is_idle(struct sched_entity *se)
  402. {
  403. if (entity_is_task(se))
  404. return task_has_idle_policy(task_of(se));
  405. return cfs_rq_is_idle(group_cfs_rq(se));
  406. }
  407. #else /* !CONFIG_FAIR_GROUP_SCHED */
  408. #define for_each_sched_entity(se) \
  409. for (; se; se = NULL)
  410. static inline bool list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
  411. {
  412. return true;
  413. }
  414. static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
  415. {
  416. }
  417. static inline void assert_list_leaf_cfs_rq(struct rq *rq)
  418. {
  419. }
  420. #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) \
  421. for (cfs_rq = &rq->cfs, pos = NULL; cfs_rq; cfs_rq = pos)
  422. static inline struct sched_entity *parent_entity(struct sched_entity *se)
  423. {
  424. return NULL;
  425. }
  426. static inline void
  427. find_matching_se(struct sched_entity **se, struct sched_entity **pse)
  428. {
  429. }
  430. static inline int tg_is_idle(struct task_group *tg)
  431. {
  432. return 0;
  433. }
  434. static int cfs_rq_is_idle(struct cfs_rq *cfs_rq)
  435. {
  436. return 0;
  437. }
  438. static int se_is_idle(struct sched_entity *se)
  439. {
  440. return task_has_idle_policy(task_of(se));
  441. }
  442. #endif /* CONFIG_FAIR_GROUP_SCHED */
  443. static __always_inline
  444. void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec);
  445. /**************************************************************
  446. * Scheduling class tree data structure manipulation methods:
  447. */
  448. static inline u64 max_vruntime(u64 max_vruntime, u64 vruntime)
  449. {
  450. s64 delta = (s64)(vruntime - max_vruntime);
  451. if (delta > 0)
  452. max_vruntime = vruntime;
  453. return max_vruntime;
  454. }
  455. static inline u64 min_vruntime(u64 min_vruntime, u64 vruntime)
  456. {
  457. s64 delta = (s64)(vruntime - min_vruntime);
  458. if (delta < 0)
  459. min_vruntime = vruntime;
  460. return min_vruntime;
  461. }
  462. static inline bool entity_before(const struct sched_entity *a,
  463. const struct sched_entity *b)
  464. {
  465. /*
  466. * Tiebreak on vruntime seems unnecessary since it can
  467. * hardly happen.
  468. */
  469. return (s64)(a->deadline - b->deadline) < 0;
  470. }
  471. static inline s64 entity_key(struct cfs_rq *cfs_rq, struct sched_entity *se)
  472. {
  473. return (s64)(se->vruntime - cfs_rq->min_vruntime);
  474. }
  475. #define __node_2_se(node) \
  476. rb_entry((node), struct sched_entity, run_node)
  477. /*
  478. * Compute virtual time from the per-task service numbers:
  479. *
  480. * Fair schedulers conserve lag:
  481. *
  482. * \Sum lag_i = 0
  483. *
  484. * Where lag_i is given by:
  485. *
  486. * lag_i = S - s_i = w_i * (V - v_i)
  487. *
  488. * Where S is the ideal service time and V is it's virtual time counterpart.
  489. * Therefore:
  490. *
  491. * \Sum lag_i = 0
  492. * \Sum w_i * (V - v_i) = 0
  493. * \Sum w_i * V - w_i * v_i = 0
  494. *
  495. * From which we can solve an expression for V in v_i (which we have in
  496. * se->vruntime):
  497. *
  498. * \Sum v_i * w_i \Sum v_i * w_i
  499. * V = -------------- = --------------
  500. * \Sum w_i W
  501. *
  502. * Specifically, this is the weighted average of all entity virtual runtimes.
  503. *
  504. * [[ NOTE: this is only equal to the ideal scheduler under the condition
  505. * that join/leave operations happen at lag_i = 0, otherwise the
  506. * virtual time has non-contiguous motion equivalent to:
  507. *
  508. * V +-= lag_i / W
  509. *
  510. * Also see the comment in place_entity() that deals with this. ]]
  511. *
  512. * However, since v_i is u64, and the multiplication could easily overflow
  513. * transform it into a relative form that uses smaller quantities:
  514. *
  515. * Substitute: v_i == (v_i - v0) + v0
  516. *
  517. * \Sum ((v_i - v0) + v0) * w_i \Sum (v_i - v0) * w_i
  518. * V = ---------------------------- = --------------------- + v0
  519. * W W
  520. *
  521. * Which we track using:
  522. *
  523. * v0 := cfs_rq->min_vruntime
  524. * \Sum (v_i - v0) * w_i := cfs_rq->avg_vruntime
  525. * \Sum w_i := cfs_rq->avg_load
  526. *
  527. * Since min_vruntime is a monotonic increasing variable that closely tracks
  528. * the per-task service, these deltas: (v_i - v), will be in the order of the
  529. * maximal (virtual) lag induced in the system due to quantisation.
  530. *
  531. * Also, we use scale_load_down() to reduce the size.
  532. *
  533. * As measured, the max (key * weight) value was ~44 bits for a kernel build.
  534. */
  535. static void
  536. avg_vruntime_add(struct cfs_rq *cfs_rq, struct sched_entity *se)
  537. {
  538. unsigned long weight = scale_load_down(se->load.weight);
  539. s64 key = entity_key(cfs_rq, se);
  540. cfs_rq->avg_vruntime += key * weight;
  541. cfs_rq->avg_load += weight;
  542. }
  543. static void
  544. avg_vruntime_sub(struct cfs_rq *cfs_rq, struct sched_entity *se)
  545. {
  546. unsigned long weight = scale_load_down(se->load.weight);
  547. s64 key = entity_key(cfs_rq, se);
  548. cfs_rq->avg_vruntime -= key * weight;
  549. cfs_rq->avg_load -= weight;
  550. }
  551. static inline
  552. void avg_vruntime_update(struct cfs_rq *cfs_rq, s64 delta)
  553. {
  554. /*
  555. * v' = v + d ==> avg_vruntime' = avg_runtime - d*avg_load
  556. */
  557. cfs_rq->avg_vruntime -= cfs_rq->avg_load * delta;
  558. }
  559. /*
  560. * Specifically: avg_runtime() + 0 must result in entity_eligible() := true
  561. * For this to be so, the result of this function must have a left bias.
  562. */
  563. u64 avg_vruntime(struct cfs_rq *cfs_rq)
  564. {
  565. struct sched_entity *curr = cfs_rq->curr;
  566. s64 avg = cfs_rq->avg_vruntime;
  567. long load = cfs_rq->avg_load;
  568. if (curr && curr->on_rq) {
  569. unsigned long weight = scale_load_down(curr->load.weight);
  570. avg += entity_key(cfs_rq, curr) * weight;
  571. load += weight;
  572. }
  573. if (load) {
  574. /* sign flips effective floor / ceiling */
  575. if (avg < 0)
  576. avg -= (load - 1);
  577. avg = div_s64(avg, load);
  578. }
  579. return cfs_rq->min_vruntime + avg;
  580. }
  581. /*
  582. * lag_i = S - s_i = w_i * (V - v_i)
  583. *
  584. * However, since V is approximated by the weighted average of all entities it
  585. * is possible -- by addition/removal/reweight to the tree -- to move V around
  586. * and end up with a larger lag than we started with.
  587. *
  588. * Limit this to either double the slice length with a minimum of TICK_NSEC
  589. * since that is the timing granularity.
  590. *
  591. * EEVDF gives the following limit for a steady state system:
  592. *
  593. * -r_max < lag < max(r_max, q)
  594. *
  595. * XXX could add max_slice to the augmented data to track this.
  596. */
  597. static s64 entity_lag(u64 avruntime, struct sched_entity *se)
  598. {
  599. s64 vlag, limit;
  600. vlag = avruntime - se->vruntime;
  601. limit = calc_delta_fair(max_t(u64, 2*se->slice, TICK_NSEC), se);
  602. return clamp(vlag, -limit, limit);
  603. }
  604. static void update_entity_lag(struct cfs_rq *cfs_rq, struct sched_entity *se)
  605. {
  606. SCHED_WARN_ON(!se->on_rq);
  607. se->vlag = entity_lag(avg_vruntime(cfs_rq), se);
  608. }
  609. /*
  610. * Entity is eligible once it received less service than it ought to have,
  611. * eg. lag >= 0.
  612. *
  613. * lag_i = S - s_i = w_i*(V - v_i)
  614. *
  615. * lag_i >= 0 -> V >= v_i
  616. *
  617. * \Sum (v_i - v)*w_i
  618. * V = ------------------ + v
  619. * \Sum w_i
  620. *
  621. * lag_i >= 0 -> \Sum (v_i - v)*w_i >= (v_i - v)*(\Sum w_i)
  622. *
  623. * Note: using 'avg_vruntime() > se->vruntime' is inaccurate due
  624. * to the loss in precision caused by the division.
  625. */
  626. static int vruntime_eligible(struct cfs_rq *cfs_rq, u64 vruntime)
  627. {
  628. struct sched_entity *curr = cfs_rq->curr;
  629. s64 avg = cfs_rq->avg_vruntime;
  630. long load = cfs_rq->avg_load;
  631. if (curr && curr->on_rq) {
  632. unsigned long weight = scale_load_down(curr->load.weight);
  633. avg += entity_key(cfs_rq, curr) * weight;
  634. load += weight;
  635. }
  636. return avg >= (s64)(vruntime - cfs_rq->min_vruntime) * load;
  637. }
  638. int entity_eligible(struct cfs_rq *cfs_rq, struct sched_entity *se)
  639. {
  640. return vruntime_eligible(cfs_rq, se->vruntime);
  641. }
  642. static u64 __update_min_vruntime(struct cfs_rq *cfs_rq, u64 vruntime)
  643. {
  644. u64 min_vruntime = cfs_rq->min_vruntime;
  645. /*
  646. * open coded max_vruntime() to allow updating avg_vruntime
  647. */
  648. s64 delta = (s64)(vruntime - min_vruntime);
  649. if (delta > 0) {
  650. avg_vruntime_update(cfs_rq, delta);
  651. min_vruntime = vruntime;
  652. }
  653. return min_vruntime;
  654. }
  655. static void update_min_vruntime(struct cfs_rq *cfs_rq)
  656. {
  657. struct sched_entity *se = __pick_root_entity(cfs_rq);
  658. struct sched_entity *curr = cfs_rq->curr;
  659. u64 vruntime = cfs_rq->min_vruntime;
  660. if (curr) {
  661. if (curr->on_rq)
  662. vruntime = curr->vruntime;
  663. else
  664. curr = NULL;
  665. }
  666. if (se) {
  667. if (!curr)
  668. vruntime = se->min_vruntime;
  669. else
  670. vruntime = min_vruntime(vruntime, se->min_vruntime);
  671. }
  672. /* ensure we never gain time by being placed backwards. */
  673. cfs_rq->min_vruntime = __update_min_vruntime(cfs_rq, vruntime);
  674. }
  675. static inline u64 cfs_rq_min_slice(struct cfs_rq *cfs_rq)
  676. {
  677. struct sched_entity *root = __pick_root_entity(cfs_rq);
  678. struct sched_entity *curr = cfs_rq->curr;
  679. u64 min_slice = ~0ULL;
  680. if (curr && curr->on_rq)
  681. min_slice = curr->slice;
  682. if (root)
  683. min_slice = min(min_slice, root->min_slice);
  684. return min_slice;
  685. }
  686. static inline bool __entity_less(struct rb_node *a, const struct rb_node *b)
  687. {
  688. return entity_before(__node_2_se(a), __node_2_se(b));
  689. }
  690. #define vruntime_gt(field, lse, rse) ({ (s64)((lse)->field - (rse)->field) > 0; })
  691. static inline void __min_vruntime_update(struct sched_entity *se, struct rb_node *node)
  692. {
  693. if (node) {
  694. struct sched_entity *rse = __node_2_se(node);
  695. if (vruntime_gt(min_vruntime, se, rse))
  696. se->min_vruntime = rse->min_vruntime;
  697. }
  698. }
  699. static inline void __min_slice_update(struct sched_entity *se, struct rb_node *node)
  700. {
  701. if (node) {
  702. struct sched_entity *rse = __node_2_se(node);
  703. if (rse->min_slice < se->min_slice)
  704. se->min_slice = rse->min_slice;
  705. }
  706. }
  707. /*
  708. * se->min_vruntime = min(se->vruntime, {left,right}->min_vruntime)
  709. */
  710. static inline bool min_vruntime_update(struct sched_entity *se, bool exit)
  711. {
  712. u64 old_min_vruntime = se->min_vruntime;
  713. u64 old_min_slice = se->min_slice;
  714. struct rb_node *node = &se->run_node;
  715. se->min_vruntime = se->vruntime;
  716. __min_vruntime_update(se, node->rb_right);
  717. __min_vruntime_update(se, node->rb_left);
  718. se->min_slice = se->slice;
  719. __min_slice_update(se, node->rb_right);
  720. __min_slice_update(se, node->rb_left);
  721. return se->min_vruntime == old_min_vruntime &&
  722. se->min_slice == old_min_slice;
  723. }
  724. RB_DECLARE_CALLBACKS(static, min_vruntime_cb, struct sched_entity,
  725. run_node, min_vruntime, min_vruntime_update);
  726. /*
  727. * Enqueue an entity into the rb-tree:
  728. */
  729. static void __enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
  730. {
  731. avg_vruntime_add(cfs_rq, se);
  732. se->min_vruntime = se->vruntime;
  733. se->min_slice = se->slice;
  734. rb_add_augmented_cached(&se->run_node, &cfs_rq->tasks_timeline,
  735. __entity_less, &min_vruntime_cb);
  736. }
  737. static void __dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
  738. {
  739. rb_erase_augmented_cached(&se->run_node, &cfs_rq->tasks_timeline,
  740. &min_vruntime_cb);
  741. avg_vruntime_sub(cfs_rq, se);
  742. }
  743. struct sched_entity *__pick_root_entity(struct cfs_rq *cfs_rq)
  744. {
  745. struct rb_node *root = cfs_rq->tasks_timeline.rb_root.rb_node;
  746. if (!root)
  747. return NULL;
  748. return __node_2_se(root);
  749. }
  750. struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq)
  751. {
  752. struct rb_node *left = rb_first_cached(&cfs_rq->tasks_timeline);
  753. if (!left)
  754. return NULL;
  755. return __node_2_se(left);
  756. }
  757. /*
  758. * HACK, stash a copy of deadline at the point of pick in vlag,
  759. * which isn't used until dequeue.
  760. */
  761. static inline void set_protect_slice(struct sched_entity *se)
  762. {
  763. se->vlag = se->deadline;
  764. }
  765. static inline bool protect_slice(struct sched_entity *se)
  766. {
  767. return se->vlag == se->deadline;
  768. }
  769. static inline void cancel_protect_slice(struct sched_entity *se)
  770. {
  771. if (protect_slice(se))
  772. se->vlag = se->deadline + 1;
  773. }
  774. /*
  775. * Earliest Eligible Virtual Deadline First
  776. *
  777. * In order to provide latency guarantees for different request sizes
  778. * EEVDF selects the best runnable task from two criteria:
  779. *
  780. * 1) the task must be eligible (must be owed service)
  781. *
  782. * 2) from those tasks that meet 1), we select the one
  783. * with the earliest virtual deadline.
  784. *
  785. * We can do this in O(log n) time due to an augmented RB-tree. The
  786. * tree keeps the entries sorted on deadline, but also functions as a
  787. * heap based on the vruntime by keeping:
  788. *
  789. * se->min_vruntime = min(se->vruntime, se->{left,right}->min_vruntime)
  790. *
  791. * Which allows tree pruning through eligibility.
  792. */
  793. static struct sched_entity *pick_eevdf(struct cfs_rq *cfs_rq)
  794. {
  795. struct rb_node *node = cfs_rq->tasks_timeline.rb_root.rb_node;
  796. struct sched_entity *se = __pick_first_entity(cfs_rq);
  797. struct sched_entity *curr = cfs_rq->curr;
  798. struct sched_entity *best = NULL;
  799. /*
  800. * We can safely skip eligibility check if there is only one entity
  801. * in this cfs_rq, saving some cycles.
  802. */
  803. if (cfs_rq->nr_running == 1)
  804. return curr && curr->on_rq ? curr : se;
  805. if (curr && (!curr->on_rq || !entity_eligible(cfs_rq, curr)))
  806. curr = NULL;
  807. if (sched_feat(RUN_TO_PARITY) && curr && protect_slice(curr))
  808. return curr;
  809. /* Pick the leftmost entity if it's eligible */
  810. if (se && entity_eligible(cfs_rq, se)) {
  811. best = se;
  812. goto found;
  813. }
  814. /* Heap search for the EEVD entity */
  815. while (node) {
  816. struct rb_node *left = node->rb_left;
  817. /*
  818. * Eligible entities in left subtree are always better
  819. * choices, since they have earlier deadlines.
  820. */
  821. if (left && vruntime_eligible(cfs_rq,
  822. __node_2_se(left)->min_vruntime)) {
  823. node = left;
  824. continue;
  825. }
  826. se = __node_2_se(node);
  827. /*
  828. * The left subtree either is empty or has no eligible
  829. * entity, so check the current node since it is the one
  830. * with earliest deadline that might be eligible.
  831. */
  832. if (entity_eligible(cfs_rq, se)) {
  833. best = se;
  834. break;
  835. }
  836. node = node->rb_right;
  837. }
  838. found:
  839. if (!best || (curr && entity_before(curr, best)))
  840. best = curr;
  841. return best;
  842. }
  843. #ifdef CONFIG_SCHED_DEBUG
  844. struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq)
  845. {
  846. struct rb_node *last = rb_last(&cfs_rq->tasks_timeline.rb_root);
  847. if (!last)
  848. return NULL;
  849. return __node_2_se(last);
  850. }
  851. /**************************************************************
  852. * Scheduling class statistics methods:
  853. */
  854. #ifdef CONFIG_SMP
  855. int sched_update_scaling(void)
  856. {
  857. unsigned int factor = get_update_sysctl_factor();
  858. #define WRT_SYSCTL(name) \
  859. (normalized_sysctl_##name = sysctl_##name / (factor))
  860. WRT_SYSCTL(sched_base_slice);
  861. #undef WRT_SYSCTL
  862. return 0;
  863. }
  864. #endif
  865. #endif
  866. static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se);
  867. /*
  868. * XXX: strictly: vd_i += N*r_i/w_i such that: vd_i > ve_i
  869. * this is probably good enough.
  870. */
  871. static bool update_deadline(struct cfs_rq *cfs_rq, struct sched_entity *se)
  872. {
  873. if ((s64)(se->vruntime - se->deadline) < 0)
  874. return false;
  875. /*
  876. * For EEVDF the virtual time slope is determined by w_i (iow.
  877. * nice) while the request time r_i is determined by
  878. * sysctl_sched_base_slice.
  879. */
  880. if (!se->custom_slice)
  881. se->slice = sysctl_sched_base_slice;
  882. /*
  883. * EEVDF: vd_i = ve_i + r_i / w_i
  884. */
  885. se->deadline = se->vruntime + calc_delta_fair(se->slice, se);
  886. /*
  887. * The task has consumed its request, reschedule.
  888. */
  889. return true;
  890. }
  891. #include "pelt.h"
  892. #ifdef CONFIG_SMP
  893. static int select_idle_sibling(struct task_struct *p, int prev_cpu, int cpu);
  894. static unsigned long task_h_load(struct task_struct *p);
  895. static unsigned long capacity_of(int cpu);
  896. /* Give new sched_entity start runnable values to heavy its load in infant time */
  897. void init_entity_runnable_average(struct sched_entity *se)
  898. {
  899. struct sched_avg *sa = &se->avg;
  900. memset(sa, 0, sizeof(*sa));
  901. /*
  902. * Tasks are initialized with full load to be seen as heavy tasks until
  903. * they get a chance to stabilize to their real load level.
  904. * Group entities are initialized with zero load to reflect the fact that
  905. * nothing has been attached to the task group yet.
  906. */
  907. if (entity_is_task(se))
  908. sa->load_avg = scale_load_down(se->load.weight);
  909. /* when this task is enqueued, it will contribute to its cfs_rq's load_avg */
  910. }
  911. /*
  912. * With new tasks being created, their initial util_avgs are extrapolated
  913. * based on the cfs_rq's current util_avg:
  914. *
  915. * util_avg = cfs_rq->avg.util_avg / (cfs_rq->avg.load_avg + 1)
  916. * * se_weight(se)
  917. *
  918. * However, in many cases, the above util_avg does not give a desired
  919. * value. Moreover, the sum of the util_avgs may be divergent, such
  920. * as when the series is a harmonic series.
  921. *
  922. * To solve this problem, we also cap the util_avg of successive tasks to
  923. * only 1/2 of the left utilization budget:
  924. *
  925. * util_avg_cap = (cpu_scale - cfs_rq->avg.util_avg) / 2^n
  926. *
  927. * where n denotes the nth task and cpu_scale the CPU capacity.
  928. *
  929. * For example, for a CPU with 1024 of capacity, a simplest series from
  930. * the beginning would be like:
  931. *
  932. * task util_avg: 512, 256, 128, 64, 32, 16, 8, ...
  933. * cfs_rq util_avg: 512, 768, 896, 960, 992, 1008, 1016, ...
  934. *
  935. * Finally, that extrapolated util_avg is clamped to the cap (util_avg_cap)
  936. * if util_avg > util_avg_cap.
  937. */
  938. void post_init_entity_util_avg(struct task_struct *p)
  939. {
  940. struct sched_entity *se = &p->se;
  941. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  942. struct sched_avg *sa = &se->avg;
  943. long cpu_scale = arch_scale_cpu_capacity(cpu_of(rq_of(cfs_rq)));
  944. long cap = (long)(cpu_scale - cfs_rq->avg.util_avg) / 2;
  945. if (p->sched_class != &fair_sched_class) {
  946. /*
  947. * For !fair tasks do:
  948. *
  949. update_cfs_rq_load_avg(now, cfs_rq);
  950. attach_entity_load_avg(cfs_rq, se);
  951. switched_from_fair(rq, p);
  952. *
  953. * such that the next switched_to_fair() has the
  954. * expected state.
  955. */
  956. se->avg.last_update_time = cfs_rq_clock_pelt(cfs_rq);
  957. return;
  958. }
  959. if (cap > 0) {
  960. if (cfs_rq->avg.util_avg != 0) {
  961. sa->util_avg = cfs_rq->avg.util_avg * se_weight(se);
  962. sa->util_avg /= (cfs_rq->avg.load_avg + 1);
  963. if (sa->util_avg > cap)
  964. sa->util_avg = cap;
  965. } else {
  966. sa->util_avg = cap;
  967. }
  968. }
  969. sa->runnable_avg = sa->util_avg;
  970. }
  971. #else /* !CONFIG_SMP */
  972. void init_entity_runnable_average(struct sched_entity *se)
  973. {
  974. }
  975. void post_init_entity_util_avg(struct task_struct *p)
  976. {
  977. }
  978. static void update_tg_load_avg(struct cfs_rq *cfs_rq)
  979. {
  980. }
  981. #endif /* CONFIG_SMP */
  982. static s64 update_curr_se(struct rq *rq, struct sched_entity *curr)
  983. {
  984. u64 now = rq_clock_task(rq);
  985. s64 delta_exec;
  986. delta_exec = now - curr->exec_start;
  987. if (unlikely(delta_exec <= 0))
  988. return delta_exec;
  989. curr->exec_start = now;
  990. curr->sum_exec_runtime += delta_exec;
  991. if (schedstat_enabled()) {
  992. struct sched_statistics *stats;
  993. stats = __schedstats_from_se(curr);
  994. __schedstat_set(stats->exec_max,
  995. max(delta_exec, stats->exec_max));
  996. }
  997. return delta_exec;
  998. }
  999. static inline void update_curr_task(struct task_struct *p, s64 delta_exec)
  1000. {
  1001. trace_sched_stat_runtime(p, delta_exec);
  1002. account_group_exec_runtime(p, delta_exec);
  1003. cgroup_account_cputime(p, delta_exec);
  1004. }
  1005. static inline bool did_preempt_short(struct cfs_rq *cfs_rq, struct sched_entity *curr)
  1006. {
  1007. if (!sched_feat(PREEMPT_SHORT))
  1008. return false;
  1009. if (curr->vlag == curr->deadline)
  1010. return false;
  1011. return !entity_eligible(cfs_rq, curr);
  1012. }
  1013. static inline bool do_preempt_short(struct cfs_rq *cfs_rq,
  1014. struct sched_entity *pse, struct sched_entity *se)
  1015. {
  1016. if (!sched_feat(PREEMPT_SHORT))
  1017. return false;
  1018. if (pse->slice >= se->slice)
  1019. return false;
  1020. if (!entity_eligible(cfs_rq, pse))
  1021. return false;
  1022. if (entity_before(pse, se))
  1023. return true;
  1024. if (!entity_eligible(cfs_rq, se))
  1025. return true;
  1026. return false;
  1027. }
  1028. /*
  1029. * Used by other classes to account runtime.
  1030. */
  1031. s64 update_curr_common(struct rq *rq)
  1032. {
  1033. struct task_struct *curr = rq->curr;
  1034. s64 delta_exec;
  1035. delta_exec = update_curr_se(rq, &curr->se);
  1036. if (likely(delta_exec > 0))
  1037. update_curr_task(curr, delta_exec);
  1038. return delta_exec;
  1039. }
  1040. /*
  1041. * Update the current task's runtime statistics.
  1042. */
  1043. static void update_curr(struct cfs_rq *cfs_rq)
  1044. {
  1045. struct sched_entity *curr = cfs_rq->curr;
  1046. struct rq *rq = rq_of(cfs_rq);
  1047. s64 delta_exec;
  1048. bool resched;
  1049. if (unlikely(!curr))
  1050. return;
  1051. delta_exec = update_curr_se(rq, curr);
  1052. if (unlikely(delta_exec <= 0))
  1053. return;
  1054. curr->vruntime += calc_delta_fair(delta_exec, curr);
  1055. resched = update_deadline(cfs_rq, curr);
  1056. update_min_vruntime(cfs_rq);
  1057. if (entity_is_task(curr)) {
  1058. struct task_struct *p = task_of(curr);
  1059. update_curr_task(p, delta_exec);
  1060. /*
  1061. * If the fair_server is active, we need to account for the
  1062. * fair_server time whether or not the task is running on
  1063. * behalf of fair_server or not:
  1064. * - If the task is running on behalf of fair_server, we need
  1065. * to limit its time based on the assigned runtime.
  1066. * - Fair task that runs outside of fair_server should account
  1067. * against fair_server such that it can account for this time
  1068. * and possibly avoid running this period.
  1069. */
  1070. if (dl_server_active(&rq->fair_server))
  1071. dl_server_update(&rq->fair_server, delta_exec);
  1072. }
  1073. account_cfs_rq_runtime(cfs_rq, delta_exec);
  1074. if (cfs_rq->nr_running == 1)
  1075. return;
  1076. if (resched || did_preempt_short(cfs_rq, curr)) {
  1077. resched_curr(rq);
  1078. clear_buddies(cfs_rq, curr);
  1079. }
  1080. }
  1081. static void update_curr_fair(struct rq *rq)
  1082. {
  1083. update_curr(cfs_rq_of(&rq->curr->se));
  1084. }
  1085. static inline void
  1086. update_stats_wait_start_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
  1087. {
  1088. struct sched_statistics *stats;
  1089. struct task_struct *p = NULL;
  1090. if (!schedstat_enabled())
  1091. return;
  1092. stats = __schedstats_from_se(se);
  1093. if (entity_is_task(se))
  1094. p = task_of(se);
  1095. __update_stats_wait_start(rq_of(cfs_rq), p, stats);
  1096. }
  1097. static inline void
  1098. update_stats_wait_end_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
  1099. {
  1100. struct sched_statistics *stats;
  1101. struct task_struct *p = NULL;
  1102. if (!schedstat_enabled())
  1103. return;
  1104. stats = __schedstats_from_se(se);
  1105. /*
  1106. * When the sched_schedstat changes from 0 to 1, some sched se
  1107. * maybe already in the runqueue, the se->statistics.wait_start
  1108. * will be 0.So it will let the delta wrong. We need to avoid this
  1109. * scenario.
  1110. */
  1111. if (unlikely(!schedstat_val(stats->wait_start)))
  1112. return;
  1113. if (entity_is_task(se))
  1114. p = task_of(se);
  1115. __update_stats_wait_end(rq_of(cfs_rq), p, stats);
  1116. }
  1117. static inline void
  1118. update_stats_enqueue_sleeper_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
  1119. {
  1120. struct sched_statistics *stats;
  1121. struct task_struct *tsk = NULL;
  1122. if (!schedstat_enabled())
  1123. return;
  1124. stats = __schedstats_from_se(se);
  1125. if (entity_is_task(se))
  1126. tsk = task_of(se);
  1127. __update_stats_enqueue_sleeper(rq_of(cfs_rq), tsk, stats);
  1128. }
  1129. /*
  1130. * Task is being enqueued - update stats:
  1131. */
  1132. static inline void
  1133. update_stats_enqueue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
  1134. {
  1135. if (!schedstat_enabled())
  1136. return;
  1137. /*
  1138. * Are we enqueueing a waiting task? (for current tasks
  1139. * a dequeue/enqueue event is a NOP)
  1140. */
  1141. if (se != cfs_rq->curr)
  1142. update_stats_wait_start_fair(cfs_rq, se);
  1143. if (flags & ENQUEUE_WAKEUP)
  1144. update_stats_enqueue_sleeper_fair(cfs_rq, se);
  1145. }
  1146. static inline void
  1147. update_stats_dequeue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
  1148. {
  1149. if (!schedstat_enabled())
  1150. return;
  1151. /*
  1152. * Mark the end of the wait period if dequeueing a
  1153. * waiting task:
  1154. */
  1155. if (se != cfs_rq->curr)
  1156. update_stats_wait_end_fair(cfs_rq, se);
  1157. if ((flags & DEQUEUE_SLEEP) && entity_is_task(se)) {
  1158. struct task_struct *tsk = task_of(se);
  1159. unsigned int state;
  1160. /* XXX racy against TTWU */
  1161. state = READ_ONCE(tsk->__state);
  1162. if (state & TASK_INTERRUPTIBLE)
  1163. __schedstat_set(tsk->stats.sleep_start,
  1164. rq_clock(rq_of(cfs_rq)));
  1165. if (state & TASK_UNINTERRUPTIBLE)
  1166. __schedstat_set(tsk->stats.block_start,
  1167. rq_clock(rq_of(cfs_rq)));
  1168. }
  1169. }
  1170. /*
  1171. * We are picking a new current task - update its stats:
  1172. */
  1173. static inline void
  1174. update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
  1175. {
  1176. /*
  1177. * We are starting a new run period:
  1178. */
  1179. se->exec_start = rq_clock_task(rq_of(cfs_rq));
  1180. }
  1181. /**************************************************
  1182. * Scheduling class queueing methods:
  1183. */
  1184. static inline bool is_core_idle(int cpu)
  1185. {
  1186. #ifdef CONFIG_SCHED_SMT
  1187. int sibling;
  1188. for_each_cpu(sibling, cpu_smt_mask(cpu)) {
  1189. if (cpu == sibling)
  1190. continue;
  1191. if (!idle_cpu(sibling))
  1192. return false;
  1193. }
  1194. #endif
  1195. return true;
  1196. }
  1197. #ifdef CONFIG_NUMA
  1198. #define NUMA_IMBALANCE_MIN 2
  1199. static inline long
  1200. adjust_numa_imbalance(int imbalance, int dst_running, int imb_numa_nr)
  1201. {
  1202. /*
  1203. * Allow a NUMA imbalance if busy CPUs is less than the maximum
  1204. * threshold. Above this threshold, individual tasks may be contending
  1205. * for both memory bandwidth and any shared HT resources. This is an
  1206. * approximation as the number of running tasks may not be related to
  1207. * the number of busy CPUs due to sched_setaffinity.
  1208. */
  1209. if (dst_running > imb_numa_nr)
  1210. return imbalance;
  1211. /*
  1212. * Allow a small imbalance based on a simple pair of communicating
  1213. * tasks that remain local when the destination is lightly loaded.
  1214. */
  1215. if (imbalance <= NUMA_IMBALANCE_MIN)
  1216. return 0;
  1217. return imbalance;
  1218. }
  1219. #endif /* CONFIG_NUMA */
  1220. #ifdef CONFIG_NUMA_BALANCING
  1221. /*
  1222. * Approximate time to scan a full NUMA task in ms. The task scan period is
  1223. * calculated based on the tasks virtual memory size and
  1224. * numa_balancing_scan_size.
  1225. */
  1226. unsigned int sysctl_numa_balancing_scan_period_min = 1000;
  1227. unsigned int sysctl_numa_balancing_scan_period_max = 60000;
  1228. /* Portion of address space to scan in MB */
  1229. unsigned int sysctl_numa_balancing_scan_size = 256;
  1230. /* Scan @scan_size MB every @scan_period after an initial @scan_delay in ms */
  1231. unsigned int sysctl_numa_balancing_scan_delay = 1000;
  1232. /* The page with hint page fault latency < threshold in ms is considered hot */
  1233. unsigned int sysctl_numa_balancing_hot_threshold = MSEC_PER_SEC;
  1234. struct numa_group {
  1235. refcount_t refcount;
  1236. spinlock_t lock; /* nr_tasks, tasks */
  1237. int nr_tasks;
  1238. pid_t gid;
  1239. int active_nodes;
  1240. struct rcu_head rcu;
  1241. unsigned long total_faults;
  1242. unsigned long max_faults_cpu;
  1243. /*
  1244. * faults[] array is split into two regions: faults_mem and faults_cpu.
  1245. *
  1246. * Faults_cpu is used to decide whether memory should move
  1247. * towards the CPU. As a consequence, these stats are weighted
  1248. * more by CPU use than by memory faults.
  1249. */
  1250. unsigned long faults[];
  1251. };
  1252. /*
  1253. * For functions that can be called in multiple contexts that permit reading
  1254. * ->numa_group (see struct task_struct for locking rules).
  1255. */
  1256. static struct numa_group *deref_task_numa_group(struct task_struct *p)
  1257. {
  1258. return rcu_dereference_check(p->numa_group, p == current ||
  1259. (lockdep_is_held(__rq_lockp(task_rq(p))) && !READ_ONCE(p->on_cpu)));
  1260. }
  1261. static struct numa_group *deref_curr_numa_group(struct task_struct *p)
  1262. {
  1263. return rcu_dereference_protected(p->numa_group, p == current);
  1264. }
  1265. static inline unsigned long group_faults_priv(struct numa_group *ng);
  1266. static inline unsigned long group_faults_shared(struct numa_group *ng);
  1267. static unsigned int task_nr_scan_windows(struct task_struct *p)
  1268. {
  1269. unsigned long rss = 0;
  1270. unsigned long nr_scan_pages;
  1271. /*
  1272. * Calculations based on RSS as non-present and empty pages are skipped
  1273. * by the PTE scanner and NUMA hinting faults should be trapped based
  1274. * on resident pages
  1275. */
  1276. nr_scan_pages = sysctl_numa_balancing_scan_size << (20 - PAGE_SHIFT);
  1277. rss = get_mm_rss(p->mm);
  1278. if (!rss)
  1279. rss = nr_scan_pages;
  1280. rss = round_up(rss, nr_scan_pages);
  1281. return rss / nr_scan_pages;
  1282. }
  1283. /* For sanity's sake, never scan more PTEs than MAX_SCAN_WINDOW MB/sec. */
  1284. #define MAX_SCAN_WINDOW 2560
  1285. static unsigned int task_scan_min(struct task_struct *p)
  1286. {
  1287. unsigned int scan_size = READ_ONCE(sysctl_numa_balancing_scan_size);
  1288. unsigned int scan, floor;
  1289. unsigned int windows = 1;
  1290. if (scan_size < MAX_SCAN_WINDOW)
  1291. windows = MAX_SCAN_WINDOW / scan_size;
  1292. floor = 1000 / windows;
  1293. scan = sysctl_numa_balancing_scan_period_min / task_nr_scan_windows(p);
  1294. return max_t(unsigned int, floor, scan);
  1295. }
  1296. static unsigned int task_scan_start(struct task_struct *p)
  1297. {
  1298. unsigned long smin = task_scan_min(p);
  1299. unsigned long period = smin;
  1300. struct numa_group *ng;
  1301. /* Scale the maximum scan period with the amount of shared memory. */
  1302. rcu_read_lock();
  1303. ng = rcu_dereference(p->numa_group);
  1304. if (ng) {
  1305. unsigned long shared = group_faults_shared(ng);
  1306. unsigned long private = group_faults_priv(ng);
  1307. period *= refcount_read(&ng->refcount);
  1308. period *= shared + 1;
  1309. period /= private + shared + 1;
  1310. }
  1311. rcu_read_unlock();
  1312. return max(smin, period);
  1313. }
  1314. static unsigned int task_scan_max(struct task_struct *p)
  1315. {
  1316. unsigned long smin = task_scan_min(p);
  1317. unsigned long smax;
  1318. struct numa_group *ng;
  1319. /* Watch for min being lower than max due to floor calculations */
  1320. smax = sysctl_numa_balancing_scan_period_max / task_nr_scan_windows(p);
  1321. /* Scale the maximum scan period with the amount of shared memory. */
  1322. ng = deref_curr_numa_group(p);
  1323. if (ng) {
  1324. unsigned long shared = group_faults_shared(ng);
  1325. unsigned long private = group_faults_priv(ng);
  1326. unsigned long period = smax;
  1327. period *= refcount_read(&ng->refcount);
  1328. period *= shared + 1;
  1329. period /= private + shared + 1;
  1330. smax = max(smax, period);
  1331. }
  1332. return max(smin, smax);
  1333. }
  1334. static void account_numa_enqueue(struct rq *rq, struct task_struct *p)
  1335. {
  1336. rq->nr_numa_running += (p->numa_preferred_nid != NUMA_NO_NODE);
  1337. rq->nr_preferred_running += (p->numa_preferred_nid == task_node(p));
  1338. }
  1339. static void account_numa_dequeue(struct rq *rq, struct task_struct *p)
  1340. {
  1341. rq->nr_numa_running -= (p->numa_preferred_nid != NUMA_NO_NODE);
  1342. rq->nr_preferred_running -= (p->numa_preferred_nid == task_node(p));
  1343. }
  1344. /* Shared or private faults. */
  1345. #define NR_NUMA_HINT_FAULT_TYPES 2
  1346. /* Memory and CPU locality */
  1347. #define NR_NUMA_HINT_FAULT_STATS (NR_NUMA_HINT_FAULT_TYPES * 2)
  1348. /* Averaged statistics, and temporary buffers. */
  1349. #define NR_NUMA_HINT_FAULT_BUCKETS (NR_NUMA_HINT_FAULT_STATS * 2)
  1350. pid_t task_numa_group_id(struct task_struct *p)
  1351. {
  1352. struct numa_group *ng;
  1353. pid_t gid = 0;
  1354. rcu_read_lock();
  1355. ng = rcu_dereference(p->numa_group);
  1356. if (ng)
  1357. gid = ng->gid;
  1358. rcu_read_unlock();
  1359. return gid;
  1360. }
  1361. /*
  1362. * The averaged statistics, shared & private, memory & CPU,
  1363. * occupy the first half of the array. The second half of the
  1364. * array is for current counters, which are averaged into the
  1365. * first set by task_numa_placement.
  1366. */
  1367. static inline int task_faults_idx(enum numa_faults_stats s, int nid, int priv)
  1368. {
  1369. return NR_NUMA_HINT_FAULT_TYPES * (s * nr_node_ids + nid) + priv;
  1370. }
  1371. static inline unsigned long task_faults(struct task_struct *p, int nid)
  1372. {
  1373. if (!p->numa_faults)
  1374. return 0;
  1375. return p->numa_faults[task_faults_idx(NUMA_MEM, nid, 0)] +
  1376. p->numa_faults[task_faults_idx(NUMA_MEM, nid, 1)];
  1377. }
  1378. static inline unsigned long group_faults(struct task_struct *p, int nid)
  1379. {
  1380. struct numa_group *ng = deref_task_numa_group(p);
  1381. if (!ng)
  1382. return 0;
  1383. return ng->faults[task_faults_idx(NUMA_MEM, nid, 0)] +
  1384. ng->faults[task_faults_idx(NUMA_MEM, nid, 1)];
  1385. }
  1386. static inline unsigned long group_faults_cpu(struct numa_group *group, int nid)
  1387. {
  1388. return group->faults[task_faults_idx(NUMA_CPU, nid, 0)] +
  1389. group->faults[task_faults_idx(NUMA_CPU, nid, 1)];
  1390. }
  1391. static inline unsigned long group_faults_priv(struct numa_group *ng)
  1392. {
  1393. unsigned long faults = 0;
  1394. int node;
  1395. for_each_online_node(node) {
  1396. faults += ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
  1397. }
  1398. return faults;
  1399. }
  1400. static inline unsigned long group_faults_shared(struct numa_group *ng)
  1401. {
  1402. unsigned long faults = 0;
  1403. int node;
  1404. for_each_online_node(node) {
  1405. faults += ng->faults[task_faults_idx(NUMA_MEM, node, 0)];
  1406. }
  1407. return faults;
  1408. }
  1409. /*
  1410. * A node triggering more than 1/3 as many NUMA faults as the maximum is
  1411. * considered part of a numa group's pseudo-interleaving set. Migrations
  1412. * between these nodes are slowed down, to allow things to settle down.
  1413. */
  1414. #define ACTIVE_NODE_FRACTION 3
  1415. static bool numa_is_active_node(int nid, struct numa_group *ng)
  1416. {
  1417. return group_faults_cpu(ng, nid) * ACTIVE_NODE_FRACTION > ng->max_faults_cpu;
  1418. }
  1419. /* Handle placement on systems where not all nodes are directly connected. */
  1420. static unsigned long score_nearby_nodes(struct task_struct *p, int nid,
  1421. int lim_dist, bool task)
  1422. {
  1423. unsigned long score = 0;
  1424. int node, max_dist;
  1425. /*
  1426. * All nodes are directly connected, and the same distance
  1427. * from each other. No need for fancy placement algorithms.
  1428. */
  1429. if (sched_numa_topology_type == NUMA_DIRECT)
  1430. return 0;
  1431. /* sched_max_numa_distance may be changed in parallel. */
  1432. max_dist = READ_ONCE(sched_max_numa_distance);
  1433. /*
  1434. * This code is called for each node, introducing N^2 complexity,
  1435. * which should be OK given the number of nodes rarely exceeds 8.
  1436. */
  1437. for_each_online_node(node) {
  1438. unsigned long faults;
  1439. int dist = node_distance(nid, node);
  1440. /*
  1441. * The furthest away nodes in the system are not interesting
  1442. * for placement; nid was already counted.
  1443. */
  1444. if (dist >= max_dist || node == nid)
  1445. continue;
  1446. /*
  1447. * On systems with a backplane NUMA topology, compare groups
  1448. * of nodes, and move tasks towards the group with the most
  1449. * memory accesses. When comparing two nodes at distance
  1450. * "hoplimit", only nodes closer by than "hoplimit" are part
  1451. * of each group. Skip other nodes.
  1452. */
  1453. if (sched_numa_topology_type == NUMA_BACKPLANE && dist >= lim_dist)
  1454. continue;
  1455. /* Add up the faults from nearby nodes. */
  1456. if (task)
  1457. faults = task_faults(p, node);
  1458. else
  1459. faults = group_faults(p, node);
  1460. /*
  1461. * On systems with a glueless mesh NUMA topology, there are
  1462. * no fixed "groups of nodes". Instead, nodes that are not
  1463. * directly connected bounce traffic through intermediate
  1464. * nodes; a numa_group can occupy any set of nodes.
  1465. * The further away a node is, the less the faults count.
  1466. * This seems to result in good task placement.
  1467. */
  1468. if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
  1469. faults *= (max_dist - dist);
  1470. faults /= (max_dist - LOCAL_DISTANCE);
  1471. }
  1472. score += faults;
  1473. }
  1474. return score;
  1475. }
  1476. /*
  1477. * These return the fraction of accesses done by a particular task, or
  1478. * task group, on a particular numa node. The group weight is given a
  1479. * larger multiplier, in order to group tasks together that are almost
  1480. * evenly spread out between numa nodes.
  1481. */
  1482. static inline unsigned long task_weight(struct task_struct *p, int nid,
  1483. int dist)
  1484. {
  1485. unsigned long faults, total_faults;
  1486. if (!p->numa_faults)
  1487. return 0;
  1488. total_faults = p->total_numa_faults;
  1489. if (!total_faults)
  1490. return 0;
  1491. faults = task_faults(p, nid);
  1492. faults += score_nearby_nodes(p, nid, dist, true);
  1493. return 1000 * faults / total_faults;
  1494. }
  1495. static inline unsigned long group_weight(struct task_struct *p, int nid,
  1496. int dist)
  1497. {
  1498. struct numa_group *ng = deref_task_numa_group(p);
  1499. unsigned long faults, total_faults;
  1500. if (!ng)
  1501. return 0;
  1502. total_faults = ng->total_faults;
  1503. if (!total_faults)
  1504. return 0;
  1505. faults = group_faults(p, nid);
  1506. faults += score_nearby_nodes(p, nid, dist, false);
  1507. return 1000 * faults / total_faults;
  1508. }
  1509. /*
  1510. * If memory tiering mode is enabled, cpupid of slow memory page is
  1511. * used to record scan time instead of CPU and PID. When tiering mode
  1512. * is disabled at run time, the scan time (in cpupid) will be
  1513. * interpreted as CPU and PID. So CPU needs to be checked to avoid to
  1514. * access out of array bound.
  1515. */
  1516. static inline bool cpupid_valid(int cpupid)
  1517. {
  1518. return cpupid_to_cpu(cpupid) < nr_cpu_ids;
  1519. }
  1520. /*
  1521. * For memory tiering mode, if there are enough free pages (more than
  1522. * enough watermark defined here) in fast memory node, to take full
  1523. * advantage of fast memory capacity, all recently accessed slow
  1524. * memory pages will be migrated to fast memory node without
  1525. * considering hot threshold.
  1526. */
  1527. static bool pgdat_free_space_enough(struct pglist_data *pgdat)
  1528. {
  1529. int z;
  1530. unsigned long enough_wmark;
  1531. enough_wmark = max(1UL * 1024 * 1024 * 1024 >> PAGE_SHIFT,
  1532. pgdat->node_present_pages >> 4);
  1533. for (z = pgdat->nr_zones - 1; z >= 0; z--) {
  1534. struct zone *zone = pgdat->node_zones + z;
  1535. if (!populated_zone(zone))
  1536. continue;
  1537. if (zone_watermark_ok(zone, 0,
  1538. promo_wmark_pages(zone) + enough_wmark,
  1539. ZONE_MOVABLE, 0))
  1540. return true;
  1541. }
  1542. return false;
  1543. }
  1544. /*
  1545. * For memory tiering mode, when page tables are scanned, the scan
  1546. * time will be recorded in struct page in addition to make page
  1547. * PROT_NONE for slow memory page. So when the page is accessed, in
  1548. * hint page fault handler, the hint page fault latency is calculated
  1549. * via,
  1550. *
  1551. * hint page fault latency = hint page fault time - scan time
  1552. *
  1553. * The smaller the hint page fault latency, the higher the possibility
  1554. * for the page to be hot.
  1555. */
  1556. static int numa_hint_fault_latency(struct folio *folio)
  1557. {
  1558. int last_time, time;
  1559. time = jiffies_to_msecs(jiffies);
  1560. last_time = folio_xchg_access_time(folio, time);
  1561. return (time - last_time) & PAGE_ACCESS_TIME_MASK;
  1562. }
  1563. /*
  1564. * For memory tiering mode, too high promotion/demotion throughput may
  1565. * hurt application latency. So we provide a mechanism to rate limit
  1566. * the number of pages that are tried to be promoted.
  1567. */
  1568. static bool numa_promotion_rate_limit(struct pglist_data *pgdat,
  1569. unsigned long rate_limit, int nr)
  1570. {
  1571. unsigned long nr_cand;
  1572. unsigned int now, start;
  1573. now = jiffies_to_msecs(jiffies);
  1574. mod_node_page_state(pgdat, PGPROMOTE_CANDIDATE, nr);
  1575. nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE);
  1576. start = pgdat->nbp_rl_start;
  1577. if (now - start > MSEC_PER_SEC &&
  1578. cmpxchg(&pgdat->nbp_rl_start, start, now) == start)
  1579. pgdat->nbp_rl_nr_cand = nr_cand;
  1580. if (nr_cand - pgdat->nbp_rl_nr_cand >= rate_limit)
  1581. return true;
  1582. return false;
  1583. }
  1584. #define NUMA_MIGRATION_ADJUST_STEPS 16
  1585. static void numa_promotion_adjust_threshold(struct pglist_data *pgdat,
  1586. unsigned long rate_limit,
  1587. unsigned int ref_th)
  1588. {
  1589. unsigned int now, start, th_period, unit_th, th;
  1590. unsigned long nr_cand, ref_cand, diff_cand;
  1591. now = jiffies_to_msecs(jiffies);
  1592. th_period = sysctl_numa_balancing_scan_period_max;
  1593. start = pgdat->nbp_th_start;
  1594. if (now - start > th_period &&
  1595. cmpxchg(&pgdat->nbp_th_start, start, now) == start) {
  1596. ref_cand = rate_limit *
  1597. sysctl_numa_balancing_scan_period_max / MSEC_PER_SEC;
  1598. nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE);
  1599. diff_cand = nr_cand - pgdat->nbp_th_nr_cand;
  1600. unit_th = ref_th * 2 / NUMA_MIGRATION_ADJUST_STEPS;
  1601. th = pgdat->nbp_threshold ? : ref_th;
  1602. if (diff_cand > ref_cand * 11 / 10)
  1603. th = max(th - unit_th, unit_th);
  1604. else if (diff_cand < ref_cand * 9 / 10)
  1605. th = min(th + unit_th, ref_th * 2);
  1606. pgdat->nbp_th_nr_cand = nr_cand;
  1607. pgdat->nbp_threshold = th;
  1608. }
  1609. }
  1610. bool should_numa_migrate_memory(struct task_struct *p, struct folio *folio,
  1611. int src_nid, int dst_cpu)
  1612. {
  1613. struct numa_group *ng = deref_curr_numa_group(p);
  1614. int dst_nid = cpu_to_node(dst_cpu);
  1615. int last_cpupid, this_cpupid;
  1616. /*
  1617. * Cannot migrate to memoryless nodes.
  1618. */
  1619. if (!node_state(dst_nid, N_MEMORY))
  1620. return false;
  1621. /*
  1622. * The pages in slow memory node should be migrated according
  1623. * to hot/cold instead of private/shared.
  1624. */
  1625. if (folio_use_access_time(folio)) {
  1626. struct pglist_data *pgdat;
  1627. unsigned long rate_limit;
  1628. unsigned int latency, th, def_th;
  1629. pgdat = NODE_DATA(dst_nid);
  1630. if (pgdat_free_space_enough(pgdat)) {
  1631. /* workload changed, reset hot threshold */
  1632. pgdat->nbp_threshold = 0;
  1633. return true;
  1634. }
  1635. def_th = sysctl_numa_balancing_hot_threshold;
  1636. rate_limit = sysctl_numa_balancing_promote_rate_limit << \
  1637. (20 - PAGE_SHIFT);
  1638. numa_promotion_adjust_threshold(pgdat, rate_limit, def_th);
  1639. th = pgdat->nbp_threshold ? : def_th;
  1640. latency = numa_hint_fault_latency(folio);
  1641. if (latency >= th)
  1642. return false;
  1643. return !numa_promotion_rate_limit(pgdat, rate_limit,
  1644. folio_nr_pages(folio));
  1645. }
  1646. this_cpupid = cpu_pid_to_cpupid(dst_cpu, current->pid);
  1647. last_cpupid = folio_xchg_last_cpupid(folio, this_cpupid);
  1648. if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) &&
  1649. !node_is_toptier(src_nid) && !cpupid_valid(last_cpupid))
  1650. return false;
  1651. /*
  1652. * Allow first faults or private faults to migrate immediately early in
  1653. * the lifetime of a task. The magic number 4 is based on waiting for
  1654. * two full passes of the "multi-stage node selection" test that is
  1655. * executed below.
  1656. */
  1657. if ((p->numa_preferred_nid == NUMA_NO_NODE || p->numa_scan_seq <= 4) &&
  1658. (cpupid_pid_unset(last_cpupid) || cpupid_match_pid(p, last_cpupid)))
  1659. return true;
  1660. /*
  1661. * Multi-stage node selection is used in conjunction with a periodic
  1662. * migration fault to build a temporal task<->page relation. By using
  1663. * a two-stage filter we remove short/unlikely relations.
  1664. *
  1665. * Using P(p) ~ n_p / n_t as per frequentist probability, we can equate
  1666. * a task's usage of a particular page (n_p) per total usage of this
  1667. * page (n_t) (in a given time-span) to a probability.
  1668. *
  1669. * Our periodic faults will sample this probability and getting the
  1670. * same result twice in a row, given these samples are fully
  1671. * independent, is then given by P(n)^2, provided our sample period
  1672. * is sufficiently short compared to the usage pattern.
  1673. *
  1674. * This quadric squishes small probabilities, making it less likely we
  1675. * act on an unlikely task<->page relation.
  1676. */
  1677. if (!cpupid_pid_unset(last_cpupid) &&
  1678. cpupid_to_nid(last_cpupid) != dst_nid)
  1679. return false;
  1680. /* Always allow migrate on private faults */
  1681. if (cpupid_match_pid(p, last_cpupid))
  1682. return true;
  1683. /* A shared fault, but p->numa_group has not been set up yet. */
  1684. if (!ng)
  1685. return true;
  1686. /*
  1687. * Destination node is much more heavily used than the source
  1688. * node? Allow migration.
  1689. */
  1690. if (group_faults_cpu(ng, dst_nid) > group_faults_cpu(ng, src_nid) *
  1691. ACTIVE_NODE_FRACTION)
  1692. return true;
  1693. /*
  1694. * Distribute memory according to CPU & memory use on each node,
  1695. * with 3/4 hysteresis to avoid unnecessary memory migrations:
  1696. *
  1697. * faults_cpu(dst) 3 faults_cpu(src)
  1698. * --------------- * - > ---------------
  1699. * faults_mem(dst) 4 faults_mem(src)
  1700. */
  1701. return group_faults_cpu(ng, dst_nid) * group_faults(p, src_nid) * 3 >
  1702. group_faults_cpu(ng, src_nid) * group_faults(p, dst_nid) * 4;
  1703. }
  1704. /*
  1705. * 'numa_type' describes the node at the moment of load balancing.
  1706. */
  1707. enum numa_type {
  1708. /* The node has spare capacity that can be used to run more tasks. */
  1709. node_has_spare = 0,
  1710. /*
  1711. * The node is fully used and the tasks don't compete for more CPU
  1712. * cycles. Nevertheless, some tasks might wait before running.
  1713. */
  1714. node_fully_busy,
  1715. /*
  1716. * The node is overloaded and can't provide expected CPU cycles to all
  1717. * tasks.
  1718. */
  1719. node_overloaded
  1720. };
  1721. /* Cached statistics for all CPUs within a node */
  1722. struct numa_stats {
  1723. unsigned long load;
  1724. unsigned long runnable;
  1725. unsigned long util;
  1726. /* Total compute capacity of CPUs on a node */
  1727. unsigned long compute_capacity;
  1728. unsigned int nr_running;
  1729. unsigned int weight;
  1730. enum numa_type node_type;
  1731. int idle_cpu;
  1732. };
  1733. struct task_numa_env {
  1734. struct task_struct *p;
  1735. int src_cpu, src_nid;
  1736. int dst_cpu, dst_nid;
  1737. int imb_numa_nr;
  1738. struct numa_stats src_stats, dst_stats;
  1739. int imbalance_pct;
  1740. int dist;
  1741. struct task_struct *best_task;
  1742. long best_imp;
  1743. int best_cpu;
  1744. };
  1745. static unsigned long cpu_load(struct rq *rq);
  1746. static unsigned long cpu_runnable(struct rq *rq);
  1747. static inline enum
  1748. numa_type numa_classify(unsigned int imbalance_pct,
  1749. struct numa_stats *ns)
  1750. {
  1751. if ((ns->nr_running > ns->weight) &&
  1752. (((ns->compute_capacity * 100) < (ns->util * imbalance_pct)) ||
  1753. ((ns->compute_capacity * imbalance_pct) < (ns->runnable * 100))))
  1754. return node_overloaded;
  1755. if ((ns->nr_running < ns->weight) ||
  1756. (((ns->compute_capacity * 100) > (ns->util * imbalance_pct)) &&
  1757. ((ns->compute_capacity * imbalance_pct) > (ns->runnable * 100))))
  1758. return node_has_spare;
  1759. return node_fully_busy;
  1760. }
  1761. #ifdef CONFIG_SCHED_SMT
  1762. /* Forward declarations of select_idle_sibling helpers */
  1763. static inline bool test_idle_cores(int cpu);
  1764. static inline int numa_idle_core(int idle_core, int cpu)
  1765. {
  1766. if (!static_branch_likely(&sched_smt_present) ||
  1767. idle_core >= 0 || !test_idle_cores(cpu))
  1768. return idle_core;
  1769. /*
  1770. * Prefer cores instead of packing HT siblings
  1771. * and triggering future load balancing.
  1772. */
  1773. if (is_core_idle(cpu))
  1774. idle_core = cpu;
  1775. return idle_core;
  1776. }
  1777. #else
  1778. static inline int numa_idle_core(int idle_core, int cpu)
  1779. {
  1780. return idle_core;
  1781. }
  1782. #endif
  1783. /*
  1784. * Gather all necessary information to make NUMA balancing placement
  1785. * decisions that are compatible with standard load balancer. This
  1786. * borrows code and logic from update_sg_lb_stats but sharing a
  1787. * common implementation is impractical.
  1788. */
  1789. static void update_numa_stats(struct task_numa_env *env,
  1790. struct numa_stats *ns, int nid,
  1791. bool find_idle)
  1792. {
  1793. int cpu, idle_core = -1;
  1794. memset(ns, 0, sizeof(*ns));
  1795. ns->idle_cpu = -1;
  1796. rcu_read_lock();
  1797. for_each_cpu(cpu, cpumask_of_node(nid)) {
  1798. struct rq *rq = cpu_rq(cpu);
  1799. ns->load += cpu_load(rq);
  1800. ns->runnable += cpu_runnable(rq);
  1801. ns->util += cpu_util_cfs(cpu);
  1802. ns->nr_running += rq->cfs.h_nr_queued;
  1803. ns->compute_capacity += capacity_of(cpu);
  1804. if (find_idle && idle_core < 0 && !rq->nr_running && idle_cpu(cpu)) {
  1805. if (READ_ONCE(rq->numa_migrate_on) ||
  1806. !cpumask_test_cpu(cpu, env->p->cpus_ptr))
  1807. continue;
  1808. if (ns->idle_cpu == -1)
  1809. ns->idle_cpu = cpu;
  1810. idle_core = numa_idle_core(idle_core, cpu);
  1811. }
  1812. }
  1813. rcu_read_unlock();
  1814. ns->weight = cpumask_weight(cpumask_of_node(nid));
  1815. ns->node_type = numa_classify(env->imbalance_pct, ns);
  1816. if (idle_core >= 0)
  1817. ns->idle_cpu = idle_core;
  1818. }
  1819. static void task_numa_assign(struct task_numa_env *env,
  1820. struct task_struct *p, long imp)
  1821. {
  1822. struct rq *rq = cpu_rq(env->dst_cpu);
  1823. /* Check if run-queue part of active NUMA balance. */
  1824. if (env->best_cpu != env->dst_cpu && xchg(&rq->numa_migrate_on, 1)) {
  1825. int cpu;
  1826. int start = env->dst_cpu;
  1827. /* Find alternative idle CPU. */
  1828. for_each_cpu_wrap(cpu, cpumask_of_node(env->dst_nid), start + 1) {
  1829. if (cpu == env->best_cpu || !idle_cpu(cpu) ||
  1830. !cpumask_test_cpu(cpu, env->p->cpus_ptr)) {
  1831. continue;
  1832. }
  1833. env->dst_cpu = cpu;
  1834. rq = cpu_rq(env->dst_cpu);
  1835. if (!xchg(&rq->numa_migrate_on, 1))
  1836. goto assign;
  1837. }
  1838. /* Failed to find an alternative idle CPU */
  1839. return;
  1840. }
  1841. assign:
  1842. /*
  1843. * Clear previous best_cpu/rq numa-migrate flag, since task now
  1844. * found a better CPU to move/swap.
  1845. */
  1846. if (env->best_cpu != -1 && env->best_cpu != env->dst_cpu) {
  1847. rq = cpu_rq(env->best_cpu);
  1848. WRITE_ONCE(rq->numa_migrate_on, 0);
  1849. }
  1850. if (env->best_task)
  1851. put_task_struct(env->best_task);
  1852. if (p)
  1853. get_task_struct(p);
  1854. env->best_task = p;
  1855. env->best_imp = imp;
  1856. env->best_cpu = env->dst_cpu;
  1857. }
  1858. static bool load_too_imbalanced(long src_load, long dst_load,
  1859. struct task_numa_env *env)
  1860. {
  1861. long imb, old_imb;
  1862. long orig_src_load, orig_dst_load;
  1863. long src_capacity, dst_capacity;
  1864. /*
  1865. * The load is corrected for the CPU capacity available on each node.
  1866. *
  1867. * src_load dst_load
  1868. * ------------ vs ---------
  1869. * src_capacity dst_capacity
  1870. */
  1871. src_capacity = env->src_stats.compute_capacity;
  1872. dst_capacity = env->dst_stats.compute_capacity;
  1873. imb = abs(dst_load * src_capacity - src_load * dst_capacity);
  1874. orig_src_load = env->src_stats.load;
  1875. orig_dst_load = env->dst_stats.load;
  1876. old_imb = abs(orig_dst_load * src_capacity - orig_src_load * dst_capacity);
  1877. /* Would this change make things worse? */
  1878. return (imb > old_imb);
  1879. }
  1880. /*
  1881. * Maximum NUMA importance can be 1998 (2*999);
  1882. * SMALLIMP @ 30 would be close to 1998/64.
  1883. * Used to deter task migration.
  1884. */
  1885. #define SMALLIMP 30
  1886. /*
  1887. * This checks if the overall compute and NUMA accesses of the system would
  1888. * be improved if the source tasks was migrated to the target dst_cpu taking
  1889. * into account that it might be best if task running on the dst_cpu should
  1890. * be exchanged with the source task
  1891. */
  1892. static bool task_numa_compare(struct task_numa_env *env,
  1893. long taskimp, long groupimp, bool maymove)
  1894. {
  1895. struct numa_group *cur_ng, *p_ng = deref_curr_numa_group(env->p);
  1896. struct rq *dst_rq = cpu_rq(env->dst_cpu);
  1897. long imp = p_ng ? groupimp : taskimp;
  1898. struct task_struct *cur;
  1899. long src_load, dst_load;
  1900. int dist = env->dist;
  1901. long moveimp = imp;
  1902. long load;
  1903. bool stopsearch = false;
  1904. if (READ_ONCE(dst_rq->numa_migrate_on))
  1905. return false;
  1906. rcu_read_lock();
  1907. cur = rcu_dereference(dst_rq->curr);
  1908. if (cur && ((cur->flags & PF_EXITING) || is_idle_task(cur)))
  1909. cur = NULL;
  1910. /*
  1911. * Because we have preemption enabled we can get migrated around and
  1912. * end try selecting ourselves (current == env->p) as a swap candidate.
  1913. */
  1914. if (cur == env->p) {
  1915. stopsearch = true;
  1916. goto unlock;
  1917. }
  1918. if (!cur) {
  1919. if (maymove && moveimp >= env->best_imp)
  1920. goto assign;
  1921. else
  1922. goto unlock;
  1923. }
  1924. /* Skip this swap candidate if cannot move to the source cpu. */
  1925. if (!cpumask_test_cpu(env->src_cpu, cur->cpus_ptr))
  1926. goto unlock;
  1927. /*
  1928. * Skip this swap candidate if it is not moving to its preferred
  1929. * node and the best task is.
  1930. */
  1931. if (env->best_task &&
  1932. env->best_task->numa_preferred_nid == env->src_nid &&
  1933. cur->numa_preferred_nid != env->src_nid) {
  1934. goto unlock;
  1935. }
  1936. /*
  1937. * "imp" is the fault differential for the source task between the
  1938. * source and destination node. Calculate the total differential for
  1939. * the source task and potential destination task. The more negative
  1940. * the value is, the more remote accesses that would be expected to
  1941. * be incurred if the tasks were swapped.
  1942. *
  1943. * If dst and source tasks are in the same NUMA group, or not
  1944. * in any group then look only at task weights.
  1945. */
  1946. cur_ng = rcu_dereference(cur->numa_group);
  1947. if (cur_ng == p_ng) {
  1948. /*
  1949. * Do not swap within a group or between tasks that have
  1950. * no group if there is spare capacity. Swapping does
  1951. * not address the load imbalance and helps one task at
  1952. * the cost of punishing another.
  1953. */
  1954. if (env->dst_stats.node_type == node_has_spare)
  1955. goto unlock;
  1956. imp = taskimp + task_weight(cur, env->src_nid, dist) -
  1957. task_weight(cur, env->dst_nid, dist);
  1958. /*
  1959. * Add some hysteresis to prevent swapping the
  1960. * tasks within a group over tiny differences.
  1961. */
  1962. if (cur_ng)
  1963. imp -= imp / 16;
  1964. } else {
  1965. /*
  1966. * Compare the group weights. If a task is all by itself
  1967. * (not part of a group), use the task weight instead.
  1968. */
  1969. if (cur_ng && p_ng)
  1970. imp += group_weight(cur, env->src_nid, dist) -
  1971. group_weight(cur, env->dst_nid, dist);
  1972. else
  1973. imp += task_weight(cur, env->src_nid, dist) -
  1974. task_weight(cur, env->dst_nid, dist);
  1975. }
  1976. /* Discourage picking a task already on its preferred node */
  1977. if (cur->numa_preferred_nid == env->dst_nid)
  1978. imp -= imp / 16;
  1979. /*
  1980. * Encourage picking a task that moves to its preferred node.
  1981. * This potentially makes imp larger than it's maximum of
  1982. * 1998 (see SMALLIMP and task_weight for why) but in this
  1983. * case, it does not matter.
  1984. */
  1985. if (cur->numa_preferred_nid == env->src_nid)
  1986. imp += imp / 8;
  1987. if (maymove && moveimp > imp && moveimp > env->best_imp) {
  1988. imp = moveimp;
  1989. cur = NULL;
  1990. goto assign;
  1991. }
  1992. /*
  1993. * Prefer swapping with a task moving to its preferred node over a
  1994. * task that is not.
  1995. */
  1996. if (env->best_task && cur->numa_preferred_nid == env->src_nid &&
  1997. env->best_task->numa_preferred_nid != env->src_nid) {
  1998. goto assign;
  1999. }
  2000. /*
  2001. * If the NUMA importance is less than SMALLIMP,
  2002. * task migration might only result in ping pong
  2003. * of tasks and also hurt performance due to cache
  2004. * misses.
  2005. */
  2006. if (imp < SMALLIMP || imp <= env->best_imp + SMALLIMP / 2)
  2007. goto unlock;
  2008. /*
  2009. * In the overloaded case, try and keep the load balanced.
  2010. */
  2011. load = task_h_load(env->p) - task_h_load(cur);
  2012. if (!load)
  2013. goto assign;
  2014. dst_load = env->dst_stats.load + load;
  2015. src_load = env->src_stats.load - load;
  2016. if (load_too_imbalanced(src_load, dst_load, env))
  2017. goto unlock;
  2018. assign:
  2019. /* Evaluate an idle CPU for a task numa move. */
  2020. if (!cur) {
  2021. int cpu = env->dst_stats.idle_cpu;
  2022. /* Nothing cached so current CPU went idle since the search. */
  2023. if (cpu < 0)
  2024. cpu = env->dst_cpu;
  2025. /*
  2026. * If the CPU is no longer truly idle and the previous best CPU
  2027. * is, keep using it.
  2028. */
  2029. if (!idle_cpu(cpu) && env->best_cpu >= 0 &&
  2030. idle_cpu(env->best_cpu)) {
  2031. cpu = env->best_cpu;
  2032. }
  2033. env->dst_cpu = cpu;
  2034. }
  2035. task_numa_assign(env, cur, imp);
  2036. /*
  2037. * If a move to idle is allowed because there is capacity or load
  2038. * balance improves then stop the search. While a better swap
  2039. * candidate may exist, a search is not free.
  2040. */
  2041. if (maymove && !cur && env->best_cpu >= 0 && idle_cpu(env->best_cpu))
  2042. stopsearch = true;
  2043. /*
  2044. * If a swap candidate must be identified and the current best task
  2045. * moves its preferred node then stop the search.
  2046. */
  2047. if (!maymove && env->best_task &&
  2048. env->best_task->numa_preferred_nid == env->src_nid) {
  2049. stopsearch = true;
  2050. }
  2051. unlock:
  2052. rcu_read_unlock();
  2053. return stopsearch;
  2054. }
  2055. static void task_numa_find_cpu(struct task_numa_env *env,
  2056. long taskimp, long groupimp)
  2057. {
  2058. bool maymove = false;
  2059. int cpu;
  2060. /*
  2061. * If dst node has spare capacity, then check if there is an
  2062. * imbalance that would be overruled by the load balancer.
  2063. */
  2064. if (env->dst_stats.node_type == node_has_spare) {
  2065. unsigned int imbalance;
  2066. int src_running, dst_running;
  2067. /*
  2068. * Would movement cause an imbalance? Note that if src has
  2069. * more running tasks that the imbalance is ignored as the
  2070. * move improves the imbalance from the perspective of the
  2071. * CPU load balancer.
  2072. * */
  2073. src_running = env->src_stats.nr_running - 1;
  2074. dst_running = env->dst_stats.nr_running + 1;
  2075. imbalance = max(0, dst_running - src_running);
  2076. imbalance = adjust_numa_imbalance(imbalance, dst_running,
  2077. env->imb_numa_nr);
  2078. /* Use idle CPU if there is no imbalance */
  2079. if (!imbalance) {
  2080. maymove = true;
  2081. if (env->dst_stats.idle_cpu >= 0) {
  2082. env->dst_cpu = env->dst_stats.idle_cpu;
  2083. task_numa_assign(env, NULL, 0);
  2084. return;
  2085. }
  2086. }
  2087. } else {
  2088. long src_load, dst_load, load;
  2089. /*
  2090. * If the improvement from just moving env->p direction is better
  2091. * than swapping tasks around, check if a move is possible.
  2092. */
  2093. load = task_h_load(env->p);
  2094. dst_load = env->dst_stats.load + load;
  2095. src_load = env->src_stats.load - load;
  2096. maymove = !load_too_imbalanced(src_load, dst_load, env);
  2097. }
  2098. for_each_cpu(cpu, cpumask_of_node(env->dst_nid)) {
  2099. /* Skip this CPU if the source task cannot migrate */
  2100. if (!cpumask_test_cpu(cpu, env->p->cpus_ptr))
  2101. continue;
  2102. env->dst_cpu = cpu;
  2103. if (task_numa_compare(env, taskimp, groupimp, maymove))
  2104. break;
  2105. }
  2106. }
  2107. static int task_numa_migrate(struct task_struct *p)
  2108. {
  2109. struct task_numa_env env = {
  2110. .p = p,
  2111. .src_cpu = task_cpu(p),
  2112. .src_nid = task_node(p),
  2113. .imbalance_pct = 112,
  2114. .best_task = NULL,
  2115. .best_imp = 0,
  2116. .best_cpu = -1,
  2117. };
  2118. unsigned long taskweight, groupweight;
  2119. struct sched_domain *sd;
  2120. long taskimp, groupimp;
  2121. struct numa_group *ng;
  2122. struct rq *best_rq;
  2123. int nid, ret, dist;
  2124. /*
  2125. * Pick the lowest SD_NUMA domain, as that would have the smallest
  2126. * imbalance and would be the first to start moving tasks about.
  2127. *
  2128. * And we want to avoid any moving of tasks about, as that would create
  2129. * random movement of tasks -- counter the numa conditions we're trying
  2130. * to satisfy here.
  2131. */
  2132. rcu_read_lock();
  2133. sd = rcu_dereference(per_cpu(sd_numa, env.src_cpu));
  2134. if (sd) {
  2135. env.imbalance_pct = 100 + (sd->imbalance_pct - 100) / 2;
  2136. env.imb_numa_nr = sd->imb_numa_nr;
  2137. }
  2138. rcu_read_unlock();
  2139. /*
  2140. * Cpusets can break the scheduler domain tree into smaller
  2141. * balance domains, some of which do not cross NUMA boundaries.
  2142. * Tasks that are "trapped" in such domains cannot be migrated
  2143. * elsewhere, so there is no point in (re)trying.
  2144. */
  2145. if (unlikely(!sd)) {
  2146. sched_setnuma(p, task_node(p));
  2147. return -EINVAL;
  2148. }
  2149. env.dst_nid = p->numa_preferred_nid;
  2150. dist = env.dist = node_distance(env.src_nid, env.dst_nid);
  2151. taskweight = task_weight(p, env.src_nid, dist);
  2152. groupweight = group_weight(p, env.src_nid, dist);
  2153. update_numa_stats(&env, &env.src_stats, env.src_nid, false);
  2154. taskimp = task_weight(p, env.dst_nid, dist) - taskweight;
  2155. groupimp = group_weight(p, env.dst_nid, dist) - groupweight;
  2156. update_numa_stats(&env, &env.dst_stats, env.dst_nid, true);
  2157. /* Try to find a spot on the preferred nid. */
  2158. task_numa_find_cpu(&env, taskimp, groupimp);
  2159. /*
  2160. * Look at other nodes in these cases:
  2161. * - there is no space available on the preferred_nid
  2162. * - the task is part of a numa_group that is interleaved across
  2163. * multiple NUMA nodes; in order to better consolidate the group,
  2164. * we need to check other locations.
  2165. */
  2166. ng = deref_curr_numa_group(p);
  2167. if (env.best_cpu == -1 || (ng && ng->active_nodes > 1)) {
  2168. for_each_node_state(nid, N_CPU) {
  2169. if (nid == env.src_nid || nid == p->numa_preferred_nid)
  2170. continue;
  2171. dist = node_distance(env.src_nid, env.dst_nid);
  2172. if (sched_numa_topology_type == NUMA_BACKPLANE &&
  2173. dist != env.dist) {
  2174. taskweight = task_weight(p, env.src_nid, dist);
  2175. groupweight = group_weight(p, env.src_nid, dist);
  2176. }
  2177. /* Only consider nodes where both task and groups benefit */
  2178. taskimp = task_weight(p, nid, dist) - taskweight;
  2179. groupimp = group_weight(p, nid, dist) - groupweight;
  2180. if (taskimp < 0 && groupimp < 0)
  2181. continue;
  2182. env.dist = dist;
  2183. env.dst_nid = nid;
  2184. update_numa_stats(&env, &env.dst_stats, env.dst_nid, true);
  2185. task_numa_find_cpu(&env, taskimp, groupimp);
  2186. }
  2187. }
  2188. /*
  2189. * If the task is part of a workload that spans multiple NUMA nodes,
  2190. * and is migrating into one of the workload's active nodes, remember
  2191. * this node as the task's preferred numa node, so the workload can
  2192. * settle down.
  2193. * A task that migrated to a second choice node will be better off
  2194. * trying for a better one later. Do not set the preferred node here.
  2195. */
  2196. if (ng) {
  2197. if (env.best_cpu == -1)
  2198. nid = env.src_nid;
  2199. else
  2200. nid = cpu_to_node(env.best_cpu);
  2201. if (nid != p->numa_preferred_nid)
  2202. sched_setnuma(p, nid);
  2203. }
  2204. /* No better CPU than the current one was found. */
  2205. if (env.best_cpu == -1) {
  2206. trace_sched_stick_numa(p, env.src_cpu, NULL, -1);
  2207. return -EAGAIN;
  2208. }
  2209. best_rq = cpu_rq(env.best_cpu);
  2210. if (env.best_task == NULL) {
  2211. ret = migrate_task_to(p, env.best_cpu);
  2212. WRITE_ONCE(best_rq->numa_migrate_on, 0);
  2213. if (ret != 0)
  2214. trace_sched_stick_numa(p, env.src_cpu, NULL, env.best_cpu);
  2215. return ret;
  2216. }
  2217. ret = migrate_swap(p, env.best_task, env.best_cpu, env.src_cpu);
  2218. WRITE_ONCE(best_rq->numa_migrate_on, 0);
  2219. if (ret != 0)
  2220. trace_sched_stick_numa(p, env.src_cpu, env.best_task, env.best_cpu);
  2221. put_task_struct(env.best_task);
  2222. return ret;
  2223. }
  2224. /* Attempt to migrate a task to a CPU on the preferred node. */
  2225. static void numa_migrate_preferred(struct task_struct *p)
  2226. {
  2227. unsigned long interval = HZ;
  2228. /* This task has no NUMA fault statistics yet */
  2229. if (unlikely(p->numa_preferred_nid == NUMA_NO_NODE || !p->numa_faults))
  2230. return;
  2231. /* Periodically retry migrating the task to the preferred node */
  2232. interval = min(interval, msecs_to_jiffies(p->numa_scan_period) / 16);
  2233. p->numa_migrate_retry = jiffies + interval;
  2234. /* Success if task is already running on preferred CPU */
  2235. if (task_node(p) == p->numa_preferred_nid)
  2236. return;
  2237. /* Otherwise, try migrate to a CPU on the preferred node */
  2238. task_numa_migrate(p);
  2239. }
  2240. /*
  2241. * Find out how many nodes the workload is actively running on. Do this by
  2242. * tracking the nodes from which NUMA hinting faults are triggered. This can
  2243. * be different from the set of nodes where the workload's memory is currently
  2244. * located.
  2245. */
  2246. static void numa_group_count_active_nodes(struct numa_group *numa_group)
  2247. {
  2248. unsigned long faults, max_faults = 0;
  2249. int nid, active_nodes = 0;
  2250. for_each_node_state(nid, N_CPU) {
  2251. faults = group_faults_cpu(numa_group, nid);
  2252. if (faults > max_faults)
  2253. max_faults = faults;
  2254. }
  2255. for_each_node_state(nid, N_CPU) {
  2256. faults = group_faults_cpu(numa_group, nid);
  2257. if (faults * ACTIVE_NODE_FRACTION > max_faults)
  2258. active_nodes++;
  2259. }
  2260. numa_group->max_faults_cpu = max_faults;
  2261. numa_group->active_nodes = active_nodes;
  2262. }
  2263. /*
  2264. * When adapting the scan rate, the period is divided into NUMA_PERIOD_SLOTS
  2265. * increments. The more local the fault statistics are, the higher the scan
  2266. * period will be for the next scan window. If local/(local+remote) ratio is
  2267. * below NUMA_PERIOD_THRESHOLD (where range of ratio is 1..NUMA_PERIOD_SLOTS)
  2268. * the scan period will decrease. Aim for 70% local accesses.
  2269. */
  2270. #define NUMA_PERIOD_SLOTS 10
  2271. #define NUMA_PERIOD_THRESHOLD 7
  2272. /*
  2273. * Increase the scan period (slow down scanning) if the majority of
  2274. * our memory is already on our local node, or if the majority of
  2275. * the page accesses are shared with other processes.
  2276. * Otherwise, decrease the scan period.
  2277. */
  2278. static void update_task_scan_period(struct task_struct *p,
  2279. unsigned long shared, unsigned long private)
  2280. {
  2281. unsigned int period_slot;
  2282. int lr_ratio, ps_ratio;
  2283. int diff;
  2284. unsigned long remote = p->numa_faults_locality[0];
  2285. unsigned long local = p->numa_faults_locality[1];
  2286. /*
  2287. * If there were no record hinting faults then either the task is
  2288. * completely idle or all activity is in areas that are not of interest
  2289. * to automatic numa balancing. Related to that, if there were failed
  2290. * migration then it implies we are migrating too quickly or the local
  2291. * node is overloaded. In either case, scan slower
  2292. */
  2293. if (local + shared == 0 || p->numa_faults_locality[2]) {
  2294. p->numa_scan_period = min(p->numa_scan_period_max,
  2295. p->numa_scan_period << 1);
  2296. p->mm->numa_next_scan = jiffies +
  2297. msecs_to_jiffies(p->numa_scan_period);
  2298. return;
  2299. }
  2300. /*
  2301. * Prepare to scale scan period relative to the current period.
  2302. * == NUMA_PERIOD_THRESHOLD scan period stays the same
  2303. * < NUMA_PERIOD_THRESHOLD scan period decreases (scan faster)
  2304. * >= NUMA_PERIOD_THRESHOLD scan period increases (scan slower)
  2305. */
  2306. period_slot = DIV_ROUND_UP(p->numa_scan_period, NUMA_PERIOD_SLOTS);
  2307. lr_ratio = (local * NUMA_PERIOD_SLOTS) / (local + remote);
  2308. ps_ratio = (private * NUMA_PERIOD_SLOTS) / (private + shared);
  2309. if (ps_ratio >= NUMA_PERIOD_THRESHOLD) {
  2310. /*
  2311. * Most memory accesses are local. There is no need to
  2312. * do fast NUMA scanning, since memory is already local.
  2313. */
  2314. int slot = ps_ratio - NUMA_PERIOD_THRESHOLD;
  2315. if (!slot)
  2316. slot = 1;
  2317. diff = slot * period_slot;
  2318. } else if (lr_ratio >= NUMA_PERIOD_THRESHOLD) {
  2319. /*
  2320. * Most memory accesses are shared with other tasks.
  2321. * There is no point in continuing fast NUMA scanning,
  2322. * since other tasks may just move the memory elsewhere.
  2323. */
  2324. int slot = lr_ratio - NUMA_PERIOD_THRESHOLD;
  2325. if (!slot)
  2326. slot = 1;
  2327. diff = slot * period_slot;
  2328. } else {
  2329. /*
  2330. * Private memory faults exceed (SLOTS-THRESHOLD)/SLOTS,
  2331. * yet they are not on the local NUMA node. Speed up
  2332. * NUMA scanning to get the memory moved over.
  2333. */
  2334. int ratio = max(lr_ratio, ps_ratio);
  2335. diff = -(NUMA_PERIOD_THRESHOLD - ratio) * period_slot;
  2336. }
  2337. p->numa_scan_period = clamp(p->numa_scan_period + diff,
  2338. task_scan_min(p), task_scan_max(p));
  2339. memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
  2340. }
  2341. /*
  2342. * Get the fraction of time the task has been running since the last
  2343. * NUMA placement cycle. The scheduler keeps similar statistics, but
  2344. * decays those on a 32ms period, which is orders of magnitude off
  2345. * from the dozens-of-seconds NUMA balancing period. Use the scheduler
  2346. * stats only if the task is so new there are no NUMA statistics yet.
  2347. */
  2348. static u64 numa_get_avg_runtime(struct task_struct *p, u64 *period)
  2349. {
  2350. u64 runtime, delta, now;
  2351. /* Use the start of this time slice to avoid calculations. */
  2352. now = p->se.exec_start;
  2353. runtime = p->se.sum_exec_runtime;
  2354. if (p->last_task_numa_placement) {
  2355. delta = runtime - p->last_sum_exec_runtime;
  2356. *period = now - p->last_task_numa_placement;
  2357. /* Avoid time going backwards, prevent potential divide error: */
  2358. if (unlikely((s64)*period < 0))
  2359. *period = 0;
  2360. } else {
  2361. delta = p->se.avg.load_sum;
  2362. *period = LOAD_AVG_MAX;
  2363. }
  2364. p->last_sum_exec_runtime = runtime;
  2365. p->last_task_numa_placement = now;
  2366. return delta;
  2367. }
  2368. /*
  2369. * Determine the preferred nid for a task in a numa_group. This needs to
  2370. * be done in a way that produces consistent results with group_weight,
  2371. * otherwise workloads might not converge.
  2372. */
  2373. static int preferred_group_nid(struct task_struct *p, int nid)
  2374. {
  2375. nodemask_t nodes;
  2376. int dist;
  2377. /* Direct connections between all NUMA nodes. */
  2378. if (sched_numa_topology_type == NUMA_DIRECT)
  2379. return nid;
  2380. /*
  2381. * On a system with glueless mesh NUMA topology, group_weight
  2382. * scores nodes according to the number of NUMA hinting faults on
  2383. * both the node itself, and on nearby nodes.
  2384. */
  2385. if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
  2386. unsigned long score, max_score = 0;
  2387. int node, max_node = nid;
  2388. dist = sched_max_numa_distance;
  2389. for_each_node_state(node, N_CPU) {
  2390. score = group_weight(p, node, dist);
  2391. if (score > max_score) {
  2392. max_score = score;
  2393. max_node = node;
  2394. }
  2395. }
  2396. return max_node;
  2397. }
  2398. /*
  2399. * Finding the preferred nid in a system with NUMA backplane
  2400. * interconnect topology is more involved. The goal is to locate
  2401. * tasks from numa_groups near each other in the system, and
  2402. * untangle workloads from different sides of the system. This requires
  2403. * searching down the hierarchy of node groups, recursively searching
  2404. * inside the highest scoring group of nodes. The nodemask tricks
  2405. * keep the complexity of the search down.
  2406. */
  2407. nodes = node_states[N_CPU];
  2408. for (dist = sched_max_numa_distance; dist > LOCAL_DISTANCE; dist--) {
  2409. unsigned long max_faults = 0;
  2410. nodemask_t max_group = NODE_MASK_NONE;
  2411. int a, b;
  2412. /* Are there nodes at this distance from each other? */
  2413. if (!find_numa_distance(dist))
  2414. continue;
  2415. for_each_node_mask(a, nodes) {
  2416. unsigned long faults = 0;
  2417. nodemask_t this_group;
  2418. nodes_clear(this_group);
  2419. /* Sum group's NUMA faults; includes a==b case. */
  2420. for_each_node_mask(b, nodes) {
  2421. if (node_distance(a, b) < dist) {
  2422. faults += group_faults(p, b);
  2423. node_set(b, this_group);
  2424. node_clear(b, nodes);
  2425. }
  2426. }
  2427. /* Remember the top group. */
  2428. if (faults > max_faults) {
  2429. max_faults = faults;
  2430. max_group = this_group;
  2431. /*
  2432. * subtle: at the smallest distance there is
  2433. * just one node left in each "group", the
  2434. * winner is the preferred nid.
  2435. */
  2436. nid = a;
  2437. }
  2438. }
  2439. /* Next round, evaluate the nodes within max_group. */
  2440. if (!max_faults)
  2441. break;
  2442. nodes = max_group;
  2443. }
  2444. return nid;
  2445. }
  2446. static void task_numa_placement(struct task_struct *p)
  2447. {
  2448. int seq, nid, max_nid = NUMA_NO_NODE;
  2449. unsigned long max_faults = 0;
  2450. unsigned long fault_types[2] = { 0, 0 };
  2451. unsigned long total_faults;
  2452. u64 runtime, period;
  2453. spinlock_t *group_lock = NULL;
  2454. struct numa_group *ng;
  2455. /*
  2456. * The p->mm->numa_scan_seq field gets updated without
  2457. * exclusive access. Use READ_ONCE() here to ensure
  2458. * that the field is read in a single access:
  2459. */
  2460. seq = READ_ONCE(p->mm->numa_scan_seq);
  2461. if (p->numa_scan_seq == seq)
  2462. return;
  2463. p->numa_scan_seq = seq;
  2464. p->numa_scan_period_max = task_scan_max(p);
  2465. total_faults = p->numa_faults_locality[0] +
  2466. p->numa_faults_locality[1];
  2467. runtime = numa_get_avg_runtime(p, &period);
  2468. /* If the task is part of a group prevent parallel updates to group stats */
  2469. ng = deref_curr_numa_group(p);
  2470. if (ng) {
  2471. group_lock = &ng->lock;
  2472. spin_lock_irq(group_lock);
  2473. }
  2474. /* Find the node with the highest number of faults */
  2475. for_each_online_node(nid) {
  2476. /* Keep track of the offsets in numa_faults array */
  2477. int mem_idx, membuf_idx, cpu_idx, cpubuf_idx;
  2478. unsigned long faults = 0, group_faults = 0;
  2479. int priv;
  2480. for (priv = 0; priv < NR_NUMA_HINT_FAULT_TYPES; priv++) {
  2481. long diff, f_diff, f_weight;
  2482. mem_idx = task_faults_idx(NUMA_MEM, nid, priv);
  2483. membuf_idx = task_faults_idx(NUMA_MEMBUF, nid, priv);
  2484. cpu_idx = task_faults_idx(NUMA_CPU, nid, priv);
  2485. cpubuf_idx = task_faults_idx(NUMA_CPUBUF, nid, priv);
  2486. /* Decay existing window, copy faults since last scan */
  2487. diff = p->numa_faults[membuf_idx] - p->numa_faults[mem_idx] / 2;
  2488. fault_types[priv] += p->numa_faults[membuf_idx];
  2489. p->numa_faults[membuf_idx] = 0;
  2490. /*
  2491. * Normalize the faults_from, so all tasks in a group
  2492. * count according to CPU use, instead of by the raw
  2493. * number of faults. Tasks with little runtime have
  2494. * little over-all impact on throughput, and thus their
  2495. * faults are less important.
  2496. */
  2497. f_weight = div64_u64(runtime << 16, period + 1);
  2498. f_weight = (f_weight * p->numa_faults[cpubuf_idx]) /
  2499. (total_faults + 1);
  2500. f_diff = f_weight - p->numa_faults[cpu_idx] / 2;
  2501. p->numa_faults[cpubuf_idx] = 0;
  2502. p->numa_faults[mem_idx] += diff;
  2503. p->numa_faults[cpu_idx] += f_diff;
  2504. faults += p->numa_faults[mem_idx];
  2505. p->total_numa_faults += diff;
  2506. if (ng) {
  2507. /*
  2508. * safe because we can only change our own group
  2509. *
  2510. * mem_idx represents the offset for a given
  2511. * nid and priv in a specific region because it
  2512. * is at the beginning of the numa_faults array.
  2513. */
  2514. ng->faults[mem_idx] += diff;
  2515. ng->faults[cpu_idx] += f_diff;
  2516. ng->total_faults += diff;
  2517. group_faults += ng->faults[mem_idx];
  2518. }
  2519. }
  2520. if (!ng) {
  2521. if (faults > max_faults) {
  2522. max_faults = faults;
  2523. max_nid = nid;
  2524. }
  2525. } else if (group_faults > max_faults) {
  2526. max_faults = group_faults;
  2527. max_nid = nid;
  2528. }
  2529. }
  2530. /* Cannot migrate task to CPU-less node */
  2531. max_nid = numa_nearest_node(max_nid, N_CPU);
  2532. if (ng) {
  2533. numa_group_count_active_nodes(ng);
  2534. spin_unlock_irq(group_lock);
  2535. max_nid = preferred_group_nid(p, max_nid);
  2536. }
  2537. if (max_faults) {
  2538. /* Set the new preferred node */
  2539. if (max_nid != p->numa_preferred_nid)
  2540. sched_setnuma(p, max_nid);
  2541. }
  2542. update_task_scan_period(p, fault_types[0], fault_types[1]);
  2543. }
  2544. static inline int get_numa_group(struct numa_group *grp)
  2545. {
  2546. return refcount_inc_not_zero(&grp->refcount);
  2547. }
  2548. static inline void put_numa_group(struct numa_group *grp)
  2549. {
  2550. if (refcount_dec_and_test(&grp->refcount))
  2551. kfree_rcu(grp, rcu);
  2552. }
  2553. static void task_numa_group(struct task_struct *p, int cpupid, int flags,
  2554. int *priv)
  2555. {
  2556. struct numa_group *grp, *my_grp;
  2557. struct task_struct *tsk;
  2558. bool join = false;
  2559. int cpu = cpupid_to_cpu(cpupid);
  2560. int i;
  2561. if (unlikely(!deref_curr_numa_group(p))) {
  2562. unsigned int size = sizeof(struct numa_group) +
  2563. NR_NUMA_HINT_FAULT_STATS *
  2564. nr_node_ids * sizeof(unsigned long);
  2565. grp = kzalloc(size, GFP_KERNEL | __GFP_NOWARN);
  2566. if (!grp)
  2567. return;
  2568. refcount_set(&grp->refcount, 1);
  2569. grp->active_nodes = 1;
  2570. grp->max_faults_cpu = 0;
  2571. spin_lock_init(&grp->lock);
  2572. grp->gid = p->pid;
  2573. for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
  2574. grp->faults[i] = p->numa_faults[i];
  2575. grp->total_faults = p->total_numa_faults;
  2576. grp->nr_tasks++;
  2577. rcu_assign_pointer(p->numa_group, grp);
  2578. }
  2579. rcu_read_lock();
  2580. tsk = READ_ONCE(cpu_rq(cpu)->curr);
  2581. if (!cpupid_match_pid(tsk, cpupid))
  2582. goto no_join;
  2583. grp = rcu_dereference(tsk->numa_group);
  2584. if (!grp)
  2585. goto no_join;
  2586. my_grp = deref_curr_numa_group(p);
  2587. if (grp == my_grp)
  2588. goto no_join;
  2589. /*
  2590. * Only join the other group if its bigger; if we're the bigger group,
  2591. * the other task will join us.
  2592. */
  2593. if (my_grp->nr_tasks > grp->nr_tasks)
  2594. goto no_join;
  2595. /*
  2596. * Tie-break on the grp address.
  2597. */
  2598. if (my_grp->nr_tasks == grp->nr_tasks && my_grp > grp)
  2599. goto no_join;
  2600. /* Always join threads in the same process. */
  2601. if (tsk->mm == current->mm)
  2602. join = true;
  2603. /* Simple filter to avoid false positives due to PID collisions */
  2604. if (flags & TNF_SHARED)
  2605. join = true;
  2606. /* Update priv based on whether false sharing was detected */
  2607. *priv = !join;
  2608. if (join && !get_numa_group(grp))
  2609. goto no_join;
  2610. rcu_read_unlock();
  2611. if (!join)
  2612. return;
  2613. WARN_ON_ONCE(irqs_disabled());
  2614. double_lock_irq(&my_grp->lock, &grp->lock);
  2615. for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) {
  2616. my_grp->faults[i] -= p->numa_faults[i];
  2617. grp->faults[i] += p->numa_faults[i];
  2618. }
  2619. my_grp->total_faults -= p->total_numa_faults;
  2620. grp->total_faults += p->total_numa_faults;
  2621. my_grp->nr_tasks--;
  2622. grp->nr_tasks++;
  2623. spin_unlock(&my_grp->lock);
  2624. spin_unlock_irq(&grp->lock);
  2625. rcu_assign_pointer(p->numa_group, grp);
  2626. put_numa_group(my_grp);
  2627. return;
  2628. no_join:
  2629. rcu_read_unlock();
  2630. return;
  2631. }
  2632. /*
  2633. * Get rid of NUMA statistics associated with a task (either current or dead).
  2634. * If @final is set, the task is dead and has reached refcount zero, so we can
  2635. * safely free all relevant data structures. Otherwise, there might be
  2636. * concurrent reads from places like load balancing and procfs, and we should
  2637. * reset the data back to default state without freeing ->numa_faults.
  2638. */
  2639. void task_numa_free(struct task_struct *p, bool final)
  2640. {
  2641. /* safe: p either is current or is being freed by current */
  2642. struct numa_group *grp = rcu_dereference_raw(p->numa_group);
  2643. unsigned long *numa_faults = p->numa_faults;
  2644. unsigned long flags;
  2645. int i;
  2646. if (!numa_faults)
  2647. return;
  2648. if (grp) {
  2649. spin_lock_irqsave(&grp->lock, flags);
  2650. for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
  2651. grp->faults[i] -= p->numa_faults[i];
  2652. grp->total_faults -= p->total_numa_faults;
  2653. grp->nr_tasks--;
  2654. spin_unlock_irqrestore(&grp->lock, flags);
  2655. RCU_INIT_POINTER(p->numa_group, NULL);
  2656. put_numa_group(grp);
  2657. }
  2658. if (final) {
  2659. p->numa_faults = NULL;
  2660. kfree(numa_faults);
  2661. } else {
  2662. p->total_numa_faults = 0;
  2663. for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
  2664. numa_faults[i] = 0;
  2665. }
  2666. }
  2667. /*
  2668. * Got a PROT_NONE fault for a page on @node.
  2669. */
  2670. void task_numa_fault(int last_cpupid, int mem_node, int pages, int flags)
  2671. {
  2672. struct task_struct *p = current;
  2673. bool migrated = flags & TNF_MIGRATED;
  2674. int cpu_node = task_node(current);
  2675. int local = !!(flags & TNF_FAULT_LOCAL);
  2676. struct numa_group *ng;
  2677. int priv;
  2678. if (!static_branch_likely(&sched_numa_balancing))
  2679. return;
  2680. /* for example, ksmd faulting in a user's mm */
  2681. if (!p->mm)
  2682. return;
  2683. /*
  2684. * NUMA faults statistics are unnecessary for the slow memory
  2685. * node for memory tiering mode.
  2686. */
  2687. if (!node_is_toptier(mem_node) &&
  2688. (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING ||
  2689. !cpupid_valid(last_cpupid)))
  2690. return;
  2691. /* Allocate buffer to track faults on a per-node basis */
  2692. if (unlikely(!p->numa_faults)) {
  2693. int size = sizeof(*p->numa_faults) *
  2694. NR_NUMA_HINT_FAULT_BUCKETS * nr_node_ids;
  2695. p->numa_faults = kzalloc(size, GFP_KERNEL|__GFP_NOWARN);
  2696. if (!p->numa_faults)
  2697. return;
  2698. p->total_numa_faults = 0;
  2699. memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
  2700. }
  2701. /*
  2702. * First accesses are treated as private, otherwise consider accesses
  2703. * to be private if the accessing pid has not changed
  2704. */
  2705. if (unlikely(last_cpupid == (-1 & LAST_CPUPID_MASK))) {
  2706. priv = 1;
  2707. } else {
  2708. priv = cpupid_match_pid(p, last_cpupid);
  2709. if (!priv && !(flags & TNF_NO_GROUP))
  2710. task_numa_group(p, last_cpupid, flags, &priv);
  2711. }
  2712. /*
  2713. * If a workload spans multiple NUMA nodes, a shared fault that
  2714. * occurs wholly within the set of nodes that the workload is
  2715. * actively using should be counted as local. This allows the
  2716. * scan rate to slow down when a workload has settled down.
  2717. */
  2718. ng = deref_curr_numa_group(p);
  2719. if (!priv && !local && ng && ng->active_nodes > 1 &&
  2720. numa_is_active_node(cpu_node, ng) &&
  2721. numa_is_active_node(mem_node, ng))
  2722. local = 1;
  2723. /*
  2724. * Retry to migrate task to preferred node periodically, in case it
  2725. * previously failed, or the scheduler moved us.
  2726. */
  2727. if (time_after(jiffies, p->numa_migrate_retry)) {
  2728. task_numa_placement(p);
  2729. numa_migrate_preferred(p);
  2730. }
  2731. if (migrated)
  2732. p->numa_pages_migrated += pages;
  2733. if (flags & TNF_MIGRATE_FAIL)
  2734. p->numa_faults_locality[2] += pages;
  2735. p->numa_faults[task_faults_idx(NUMA_MEMBUF, mem_node, priv)] += pages;
  2736. p->numa_faults[task_faults_idx(NUMA_CPUBUF, cpu_node, priv)] += pages;
  2737. p->numa_faults_locality[local] += pages;
  2738. }
  2739. static void reset_ptenuma_scan(struct task_struct *p)
  2740. {
  2741. /*
  2742. * We only did a read acquisition of the mmap sem, so
  2743. * p->mm->numa_scan_seq is written to without exclusive access
  2744. * and the update is not guaranteed to be atomic. That's not
  2745. * much of an issue though, since this is just used for
  2746. * statistical sampling. Use READ_ONCE/WRITE_ONCE, which are not
  2747. * expensive, to avoid any form of compiler optimizations:
  2748. */
  2749. WRITE_ONCE(p->mm->numa_scan_seq, READ_ONCE(p->mm->numa_scan_seq) + 1);
  2750. p->mm->numa_scan_offset = 0;
  2751. }
  2752. static bool vma_is_accessed(struct mm_struct *mm, struct vm_area_struct *vma)
  2753. {
  2754. unsigned long pids;
  2755. /*
  2756. * Allow unconditional access first two times, so that all the (pages)
  2757. * of VMAs get prot_none fault introduced irrespective of accesses.
  2758. * This is also done to avoid any side effect of task scanning
  2759. * amplifying the unfairness of disjoint set of VMAs' access.
  2760. */
  2761. if ((READ_ONCE(current->mm->numa_scan_seq) - vma->numab_state->start_scan_seq) < 2)
  2762. return true;
  2763. pids = vma->numab_state->pids_active[0] | vma->numab_state->pids_active[1];
  2764. if (test_bit(hash_32(current->pid, ilog2(BITS_PER_LONG)), &pids))
  2765. return true;
  2766. /*
  2767. * Complete a scan that has already started regardless of PID access, or
  2768. * some VMAs may never be scanned in multi-threaded applications:
  2769. */
  2770. if (mm->numa_scan_offset > vma->vm_start) {
  2771. trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_IGNORE_PID);
  2772. return true;
  2773. }
  2774. /*
  2775. * This vma has not been accessed for a while, and if the number
  2776. * the threads in the same process is low, which means no other
  2777. * threads can help scan this vma, force a vma scan.
  2778. */
  2779. if (READ_ONCE(mm->numa_scan_seq) >
  2780. (vma->numab_state->prev_scan_seq + get_nr_threads(current)))
  2781. return true;
  2782. return false;
  2783. }
  2784. #define VMA_PID_RESET_PERIOD (4 * sysctl_numa_balancing_scan_delay)
  2785. /*
  2786. * The expensive part of numa migration is done from task_work context.
  2787. * Triggered from task_tick_numa().
  2788. */
  2789. static void task_numa_work(struct callback_head *work)
  2790. {
  2791. unsigned long migrate, next_scan, now = jiffies;
  2792. struct task_struct *p = current;
  2793. struct mm_struct *mm = p->mm;
  2794. u64 runtime = p->se.sum_exec_runtime;
  2795. struct vm_area_struct *vma;
  2796. unsigned long start, end;
  2797. unsigned long nr_pte_updates = 0;
  2798. long pages, virtpages;
  2799. struct vma_iterator vmi;
  2800. bool vma_pids_skipped;
  2801. bool vma_pids_forced = false;
  2802. SCHED_WARN_ON(p != container_of(work, struct task_struct, numa_work));
  2803. work->next = work;
  2804. /*
  2805. * Who cares about NUMA placement when they're dying.
  2806. *
  2807. * NOTE: make sure not to dereference p->mm before this check,
  2808. * exit_task_work() happens _after_ exit_mm() so we could be called
  2809. * without p->mm even though we still had it when we enqueued this
  2810. * work.
  2811. */
  2812. if (p->flags & PF_EXITING)
  2813. return;
  2814. if (!mm->numa_next_scan) {
  2815. mm->numa_next_scan = now +
  2816. msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
  2817. }
  2818. /*
  2819. * Enforce maximal scan/migration frequency..
  2820. */
  2821. migrate = mm->numa_next_scan;
  2822. if (time_before(now, migrate))
  2823. return;
  2824. if (p->numa_scan_period == 0) {
  2825. p->numa_scan_period_max = task_scan_max(p);
  2826. p->numa_scan_period = task_scan_start(p);
  2827. }
  2828. next_scan = now + msecs_to_jiffies(p->numa_scan_period);
  2829. if (!try_cmpxchg(&mm->numa_next_scan, &migrate, next_scan))
  2830. return;
  2831. /*
  2832. * Delay this task enough that another task of this mm will likely win
  2833. * the next time around.
  2834. */
  2835. p->node_stamp += 2 * TICK_NSEC;
  2836. pages = sysctl_numa_balancing_scan_size;
  2837. pages <<= 20 - PAGE_SHIFT; /* MB in pages */
  2838. virtpages = pages * 8; /* Scan up to this much virtual space */
  2839. if (!pages)
  2840. return;
  2841. if (!mmap_read_trylock(mm))
  2842. return;
  2843. /*
  2844. * VMAs are skipped if the current PID has not trapped a fault within
  2845. * the VMA recently. Allow scanning to be forced if there is no
  2846. * suitable VMA remaining.
  2847. */
  2848. vma_pids_skipped = false;
  2849. retry_pids:
  2850. start = mm->numa_scan_offset;
  2851. vma_iter_init(&vmi, mm, start);
  2852. vma = vma_next(&vmi);
  2853. if (!vma) {
  2854. reset_ptenuma_scan(p);
  2855. start = 0;
  2856. vma_iter_set(&vmi, start);
  2857. vma = vma_next(&vmi);
  2858. }
  2859. for (; vma; vma = vma_next(&vmi)) {
  2860. if (!vma_migratable(vma) || !vma_policy_mof(vma) ||
  2861. is_vm_hugetlb_page(vma) || (vma->vm_flags & VM_MIXEDMAP)) {
  2862. trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_UNSUITABLE);
  2863. continue;
  2864. }
  2865. /*
  2866. * Shared library pages mapped by multiple processes are not
  2867. * migrated as it is expected they are cache replicated. Avoid
  2868. * hinting faults in read-only file-backed mappings or the vDSO
  2869. * as migrating the pages will be of marginal benefit.
  2870. */
  2871. if (!vma->vm_mm ||
  2872. (vma->vm_file && (vma->vm_flags & (VM_READ|VM_WRITE)) == (VM_READ))) {
  2873. trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SHARED_RO);
  2874. continue;
  2875. }
  2876. /*
  2877. * Skip inaccessible VMAs to avoid any confusion between
  2878. * PROT_NONE and NUMA hinting PTEs
  2879. */
  2880. if (!vma_is_accessible(vma)) {
  2881. trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_INACCESSIBLE);
  2882. continue;
  2883. }
  2884. /* Initialise new per-VMA NUMAB state. */
  2885. if (!vma->numab_state) {
  2886. struct vma_numab_state *ptr;
  2887. ptr = kzalloc(sizeof(*ptr), GFP_KERNEL);
  2888. if (!ptr)
  2889. continue;
  2890. if (cmpxchg(&vma->numab_state, NULL, ptr)) {
  2891. kfree(ptr);
  2892. continue;
  2893. }
  2894. vma->numab_state->start_scan_seq = mm->numa_scan_seq;
  2895. vma->numab_state->next_scan = now +
  2896. msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
  2897. /* Reset happens after 4 times scan delay of scan start */
  2898. vma->numab_state->pids_active_reset = vma->numab_state->next_scan +
  2899. msecs_to_jiffies(VMA_PID_RESET_PERIOD);
  2900. /*
  2901. * Ensure prev_scan_seq does not match numa_scan_seq,
  2902. * to prevent VMAs being skipped prematurely on the
  2903. * first scan:
  2904. */
  2905. vma->numab_state->prev_scan_seq = mm->numa_scan_seq - 1;
  2906. }
  2907. /*
  2908. * Scanning the VMAs of short lived tasks add more overhead. So
  2909. * delay the scan for new VMAs.
  2910. */
  2911. if (mm->numa_scan_seq && time_before(jiffies,
  2912. vma->numab_state->next_scan)) {
  2913. trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SCAN_DELAY);
  2914. continue;
  2915. }
  2916. /* RESET access PIDs regularly for old VMAs. */
  2917. if (mm->numa_scan_seq &&
  2918. time_after(jiffies, vma->numab_state->pids_active_reset)) {
  2919. vma->numab_state->pids_active_reset = vma->numab_state->pids_active_reset +
  2920. msecs_to_jiffies(VMA_PID_RESET_PERIOD);
  2921. vma->numab_state->pids_active[0] = READ_ONCE(vma->numab_state->pids_active[1]);
  2922. vma->numab_state->pids_active[1] = 0;
  2923. }
  2924. /* Do not rescan VMAs twice within the same sequence. */
  2925. if (vma->numab_state->prev_scan_seq == mm->numa_scan_seq) {
  2926. mm->numa_scan_offset = vma->vm_end;
  2927. trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SEQ_COMPLETED);
  2928. continue;
  2929. }
  2930. /*
  2931. * Do not scan the VMA if task has not accessed it, unless no other
  2932. * VMA candidate exists.
  2933. */
  2934. if (!vma_pids_forced && !vma_is_accessed(mm, vma)) {
  2935. vma_pids_skipped = true;
  2936. trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_PID_INACTIVE);
  2937. continue;
  2938. }
  2939. do {
  2940. start = max(start, vma->vm_start);
  2941. end = ALIGN(start + (pages << PAGE_SHIFT), HPAGE_SIZE);
  2942. end = min(end, vma->vm_end);
  2943. nr_pte_updates = change_prot_numa(vma, start, end);
  2944. /*
  2945. * Try to scan sysctl_numa_balancing_size worth of
  2946. * hpages that have at least one present PTE that
  2947. * is not already PTE-numa. If the VMA contains
  2948. * areas that are unused or already full of prot_numa
  2949. * PTEs, scan up to virtpages, to skip through those
  2950. * areas faster.
  2951. */
  2952. if (nr_pte_updates)
  2953. pages -= (end - start) >> PAGE_SHIFT;
  2954. virtpages -= (end - start) >> PAGE_SHIFT;
  2955. start = end;
  2956. if (pages <= 0 || virtpages <= 0)
  2957. goto out;
  2958. cond_resched();
  2959. } while (end != vma->vm_end);
  2960. /* VMA scan is complete, do not scan until next sequence. */
  2961. vma->numab_state->prev_scan_seq = mm->numa_scan_seq;
  2962. /*
  2963. * Only force scan within one VMA at a time, to limit the
  2964. * cost of scanning a potentially uninteresting VMA.
  2965. */
  2966. if (vma_pids_forced)
  2967. break;
  2968. }
  2969. /*
  2970. * If no VMAs are remaining and VMAs were skipped due to the PID
  2971. * not accessing the VMA previously, then force a scan to ensure
  2972. * forward progress:
  2973. */
  2974. if (!vma && !vma_pids_forced && vma_pids_skipped) {
  2975. vma_pids_forced = true;
  2976. goto retry_pids;
  2977. }
  2978. out:
  2979. /*
  2980. * It is possible to reach the end of the VMA list but the last few
  2981. * VMAs are not guaranteed to the vma_migratable. If they are not, we
  2982. * would find the !migratable VMA on the next scan but not reset the
  2983. * scanner to the start so check it now.
  2984. */
  2985. if (vma)
  2986. mm->numa_scan_offset = start;
  2987. else
  2988. reset_ptenuma_scan(p);
  2989. mmap_read_unlock(mm);
  2990. /*
  2991. * Make sure tasks use at least 32x as much time to run other code
  2992. * than they used here, to limit NUMA PTE scanning overhead to 3% max.
  2993. * Usually update_task_scan_period slows down scanning enough; on an
  2994. * overloaded system we need to limit overhead on a per task basis.
  2995. */
  2996. if (unlikely(p->se.sum_exec_runtime != runtime)) {
  2997. u64 diff = p->se.sum_exec_runtime - runtime;
  2998. p->node_stamp += 32 * diff;
  2999. }
  3000. }
  3001. void init_numa_balancing(unsigned long clone_flags, struct task_struct *p)
  3002. {
  3003. int mm_users = 0;
  3004. struct mm_struct *mm = p->mm;
  3005. if (mm) {
  3006. mm_users = atomic_read(&mm->mm_users);
  3007. if (mm_users == 1) {
  3008. mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
  3009. mm->numa_scan_seq = 0;
  3010. }
  3011. }
  3012. p->node_stamp = 0;
  3013. p->numa_scan_seq = mm ? mm->numa_scan_seq : 0;
  3014. p->numa_scan_period = sysctl_numa_balancing_scan_delay;
  3015. p->numa_migrate_retry = 0;
  3016. /* Protect against double add, see task_tick_numa and task_numa_work */
  3017. p->numa_work.next = &p->numa_work;
  3018. p->numa_faults = NULL;
  3019. p->numa_pages_migrated = 0;
  3020. p->total_numa_faults = 0;
  3021. RCU_INIT_POINTER(p->numa_group, NULL);
  3022. p->last_task_numa_placement = 0;
  3023. p->last_sum_exec_runtime = 0;
  3024. init_task_work(&p->numa_work, task_numa_work);
  3025. /* New address space, reset the preferred nid */
  3026. if (!(clone_flags & CLONE_VM)) {
  3027. p->numa_preferred_nid = NUMA_NO_NODE;
  3028. return;
  3029. }
  3030. /*
  3031. * New thread, keep existing numa_preferred_nid which should be copied
  3032. * already by arch_dup_task_struct but stagger when scans start.
  3033. */
  3034. if (mm) {
  3035. unsigned int delay;
  3036. delay = min_t(unsigned int, task_scan_max(current),
  3037. current->numa_scan_period * mm_users * NSEC_PER_MSEC);
  3038. delay += 2 * TICK_NSEC;
  3039. p->node_stamp = delay;
  3040. }
  3041. }
  3042. /*
  3043. * Drive the periodic memory faults..
  3044. */
  3045. static void task_tick_numa(struct rq *rq, struct task_struct *curr)
  3046. {
  3047. struct callback_head *work = &curr->numa_work;
  3048. u64 period, now;
  3049. /*
  3050. * We don't care about NUMA placement if we don't have memory.
  3051. */
  3052. if (!curr->mm || (curr->flags & (PF_EXITING | PF_KTHREAD)) || work->next != work)
  3053. return;
  3054. /*
  3055. * Using runtime rather than walltime has the dual advantage that
  3056. * we (mostly) drive the selection from busy threads and that the
  3057. * task needs to have done some actual work before we bother with
  3058. * NUMA placement.
  3059. */
  3060. now = curr->se.sum_exec_runtime;
  3061. period = (u64)curr->numa_scan_period * NSEC_PER_MSEC;
  3062. if (now > curr->node_stamp + period) {
  3063. if (!curr->node_stamp)
  3064. curr->numa_scan_period = task_scan_start(curr);
  3065. curr->node_stamp += period;
  3066. if (!time_before(jiffies, curr->mm->numa_next_scan))
  3067. task_work_add(curr, work, TWA_RESUME);
  3068. }
  3069. }
  3070. static void update_scan_period(struct task_struct *p, int new_cpu)
  3071. {
  3072. int src_nid = cpu_to_node(task_cpu(p));
  3073. int dst_nid = cpu_to_node(new_cpu);
  3074. if (!static_branch_likely(&sched_numa_balancing))
  3075. return;
  3076. if (!p->mm || !p->numa_faults || (p->flags & PF_EXITING))
  3077. return;
  3078. if (src_nid == dst_nid)
  3079. return;
  3080. /*
  3081. * Allow resets if faults have been trapped before one scan
  3082. * has completed. This is most likely due to a new task that
  3083. * is pulled cross-node due to wakeups or load balancing.
  3084. */
  3085. if (p->numa_scan_seq) {
  3086. /*
  3087. * Avoid scan adjustments if moving to the preferred
  3088. * node or if the task was not previously running on
  3089. * the preferred node.
  3090. */
  3091. if (dst_nid == p->numa_preferred_nid ||
  3092. (p->numa_preferred_nid != NUMA_NO_NODE &&
  3093. src_nid != p->numa_preferred_nid))
  3094. return;
  3095. }
  3096. p->numa_scan_period = task_scan_start(p);
  3097. }
  3098. #else
  3099. static void task_tick_numa(struct rq *rq, struct task_struct *curr)
  3100. {
  3101. }
  3102. static inline void account_numa_enqueue(struct rq *rq, struct task_struct *p)
  3103. {
  3104. }
  3105. static inline void account_numa_dequeue(struct rq *rq, struct task_struct *p)
  3106. {
  3107. }
  3108. static inline void update_scan_period(struct task_struct *p, int new_cpu)
  3109. {
  3110. }
  3111. #endif /* CONFIG_NUMA_BALANCING */
  3112. static void
  3113. account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
  3114. {
  3115. update_load_add(&cfs_rq->load, se->load.weight);
  3116. #ifdef CONFIG_SMP
  3117. if (entity_is_task(se)) {
  3118. struct rq *rq = rq_of(cfs_rq);
  3119. account_numa_enqueue(rq, task_of(se));
  3120. list_add(&se->group_node, &rq->cfs_tasks);
  3121. }
  3122. #endif
  3123. cfs_rq->nr_running++;
  3124. if (se_is_idle(se))
  3125. cfs_rq->idle_nr_running++;
  3126. }
  3127. static void
  3128. account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
  3129. {
  3130. update_load_sub(&cfs_rq->load, se->load.weight);
  3131. #ifdef CONFIG_SMP
  3132. if (entity_is_task(se)) {
  3133. account_numa_dequeue(rq_of(cfs_rq), task_of(se));
  3134. list_del_init(&se->group_node);
  3135. }
  3136. #endif
  3137. cfs_rq->nr_running--;
  3138. if (se_is_idle(se))
  3139. cfs_rq->idle_nr_running--;
  3140. }
  3141. /*
  3142. * Signed add and clamp on underflow.
  3143. *
  3144. * Explicitly do a load-store to ensure the intermediate value never hits
  3145. * memory. This allows lockless observations without ever seeing the negative
  3146. * values.
  3147. */
  3148. #define add_positive(_ptr, _val) do { \
  3149. typeof(_ptr) ptr = (_ptr); \
  3150. typeof(_val) val = (_val); \
  3151. typeof(*ptr) res, var = READ_ONCE(*ptr); \
  3152. \
  3153. res = var + val; \
  3154. \
  3155. if (val < 0 && res > var) \
  3156. res = 0; \
  3157. \
  3158. WRITE_ONCE(*ptr, res); \
  3159. } while (0)
  3160. /*
  3161. * Unsigned subtract and clamp on underflow.
  3162. *
  3163. * Explicitly do a load-store to ensure the intermediate value never hits
  3164. * memory. This allows lockless observations without ever seeing the negative
  3165. * values.
  3166. */
  3167. #define sub_positive(_ptr, _val) do { \
  3168. typeof(_ptr) ptr = (_ptr); \
  3169. typeof(*ptr) val = (_val); \
  3170. typeof(*ptr) res, var = READ_ONCE(*ptr); \
  3171. res = var - val; \
  3172. if (res > var) \
  3173. res = 0; \
  3174. WRITE_ONCE(*ptr, res); \
  3175. } while (0)
  3176. /*
  3177. * Remove and clamp on negative, from a local variable.
  3178. *
  3179. * A variant of sub_positive(), which does not use explicit load-store
  3180. * and is thus optimized for local variable updates.
  3181. */
  3182. #define lsub_positive(_ptr, _val) do { \
  3183. typeof(_ptr) ptr = (_ptr); \
  3184. *ptr -= min_t(typeof(*ptr), *ptr, _val); \
  3185. } while (0)
  3186. #ifdef CONFIG_SMP
  3187. static inline void
  3188. enqueue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
  3189. {
  3190. cfs_rq->avg.load_avg += se->avg.load_avg;
  3191. cfs_rq->avg.load_sum += se_weight(se) * se->avg.load_sum;
  3192. }
  3193. static inline void
  3194. dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
  3195. {
  3196. sub_positive(&cfs_rq->avg.load_avg, se->avg.load_avg);
  3197. sub_positive(&cfs_rq->avg.load_sum, se_weight(se) * se->avg.load_sum);
  3198. /* See update_cfs_rq_load_avg() */
  3199. cfs_rq->avg.load_sum = max_t(u32, cfs_rq->avg.load_sum,
  3200. cfs_rq->avg.load_avg * PELT_MIN_DIVIDER);
  3201. }
  3202. #else
  3203. static inline void
  3204. enqueue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) { }
  3205. static inline void
  3206. dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) { }
  3207. #endif
  3208. static void reweight_eevdf(struct sched_entity *se, u64 avruntime,
  3209. unsigned long weight)
  3210. {
  3211. unsigned long old_weight = se->load.weight;
  3212. s64 vlag, vslice;
  3213. /*
  3214. * VRUNTIME
  3215. * --------
  3216. *
  3217. * COROLLARY #1: The virtual runtime of the entity needs to be
  3218. * adjusted if re-weight at !0-lag point.
  3219. *
  3220. * Proof: For contradiction assume this is not true, so we can
  3221. * re-weight without changing vruntime at !0-lag point.
  3222. *
  3223. * Weight VRuntime Avg-VRuntime
  3224. * before w v V
  3225. * after w' v' V'
  3226. *
  3227. * Since lag needs to be preserved through re-weight:
  3228. *
  3229. * lag = (V - v)*w = (V'- v')*w', where v = v'
  3230. * ==> V' = (V - v)*w/w' + v (1)
  3231. *
  3232. * Let W be the total weight of the entities before reweight,
  3233. * since V' is the new weighted average of entities:
  3234. *
  3235. * V' = (WV + w'v - wv) / (W + w' - w) (2)
  3236. *
  3237. * by using (1) & (2) we obtain:
  3238. *
  3239. * (WV + w'v - wv) / (W + w' - w) = (V - v)*w/w' + v
  3240. * ==> (WV-Wv+Wv+w'v-wv)/(W+w'-w) = (V - v)*w/w' + v
  3241. * ==> (WV - Wv)/(W + w' - w) + v = (V - v)*w/w' + v
  3242. * ==> (V - v)*W/(W + w' - w) = (V - v)*w/w' (3)
  3243. *
  3244. * Since we are doing at !0-lag point which means V != v, we
  3245. * can simplify (3):
  3246. *
  3247. * ==> W / (W + w' - w) = w / w'
  3248. * ==> Ww' = Ww + ww' - ww
  3249. * ==> W * (w' - w) = w * (w' - w)
  3250. * ==> W = w (re-weight indicates w' != w)
  3251. *
  3252. * So the cfs_rq contains only one entity, hence vruntime of
  3253. * the entity @v should always equal to the cfs_rq's weighted
  3254. * average vruntime @V, which means we will always re-weight
  3255. * at 0-lag point, thus breach assumption. Proof completed.
  3256. *
  3257. *
  3258. * COROLLARY #2: Re-weight does NOT affect weighted average
  3259. * vruntime of all the entities.
  3260. *
  3261. * Proof: According to corollary #1, Eq. (1) should be:
  3262. *
  3263. * (V - v)*w = (V' - v')*w'
  3264. * ==> v' = V' - (V - v)*w/w' (4)
  3265. *
  3266. * According to the weighted average formula, we have:
  3267. *
  3268. * V' = (WV - wv + w'v') / (W - w + w')
  3269. * = (WV - wv + w'(V' - (V - v)w/w')) / (W - w + w')
  3270. * = (WV - wv + w'V' - Vw + wv) / (W - w + w')
  3271. * = (WV + w'V' - Vw) / (W - w + w')
  3272. *
  3273. * ==> V'*(W - w + w') = WV + w'V' - Vw
  3274. * ==> V' * (W - w) = (W - w) * V (5)
  3275. *
  3276. * If the entity is the only one in the cfs_rq, then reweight
  3277. * always occurs at 0-lag point, so V won't change. Or else
  3278. * there are other entities, hence W != w, then Eq. (5) turns
  3279. * into V' = V. So V won't change in either case, proof done.
  3280. *
  3281. *
  3282. * So according to corollary #1 & #2, the effect of re-weight
  3283. * on vruntime should be:
  3284. *
  3285. * v' = V' - (V - v) * w / w' (4)
  3286. * = V - (V - v) * w / w'
  3287. * = V - vl * w / w'
  3288. * = V - vl'
  3289. */
  3290. if (avruntime != se->vruntime) {
  3291. vlag = entity_lag(avruntime, se);
  3292. vlag = div_s64(vlag * old_weight, weight);
  3293. se->vruntime = avruntime - vlag;
  3294. }
  3295. /*
  3296. * DEADLINE
  3297. * --------
  3298. *
  3299. * When the weight changes, the virtual time slope changes and
  3300. * we should adjust the relative virtual deadline accordingly.
  3301. *
  3302. * d' = v' + (d - v)*w/w'
  3303. * = V' - (V - v)*w/w' + (d - v)*w/w'
  3304. * = V - (V - v)*w/w' + (d - v)*w/w'
  3305. * = V + (d - V)*w/w'
  3306. */
  3307. vslice = (s64)(se->deadline - avruntime);
  3308. vslice = div_s64(vslice * old_weight, weight);
  3309. se->deadline = avruntime + vslice;
  3310. }
  3311. static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se,
  3312. unsigned long weight)
  3313. {
  3314. bool curr = cfs_rq->curr == se;
  3315. u64 avruntime;
  3316. if (se->on_rq) {
  3317. /* commit outstanding execution time */
  3318. update_curr(cfs_rq);
  3319. avruntime = avg_vruntime(cfs_rq);
  3320. if (!curr)
  3321. __dequeue_entity(cfs_rq, se);
  3322. update_load_sub(&cfs_rq->load, se->load.weight);
  3323. }
  3324. dequeue_load_avg(cfs_rq, se);
  3325. if (se->on_rq) {
  3326. reweight_eevdf(se, avruntime, weight);
  3327. } else {
  3328. /*
  3329. * Because we keep se->vlag = V - v_i, while: lag_i = w_i*(V - v_i),
  3330. * we need to scale se->vlag when w_i changes.
  3331. */
  3332. se->vlag = div_s64(se->vlag * se->load.weight, weight);
  3333. }
  3334. update_load_set(&se->load, weight);
  3335. #ifdef CONFIG_SMP
  3336. do {
  3337. u32 divider = get_pelt_divider(&se->avg);
  3338. se->avg.load_avg = div_u64(se_weight(se) * se->avg.load_sum, divider);
  3339. } while (0);
  3340. #endif
  3341. enqueue_load_avg(cfs_rq, se);
  3342. if (se->on_rq) {
  3343. update_load_add(&cfs_rq->load, se->load.weight);
  3344. if (!curr)
  3345. __enqueue_entity(cfs_rq, se);
  3346. /*
  3347. * The entity's vruntime has been adjusted, so let's check
  3348. * whether the rq-wide min_vruntime needs updated too. Since
  3349. * the calculations above require stable min_vruntime rather
  3350. * than up-to-date one, we do the update at the end of the
  3351. * reweight process.
  3352. */
  3353. update_min_vruntime(cfs_rq);
  3354. }
  3355. }
  3356. static void reweight_task_fair(struct rq *rq, struct task_struct *p,
  3357. const struct load_weight *lw)
  3358. {
  3359. struct sched_entity *se = &p->se;
  3360. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  3361. struct load_weight *load = &se->load;
  3362. reweight_entity(cfs_rq, se, lw->weight);
  3363. load->inv_weight = lw->inv_weight;
  3364. }
  3365. static inline int throttled_hierarchy(struct cfs_rq *cfs_rq);
  3366. #ifdef CONFIG_FAIR_GROUP_SCHED
  3367. #ifdef CONFIG_SMP
  3368. /*
  3369. * All this does is approximate the hierarchical proportion which includes that
  3370. * global sum we all love to hate.
  3371. *
  3372. * That is, the weight of a group entity, is the proportional share of the
  3373. * group weight based on the group runqueue weights. That is:
  3374. *
  3375. * tg->weight * grq->load.weight
  3376. * ge->load.weight = ----------------------------- (1)
  3377. * \Sum grq->load.weight
  3378. *
  3379. * Now, because computing that sum is prohibitively expensive to compute (been
  3380. * there, done that) we approximate it with this average stuff. The average
  3381. * moves slower and therefore the approximation is cheaper and more stable.
  3382. *
  3383. * So instead of the above, we substitute:
  3384. *
  3385. * grq->load.weight -> grq->avg.load_avg (2)
  3386. *
  3387. * which yields the following:
  3388. *
  3389. * tg->weight * grq->avg.load_avg
  3390. * ge->load.weight = ------------------------------ (3)
  3391. * tg->load_avg
  3392. *
  3393. * Where: tg->load_avg ~= \Sum grq->avg.load_avg
  3394. *
  3395. * That is shares_avg, and it is right (given the approximation (2)).
  3396. *
  3397. * The problem with it is that because the average is slow -- it was designed
  3398. * to be exactly that of course -- this leads to transients in boundary
  3399. * conditions. In specific, the case where the group was idle and we start the
  3400. * one task. It takes time for our CPU's grq->avg.load_avg to build up,
  3401. * yielding bad latency etc..
  3402. *
  3403. * Now, in that special case (1) reduces to:
  3404. *
  3405. * tg->weight * grq->load.weight
  3406. * ge->load.weight = ----------------------------- = tg->weight (4)
  3407. * grp->load.weight
  3408. *
  3409. * That is, the sum collapses because all other CPUs are idle; the UP scenario.
  3410. *
  3411. * So what we do is modify our approximation (3) to approach (4) in the (near)
  3412. * UP case, like:
  3413. *
  3414. * ge->load.weight =
  3415. *
  3416. * tg->weight * grq->load.weight
  3417. * --------------------------------------------------- (5)
  3418. * tg->load_avg - grq->avg.load_avg + grq->load.weight
  3419. *
  3420. * But because grq->load.weight can drop to 0, resulting in a divide by zero,
  3421. * we need to use grq->avg.load_avg as its lower bound, which then gives:
  3422. *
  3423. *
  3424. * tg->weight * grq->load.weight
  3425. * ge->load.weight = ----------------------------- (6)
  3426. * tg_load_avg'
  3427. *
  3428. * Where:
  3429. *
  3430. * tg_load_avg' = tg->load_avg - grq->avg.load_avg +
  3431. * max(grq->load.weight, grq->avg.load_avg)
  3432. *
  3433. * And that is shares_weight and is icky. In the (near) UP case it approaches
  3434. * (4) while in the normal case it approaches (3). It consistently
  3435. * overestimates the ge->load.weight and therefore:
  3436. *
  3437. * \Sum ge->load.weight >= tg->weight
  3438. *
  3439. * hence icky!
  3440. */
  3441. static long calc_group_shares(struct cfs_rq *cfs_rq)
  3442. {
  3443. long tg_weight, tg_shares, load, shares;
  3444. struct task_group *tg = cfs_rq->tg;
  3445. tg_shares = READ_ONCE(tg->shares);
  3446. load = max(scale_load_down(cfs_rq->load.weight), cfs_rq->avg.load_avg);
  3447. tg_weight = atomic_long_read(&tg->load_avg);
  3448. /* Ensure tg_weight >= load */
  3449. tg_weight -= cfs_rq->tg_load_avg_contrib;
  3450. tg_weight += load;
  3451. shares = (tg_shares * load);
  3452. if (tg_weight)
  3453. shares /= tg_weight;
  3454. /*
  3455. * MIN_SHARES has to be unscaled here to support per-CPU partitioning
  3456. * of a group with small tg->shares value. It is a floor value which is
  3457. * assigned as a minimum load.weight to the sched_entity representing
  3458. * the group on a CPU.
  3459. *
  3460. * E.g. on 64-bit for a group with tg->shares of scale_load(15)=15*1024
  3461. * on an 8-core system with 8 tasks each runnable on one CPU shares has
  3462. * to be 15*1024*1/8=1920 instead of scale_load(MIN_SHARES)=2*1024. In
  3463. * case no task is runnable on a CPU MIN_SHARES=2 should be returned
  3464. * instead of 0.
  3465. */
  3466. return clamp_t(long, shares, MIN_SHARES, tg_shares);
  3467. }
  3468. #endif /* CONFIG_SMP */
  3469. /*
  3470. * Recomputes the group entity based on the current state of its group
  3471. * runqueue.
  3472. */
  3473. static void update_cfs_group(struct sched_entity *se)
  3474. {
  3475. struct cfs_rq *gcfs_rq = group_cfs_rq(se);
  3476. long shares;
  3477. /*
  3478. * When a group becomes empty, preserve its weight. This matters for
  3479. * DELAY_DEQUEUE.
  3480. */
  3481. if (!gcfs_rq || !gcfs_rq->load.weight)
  3482. return;
  3483. if (throttled_hierarchy(gcfs_rq))
  3484. return;
  3485. #ifndef CONFIG_SMP
  3486. shares = READ_ONCE(gcfs_rq->tg->shares);
  3487. #else
  3488. shares = calc_group_shares(gcfs_rq);
  3489. #endif
  3490. if (unlikely(se->load.weight != shares))
  3491. reweight_entity(cfs_rq_of(se), se, shares);
  3492. }
  3493. #else /* CONFIG_FAIR_GROUP_SCHED */
  3494. static inline void update_cfs_group(struct sched_entity *se)
  3495. {
  3496. }
  3497. #endif /* CONFIG_FAIR_GROUP_SCHED */
  3498. static inline void cfs_rq_util_change(struct cfs_rq *cfs_rq, int flags)
  3499. {
  3500. struct rq *rq = rq_of(cfs_rq);
  3501. if (&rq->cfs == cfs_rq) {
  3502. /*
  3503. * There are a few boundary cases this might miss but it should
  3504. * get called often enough that that should (hopefully) not be
  3505. * a real problem.
  3506. *
  3507. * It will not get called when we go idle, because the idle
  3508. * thread is a different class (!fair), nor will the utilization
  3509. * number include things like RT tasks.
  3510. *
  3511. * As is, the util number is not freq-invariant (we'd have to
  3512. * implement arch_scale_freq_capacity() for that).
  3513. *
  3514. * See cpu_util_cfs().
  3515. */
  3516. cpufreq_update_util(rq, flags);
  3517. }
  3518. }
  3519. #ifdef CONFIG_SMP
  3520. static inline bool load_avg_is_decayed(struct sched_avg *sa)
  3521. {
  3522. if (sa->load_sum)
  3523. return false;
  3524. if (sa->util_sum)
  3525. return false;
  3526. if (sa->runnable_sum)
  3527. return false;
  3528. /*
  3529. * _avg must be null when _sum are null because _avg = _sum / divider
  3530. * Make sure that rounding and/or propagation of PELT values never
  3531. * break this.
  3532. */
  3533. SCHED_WARN_ON(sa->load_avg ||
  3534. sa->util_avg ||
  3535. sa->runnable_avg);
  3536. return true;
  3537. }
  3538. static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq)
  3539. {
  3540. return u64_u32_load_copy(cfs_rq->avg.last_update_time,
  3541. cfs_rq->last_update_time_copy);
  3542. }
  3543. #ifdef CONFIG_FAIR_GROUP_SCHED
  3544. /*
  3545. * Because list_add_leaf_cfs_rq always places a child cfs_rq on the list
  3546. * immediately before a parent cfs_rq, and cfs_rqs are removed from the list
  3547. * bottom-up, we only have to test whether the cfs_rq before us on the list
  3548. * is our child.
  3549. * If cfs_rq is not on the list, test whether a child needs its to be added to
  3550. * connect a branch to the tree * (see list_add_leaf_cfs_rq() for details).
  3551. */
  3552. static inline bool child_cfs_rq_on_list(struct cfs_rq *cfs_rq)
  3553. {
  3554. struct cfs_rq *prev_cfs_rq;
  3555. struct list_head *prev;
  3556. struct rq *rq = rq_of(cfs_rq);
  3557. if (cfs_rq->on_list) {
  3558. prev = cfs_rq->leaf_cfs_rq_list.prev;
  3559. } else {
  3560. prev = rq->tmp_alone_branch;
  3561. }
  3562. if (prev == &rq->leaf_cfs_rq_list)
  3563. return false;
  3564. prev_cfs_rq = container_of(prev, struct cfs_rq, leaf_cfs_rq_list);
  3565. return (prev_cfs_rq->tg->parent == cfs_rq->tg);
  3566. }
  3567. static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq)
  3568. {
  3569. if (cfs_rq->load.weight)
  3570. return false;
  3571. if (!load_avg_is_decayed(&cfs_rq->avg))
  3572. return false;
  3573. if (child_cfs_rq_on_list(cfs_rq))
  3574. return false;
  3575. return true;
  3576. }
  3577. /**
  3578. * update_tg_load_avg - update the tg's load avg
  3579. * @cfs_rq: the cfs_rq whose avg changed
  3580. *
  3581. * This function 'ensures': tg->load_avg := \Sum tg->cfs_rq[]->avg.load.
  3582. * However, because tg->load_avg is a global value there are performance
  3583. * considerations.
  3584. *
  3585. * In order to avoid having to look at the other cfs_rq's, we use a
  3586. * differential update where we store the last value we propagated. This in
  3587. * turn allows skipping updates if the differential is 'small'.
  3588. *
  3589. * Updating tg's load_avg is necessary before update_cfs_share().
  3590. */
  3591. static inline void update_tg_load_avg(struct cfs_rq *cfs_rq)
  3592. {
  3593. long delta;
  3594. u64 now;
  3595. /*
  3596. * No need to update load_avg for root_task_group as it is not used.
  3597. */
  3598. if (cfs_rq->tg == &root_task_group)
  3599. return;
  3600. /* rq has been offline and doesn't contribute to the share anymore: */
  3601. if (!cpu_active(cpu_of(rq_of(cfs_rq))))
  3602. return;
  3603. /*
  3604. * For migration heavy workloads, access to tg->load_avg can be
  3605. * unbound. Limit the update rate to at most once per ms.
  3606. */
  3607. now = sched_clock_cpu(cpu_of(rq_of(cfs_rq)));
  3608. if (now - cfs_rq->last_update_tg_load_avg < NSEC_PER_MSEC)
  3609. return;
  3610. delta = cfs_rq->avg.load_avg - cfs_rq->tg_load_avg_contrib;
  3611. if (abs(delta) > cfs_rq->tg_load_avg_contrib / 64) {
  3612. atomic_long_add(delta, &cfs_rq->tg->load_avg);
  3613. cfs_rq->tg_load_avg_contrib = cfs_rq->avg.load_avg;
  3614. cfs_rq->last_update_tg_load_avg = now;
  3615. }
  3616. }
  3617. static inline void clear_tg_load_avg(struct cfs_rq *cfs_rq)
  3618. {
  3619. long delta;
  3620. u64 now;
  3621. /*
  3622. * No need to update load_avg for root_task_group, as it is not used.
  3623. */
  3624. if (cfs_rq->tg == &root_task_group)
  3625. return;
  3626. now = sched_clock_cpu(cpu_of(rq_of(cfs_rq)));
  3627. delta = 0 - cfs_rq->tg_load_avg_contrib;
  3628. atomic_long_add(delta, &cfs_rq->tg->load_avg);
  3629. cfs_rq->tg_load_avg_contrib = 0;
  3630. cfs_rq->last_update_tg_load_avg = now;
  3631. }
  3632. /* CPU offline callback: */
  3633. static void __maybe_unused clear_tg_offline_cfs_rqs(struct rq *rq)
  3634. {
  3635. struct task_group *tg;
  3636. lockdep_assert_rq_held(rq);
  3637. /*
  3638. * The rq clock has already been updated in
  3639. * set_rq_offline(), so we should skip updating
  3640. * the rq clock again in unthrottle_cfs_rq().
  3641. */
  3642. rq_clock_start_loop_update(rq);
  3643. rcu_read_lock();
  3644. list_for_each_entry_rcu(tg, &task_groups, list) {
  3645. struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
  3646. clear_tg_load_avg(cfs_rq);
  3647. }
  3648. rcu_read_unlock();
  3649. rq_clock_stop_loop_update(rq);
  3650. }
  3651. /*
  3652. * Called within set_task_rq() right before setting a task's CPU. The
  3653. * caller only guarantees p->pi_lock is held; no other assumptions,
  3654. * including the state of rq->lock, should be made.
  3655. */
  3656. void set_task_rq_fair(struct sched_entity *se,
  3657. struct cfs_rq *prev, struct cfs_rq *next)
  3658. {
  3659. u64 p_last_update_time;
  3660. u64 n_last_update_time;
  3661. if (!sched_feat(ATTACH_AGE_LOAD))
  3662. return;
  3663. /*
  3664. * We are supposed to update the task to "current" time, then its up to
  3665. * date and ready to go to new CPU/cfs_rq. But we have difficulty in
  3666. * getting what current time is, so simply throw away the out-of-date
  3667. * time. This will result in the wakee task is less decayed, but giving
  3668. * the wakee more load sounds not bad.
  3669. */
  3670. if (!(se->avg.last_update_time && prev))
  3671. return;
  3672. p_last_update_time = cfs_rq_last_update_time(prev);
  3673. n_last_update_time = cfs_rq_last_update_time(next);
  3674. __update_load_avg_blocked_se(p_last_update_time, se);
  3675. se->avg.last_update_time = n_last_update_time;
  3676. }
  3677. /*
  3678. * When on migration a sched_entity joins/leaves the PELT hierarchy, we need to
  3679. * propagate its contribution. The key to this propagation is the invariant
  3680. * that for each group:
  3681. *
  3682. * ge->avg == grq->avg (1)
  3683. *
  3684. * _IFF_ we look at the pure running and runnable sums. Because they
  3685. * represent the very same entity, just at different points in the hierarchy.
  3686. *
  3687. * Per the above update_tg_cfs_util() and update_tg_cfs_runnable() are trivial
  3688. * and simply copies the running/runnable sum over (but still wrong, because
  3689. * the group entity and group rq do not have their PELT windows aligned).
  3690. *
  3691. * However, update_tg_cfs_load() is more complex. So we have:
  3692. *
  3693. * ge->avg.load_avg = ge->load.weight * ge->avg.runnable_avg (2)
  3694. *
  3695. * And since, like util, the runnable part should be directly transferable,
  3696. * the following would _appear_ to be the straight forward approach:
  3697. *
  3698. * grq->avg.load_avg = grq->load.weight * grq->avg.runnable_avg (3)
  3699. *
  3700. * And per (1) we have:
  3701. *
  3702. * ge->avg.runnable_avg == grq->avg.runnable_avg
  3703. *
  3704. * Which gives:
  3705. *
  3706. * ge->load.weight * grq->avg.load_avg
  3707. * ge->avg.load_avg = ----------------------------------- (4)
  3708. * grq->load.weight
  3709. *
  3710. * Except that is wrong!
  3711. *
  3712. * Because while for entities historical weight is not important and we
  3713. * really only care about our future and therefore can consider a pure
  3714. * runnable sum, runqueues can NOT do this.
  3715. *
  3716. * We specifically want runqueues to have a load_avg that includes
  3717. * historical weights. Those represent the blocked load, the load we expect
  3718. * to (shortly) return to us. This only works by keeping the weights as
  3719. * integral part of the sum. We therefore cannot decompose as per (3).
  3720. *
  3721. * Another reason this doesn't work is that runnable isn't a 0-sum entity.
  3722. * Imagine a rq with 2 tasks that each are runnable 2/3 of the time. Then the
  3723. * rq itself is runnable anywhere between 2/3 and 1 depending on how the
  3724. * runnable section of these tasks overlap (or not). If they were to perfectly
  3725. * align the rq as a whole would be runnable 2/3 of the time. If however we
  3726. * always have at least 1 runnable task, the rq as a whole is always runnable.
  3727. *
  3728. * So we'll have to approximate.. :/
  3729. *
  3730. * Given the constraint:
  3731. *
  3732. * ge->avg.running_sum <= ge->avg.runnable_sum <= LOAD_AVG_MAX
  3733. *
  3734. * We can construct a rule that adds runnable to a rq by assuming minimal
  3735. * overlap.
  3736. *
  3737. * On removal, we'll assume each task is equally runnable; which yields:
  3738. *
  3739. * grq->avg.runnable_sum = grq->avg.load_sum / grq->load.weight
  3740. *
  3741. * XXX: only do this for the part of runnable > running ?
  3742. *
  3743. */
  3744. static inline void
  3745. update_tg_cfs_util(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
  3746. {
  3747. long delta_sum, delta_avg = gcfs_rq->avg.util_avg - se->avg.util_avg;
  3748. u32 new_sum, divider;
  3749. /* Nothing to update */
  3750. if (!delta_avg)
  3751. return;
  3752. /*
  3753. * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
  3754. * See ___update_load_avg() for details.
  3755. */
  3756. divider = get_pelt_divider(&cfs_rq->avg);
  3757. /* Set new sched_entity's utilization */
  3758. se->avg.util_avg = gcfs_rq->avg.util_avg;
  3759. new_sum = se->avg.util_avg * divider;
  3760. delta_sum = (long)new_sum - (long)se->avg.util_sum;
  3761. se->avg.util_sum = new_sum;
  3762. /* Update parent cfs_rq utilization */
  3763. add_positive(&cfs_rq->avg.util_avg, delta_avg);
  3764. add_positive(&cfs_rq->avg.util_sum, delta_sum);
  3765. /* See update_cfs_rq_load_avg() */
  3766. cfs_rq->avg.util_sum = max_t(u32, cfs_rq->avg.util_sum,
  3767. cfs_rq->avg.util_avg * PELT_MIN_DIVIDER);
  3768. }
  3769. static inline void
  3770. update_tg_cfs_runnable(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
  3771. {
  3772. long delta_sum, delta_avg = gcfs_rq->avg.runnable_avg - se->avg.runnable_avg;
  3773. u32 new_sum, divider;
  3774. /* Nothing to update */
  3775. if (!delta_avg)
  3776. return;
  3777. /*
  3778. * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
  3779. * See ___update_load_avg() for details.
  3780. */
  3781. divider = get_pelt_divider(&cfs_rq->avg);
  3782. /* Set new sched_entity's runnable */
  3783. se->avg.runnable_avg = gcfs_rq->avg.runnable_avg;
  3784. new_sum = se->avg.runnable_avg * divider;
  3785. delta_sum = (long)new_sum - (long)se->avg.runnable_sum;
  3786. se->avg.runnable_sum = new_sum;
  3787. /* Update parent cfs_rq runnable */
  3788. add_positive(&cfs_rq->avg.runnable_avg, delta_avg);
  3789. add_positive(&cfs_rq->avg.runnable_sum, delta_sum);
  3790. /* See update_cfs_rq_load_avg() */
  3791. cfs_rq->avg.runnable_sum = max_t(u32, cfs_rq->avg.runnable_sum,
  3792. cfs_rq->avg.runnable_avg * PELT_MIN_DIVIDER);
  3793. }
  3794. static inline void
  3795. update_tg_cfs_load(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
  3796. {
  3797. long delta_avg, running_sum, runnable_sum = gcfs_rq->prop_runnable_sum;
  3798. unsigned long load_avg;
  3799. u64 load_sum = 0;
  3800. s64 delta_sum;
  3801. u32 divider;
  3802. if (!runnable_sum)
  3803. return;
  3804. gcfs_rq->prop_runnable_sum = 0;
  3805. /*
  3806. * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
  3807. * See ___update_load_avg() for details.
  3808. */
  3809. divider = get_pelt_divider(&cfs_rq->avg);
  3810. if (runnable_sum >= 0) {
  3811. /*
  3812. * Add runnable; clip at LOAD_AVG_MAX. Reflects that until
  3813. * the CPU is saturated running == runnable.
  3814. */
  3815. runnable_sum += se->avg.load_sum;
  3816. runnable_sum = min_t(long, runnable_sum, divider);
  3817. } else {
  3818. /*
  3819. * Estimate the new unweighted runnable_sum of the gcfs_rq by
  3820. * assuming all tasks are equally runnable.
  3821. */
  3822. if (scale_load_down(gcfs_rq->load.weight)) {
  3823. load_sum = div_u64(gcfs_rq->avg.load_sum,
  3824. scale_load_down(gcfs_rq->load.weight));
  3825. }
  3826. /* But make sure to not inflate se's runnable */
  3827. runnable_sum = min(se->avg.load_sum, load_sum);
  3828. }
  3829. /*
  3830. * runnable_sum can't be lower than running_sum
  3831. * Rescale running sum to be in the same range as runnable sum
  3832. * running_sum is in [0 : LOAD_AVG_MAX << SCHED_CAPACITY_SHIFT]
  3833. * runnable_sum is in [0 : LOAD_AVG_MAX]
  3834. */
  3835. running_sum = se->avg.util_sum >> SCHED_CAPACITY_SHIFT;
  3836. runnable_sum = max(runnable_sum, running_sum);
  3837. load_sum = se_weight(se) * runnable_sum;
  3838. load_avg = div_u64(load_sum, divider);
  3839. delta_avg = load_avg - se->avg.load_avg;
  3840. if (!delta_avg)
  3841. return;
  3842. delta_sum = load_sum - (s64)se_weight(se) * se->avg.load_sum;
  3843. se->avg.load_sum = runnable_sum;
  3844. se->avg.load_avg = load_avg;
  3845. add_positive(&cfs_rq->avg.load_avg, delta_avg);
  3846. add_positive(&cfs_rq->avg.load_sum, delta_sum);
  3847. /* See update_cfs_rq_load_avg() */
  3848. cfs_rq->avg.load_sum = max_t(u32, cfs_rq->avg.load_sum,
  3849. cfs_rq->avg.load_avg * PELT_MIN_DIVIDER);
  3850. }
  3851. static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum)
  3852. {
  3853. cfs_rq->propagate = 1;
  3854. cfs_rq->prop_runnable_sum += runnable_sum;
  3855. }
  3856. /* Update task and its cfs_rq load average */
  3857. static inline int propagate_entity_load_avg(struct sched_entity *se)
  3858. {
  3859. struct cfs_rq *cfs_rq, *gcfs_rq;
  3860. if (entity_is_task(se))
  3861. return 0;
  3862. gcfs_rq = group_cfs_rq(se);
  3863. if (!gcfs_rq->propagate)
  3864. return 0;
  3865. gcfs_rq->propagate = 0;
  3866. cfs_rq = cfs_rq_of(se);
  3867. add_tg_cfs_propagate(cfs_rq, gcfs_rq->prop_runnable_sum);
  3868. update_tg_cfs_util(cfs_rq, se, gcfs_rq);
  3869. update_tg_cfs_runnable(cfs_rq, se, gcfs_rq);
  3870. update_tg_cfs_load(cfs_rq, se, gcfs_rq);
  3871. trace_pelt_cfs_tp(cfs_rq);
  3872. trace_pelt_se_tp(se);
  3873. return 1;
  3874. }
  3875. /*
  3876. * Check if we need to update the load and the utilization of a blocked
  3877. * group_entity:
  3878. */
  3879. static inline bool skip_blocked_update(struct sched_entity *se)
  3880. {
  3881. struct cfs_rq *gcfs_rq = group_cfs_rq(se);
  3882. /*
  3883. * If sched_entity still have not zero load or utilization, we have to
  3884. * decay it:
  3885. */
  3886. if (se->avg.load_avg || se->avg.util_avg)
  3887. return false;
  3888. /*
  3889. * If there is a pending propagation, we have to update the load and
  3890. * the utilization of the sched_entity:
  3891. */
  3892. if (gcfs_rq->propagate)
  3893. return false;
  3894. /*
  3895. * Otherwise, the load and the utilization of the sched_entity is
  3896. * already zero and there is no pending propagation, so it will be a
  3897. * waste of time to try to decay it:
  3898. */
  3899. return true;
  3900. }
  3901. #else /* CONFIG_FAIR_GROUP_SCHED */
  3902. static inline void update_tg_load_avg(struct cfs_rq *cfs_rq) {}
  3903. static inline void clear_tg_offline_cfs_rqs(struct rq *rq) {}
  3904. static inline int propagate_entity_load_avg(struct sched_entity *se)
  3905. {
  3906. return 0;
  3907. }
  3908. static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum) {}
  3909. #endif /* CONFIG_FAIR_GROUP_SCHED */
  3910. #ifdef CONFIG_NO_HZ_COMMON
  3911. static inline void migrate_se_pelt_lag(struct sched_entity *se)
  3912. {
  3913. u64 throttled = 0, now, lut;
  3914. struct cfs_rq *cfs_rq;
  3915. struct rq *rq;
  3916. bool is_idle;
  3917. if (load_avg_is_decayed(&se->avg))
  3918. return;
  3919. cfs_rq = cfs_rq_of(se);
  3920. rq = rq_of(cfs_rq);
  3921. rcu_read_lock();
  3922. is_idle = is_idle_task(rcu_dereference(rq->curr));
  3923. rcu_read_unlock();
  3924. /*
  3925. * The lag estimation comes with a cost we don't want to pay all the
  3926. * time. Hence, limiting to the case where the source CPU is idle and
  3927. * we know we are at the greatest risk to have an outdated clock.
  3928. */
  3929. if (!is_idle)
  3930. return;
  3931. /*
  3932. * Estimated "now" is: last_update_time + cfs_idle_lag + rq_idle_lag, where:
  3933. *
  3934. * last_update_time (the cfs_rq's last_update_time)
  3935. * = cfs_rq_clock_pelt()@cfs_rq_idle
  3936. * = rq_clock_pelt()@cfs_rq_idle
  3937. * - cfs->throttled_clock_pelt_time@cfs_rq_idle
  3938. *
  3939. * cfs_idle_lag (delta between rq's update and cfs_rq's update)
  3940. * = rq_clock_pelt()@rq_idle - rq_clock_pelt()@cfs_rq_idle
  3941. *
  3942. * rq_idle_lag (delta between now and rq's update)
  3943. * = sched_clock_cpu() - rq_clock()@rq_idle
  3944. *
  3945. * We can then write:
  3946. *
  3947. * now = rq_clock_pelt()@rq_idle - cfs->throttled_clock_pelt_time +
  3948. * sched_clock_cpu() - rq_clock()@rq_idle
  3949. * Where:
  3950. * rq_clock_pelt()@rq_idle is rq->clock_pelt_idle
  3951. * rq_clock()@rq_idle is rq->clock_idle
  3952. * cfs->throttled_clock_pelt_time@cfs_rq_idle
  3953. * is cfs_rq->throttled_pelt_idle
  3954. */
  3955. #ifdef CONFIG_CFS_BANDWIDTH
  3956. throttled = u64_u32_load(cfs_rq->throttled_pelt_idle);
  3957. /* The clock has been stopped for throttling */
  3958. if (throttled == U64_MAX)
  3959. return;
  3960. #endif
  3961. now = u64_u32_load(rq->clock_pelt_idle);
  3962. /*
  3963. * Paired with _update_idle_rq_clock_pelt(). It ensures at the worst case
  3964. * is observed the old clock_pelt_idle value and the new clock_idle,
  3965. * which lead to an underestimation. The opposite would lead to an
  3966. * overestimation.
  3967. */
  3968. smp_rmb();
  3969. lut = cfs_rq_last_update_time(cfs_rq);
  3970. now -= throttled;
  3971. if (now < lut)
  3972. /*
  3973. * cfs_rq->avg.last_update_time is more recent than our
  3974. * estimation, let's use it.
  3975. */
  3976. now = lut;
  3977. else
  3978. now += sched_clock_cpu(cpu_of(rq)) - u64_u32_load(rq->clock_idle);
  3979. __update_load_avg_blocked_se(now, se);
  3980. }
  3981. #else
  3982. static void migrate_se_pelt_lag(struct sched_entity *se) {}
  3983. #endif
  3984. /**
  3985. * update_cfs_rq_load_avg - update the cfs_rq's load/util averages
  3986. * @now: current time, as per cfs_rq_clock_pelt()
  3987. * @cfs_rq: cfs_rq to update
  3988. *
  3989. * The cfs_rq avg is the direct sum of all its entities (blocked and runnable)
  3990. * avg. The immediate corollary is that all (fair) tasks must be attached.
  3991. *
  3992. * cfs_rq->avg is used for task_h_load() and update_cfs_share() for example.
  3993. *
  3994. * Return: true if the load decayed or we removed load.
  3995. *
  3996. * Since both these conditions indicate a changed cfs_rq->avg.load we should
  3997. * call update_tg_load_avg() when this function returns true.
  3998. */
  3999. static inline int
  4000. update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq)
  4001. {
  4002. unsigned long removed_load = 0, removed_util = 0, removed_runnable = 0;
  4003. struct sched_avg *sa = &cfs_rq->avg;
  4004. int decayed = 0;
  4005. if (cfs_rq->removed.nr) {
  4006. unsigned long r;
  4007. u32 divider = get_pelt_divider(&cfs_rq->avg);
  4008. raw_spin_lock(&cfs_rq->removed.lock);
  4009. swap(cfs_rq->removed.util_avg, removed_util);
  4010. swap(cfs_rq->removed.load_avg, removed_load);
  4011. swap(cfs_rq->removed.runnable_avg, removed_runnable);
  4012. cfs_rq->removed.nr = 0;
  4013. raw_spin_unlock(&cfs_rq->removed.lock);
  4014. r = removed_load;
  4015. sub_positive(&sa->load_avg, r);
  4016. sub_positive(&sa->load_sum, r * divider);
  4017. /* See sa->util_sum below */
  4018. sa->load_sum = max_t(u32, sa->load_sum, sa->load_avg * PELT_MIN_DIVIDER);
  4019. r = removed_util;
  4020. sub_positive(&sa->util_avg, r);
  4021. sub_positive(&sa->util_sum, r * divider);
  4022. /*
  4023. * Because of rounding, se->util_sum might ends up being +1 more than
  4024. * cfs->util_sum. Although this is not a problem by itself, detaching
  4025. * a lot of tasks with the rounding problem between 2 updates of
  4026. * util_avg (~1ms) can make cfs->util_sum becoming null whereas
  4027. * cfs_util_avg is not.
  4028. * Check that util_sum is still above its lower bound for the new
  4029. * util_avg. Given that period_contrib might have moved since the last
  4030. * sync, we are only sure that util_sum must be above or equal to
  4031. * util_avg * minimum possible divider
  4032. */
  4033. sa->util_sum = max_t(u32, sa->util_sum, sa->util_avg * PELT_MIN_DIVIDER);
  4034. r = removed_runnable;
  4035. sub_positive(&sa->runnable_avg, r);
  4036. sub_positive(&sa->runnable_sum, r * divider);
  4037. /* See sa->util_sum above */
  4038. sa->runnable_sum = max_t(u32, sa->runnable_sum,
  4039. sa->runnable_avg * PELT_MIN_DIVIDER);
  4040. /*
  4041. * removed_runnable is the unweighted version of removed_load so we
  4042. * can use it to estimate removed_load_sum.
  4043. */
  4044. add_tg_cfs_propagate(cfs_rq,
  4045. -(long)(removed_runnable * divider) >> SCHED_CAPACITY_SHIFT);
  4046. decayed = 1;
  4047. }
  4048. decayed |= __update_load_avg_cfs_rq(now, cfs_rq);
  4049. u64_u32_store_copy(sa->last_update_time,
  4050. cfs_rq->last_update_time_copy,
  4051. sa->last_update_time);
  4052. return decayed;
  4053. }
  4054. /**
  4055. * attach_entity_load_avg - attach this entity to its cfs_rq load avg
  4056. * @cfs_rq: cfs_rq to attach to
  4057. * @se: sched_entity to attach
  4058. *
  4059. * Must call update_cfs_rq_load_avg() before this, since we rely on
  4060. * cfs_rq->avg.last_update_time being current.
  4061. */
  4062. static void attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
  4063. {
  4064. /*
  4065. * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
  4066. * See ___update_load_avg() for details.
  4067. */
  4068. u32 divider = get_pelt_divider(&cfs_rq->avg);
  4069. /*
  4070. * When we attach the @se to the @cfs_rq, we must align the decay
  4071. * window because without that, really weird and wonderful things can
  4072. * happen.
  4073. *
  4074. * XXX illustrate
  4075. */
  4076. se->avg.last_update_time = cfs_rq->avg.last_update_time;
  4077. se->avg.period_contrib = cfs_rq->avg.period_contrib;
  4078. /*
  4079. * Hell(o) Nasty stuff.. we need to recompute _sum based on the new
  4080. * period_contrib. This isn't strictly correct, but since we're
  4081. * entirely outside of the PELT hierarchy, nobody cares if we truncate
  4082. * _sum a little.
  4083. */
  4084. se->avg.util_sum = se->avg.util_avg * divider;
  4085. se->avg.runnable_sum = se->avg.runnable_avg * divider;
  4086. se->avg.load_sum = se->avg.load_avg * divider;
  4087. if (se_weight(se) < se->avg.load_sum)
  4088. se->avg.load_sum = div_u64(se->avg.load_sum, se_weight(se));
  4089. else
  4090. se->avg.load_sum = 1;
  4091. enqueue_load_avg(cfs_rq, se);
  4092. cfs_rq->avg.util_avg += se->avg.util_avg;
  4093. cfs_rq->avg.util_sum += se->avg.util_sum;
  4094. cfs_rq->avg.runnable_avg += se->avg.runnable_avg;
  4095. cfs_rq->avg.runnable_sum += se->avg.runnable_sum;
  4096. add_tg_cfs_propagate(cfs_rq, se->avg.load_sum);
  4097. cfs_rq_util_change(cfs_rq, 0);
  4098. trace_pelt_cfs_tp(cfs_rq);
  4099. }
  4100. /**
  4101. * detach_entity_load_avg - detach this entity from its cfs_rq load avg
  4102. * @cfs_rq: cfs_rq to detach from
  4103. * @se: sched_entity to detach
  4104. *
  4105. * Must call update_cfs_rq_load_avg() before this, since we rely on
  4106. * cfs_rq->avg.last_update_time being current.
  4107. */
  4108. static void detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
  4109. {
  4110. dequeue_load_avg(cfs_rq, se);
  4111. sub_positive(&cfs_rq->avg.util_avg, se->avg.util_avg);
  4112. sub_positive(&cfs_rq->avg.util_sum, se->avg.util_sum);
  4113. /* See update_cfs_rq_load_avg() */
  4114. cfs_rq->avg.util_sum = max_t(u32, cfs_rq->avg.util_sum,
  4115. cfs_rq->avg.util_avg * PELT_MIN_DIVIDER);
  4116. sub_positive(&cfs_rq->avg.runnable_avg, se->avg.runnable_avg);
  4117. sub_positive(&cfs_rq->avg.runnable_sum, se->avg.runnable_sum);
  4118. /* See update_cfs_rq_load_avg() */
  4119. cfs_rq->avg.runnable_sum = max_t(u32, cfs_rq->avg.runnable_sum,
  4120. cfs_rq->avg.runnable_avg * PELT_MIN_DIVIDER);
  4121. add_tg_cfs_propagate(cfs_rq, -se->avg.load_sum);
  4122. cfs_rq_util_change(cfs_rq, 0);
  4123. trace_pelt_cfs_tp(cfs_rq);
  4124. }
  4125. /*
  4126. * Optional action to be done while updating the load average
  4127. */
  4128. #define UPDATE_TG 0x1
  4129. #define SKIP_AGE_LOAD 0x2
  4130. #define DO_ATTACH 0x4
  4131. #define DO_DETACH 0x8
  4132. /* Update task and its cfs_rq load average */
  4133. static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
  4134. {
  4135. u64 now = cfs_rq_clock_pelt(cfs_rq);
  4136. int decayed;
  4137. /*
  4138. * Track task load average for carrying it to new CPU after migrated, and
  4139. * track group sched_entity load average for task_h_load calculation in migration
  4140. */
  4141. if (se->avg.last_update_time && !(flags & SKIP_AGE_LOAD))
  4142. __update_load_avg_se(now, cfs_rq, se);
  4143. decayed = update_cfs_rq_load_avg(now, cfs_rq);
  4144. decayed |= propagate_entity_load_avg(se);
  4145. if (!se->avg.last_update_time && (flags & DO_ATTACH)) {
  4146. /*
  4147. * DO_ATTACH means we're here from enqueue_entity().
  4148. * !last_update_time means we've passed through
  4149. * migrate_task_rq_fair() indicating we migrated.
  4150. *
  4151. * IOW we're enqueueing a task on a new CPU.
  4152. */
  4153. attach_entity_load_avg(cfs_rq, se);
  4154. update_tg_load_avg(cfs_rq);
  4155. } else if (flags & DO_DETACH) {
  4156. /*
  4157. * DO_DETACH means we're here from dequeue_entity()
  4158. * and we are migrating task out of the CPU.
  4159. */
  4160. detach_entity_load_avg(cfs_rq, se);
  4161. update_tg_load_avg(cfs_rq);
  4162. } else if (decayed) {
  4163. cfs_rq_util_change(cfs_rq, 0);
  4164. if (flags & UPDATE_TG)
  4165. update_tg_load_avg(cfs_rq);
  4166. }
  4167. }
  4168. /*
  4169. * Synchronize entity load avg of dequeued entity without locking
  4170. * the previous rq.
  4171. */
  4172. static void sync_entity_load_avg(struct sched_entity *se)
  4173. {
  4174. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  4175. u64 last_update_time;
  4176. last_update_time = cfs_rq_last_update_time(cfs_rq);
  4177. __update_load_avg_blocked_se(last_update_time, se);
  4178. }
  4179. /*
  4180. * Task first catches up with cfs_rq, and then subtract
  4181. * itself from the cfs_rq (task must be off the queue now).
  4182. */
  4183. static void remove_entity_load_avg(struct sched_entity *se)
  4184. {
  4185. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  4186. unsigned long flags;
  4187. /*
  4188. * tasks cannot exit without having gone through wake_up_new_task() ->
  4189. * enqueue_task_fair() which will have added things to the cfs_rq,
  4190. * so we can remove unconditionally.
  4191. */
  4192. sync_entity_load_avg(se);
  4193. raw_spin_lock_irqsave(&cfs_rq->removed.lock, flags);
  4194. ++cfs_rq->removed.nr;
  4195. cfs_rq->removed.util_avg += se->avg.util_avg;
  4196. cfs_rq->removed.load_avg += se->avg.load_avg;
  4197. cfs_rq->removed.runnable_avg += se->avg.runnable_avg;
  4198. raw_spin_unlock_irqrestore(&cfs_rq->removed.lock, flags);
  4199. }
  4200. static inline unsigned long cfs_rq_runnable_avg(struct cfs_rq *cfs_rq)
  4201. {
  4202. return cfs_rq->avg.runnable_avg;
  4203. }
  4204. static inline unsigned long cfs_rq_load_avg(struct cfs_rq *cfs_rq)
  4205. {
  4206. return cfs_rq->avg.load_avg;
  4207. }
  4208. static int sched_balance_newidle(struct rq *this_rq, struct rq_flags *rf);
  4209. static inline unsigned long task_util(struct task_struct *p)
  4210. {
  4211. return READ_ONCE(p->se.avg.util_avg);
  4212. }
  4213. static inline unsigned long task_runnable(struct task_struct *p)
  4214. {
  4215. return READ_ONCE(p->se.avg.runnable_avg);
  4216. }
  4217. static inline unsigned long _task_util_est(struct task_struct *p)
  4218. {
  4219. return READ_ONCE(p->se.avg.util_est) & ~UTIL_AVG_UNCHANGED;
  4220. }
  4221. static inline unsigned long task_util_est(struct task_struct *p)
  4222. {
  4223. return max(task_util(p), _task_util_est(p));
  4224. }
  4225. static inline void util_est_enqueue(struct cfs_rq *cfs_rq,
  4226. struct task_struct *p)
  4227. {
  4228. unsigned int enqueued;
  4229. if (!sched_feat(UTIL_EST))
  4230. return;
  4231. /* Update root cfs_rq's estimated utilization */
  4232. enqueued = cfs_rq->avg.util_est;
  4233. enqueued += _task_util_est(p);
  4234. WRITE_ONCE(cfs_rq->avg.util_est, enqueued);
  4235. trace_sched_util_est_cfs_tp(cfs_rq);
  4236. }
  4237. static inline void util_est_dequeue(struct cfs_rq *cfs_rq,
  4238. struct task_struct *p)
  4239. {
  4240. unsigned int enqueued;
  4241. if (!sched_feat(UTIL_EST))
  4242. return;
  4243. /* Update root cfs_rq's estimated utilization */
  4244. enqueued = cfs_rq->avg.util_est;
  4245. enqueued -= min_t(unsigned int, enqueued, _task_util_est(p));
  4246. WRITE_ONCE(cfs_rq->avg.util_est, enqueued);
  4247. trace_sched_util_est_cfs_tp(cfs_rq);
  4248. }
  4249. #define UTIL_EST_MARGIN (SCHED_CAPACITY_SCALE / 100)
  4250. static inline void util_est_update(struct cfs_rq *cfs_rq,
  4251. struct task_struct *p,
  4252. bool task_sleep)
  4253. {
  4254. unsigned int ewma, dequeued, last_ewma_diff;
  4255. if (!sched_feat(UTIL_EST))
  4256. return;
  4257. /*
  4258. * Skip update of task's estimated utilization when the task has not
  4259. * yet completed an activation, e.g. being migrated.
  4260. */
  4261. if (!task_sleep)
  4262. return;
  4263. /* Get current estimate of utilization */
  4264. ewma = READ_ONCE(p->se.avg.util_est);
  4265. /*
  4266. * If the PELT values haven't changed since enqueue time,
  4267. * skip the util_est update.
  4268. */
  4269. if (ewma & UTIL_AVG_UNCHANGED)
  4270. return;
  4271. /* Get utilization at dequeue */
  4272. dequeued = task_util(p);
  4273. /*
  4274. * Reset EWMA on utilization increases, the moving average is used only
  4275. * to smooth utilization decreases.
  4276. */
  4277. if (ewma <= dequeued) {
  4278. ewma = dequeued;
  4279. goto done;
  4280. }
  4281. /*
  4282. * Skip update of task's estimated utilization when its members are
  4283. * already ~1% close to its last activation value.
  4284. */
  4285. last_ewma_diff = ewma - dequeued;
  4286. if (last_ewma_diff < UTIL_EST_MARGIN)
  4287. goto done;
  4288. /*
  4289. * To avoid overestimation of actual task utilization, skip updates if
  4290. * we cannot grant there is idle time in this CPU.
  4291. */
  4292. if (dequeued > arch_scale_cpu_capacity(cpu_of(rq_of(cfs_rq))))
  4293. return;
  4294. /*
  4295. * To avoid underestimate of task utilization, skip updates of EWMA if
  4296. * we cannot grant that thread got all CPU time it wanted.
  4297. */
  4298. if ((dequeued + UTIL_EST_MARGIN) < task_runnable(p))
  4299. goto done;
  4300. /*
  4301. * Update Task's estimated utilization
  4302. *
  4303. * When *p completes an activation we can consolidate another sample
  4304. * of the task size. This is done by using this value to update the
  4305. * Exponential Weighted Moving Average (EWMA):
  4306. *
  4307. * ewma(t) = w * task_util(p) + (1-w) * ewma(t-1)
  4308. * = w * task_util(p) + ewma(t-1) - w * ewma(t-1)
  4309. * = w * (task_util(p) - ewma(t-1)) + ewma(t-1)
  4310. * = w * ( -last_ewma_diff ) + ewma(t-1)
  4311. * = w * (-last_ewma_diff + ewma(t-1) / w)
  4312. *
  4313. * Where 'w' is the weight of new samples, which is configured to be
  4314. * 0.25, thus making w=1/4 ( >>= UTIL_EST_WEIGHT_SHIFT)
  4315. */
  4316. ewma <<= UTIL_EST_WEIGHT_SHIFT;
  4317. ewma -= last_ewma_diff;
  4318. ewma >>= UTIL_EST_WEIGHT_SHIFT;
  4319. done:
  4320. ewma |= UTIL_AVG_UNCHANGED;
  4321. WRITE_ONCE(p->se.avg.util_est, ewma);
  4322. trace_sched_util_est_se_tp(&p->se);
  4323. }
  4324. static inline unsigned long get_actual_cpu_capacity(int cpu)
  4325. {
  4326. unsigned long capacity = arch_scale_cpu_capacity(cpu);
  4327. capacity -= max(hw_load_avg(cpu_rq(cpu)), cpufreq_get_pressure(cpu));
  4328. return capacity;
  4329. }
  4330. static inline int util_fits_cpu(unsigned long util,
  4331. unsigned long uclamp_min,
  4332. unsigned long uclamp_max,
  4333. int cpu)
  4334. {
  4335. unsigned long capacity = capacity_of(cpu);
  4336. unsigned long capacity_orig;
  4337. bool fits, uclamp_max_fits;
  4338. /*
  4339. * Check if the real util fits without any uclamp boost/cap applied.
  4340. */
  4341. fits = fits_capacity(util, capacity);
  4342. if (!uclamp_is_used())
  4343. return fits;
  4344. /*
  4345. * We must use arch_scale_cpu_capacity() for comparing against uclamp_min and
  4346. * uclamp_max. We only care about capacity pressure (by using
  4347. * capacity_of()) for comparing against the real util.
  4348. *
  4349. * If a task is boosted to 1024 for example, we don't want a tiny
  4350. * pressure to skew the check whether it fits a CPU or not.
  4351. *
  4352. * Similarly if a task is capped to arch_scale_cpu_capacity(little_cpu), it
  4353. * should fit a little cpu even if there's some pressure.
  4354. *
  4355. * Only exception is for HW or cpufreq pressure since it has a direct impact
  4356. * on available OPP of the system.
  4357. *
  4358. * We honour it for uclamp_min only as a drop in performance level
  4359. * could result in not getting the requested minimum performance level.
  4360. *
  4361. * For uclamp_max, we can tolerate a drop in performance level as the
  4362. * goal is to cap the task. So it's okay if it's getting less.
  4363. */
  4364. capacity_orig = arch_scale_cpu_capacity(cpu);
  4365. /*
  4366. * We want to force a task to fit a cpu as implied by uclamp_max.
  4367. * But we do have some corner cases to cater for..
  4368. *
  4369. *
  4370. * C=z
  4371. * | ___
  4372. * | C=y | |
  4373. * |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _ uclamp_max
  4374. * | C=x | | | |
  4375. * | ___ | | | |
  4376. * | | | | | | | (util somewhere in this region)
  4377. * | | | | | | |
  4378. * | | | | | | |
  4379. * +----------------------------------------
  4380. * CPU0 CPU1 CPU2
  4381. *
  4382. * In the above example if a task is capped to a specific performance
  4383. * point, y, then when:
  4384. *
  4385. * * util = 80% of x then it does not fit on CPU0 and should migrate
  4386. * to CPU1
  4387. * * util = 80% of y then it is forced to fit on CPU1 to honour
  4388. * uclamp_max request.
  4389. *
  4390. * which is what we're enforcing here. A task always fits if
  4391. * uclamp_max <= capacity_orig. But when uclamp_max > capacity_orig,
  4392. * the normal upmigration rules should withhold still.
  4393. *
  4394. * Only exception is when we are on max capacity, then we need to be
  4395. * careful not to block overutilized state. This is so because:
  4396. *
  4397. * 1. There's no concept of capping at max_capacity! We can't go
  4398. * beyond this performance level anyway.
  4399. * 2. The system is being saturated when we're operating near
  4400. * max capacity, it doesn't make sense to block overutilized.
  4401. */
  4402. uclamp_max_fits = (capacity_orig == SCHED_CAPACITY_SCALE) && (uclamp_max == SCHED_CAPACITY_SCALE);
  4403. uclamp_max_fits = !uclamp_max_fits && (uclamp_max <= capacity_orig);
  4404. fits = fits || uclamp_max_fits;
  4405. /*
  4406. *
  4407. * C=z
  4408. * | ___ (region a, capped, util >= uclamp_max)
  4409. * | C=y | |
  4410. * |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _ uclamp_max
  4411. * | C=x | | | |
  4412. * | ___ | | | | (region b, uclamp_min <= util <= uclamp_max)
  4413. * |_ _ _|_ _|_ _ _ _| _ | _ _ _| _ | _ _ _ _ _ uclamp_min
  4414. * | | | | | | |
  4415. * | | | | | | | (region c, boosted, util < uclamp_min)
  4416. * +----------------------------------------
  4417. * CPU0 CPU1 CPU2
  4418. *
  4419. * a) If util > uclamp_max, then we're capped, we don't care about
  4420. * actual fitness value here. We only care if uclamp_max fits
  4421. * capacity without taking margin/pressure into account.
  4422. * See comment above.
  4423. *
  4424. * b) If uclamp_min <= util <= uclamp_max, then the normal
  4425. * fits_capacity() rules apply. Except we need to ensure that we
  4426. * enforce we remain within uclamp_max, see comment above.
  4427. *
  4428. * c) If util < uclamp_min, then we are boosted. Same as (b) but we
  4429. * need to take into account the boosted value fits the CPU without
  4430. * taking margin/pressure into account.
  4431. *
  4432. * Cases (a) and (b) are handled in the 'fits' variable already. We
  4433. * just need to consider an extra check for case (c) after ensuring we
  4434. * handle the case uclamp_min > uclamp_max.
  4435. */
  4436. uclamp_min = min(uclamp_min, uclamp_max);
  4437. if (fits && (util < uclamp_min) &&
  4438. (uclamp_min > get_actual_cpu_capacity(cpu)))
  4439. return -1;
  4440. return fits;
  4441. }
  4442. static inline int task_fits_cpu(struct task_struct *p, int cpu)
  4443. {
  4444. unsigned long uclamp_min = uclamp_eff_value(p, UCLAMP_MIN);
  4445. unsigned long uclamp_max = uclamp_eff_value(p, UCLAMP_MAX);
  4446. unsigned long util = task_util_est(p);
  4447. /*
  4448. * Return true only if the cpu fully fits the task requirements, which
  4449. * include the utilization but also the performance hints.
  4450. */
  4451. return (util_fits_cpu(util, uclamp_min, uclamp_max, cpu) > 0);
  4452. }
  4453. static inline void update_misfit_status(struct task_struct *p, struct rq *rq)
  4454. {
  4455. int cpu = cpu_of(rq);
  4456. if (!sched_asym_cpucap_active())
  4457. return;
  4458. /*
  4459. * Affinity allows us to go somewhere higher? Or are we on biggest
  4460. * available CPU already? Or do we fit into this CPU ?
  4461. */
  4462. if (!p || (p->nr_cpus_allowed == 1) ||
  4463. (arch_scale_cpu_capacity(cpu) == p->max_allowed_capacity) ||
  4464. task_fits_cpu(p, cpu)) {
  4465. rq->misfit_task_load = 0;
  4466. return;
  4467. }
  4468. /*
  4469. * Make sure that misfit_task_load will not be null even if
  4470. * task_h_load() returns 0.
  4471. */
  4472. rq->misfit_task_load = max_t(unsigned long, task_h_load(p), 1);
  4473. }
  4474. #else /* CONFIG_SMP */
  4475. static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq)
  4476. {
  4477. return !cfs_rq->nr_running;
  4478. }
  4479. #define UPDATE_TG 0x0
  4480. #define SKIP_AGE_LOAD 0x0
  4481. #define DO_ATTACH 0x0
  4482. #define DO_DETACH 0x0
  4483. static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int not_used1)
  4484. {
  4485. cfs_rq_util_change(cfs_rq, 0);
  4486. }
  4487. static inline void remove_entity_load_avg(struct sched_entity *se) {}
  4488. static inline void
  4489. attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
  4490. static inline void
  4491. detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
  4492. static inline int sched_balance_newidle(struct rq *rq, struct rq_flags *rf)
  4493. {
  4494. return 0;
  4495. }
  4496. static inline void
  4497. util_est_enqueue(struct cfs_rq *cfs_rq, struct task_struct *p) {}
  4498. static inline void
  4499. util_est_dequeue(struct cfs_rq *cfs_rq, struct task_struct *p) {}
  4500. static inline void
  4501. util_est_update(struct cfs_rq *cfs_rq, struct task_struct *p,
  4502. bool task_sleep) {}
  4503. static inline void update_misfit_status(struct task_struct *p, struct rq *rq) {}
  4504. #endif /* CONFIG_SMP */
  4505. static void
  4506. place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
  4507. {
  4508. u64 vslice, vruntime = avg_vruntime(cfs_rq);
  4509. s64 lag = 0;
  4510. if (!se->custom_slice)
  4511. se->slice = sysctl_sched_base_slice;
  4512. vslice = calc_delta_fair(se->slice, se);
  4513. /*
  4514. * Due to how V is constructed as the weighted average of entities,
  4515. * adding tasks with positive lag, or removing tasks with negative lag
  4516. * will move 'time' backwards, this can screw around with the lag of
  4517. * other tasks.
  4518. *
  4519. * EEVDF: placement strategy #1 / #2
  4520. */
  4521. if (sched_feat(PLACE_LAG) && cfs_rq->nr_running) {
  4522. struct sched_entity *curr = cfs_rq->curr;
  4523. unsigned long load;
  4524. lag = se->vlag;
  4525. /*
  4526. * If we want to place a task and preserve lag, we have to
  4527. * consider the effect of the new entity on the weighted
  4528. * average and compensate for this, otherwise lag can quickly
  4529. * evaporate.
  4530. *
  4531. * Lag is defined as:
  4532. *
  4533. * lag_i = S - s_i = w_i * (V - v_i)
  4534. *
  4535. * To avoid the 'w_i' term all over the place, we only track
  4536. * the virtual lag:
  4537. *
  4538. * vl_i = V - v_i <=> v_i = V - vl_i
  4539. *
  4540. * And we take V to be the weighted average of all v:
  4541. *
  4542. * V = (\Sum w_j*v_j) / W
  4543. *
  4544. * Where W is: \Sum w_j
  4545. *
  4546. * Then, the weighted average after adding an entity with lag
  4547. * vl_i is given by:
  4548. *
  4549. * V' = (\Sum w_j*v_j + w_i*v_i) / (W + w_i)
  4550. * = (W*V + w_i*(V - vl_i)) / (W + w_i)
  4551. * = (W*V + w_i*V - w_i*vl_i) / (W + w_i)
  4552. * = (V*(W + w_i) - w_i*l) / (W + w_i)
  4553. * = V - w_i*vl_i / (W + w_i)
  4554. *
  4555. * And the actual lag after adding an entity with vl_i is:
  4556. *
  4557. * vl'_i = V' - v_i
  4558. * = V - w_i*vl_i / (W + w_i) - (V - vl_i)
  4559. * = vl_i - w_i*vl_i / (W + w_i)
  4560. *
  4561. * Which is strictly less than vl_i. So in order to preserve lag
  4562. * we should inflate the lag before placement such that the
  4563. * effective lag after placement comes out right.
  4564. *
  4565. * As such, invert the above relation for vl'_i to get the vl_i
  4566. * we need to use such that the lag after placement is the lag
  4567. * we computed before dequeue.
  4568. *
  4569. * vl'_i = vl_i - w_i*vl_i / (W + w_i)
  4570. * = ((W + w_i)*vl_i - w_i*vl_i) / (W + w_i)
  4571. *
  4572. * (W + w_i)*vl'_i = (W + w_i)*vl_i - w_i*vl_i
  4573. * = W*vl_i
  4574. *
  4575. * vl_i = (W + w_i)*vl'_i / W
  4576. */
  4577. load = cfs_rq->avg_load;
  4578. if (curr && curr->on_rq)
  4579. load += scale_load_down(curr->load.weight);
  4580. lag *= load + scale_load_down(se->load.weight);
  4581. if (WARN_ON_ONCE(!load))
  4582. load = 1;
  4583. lag = div_s64(lag, load);
  4584. }
  4585. se->vruntime = vruntime - lag;
  4586. if (sched_feat(PLACE_REL_DEADLINE) && se->rel_deadline) {
  4587. se->deadline += se->vruntime;
  4588. se->rel_deadline = 0;
  4589. return;
  4590. }
  4591. /*
  4592. * When joining the competition; the existing tasks will be,
  4593. * on average, halfway through their slice, as such start tasks
  4594. * off with half a slice to ease into the competition.
  4595. */
  4596. if (sched_feat(PLACE_DEADLINE_INITIAL) && (flags & ENQUEUE_INITIAL))
  4597. vslice /= 2;
  4598. /*
  4599. * EEVDF: vd_i = ve_i + r_i/w_i
  4600. */
  4601. se->deadline = se->vruntime + vslice;
  4602. }
  4603. static void check_enqueue_throttle(struct cfs_rq *cfs_rq);
  4604. static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq);
  4605. static inline bool cfs_bandwidth_used(void);
  4606. static void
  4607. requeue_delayed_entity(struct sched_entity *se);
  4608. static void
  4609. enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
  4610. {
  4611. bool curr = cfs_rq->curr == se;
  4612. /*
  4613. * If we're the current task, we must renormalise before calling
  4614. * update_curr().
  4615. */
  4616. if (curr)
  4617. place_entity(cfs_rq, se, flags);
  4618. update_curr(cfs_rq);
  4619. /*
  4620. * When enqueuing a sched_entity, we must:
  4621. * - Update loads to have both entity and cfs_rq synced with now.
  4622. * - For group_entity, update its runnable_weight to reflect the new
  4623. * h_nr_queued of its group cfs_rq.
  4624. * - For group_entity, update its weight to reflect the new share of
  4625. * its group cfs_rq
  4626. * - Add its new weight to cfs_rq->load.weight
  4627. */
  4628. update_load_avg(cfs_rq, se, UPDATE_TG | DO_ATTACH);
  4629. se_update_runnable(se);
  4630. /*
  4631. * XXX update_load_avg() above will have attached us to the pelt sum;
  4632. * but update_cfs_group() here will re-adjust the weight and have to
  4633. * undo/redo all that. Seems wasteful.
  4634. */
  4635. update_cfs_group(se);
  4636. /*
  4637. * XXX now that the entity has been re-weighted, and it's lag adjusted,
  4638. * we can place the entity.
  4639. */
  4640. if (!curr)
  4641. place_entity(cfs_rq, se, flags);
  4642. account_entity_enqueue(cfs_rq, se);
  4643. /* Entity has migrated, no longer consider this task hot */
  4644. if (flags & ENQUEUE_MIGRATED)
  4645. se->exec_start = 0;
  4646. check_schedstat_required();
  4647. update_stats_enqueue_fair(cfs_rq, se, flags);
  4648. if (!curr)
  4649. __enqueue_entity(cfs_rq, se);
  4650. se->on_rq = 1;
  4651. if (cfs_rq->nr_running == 1) {
  4652. check_enqueue_throttle(cfs_rq);
  4653. if (!throttled_hierarchy(cfs_rq)) {
  4654. list_add_leaf_cfs_rq(cfs_rq);
  4655. } else {
  4656. #ifdef CONFIG_CFS_BANDWIDTH
  4657. struct rq *rq = rq_of(cfs_rq);
  4658. if (cfs_rq_throttled(cfs_rq) && !cfs_rq->throttled_clock)
  4659. cfs_rq->throttled_clock = rq_clock(rq);
  4660. if (!cfs_rq->throttled_clock_self)
  4661. cfs_rq->throttled_clock_self = rq_clock(rq);
  4662. #endif
  4663. }
  4664. }
  4665. }
  4666. static void __clear_buddies_next(struct sched_entity *se)
  4667. {
  4668. for_each_sched_entity(se) {
  4669. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  4670. if (cfs_rq->next != se)
  4671. break;
  4672. cfs_rq->next = NULL;
  4673. }
  4674. }
  4675. static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
  4676. {
  4677. if (cfs_rq->next == se)
  4678. __clear_buddies_next(se);
  4679. }
  4680. static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq);
  4681. static void set_delayed(struct sched_entity *se)
  4682. {
  4683. se->sched_delayed = 1;
  4684. /*
  4685. * Delayed se of cfs_rq have no tasks queued on them.
  4686. * Do not adjust h_nr_runnable since dequeue_entities()
  4687. * will account it for blocked tasks.
  4688. */
  4689. if (!entity_is_task(se))
  4690. return;
  4691. for_each_sched_entity(se) {
  4692. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  4693. cfs_rq->h_nr_runnable--;
  4694. cfs_rq->h_nr_delayed++;
  4695. if (cfs_rq_throttled(cfs_rq))
  4696. break;
  4697. }
  4698. }
  4699. static void clear_delayed(struct sched_entity *se)
  4700. {
  4701. se->sched_delayed = 0;
  4702. /*
  4703. * Delayed se of cfs_rq have no tasks queued on them.
  4704. * Do not adjust h_nr_runnable since a dequeue has
  4705. * already accounted for it or an enqueue of a task
  4706. * below it will account for it in enqueue_task_fair().
  4707. */
  4708. if (!entity_is_task(se))
  4709. return;
  4710. for_each_sched_entity(se) {
  4711. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  4712. cfs_rq->h_nr_runnable++;
  4713. cfs_rq->h_nr_delayed--;
  4714. if (cfs_rq_throttled(cfs_rq))
  4715. break;
  4716. }
  4717. }
  4718. static inline void finish_delayed_dequeue_entity(struct sched_entity *se)
  4719. {
  4720. clear_delayed(se);
  4721. if (sched_feat(DELAY_ZERO) && se->vlag > 0)
  4722. se->vlag = 0;
  4723. }
  4724. static bool
  4725. dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
  4726. {
  4727. bool sleep = flags & DEQUEUE_SLEEP;
  4728. update_curr(cfs_rq);
  4729. clear_buddies(cfs_rq, se);
  4730. if (flags & DEQUEUE_DELAYED) {
  4731. SCHED_WARN_ON(!se->sched_delayed);
  4732. } else {
  4733. bool delay = sleep;
  4734. /*
  4735. * DELAY_DEQUEUE relies on spurious wakeups, special task
  4736. * states must not suffer spurious wakeups, excempt them.
  4737. */
  4738. if (flags & DEQUEUE_SPECIAL)
  4739. delay = false;
  4740. SCHED_WARN_ON(delay && se->sched_delayed);
  4741. if (sched_feat(DELAY_DEQUEUE) && delay &&
  4742. !entity_eligible(cfs_rq, se)) {
  4743. update_load_avg(cfs_rq, se, 0);
  4744. set_delayed(se);
  4745. return false;
  4746. }
  4747. }
  4748. int action = UPDATE_TG;
  4749. if (entity_is_task(se) && task_on_rq_migrating(task_of(se)))
  4750. action |= DO_DETACH;
  4751. /*
  4752. * When dequeuing a sched_entity, we must:
  4753. * - Update loads to have both entity and cfs_rq synced with now.
  4754. * - For group_entity, update its runnable_weight to reflect the new
  4755. * h_nr_queued of its group cfs_rq.
  4756. * - Subtract its previous weight from cfs_rq->load.weight.
  4757. * - For group entity, update its weight to reflect the new share
  4758. * of its group cfs_rq.
  4759. */
  4760. update_load_avg(cfs_rq, se, action);
  4761. se_update_runnable(se);
  4762. update_stats_dequeue_fair(cfs_rq, se, flags);
  4763. update_entity_lag(cfs_rq, se);
  4764. if (sched_feat(PLACE_REL_DEADLINE) && !sleep) {
  4765. se->deadline -= se->vruntime;
  4766. se->rel_deadline = 1;
  4767. }
  4768. if (se != cfs_rq->curr)
  4769. __dequeue_entity(cfs_rq, se);
  4770. se->on_rq = 0;
  4771. account_entity_dequeue(cfs_rq, se);
  4772. /* return excess runtime on last dequeue */
  4773. return_cfs_rq_runtime(cfs_rq);
  4774. update_cfs_group(se);
  4775. /*
  4776. * Now advance min_vruntime if @se was the entity holding it back,
  4777. * except when: DEQUEUE_SAVE && !DEQUEUE_MOVE, in this case we'll be
  4778. * put back on, and if we advance min_vruntime, we'll be placed back
  4779. * further than we started -- i.e. we'll be penalized.
  4780. */
  4781. if ((flags & (DEQUEUE_SAVE | DEQUEUE_MOVE)) != DEQUEUE_SAVE)
  4782. update_min_vruntime(cfs_rq);
  4783. if (flags & DEQUEUE_DELAYED)
  4784. finish_delayed_dequeue_entity(se);
  4785. if (cfs_rq->nr_running == 0)
  4786. update_idle_cfs_rq_clock_pelt(cfs_rq);
  4787. return true;
  4788. }
  4789. static void
  4790. set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
  4791. {
  4792. clear_buddies(cfs_rq, se);
  4793. /* 'current' is not kept within the tree. */
  4794. if (se->on_rq) {
  4795. /*
  4796. * Any task has to be enqueued before it get to execute on
  4797. * a CPU. So account for the time it spent waiting on the
  4798. * runqueue.
  4799. */
  4800. update_stats_wait_end_fair(cfs_rq, se);
  4801. __dequeue_entity(cfs_rq, se);
  4802. update_load_avg(cfs_rq, se, UPDATE_TG);
  4803. set_protect_slice(se);
  4804. }
  4805. update_stats_curr_start(cfs_rq, se);
  4806. SCHED_WARN_ON(cfs_rq->curr);
  4807. cfs_rq->curr = se;
  4808. /*
  4809. * Track our maximum slice length, if the CPU's load is at
  4810. * least twice that of our own weight (i.e. don't track it
  4811. * when there are only lesser-weight tasks around):
  4812. */
  4813. if (schedstat_enabled() &&
  4814. rq_of(cfs_rq)->cfs.load.weight >= 2*se->load.weight) {
  4815. struct sched_statistics *stats;
  4816. stats = __schedstats_from_se(se);
  4817. __schedstat_set(stats->slice_max,
  4818. max((u64)stats->slice_max,
  4819. se->sum_exec_runtime - se->prev_sum_exec_runtime));
  4820. }
  4821. se->prev_sum_exec_runtime = se->sum_exec_runtime;
  4822. }
  4823. static int dequeue_entities(struct rq *rq, struct sched_entity *se, int flags);
  4824. /*
  4825. * Pick the next process, keeping these things in mind, in this order:
  4826. * 1) keep things fair between processes/task groups
  4827. * 2) pick the "next" process, since someone really wants that to run
  4828. * 3) pick the "last" process, for cache locality
  4829. * 4) do not run the "skip" process, if something else is available
  4830. */
  4831. static struct sched_entity *
  4832. pick_next_entity(struct rq *rq, struct cfs_rq *cfs_rq)
  4833. {
  4834. /*
  4835. * Picking the ->next buddy will affect latency but not fairness.
  4836. */
  4837. if (sched_feat(PICK_BUDDY) &&
  4838. cfs_rq->next && entity_eligible(cfs_rq, cfs_rq->next)) {
  4839. /* ->next will never be delayed */
  4840. SCHED_WARN_ON(cfs_rq->next->sched_delayed);
  4841. return cfs_rq->next;
  4842. }
  4843. struct sched_entity *se = pick_eevdf(cfs_rq);
  4844. if (se->sched_delayed) {
  4845. dequeue_entities(rq, se, DEQUEUE_SLEEP | DEQUEUE_DELAYED);
  4846. /*
  4847. * Must not reference @se again, see __block_task().
  4848. */
  4849. return NULL;
  4850. }
  4851. return se;
  4852. }
  4853. static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq);
  4854. static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
  4855. {
  4856. /*
  4857. * If still on the runqueue then deactivate_task()
  4858. * was not called and update_curr() has to be done:
  4859. */
  4860. if (prev->on_rq)
  4861. update_curr(cfs_rq);
  4862. /* throttle cfs_rqs exceeding runtime */
  4863. check_cfs_rq_runtime(cfs_rq);
  4864. if (prev->on_rq) {
  4865. update_stats_wait_start_fair(cfs_rq, prev);
  4866. /* Put 'current' back into the tree. */
  4867. __enqueue_entity(cfs_rq, prev);
  4868. /* in !on_rq case, update occurred at dequeue */
  4869. update_load_avg(cfs_rq, prev, 0);
  4870. }
  4871. SCHED_WARN_ON(cfs_rq->curr != prev);
  4872. cfs_rq->curr = NULL;
  4873. }
  4874. static void
  4875. entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
  4876. {
  4877. /*
  4878. * Update run-time statistics of the 'current'.
  4879. */
  4880. update_curr(cfs_rq);
  4881. /*
  4882. * Ensure that runnable average is periodically updated.
  4883. */
  4884. update_load_avg(cfs_rq, curr, UPDATE_TG);
  4885. update_cfs_group(curr);
  4886. #ifdef CONFIG_SCHED_HRTICK
  4887. /*
  4888. * queued ticks are scheduled to match the slice, so don't bother
  4889. * validating it and just reschedule.
  4890. */
  4891. if (queued) {
  4892. resched_curr(rq_of(cfs_rq));
  4893. return;
  4894. }
  4895. /*
  4896. * don't let the period tick interfere with the hrtick preemption
  4897. */
  4898. if (!sched_feat(DOUBLE_TICK) &&
  4899. hrtimer_active(&rq_of(cfs_rq)->hrtick_timer))
  4900. return;
  4901. #endif
  4902. }
  4903. /**************************************************
  4904. * CFS bandwidth control machinery
  4905. */
  4906. #ifdef CONFIG_CFS_BANDWIDTH
  4907. #ifdef CONFIG_JUMP_LABEL
  4908. static struct static_key __cfs_bandwidth_used;
  4909. static inline bool cfs_bandwidth_used(void)
  4910. {
  4911. return static_key_false(&__cfs_bandwidth_used);
  4912. }
  4913. void cfs_bandwidth_usage_inc(void)
  4914. {
  4915. static_key_slow_inc_cpuslocked(&__cfs_bandwidth_used);
  4916. }
  4917. void cfs_bandwidth_usage_dec(void)
  4918. {
  4919. static_key_slow_dec_cpuslocked(&__cfs_bandwidth_used);
  4920. }
  4921. #else /* CONFIG_JUMP_LABEL */
  4922. static bool cfs_bandwidth_used(void)
  4923. {
  4924. return true;
  4925. }
  4926. void cfs_bandwidth_usage_inc(void) {}
  4927. void cfs_bandwidth_usage_dec(void) {}
  4928. #endif /* CONFIG_JUMP_LABEL */
  4929. /*
  4930. * default period for cfs group bandwidth.
  4931. * default: 0.1s, units: nanoseconds
  4932. */
  4933. static inline u64 default_cfs_period(void)
  4934. {
  4935. return 100000000ULL;
  4936. }
  4937. static inline u64 sched_cfs_bandwidth_slice(void)
  4938. {
  4939. return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC;
  4940. }
  4941. /*
  4942. * Replenish runtime according to assigned quota. We use sched_clock_cpu
  4943. * directly instead of rq->clock to avoid adding additional synchronization
  4944. * around rq->lock.
  4945. *
  4946. * requires cfs_b->lock
  4947. */
  4948. void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
  4949. {
  4950. s64 runtime;
  4951. if (unlikely(cfs_b->quota == RUNTIME_INF))
  4952. return;
  4953. cfs_b->runtime += cfs_b->quota;
  4954. runtime = cfs_b->runtime_snap - cfs_b->runtime;
  4955. if (runtime > 0) {
  4956. cfs_b->burst_time += runtime;
  4957. cfs_b->nr_burst++;
  4958. }
  4959. cfs_b->runtime = min(cfs_b->runtime, cfs_b->quota + cfs_b->burst);
  4960. cfs_b->runtime_snap = cfs_b->runtime;
  4961. }
  4962. static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
  4963. {
  4964. return &tg->cfs_bandwidth;
  4965. }
  4966. /* returns 0 on failure to allocate runtime */
  4967. static int __assign_cfs_rq_runtime(struct cfs_bandwidth *cfs_b,
  4968. struct cfs_rq *cfs_rq, u64 target_runtime)
  4969. {
  4970. u64 min_amount, amount = 0;
  4971. lockdep_assert_held(&cfs_b->lock);
  4972. /* note: this is a positive sum as runtime_remaining <= 0 */
  4973. min_amount = target_runtime - cfs_rq->runtime_remaining;
  4974. if (cfs_b->quota == RUNTIME_INF)
  4975. amount = min_amount;
  4976. else {
  4977. start_cfs_bandwidth(cfs_b);
  4978. if (cfs_b->runtime > 0) {
  4979. amount = min(cfs_b->runtime, min_amount);
  4980. cfs_b->runtime -= amount;
  4981. cfs_b->idle = 0;
  4982. }
  4983. }
  4984. cfs_rq->runtime_remaining += amount;
  4985. return cfs_rq->runtime_remaining > 0;
  4986. }
  4987. /* returns 0 on failure to allocate runtime */
  4988. static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  4989. {
  4990. struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
  4991. int ret;
  4992. raw_spin_lock(&cfs_b->lock);
  4993. ret = __assign_cfs_rq_runtime(cfs_b, cfs_rq, sched_cfs_bandwidth_slice());
  4994. raw_spin_unlock(&cfs_b->lock);
  4995. return ret;
  4996. }
  4997. static void __account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
  4998. {
  4999. /* dock delta_exec before expiring quota (as it could span periods) */
  5000. cfs_rq->runtime_remaining -= delta_exec;
  5001. if (likely(cfs_rq->runtime_remaining > 0))
  5002. return;
  5003. if (cfs_rq->throttled)
  5004. return;
  5005. /*
  5006. * if we're unable to extend our runtime we resched so that the active
  5007. * hierarchy can be throttled
  5008. */
  5009. if (!assign_cfs_rq_runtime(cfs_rq) && likely(cfs_rq->curr))
  5010. resched_curr(rq_of(cfs_rq));
  5011. }
  5012. static __always_inline
  5013. void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
  5014. {
  5015. if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled)
  5016. return;
  5017. __account_cfs_rq_runtime(cfs_rq, delta_exec);
  5018. }
  5019. static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
  5020. {
  5021. return cfs_bandwidth_used() && cfs_rq->throttled;
  5022. }
  5023. /* check whether cfs_rq, or any parent, is throttled */
  5024. static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
  5025. {
  5026. return cfs_bandwidth_used() && cfs_rq->throttle_count;
  5027. }
  5028. /*
  5029. * Ensure that neither of the group entities corresponding to src_cpu or
  5030. * dest_cpu are members of a throttled hierarchy when performing group
  5031. * load-balance operations.
  5032. */
  5033. static inline int throttled_lb_pair(struct task_group *tg,
  5034. int src_cpu, int dest_cpu)
  5035. {
  5036. struct cfs_rq *src_cfs_rq, *dest_cfs_rq;
  5037. src_cfs_rq = tg->cfs_rq[src_cpu];
  5038. dest_cfs_rq = tg->cfs_rq[dest_cpu];
  5039. return throttled_hierarchy(src_cfs_rq) ||
  5040. throttled_hierarchy(dest_cfs_rq);
  5041. }
  5042. static int tg_unthrottle_up(struct task_group *tg, void *data)
  5043. {
  5044. struct rq *rq = data;
  5045. struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
  5046. cfs_rq->throttle_count--;
  5047. if (!cfs_rq->throttle_count) {
  5048. cfs_rq->throttled_clock_pelt_time += rq_clock_pelt(rq) -
  5049. cfs_rq->throttled_clock_pelt;
  5050. /* Add cfs_rq with load or one or more already running entities to the list */
  5051. if (!cfs_rq_is_decayed(cfs_rq))
  5052. list_add_leaf_cfs_rq(cfs_rq);
  5053. if (cfs_rq->throttled_clock_self) {
  5054. u64 delta = rq_clock(rq) - cfs_rq->throttled_clock_self;
  5055. cfs_rq->throttled_clock_self = 0;
  5056. if (SCHED_WARN_ON((s64)delta < 0))
  5057. delta = 0;
  5058. cfs_rq->throttled_clock_self_time += delta;
  5059. }
  5060. }
  5061. return 0;
  5062. }
  5063. static int tg_throttle_down(struct task_group *tg, void *data)
  5064. {
  5065. struct rq *rq = data;
  5066. struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
  5067. /* group is entering throttled state, stop time */
  5068. if (!cfs_rq->throttle_count) {
  5069. cfs_rq->throttled_clock_pelt = rq_clock_pelt(rq);
  5070. list_del_leaf_cfs_rq(cfs_rq);
  5071. SCHED_WARN_ON(cfs_rq->throttled_clock_self);
  5072. if (cfs_rq->nr_running)
  5073. cfs_rq->throttled_clock_self = rq_clock(rq);
  5074. }
  5075. cfs_rq->throttle_count++;
  5076. return 0;
  5077. }
  5078. static bool throttle_cfs_rq(struct cfs_rq *cfs_rq)
  5079. {
  5080. struct rq *rq = rq_of(cfs_rq);
  5081. struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
  5082. struct sched_entity *se;
  5083. long queued_delta, runnable_delta, idle_task_delta, delayed_delta, dequeue = 1;
  5084. long rq_h_nr_queued = rq->cfs.h_nr_queued;
  5085. raw_spin_lock(&cfs_b->lock);
  5086. /* This will start the period timer if necessary */
  5087. if (__assign_cfs_rq_runtime(cfs_b, cfs_rq, 1)) {
  5088. /*
  5089. * We have raced with bandwidth becoming available, and if we
  5090. * actually throttled the timer might not unthrottle us for an
  5091. * entire period. We additionally needed to make sure that any
  5092. * subsequent check_cfs_rq_runtime calls agree not to throttle
  5093. * us, as we may commit to do cfs put_prev+pick_next, so we ask
  5094. * for 1ns of runtime rather than just check cfs_b.
  5095. */
  5096. dequeue = 0;
  5097. } else {
  5098. list_add_tail_rcu(&cfs_rq->throttled_list,
  5099. &cfs_b->throttled_cfs_rq);
  5100. }
  5101. raw_spin_unlock(&cfs_b->lock);
  5102. if (!dequeue)
  5103. return false; /* Throttle no longer required. */
  5104. se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))];
  5105. /* freeze hierarchy runnable averages while throttled */
  5106. rcu_read_lock();
  5107. walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq);
  5108. rcu_read_unlock();
  5109. queued_delta = cfs_rq->h_nr_queued;
  5110. runnable_delta = cfs_rq->h_nr_runnable;
  5111. idle_task_delta = cfs_rq->idle_h_nr_running;
  5112. delayed_delta = cfs_rq->h_nr_delayed;
  5113. for_each_sched_entity(se) {
  5114. struct cfs_rq *qcfs_rq = cfs_rq_of(se);
  5115. int flags;
  5116. /* throttled entity or throttle-on-deactivate */
  5117. if (!se->on_rq)
  5118. goto done;
  5119. /*
  5120. * Abuse SPECIAL to avoid delayed dequeue in this instance.
  5121. * This avoids teaching dequeue_entities() about throttled
  5122. * entities and keeps things relatively simple.
  5123. */
  5124. flags = DEQUEUE_SLEEP | DEQUEUE_SPECIAL;
  5125. if (se->sched_delayed)
  5126. flags |= DEQUEUE_DELAYED;
  5127. dequeue_entity(qcfs_rq, se, flags);
  5128. if (cfs_rq_is_idle(group_cfs_rq(se)))
  5129. idle_task_delta = cfs_rq->h_nr_queued;
  5130. qcfs_rq->h_nr_queued -= queued_delta;
  5131. qcfs_rq->h_nr_runnable -= runnable_delta;
  5132. qcfs_rq->idle_h_nr_running -= idle_task_delta;
  5133. qcfs_rq->h_nr_delayed -= delayed_delta;
  5134. if (qcfs_rq->load.weight) {
  5135. /* Avoid re-evaluating load for this entity: */
  5136. se = parent_entity(se);
  5137. break;
  5138. }
  5139. }
  5140. for_each_sched_entity(se) {
  5141. struct cfs_rq *qcfs_rq = cfs_rq_of(se);
  5142. /* throttled entity or throttle-on-deactivate */
  5143. if (!se->on_rq)
  5144. goto done;
  5145. update_load_avg(qcfs_rq, se, 0);
  5146. se_update_runnable(se);
  5147. if (cfs_rq_is_idle(group_cfs_rq(se)))
  5148. idle_task_delta = cfs_rq->h_nr_queued;
  5149. qcfs_rq->h_nr_queued -= queued_delta;
  5150. qcfs_rq->h_nr_runnable -= runnable_delta;
  5151. qcfs_rq->idle_h_nr_running -= idle_task_delta;
  5152. qcfs_rq->h_nr_delayed -= delayed_delta;
  5153. }
  5154. /* At this point se is NULL and we are at root level*/
  5155. sub_nr_running(rq, queued_delta);
  5156. /* Stop the fair server if throttling resulted in no runnable tasks */
  5157. if (rq_h_nr_queued && !rq->cfs.h_nr_queued)
  5158. dl_server_stop(&rq->fair_server);
  5159. done:
  5160. /*
  5161. * Note: distribution will already see us throttled via the
  5162. * throttled-list. rq->lock protects completion.
  5163. */
  5164. cfs_rq->throttled = 1;
  5165. SCHED_WARN_ON(cfs_rq->throttled_clock);
  5166. if (cfs_rq->nr_running)
  5167. cfs_rq->throttled_clock = rq_clock(rq);
  5168. return true;
  5169. }
  5170. void unthrottle_cfs_rq(struct cfs_rq *cfs_rq)
  5171. {
  5172. struct rq *rq = rq_of(cfs_rq);
  5173. struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
  5174. struct sched_entity *se;
  5175. long queued_delta, runnable_delta, idle_task_delta, delayed_delta;
  5176. long rq_h_nr_queued = rq->cfs.h_nr_queued;
  5177. se = cfs_rq->tg->se[cpu_of(rq)];
  5178. cfs_rq->throttled = 0;
  5179. update_rq_clock(rq);
  5180. raw_spin_lock(&cfs_b->lock);
  5181. if (cfs_rq->throttled_clock) {
  5182. cfs_b->throttled_time += rq_clock(rq) - cfs_rq->throttled_clock;
  5183. cfs_rq->throttled_clock = 0;
  5184. }
  5185. list_del_rcu(&cfs_rq->throttled_list);
  5186. raw_spin_unlock(&cfs_b->lock);
  5187. /* update hierarchical throttle state */
  5188. walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq);
  5189. if (!cfs_rq->load.weight) {
  5190. if (!cfs_rq->on_list)
  5191. return;
  5192. /*
  5193. * Nothing to run but something to decay (on_list)?
  5194. * Complete the branch.
  5195. */
  5196. for_each_sched_entity(se) {
  5197. if (list_add_leaf_cfs_rq(cfs_rq_of(se)))
  5198. break;
  5199. }
  5200. goto unthrottle_throttle;
  5201. }
  5202. queued_delta = cfs_rq->h_nr_queued;
  5203. runnable_delta = cfs_rq->h_nr_runnable;
  5204. idle_task_delta = cfs_rq->idle_h_nr_running;
  5205. delayed_delta = cfs_rq->h_nr_delayed;
  5206. for_each_sched_entity(se) {
  5207. struct cfs_rq *qcfs_rq = cfs_rq_of(se);
  5208. /* Handle any unfinished DELAY_DEQUEUE business first. */
  5209. if (se->sched_delayed) {
  5210. int flags = DEQUEUE_SLEEP | DEQUEUE_DELAYED;
  5211. dequeue_entity(qcfs_rq, se, flags);
  5212. } else if (se->on_rq)
  5213. break;
  5214. enqueue_entity(qcfs_rq, se, ENQUEUE_WAKEUP);
  5215. if (cfs_rq_is_idle(group_cfs_rq(se)))
  5216. idle_task_delta = cfs_rq->h_nr_queued;
  5217. qcfs_rq->h_nr_queued += queued_delta;
  5218. qcfs_rq->h_nr_runnable += runnable_delta;
  5219. qcfs_rq->idle_h_nr_running += idle_task_delta;
  5220. qcfs_rq->h_nr_delayed += delayed_delta;
  5221. /* end evaluation on encountering a throttled cfs_rq */
  5222. if (cfs_rq_throttled(qcfs_rq))
  5223. goto unthrottle_throttle;
  5224. }
  5225. for_each_sched_entity(se) {
  5226. struct cfs_rq *qcfs_rq = cfs_rq_of(se);
  5227. update_load_avg(qcfs_rq, se, UPDATE_TG);
  5228. se_update_runnable(se);
  5229. if (cfs_rq_is_idle(group_cfs_rq(se)))
  5230. idle_task_delta = cfs_rq->h_nr_queued;
  5231. qcfs_rq->h_nr_queued += queued_delta;
  5232. qcfs_rq->h_nr_runnable += runnable_delta;
  5233. qcfs_rq->idle_h_nr_running += idle_task_delta;
  5234. qcfs_rq->h_nr_delayed += delayed_delta;
  5235. /* end evaluation on encountering a throttled cfs_rq */
  5236. if (cfs_rq_throttled(qcfs_rq))
  5237. goto unthrottle_throttle;
  5238. }
  5239. /* Start the fair server if un-throttling resulted in new runnable tasks */
  5240. if (!rq_h_nr_queued && rq->cfs.h_nr_queued)
  5241. dl_server_start(&rq->fair_server);
  5242. /* At this point se is NULL and we are at root level*/
  5243. add_nr_running(rq, queued_delta);
  5244. unthrottle_throttle:
  5245. assert_list_leaf_cfs_rq(rq);
  5246. /* Determine whether we need to wake up potentially idle CPU: */
  5247. if (rq->curr == rq->idle && rq->cfs.nr_running)
  5248. resched_curr(rq);
  5249. }
  5250. #ifdef CONFIG_SMP
  5251. static void __cfsb_csd_unthrottle(void *arg)
  5252. {
  5253. struct cfs_rq *cursor, *tmp;
  5254. struct rq *rq = arg;
  5255. struct rq_flags rf;
  5256. rq_lock(rq, &rf);
  5257. /*
  5258. * Iterating over the list can trigger several call to
  5259. * update_rq_clock() in unthrottle_cfs_rq().
  5260. * Do it once and skip the potential next ones.
  5261. */
  5262. update_rq_clock(rq);
  5263. rq_clock_start_loop_update(rq);
  5264. /*
  5265. * Since we hold rq lock we're safe from concurrent manipulation of
  5266. * the CSD list. However, this RCU critical section annotates the
  5267. * fact that we pair with sched_free_group_rcu(), so that we cannot
  5268. * race with group being freed in the window between removing it
  5269. * from the list and advancing to the next entry in the list.
  5270. */
  5271. rcu_read_lock();
  5272. list_for_each_entry_safe(cursor, tmp, &rq->cfsb_csd_list,
  5273. throttled_csd_list) {
  5274. list_del_init(&cursor->throttled_csd_list);
  5275. if (cfs_rq_throttled(cursor))
  5276. unthrottle_cfs_rq(cursor);
  5277. }
  5278. rcu_read_unlock();
  5279. rq_clock_stop_loop_update(rq);
  5280. rq_unlock(rq, &rf);
  5281. }
  5282. static inline void __unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
  5283. {
  5284. struct rq *rq = rq_of(cfs_rq);
  5285. bool first;
  5286. if (rq == this_rq()) {
  5287. unthrottle_cfs_rq(cfs_rq);
  5288. return;
  5289. }
  5290. /* Already enqueued */
  5291. if (SCHED_WARN_ON(!list_empty(&cfs_rq->throttled_csd_list)))
  5292. return;
  5293. first = list_empty(&rq->cfsb_csd_list);
  5294. list_add_tail(&cfs_rq->throttled_csd_list, &rq->cfsb_csd_list);
  5295. if (first)
  5296. smp_call_function_single_async(cpu_of(rq), &rq->cfsb_csd);
  5297. }
  5298. #else
  5299. static inline void __unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
  5300. {
  5301. unthrottle_cfs_rq(cfs_rq);
  5302. }
  5303. #endif
  5304. static void unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
  5305. {
  5306. lockdep_assert_rq_held(rq_of(cfs_rq));
  5307. if (SCHED_WARN_ON(!cfs_rq_throttled(cfs_rq) ||
  5308. cfs_rq->runtime_remaining <= 0))
  5309. return;
  5310. __unthrottle_cfs_rq_async(cfs_rq);
  5311. }
  5312. static bool distribute_cfs_runtime(struct cfs_bandwidth *cfs_b)
  5313. {
  5314. int this_cpu = smp_processor_id();
  5315. u64 runtime, remaining = 1;
  5316. bool throttled = false;
  5317. struct cfs_rq *cfs_rq, *tmp;
  5318. struct rq_flags rf;
  5319. struct rq *rq;
  5320. LIST_HEAD(local_unthrottle);
  5321. rcu_read_lock();
  5322. list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
  5323. throttled_list) {
  5324. rq = rq_of(cfs_rq);
  5325. if (!remaining) {
  5326. throttled = true;
  5327. break;
  5328. }
  5329. rq_lock_irqsave(rq, &rf);
  5330. if (!cfs_rq_throttled(cfs_rq))
  5331. goto next;
  5332. /* Already queued for async unthrottle */
  5333. if (!list_empty(&cfs_rq->throttled_csd_list))
  5334. goto next;
  5335. /* By the above checks, this should never be true */
  5336. SCHED_WARN_ON(cfs_rq->runtime_remaining > 0);
  5337. raw_spin_lock(&cfs_b->lock);
  5338. runtime = -cfs_rq->runtime_remaining + 1;
  5339. if (runtime > cfs_b->runtime)
  5340. runtime = cfs_b->runtime;
  5341. cfs_b->runtime -= runtime;
  5342. remaining = cfs_b->runtime;
  5343. raw_spin_unlock(&cfs_b->lock);
  5344. cfs_rq->runtime_remaining += runtime;
  5345. /* we check whether we're throttled above */
  5346. if (cfs_rq->runtime_remaining > 0) {
  5347. if (cpu_of(rq) != this_cpu) {
  5348. unthrottle_cfs_rq_async(cfs_rq);
  5349. } else {
  5350. /*
  5351. * We currently only expect to be unthrottling
  5352. * a single cfs_rq locally.
  5353. */
  5354. SCHED_WARN_ON(!list_empty(&local_unthrottle));
  5355. list_add_tail(&cfs_rq->throttled_csd_list,
  5356. &local_unthrottle);
  5357. }
  5358. } else {
  5359. throttled = true;
  5360. }
  5361. next:
  5362. rq_unlock_irqrestore(rq, &rf);
  5363. }
  5364. list_for_each_entry_safe(cfs_rq, tmp, &local_unthrottle,
  5365. throttled_csd_list) {
  5366. struct rq *rq = rq_of(cfs_rq);
  5367. rq_lock_irqsave(rq, &rf);
  5368. list_del_init(&cfs_rq->throttled_csd_list);
  5369. if (cfs_rq_throttled(cfs_rq))
  5370. unthrottle_cfs_rq(cfs_rq);
  5371. rq_unlock_irqrestore(rq, &rf);
  5372. }
  5373. SCHED_WARN_ON(!list_empty(&local_unthrottle));
  5374. rcu_read_unlock();
  5375. return throttled;
  5376. }
  5377. /*
  5378. * Responsible for refilling a task_group's bandwidth and unthrottling its
  5379. * cfs_rqs as appropriate. If there has been no activity within the last
  5380. * period the timer is deactivated until scheduling resumes; cfs_b->idle is
  5381. * used to track this state.
  5382. */
  5383. static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun, unsigned long flags)
  5384. {
  5385. int throttled;
  5386. /* no need to continue the timer with no bandwidth constraint */
  5387. if (cfs_b->quota == RUNTIME_INF)
  5388. goto out_deactivate;
  5389. throttled = !list_empty(&cfs_b->throttled_cfs_rq);
  5390. cfs_b->nr_periods += overrun;
  5391. /* Refill extra burst quota even if cfs_b->idle */
  5392. __refill_cfs_bandwidth_runtime(cfs_b);
  5393. /*
  5394. * idle depends on !throttled (for the case of a large deficit), and if
  5395. * we're going inactive then everything else can be deferred
  5396. */
  5397. if (cfs_b->idle && !throttled)
  5398. goto out_deactivate;
  5399. if (!throttled) {
  5400. /* mark as potentially idle for the upcoming period */
  5401. cfs_b->idle = 1;
  5402. return 0;
  5403. }
  5404. /* account preceding periods in which throttling occurred */
  5405. cfs_b->nr_throttled += overrun;
  5406. /*
  5407. * This check is repeated as we release cfs_b->lock while we unthrottle.
  5408. */
  5409. while (throttled && cfs_b->runtime > 0) {
  5410. raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
  5411. /* we can't nest cfs_b->lock while distributing bandwidth */
  5412. throttled = distribute_cfs_runtime(cfs_b);
  5413. raw_spin_lock_irqsave(&cfs_b->lock, flags);
  5414. }
  5415. /*
  5416. * While we are ensured activity in the period following an
  5417. * unthrottle, this also covers the case in which the new bandwidth is
  5418. * insufficient to cover the existing bandwidth deficit. (Forcing the
  5419. * timer to remain active while there are any throttled entities.)
  5420. */
  5421. cfs_b->idle = 0;
  5422. return 0;
  5423. out_deactivate:
  5424. return 1;
  5425. }
  5426. /* a cfs_rq won't donate quota below this amount */
  5427. static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC;
  5428. /* minimum remaining period time to redistribute slack quota */
  5429. static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC;
  5430. /* how long we wait to gather additional slack before distributing */
  5431. static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC;
  5432. /*
  5433. * Are we near the end of the current quota period?
  5434. *
  5435. * Requires cfs_b->lock for hrtimer_expires_remaining to be safe against the
  5436. * hrtimer base being cleared by hrtimer_start. In the case of
  5437. * migrate_hrtimers, base is never cleared, so we are fine.
  5438. */
  5439. static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire)
  5440. {
  5441. struct hrtimer *refresh_timer = &cfs_b->period_timer;
  5442. s64 remaining;
  5443. /* if the call-back is running a quota refresh is already occurring */
  5444. if (hrtimer_callback_running(refresh_timer))
  5445. return 1;
  5446. /* is a quota refresh about to occur? */
  5447. remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer));
  5448. if (remaining < (s64)min_expire)
  5449. return 1;
  5450. return 0;
  5451. }
  5452. static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b)
  5453. {
  5454. u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration;
  5455. /* if there's a quota refresh soon don't bother with slack */
  5456. if (runtime_refresh_within(cfs_b, min_left))
  5457. return;
  5458. /* don't push forwards an existing deferred unthrottle */
  5459. if (cfs_b->slack_started)
  5460. return;
  5461. cfs_b->slack_started = true;
  5462. hrtimer_start(&cfs_b->slack_timer,
  5463. ns_to_ktime(cfs_bandwidth_slack_period),
  5464. HRTIMER_MODE_REL);
  5465. }
  5466. /* we know any runtime found here is valid as update_curr() precedes return */
  5467. static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  5468. {
  5469. struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
  5470. s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;
  5471. if (slack_runtime <= 0)
  5472. return;
  5473. raw_spin_lock(&cfs_b->lock);
  5474. if (cfs_b->quota != RUNTIME_INF) {
  5475. cfs_b->runtime += slack_runtime;
  5476. /* we are under rq->lock, defer unthrottling using a timer */
  5477. if (cfs_b->runtime > sched_cfs_bandwidth_slice() &&
  5478. !list_empty(&cfs_b->throttled_cfs_rq))
  5479. start_cfs_slack_bandwidth(cfs_b);
  5480. }
  5481. raw_spin_unlock(&cfs_b->lock);
  5482. /* even if it's not valid for return we don't want to try again */
  5483. cfs_rq->runtime_remaining -= slack_runtime;
  5484. }
  5485. static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  5486. {
  5487. if (!cfs_bandwidth_used())
  5488. return;
  5489. if (!cfs_rq->runtime_enabled || cfs_rq->nr_running)
  5490. return;
  5491. __return_cfs_rq_runtime(cfs_rq);
  5492. }
  5493. /*
  5494. * This is done with a timer (instead of inline with bandwidth return) since
  5495. * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
  5496. */
  5497. static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)
  5498. {
  5499. u64 runtime = 0, slice = sched_cfs_bandwidth_slice();
  5500. unsigned long flags;
  5501. /* confirm we're still not at a refresh boundary */
  5502. raw_spin_lock_irqsave(&cfs_b->lock, flags);
  5503. cfs_b->slack_started = false;
  5504. if (runtime_refresh_within(cfs_b, min_bandwidth_expiration)) {
  5505. raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
  5506. return;
  5507. }
  5508. if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice)
  5509. runtime = cfs_b->runtime;
  5510. raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
  5511. if (!runtime)
  5512. return;
  5513. distribute_cfs_runtime(cfs_b);
  5514. }
  5515. /*
  5516. * When a group wakes up we want to make sure that its quota is not already
  5517. * expired/exceeded, otherwise it may be allowed to steal additional ticks of
  5518. * runtime as update_curr() throttling can not trigger until it's on-rq.
  5519. */
  5520. static void check_enqueue_throttle(struct cfs_rq *cfs_rq)
  5521. {
  5522. if (!cfs_bandwidth_used())
  5523. return;
  5524. /* an active group must be handled by the update_curr()->put() path */
  5525. if (!cfs_rq->runtime_enabled || cfs_rq->curr)
  5526. return;
  5527. /* ensure the group is not already throttled */
  5528. if (cfs_rq_throttled(cfs_rq))
  5529. return;
  5530. /* update runtime allocation */
  5531. account_cfs_rq_runtime(cfs_rq, 0);
  5532. if (cfs_rq->runtime_remaining <= 0)
  5533. throttle_cfs_rq(cfs_rq);
  5534. }
  5535. static void sync_throttle(struct task_group *tg, int cpu)
  5536. {
  5537. struct cfs_rq *pcfs_rq, *cfs_rq;
  5538. if (!cfs_bandwidth_used())
  5539. return;
  5540. if (!tg->parent)
  5541. return;
  5542. cfs_rq = tg->cfs_rq[cpu];
  5543. pcfs_rq = tg->parent->cfs_rq[cpu];
  5544. cfs_rq->throttle_count = pcfs_rq->throttle_count;
  5545. cfs_rq->throttled_clock_pelt = rq_clock_pelt(cpu_rq(cpu));
  5546. }
  5547. /* conditionally throttle active cfs_rq's from put_prev_entity() */
  5548. static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  5549. {
  5550. if (!cfs_bandwidth_used())
  5551. return false;
  5552. if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0))
  5553. return false;
  5554. /*
  5555. * it's possible for a throttled entity to be forced into a running
  5556. * state (e.g. set_curr_task), in this case we're finished.
  5557. */
  5558. if (cfs_rq_throttled(cfs_rq))
  5559. return true;
  5560. return throttle_cfs_rq(cfs_rq);
  5561. }
  5562. static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer)
  5563. {
  5564. struct cfs_bandwidth *cfs_b =
  5565. container_of(timer, struct cfs_bandwidth, slack_timer);
  5566. do_sched_cfs_slack_timer(cfs_b);
  5567. return HRTIMER_NORESTART;
  5568. }
  5569. extern const u64 max_cfs_quota_period;
  5570. static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)
  5571. {
  5572. struct cfs_bandwidth *cfs_b =
  5573. container_of(timer, struct cfs_bandwidth, period_timer);
  5574. unsigned long flags;
  5575. int overrun;
  5576. int idle = 0;
  5577. int count = 0;
  5578. raw_spin_lock_irqsave(&cfs_b->lock, flags);
  5579. for (;;) {
  5580. overrun = hrtimer_forward_now(timer, cfs_b->period);
  5581. if (!overrun)
  5582. break;
  5583. idle = do_sched_cfs_period_timer(cfs_b, overrun, flags);
  5584. if (++count > 3) {
  5585. u64 new, old = ktime_to_ns(cfs_b->period);
  5586. /*
  5587. * Grow period by a factor of 2 to avoid losing precision.
  5588. * Precision loss in the quota/period ratio can cause __cfs_schedulable
  5589. * to fail.
  5590. */
  5591. new = old * 2;
  5592. if (new < max_cfs_quota_period) {
  5593. cfs_b->period = ns_to_ktime(new);
  5594. cfs_b->quota *= 2;
  5595. cfs_b->burst *= 2;
  5596. pr_warn_ratelimited(
  5597. "cfs_period_timer[cpu%d]: period too short, scaling up (new cfs_period_us = %lld, cfs_quota_us = %lld)\n",
  5598. smp_processor_id(),
  5599. div_u64(new, NSEC_PER_USEC),
  5600. div_u64(cfs_b->quota, NSEC_PER_USEC));
  5601. } else {
  5602. pr_warn_ratelimited(
  5603. "cfs_period_timer[cpu%d]: period too short, but cannot scale up without losing precision (cfs_period_us = %lld, cfs_quota_us = %lld)\n",
  5604. smp_processor_id(),
  5605. div_u64(old, NSEC_PER_USEC),
  5606. div_u64(cfs_b->quota, NSEC_PER_USEC));
  5607. }
  5608. /* reset count so we don't come right back in here */
  5609. count = 0;
  5610. }
  5611. }
  5612. if (idle)
  5613. cfs_b->period_active = 0;
  5614. raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
  5615. return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
  5616. }
  5617. void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent)
  5618. {
  5619. raw_spin_lock_init(&cfs_b->lock);
  5620. cfs_b->runtime = 0;
  5621. cfs_b->quota = RUNTIME_INF;
  5622. cfs_b->period = ns_to_ktime(default_cfs_period());
  5623. cfs_b->burst = 0;
  5624. cfs_b->hierarchical_quota = parent ? parent->hierarchical_quota : RUNTIME_INF;
  5625. INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq);
  5626. hrtimer_init(&cfs_b->period_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED);
  5627. cfs_b->period_timer.function = sched_cfs_period_timer;
  5628. /* Add a random offset so that timers interleave */
  5629. hrtimer_set_expires(&cfs_b->period_timer,
  5630. get_random_u32_below(cfs_b->period));
  5631. hrtimer_init(&cfs_b->slack_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
  5632. cfs_b->slack_timer.function = sched_cfs_slack_timer;
  5633. cfs_b->slack_started = false;
  5634. }
  5635. static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  5636. {
  5637. cfs_rq->runtime_enabled = 0;
  5638. INIT_LIST_HEAD(&cfs_rq->throttled_list);
  5639. INIT_LIST_HEAD(&cfs_rq->throttled_csd_list);
  5640. }
  5641. void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
  5642. {
  5643. lockdep_assert_held(&cfs_b->lock);
  5644. if (cfs_b->period_active)
  5645. return;
  5646. cfs_b->period_active = 1;
  5647. hrtimer_forward_now(&cfs_b->period_timer, cfs_b->period);
  5648. hrtimer_start_expires(&cfs_b->period_timer, HRTIMER_MODE_ABS_PINNED);
  5649. }
  5650. static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
  5651. {
  5652. int __maybe_unused i;
  5653. /* init_cfs_bandwidth() was not called */
  5654. if (!cfs_b->throttled_cfs_rq.next)
  5655. return;
  5656. hrtimer_cancel(&cfs_b->period_timer);
  5657. hrtimer_cancel(&cfs_b->slack_timer);
  5658. /*
  5659. * It is possible that we still have some cfs_rq's pending on a CSD
  5660. * list, though this race is very rare. In order for this to occur, we
  5661. * must have raced with the last task leaving the group while there
  5662. * exist throttled cfs_rq(s), and the period_timer must have queued the
  5663. * CSD item but the remote cpu has not yet processed it. To handle this,
  5664. * we can simply flush all pending CSD work inline here. We're
  5665. * guaranteed at this point that no additional cfs_rq of this group can
  5666. * join a CSD list.
  5667. */
  5668. #ifdef CONFIG_SMP
  5669. for_each_possible_cpu(i) {
  5670. struct rq *rq = cpu_rq(i);
  5671. unsigned long flags;
  5672. if (list_empty(&rq->cfsb_csd_list))
  5673. continue;
  5674. local_irq_save(flags);
  5675. __cfsb_csd_unthrottle(rq);
  5676. local_irq_restore(flags);
  5677. }
  5678. #endif
  5679. }
  5680. /*
  5681. * Both these CPU hotplug callbacks race against unregister_fair_sched_group()
  5682. *
  5683. * The race is harmless, since modifying bandwidth settings of unhooked group
  5684. * bits doesn't do much.
  5685. */
  5686. /* cpu online callback */
  5687. static void __maybe_unused update_runtime_enabled(struct rq *rq)
  5688. {
  5689. struct task_group *tg;
  5690. lockdep_assert_rq_held(rq);
  5691. rcu_read_lock();
  5692. list_for_each_entry_rcu(tg, &task_groups, list) {
  5693. struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
  5694. struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
  5695. raw_spin_lock(&cfs_b->lock);
  5696. cfs_rq->runtime_enabled = cfs_b->quota != RUNTIME_INF;
  5697. raw_spin_unlock(&cfs_b->lock);
  5698. }
  5699. rcu_read_unlock();
  5700. }
  5701. /* cpu offline callback */
  5702. static void __maybe_unused unthrottle_offline_cfs_rqs(struct rq *rq)
  5703. {
  5704. struct task_group *tg;
  5705. lockdep_assert_rq_held(rq);
  5706. /*
  5707. * The rq clock has already been updated in the
  5708. * set_rq_offline(), so we should skip updating
  5709. * the rq clock again in unthrottle_cfs_rq().
  5710. */
  5711. rq_clock_start_loop_update(rq);
  5712. rcu_read_lock();
  5713. list_for_each_entry_rcu(tg, &task_groups, list) {
  5714. struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
  5715. if (!cfs_rq->runtime_enabled)
  5716. continue;
  5717. /*
  5718. * clock_task is not advancing so we just need to make sure
  5719. * there's some valid quota amount
  5720. */
  5721. cfs_rq->runtime_remaining = 1;
  5722. /*
  5723. * Offline rq is schedulable till CPU is completely disabled
  5724. * in take_cpu_down(), so we prevent new cfs throttling here.
  5725. */
  5726. cfs_rq->runtime_enabled = 0;
  5727. if (cfs_rq_throttled(cfs_rq))
  5728. unthrottle_cfs_rq(cfs_rq);
  5729. }
  5730. rcu_read_unlock();
  5731. rq_clock_stop_loop_update(rq);
  5732. }
  5733. bool cfs_task_bw_constrained(struct task_struct *p)
  5734. {
  5735. struct cfs_rq *cfs_rq = task_cfs_rq(p);
  5736. if (!cfs_bandwidth_used())
  5737. return false;
  5738. if (cfs_rq->runtime_enabled ||
  5739. tg_cfs_bandwidth(cfs_rq->tg)->hierarchical_quota != RUNTIME_INF)
  5740. return true;
  5741. return false;
  5742. }
  5743. #ifdef CONFIG_NO_HZ_FULL
  5744. /* called from pick_next_task_fair() */
  5745. static void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p)
  5746. {
  5747. int cpu = cpu_of(rq);
  5748. if (!cfs_bandwidth_used())
  5749. return;
  5750. if (!tick_nohz_full_cpu(cpu))
  5751. return;
  5752. if (rq->nr_running != 1)
  5753. return;
  5754. /*
  5755. * We know there is only one task runnable and we've just picked it. The
  5756. * normal enqueue path will have cleared TICK_DEP_BIT_SCHED if we will
  5757. * be otherwise able to stop the tick. Just need to check if we are using
  5758. * bandwidth control.
  5759. */
  5760. if (cfs_task_bw_constrained(p))
  5761. tick_nohz_dep_set_cpu(cpu, TICK_DEP_BIT_SCHED);
  5762. }
  5763. #endif
  5764. #else /* CONFIG_CFS_BANDWIDTH */
  5765. static inline bool cfs_bandwidth_used(void)
  5766. {
  5767. return false;
  5768. }
  5769. static void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) {}
  5770. static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq) { return false; }
  5771. static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {}
  5772. static inline void sync_throttle(struct task_group *tg, int cpu) {}
  5773. static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
  5774. static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
  5775. {
  5776. return 0;
  5777. }
  5778. static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
  5779. {
  5780. return 0;
  5781. }
  5782. static inline int throttled_lb_pair(struct task_group *tg,
  5783. int src_cpu, int dest_cpu)
  5784. {
  5785. return 0;
  5786. }
  5787. #ifdef CONFIG_FAIR_GROUP_SCHED
  5788. void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent) {}
  5789. static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
  5790. #endif
  5791. static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
  5792. {
  5793. return NULL;
  5794. }
  5795. static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
  5796. static inline void update_runtime_enabled(struct rq *rq) {}
  5797. static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {}
  5798. #ifdef CONFIG_CGROUP_SCHED
  5799. bool cfs_task_bw_constrained(struct task_struct *p)
  5800. {
  5801. return false;
  5802. }
  5803. #endif
  5804. #endif /* CONFIG_CFS_BANDWIDTH */
  5805. #if !defined(CONFIG_CFS_BANDWIDTH) || !defined(CONFIG_NO_HZ_FULL)
  5806. static inline void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p) {}
  5807. #endif
  5808. /**************************************************
  5809. * CFS operations on tasks:
  5810. */
  5811. #ifdef CONFIG_SCHED_HRTICK
  5812. static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
  5813. {
  5814. struct sched_entity *se = &p->se;
  5815. SCHED_WARN_ON(task_rq(p) != rq);
  5816. if (rq->cfs.h_nr_queued > 1) {
  5817. u64 ran = se->sum_exec_runtime - se->prev_sum_exec_runtime;
  5818. u64 slice = se->slice;
  5819. s64 delta = slice - ran;
  5820. if (delta < 0) {
  5821. if (task_current(rq, p))
  5822. resched_curr(rq);
  5823. return;
  5824. }
  5825. hrtick_start(rq, delta);
  5826. }
  5827. }
  5828. /*
  5829. * called from enqueue/dequeue and updates the hrtick when the
  5830. * current task is from our class and nr_running is low enough
  5831. * to matter.
  5832. */
  5833. static void hrtick_update(struct rq *rq)
  5834. {
  5835. struct task_struct *curr = rq->curr;
  5836. if (!hrtick_enabled_fair(rq) || curr->sched_class != &fair_sched_class)
  5837. return;
  5838. hrtick_start_fair(rq, curr);
  5839. }
  5840. #else /* !CONFIG_SCHED_HRTICK */
  5841. static inline void
  5842. hrtick_start_fair(struct rq *rq, struct task_struct *p)
  5843. {
  5844. }
  5845. static inline void hrtick_update(struct rq *rq)
  5846. {
  5847. }
  5848. #endif
  5849. #ifdef CONFIG_SMP
  5850. static inline bool cpu_overutilized(int cpu)
  5851. {
  5852. unsigned long rq_util_min, rq_util_max;
  5853. if (!sched_energy_enabled())
  5854. return false;
  5855. rq_util_min = uclamp_rq_get(cpu_rq(cpu), UCLAMP_MIN);
  5856. rq_util_max = uclamp_rq_get(cpu_rq(cpu), UCLAMP_MAX);
  5857. /* Return true only if the utilization doesn't fit CPU's capacity */
  5858. return !util_fits_cpu(cpu_util_cfs(cpu), rq_util_min, rq_util_max, cpu);
  5859. }
  5860. /*
  5861. * overutilized value make sense only if EAS is enabled
  5862. */
  5863. static inline bool is_rd_overutilized(struct root_domain *rd)
  5864. {
  5865. return !sched_energy_enabled() || READ_ONCE(rd->overutilized);
  5866. }
  5867. static inline void set_rd_overutilized(struct root_domain *rd, bool flag)
  5868. {
  5869. if (!sched_energy_enabled())
  5870. return;
  5871. WRITE_ONCE(rd->overutilized, flag);
  5872. trace_sched_overutilized_tp(rd, flag);
  5873. }
  5874. static inline void check_update_overutilized_status(struct rq *rq)
  5875. {
  5876. /*
  5877. * overutilized field is used for load balancing decisions only
  5878. * if energy aware scheduler is being used
  5879. */
  5880. if (!is_rd_overutilized(rq->rd) && cpu_overutilized(rq->cpu))
  5881. set_rd_overutilized(rq->rd, 1);
  5882. }
  5883. #else
  5884. static inline void check_update_overutilized_status(struct rq *rq) { }
  5885. #endif
  5886. /* Runqueue only has SCHED_IDLE tasks enqueued */
  5887. static int sched_idle_rq(struct rq *rq)
  5888. {
  5889. return unlikely(rq->nr_running == rq->cfs.idle_h_nr_running &&
  5890. rq->nr_running);
  5891. }
  5892. #ifdef CONFIG_SMP
  5893. static int sched_idle_cpu(int cpu)
  5894. {
  5895. return sched_idle_rq(cpu_rq(cpu));
  5896. }
  5897. #endif
  5898. static void
  5899. requeue_delayed_entity(struct sched_entity *se)
  5900. {
  5901. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  5902. /*
  5903. * se->sched_delayed should imply: se->on_rq == 1.
  5904. * Because a delayed entity is one that is still on
  5905. * the runqueue competing until elegibility.
  5906. */
  5907. SCHED_WARN_ON(!se->sched_delayed);
  5908. SCHED_WARN_ON(!se->on_rq);
  5909. if (sched_feat(DELAY_ZERO)) {
  5910. update_entity_lag(cfs_rq, se);
  5911. if (se->vlag > 0) {
  5912. cfs_rq->nr_running--;
  5913. if (se != cfs_rq->curr)
  5914. __dequeue_entity(cfs_rq, se);
  5915. se->vlag = 0;
  5916. place_entity(cfs_rq, se, 0);
  5917. if (se != cfs_rq->curr)
  5918. __enqueue_entity(cfs_rq, se);
  5919. cfs_rq->nr_running++;
  5920. }
  5921. }
  5922. update_load_avg(cfs_rq, se, 0);
  5923. clear_delayed(se);
  5924. }
  5925. /*
  5926. * The enqueue_task method is called before nr_running is
  5927. * increased. Here we update the fair scheduling stats and
  5928. * then put the task into the rbtree:
  5929. */
  5930. static void
  5931. enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
  5932. {
  5933. struct cfs_rq *cfs_rq;
  5934. struct sched_entity *se = &p->se;
  5935. int idle_h_nr_running = task_has_idle_policy(p);
  5936. int h_nr_delayed = 0;
  5937. int task_new = !(flags & ENQUEUE_WAKEUP);
  5938. int rq_h_nr_queued = rq->cfs.h_nr_queued;
  5939. u64 slice = 0;
  5940. /*
  5941. * The code below (indirectly) updates schedutil which looks at
  5942. * the cfs_rq utilization to select a frequency.
  5943. * Let's add the task's estimated utilization to the cfs_rq's
  5944. * estimated utilization, before we update schedutil.
  5945. */
  5946. if (!(p->se.sched_delayed && (task_on_rq_migrating(p) || (flags & ENQUEUE_RESTORE))))
  5947. util_est_enqueue(&rq->cfs, p);
  5948. if (flags & ENQUEUE_DELAYED) {
  5949. requeue_delayed_entity(se);
  5950. return;
  5951. }
  5952. /*
  5953. * If in_iowait is set, the code below may not trigger any cpufreq
  5954. * utilization updates, so do it here explicitly with the IOWAIT flag
  5955. * passed.
  5956. */
  5957. if (p->in_iowait)
  5958. cpufreq_update_util(rq, SCHED_CPUFREQ_IOWAIT);
  5959. if (task_new)
  5960. h_nr_delayed = !!se->sched_delayed;
  5961. for_each_sched_entity(se) {
  5962. if (se->on_rq) {
  5963. if (se->sched_delayed)
  5964. requeue_delayed_entity(se);
  5965. break;
  5966. }
  5967. cfs_rq = cfs_rq_of(se);
  5968. /*
  5969. * Basically set the slice of group entries to the min_slice of
  5970. * their respective cfs_rq. This ensures the group can service
  5971. * its entities in the desired time-frame.
  5972. */
  5973. if (slice) {
  5974. se->slice = slice;
  5975. se->custom_slice = 1;
  5976. }
  5977. enqueue_entity(cfs_rq, se, flags);
  5978. slice = cfs_rq_min_slice(cfs_rq);
  5979. if (!h_nr_delayed)
  5980. cfs_rq->h_nr_runnable++;
  5981. cfs_rq->h_nr_queued++;
  5982. cfs_rq->idle_h_nr_running += idle_h_nr_running;
  5983. cfs_rq->h_nr_delayed += h_nr_delayed;
  5984. if (cfs_rq_is_idle(cfs_rq))
  5985. idle_h_nr_running = 1;
  5986. /* end evaluation on encountering a throttled cfs_rq */
  5987. if (cfs_rq_throttled(cfs_rq))
  5988. goto enqueue_throttle;
  5989. flags = ENQUEUE_WAKEUP;
  5990. }
  5991. for_each_sched_entity(se) {
  5992. cfs_rq = cfs_rq_of(se);
  5993. update_load_avg(cfs_rq, se, UPDATE_TG);
  5994. se_update_runnable(se);
  5995. update_cfs_group(se);
  5996. se->slice = slice;
  5997. if (se != cfs_rq->curr)
  5998. min_vruntime_cb_propagate(&se->run_node, NULL);
  5999. slice = cfs_rq_min_slice(cfs_rq);
  6000. if (!h_nr_delayed)
  6001. cfs_rq->h_nr_runnable++;
  6002. cfs_rq->h_nr_queued++;
  6003. cfs_rq->idle_h_nr_running += idle_h_nr_running;
  6004. cfs_rq->h_nr_delayed += h_nr_delayed;
  6005. if (cfs_rq_is_idle(cfs_rq))
  6006. idle_h_nr_running = 1;
  6007. /* end evaluation on encountering a throttled cfs_rq */
  6008. if (cfs_rq_throttled(cfs_rq))
  6009. goto enqueue_throttle;
  6010. }
  6011. if (!rq_h_nr_queued && rq->cfs.h_nr_queued) {
  6012. /* Account for idle runtime */
  6013. if (!rq->nr_running)
  6014. dl_server_update_idle_time(rq, rq->curr);
  6015. dl_server_start(&rq->fair_server);
  6016. }
  6017. /* At this point se is NULL and we are at root level*/
  6018. add_nr_running(rq, 1);
  6019. /*
  6020. * Since new tasks are assigned an initial util_avg equal to
  6021. * half of the spare capacity of their CPU, tiny tasks have the
  6022. * ability to cross the overutilized threshold, which will
  6023. * result in the load balancer ruining all the task placement
  6024. * done by EAS. As a way to mitigate that effect, do not account
  6025. * for the first enqueue operation of new tasks during the
  6026. * overutilized flag detection.
  6027. *
  6028. * A better way of solving this problem would be to wait for
  6029. * the PELT signals of tasks to converge before taking them
  6030. * into account, but that is not straightforward to implement,
  6031. * and the following generally works well enough in practice.
  6032. */
  6033. if (!task_new)
  6034. check_update_overutilized_status(rq);
  6035. enqueue_throttle:
  6036. assert_list_leaf_cfs_rq(rq);
  6037. hrtick_update(rq);
  6038. }
  6039. static void set_next_buddy(struct sched_entity *se);
  6040. /*
  6041. * Basically dequeue_task_fair(), except it can deal with dequeue_entity()
  6042. * failing half-way through and resume the dequeue later.
  6043. *
  6044. * Returns:
  6045. * -1 - dequeue delayed
  6046. * 0 - dequeue throttled
  6047. * 1 - dequeue complete
  6048. */
  6049. static int dequeue_entities(struct rq *rq, struct sched_entity *se, int flags)
  6050. {
  6051. bool was_sched_idle = sched_idle_rq(rq);
  6052. int rq_h_nr_queued = rq->cfs.h_nr_queued;
  6053. bool task_sleep = flags & DEQUEUE_SLEEP;
  6054. bool task_delayed = flags & DEQUEUE_DELAYED;
  6055. struct task_struct *p = NULL;
  6056. int idle_h_nr_running = 0;
  6057. int h_nr_queued = 0;
  6058. int h_nr_delayed = 0;
  6059. struct cfs_rq *cfs_rq;
  6060. u64 slice = 0;
  6061. int ret = 0;
  6062. if (entity_is_task(se)) {
  6063. p = task_of(se);
  6064. h_nr_queued = 1;
  6065. idle_h_nr_running = task_has_idle_policy(p);
  6066. if (!task_sleep && !task_delayed)
  6067. h_nr_delayed = !!se->sched_delayed;
  6068. }
  6069. for_each_sched_entity(se) {
  6070. cfs_rq = cfs_rq_of(se);
  6071. if (!dequeue_entity(cfs_rq, se, flags)) {
  6072. if (p && &p->se == se)
  6073. return -1;
  6074. slice = cfs_rq_min_slice(cfs_rq);
  6075. break;
  6076. }
  6077. if (!h_nr_delayed)
  6078. cfs_rq->h_nr_runnable -= h_nr_queued;
  6079. cfs_rq->h_nr_queued -= h_nr_queued;
  6080. cfs_rq->idle_h_nr_running -= idle_h_nr_running;
  6081. cfs_rq->h_nr_delayed -= h_nr_delayed;
  6082. if (cfs_rq_is_idle(cfs_rq))
  6083. idle_h_nr_running = h_nr_queued;
  6084. /* end evaluation on encountering a throttled cfs_rq */
  6085. if (cfs_rq_throttled(cfs_rq))
  6086. goto out;
  6087. /* Don't dequeue parent if it has other entities besides us */
  6088. if (cfs_rq->load.weight) {
  6089. slice = cfs_rq_min_slice(cfs_rq);
  6090. /* Avoid re-evaluating load for this entity: */
  6091. se = parent_entity(se);
  6092. /*
  6093. * Bias pick_next to pick a task from this cfs_rq, as
  6094. * p is sleeping when it is within its sched_slice.
  6095. */
  6096. if (task_sleep && se && !throttled_hierarchy(cfs_rq))
  6097. set_next_buddy(se);
  6098. break;
  6099. }
  6100. flags |= DEQUEUE_SLEEP;
  6101. flags &= ~(DEQUEUE_DELAYED | DEQUEUE_SPECIAL);
  6102. }
  6103. for_each_sched_entity(se) {
  6104. cfs_rq = cfs_rq_of(se);
  6105. update_load_avg(cfs_rq, se, UPDATE_TG);
  6106. se_update_runnable(se);
  6107. update_cfs_group(se);
  6108. se->slice = slice;
  6109. if (se != cfs_rq->curr)
  6110. min_vruntime_cb_propagate(&se->run_node, NULL);
  6111. slice = cfs_rq_min_slice(cfs_rq);
  6112. if (!h_nr_delayed)
  6113. cfs_rq->h_nr_runnable -= h_nr_queued;
  6114. cfs_rq->h_nr_queued -= h_nr_queued;
  6115. cfs_rq->idle_h_nr_running -= idle_h_nr_running;
  6116. cfs_rq->h_nr_delayed -= h_nr_delayed;
  6117. if (cfs_rq_is_idle(cfs_rq))
  6118. idle_h_nr_running = h_nr_queued;
  6119. /* end evaluation on encountering a throttled cfs_rq */
  6120. if (cfs_rq_throttled(cfs_rq))
  6121. goto out;
  6122. }
  6123. sub_nr_running(rq, h_nr_queued);
  6124. if (rq_h_nr_queued && !rq->cfs.h_nr_queued)
  6125. dl_server_stop(&rq->fair_server);
  6126. /* balance early to pull high priority tasks */
  6127. if (unlikely(!was_sched_idle && sched_idle_rq(rq)))
  6128. rq->next_balance = jiffies;
  6129. ret = 1;
  6130. out:
  6131. if (p && task_delayed) {
  6132. SCHED_WARN_ON(!task_sleep);
  6133. SCHED_WARN_ON(p->on_rq != 1);
  6134. /* Fix-up what dequeue_task_fair() skipped */
  6135. hrtick_update(rq);
  6136. /*
  6137. * Fix-up what block_task() skipped.
  6138. *
  6139. * Must be last, @p might not be valid after this.
  6140. */
  6141. __block_task(rq, p);
  6142. }
  6143. return ret;
  6144. }
  6145. /*
  6146. * The dequeue_task method is called before nr_running is
  6147. * decreased. We remove the task from the rbtree and
  6148. * update the fair scheduling stats:
  6149. */
  6150. static bool dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
  6151. {
  6152. if (!(p->se.sched_delayed && (task_on_rq_migrating(p) || (flags & DEQUEUE_SAVE))))
  6153. util_est_dequeue(&rq->cfs, p);
  6154. util_est_update(&rq->cfs, p, flags & DEQUEUE_SLEEP);
  6155. if (dequeue_entities(rq, &p->se, flags) < 0)
  6156. return false;
  6157. /*
  6158. * Must not reference @p after dequeue_entities(DEQUEUE_DELAYED).
  6159. */
  6160. hrtick_update(rq);
  6161. return true;
  6162. }
  6163. static inline unsigned int cfs_h_nr_delayed(struct rq *rq)
  6164. {
  6165. return (rq->cfs.h_nr_queued - rq->cfs.h_nr_runnable);
  6166. }
  6167. #ifdef CONFIG_SMP
  6168. /* Working cpumask for: sched_balance_rq(), sched_balance_newidle(). */
  6169. static DEFINE_PER_CPU(cpumask_var_t, load_balance_mask);
  6170. static DEFINE_PER_CPU(cpumask_var_t, select_rq_mask);
  6171. static DEFINE_PER_CPU(cpumask_var_t, should_we_balance_tmpmask);
  6172. #ifdef CONFIG_NO_HZ_COMMON
  6173. static struct {
  6174. cpumask_var_t idle_cpus_mask;
  6175. atomic_t nr_cpus;
  6176. int has_blocked; /* Idle CPUS has blocked load */
  6177. int needs_update; /* Newly idle CPUs need their next_balance collated */
  6178. unsigned long next_balance; /* in jiffy units */
  6179. unsigned long next_blocked; /* Next update of blocked load in jiffies */
  6180. } nohz ____cacheline_aligned;
  6181. #endif /* CONFIG_NO_HZ_COMMON */
  6182. static unsigned long cpu_load(struct rq *rq)
  6183. {
  6184. return cfs_rq_load_avg(&rq->cfs);
  6185. }
  6186. /*
  6187. * cpu_load_without - compute CPU load without any contributions from *p
  6188. * @cpu: the CPU which load is requested
  6189. * @p: the task which load should be discounted
  6190. *
  6191. * The load of a CPU is defined by the load of tasks currently enqueued on that
  6192. * CPU as well as tasks which are currently sleeping after an execution on that
  6193. * CPU.
  6194. *
  6195. * This method returns the load of the specified CPU by discounting the load of
  6196. * the specified task, whenever the task is currently contributing to the CPU
  6197. * load.
  6198. */
  6199. static unsigned long cpu_load_without(struct rq *rq, struct task_struct *p)
  6200. {
  6201. struct cfs_rq *cfs_rq;
  6202. unsigned int load;
  6203. /* Task has no contribution or is new */
  6204. if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
  6205. return cpu_load(rq);
  6206. cfs_rq = &rq->cfs;
  6207. load = READ_ONCE(cfs_rq->avg.load_avg);
  6208. /* Discount task's util from CPU's util */
  6209. lsub_positive(&load, task_h_load(p));
  6210. return load;
  6211. }
  6212. static unsigned long cpu_runnable(struct rq *rq)
  6213. {
  6214. return cfs_rq_runnable_avg(&rq->cfs);
  6215. }
  6216. static unsigned long cpu_runnable_without(struct rq *rq, struct task_struct *p)
  6217. {
  6218. struct cfs_rq *cfs_rq;
  6219. unsigned int runnable;
  6220. /* Task has no contribution or is new */
  6221. if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
  6222. return cpu_runnable(rq);
  6223. cfs_rq = &rq->cfs;
  6224. runnable = READ_ONCE(cfs_rq->avg.runnable_avg);
  6225. /* Discount task's runnable from CPU's runnable */
  6226. lsub_positive(&runnable, p->se.avg.runnable_avg);
  6227. return runnable;
  6228. }
  6229. static unsigned long capacity_of(int cpu)
  6230. {
  6231. return cpu_rq(cpu)->cpu_capacity;
  6232. }
  6233. static void record_wakee(struct task_struct *p)
  6234. {
  6235. /*
  6236. * Only decay a single time; tasks that have less then 1 wakeup per
  6237. * jiffy will not have built up many flips.
  6238. */
  6239. if (time_after(jiffies, current->wakee_flip_decay_ts + HZ)) {
  6240. current->wakee_flips >>= 1;
  6241. current->wakee_flip_decay_ts = jiffies;
  6242. }
  6243. if (current->last_wakee != p) {
  6244. current->last_wakee = p;
  6245. current->wakee_flips++;
  6246. }
  6247. }
  6248. /*
  6249. * Detect M:N waker/wakee relationships via a switching-frequency heuristic.
  6250. *
  6251. * A waker of many should wake a different task than the one last awakened
  6252. * at a frequency roughly N times higher than one of its wakees.
  6253. *
  6254. * In order to determine whether we should let the load spread vs consolidating
  6255. * to shared cache, we look for a minimum 'flip' frequency of llc_size in one
  6256. * partner, and a factor of lls_size higher frequency in the other.
  6257. *
  6258. * With both conditions met, we can be relatively sure that the relationship is
  6259. * non-monogamous, with partner count exceeding socket size.
  6260. *
  6261. * Waker/wakee being client/server, worker/dispatcher, interrupt source or
  6262. * whatever is irrelevant, spread criteria is apparent partner count exceeds
  6263. * socket size.
  6264. */
  6265. static int wake_wide(struct task_struct *p)
  6266. {
  6267. unsigned int master = current->wakee_flips;
  6268. unsigned int slave = p->wakee_flips;
  6269. int factor = __this_cpu_read(sd_llc_size);
  6270. if (master < slave)
  6271. swap(master, slave);
  6272. if (slave < factor || master < slave * factor)
  6273. return 0;
  6274. return 1;
  6275. }
  6276. /*
  6277. * The purpose of wake_affine() is to quickly determine on which CPU we can run
  6278. * soonest. For the purpose of speed we only consider the waking and previous
  6279. * CPU.
  6280. *
  6281. * wake_affine_idle() - only considers 'now', it check if the waking CPU is
  6282. * cache-affine and is (or will be) idle.
  6283. *
  6284. * wake_affine_weight() - considers the weight to reflect the average
  6285. * scheduling latency of the CPUs. This seems to work
  6286. * for the overloaded case.
  6287. */
  6288. static int
  6289. wake_affine_idle(int this_cpu, int prev_cpu, int sync)
  6290. {
  6291. /*
  6292. * If this_cpu is idle, it implies the wakeup is from interrupt
  6293. * context. Only allow the move if cache is shared. Otherwise an
  6294. * interrupt intensive workload could force all tasks onto one
  6295. * node depending on the IO topology or IRQ affinity settings.
  6296. *
  6297. * If the prev_cpu is idle and cache affine then avoid a migration.
  6298. * There is no guarantee that the cache hot data from an interrupt
  6299. * is more important than cache hot data on the prev_cpu and from
  6300. * a cpufreq perspective, it's better to have higher utilisation
  6301. * on one CPU.
  6302. */
  6303. if (available_idle_cpu(this_cpu) && cpus_share_cache(this_cpu, prev_cpu))
  6304. return available_idle_cpu(prev_cpu) ? prev_cpu : this_cpu;
  6305. if (sync) {
  6306. struct rq *rq = cpu_rq(this_cpu);
  6307. if ((rq->nr_running - cfs_h_nr_delayed(rq)) == 1)
  6308. return this_cpu;
  6309. }
  6310. if (available_idle_cpu(prev_cpu))
  6311. return prev_cpu;
  6312. return nr_cpumask_bits;
  6313. }
  6314. static int
  6315. wake_affine_weight(struct sched_domain *sd, struct task_struct *p,
  6316. int this_cpu, int prev_cpu, int sync)
  6317. {
  6318. s64 this_eff_load, prev_eff_load;
  6319. unsigned long task_load;
  6320. this_eff_load = cpu_load(cpu_rq(this_cpu));
  6321. if (sync) {
  6322. unsigned long current_load = task_h_load(current);
  6323. if (current_load > this_eff_load)
  6324. return this_cpu;
  6325. this_eff_load -= current_load;
  6326. }
  6327. task_load = task_h_load(p);
  6328. this_eff_load += task_load;
  6329. if (sched_feat(WA_BIAS))
  6330. this_eff_load *= 100;
  6331. this_eff_load *= capacity_of(prev_cpu);
  6332. prev_eff_load = cpu_load(cpu_rq(prev_cpu));
  6333. prev_eff_load -= task_load;
  6334. if (sched_feat(WA_BIAS))
  6335. prev_eff_load *= 100 + (sd->imbalance_pct - 100) / 2;
  6336. prev_eff_load *= capacity_of(this_cpu);
  6337. /*
  6338. * If sync, adjust the weight of prev_eff_load such that if
  6339. * prev_eff == this_eff that select_idle_sibling() will consider
  6340. * stacking the wakee on top of the waker if no other CPU is
  6341. * idle.
  6342. */
  6343. if (sync)
  6344. prev_eff_load += 1;
  6345. return this_eff_load < prev_eff_load ? this_cpu : nr_cpumask_bits;
  6346. }
  6347. static int wake_affine(struct sched_domain *sd, struct task_struct *p,
  6348. int this_cpu, int prev_cpu, int sync)
  6349. {
  6350. int target = nr_cpumask_bits;
  6351. if (sched_feat(WA_IDLE))
  6352. target = wake_affine_idle(this_cpu, prev_cpu, sync);
  6353. if (sched_feat(WA_WEIGHT) && target == nr_cpumask_bits)
  6354. target = wake_affine_weight(sd, p, this_cpu, prev_cpu, sync);
  6355. schedstat_inc(p->stats.nr_wakeups_affine_attempts);
  6356. if (target != this_cpu)
  6357. return prev_cpu;
  6358. schedstat_inc(sd->ttwu_move_affine);
  6359. schedstat_inc(p->stats.nr_wakeups_affine);
  6360. return target;
  6361. }
  6362. static struct sched_group *
  6363. sched_balance_find_dst_group(struct sched_domain *sd, struct task_struct *p, int this_cpu);
  6364. /*
  6365. * sched_balance_find_dst_group_cpu - find the idlest CPU among the CPUs in the group.
  6366. */
  6367. static int
  6368. sched_balance_find_dst_group_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
  6369. {
  6370. unsigned long load, min_load = ULONG_MAX;
  6371. unsigned int min_exit_latency = UINT_MAX;
  6372. u64 latest_idle_timestamp = 0;
  6373. int least_loaded_cpu = this_cpu;
  6374. int shallowest_idle_cpu = -1;
  6375. int i;
  6376. /* Check if we have any choice: */
  6377. if (group->group_weight == 1)
  6378. return cpumask_first(sched_group_span(group));
  6379. /* Traverse only the allowed CPUs */
  6380. for_each_cpu_and(i, sched_group_span(group), p->cpus_ptr) {
  6381. struct rq *rq = cpu_rq(i);
  6382. if (!sched_core_cookie_match(rq, p))
  6383. continue;
  6384. if (sched_idle_cpu(i))
  6385. return i;
  6386. if (available_idle_cpu(i)) {
  6387. struct cpuidle_state *idle = idle_get_state(rq);
  6388. if (idle && idle->exit_latency < min_exit_latency) {
  6389. /*
  6390. * We give priority to a CPU whose idle state
  6391. * has the smallest exit latency irrespective
  6392. * of any idle timestamp.
  6393. */
  6394. min_exit_latency = idle->exit_latency;
  6395. latest_idle_timestamp = rq->idle_stamp;
  6396. shallowest_idle_cpu = i;
  6397. } else if ((!idle || idle->exit_latency == min_exit_latency) &&
  6398. rq->idle_stamp > latest_idle_timestamp) {
  6399. /*
  6400. * If equal or no active idle state, then
  6401. * the most recently idled CPU might have
  6402. * a warmer cache.
  6403. */
  6404. latest_idle_timestamp = rq->idle_stamp;
  6405. shallowest_idle_cpu = i;
  6406. }
  6407. } else if (shallowest_idle_cpu == -1) {
  6408. load = cpu_load(cpu_rq(i));
  6409. if (load < min_load) {
  6410. min_load = load;
  6411. least_loaded_cpu = i;
  6412. }
  6413. }
  6414. }
  6415. return shallowest_idle_cpu != -1 ? shallowest_idle_cpu : least_loaded_cpu;
  6416. }
  6417. static inline int sched_balance_find_dst_cpu(struct sched_domain *sd, struct task_struct *p,
  6418. int cpu, int prev_cpu, int sd_flag)
  6419. {
  6420. int new_cpu = cpu;
  6421. if (!cpumask_intersects(sched_domain_span(sd), p->cpus_ptr))
  6422. return prev_cpu;
  6423. /*
  6424. * We need task's util for cpu_util_without, sync it up to
  6425. * prev_cpu's last_update_time.
  6426. */
  6427. if (!(sd_flag & SD_BALANCE_FORK))
  6428. sync_entity_load_avg(&p->se);
  6429. while (sd) {
  6430. struct sched_group *group;
  6431. struct sched_domain *tmp;
  6432. int weight;
  6433. if (!(sd->flags & sd_flag)) {
  6434. sd = sd->child;
  6435. continue;
  6436. }
  6437. group = sched_balance_find_dst_group(sd, p, cpu);
  6438. if (!group) {
  6439. sd = sd->child;
  6440. continue;
  6441. }
  6442. new_cpu = sched_balance_find_dst_group_cpu(group, p, cpu);
  6443. if (new_cpu == cpu) {
  6444. /* Now try balancing at a lower domain level of 'cpu': */
  6445. sd = sd->child;
  6446. continue;
  6447. }
  6448. /* Now try balancing at a lower domain level of 'new_cpu': */
  6449. cpu = new_cpu;
  6450. weight = sd->span_weight;
  6451. sd = NULL;
  6452. for_each_domain(cpu, tmp) {
  6453. if (weight <= tmp->span_weight)
  6454. break;
  6455. if (tmp->flags & sd_flag)
  6456. sd = tmp;
  6457. }
  6458. }
  6459. return new_cpu;
  6460. }
  6461. static inline int __select_idle_cpu(int cpu, struct task_struct *p)
  6462. {
  6463. if ((available_idle_cpu(cpu) || sched_idle_cpu(cpu)) &&
  6464. sched_cpu_cookie_match(cpu_rq(cpu), p))
  6465. return cpu;
  6466. return -1;
  6467. }
  6468. #ifdef CONFIG_SCHED_SMT
  6469. DEFINE_STATIC_KEY_FALSE(sched_smt_present);
  6470. EXPORT_SYMBOL_GPL(sched_smt_present);
  6471. static inline void set_idle_cores(int cpu, int val)
  6472. {
  6473. struct sched_domain_shared *sds;
  6474. sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
  6475. if (sds)
  6476. WRITE_ONCE(sds->has_idle_cores, val);
  6477. }
  6478. static inline bool test_idle_cores(int cpu)
  6479. {
  6480. struct sched_domain_shared *sds;
  6481. sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
  6482. if (sds)
  6483. return READ_ONCE(sds->has_idle_cores);
  6484. return false;
  6485. }
  6486. /*
  6487. * Scans the local SMT mask to see if the entire core is idle, and records this
  6488. * information in sd_llc_shared->has_idle_cores.
  6489. *
  6490. * Since SMT siblings share all cache levels, inspecting this limited remote
  6491. * state should be fairly cheap.
  6492. */
  6493. void __update_idle_core(struct rq *rq)
  6494. {
  6495. int core = cpu_of(rq);
  6496. int cpu;
  6497. rcu_read_lock();
  6498. if (test_idle_cores(core))
  6499. goto unlock;
  6500. for_each_cpu(cpu, cpu_smt_mask(core)) {
  6501. if (cpu == core)
  6502. continue;
  6503. if (!available_idle_cpu(cpu))
  6504. goto unlock;
  6505. }
  6506. set_idle_cores(core, 1);
  6507. unlock:
  6508. rcu_read_unlock();
  6509. }
  6510. /*
  6511. * Scan the entire LLC domain for idle cores; this dynamically switches off if
  6512. * there are no idle cores left in the system; tracked through
  6513. * sd_llc->shared->has_idle_cores and enabled through update_idle_core() above.
  6514. */
  6515. static int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu)
  6516. {
  6517. bool idle = true;
  6518. int cpu;
  6519. for_each_cpu(cpu, cpu_smt_mask(core)) {
  6520. if (!available_idle_cpu(cpu)) {
  6521. idle = false;
  6522. if (*idle_cpu == -1) {
  6523. if (sched_idle_cpu(cpu) && cpumask_test_cpu(cpu, cpus)) {
  6524. *idle_cpu = cpu;
  6525. break;
  6526. }
  6527. continue;
  6528. }
  6529. break;
  6530. }
  6531. if (*idle_cpu == -1 && cpumask_test_cpu(cpu, cpus))
  6532. *idle_cpu = cpu;
  6533. }
  6534. if (idle)
  6535. return core;
  6536. cpumask_andnot(cpus, cpus, cpu_smt_mask(core));
  6537. return -1;
  6538. }
  6539. /*
  6540. * Scan the local SMT mask for idle CPUs.
  6541. */
  6542. static int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target)
  6543. {
  6544. int cpu;
  6545. for_each_cpu_and(cpu, cpu_smt_mask(target), p->cpus_ptr) {
  6546. if (cpu == target)
  6547. continue;
  6548. /*
  6549. * Check if the CPU is in the LLC scheduling domain of @target.
  6550. * Due to isolcpus, there is no guarantee that all the siblings are in the domain.
  6551. */
  6552. if (!cpumask_test_cpu(cpu, sched_domain_span(sd)))
  6553. continue;
  6554. if (available_idle_cpu(cpu) || sched_idle_cpu(cpu))
  6555. return cpu;
  6556. }
  6557. return -1;
  6558. }
  6559. #else /* CONFIG_SCHED_SMT */
  6560. static inline void set_idle_cores(int cpu, int val)
  6561. {
  6562. }
  6563. static inline bool test_idle_cores(int cpu)
  6564. {
  6565. return false;
  6566. }
  6567. static inline int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu)
  6568. {
  6569. return __select_idle_cpu(core, p);
  6570. }
  6571. static inline int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target)
  6572. {
  6573. return -1;
  6574. }
  6575. #endif /* CONFIG_SCHED_SMT */
  6576. /*
  6577. * Scan the LLC domain for idle CPUs; this is dynamically regulated by
  6578. * comparing the average scan cost (tracked in sd->avg_scan_cost) against the
  6579. * average idle time for this rq (as found in rq->avg_idle).
  6580. */
  6581. static int select_idle_cpu(struct task_struct *p, struct sched_domain *sd, bool has_idle_core, int target)
  6582. {
  6583. struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
  6584. int i, cpu, idle_cpu = -1, nr = INT_MAX;
  6585. struct sched_domain_shared *sd_share;
  6586. cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr);
  6587. if (sched_feat(SIS_UTIL)) {
  6588. sd_share = rcu_dereference(per_cpu(sd_llc_shared, target));
  6589. if (sd_share) {
  6590. /* because !--nr is the condition to stop scan */
  6591. nr = READ_ONCE(sd_share->nr_idle_scan) + 1;
  6592. /* overloaded LLC is unlikely to have idle cpu/core */
  6593. if (nr == 1)
  6594. return -1;
  6595. }
  6596. }
  6597. if (static_branch_unlikely(&sched_cluster_active)) {
  6598. struct sched_group *sg = sd->groups;
  6599. if (sg->flags & SD_CLUSTER) {
  6600. for_each_cpu_wrap(cpu, sched_group_span(sg), target + 1) {
  6601. if (!cpumask_test_cpu(cpu, cpus))
  6602. continue;
  6603. if (has_idle_core) {
  6604. i = select_idle_core(p, cpu, cpus, &idle_cpu);
  6605. if ((unsigned int)i < nr_cpumask_bits)
  6606. return i;
  6607. } else {
  6608. if (--nr <= 0)
  6609. return -1;
  6610. idle_cpu = __select_idle_cpu(cpu, p);
  6611. if ((unsigned int)idle_cpu < nr_cpumask_bits)
  6612. return idle_cpu;
  6613. }
  6614. }
  6615. cpumask_andnot(cpus, cpus, sched_group_span(sg));
  6616. }
  6617. }
  6618. for_each_cpu_wrap(cpu, cpus, target + 1) {
  6619. if (has_idle_core) {
  6620. i = select_idle_core(p, cpu, cpus, &idle_cpu);
  6621. if ((unsigned int)i < nr_cpumask_bits)
  6622. return i;
  6623. } else {
  6624. if (--nr <= 0)
  6625. return -1;
  6626. idle_cpu = __select_idle_cpu(cpu, p);
  6627. if ((unsigned int)idle_cpu < nr_cpumask_bits)
  6628. break;
  6629. }
  6630. }
  6631. if (has_idle_core)
  6632. set_idle_cores(target, false);
  6633. return idle_cpu;
  6634. }
  6635. /*
  6636. * Scan the asym_capacity domain for idle CPUs; pick the first idle one on which
  6637. * the task fits. If no CPU is big enough, but there are idle ones, try to
  6638. * maximize capacity.
  6639. */
  6640. static int
  6641. select_idle_capacity(struct task_struct *p, struct sched_domain *sd, int target)
  6642. {
  6643. unsigned long task_util, util_min, util_max, best_cap = 0;
  6644. int fits, best_fits = 0;
  6645. int cpu, best_cpu = -1;
  6646. struct cpumask *cpus;
  6647. cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
  6648. cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr);
  6649. task_util = task_util_est(p);
  6650. util_min = uclamp_eff_value(p, UCLAMP_MIN);
  6651. util_max = uclamp_eff_value(p, UCLAMP_MAX);
  6652. for_each_cpu_wrap(cpu, cpus, target) {
  6653. unsigned long cpu_cap = capacity_of(cpu);
  6654. if (!available_idle_cpu(cpu) && !sched_idle_cpu(cpu))
  6655. continue;
  6656. fits = util_fits_cpu(task_util, util_min, util_max, cpu);
  6657. /* This CPU fits with all requirements */
  6658. if (fits > 0)
  6659. return cpu;
  6660. /*
  6661. * Only the min performance hint (i.e. uclamp_min) doesn't fit.
  6662. * Look for the CPU with best capacity.
  6663. */
  6664. else if (fits < 0)
  6665. cpu_cap = get_actual_cpu_capacity(cpu);
  6666. /*
  6667. * First, select CPU which fits better (-1 being better than 0).
  6668. * Then, select the one with best capacity at same level.
  6669. */
  6670. if ((fits < best_fits) ||
  6671. ((fits == best_fits) && (cpu_cap > best_cap))) {
  6672. best_cap = cpu_cap;
  6673. best_cpu = cpu;
  6674. best_fits = fits;
  6675. }
  6676. }
  6677. return best_cpu;
  6678. }
  6679. static inline bool asym_fits_cpu(unsigned long util,
  6680. unsigned long util_min,
  6681. unsigned long util_max,
  6682. int cpu)
  6683. {
  6684. if (sched_asym_cpucap_active())
  6685. /*
  6686. * Return true only if the cpu fully fits the task requirements
  6687. * which include the utilization and the performance hints.
  6688. */
  6689. return (util_fits_cpu(util, util_min, util_max, cpu) > 0);
  6690. return true;
  6691. }
  6692. /*
  6693. * Try and locate an idle core/thread in the LLC cache domain.
  6694. */
  6695. static int select_idle_sibling(struct task_struct *p, int prev, int target)
  6696. {
  6697. bool has_idle_core = false;
  6698. struct sched_domain *sd;
  6699. unsigned long task_util, util_min, util_max;
  6700. int i, recent_used_cpu, prev_aff = -1;
  6701. /*
  6702. * On asymmetric system, update task utilization because we will check
  6703. * that the task fits with CPU's capacity.
  6704. */
  6705. if (sched_asym_cpucap_active()) {
  6706. sync_entity_load_avg(&p->se);
  6707. task_util = task_util_est(p);
  6708. util_min = uclamp_eff_value(p, UCLAMP_MIN);
  6709. util_max = uclamp_eff_value(p, UCLAMP_MAX);
  6710. }
  6711. /*
  6712. * per-cpu select_rq_mask usage
  6713. */
  6714. lockdep_assert_irqs_disabled();
  6715. if ((available_idle_cpu(target) || sched_idle_cpu(target)) &&
  6716. asym_fits_cpu(task_util, util_min, util_max, target))
  6717. return target;
  6718. /*
  6719. * If the previous CPU is cache affine and idle, don't be stupid:
  6720. */
  6721. if (prev != target && cpus_share_cache(prev, target) &&
  6722. (available_idle_cpu(prev) || sched_idle_cpu(prev)) &&
  6723. asym_fits_cpu(task_util, util_min, util_max, prev)) {
  6724. if (!static_branch_unlikely(&sched_cluster_active) ||
  6725. cpus_share_resources(prev, target))
  6726. return prev;
  6727. prev_aff = prev;
  6728. }
  6729. /*
  6730. * Allow a per-cpu kthread to stack with the wakee if the
  6731. * kworker thread and the tasks previous CPUs are the same.
  6732. * The assumption is that the wakee queued work for the
  6733. * per-cpu kthread that is now complete and the wakeup is
  6734. * essentially a sync wakeup. An obvious example of this
  6735. * pattern is IO completions.
  6736. */
  6737. if (is_per_cpu_kthread(current) &&
  6738. in_task() &&
  6739. prev == smp_processor_id() &&
  6740. this_rq()->nr_running <= 1 &&
  6741. asym_fits_cpu(task_util, util_min, util_max, prev)) {
  6742. return prev;
  6743. }
  6744. /* Check a recently used CPU as a potential idle candidate: */
  6745. recent_used_cpu = p->recent_used_cpu;
  6746. p->recent_used_cpu = prev;
  6747. if (recent_used_cpu != prev &&
  6748. recent_used_cpu != target &&
  6749. cpus_share_cache(recent_used_cpu, target) &&
  6750. (available_idle_cpu(recent_used_cpu) || sched_idle_cpu(recent_used_cpu)) &&
  6751. cpumask_test_cpu(recent_used_cpu, p->cpus_ptr) &&
  6752. asym_fits_cpu(task_util, util_min, util_max, recent_used_cpu)) {
  6753. if (!static_branch_unlikely(&sched_cluster_active) ||
  6754. cpus_share_resources(recent_used_cpu, target))
  6755. return recent_used_cpu;
  6756. } else {
  6757. recent_used_cpu = -1;
  6758. }
  6759. /*
  6760. * For asymmetric CPU capacity systems, our domain of interest is
  6761. * sd_asym_cpucapacity rather than sd_llc.
  6762. */
  6763. if (sched_asym_cpucap_active()) {
  6764. sd = rcu_dereference(per_cpu(sd_asym_cpucapacity, target));
  6765. /*
  6766. * On an asymmetric CPU capacity system where an exclusive
  6767. * cpuset defines a symmetric island (i.e. one unique
  6768. * capacity_orig value through the cpuset), the key will be set
  6769. * but the CPUs within that cpuset will not have a domain with
  6770. * SD_ASYM_CPUCAPACITY. These should follow the usual symmetric
  6771. * capacity path.
  6772. */
  6773. if (sd) {
  6774. i = select_idle_capacity(p, sd, target);
  6775. return ((unsigned)i < nr_cpumask_bits) ? i : target;
  6776. }
  6777. }
  6778. sd = rcu_dereference(per_cpu(sd_llc, target));
  6779. if (!sd)
  6780. return target;
  6781. if (sched_smt_active()) {
  6782. has_idle_core = test_idle_cores(target);
  6783. if (!has_idle_core && cpus_share_cache(prev, target)) {
  6784. i = select_idle_smt(p, sd, prev);
  6785. if ((unsigned int)i < nr_cpumask_bits)
  6786. return i;
  6787. }
  6788. }
  6789. i = select_idle_cpu(p, sd, has_idle_core, target);
  6790. if ((unsigned)i < nr_cpumask_bits)
  6791. return i;
  6792. /*
  6793. * For cluster machines which have lower sharing cache like L2 or
  6794. * LLC Tag, we tend to find an idle CPU in the target's cluster
  6795. * first. But prev_cpu or recent_used_cpu may also be a good candidate,
  6796. * use them if possible when no idle CPU found in select_idle_cpu().
  6797. */
  6798. if ((unsigned int)prev_aff < nr_cpumask_bits)
  6799. return prev_aff;
  6800. if ((unsigned int)recent_used_cpu < nr_cpumask_bits)
  6801. return recent_used_cpu;
  6802. return target;
  6803. }
  6804. /**
  6805. * cpu_util() - Estimates the amount of CPU capacity used by CFS tasks.
  6806. * @cpu: the CPU to get the utilization for
  6807. * @p: task for which the CPU utilization should be predicted or NULL
  6808. * @dst_cpu: CPU @p migrates to, -1 if @p moves from @cpu or @p == NULL
  6809. * @boost: 1 to enable boosting, otherwise 0
  6810. *
  6811. * The unit of the return value must be the same as the one of CPU capacity
  6812. * so that CPU utilization can be compared with CPU capacity.
  6813. *
  6814. * CPU utilization is the sum of running time of runnable tasks plus the
  6815. * recent utilization of currently non-runnable tasks on that CPU.
  6816. * It represents the amount of CPU capacity currently used by CFS tasks in
  6817. * the range [0..max CPU capacity] with max CPU capacity being the CPU
  6818. * capacity at f_max.
  6819. *
  6820. * The estimated CPU utilization is defined as the maximum between CPU
  6821. * utilization and sum of the estimated utilization of the currently
  6822. * runnable tasks on that CPU. It preserves a utilization "snapshot" of
  6823. * previously-executed tasks, which helps better deduce how busy a CPU will
  6824. * be when a long-sleeping task wakes up. The contribution to CPU utilization
  6825. * of such a task would be significantly decayed at this point of time.
  6826. *
  6827. * Boosted CPU utilization is defined as max(CPU runnable, CPU utilization).
  6828. * CPU contention for CFS tasks can be detected by CPU runnable > CPU
  6829. * utilization. Boosting is implemented in cpu_util() so that internal
  6830. * users (e.g. EAS) can use it next to external users (e.g. schedutil),
  6831. * latter via cpu_util_cfs_boost().
  6832. *
  6833. * CPU utilization can be higher than the current CPU capacity
  6834. * (f_curr/f_max * max CPU capacity) or even the max CPU capacity because
  6835. * of rounding errors as well as task migrations or wakeups of new tasks.
  6836. * CPU utilization has to be capped to fit into the [0..max CPU capacity]
  6837. * range. Otherwise a group of CPUs (CPU0 util = 121% + CPU1 util = 80%)
  6838. * could be seen as over-utilized even though CPU1 has 20% of spare CPU
  6839. * capacity. CPU utilization is allowed to overshoot current CPU capacity
  6840. * though since this is useful for predicting the CPU capacity required
  6841. * after task migrations (scheduler-driven DVFS).
  6842. *
  6843. * Return: (Boosted) (estimated) utilization for the specified CPU.
  6844. */
  6845. static unsigned long
  6846. cpu_util(int cpu, struct task_struct *p, int dst_cpu, int boost)
  6847. {
  6848. struct cfs_rq *cfs_rq = &cpu_rq(cpu)->cfs;
  6849. unsigned long util = READ_ONCE(cfs_rq->avg.util_avg);
  6850. unsigned long runnable;
  6851. if (boost) {
  6852. runnable = READ_ONCE(cfs_rq->avg.runnable_avg);
  6853. util = max(util, runnable);
  6854. }
  6855. /*
  6856. * If @dst_cpu is -1 or @p migrates from @cpu to @dst_cpu remove its
  6857. * contribution. If @p migrates from another CPU to @cpu add its
  6858. * contribution. In all the other cases @cpu is not impacted by the
  6859. * migration so its util_avg is already correct.
  6860. */
  6861. if (p && task_cpu(p) == cpu && dst_cpu != cpu)
  6862. lsub_positive(&util, task_util(p));
  6863. else if (p && task_cpu(p) != cpu && dst_cpu == cpu)
  6864. util += task_util(p);
  6865. if (sched_feat(UTIL_EST)) {
  6866. unsigned long util_est;
  6867. util_est = READ_ONCE(cfs_rq->avg.util_est);
  6868. /*
  6869. * During wake-up @p isn't enqueued yet and doesn't contribute
  6870. * to any cpu_rq(cpu)->cfs.avg.util_est.
  6871. * If @dst_cpu == @cpu add it to "simulate" cpu_util after @p
  6872. * has been enqueued.
  6873. *
  6874. * During exec (@dst_cpu = -1) @p is enqueued and does
  6875. * contribute to cpu_rq(cpu)->cfs.util_est.
  6876. * Remove it to "simulate" cpu_util without @p's contribution.
  6877. *
  6878. * Despite the task_on_rq_queued(@p) check there is still a
  6879. * small window for a possible race when an exec
  6880. * select_task_rq_fair() races with LB's detach_task().
  6881. *
  6882. * detach_task()
  6883. * deactivate_task()
  6884. * p->on_rq = TASK_ON_RQ_MIGRATING;
  6885. * -------------------------------- A
  6886. * dequeue_task() \
  6887. * dequeue_task_fair() + Race Time
  6888. * util_est_dequeue() /
  6889. * -------------------------------- B
  6890. *
  6891. * The additional check "current == p" is required to further
  6892. * reduce the race window.
  6893. */
  6894. if (dst_cpu == cpu)
  6895. util_est += _task_util_est(p);
  6896. else if (p && unlikely(task_on_rq_queued(p) || current == p))
  6897. lsub_positive(&util_est, _task_util_est(p));
  6898. util = max(util, util_est);
  6899. }
  6900. return min(util, arch_scale_cpu_capacity(cpu));
  6901. }
  6902. unsigned long cpu_util_cfs(int cpu)
  6903. {
  6904. return cpu_util(cpu, NULL, -1, 0);
  6905. }
  6906. unsigned long cpu_util_cfs_boost(int cpu)
  6907. {
  6908. return cpu_util(cpu, NULL, -1, 1);
  6909. }
  6910. /*
  6911. * cpu_util_without: compute cpu utilization without any contributions from *p
  6912. * @cpu: the CPU which utilization is requested
  6913. * @p: the task which utilization should be discounted
  6914. *
  6915. * The utilization of a CPU is defined by the utilization of tasks currently
  6916. * enqueued on that CPU as well as tasks which are currently sleeping after an
  6917. * execution on that CPU.
  6918. *
  6919. * This method returns the utilization of the specified CPU by discounting the
  6920. * utilization of the specified task, whenever the task is currently
  6921. * contributing to the CPU utilization.
  6922. */
  6923. static unsigned long cpu_util_without(int cpu, struct task_struct *p)
  6924. {
  6925. /* Task has no contribution or is new */
  6926. if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
  6927. p = NULL;
  6928. return cpu_util(cpu, p, -1, 0);
  6929. }
  6930. /*
  6931. * This function computes an effective utilization for the given CPU, to be
  6932. * used for frequency selection given the linear relation: f = u * f_max.
  6933. *
  6934. * The scheduler tracks the following metrics:
  6935. *
  6936. * cpu_util_{cfs,rt,dl,irq}()
  6937. * cpu_bw_dl()
  6938. *
  6939. * Where the cfs,rt and dl util numbers are tracked with the same metric and
  6940. * synchronized windows and are thus directly comparable.
  6941. *
  6942. * The cfs,rt,dl utilization are the running times measured with rq->clock_task
  6943. * which excludes things like IRQ and steal-time. These latter are then accrued
  6944. * in the IRQ utilization.
  6945. *
  6946. * The DL bandwidth number OTOH is not a measured metric but a value computed
  6947. * based on the task model parameters and gives the minimal utilization
  6948. * required to meet deadlines.
  6949. */
  6950. unsigned long effective_cpu_util(int cpu, unsigned long util_cfs,
  6951. unsigned long *min,
  6952. unsigned long *max)
  6953. {
  6954. unsigned long util, irq, scale;
  6955. struct rq *rq = cpu_rq(cpu);
  6956. scale = arch_scale_cpu_capacity(cpu);
  6957. /*
  6958. * Early check to see if IRQ/steal time saturates the CPU, can be
  6959. * because of inaccuracies in how we track these -- see
  6960. * update_irq_load_avg().
  6961. */
  6962. irq = cpu_util_irq(rq);
  6963. if (unlikely(irq >= scale)) {
  6964. if (min)
  6965. *min = scale;
  6966. if (max)
  6967. *max = scale;
  6968. return scale;
  6969. }
  6970. if (min) {
  6971. /*
  6972. * The minimum utilization returns the highest level between:
  6973. * - the computed DL bandwidth needed with the IRQ pressure which
  6974. * steals time to the deadline task.
  6975. * - The minimum performance requirement for CFS and/or RT.
  6976. */
  6977. *min = max(irq + cpu_bw_dl(rq), uclamp_rq_get(rq, UCLAMP_MIN));
  6978. /*
  6979. * When an RT task is runnable and uclamp is not used, we must
  6980. * ensure that the task will run at maximum compute capacity.
  6981. */
  6982. if (!uclamp_is_used() && rt_rq_is_runnable(&rq->rt))
  6983. *min = max(*min, scale);
  6984. }
  6985. /*
  6986. * Because the time spend on RT/DL tasks is visible as 'lost' time to
  6987. * CFS tasks and we use the same metric to track the effective
  6988. * utilization (PELT windows are synchronized) we can directly add them
  6989. * to obtain the CPU's actual utilization.
  6990. */
  6991. util = util_cfs + cpu_util_rt(rq);
  6992. util += cpu_util_dl(rq);
  6993. /*
  6994. * The maximum hint is a soft bandwidth requirement, which can be lower
  6995. * than the actual utilization because of uclamp_max requirements.
  6996. */
  6997. if (max)
  6998. *max = min(scale, uclamp_rq_get(rq, UCLAMP_MAX));
  6999. if (util >= scale)
  7000. return scale;
  7001. /*
  7002. * There is still idle time; further improve the number by using the
  7003. * IRQ metric. Because IRQ/steal time is hidden from the task clock we
  7004. * need to scale the task numbers:
  7005. *
  7006. * max - irq
  7007. * U' = irq + --------- * U
  7008. * max
  7009. */
  7010. util = scale_irq_capacity(util, irq, scale);
  7011. util += irq;
  7012. return min(scale, util);
  7013. }
  7014. unsigned long sched_cpu_util(int cpu)
  7015. {
  7016. return effective_cpu_util(cpu, cpu_util_cfs(cpu), NULL, NULL);
  7017. }
  7018. /*
  7019. * energy_env - Utilization landscape for energy estimation.
  7020. * @task_busy_time: Utilization contribution by the task for which we test the
  7021. * placement. Given by eenv_task_busy_time().
  7022. * @pd_busy_time: Utilization of the whole perf domain without the task
  7023. * contribution. Given by eenv_pd_busy_time().
  7024. * @cpu_cap: Maximum CPU capacity for the perf domain.
  7025. * @pd_cap: Entire perf domain capacity. (pd->nr_cpus * cpu_cap).
  7026. */
  7027. struct energy_env {
  7028. unsigned long task_busy_time;
  7029. unsigned long pd_busy_time;
  7030. unsigned long cpu_cap;
  7031. unsigned long pd_cap;
  7032. };
  7033. /*
  7034. * Compute the task busy time for compute_energy(). This time cannot be
  7035. * injected directly into effective_cpu_util() because of the IRQ scaling.
  7036. * The latter only makes sense with the most recent CPUs where the task has
  7037. * run.
  7038. */
  7039. static inline void eenv_task_busy_time(struct energy_env *eenv,
  7040. struct task_struct *p, int prev_cpu)
  7041. {
  7042. unsigned long busy_time, max_cap = arch_scale_cpu_capacity(prev_cpu);
  7043. unsigned long irq = cpu_util_irq(cpu_rq(prev_cpu));
  7044. if (unlikely(irq >= max_cap))
  7045. busy_time = max_cap;
  7046. else
  7047. busy_time = scale_irq_capacity(task_util_est(p), irq, max_cap);
  7048. eenv->task_busy_time = busy_time;
  7049. }
  7050. /*
  7051. * Compute the perf_domain (PD) busy time for compute_energy(). Based on the
  7052. * utilization for each @pd_cpus, it however doesn't take into account
  7053. * clamping since the ratio (utilization / cpu_capacity) is already enough to
  7054. * scale the EM reported power consumption at the (eventually clamped)
  7055. * cpu_capacity.
  7056. *
  7057. * The contribution of the task @p for which we want to estimate the
  7058. * energy cost is removed (by cpu_util()) and must be calculated
  7059. * separately (see eenv_task_busy_time). This ensures:
  7060. *
  7061. * - A stable PD utilization, no matter which CPU of that PD we want to place
  7062. * the task on.
  7063. *
  7064. * - A fair comparison between CPUs as the task contribution (task_util())
  7065. * will always be the same no matter which CPU utilization we rely on
  7066. * (util_avg or util_est).
  7067. *
  7068. * Set @eenv busy time for the PD that spans @pd_cpus. This busy time can't
  7069. * exceed @eenv->pd_cap.
  7070. */
  7071. static inline void eenv_pd_busy_time(struct energy_env *eenv,
  7072. struct cpumask *pd_cpus,
  7073. struct task_struct *p)
  7074. {
  7075. unsigned long busy_time = 0;
  7076. int cpu;
  7077. for_each_cpu(cpu, pd_cpus) {
  7078. unsigned long util = cpu_util(cpu, p, -1, 0);
  7079. busy_time += effective_cpu_util(cpu, util, NULL, NULL);
  7080. }
  7081. eenv->pd_busy_time = min(eenv->pd_cap, busy_time);
  7082. }
  7083. /*
  7084. * Compute the maximum utilization for compute_energy() when the task @p
  7085. * is placed on the cpu @dst_cpu.
  7086. *
  7087. * Returns the maximum utilization among @eenv->cpus. This utilization can't
  7088. * exceed @eenv->cpu_cap.
  7089. */
  7090. static inline unsigned long
  7091. eenv_pd_max_util(struct energy_env *eenv, struct cpumask *pd_cpus,
  7092. struct task_struct *p, int dst_cpu)
  7093. {
  7094. unsigned long max_util = 0;
  7095. int cpu;
  7096. for_each_cpu(cpu, pd_cpus) {
  7097. struct task_struct *tsk = (cpu == dst_cpu) ? p : NULL;
  7098. unsigned long util = cpu_util(cpu, p, dst_cpu, 1);
  7099. unsigned long eff_util, min, max;
  7100. /*
  7101. * Performance domain frequency: utilization clamping
  7102. * must be considered since it affects the selection
  7103. * of the performance domain frequency.
  7104. * NOTE: in case RT tasks are running, by default the min
  7105. * utilization can be max OPP.
  7106. */
  7107. eff_util = effective_cpu_util(cpu, util, &min, &max);
  7108. /* Task's uclamp can modify min and max value */
  7109. if (tsk && uclamp_is_used()) {
  7110. min = max(min, uclamp_eff_value(p, UCLAMP_MIN));
  7111. /*
  7112. * If there is no active max uclamp constraint,
  7113. * directly use task's one, otherwise keep max.
  7114. */
  7115. if (uclamp_rq_is_idle(cpu_rq(cpu)))
  7116. max = uclamp_eff_value(p, UCLAMP_MAX);
  7117. else
  7118. max = max(max, uclamp_eff_value(p, UCLAMP_MAX));
  7119. }
  7120. eff_util = sugov_effective_cpu_perf(cpu, eff_util, min, max);
  7121. max_util = max(max_util, eff_util);
  7122. }
  7123. return min(max_util, eenv->cpu_cap);
  7124. }
  7125. /*
  7126. * compute_energy(): Use the Energy Model to estimate the energy that @pd would
  7127. * consume for a given utilization landscape @eenv. When @dst_cpu < 0, the task
  7128. * contribution is ignored.
  7129. */
  7130. static inline unsigned long
  7131. compute_energy(struct energy_env *eenv, struct perf_domain *pd,
  7132. struct cpumask *pd_cpus, struct task_struct *p, int dst_cpu)
  7133. {
  7134. unsigned long max_util = eenv_pd_max_util(eenv, pd_cpus, p, dst_cpu);
  7135. unsigned long busy_time = eenv->pd_busy_time;
  7136. unsigned long energy;
  7137. if (dst_cpu >= 0)
  7138. busy_time = min(eenv->pd_cap, busy_time + eenv->task_busy_time);
  7139. energy = em_cpu_energy(pd->em_pd, max_util, busy_time, eenv->cpu_cap);
  7140. trace_sched_compute_energy_tp(p, dst_cpu, energy, max_util, busy_time);
  7141. return energy;
  7142. }
  7143. /*
  7144. * find_energy_efficient_cpu(): Find most energy-efficient target CPU for the
  7145. * waking task. find_energy_efficient_cpu() looks for the CPU with maximum
  7146. * spare capacity in each performance domain and uses it as a potential
  7147. * candidate to execute the task. Then, it uses the Energy Model to figure
  7148. * out which of the CPU candidates is the most energy-efficient.
  7149. *
  7150. * The rationale for this heuristic is as follows. In a performance domain,
  7151. * all the most energy efficient CPU candidates (according to the Energy
  7152. * Model) are those for which we'll request a low frequency. When there are
  7153. * several CPUs for which the frequency request will be the same, we don't
  7154. * have enough data to break the tie between them, because the Energy Model
  7155. * only includes active power costs. With this model, if we assume that
  7156. * frequency requests follow utilization (e.g. using schedutil), the CPU with
  7157. * the maximum spare capacity in a performance domain is guaranteed to be among
  7158. * the best candidates of the performance domain.
  7159. *
  7160. * In practice, it could be preferable from an energy standpoint to pack
  7161. * small tasks on a CPU in order to let other CPUs go in deeper idle states,
  7162. * but that could also hurt our chances to go cluster idle, and we have no
  7163. * ways to tell with the current Energy Model if this is actually a good
  7164. * idea or not. So, find_energy_efficient_cpu() basically favors
  7165. * cluster-packing, and spreading inside a cluster. That should at least be
  7166. * a good thing for latency, and this is consistent with the idea that most
  7167. * of the energy savings of EAS come from the asymmetry of the system, and
  7168. * not so much from breaking the tie between identical CPUs. That's also the
  7169. * reason why EAS is enabled in the topology code only for systems where
  7170. * SD_ASYM_CPUCAPACITY is set.
  7171. *
  7172. * NOTE: Forkees are not accepted in the energy-aware wake-up path because
  7173. * they don't have any useful utilization data yet and it's not possible to
  7174. * forecast their impact on energy consumption. Consequently, they will be
  7175. * placed by sched_balance_find_dst_cpu() on the least loaded CPU, which might turn out
  7176. * to be energy-inefficient in some use-cases. The alternative would be to
  7177. * bias new tasks towards specific types of CPUs first, or to try to infer
  7178. * their util_avg from the parent task, but those heuristics could hurt
  7179. * other use-cases too. So, until someone finds a better way to solve this,
  7180. * let's keep things simple by re-using the existing slow path.
  7181. */
  7182. static int find_energy_efficient_cpu(struct task_struct *p, int prev_cpu)
  7183. {
  7184. struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
  7185. unsigned long prev_delta = ULONG_MAX, best_delta = ULONG_MAX;
  7186. unsigned long p_util_min = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MIN) : 0;
  7187. unsigned long p_util_max = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MAX) : 1024;
  7188. struct root_domain *rd = this_rq()->rd;
  7189. int cpu, best_energy_cpu, target = -1;
  7190. int prev_fits = -1, best_fits = -1;
  7191. unsigned long best_actual_cap = 0;
  7192. unsigned long prev_actual_cap = 0;
  7193. struct sched_domain *sd;
  7194. struct perf_domain *pd;
  7195. struct energy_env eenv;
  7196. rcu_read_lock();
  7197. pd = rcu_dereference(rd->pd);
  7198. if (!pd)
  7199. goto unlock;
  7200. /*
  7201. * Energy-aware wake-up happens on the lowest sched_domain starting
  7202. * from sd_asym_cpucapacity spanning over this_cpu and prev_cpu.
  7203. */
  7204. sd = rcu_dereference(*this_cpu_ptr(&sd_asym_cpucapacity));
  7205. while (sd && !cpumask_test_cpu(prev_cpu, sched_domain_span(sd)))
  7206. sd = sd->parent;
  7207. if (!sd)
  7208. goto unlock;
  7209. target = prev_cpu;
  7210. sync_entity_load_avg(&p->se);
  7211. if (!task_util_est(p) && p_util_min == 0)
  7212. goto unlock;
  7213. eenv_task_busy_time(&eenv, p, prev_cpu);
  7214. for (; pd; pd = pd->next) {
  7215. unsigned long util_min = p_util_min, util_max = p_util_max;
  7216. unsigned long cpu_cap, cpu_actual_cap, util;
  7217. long prev_spare_cap = -1, max_spare_cap = -1;
  7218. unsigned long rq_util_min, rq_util_max;
  7219. unsigned long cur_delta, base_energy;
  7220. int max_spare_cap_cpu = -1;
  7221. int fits, max_fits = -1;
  7222. cpumask_and(cpus, perf_domain_span(pd), cpu_online_mask);
  7223. if (cpumask_empty(cpus))
  7224. continue;
  7225. /* Account external pressure for the energy estimation */
  7226. cpu = cpumask_first(cpus);
  7227. cpu_actual_cap = get_actual_cpu_capacity(cpu);
  7228. eenv.cpu_cap = cpu_actual_cap;
  7229. eenv.pd_cap = 0;
  7230. for_each_cpu(cpu, cpus) {
  7231. struct rq *rq = cpu_rq(cpu);
  7232. eenv.pd_cap += cpu_actual_cap;
  7233. if (!cpumask_test_cpu(cpu, sched_domain_span(sd)))
  7234. continue;
  7235. if (!cpumask_test_cpu(cpu, p->cpus_ptr))
  7236. continue;
  7237. util = cpu_util(cpu, p, cpu, 0);
  7238. cpu_cap = capacity_of(cpu);
  7239. /*
  7240. * Skip CPUs that cannot satisfy the capacity request.
  7241. * IOW, placing the task there would make the CPU
  7242. * overutilized. Take uclamp into account to see how
  7243. * much capacity we can get out of the CPU; this is
  7244. * aligned with sched_cpu_util().
  7245. */
  7246. if (uclamp_is_used() && !uclamp_rq_is_idle(rq)) {
  7247. /*
  7248. * Open code uclamp_rq_util_with() except for
  7249. * the clamp() part. I.e.: apply max aggregation
  7250. * only. util_fits_cpu() logic requires to
  7251. * operate on non clamped util but must use the
  7252. * max-aggregated uclamp_{min, max}.
  7253. */
  7254. rq_util_min = uclamp_rq_get(rq, UCLAMP_MIN);
  7255. rq_util_max = uclamp_rq_get(rq, UCLAMP_MAX);
  7256. util_min = max(rq_util_min, p_util_min);
  7257. util_max = max(rq_util_max, p_util_max);
  7258. }
  7259. fits = util_fits_cpu(util, util_min, util_max, cpu);
  7260. if (!fits)
  7261. continue;
  7262. lsub_positive(&cpu_cap, util);
  7263. if (cpu == prev_cpu) {
  7264. /* Always use prev_cpu as a candidate. */
  7265. prev_spare_cap = cpu_cap;
  7266. prev_fits = fits;
  7267. } else if ((fits > max_fits) ||
  7268. ((fits == max_fits) && ((long)cpu_cap > max_spare_cap))) {
  7269. /*
  7270. * Find the CPU with the maximum spare capacity
  7271. * among the remaining CPUs in the performance
  7272. * domain.
  7273. */
  7274. max_spare_cap = cpu_cap;
  7275. max_spare_cap_cpu = cpu;
  7276. max_fits = fits;
  7277. }
  7278. }
  7279. if (max_spare_cap_cpu < 0 && prev_spare_cap < 0)
  7280. continue;
  7281. eenv_pd_busy_time(&eenv, cpus, p);
  7282. /* Compute the 'base' energy of the pd, without @p */
  7283. base_energy = compute_energy(&eenv, pd, cpus, p, -1);
  7284. /* Evaluate the energy impact of using prev_cpu. */
  7285. if (prev_spare_cap > -1) {
  7286. prev_delta = compute_energy(&eenv, pd, cpus, p,
  7287. prev_cpu);
  7288. /* CPU utilization has changed */
  7289. if (prev_delta < base_energy)
  7290. goto unlock;
  7291. prev_delta -= base_energy;
  7292. prev_actual_cap = cpu_actual_cap;
  7293. best_delta = min(best_delta, prev_delta);
  7294. }
  7295. /* Evaluate the energy impact of using max_spare_cap_cpu. */
  7296. if (max_spare_cap_cpu >= 0 && max_spare_cap > prev_spare_cap) {
  7297. /* Current best energy cpu fits better */
  7298. if (max_fits < best_fits)
  7299. continue;
  7300. /*
  7301. * Both don't fit performance hint (i.e. uclamp_min)
  7302. * but best energy cpu has better capacity.
  7303. */
  7304. if ((max_fits < 0) &&
  7305. (cpu_actual_cap <= best_actual_cap))
  7306. continue;
  7307. cur_delta = compute_energy(&eenv, pd, cpus, p,
  7308. max_spare_cap_cpu);
  7309. /* CPU utilization has changed */
  7310. if (cur_delta < base_energy)
  7311. goto unlock;
  7312. cur_delta -= base_energy;
  7313. /*
  7314. * Both fit for the task but best energy cpu has lower
  7315. * energy impact.
  7316. */
  7317. if ((max_fits > 0) && (best_fits > 0) &&
  7318. (cur_delta >= best_delta))
  7319. continue;
  7320. best_delta = cur_delta;
  7321. best_energy_cpu = max_spare_cap_cpu;
  7322. best_fits = max_fits;
  7323. best_actual_cap = cpu_actual_cap;
  7324. }
  7325. }
  7326. rcu_read_unlock();
  7327. if ((best_fits > prev_fits) ||
  7328. ((best_fits > 0) && (best_delta < prev_delta)) ||
  7329. ((best_fits < 0) && (best_actual_cap > prev_actual_cap)))
  7330. target = best_energy_cpu;
  7331. return target;
  7332. unlock:
  7333. rcu_read_unlock();
  7334. return target;
  7335. }
  7336. /*
  7337. * select_task_rq_fair: Select target runqueue for the waking task in domains
  7338. * that have the relevant SD flag set. In practice, this is SD_BALANCE_WAKE,
  7339. * SD_BALANCE_FORK, or SD_BALANCE_EXEC.
  7340. *
  7341. * Balances load by selecting the idlest CPU in the idlest group, or under
  7342. * certain conditions an idle sibling CPU if the domain has SD_WAKE_AFFINE set.
  7343. *
  7344. * Returns the target CPU number.
  7345. */
  7346. static int
  7347. select_task_rq_fair(struct task_struct *p, int prev_cpu, int wake_flags)
  7348. {
  7349. int sync = (wake_flags & WF_SYNC) && !(current->flags & PF_EXITING);
  7350. struct sched_domain *tmp, *sd = NULL;
  7351. int cpu = smp_processor_id();
  7352. int new_cpu = prev_cpu;
  7353. int want_affine = 0;
  7354. /* SD_flags and WF_flags share the first nibble */
  7355. int sd_flag = wake_flags & 0xF;
  7356. /*
  7357. * required for stable ->cpus_allowed
  7358. */
  7359. lockdep_assert_held(&p->pi_lock);
  7360. if (wake_flags & WF_TTWU) {
  7361. record_wakee(p);
  7362. if ((wake_flags & WF_CURRENT_CPU) &&
  7363. cpumask_test_cpu(cpu, p->cpus_ptr))
  7364. return cpu;
  7365. if (!is_rd_overutilized(this_rq()->rd)) {
  7366. new_cpu = find_energy_efficient_cpu(p, prev_cpu);
  7367. if (new_cpu >= 0)
  7368. return new_cpu;
  7369. new_cpu = prev_cpu;
  7370. }
  7371. want_affine = !wake_wide(p) && cpumask_test_cpu(cpu, p->cpus_ptr);
  7372. }
  7373. rcu_read_lock();
  7374. for_each_domain(cpu, tmp) {
  7375. /*
  7376. * If both 'cpu' and 'prev_cpu' are part of this domain,
  7377. * cpu is a valid SD_WAKE_AFFINE target.
  7378. */
  7379. if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
  7380. cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
  7381. if (cpu != prev_cpu)
  7382. new_cpu = wake_affine(tmp, p, cpu, prev_cpu, sync);
  7383. sd = NULL; /* Prefer wake_affine over balance flags */
  7384. break;
  7385. }
  7386. /*
  7387. * Usually only true for WF_EXEC and WF_FORK, as sched_domains
  7388. * usually do not have SD_BALANCE_WAKE set. That means wakeup
  7389. * will usually go to the fast path.
  7390. */
  7391. if (tmp->flags & sd_flag)
  7392. sd = tmp;
  7393. else if (!want_affine)
  7394. break;
  7395. }
  7396. if (unlikely(sd)) {
  7397. /* Slow path */
  7398. new_cpu = sched_balance_find_dst_cpu(sd, p, cpu, prev_cpu, sd_flag);
  7399. } else if (wake_flags & WF_TTWU) { /* XXX always ? */
  7400. /* Fast path */
  7401. new_cpu = select_idle_sibling(p, prev_cpu, new_cpu);
  7402. }
  7403. rcu_read_unlock();
  7404. return new_cpu;
  7405. }
  7406. /*
  7407. * Called immediately before a task is migrated to a new CPU; task_cpu(p) and
  7408. * cfs_rq_of(p) references at time of call are still valid and identify the
  7409. * previous CPU. The caller guarantees p->pi_lock or task_rq(p)->lock is held.
  7410. */
  7411. static void migrate_task_rq_fair(struct task_struct *p, int new_cpu)
  7412. {
  7413. struct sched_entity *se = &p->se;
  7414. if (!task_on_rq_migrating(p)) {
  7415. remove_entity_load_avg(se);
  7416. /*
  7417. * Here, the task's PELT values have been updated according to
  7418. * the current rq's clock. But if that clock hasn't been
  7419. * updated in a while, a substantial idle time will be missed,
  7420. * leading to an inflation after wake-up on the new rq.
  7421. *
  7422. * Estimate the missing time from the cfs_rq last_update_time
  7423. * and update sched_avg to improve the PELT continuity after
  7424. * migration.
  7425. */
  7426. migrate_se_pelt_lag(se);
  7427. }
  7428. /* Tell new CPU we are migrated */
  7429. se->avg.last_update_time = 0;
  7430. update_scan_period(p, new_cpu);
  7431. }
  7432. static void task_dead_fair(struct task_struct *p)
  7433. {
  7434. struct sched_entity *se = &p->se;
  7435. if (se->sched_delayed) {
  7436. struct rq_flags rf;
  7437. struct rq *rq;
  7438. rq = task_rq_lock(p, &rf);
  7439. if (se->sched_delayed) {
  7440. update_rq_clock(rq);
  7441. dequeue_entities(rq, se, DEQUEUE_SLEEP | DEQUEUE_DELAYED);
  7442. }
  7443. task_rq_unlock(rq, p, &rf);
  7444. }
  7445. remove_entity_load_avg(se);
  7446. }
  7447. /*
  7448. * Set the max capacity the task is allowed to run at for misfit detection.
  7449. */
  7450. static void set_task_max_allowed_capacity(struct task_struct *p)
  7451. {
  7452. struct asym_cap_data *entry;
  7453. if (!sched_asym_cpucap_active())
  7454. return;
  7455. rcu_read_lock();
  7456. list_for_each_entry_rcu(entry, &asym_cap_list, link) {
  7457. cpumask_t *cpumask;
  7458. cpumask = cpu_capacity_span(entry);
  7459. if (!cpumask_intersects(p->cpus_ptr, cpumask))
  7460. continue;
  7461. p->max_allowed_capacity = entry->capacity;
  7462. break;
  7463. }
  7464. rcu_read_unlock();
  7465. }
  7466. static void set_cpus_allowed_fair(struct task_struct *p, struct affinity_context *ctx)
  7467. {
  7468. set_cpus_allowed_common(p, ctx);
  7469. set_task_max_allowed_capacity(p);
  7470. }
  7471. static int
  7472. balance_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
  7473. {
  7474. if (sched_fair_runnable(rq))
  7475. return 1;
  7476. return sched_balance_newidle(rq, rf) != 0;
  7477. }
  7478. #else
  7479. static inline void set_task_max_allowed_capacity(struct task_struct *p) {}
  7480. #endif /* CONFIG_SMP */
  7481. static void set_next_buddy(struct sched_entity *se)
  7482. {
  7483. for_each_sched_entity(se) {
  7484. if (SCHED_WARN_ON(!se->on_rq))
  7485. return;
  7486. if (se_is_idle(se))
  7487. return;
  7488. cfs_rq_of(se)->next = se;
  7489. }
  7490. }
  7491. /*
  7492. * Preempt the current task with a newly woken task if needed:
  7493. */
  7494. static void check_preempt_wakeup_fair(struct rq *rq, struct task_struct *p, int wake_flags)
  7495. {
  7496. struct task_struct *curr = rq->curr;
  7497. struct sched_entity *se = &curr->se, *pse = &p->se;
  7498. struct cfs_rq *cfs_rq = task_cfs_rq(curr);
  7499. int cse_is_idle, pse_is_idle;
  7500. if (unlikely(se == pse))
  7501. return;
  7502. /*
  7503. * This is possible from callers such as attach_tasks(), in which we
  7504. * unconditionally wakeup_preempt() after an enqueue (which may have
  7505. * lead to a throttle). This both saves work and prevents false
  7506. * next-buddy nomination below.
  7507. */
  7508. if (unlikely(throttled_hierarchy(cfs_rq_of(pse))))
  7509. return;
  7510. if (sched_feat(NEXT_BUDDY) && !(wake_flags & WF_FORK) && !pse->sched_delayed) {
  7511. set_next_buddy(pse);
  7512. }
  7513. /*
  7514. * We can come here with TIF_NEED_RESCHED already set from new task
  7515. * wake up path.
  7516. *
  7517. * Note: this also catches the edge-case of curr being in a throttled
  7518. * group (e.g. via set_curr_task), since update_curr() (in the
  7519. * enqueue of curr) will have resulted in resched being set. This
  7520. * prevents us from potentially nominating it as a false LAST_BUDDY
  7521. * below.
  7522. */
  7523. if (test_tsk_need_resched(curr))
  7524. return;
  7525. if (!sched_feat(WAKEUP_PREEMPTION))
  7526. return;
  7527. find_matching_se(&se, &pse);
  7528. WARN_ON_ONCE(!pse);
  7529. cse_is_idle = se_is_idle(se);
  7530. pse_is_idle = se_is_idle(pse);
  7531. /*
  7532. * Preempt an idle entity in favor of a non-idle entity (and don't preempt
  7533. * in the inverse case).
  7534. */
  7535. if (cse_is_idle && !pse_is_idle) {
  7536. /*
  7537. * When non-idle entity preempt an idle entity,
  7538. * don't give idle entity slice protection.
  7539. */
  7540. cancel_protect_slice(se);
  7541. goto preempt;
  7542. }
  7543. if (cse_is_idle != pse_is_idle)
  7544. return;
  7545. /*
  7546. * BATCH and IDLE tasks do not preempt others.
  7547. */
  7548. if (unlikely(!normal_policy(p->policy)))
  7549. return;
  7550. cfs_rq = cfs_rq_of(se);
  7551. update_curr(cfs_rq);
  7552. /*
  7553. * If @p has a shorter slice than current and @p is eligible, override
  7554. * current's slice protection in order to allow preemption.
  7555. *
  7556. * Note that even if @p does not turn out to be the most eligible
  7557. * task at this moment, current's slice protection will be lost.
  7558. */
  7559. if (do_preempt_short(cfs_rq, pse, se))
  7560. cancel_protect_slice(se);
  7561. /*
  7562. * If @p has become the most eligible task, force preemption.
  7563. */
  7564. if (pick_eevdf(cfs_rq) == pse)
  7565. goto preempt;
  7566. return;
  7567. preempt:
  7568. resched_curr(rq);
  7569. }
  7570. static struct task_struct *pick_task_fair(struct rq *rq)
  7571. {
  7572. struct sched_entity *se;
  7573. struct cfs_rq *cfs_rq;
  7574. again:
  7575. cfs_rq = &rq->cfs;
  7576. if (!cfs_rq->nr_running)
  7577. return NULL;
  7578. do {
  7579. /* Might not have done put_prev_entity() */
  7580. if (cfs_rq->curr && cfs_rq->curr->on_rq)
  7581. update_curr(cfs_rq);
  7582. if (unlikely(check_cfs_rq_runtime(cfs_rq)))
  7583. goto again;
  7584. se = pick_next_entity(rq, cfs_rq);
  7585. if (!se)
  7586. goto again;
  7587. cfs_rq = group_cfs_rq(se);
  7588. } while (cfs_rq);
  7589. return task_of(se);
  7590. }
  7591. static void __set_next_task_fair(struct rq *rq, struct task_struct *p, bool first);
  7592. static void set_next_task_fair(struct rq *rq, struct task_struct *p, bool first);
  7593. struct task_struct *
  7594. pick_next_task_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
  7595. {
  7596. struct sched_entity *se;
  7597. struct task_struct *p;
  7598. int new_tasks;
  7599. again:
  7600. p = pick_task_fair(rq);
  7601. if (!p)
  7602. goto idle;
  7603. se = &p->se;
  7604. #ifdef CONFIG_FAIR_GROUP_SCHED
  7605. if (prev->sched_class != &fair_sched_class)
  7606. goto simple;
  7607. __put_prev_set_next_dl_server(rq, prev, p);
  7608. /*
  7609. * Because of the set_next_buddy() in dequeue_task_fair() it is rather
  7610. * likely that a next task is from the same cgroup as the current.
  7611. *
  7612. * Therefore attempt to avoid putting and setting the entire cgroup
  7613. * hierarchy, only change the part that actually changes.
  7614. *
  7615. * Since we haven't yet done put_prev_entity and if the selected task
  7616. * is a different task than we started out with, try and touch the
  7617. * least amount of cfs_rqs.
  7618. */
  7619. if (prev != p) {
  7620. struct sched_entity *pse = &prev->se;
  7621. struct cfs_rq *cfs_rq;
  7622. while (!(cfs_rq = is_same_group(se, pse))) {
  7623. int se_depth = se->depth;
  7624. int pse_depth = pse->depth;
  7625. if (se_depth <= pse_depth) {
  7626. put_prev_entity(cfs_rq_of(pse), pse);
  7627. pse = parent_entity(pse);
  7628. }
  7629. if (se_depth >= pse_depth) {
  7630. set_next_entity(cfs_rq_of(se), se);
  7631. se = parent_entity(se);
  7632. }
  7633. }
  7634. put_prev_entity(cfs_rq, pse);
  7635. set_next_entity(cfs_rq, se);
  7636. __set_next_task_fair(rq, p, true);
  7637. }
  7638. return p;
  7639. simple:
  7640. #endif
  7641. put_prev_set_next_task(rq, prev, p);
  7642. return p;
  7643. idle:
  7644. if (rf) {
  7645. new_tasks = sched_balance_newidle(rq, rf);
  7646. /*
  7647. * Because sched_balance_newidle() releases (and re-acquires)
  7648. * rq->lock, it is possible for any higher priority task to
  7649. * appear. In that case we must re-start the pick_next_entity()
  7650. * loop.
  7651. */
  7652. if (new_tasks < 0)
  7653. return RETRY_TASK;
  7654. if (new_tasks > 0)
  7655. goto again;
  7656. }
  7657. /*
  7658. * rq is about to be idle, check if we need to update the
  7659. * lost_idle_time of clock_pelt
  7660. */
  7661. update_idle_rq_clock_pelt(rq);
  7662. return NULL;
  7663. }
  7664. static struct task_struct *__pick_next_task_fair(struct rq *rq, struct task_struct *prev)
  7665. {
  7666. return pick_next_task_fair(rq, prev, NULL);
  7667. }
  7668. static bool fair_server_has_tasks(struct sched_dl_entity *dl_se)
  7669. {
  7670. return !!dl_se->rq->cfs.nr_running;
  7671. }
  7672. static struct task_struct *fair_server_pick_task(struct sched_dl_entity *dl_se)
  7673. {
  7674. return pick_task_fair(dl_se->rq);
  7675. }
  7676. void fair_server_init(struct rq *rq)
  7677. {
  7678. struct sched_dl_entity *dl_se = &rq->fair_server;
  7679. init_dl_entity(dl_se);
  7680. dl_server_init(dl_se, rq, fair_server_has_tasks, fair_server_pick_task);
  7681. }
  7682. /*
  7683. * Account for a descheduled task:
  7684. */
  7685. static void put_prev_task_fair(struct rq *rq, struct task_struct *prev, struct task_struct *next)
  7686. {
  7687. struct sched_entity *se = &prev->se;
  7688. struct cfs_rq *cfs_rq;
  7689. for_each_sched_entity(se) {
  7690. cfs_rq = cfs_rq_of(se);
  7691. put_prev_entity(cfs_rq, se);
  7692. }
  7693. }
  7694. /*
  7695. * sched_yield() is very simple
  7696. */
  7697. static void yield_task_fair(struct rq *rq)
  7698. {
  7699. struct task_struct *curr = rq->curr;
  7700. struct cfs_rq *cfs_rq = task_cfs_rq(curr);
  7701. struct sched_entity *se = &curr->se;
  7702. /*
  7703. * Are we the only task in the tree?
  7704. */
  7705. if (unlikely(rq->nr_running == 1))
  7706. return;
  7707. clear_buddies(cfs_rq, se);
  7708. update_rq_clock(rq);
  7709. /*
  7710. * Update run-time statistics of the 'current'.
  7711. */
  7712. update_curr(cfs_rq);
  7713. /*
  7714. * Tell update_rq_clock() that we've just updated,
  7715. * so we don't do microscopic update in schedule()
  7716. * and double the fastpath cost.
  7717. */
  7718. rq_clock_skip_update(rq);
  7719. se->deadline += calc_delta_fair(se->slice, se);
  7720. }
  7721. static bool yield_to_task_fair(struct rq *rq, struct task_struct *p)
  7722. {
  7723. struct sched_entity *se = &p->se;
  7724. /* throttled hierarchies are not runnable */
  7725. if (!se->on_rq || throttled_hierarchy(cfs_rq_of(se)))
  7726. return false;
  7727. /* Tell the scheduler that we'd really like se to run next. */
  7728. set_next_buddy(se);
  7729. yield_task_fair(rq);
  7730. return true;
  7731. }
  7732. #ifdef CONFIG_SMP
  7733. /**************************************************
  7734. * Fair scheduling class load-balancing methods.
  7735. *
  7736. * BASICS
  7737. *
  7738. * The purpose of load-balancing is to achieve the same basic fairness the
  7739. * per-CPU scheduler provides, namely provide a proportional amount of compute
  7740. * time to each task. This is expressed in the following equation:
  7741. *
  7742. * W_i,n/P_i == W_j,n/P_j for all i,j (1)
  7743. *
  7744. * Where W_i,n is the n-th weight average for CPU i. The instantaneous weight
  7745. * W_i,0 is defined as:
  7746. *
  7747. * W_i,0 = \Sum_j w_i,j (2)
  7748. *
  7749. * Where w_i,j is the weight of the j-th runnable task on CPU i. This weight
  7750. * is derived from the nice value as per sched_prio_to_weight[].
  7751. *
  7752. * The weight average is an exponential decay average of the instantaneous
  7753. * weight:
  7754. *
  7755. * W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0 (3)
  7756. *
  7757. * C_i is the compute capacity of CPU i, typically it is the
  7758. * fraction of 'recent' time available for SCHED_OTHER task execution. But it
  7759. * can also include other factors [XXX].
  7760. *
  7761. * To achieve this balance we define a measure of imbalance which follows
  7762. * directly from (1):
  7763. *
  7764. * imb_i,j = max{ avg(W/C), W_i/C_i } - min{ avg(W/C), W_j/C_j } (4)
  7765. *
  7766. * We them move tasks around to minimize the imbalance. In the continuous
  7767. * function space it is obvious this converges, in the discrete case we get
  7768. * a few fun cases generally called infeasible weight scenarios.
  7769. *
  7770. * [XXX expand on:
  7771. * - infeasible weights;
  7772. * - local vs global optima in the discrete case. ]
  7773. *
  7774. *
  7775. * SCHED DOMAINS
  7776. *
  7777. * In order to solve the imbalance equation (4), and avoid the obvious O(n^2)
  7778. * for all i,j solution, we create a tree of CPUs that follows the hardware
  7779. * topology where each level pairs two lower groups (or better). This results
  7780. * in O(log n) layers. Furthermore we reduce the number of CPUs going up the
  7781. * tree to only the first of the previous level and we decrease the frequency
  7782. * of load-balance at each level inversely proportional to the number of CPUs in
  7783. * the groups.
  7784. *
  7785. * This yields:
  7786. *
  7787. * log_2 n 1 n
  7788. * \Sum { --- * --- * 2^i } = O(n) (5)
  7789. * i = 0 2^i 2^i
  7790. * `- size of each group
  7791. * | | `- number of CPUs doing load-balance
  7792. * | `- freq
  7793. * `- sum over all levels
  7794. *
  7795. * Coupled with a limit on how many tasks we can migrate every balance pass,
  7796. * this makes (5) the runtime complexity of the balancer.
  7797. *
  7798. * An important property here is that each CPU is still (indirectly) connected
  7799. * to every other CPU in at most O(log n) steps:
  7800. *
  7801. * The adjacency matrix of the resulting graph is given by:
  7802. *
  7803. * log_2 n
  7804. * A_i,j = \Union (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1) (6)
  7805. * k = 0
  7806. *
  7807. * And you'll find that:
  7808. *
  7809. * A^(log_2 n)_i,j != 0 for all i,j (7)
  7810. *
  7811. * Showing there's indeed a path between every CPU in at most O(log n) steps.
  7812. * The task movement gives a factor of O(m), giving a convergence complexity
  7813. * of:
  7814. *
  7815. * O(nm log n), n := nr_cpus, m := nr_tasks (8)
  7816. *
  7817. *
  7818. * WORK CONSERVING
  7819. *
  7820. * In order to avoid CPUs going idle while there's still work to do, new idle
  7821. * balancing is more aggressive and has the newly idle CPU iterate up the domain
  7822. * tree itself instead of relying on other CPUs to bring it work.
  7823. *
  7824. * This adds some complexity to both (5) and (8) but it reduces the total idle
  7825. * time.
  7826. *
  7827. * [XXX more?]
  7828. *
  7829. *
  7830. * CGROUPS
  7831. *
  7832. * Cgroups make a horror show out of (2), instead of a simple sum we get:
  7833. *
  7834. * s_k,i
  7835. * W_i,0 = \Sum_j \Prod_k w_k * ----- (9)
  7836. * S_k
  7837. *
  7838. * Where
  7839. *
  7840. * s_k,i = \Sum_j w_i,j,k and S_k = \Sum_i s_k,i (10)
  7841. *
  7842. * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on CPU i.
  7843. *
  7844. * The big problem is S_k, its a global sum needed to compute a local (W_i)
  7845. * property.
  7846. *
  7847. * [XXX write more on how we solve this.. _after_ merging pjt's patches that
  7848. * rewrite all of this once again.]
  7849. */
  7850. static unsigned long __read_mostly max_load_balance_interval = HZ/10;
  7851. enum fbq_type { regular, remote, all };
  7852. /*
  7853. * 'group_type' describes the group of CPUs at the moment of load balancing.
  7854. *
  7855. * The enum is ordered by pulling priority, with the group with lowest priority
  7856. * first so the group_type can simply be compared when selecting the busiest
  7857. * group. See update_sd_pick_busiest().
  7858. */
  7859. enum group_type {
  7860. /* The group has spare capacity that can be used to run more tasks. */
  7861. group_has_spare = 0,
  7862. /*
  7863. * The group is fully used and the tasks don't compete for more CPU
  7864. * cycles. Nevertheless, some tasks might wait before running.
  7865. */
  7866. group_fully_busy,
  7867. /*
  7868. * One task doesn't fit with CPU's capacity and must be migrated to a
  7869. * more powerful CPU.
  7870. */
  7871. group_misfit_task,
  7872. /*
  7873. * Balance SMT group that's fully busy. Can benefit from migration
  7874. * a task on SMT with busy sibling to another CPU on idle core.
  7875. */
  7876. group_smt_balance,
  7877. /*
  7878. * SD_ASYM_PACKING only: One local CPU with higher capacity is available,
  7879. * and the task should be migrated to it instead of running on the
  7880. * current CPU.
  7881. */
  7882. group_asym_packing,
  7883. /*
  7884. * The tasks' affinity constraints previously prevented the scheduler
  7885. * from balancing the load across the system.
  7886. */
  7887. group_imbalanced,
  7888. /*
  7889. * The CPU is overloaded and can't provide expected CPU cycles to all
  7890. * tasks.
  7891. */
  7892. group_overloaded
  7893. };
  7894. enum migration_type {
  7895. migrate_load = 0,
  7896. migrate_util,
  7897. migrate_task,
  7898. migrate_misfit
  7899. };
  7900. #define LBF_ALL_PINNED 0x01
  7901. #define LBF_NEED_BREAK 0x02
  7902. #define LBF_DST_PINNED 0x04
  7903. #define LBF_SOME_PINNED 0x08
  7904. #define LBF_ACTIVE_LB 0x10
  7905. struct lb_env {
  7906. struct sched_domain *sd;
  7907. struct rq *src_rq;
  7908. int src_cpu;
  7909. int dst_cpu;
  7910. struct rq *dst_rq;
  7911. struct cpumask *dst_grpmask;
  7912. int new_dst_cpu;
  7913. enum cpu_idle_type idle;
  7914. long imbalance;
  7915. /* The set of CPUs under consideration for load-balancing */
  7916. struct cpumask *cpus;
  7917. unsigned int flags;
  7918. unsigned int loop;
  7919. unsigned int loop_break;
  7920. unsigned int loop_max;
  7921. enum fbq_type fbq_type;
  7922. enum migration_type migration_type;
  7923. struct list_head tasks;
  7924. };
  7925. /*
  7926. * Is this task likely cache-hot:
  7927. */
  7928. static int task_hot(struct task_struct *p, struct lb_env *env)
  7929. {
  7930. s64 delta;
  7931. lockdep_assert_rq_held(env->src_rq);
  7932. if (p->sched_class != &fair_sched_class)
  7933. return 0;
  7934. if (unlikely(task_has_idle_policy(p)))
  7935. return 0;
  7936. /* SMT siblings share cache */
  7937. if (env->sd->flags & SD_SHARE_CPUCAPACITY)
  7938. return 0;
  7939. /*
  7940. * Buddy candidates are cache hot:
  7941. */
  7942. if (sched_feat(CACHE_HOT_BUDDY) && env->dst_rq->nr_running &&
  7943. (&p->se == cfs_rq_of(&p->se)->next))
  7944. return 1;
  7945. if (sysctl_sched_migration_cost == -1)
  7946. return 1;
  7947. /*
  7948. * Don't migrate task if the task's cookie does not match
  7949. * with the destination CPU's core cookie.
  7950. */
  7951. if (!sched_core_cookie_match(cpu_rq(env->dst_cpu), p))
  7952. return 1;
  7953. if (sysctl_sched_migration_cost == 0)
  7954. return 0;
  7955. delta = rq_clock_task(env->src_rq) - p->se.exec_start;
  7956. return delta < (s64)sysctl_sched_migration_cost;
  7957. }
  7958. #ifdef CONFIG_NUMA_BALANCING
  7959. /*
  7960. * Returns 1, if task migration degrades locality
  7961. * Returns 0, if task migration improves locality i.e migration preferred.
  7962. * Returns -1, if task migration is not affected by locality.
  7963. */
  7964. static int migrate_degrades_locality(struct task_struct *p, struct lb_env *env)
  7965. {
  7966. struct numa_group *numa_group = rcu_dereference(p->numa_group);
  7967. unsigned long src_weight, dst_weight;
  7968. int src_nid, dst_nid, dist;
  7969. if (!static_branch_likely(&sched_numa_balancing))
  7970. return -1;
  7971. if (!p->numa_faults || !(env->sd->flags & SD_NUMA))
  7972. return -1;
  7973. src_nid = cpu_to_node(env->src_cpu);
  7974. dst_nid = cpu_to_node(env->dst_cpu);
  7975. if (src_nid == dst_nid)
  7976. return -1;
  7977. /* Migrating away from the preferred node is always bad. */
  7978. if (src_nid == p->numa_preferred_nid) {
  7979. if (env->src_rq->nr_running > env->src_rq->nr_preferred_running)
  7980. return 1;
  7981. else
  7982. return -1;
  7983. }
  7984. /* Encourage migration to the preferred node. */
  7985. if (dst_nid == p->numa_preferred_nid)
  7986. return 0;
  7987. /* Leaving a core idle is often worse than degrading locality. */
  7988. if (env->idle == CPU_IDLE)
  7989. return -1;
  7990. dist = node_distance(src_nid, dst_nid);
  7991. if (numa_group) {
  7992. src_weight = group_weight(p, src_nid, dist);
  7993. dst_weight = group_weight(p, dst_nid, dist);
  7994. } else {
  7995. src_weight = task_weight(p, src_nid, dist);
  7996. dst_weight = task_weight(p, dst_nid, dist);
  7997. }
  7998. return dst_weight < src_weight;
  7999. }
  8000. #else
  8001. static inline int migrate_degrades_locality(struct task_struct *p,
  8002. struct lb_env *env)
  8003. {
  8004. return -1;
  8005. }
  8006. #endif
  8007. /*
  8008. * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
  8009. */
  8010. static
  8011. int can_migrate_task(struct task_struct *p, struct lb_env *env)
  8012. {
  8013. int tsk_cache_hot;
  8014. lockdep_assert_rq_held(env->src_rq);
  8015. if (p->sched_task_hot)
  8016. p->sched_task_hot = 0;
  8017. /*
  8018. * We do not migrate tasks that are:
  8019. * 1) throttled_lb_pair, or
  8020. * 2) cannot be migrated to this CPU due to cpus_ptr, or
  8021. * 3) running (obviously), or
  8022. * 4) are cache-hot on their current CPU.
  8023. */
  8024. if (throttled_lb_pair(task_group(p), env->src_cpu, env->dst_cpu))
  8025. return 0;
  8026. /* Disregard percpu kthreads; they are where they need to be. */
  8027. if (kthread_is_per_cpu(p))
  8028. return 0;
  8029. if (!cpumask_test_cpu(env->dst_cpu, p->cpus_ptr)) {
  8030. int cpu;
  8031. schedstat_inc(p->stats.nr_failed_migrations_affine);
  8032. env->flags |= LBF_SOME_PINNED;
  8033. /*
  8034. * Remember if this task can be migrated to any other CPU in
  8035. * our sched_group. We may want to revisit it if we couldn't
  8036. * meet load balance goals by pulling other tasks on src_cpu.
  8037. *
  8038. * Avoid computing new_dst_cpu
  8039. * - for NEWLY_IDLE
  8040. * - if we have already computed one in current iteration
  8041. * - if it's an active balance
  8042. */
  8043. if (env->idle == CPU_NEWLY_IDLE ||
  8044. env->flags & (LBF_DST_PINNED | LBF_ACTIVE_LB))
  8045. return 0;
  8046. /* Prevent to re-select dst_cpu via env's CPUs: */
  8047. for_each_cpu_and(cpu, env->dst_grpmask, env->cpus) {
  8048. if (cpumask_test_cpu(cpu, p->cpus_ptr)) {
  8049. env->flags |= LBF_DST_PINNED;
  8050. env->new_dst_cpu = cpu;
  8051. break;
  8052. }
  8053. }
  8054. return 0;
  8055. }
  8056. /* Record that we found at least one task that could run on dst_cpu */
  8057. env->flags &= ~LBF_ALL_PINNED;
  8058. if (task_on_cpu(env->src_rq, p)) {
  8059. schedstat_inc(p->stats.nr_failed_migrations_running);
  8060. return 0;
  8061. }
  8062. /*
  8063. * Aggressive migration if:
  8064. * 1) active balance
  8065. * 2) destination numa is preferred
  8066. * 3) task is cache cold, or
  8067. * 4) too many balance attempts have failed.
  8068. */
  8069. if (env->flags & LBF_ACTIVE_LB)
  8070. return 1;
  8071. tsk_cache_hot = migrate_degrades_locality(p, env);
  8072. if (tsk_cache_hot == -1)
  8073. tsk_cache_hot = task_hot(p, env);
  8074. if (tsk_cache_hot <= 0 ||
  8075. env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
  8076. if (tsk_cache_hot == 1)
  8077. p->sched_task_hot = 1;
  8078. return 1;
  8079. }
  8080. schedstat_inc(p->stats.nr_failed_migrations_hot);
  8081. return 0;
  8082. }
  8083. /*
  8084. * detach_task() -- detach the task for the migration specified in env
  8085. */
  8086. static void detach_task(struct task_struct *p, struct lb_env *env)
  8087. {
  8088. lockdep_assert_rq_held(env->src_rq);
  8089. if (p->sched_task_hot) {
  8090. p->sched_task_hot = 0;
  8091. schedstat_inc(env->sd->lb_hot_gained[env->idle]);
  8092. schedstat_inc(p->stats.nr_forced_migrations);
  8093. }
  8094. deactivate_task(env->src_rq, p, DEQUEUE_NOCLOCK);
  8095. set_task_cpu(p, env->dst_cpu);
  8096. }
  8097. /*
  8098. * detach_one_task() -- tries to dequeue exactly one task from env->src_rq, as
  8099. * part of active balancing operations within "domain".
  8100. *
  8101. * Returns a task if successful and NULL otherwise.
  8102. */
  8103. static struct task_struct *detach_one_task(struct lb_env *env)
  8104. {
  8105. struct task_struct *p;
  8106. lockdep_assert_rq_held(env->src_rq);
  8107. list_for_each_entry_reverse(p,
  8108. &env->src_rq->cfs_tasks, se.group_node) {
  8109. if (!can_migrate_task(p, env))
  8110. continue;
  8111. detach_task(p, env);
  8112. /*
  8113. * Right now, this is only the second place where
  8114. * lb_gained[env->idle] is updated (other is detach_tasks)
  8115. * so we can safely collect stats here rather than
  8116. * inside detach_tasks().
  8117. */
  8118. schedstat_inc(env->sd->lb_gained[env->idle]);
  8119. return p;
  8120. }
  8121. return NULL;
  8122. }
  8123. /*
  8124. * detach_tasks() -- tries to detach up to imbalance load/util/tasks from
  8125. * busiest_rq, as part of a balancing operation within domain "sd".
  8126. *
  8127. * Returns number of detached tasks if successful and 0 otherwise.
  8128. */
  8129. static int detach_tasks(struct lb_env *env)
  8130. {
  8131. struct list_head *tasks = &env->src_rq->cfs_tasks;
  8132. unsigned long util, load;
  8133. struct task_struct *p;
  8134. int detached = 0;
  8135. lockdep_assert_rq_held(env->src_rq);
  8136. /*
  8137. * Source run queue has been emptied by another CPU, clear
  8138. * LBF_ALL_PINNED flag as we will not test any task.
  8139. */
  8140. if (env->src_rq->nr_running <= 1) {
  8141. env->flags &= ~LBF_ALL_PINNED;
  8142. return 0;
  8143. }
  8144. if (env->imbalance <= 0)
  8145. return 0;
  8146. while (!list_empty(tasks)) {
  8147. /*
  8148. * We don't want to steal all, otherwise we may be treated likewise,
  8149. * which could at worst lead to a livelock crash.
  8150. */
  8151. if (env->idle && env->src_rq->nr_running <= 1)
  8152. break;
  8153. env->loop++;
  8154. /* We've more or less seen every task there is, call it quits */
  8155. if (env->loop > env->loop_max)
  8156. break;
  8157. /* take a breather every nr_migrate tasks */
  8158. if (env->loop > env->loop_break) {
  8159. env->loop_break += SCHED_NR_MIGRATE_BREAK;
  8160. env->flags |= LBF_NEED_BREAK;
  8161. break;
  8162. }
  8163. p = list_last_entry(tasks, struct task_struct, se.group_node);
  8164. if (!can_migrate_task(p, env))
  8165. goto next;
  8166. switch (env->migration_type) {
  8167. case migrate_load:
  8168. /*
  8169. * Depending of the number of CPUs and tasks and the
  8170. * cgroup hierarchy, task_h_load() can return a null
  8171. * value. Make sure that env->imbalance decreases
  8172. * otherwise detach_tasks() will stop only after
  8173. * detaching up to loop_max tasks.
  8174. */
  8175. load = max_t(unsigned long, task_h_load(p), 1);
  8176. if (sched_feat(LB_MIN) &&
  8177. load < 16 && !env->sd->nr_balance_failed)
  8178. goto next;
  8179. /*
  8180. * Make sure that we don't migrate too much load.
  8181. * Nevertheless, let relax the constraint if
  8182. * scheduler fails to find a good waiting task to
  8183. * migrate.
  8184. */
  8185. if (shr_bound(load, env->sd->nr_balance_failed) > env->imbalance)
  8186. goto next;
  8187. env->imbalance -= load;
  8188. break;
  8189. case migrate_util:
  8190. util = task_util_est(p);
  8191. if (shr_bound(util, env->sd->nr_balance_failed) > env->imbalance)
  8192. goto next;
  8193. env->imbalance -= util;
  8194. break;
  8195. case migrate_task:
  8196. env->imbalance--;
  8197. break;
  8198. case migrate_misfit:
  8199. /* This is not a misfit task */
  8200. if (task_fits_cpu(p, env->src_cpu))
  8201. goto next;
  8202. env->imbalance = 0;
  8203. break;
  8204. }
  8205. detach_task(p, env);
  8206. list_add(&p->se.group_node, &env->tasks);
  8207. detached++;
  8208. #ifdef CONFIG_PREEMPTION
  8209. /*
  8210. * NEWIDLE balancing is a source of latency, so preemptible
  8211. * kernels will stop after the first task is detached to minimize
  8212. * the critical section.
  8213. */
  8214. if (env->idle == CPU_NEWLY_IDLE)
  8215. break;
  8216. #endif
  8217. /*
  8218. * We only want to steal up to the prescribed amount of
  8219. * load/util/tasks.
  8220. */
  8221. if (env->imbalance <= 0)
  8222. break;
  8223. continue;
  8224. next:
  8225. if (p->sched_task_hot)
  8226. schedstat_inc(p->stats.nr_failed_migrations_hot);
  8227. list_move(&p->se.group_node, tasks);
  8228. }
  8229. /*
  8230. * Right now, this is one of only two places we collect this stat
  8231. * so we can safely collect detach_one_task() stats here rather
  8232. * than inside detach_one_task().
  8233. */
  8234. schedstat_add(env->sd->lb_gained[env->idle], detached);
  8235. return detached;
  8236. }
  8237. /*
  8238. * attach_task() -- attach the task detached by detach_task() to its new rq.
  8239. */
  8240. static void attach_task(struct rq *rq, struct task_struct *p)
  8241. {
  8242. lockdep_assert_rq_held(rq);
  8243. WARN_ON_ONCE(task_rq(p) != rq);
  8244. activate_task(rq, p, ENQUEUE_NOCLOCK);
  8245. wakeup_preempt(rq, p, 0);
  8246. }
  8247. /*
  8248. * attach_one_task() -- attaches the task returned from detach_one_task() to
  8249. * its new rq.
  8250. */
  8251. static void attach_one_task(struct rq *rq, struct task_struct *p)
  8252. {
  8253. struct rq_flags rf;
  8254. rq_lock(rq, &rf);
  8255. update_rq_clock(rq);
  8256. attach_task(rq, p);
  8257. rq_unlock(rq, &rf);
  8258. }
  8259. /*
  8260. * attach_tasks() -- attaches all tasks detached by detach_tasks() to their
  8261. * new rq.
  8262. */
  8263. static void attach_tasks(struct lb_env *env)
  8264. {
  8265. struct list_head *tasks = &env->tasks;
  8266. struct task_struct *p;
  8267. struct rq_flags rf;
  8268. rq_lock(env->dst_rq, &rf);
  8269. update_rq_clock(env->dst_rq);
  8270. while (!list_empty(tasks)) {
  8271. p = list_first_entry(tasks, struct task_struct, se.group_node);
  8272. list_del_init(&p->se.group_node);
  8273. attach_task(env->dst_rq, p);
  8274. }
  8275. rq_unlock(env->dst_rq, &rf);
  8276. }
  8277. #ifdef CONFIG_NO_HZ_COMMON
  8278. static inline bool cfs_rq_has_blocked(struct cfs_rq *cfs_rq)
  8279. {
  8280. if (cfs_rq->avg.load_avg)
  8281. return true;
  8282. if (cfs_rq->avg.util_avg)
  8283. return true;
  8284. return false;
  8285. }
  8286. static inline bool others_have_blocked(struct rq *rq)
  8287. {
  8288. if (cpu_util_rt(rq))
  8289. return true;
  8290. if (cpu_util_dl(rq))
  8291. return true;
  8292. if (hw_load_avg(rq))
  8293. return true;
  8294. if (cpu_util_irq(rq))
  8295. return true;
  8296. return false;
  8297. }
  8298. static inline void update_blocked_load_tick(struct rq *rq)
  8299. {
  8300. WRITE_ONCE(rq->last_blocked_load_update_tick, jiffies);
  8301. }
  8302. static inline void update_blocked_load_status(struct rq *rq, bool has_blocked)
  8303. {
  8304. if (!has_blocked)
  8305. rq->has_blocked_load = 0;
  8306. }
  8307. #else
  8308. static inline bool cfs_rq_has_blocked(struct cfs_rq *cfs_rq) { return false; }
  8309. static inline bool others_have_blocked(struct rq *rq) { return false; }
  8310. static inline void update_blocked_load_tick(struct rq *rq) {}
  8311. static inline void update_blocked_load_status(struct rq *rq, bool has_blocked) {}
  8312. #endif
  8313. static bool __update_blocked_others(struct rq *rq, bool *done)
  8314. {
  8315. bool updated;
  8316. /*
  8317. * update_load_avg() can call cpufreq_update_util(). Make sure that RT,
  8318. * DL and IRQ signals have been updated before updating CFS.
  8319. */
  8320. updated = update_other_load_avgs(rq);
  8321. if (others_have_blocked(rq))
  8322. *done = false;
  8323. return updated;
  8324. }
  8325. #ifdef CONFIG_FAIR_GROUP_SCHED
  8326. static bool __update_blocked_fair(struct rq *rq, bool *done)
  8327. {
  8328. struct cfs_rq *cfs_rq, *pos;
  8329. bool decayed = false;
  8330. int cpu = cpu_of(rq);
  8331. /*
  8332. * Iterates the task_group tree in a bottom up fashion, see
  8333. * list_add_leaf_cfs_rq() for details.
  8334. */
  8335. for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) {
  8336. struct sched_entity *se;
  8337. if (update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq)) {
  8338. update_tg_load_avg(cfs_rq);
  8339. if (cfs_rq->nr_running == 0)
  8340. update_idle_cfs_rq_clock_pelt(cfs_rq);
  8341. if (cfs_rq == &rq->cfs)
  8342. decayed = true;
  8343. }
  8344. /* Propagate pending load changes to the parent, if any: */
  8345. se = cfs_rq->tg->se[cpu];
  8346. if (se && !skip_blocked_update(se))
  8347. update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
  8348. /*
  8349. * There can be a lot of idle CPU cgroups. Don't let fully
  8350. * decayed cfs_rqs linger on the list.
  8351. */
  8352. if (cfs_rq_is_decayed(cfs_rq))
  8353. list_del_leaf_cfs_rq(cfs_rq);
  8354. /* Don't need periodic decay once load/util_avg are null */
  8355. if (cfs_rq_has_blocked(cfs_rq))
  8356. *done = false;
  8357. }
  8358. return decayed;
  8359. }
  8360. /*
  8361. * Compute the hierarchical load factor for cfs_rq and all its ascendants.
  8362. * This needs to be done in a top-down fashion because the load of a child
  8363. * group is a fraction of its parents load.
  8364. */
  8365. static void update_cfs_rq_h_load(struct cfs_rq *cfs_rq)
  8366. {
  8367. struct rq *rq = rq_of(cfs_rq);
  8368. struct sched_entity *se = cfs_rq->tg->se[cpu_of(rq)];
  8369. unsigned long now = jiffies;
  8370. unsigned long load;
  8371. if (cfs_rq->last_h_load_update == now)
  8372. return;
  8373. WRITE_ONCE(cfs_rq->h_load_next, NULL);
  8374. for_each_sched_entity(se) {
  8375. cfs_rq = cfs_rq_of(se);
  8376. WRITE_ONCE(cfs_rq->h_load_next, se);
  8377. if (cfs_rq->last_h_load_update == now)
  8378. break;
  8379. }
  8380. if (!se) {
  8381. cfs_rq->h_load = cfs_rq_load_avg(cfs_rq);
  8382. cfs_rq->last_h_load_update = now;
  8383. }
  8384. while ((se = READ_ONCE(cfs_rq->h_load_next)) != NULL) {
  8385. load = cfs_rq->h_load;
  8386. load = div64_ul(load * se->avg.load_avg,
  8387. cfs_rq_load_avg(cfs_rq) + 1);
  8388. cfs_rq = group_cfs_rq(se);
  8389. cfs_rq->h_load = load;
  8390. cfs_rq->last_h_load_update = now;
  8391. }
  8392. }
  8393. static unsigned long task_h_load(struct task_struct *p)
  8394. {
  8395. struct cfs_rq *cfs_rq = task_cfs_rq(p);
  8396. update_cfs_rq_h_load(cfs_rq);
  8397. return div64_ul(p->se.avg.load_avg * cfs_rq->h_load,
  8398. cfs_rq_load_avg(cfs_rq) + 1);
  8399. }
  8400. #else
  8401. static bool __update_blocked_fair(struct rq *rq, bool *done)
  8402. {
  8403. struct cfs_rq *cfs_rq = &rq->cfs;
  8404. bool decayed;
  8405. decayed = update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq);
  8406. if (cfs_rq_has_blocked(cfs_rq))
  8407. *done = false;
  8408. return decayed;
  8409. }
  8410. static unsigned long task_h_load(struct task_struct *p)
  8411. {
  8412. return p->se.avg.load_avg;
  8413. }
  8414. #endif
  8415. static void sched_balance_update_blocked_averages(int cpu)
  8416. {
  8417. bool decayed = false, done = true;
  8418. struct rq *rq = cpu_rq(cpu);
  8419. struct rq_flags rf;
  8420. rq_lock_irqsave(rq, &rf);
  8421. update_blocked_load_tick(rq);
  8422. update_rq_clock(rq);
  8423. decayed |= __update_blocked_others(rq, &done);
  8424. decayed |= __update_blocked_fair(rq, &done);
  8425. update_blocked_load_status(rq, !done);
  8426. if (decayed)
  8427. cpufreq_update_util(rq, 0);
  8428. rq_unlock_irqrestore(rq, &rf);
  8429. }
  8430. /********** Helpers for sched_balance_find_src_group ************************/
  8431. /*
  8432. * sg_lb_stats - stats of a sched_group required for load-balancing:
  8433. */
  8434. struct sg_lb_stats {
  8435. unsigned long avg_load; /* Avg load over the CPUs of the group */
  8436. unsigned long group_load; /* Total load over the CPUs of the group */
  8437. unsigned long group_capacity; /* Capacity over the CPUs of the group */
  8438. unsigned long group_util; /* Total utilization over the CPUs of the group */
  8439. unsigned long group_runnable; /* Total runnable time over the CPUs of the group */
  8440. unsigned int sum_nr_running; /* Nr of all tasks running in the group */
  8441. unsigned int sum_h_nr_running; /* Nr of CFS tasks running in the group */
  8442. unsigned int idle_cpus; /* Nr of idle CPUs in the group */
  8443. unsigned int group_weight;
  8444. enum group_type group_type;
  8445. unsigned int group_asym_packing; /* Tasks should be moved to preferred CPU */
  8446. unsigned int group_smt_balance; /* Task on busy SMT be moved */
  8447. unsigned long group_misfit_task_load; /* A CPU has a task too big for its capacity */
  8448. #ifdef CONFIG_NUMA_BALANCING
  8449. unsigned int nr_numa_running;
  8450. unsigned int nr_preferred_running;
  8451. #endif
  8452. };
  8453. /*
  8454. * sd_lb_stats - stats of a sched_domain required for load-balancing:
  8455. */
  8456. struct sd_lb_stats {
  8457. struct sched_group *busiest; /* Busiest group in this sd */
  8458. struct sched_group *local; /* Local group in this sd */
  8459. unsigned long total_load; /* Total load of all groups in sd */
  8460. unsigned long total_capacity; /* Total capacity of all groups in sd */
  8461. unsigned long avg_load; /* Average load across all groups in sd */
  8462. unsigned int prefer_sibling; /* Tasks should go to sibling first */
  8463. struct sg_lb_stats busiest_stat; /* Statistics of the busiest group */
  8464. struct sg_lb_stats local_stat; /* Statistics of the local group */
  8465. };
  8466. static inline void init_sd_lb_stats(struct sd_lb_stats *sds)
  8467. {
  8468. /*
  8469. * Skimp on the clearing to avoid duplicate work. We can avoid clearing
  8470. * local_stat because update_sg_lb_stats() does a full clear/assignment.
  8471. * We must however set busiest_stat::group_type and
  8472. * busiest_stat::idle_cpus to the worst busiest group because
  8473. * update_sd_pick_busiest() reads these before assignment.
  8474. */
  8475. *sds = (struct sd_lb_stats){
  8476. .busiest = NULL,
  8477. .local = NULL,
  8478. .total_load = 0UL,
  8479. .total_capacity = 0UL,
  8480. .busiest_stat = {
  8481. .idle_cpus = UINT_MAX,
  8482. .group_type = group_has_spare,
  8483. },
  8484. };
  8485. }
  8486. static unsigned long scale_rt_capacity(int cpu)
  8487. {
  8488. unsigned long max = get_actual_cpu_capacity(cpu);
  8489. struct rq *rq = cpu_rq(cpu);
  8490. unsigned long used, free;
  8491. unsigned long irq;
  8492. irq = cpu_util_irq(rq);
  8493. if (unlikely(irq >= max))
  8494. return 1;
  8495. /*
  8496. * avg_rt.util_avg and avg_dl.util_avg track binary signals
  8497. * (running and not running) with weights 0 and 1024 respectively.
  8498. */
  8499. used = cpu_util_rt(rq);
  8500. used += cpu_util_dl(rq);
  8501. if (unlikely(used >= max))
  8502. return 1;
  8503. free = max - used;
  8504. return scale_irq_capacity(free, irq, max);
  8505. }
  8506. static void update_cpu_capacity(struct sched_domain *sd, int cpu)
  8507. {
  8508. unsigned long capacity = scale_rt_capacity(cpu);
  8509. struct sched_group *sdg = sd->groups;
  8510. if (!capacity)
  8511. capacity = 1;
  8512. cpu_rq(cpu)->cpu_capacity = capacity;
  8513. trace_sched_cpu_capacity_tp(cpu_rq(cpu));
  8514. sdg->sgc->capacity = capacity;
  8515. sdg->sgc->min_capacity = capacity;
  8516. sdg->sgc->max_capacity = capacity;
  8517. }
  8518. void update_group_capacity(struct sched_domain *sd, int cpu)
  8519. {
  8520. struct sched_domain *child = sd->child;
  8521. struct sched_group *group, *sdg = sd->groups;
  8522. unsigned long capacity, min_capacity, max_capacity;
  8523. unsigned long interval;
  8524. interval = msecs_to_jiffies(sd->balance_interval);
  8525. interval = clamp(interval, 1UL, max_load_balance_interval);
  8526. sdg->sgc->next_update = jiffies + interval;
  8527. if (!child) {
  8528. update_cpu_capacity(sd, cpu);
  8529. return;
  8530. }
  8531. capacity = 0;
  8532. min_capacity = ULONG_MAX;
  8533. max_capacity = 0;
  8534. if (child->flags & SD_OVERLAP) {
  8535. /*
  8536. * SD_OVERLAP domains cannot assume that child groups
  8537. * span the current group.
  8538. */
  8539. for_each_cpu(cpu, sched_group_span(sdg)) {
  8540. unsigned long cpu_cap = capacity_of(cpu);
  8541. capacity += cpu_cap;
  8542. min_capacity = min(cpu_cap, min_capacity);
  8543. max_capacity = max(cpu_cap, max_capacity);
  8544. }
  8545. } else {
  8546. /*
  8547. * !SD_OVERLAP domains can assume that child groups
  8548. * span the current group.
  8549. */
  8550. group = child->groups;
  8551. do {
  8552. struct sched_group_capacity *sgc = group->sgc;
  8553. capacity += sgc->capacity;
  8554. min_capacity = min(sgc->min_capacity, min_capacity);
  8555. max_capacity = max(sgc->max_capacity, max_capacity);
  8556. group = group->next;
  8557. } while (group != child->groups);
  8558. }
  8559. sdg->sgc->capacity = capacity;
  8560. sdg->sgc->min_capacity = min_capacity;
  8561. sdg->sgc->max_capacity = max_capacity;
  8562. }
  8563. /*
  8564. * Check whether the capacity of the rq has been noticeably reduced by side
  8565. * activity. The imbalance_pct is used for the threshold.
  8566. * Return true is the capacity is reduced
  8567. */
  8568. static inline int
  8569. check_cpu_capacity(struct rq *rq, struct sched_domain *sd)
  8570. {
  8571. return ((rq->cpu_capacity * sd->imbalance_pct) <
  8572. (arch_scale_cpu_capacity(cpu_of(rq)) * 100));
  8573. }
  8574. /* Check if the rq has a misfit task */
  8575. static inline bool check_misfit_status(struct rq *rq)
  8576. {
  8577. return rq->misfit_task_load;
  8578. }
  8579. /*
  8580. * Group imbalance indicates (and tries to solve) the problem where balancing
  8581. * groups is inadequate due to ->cpus_ptr constraints.
  8582. *
  8583. * Imagine a situation of two groups of 4 CPUs each and 4 tasks each with a
  8584. * cpumask covering 1 CPU of the first group and 3 CPUs of the second group.
  8585. * Something like:
  8586. *
  8587. * { 0 1 2 3 } { 4 5 6 7 }
  8588. * * * * *
  8589. *
  8590. * If we were to balance group-wise we'd place two tasks in the first group and
  8591. * two tasks in the second group. Clearly this is undesired as it will overload
  8592. * cpu 3 and leave one of the CPUs in the second group unused.
  8593. *
  8594. * The current solution to this issue is detecting the skew in the first group
  8595. * by noticing the lower domain failed to reach balance and had difficulty
  8596. * moving tasks due to affinity constraints.
  8597. *
  8598. * When this is so detected; this group becomes a candidate for busiest; see
  8599. * update_sd_pick_busiest(). And calculate_imbalance() and
  8600. * sched_balance_find_src_group() avoid some of the usual balance conditions to allow it
  8601. * to create an effective group imbalance.
  8602. *
  8603. * This is a somewhat tricky proposition since the next run might not find the
  8604. * group imbalance and decide the groups need to be balanced again. A most
  8605. * subtle and fragile situation.
  8606. */
  8607. static inline int sg_imbalanced(struct sched_group *group)
  8608. {
  8609. return group->sgc->imbalance;
  8610. }
  8611. /*
  8612. * group_has_capacity returns true if the group has spare capacity that could
  8613. * be used by some tasks.
  8614. * We consider that a group has spare capacity if the number of task is
  8615. * smaller than the number of CPUs or if the utilization is lower than the
  8616. * available capacity for CFS tasks.
  8617. * For the latter, we use a threshold to stabilize the state, to take into
  8618. * account the variance of the tasks' load and to return true if the available
  8619. * capacity in meaningful for the load balancer.
  8620. * As an example, an available capacity of 1% can appear but it doesn't make
  8621. * any benefit for the load balance.
  8622. */
  8623. static inline bool
  8624. group_has_capacity(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
  8625. {
  8626. if (sgs->sum_nr_running < sgs->group_weight)
  8627. return true;
  8628. if ((sgs->group_capacity * imbalance_pct) <
  8629. (sgs->group_runnable * 100))
  8630. return false;
  8631. if ((sgs->group_capacity * 100) >
  8632. (sgs->group_util * imbalance_pct))
  8633. return true;
  8634. return false;
  8635. }
  8636. /*
  8637. * group_is_overloaded returns true if the group has more tasks than it can
  8638. * handle.
  8639. * group_is_overloaded is not equals to !group_has_capacity because a group
  8640. * with the exact right number of tasks, has no more spare capacity but is not
  8641. * overloaded so both group_has_capacity and group_is_overloaded return
  8642. * false.
  8643. */
  8644. static inline bool
  8645. group_is_overloaded(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
  8646. {
  8647. if (sgs->sum_nr_running <= sgs->group_weight)
  8648. return false;
  8649. if ((sgs->group_capacity * 100) <
  8650. (sgs->group_util * imbalance_pct))
  8651. return true;
  8652. if ((sgs->group_capacity * imbalance_pct) <
  8653. (sgs->group_runnable * 100))
  8654. return true;
  8655. return false;
  8656. }
  8657. static inline enum
  8658. group_type group_classify(unsigned int imbalance_pct,
  8659. struct sched_group *group,
  8660. struct sg_lb_stats *sgs)
  8661. {
  8662. if (group_is_overloaded(imbalance_pct, sgs))
  8663. return group_overloaded;
  8664. if (sg_imbalanced(group))
  8665. return group_imbalanced;
  8666. if (sgs->group_asym_packing)
  8667. return group_asym_packing;
  8668. if (sgs->group_smt_balance)
  8669. return group_smt_balance;
  8670. if (sgs->group_misfit_task_load)
  8671. return group_misfit_task;
  8672. if (!group_has_capacity(imbalance_pct, sgs))
  8673. return group_fully_busy;
  8674. return group_has_spare;
  8675. }
  8676. /**
  8677. * sched_use_asym_prio - Check whether asym_packing priority must be used
  8678. * @sd: The scheduling domain of the load balancing
  8679. * @cpu: A CPU
  8680. *
  8681. * Always use CPU priority when balancing load between SMT siblings. When
  8682. * balancing load between cores, it is not sufficient that @cpu is idle. Only
  8683. * use CPU priority if the whole core is idle.
  8684. *
  8685. * Returns: True if the priority of @cpu must be followed. False otherwise.
  8686. */
  8687. static bool sched_use_asym_prio(struct sched_domain *sd, int cpu)
  8688. {
  8689. if (!(sd->flags & SD_ASYM_PACKING))
  8690. return false;
  8691. if (!sched_smt_active())
  8692. return true;
  8693. return sd->flags & SD_SHARE_CPUCAPACITY || is_core_idle(cpu);
  8694. }
  8695. static inline bool sched_asym(struct sched_domain *sd, int dst_cpu, int src_cpu)
  8696. {
  8697. /*
  8698. * First check if @dst_cpu can do asym_packing load balance. Only do it
  8699. * if it has higher priority than @src_cpu.
  8700. */
  8701. return sched_use_asym_prio(sd, dst_cpu) &&
  8702. sched_asym_prefer(dst_cpu, src_cpu);
  8703. }
  8704. /**
  8705. * sched_group_asym - Check if the destination CPU can do asym_packing balance
  8706. * @env: The load balancing environment
  8707. * @sgs: Load-balancing statistics of the candidate busiest group
  8708. * @group: The candidate busiest group
  8709. *
  8710. * @env::dst_cpu can do asym_packing if it has higher priority than the
  8711. * preferred CPU of @group.
  8712. *
  8713. * Return: true if @env::dst_cpu can do with asym_packing load balance. False
  8714. * otherwise.
  8715. */
  8716. static inline bool
  8717. sched_group_asym(struct lb_env *env, struct sg_lb_stats *sgs, struct sched_group *group)
  8718. {
  8719. /*
  8720. * CPU priorities do not make sense for SMT cores with more than one
  8721. * busy sibling.
  8722. */
  8723. if ((group->flags & SD_SHARE_CPUCAPACITY) &&
  8724. (sgs->group_weight - sgs->idle_cpus != 1))
  8725. return false;
  8726. return sched_asym(env->sd, env->dst_cpu, group->asym_prefer_cpu);
  8727. }
  8728. /* One group has more than one SMT CPU while the other group does not */
  8729. static inline bool smt_vs_nonsmt_groups(struct sched_group *sg1,
  8730. struct sched_group *sg2)
  8731. {
  8732. if (!sg1 || !sg2)
  8733. return false;
  8734. return (sg1->flags & SD_SHARE_CPUCAPACITY) !=
  8735. (sg2->flags & SD_SHARE_CPUCAPACITY);
  8736. }
  8737. static inline bool smt_balance(struct lb_env *env, struct sg_lb_stats *sgs,
  8738. struct sched_group *group)
  8739. {
  8740. if (!env->idle)
  8741. return false;
  8742. /*
  8743. * For SMT source group, it is better to move a task
  8744. * to a CPU that doesn't have multiple tasks sharing its CPU capacity.
  8745. * Note that if a group has a single SMT, SD_SHARE_CPUCAPACITY
  8746. * will not be on.
  8747. */
  8748. if (group->flags & SD_SHARE_CPUCAPACITY &&
  8749. sgs->sum_h_nr_running > 1)
  8750. return true;
  8751. return false;
  8752. }
  8753. static inline long sibling_imbalance(struct lb_env *env,
  8754. struct sd_lb_stats *sds,
  8755. struct sg_lb_stats *busiest,
  8756. struct sg_lb_stats *local)
  8757. {
  8758. int ncores_busiest, ncores_local;
  8759. long imbalance;
  8760. if (!env->idle || !busiest->sum_nr_running)
  8761. return 0;
  8762. ncores_busiest = sds->busiest->cores;
  8763. ncores_local = sds->local->cores;
  8764. if (ncores_busiest == ncores_local) {
  8765. imbalance = busiest->sum_nr_running;
  8766. lsub_positive(&imbalance, local->sum_nr_running);
  8767. return imbalance;
  8768. }
  8769. /* Balance such that nr_running/ncores ratio are same on both groups */
  8770. imbalance = ncores_local * busiest->sum_nr_running;
  8771. lsub_positive(&imbalance, ncores_busiest * local->sum_nr_running);
  8772. /* Normalize imbalance and do rounding on normalization */
  8773. imbalance = 2 * imbalance + ncores_local + ncores_busiest;
  8774. imbalance /= ncores_local + ncores_busiest;
  8775. /* Take advantage of resource in an empty sched group */
  8776. if (imbalance <= 1 && local->sum_nr_running == 0 &&
  8777. busiest->sum_nr_running > 1)
  8778. imbalance = 2;
  8779. return imbalance;
  8780. }
  8781. static inline bool
  8782. sched_reduced_capacity(struct rq *rq, struct sched_domain *sd)
  8783. {
  8784. /*
  8785. * When there is more than 1 task, the group_overloaded case already
  8786. * takes care of cpu with reduced capacity
  8787. */
  8788. if (rq->cfs.h_nr_queued != 1)
  8789. return false;
  8790. return check_cpu_capacity(rq, sd);
  8791. }
  8792. /**
  8793. * update_sg_lb_stats - Update sched_group's statistics for load balancing.
  8794. * @env: The load balancing environment.
  8795. * @sds: Load-balancing data with statistics of the local group.
  8796. * @group: sched_group whose statistics are to be updated.
  8797. * @sgs: variable to hold the statistics for this group.
  8798. * @sg_overloaded: sched_group is overloaded
  8799. * @sg_overutilized: sched_group is overutilized
  8800. */
  8801. static inline void update_sg_lb_stats(struct lb_env *env,
  8802. struct sd_lb_stats *sds,
  8803. struct sched_group *group,
  8804. struct sg_lb_stats *sgs,
  8805. bool *sg_overloaded,
  8806. bool *sg_overutilized)
  8807. {
  8808. int i, nr_running, local_group;
  8809. memset(sgs, 0, sizeof(*sgs));
  8810. local_group = group == sds->local;
  8811. for_each_cpu_and(i, sched_group_span(group), env->cpus) {
  8812. struct rq *rq = cpu_rq(i);
  8813. unsigned long load = cpu_load(rq);
  8814. sgs->group_load += load;
  8815. sgs->group_util += cpu_util_cfs(i);
  8816. sgs->group_runnable += cpu_runnable(rq);
  8817. sgs->sum_h_nr_running += rq->cfs.h_nr_queued;
  8818. nr_running = rq->nr_running;
  8819. sgs->sum_nr_running += nr_running;
  8820. if (nr_running > 1)
  8821. *sg_overloaded = 1;
  8822. if (cpu_overutilized(i))
  8823. *sg_overutilized = 1;
  8824. #ifdef CONFIG_NUMA_BALANCING
  8825. sgs->nr_numa_running += rq->nr_numa_running;
  8826. sgs->nr_preferred_running += rq->nr_preferred_running;
  8827. #endif
  8828. /*
  8829. * No need to call idle_cpu() if nr_running is not 0
  8830. */
  8831. if (!nr_running && idle_cpu(i)) {
  8832. sgs->idle_cpus++;
  8833. /* Idle cpu can't have misfit task */
  8834. continue;
  8835. }
  8836. if (local_group)
  8837. continue;
  8838. if (env->sd->flags & SD_ASYM_CPUCAPACITY) {
  8839. /* Check for a misfit task on the cpu */
  8840. if (sgs->group_misfit_task_load < rq->misfit_task_load) {
  8841. sgs->group_misfit_task_load = rq->misfit_task_load;
  8842. *sg_overloaded = 1;
  8843. }
  8844. } else if (env->idle && sched_reduced_capacity(rq, env->sd)) {
  8845. /* Check for a task running on a CPU with reduced capacity */
  8846. if (sgs->group_misfit_task_load < load)
  8847. sgs->group_misfit_task_load = load;
  8848. }
  8849. }
  8850. sgs->group_capacity = group->sgc->capacity;
  8851. sgs->group_weight = group->group_weight;
  8852. /* Check if dst CPU is idle and preferred to this group */
  8853. if (!local_group && env->idle && sgs->sum_h_nr_running &&
  8854. sched_group_asym(env, sgs, group))
  8855. sgs->group_asym_packing = 1;
  8856. /* Check for loaded SMT group to be balanced to dst CPU */
  8857. if (!local_group && smt_balance(env, sgs, group))
  8858. sgs->group_smt_balance = 1;
  8859. sgs->group_type = group_classify(env->sd->imbalance_pct, group, sgs);
  8860. /* Computing avg_load makes sense only when group is overloaded */
  8861. if (sgs->group_type == group_overloaded)
  8862. sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
  8863. sgs->group_capacity;
  8864. }
  8865. /**
  8866. * update_sd_pick_busiest - return 1 on busiest group
  8867. * @env: The load balancing environment.
  8868. * @sds: sched_domain statistics
  8869. * @sg: sched_group candidate to be checked for being the busiest
  8870. * @sgs: sched_group statistics
  8871. *
  8872. * Determine if @sg is a busier group than the previously selected
  8873. * busiest group.
  8874. *
  8875. * Return: %true if @sg is a busier group than the previously selected
  8876. * busiest group. %false otherwise.
  8877. */
  8878. static bool update_sd_pick_busiest(struct lb_env *env,
  8879. struct sd_lb_stats *sds,
  8880. struct sched_group *sg,
  8881. struct sg_lb_stats *sgs)
  8882. {
  8883. struct sg_lb_stats *busiest = &sds->busiest_stat;
  8884. /* Make sure that there is at least one task to pull */
  8885. if (!sgs->sum_h_nr_running)
  8886. return false;
  8887. /*
  8888. * Don't try to pull misfit tasks we can't help.
  8889. * We can use max_capacity here as reduction in capacity on some
  8890. * CPUs in the group should either be possible to resolve
  8891. * internally or be covered by avg_load imbalance (eventually).
  8892. */
  8893. if ((env->sd->flags & SD_ASYM_CPUCAPACITY) &&
  8894. (sgs->group_type == group_misfit_task) &&
  8895. (!capacity_greater(capacity_of(env->dst_cpu), sg->sgc->max_capacity) ||
  8896. sds->local_stat.group_type != group_has_spare))
  8897. return false;
  8898. if (sgs->group_type > busiest->group_type)
  8899. return true;
  8900. if (sgs->group_type < busiest->group_type)
  8901. return false;
  8902. /*
  8903. * The candidate and the current busiest group are the same type of
  8904. * group. Let check which one is the busiest according to the type.
  8905. */
  8906. switch (sgs->group_type) {
  8907. case group_overloaded:
  8908. /* Select the overloaded group with highest avg_load. */
  8909. return sgs->avg_load > busiest->avg_load;
  8910. case group_imbalanced:
  8911. /*
  8912. * Select the 1st imbalanced group as we don't have any way to
  8913. * choose one more than another.
  8914. */
  8915. return false;
  8916. case group_asym_packing:
  8917. /* Prefer to move from lowest priority CPU's work */
  8918. return sched_asym_prefer(sds->busiest->asym_prefer_cpu, sg->asym_prefer_cpu);
  8919. case group_misfit_task:
  8920. /*
  8921. * If we have more than one misfit sg go with the biggest
  8922. * misfit.
  8923. */
  8924. return sgs->group_misfit_task_load > busiest->group_misfit_task_load;
  8925. case group_smt_balance:
  8926. /*
  8927. * Check if we have spare CPUs on either SMT group to
  8928. * choose has spare or fully busy handling.
  8929. */
  8930. if (sgs->idle_cpus != 0 || busiest->idle_cpus != 0)
  8931. goto has_spare;
  8932. fallthrough;
  8933. case group_fully_busy:
  8934. /*
  8935. * Select the fully busy group with highest avg_load. In
  8936. * theory, there is no need to pull task from such kind of
  8937. * group because tasks have all compute capacity that they need
  8938. * but we can still improve the overall throughput by reducing
  8939. * contention when accessing shared HW resources.
  8940. *
  8941. * XXX for now avg_load is not computed and always 0 so we
  8942. * select the 1st one, except if @sg is composed of SMT
  8943. * siblings.
  8944. */
  8945. if (sgs->avg_load < busiest->avg_load)
  8946. return false;
  8947. if (sgs->avg_load == busiest->avg_load) {
  8948. /*
  8949. * SMT sched groups need more help than non-SMT groups.
  8950. * If @sg happens to also be SMT, either choice is good.
  8951. */
  8952. if (sds->busiest->flags & SD_SHARE_CPUCAPACITY)
  8953. return false;
  8954. }
  8955. break;
  8956. case group_has_spare:
  8957. /*
  8958. * Do not pick sg with SMT CPUs over sg with pure CPUs,
  8959. * as we do not want to pull task off SMT core with one task
  8960. * and make the core idle.
  8961. */
  8962. if (smt_vs_nonsmt_groups(sds->busiest, sg)) {
  8963. if (sg->flags & SD_SHARE_CPUCAPACITY && sgs->sum_h_nr_running <= 1)
  8964. return false;
  8965. else
  8966. return true;
  8967. }
  8968. has_spare:
  8969. /*
  8970. * Select not overloaded group with lowest number of idle CPUs
  8971. * and highest number of running tasks. We could also compare
  8972. * the spare capacity which is more stable but it can end up
  8973. * that the group has less spare capacity but finally more idle
  8974. * CPUs which means less opportunity to pull tasks.
  8975. */
  8976. if (sgs->idle_cpus > busiest->idle_cpus)
  8977. return false;
  8978. else if ((sgs->idle_cpus == busiest->idle_cpus) &&
  8979. (sgs->sum_nr_running <= busiest->sum_nr_running))
  8980. return false;
  8981. break;
  8982. }
  8983. /*
  8984. * Candidate sg has no more than one task per CPU and has higher
  8985. * per-CPU capacity. Migrating tasks to less capable CPUs may harm
  8986. * throughput. Maximize throughput, power/energy consequences are not
  8987. * considered.
  8988. */
  8989. if ((env->sd->flags & SD_ASYM_CPUCAPACITY) &&
  8990. (sgs->group_type <= group_fully_busy) &&
  8991. (capacity_greater(sg->sgc->min_capacity, capacity_of(env->dst_cpu))))
  8992. return false;
  8993. return true;
  8994. }
  8995. #ifdef CONFIG_NUMA_BALANCING
  8996. static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
  8997. {
  8998. if (sgs->sum_h_nr_running > sgs->nr_numa_running)
  8999. return regular;
  9000. if (sgs->sum_h_nr_running > sgs->nr_preferred_running)
  9001. return remote;
  9002. return all;
  9003. }
  9004. static inline enum fbq_type fbq_classify_rq(struct rq *rq)
  9005. {
  9006. if (rq->nr_running > rq->nr_numa_running)
  9007. return regular;
  9008. if (rq->nr_running > rq->nr_preferred_running)
  9009. return remote;
  9010. return all;
  9011. }
  9012. #else
  9013. static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
  9014. {
  9015. return all;
  9016. }
  9017. static inline enum fbq_type fbq_classify_rq(struct rq *rq)
  9018. {
  9019. return regular;
  9020. }
  9021. #endif /* CONFIG_NUMA_BALANCING */
  9022. struct sg_lb_stats;
  9023. /*
  9024. * task_running_on_cpu - return 1 if @p is running on @cpu.
  9025. */
  9026. static unsigned int task_running_on_cpu(int cpu, struct task_struct *p)
  9027. {
  9028. /* Task has no contribution or is new */
  9029. if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
  9030. return 0;
  9031. if (task_on_rq_queued(p))
  9032. return 1;
  9033. return 0;
  9034. }
  9035. /**
  9036. * idle_cpu_without - would a given CPU be idle without p ?
  9037. * @cpu: the processor on which idleness is tested.
  9038. * @p: task which should be ignored.
  9039. *
  9040. * Return: 1 if the CPU would be idle. 0 otherwise.
  9041. */
  9042. static int idle_cpu_without(int cpu, struct task_struct *p)
  9043. {
  9044. struct rq *rq = cpu_rq(cpu);
  9045. if (rq->curr != rq->idle && rq->curr != p)
  9046. return 0;
  9047. /*
  9048. * rq->nr_running can't be used but an updated version without the
  9049. * impact of p on cpu must be used instead. The updated nr_running
  9050. * be computed and tested before calling idle_cpu_without().
  9051. */
  9052. if (rq->ttwu_pending)
  9053. return 0;
  9054. return 1;
  9055. }
  9056. /*
  9057. * update_sg_wakeup_stats - Update sched_group's statistics for wakeup.
  9058. * @sd: The sched_domain level to look for idlest group.
  9059. * @group: sched_group whose statistics are to be updated.
  9060. * @sgs: variable to hold the statistics for this group.
  9061. * @p: The task for which we look for the idlest group/CPU.
  9062. */
  9063. static inline void update_sg_wakeup_stats(struct sched_domain *sd,
  9064. struct sched_group *group,
  9065. struct sg_lb_stats *sgs,
  9066. struct task_struct *p)
  9067. {
  9068. int i, nr_running;
  9069. memset(sgs, 0, sizeof(*sgs));
  9070. /* Assume that task can't fit any CPU of the group */
  9071. if (sd->flags & SD_ASYM_CPUCAPACITY)
  9072. sgs->group_misfit_task_load = 1;
  9073. for_each_cpu(i, sched_group_span(group)) {
  9074. struct rq *rq = cpu_rq(i);
  9075. unsigned int local;
  9076. sgs->group_load += cpu_load_without(rq, p);
  9077. sgs->group_util += cpu_util_without(i, p);
  9078. sgs->group_runnable += cpu_runnable_without(rq, p);
  9079. local = task_running_on_cpu(i, p);
  9080. sgs->sum_h_nr_running += rq->cfs.h_nr_queued - local;
  9081. nr_running = rq->nr_running - local;
  9082. sgs->sum_nr_running += nr_running;
  9083. /*
  9084. * No need to call idle_cpu_without() if nr_running is not 0
  9085. */
  9086. if (!nr_running && idle_cpu_without(i, p))
  9087. sgs->idle_cpus++;
  9088. /* Check if task fits in the CPU */
  9089. if (sd->flags & SD_ASYM_CPUCAPACITY &&
  9090. sgs->group_misfit_task_load &&
  9091. task_fits_cpu(p, i))
  9092. sgs->group_misfit_task_load = 0;
  9093. }
  9094. sgs->group_capacity = group->sgc->capacity;
  9095. sgs->group_weight = group->group_weight;
  9096. sgs->group_type = group_classify(sd->imbalance_pct, group, sgs);
  9097. /*
  9098. * Computing avg_load makes sense only when group is fully busy or
  9099. * overloaded
  9100. */
  9101. if (sgs->group_type == group_fully_busy ||
  9102. sgs->group_type == group_overloaded)
  9103. sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
  9104. sgs->group_capacity;
  9105. }
  9106. static bool update_pick_idlest(struct sched_group *idlest,
  9107. struct sg_lb_stats *idlest_sgs,
  9108. struct sched_group *group,
  9109. struct sg_lb_stats *sgs)
  9110. {
  9111. if (sgs->group_type < idlest_sgs->group_type)
  9112. return true;
  9113. if (sgs->group_type > idlest_sgs->group_type)
  9114. return false;
  9115. /*
  9116. * The candidate and the current idlest group are the same type of
  9117. * group. Let check which one is the idlest according to the type.
  9118. */
  9119. switch (sgs->group_type) {
  9120. case group_overloaded:
  9121. case group_fully_busy:
  9122. /* Select the group with lowest avg_load. */
  9123. if (idlest_sgs->avg_load <= sgs->avg_load)
  9124. return false;
  9125. break;
  9126. case group_imbalanced:
  9127. case group_asym_packing:
  9128. case group_smt_balance:
  9129. /* Those types are not used in the slow wakeup path */
  9130. return false;
  9131. case group_misfit_task:
  9132. /* Select group with the highest max capacity */
  9133. if (idlest->sgc->max_capacity >= group->sgc->max_capacity)
  9134. return false;
  9135. break;
  9136. case group_has_spare:
  9137. /* Select group with most idle CPUs */
  9138. if (idlest_sgs->idle_cpus > sgs->idle_cpus)
  9139. return false;
  9140. /* Select group with lowest group_util */
  9141. if (idlest_sgs->idle_cpus == sgs->idle_cpus &&
  9142. idlest_sgs->group_util <= sgs->group_util)
  9143. return false;
  9144. break;
  9145. }
  9146. return true;
  9147. }
  9148. /*
  9149. * sched_balance_find_dst_group() finds and returns the least busy CPU group within the
  9150. * domain.
  9151. *
  9152. * Assumes p is allowed on at least one CPU in sd.
  9153. */
  9154. static struct sched_group *
  9155. sched_balance_find_dst_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
  9156. {
  9157. struct sched_group *idlest = NULL, *local = NULL, *group = sd->groups;
  9158. struct sg_lb_stats local_sgs, tmp_sgs;
  9159. struct sg_lb_stats *sgs;
  9160. unsigned long imbalance;
  9161. struct sg_lb_stats idlest_sgs = {
  9162. .avg_load = UINT_MAX,
  9163. .group_type = group_overloaded,
  9164. };
  9165. do {
  9166. int local_group;
  9167. /* Skip over this group if it has no CPUs allowed */
  9168. if (!cpumask_intersects(sched_group_span(group),
  9169. p->cpus_ptr))
  9170. continue;
  9171. /* Skip over this group if no cookie matched */
  9172. if (!sched_group_cookie_match(cpu_rq(this_cpu), p, group))
  9173. continue;
  9174. local_group = cpumask_test_cpu(this_cpu,
  9175. sched_group_span(group));
  9176. if (local_group) {
  9177. sgs = &local_sgs;
  9178. local = group;
  9179. } else {
  9180. sgs = &tmp_sgs;
  9181. }
  9182. update_sg_wakeup_stats(sd, group, sgs, p);
  9183. if (!local_group && update_pick_idlest(idlest, &idlest_sgs, group, sgs)) {
  9184. idlest = group;
  9185. idlest_sgs = *sgs;
  9186. }
  9187. } while (group = group->next, group != sd->groups);
  9188. /* There is no idlest group to push tasks to */
  9189. if (!idlest)
  9190. return NULL;
  9191. /* The local group has been skipped because of CPU affinity */
  9192. if (!local)
  9193. return idlest;
  9194. /*
  9195. * If the local group is idler than the selected idlest group
  9196. * don't try and push the task.
  9197. */
  9198. if (local_sgs.group_type < idlest_sgs.group_type)
  9199. return NULL;
  9200. /*
  9201. * If the local group is busier than the selected idlest group
  9202. * try and push the task.
  9203. */
  9204. if (local_sgs.group_type > idlest_sgs.group_type)
  9205. return idlest;
  9206. switch (local_sgs.group_type) {
  9207. case group_overloaded:
  9208. case group_fully_busy:
  9209. /* Calculate allowed imbalance based on load */
  9210. imbalance = scale_load_down(NICE_0_LOAD) *
  9211. (sd->imbalance_pct-100) / 100;
  9212. /*
  9213. * When comparing groups across NUMA domains, it's possible for
  9214. * the local domain to be very lightly loaded relative to the
  9215. * remote domains but "imbalance" skews the comparison making
  9216. * remote CPUs look much more favourable. When considering
  9217. * cross-domain, add imbalance to the load on the remote node
  9218. * and consider staying local.
  9219. */
  9220. if ((sd->flags & SD_NUMA) &&
  9221. ((idlest_sgs.avg_load + imbalance) >= local_sgs.avg_load))
  9222. return NULL;
  9223. /*
  9224. * If the local group is less loaded than the selected
  9225. * idlest group don't try and push any tasks.
  9226. */
  9227. if (idlest_sgs.avg_load >= (local_sgs.avg_load + imbalance))
  9228. return NULL;
  9229. if (100 * local_sgs.avg_load <= sd->imbalance_pct * idlest_sgs.avg_load)
  9230. return NULL;
  9231. break;
  9232. case group_imbalanced:
  9233. case group_asym_packing:
  9234. case group_smt_balance:
  9235. /* Those type are not used in the slow wakeup path */
  9236. return NULL;
  9237. case group_misfit_task:
  9238. /* Select group with the highest max capacity */
  9239. if (local->sgc->max_capacity >= idlest->sgc->max_capacity)
  9240. return NULL;
  9241. break;
  9242. case group_has_spare:
  9243. #ifdef CONFIG_NUMA
  9244. if (sd->flags & SD_NUMA) {
  9245. int imb_numa_nr = sd->imb_numa_nr;
  9246. #ifdef CONFIG_NUMA_BALANCING
  9247. int idlest_cpu;
  9248. /*
  9249. * If there is spare capacity at NUMA, try to select
  9250. * the preferred node
  9251. */
  9252. if (cpu_to_node(this_cpu) == p->numa_preferred_nid)
  9253. return NULL;
  9254. idlest_cpu = cpumask_first(sched_group_span(idlest));
  9255. if (cpu_to_node(idlest_cpu) == p->numa_preferred_nid)
  9256. return idlest;
  9257. #endif /* CONFIG_NUMA_BALANCING */
  9258. /*
  9259. * Otherwise, keep the task close to the wakeup source
  9260. * and improve locality if the number of running tasks
  9261. * would remain below threshold where an imbalance is
  9262. * allowed while accounting for the possibility the
  9263. * task is pinned to a subset of CPUs. If there is a
  9264. * real need of migration, periodic load balance will
  9265. * take care of it.
  9266. */
  9267. if (p->nr_cpus_allowed != NR_CPUS) {
  9268. struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
  9269. cpumask_and(cpus, sched_group_span(local), p->cpus_ptr);
  9270. imb_numa_nr = min(cpumask_weight(cpus), sd->imb_numa_nr);
  9271. }
  9272. imbalance = abs(local_sgs.idle_cpus - idlest_sgs.idle_cpus);
  9273. if (!adjust_numa_imbalance(imbalance,
  9274. local_sgs.sum_nr_running + 1,
  9275. imb_numa_nr)) {
  9276. return NULL;
  9277. }
  9278. }
  9279. #endif /* CONFIG_NUMA */
  9280. /*
  9281. * Select group with highest number of idle CPUs. We could also
  9282. * compare the utilization which is more stable but it can end
  9283. * up that the group has less spare capacity but finally more
  9284. * idle CPUs which means more opportunity to run task.
  9285. */
  9286. if (local_sgs.idle_cpus >= idlest_sgs.idle_cpus)
  9287. return NULL;
  9288. break;
  9289. }
  9290. return idlest;
  9291. }
  9292. static void update_idle_cpu_scan(struct lb_env *env,
  9293. unsigned long sum_util)
  9294. {
  9295. struct sched_domain_shared *sd_share;
  9296. int llc_weight, pct;
  9297. u64 x, y, tmp;
  9298. /*
  9299. * Update the number of CPUs to scan in LLC domain, which could
  9300. * be used as a hint in select_idle_cpu(). The update of sd_share
  9301. * could be expensive because it is within a shared cache line.
  9302. * So the write of this hint only occurs during periodic load
  9303. * balancing, rather than CPU_NEWLY_IDLE, because the latter
  9304. * can fire way more frequently than the former.
  9305. */
  9306. if (!sched_feat(SIS_UTIL) || env->idle == CPU_NEWLY_IDLE)
  9307. return;
  9308. llc_weight = per_cpu(sd_llc_size, env->dst_cpu);
  9309. if (env->sd->span_weight != llc_weight)
  9310. return;
  9311. sd_share = rcu_dereference(per_cpu(sd_llc_shared, env->dst_cpu));
  9312. if (!sd_share)
  9313. return;
  9314. /*
  9315. * The number of CPUs to search drops as sum_util increases, when
  9316. * sum_util hits 85% or above, the scan stops.
  9317. * The reason to choose 85% as the threshold is because this is the
  9318. * imbalance_pct(117) when a LLC sched group is overloaded.
  9319. *
  9320. * let y = SCHED_CAPACITY_SCALE - p * x^2 [1]
  9321. * and y'= y / SCHED_CAPACITY_SCALE
  9322. *
  9323. * x is the ratio of sum_util compared to the CPU capacity:
  9324. * x = sum_util / (llc_weight * SCHED_CAPACITY_SCALE)
  9325. * y' is the ratio of CPUs to be scanned in the LLC domain,
  9326. * and the number of CPUs to scan is calculated by:
  9327. *
  9328. * nr_scan = llc_weight * y' [2]
  9329. *
  9330. * When x hits the threshold of overloaded, AKA, when
  9331. * x = 100 / pct, y drops to 0. According to [1],
  9332. * p should be SCHED_CAPACITY_SCALE * pct^2 / 10000
  9333. *
  9334. * Scale x by SCHED_CAPACITY_SCALE:
  9335. * x' = sum_util / llc_weight; [3]
  9336. *
  9337. * and finally [1] becomes:
  9338. * y = SCHED_CAPACITY_SCALE -
  9339. * x'^2 * pct^2 / (10000 * SCHED_CAPACITY_SCALE) [4]
  9340. *
  9341. */
  9342. /* equation [3] */
  9343. x = sum_util;
  9344. do_div(x, llc_weight);
  9345. /* equation [4] */
  9346. pct = env->sd->imbalance_pct;
  9347. tmp = x * x * pct * pct;
  9348. do_div(tmp, 10000 * SCHED_CAPACITY_SCALE);
  9349. tmp = min_t(long, tmp, SCHED_CAPACITY_SCALE);
  9350. y = SCHED_CAPACITY_SCALE - tmp;
  9351. /* equation [2] */
  9352. y *= llc_weight;
  9353. do_div(y, SCHED_CAPACITY_SCALE);
  9354. if ((int)y != sd_share->nr_idle_scan)
  9355. WRITE_ONCE(sd_share->nr_idle_scan, (int)y);
  9356. }
  9357. /**
  9358. * update_sd_lb_stats - Update sched_domain's statistics for load balancing.
  9359. * @env: The load balancing environment.
  9360. * @sds: variable to hold the statistics for this sched_domain.
  9361. */
  9362. static inline void update_sd_lb_stats(struct lb_env *env, struct sd_lb_stats *sds)
  9363. {
  9364. struct sched_group *sg = env->sd->groups;
  9365. struct sg_lb_stats *local = &sds->local_stat;
  9366. struct sg_lb_stats tmp_sgs;
  9367. unsigned long sum_util = 0;
  9368. bool sg_overloaded = 0, sg_overutilized = 0;
  9369. do {
  9370. struct sg_lb_stats *sgs = &tmp_sgs;
  9371. int local_group;
  9372. local_group = cpumask_test_cpu(env->dst_cpu, sched_group_span(sg));
  9373. if (local_group) {
  9374. sds->local = sg;
  9375. sgs = local;
  9376. if (env->idle != CPU_NEWLY_IDLE ||
  9377. time_after_eq(jiffies, sg->sgc->next_update))
  9378. update_group_capacity(env->sd, env->dst_cpu);
  9379. }
  9380. update_sg_lb_stats(env, sds, sg, sgs, &sg_overloaded, &sg_overutilized);
  9381. if (!local_group && update_sd_pick_busiest(env, sds, sg, sgs)) {
  9382. sds->busiest = sg;
  9383. sds->busiest_stat = *sgs;
  9384. }
  9385. /* Now, start updating sd_lb_stats */
  9386. sds->total_load += sgs->group_load;
  9387. sds->total_capacity += sgs->group_capacity;
  9388. sum_util += sgs->group_util;
  9389. sg = sg->next;
  9390. } while (sg != env->sd->groups);
  9391. /*
  9392. * Indicate that the child domain of the busiest group prefers tasks
  9393. * go to a child's sibling domains first. NB the flags of a sched group
  9394. * are those of the child domain.
  9395. */
  9396. if (sds->busiest)
  9397. sds->prefer_sibling = !!(sds->busiest->flags & SD_PREFER_SIBLING);
  9398. if (env->sd->flags & SD_NUMA)
  9399. env->fbq_type = fbq_classify_group(&sds->busiest_stat);
  9400. if (!env->sd->parent) {
  9401. /* update overload indicator if we are at root domain */
  9402. set_rd_overloaded(env->dst_rq->rd, sg_overloaded);
  9403. /* Update over-utilization (tipping point, U >= 0) indicator */
  9404. set_rd_overutilized(env->dst_rq->rd, sg_overutilized);
  9405. } else if (sg_overutilized) {
  9406. set_rd_overutilized(env->dst_rq->rd, sg_overutilized);
  9407. }
  9408. update_idle_cpu_scan(env, sum_util);
  9409. }
  9410. /**
  9411. * calculate_imbalance - Calculate the amount of imbalance present within the
  9412. * groups of a given sched_domain during load balance.
  9413. * @env: load balance environment
  9414. * @sds: statistics of the sched_domain whose imbalance is to be calculated.
  9415. */
  9416. static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
  9417. {
  9418. struct sg_lb_stats *local, *busiest;
  9419. local = &sds->local_stat;
  9420. busiest = &sds->busiest_stat;
  9421. if (busiest->group_type == group_misfit_task) {
  9422. if (env->sd->flags & SD_ASYM_CPUCAPACITY) {
  9423. /* Set imbalance to allow misfit tasks to be balanced. */
  9424. env->migration_type = migrate_misfit;
  9425. env->imbalance = 1;
  9426. } else {
  9427. /*
  9428. * Set load imbalance to allow moving task from cpu
  9429. * with reduced capacity.
  9430. */
  9431. env->migration_type = migrate_load;
  9432. env->imbalance = busiest->group_misfit_task_load;
  9433. }
  9434. return;
  9435. }
  9436. if (busiest->group_type == group_asym_packing) {
  9437. /*
  9438. * In case of asym capacity, we will try to migrate all load to
  9439. * the preferred CPU.
  9440. */
  9441. env->migration_type = migrate_task;
  9442. env->imbalance = busiest->sum_h_nr_running;
  9443. return;
  9444. }
  9445. if (busiest->group_type == group_smt_balance) {
  9446. /* Reduce number of tasks sharing CPU capacity */
  9447. env->migration_type = migrate_task;
  9448. env->imbalance = 1;
  9449. return;
  9450. }
  9451. if (busiest->group_type == group_imbalanced) {
  9452. /*
  9453. * In the group_imb case we cannot rely on group-wide averages
  9454. * to ensure CPU-load equilibrium, try to move any task to fix
  9455. * the imbalance. The next load balance will take care of
  9456. * balancing back the system.
  9457. */
  9458. env->migration_type = migrate_task;
  9459. env->imbalance = 1;
  9460. return;
  9461. }
  9462. /*
  9463. * Try to use spare capacity of local group without overloading it or
  9464. * emptying busiest.
  9465. */
  9466. if (local->group_type == group_has_spare) {
  9467. if ((busiest->group_type > group_fully_busy) &&
  9468. !(env->sd->flags & SD_SHARE_LLC)) {
  9469. /*
  9470. * If busiest is overloaded, try to fill spare
  9471. * capacity. This might end up creating spare capacity
  9472. * in busiest or busiest still being overloaded but
  9473. * there is no simple way to directly compute the
  9474. * amount of load to migrate in order to balance the
  9475. * system.
  9476. */
  9477. env->migration_type = migrate_util;
  9478. env->imbalance = max(local->group_capacity, local->group_util) -
  9479. local->group_util;
  9480. /*
  9481. * In some cases, the group's utilization is max or even
  9482. * higher than capacity because of migrations but the
  9483. * local CPU is (newly) idle. There is at least one
  9484. * waiting task in this overloaded busiest group. Let's
  9485. * try to pull it.
  9486. */
  9487. if (env->idle && env->imbalance == 0) {
  9488. env->migration_type = migrate_task;
  9489. env->imbalance = 1;
  9490. }
  9491. return;
  9492. }
  9493. if (busiest->group_weight == 1 || sds->prefer_sibling) {
  9494. /*
  9495. * When prefer sibling, evenly spread running tasks on
  9496. * groups.
  9497. */
  9498. env->migration_type = migrate_task;
  9499. env->imbalance = sibling_imbalance(env, sds, busiest, local);
  9500. } else {
  9501. /*
  9502. * If there is no overload, we just want to even the number of
  9503. * idle CPUs.
  9504. */
  9505. env->migration_type = migrate_task;
  9506. env->imbalance = max_t(long, 0,
  9507. (local->idle_cpus - busiest->idle_cpus));
  9508. }
  9509. #ifdef CONFIG_NUMA
  9510. /* Consider allowing a small imbalance between NUMA groups */
  9511. if (env->sd->flags & SD_NUMA) {
  9512. env->imbalance = adjust_numa_imbalance(env->imbalance,
  9513. local->sum_nr_running + 1,
  9514. env->sd->imb_numa_nr);
  9515. }
  9516. #endif
  9517. /* Number of tasks to move to restore balance */
  9518. env->imbalance >>= 1;
  9519. return;
  9520. }
  9521. /*
  9522. * Local is fully busy but has to take more load to relieve the
  9523. * busiest group
  9524. */
  9525. if (local->group_type < group_overloaded) {
  9526. /*
  9527. * Local will become overloaded so the avg_load metrics are
  9528. * finally needed.
  9529. */
  9530. local->avg_load = (local->group_load * SCHED_CAPACITY_SCALE) /
  9531. local->group_capacity;
  9532. /*
  9533. * If the local group is more loaded than the selected
  9534. * busiest group don't try to pull any tasks.
  9535. */
  9536. if (local->avg_load >= busiest->avg_load) {
  9537. env->imbalance = 0;
  9538. return;
  9539. }
  9540. sds->avg_load = (sds->total_load * SCHED_CAPACITY_SCALE) /
  9541. sds->total_capacity;
  9542. /*
  9543. * If the local group is more loaded than the average system
  9544. * load, don't try to pull any tasks.
  9545. */
  9546. if (local->avg_load >= sds->avg_load) {
  9547. env->imbalance = 0;
  9548. return;
  9549. }
  9550. }
  9551. /*
  9552. * Both group are or will become overloaded and we're trying to get all
  9553. * the CPUs to the average_load, so we don't want to push ourselves
  9554. * above the average load, nor do we wish to reduce the max loaded CPU
  9555. * below the average load. At the same time, we also don't want to
  9556. * reduce the group load below the group capacity. Thus we look for
  9557. * the minimum possible imbalance.
  9558. */
  9559. env->migration_type = migrate_load;
  9560. env->imbalance = min(
  9561. (busiest->avg_load - sds->avg_load) * busiest->group_capacity,
  9562. (sds->avg_load - local->avg_load) * local->group_capacity
  9563. ) / SCHED_CAPACITY_SCALE;
  9564. }
  9565. /******* sched_balance_find_src_group() helpers end here *********************/
  9566. /*
  9567. * Decision matrix according to the local and busiest group type:
  9568. *
  9569. * busiest \ local has_spare fully_busy misfit asym imbalanced overloaded
  9570. * has_spare nr_idle balanced N/A N/A balanced balanced
  9571. * fully_busy nr_idle nr_idle N/A N/A balanced balanced
  9572. * misfit_task force N/A N/A N/A N/A N/A
  9573. * asym_packing force force N/A N/A force force
  9574. * imbalanced force force N/A N/A force force
  9575. * overloaded force force N/A N/A force avg_load
  9576. *
  9577. * N/A : Not Applicable because already filtered while updating
  9578. * statistics.
  9579. * balanced : The system is balanced for these 2 groups.
  9580. * force : Calculate the imbalance as load migration is probably needed.
  9581. * avg_load : Only if imbalance is significant enough.
  9582. * nr_idle : dst_cpu is not busy and the number of idle CPUs is quite
  9583. * different in groups.
  9584. */
  9585. /**
  9586. * sched_balance_find_src_group - Returns the busiest group within the sched_domain
  9587. * if there is an imbalance.
  9588. * @env: The load balancing environment.
  9589. *
  9590. * Also calculates the amount of runnable load which should be moved
  9591. * to restore balance.
  9592. *
  9593. * Return: - The busiest group if imbalance exists.
  9594. */
  9595. static struct sched_group *sched_balance_find_src_group(struct lb_env *env)
  9596. {
  9597. struct sg_lb_stats *local, *busiest;
  9598. struct sd_lb_stats sds;
  9599. init_sd_lb_stats(&sds);
  9600. /*
  9601. * Compute the various statistics relevant for load balancing at
  9602. * this level.
  9603. */
  9604. update_sd_lb_stats(env, &sds);
  9605. /* There is no busy sibling group to pull tasks from */
  9606. if (!sds.busiest)
  9607. goto out_balanced;
  9608. busiest = &sds.busiest_stat;
  9609. /* Misfit tasks should be dealt with regardless of the avg load */
  9610. if (busiest->group_type == group_misfit_task)
  9611. goto force_balance;
  9612. if (!is_rd_overutilized(env->dst_rq->rd) &&
  9613. rcu_dereference(env->dst_rq->rd->pd))
  9614. goto out_balanced;
  9615. /* ASYM feature bypasses nice load balance check */
  9616. if (busiest->group_type == group_asym_packing)
  9617. goto force_balance;
  9618. /*
  9619. * If the busiest group is imbalanced the below checks don't
  9620. * work because they assume all things are equal, which typically
  9621. * isn't true due to cpus_ptr constraints and the like.
  9622. */
  9623. if (busiest->group_type == group_imbalanced)
  9624. goto force_balance;
  9625. local = &sds.local_stat;
  9626. /*
  9627. * If the local group is busier than the selected busiest group
  9628. * don't try and pull any tasks.
  9629. */
  9630. if (local->group_type > busiest->group_type)
  9631. goto out_balanced;
  9632. /*
  9633. * When groups are overloaded, use the avg_load to ensure fairness
  9634. * between tasks.
  9635. */
  9636. if (local->group_type == group_overloaded) {
  9637. /*
  9638. * If the local group is more loaded than the selected
  9639. * busiest group don't try to pull any tasks.
  9640. */
  9641. if (local->avg_load >= busiest->avg_load)
  9642. goto out_balanced;
  9643. /* XXX broken for overlapping NUMA groups */
  9644. sds.avg_load = (sds.total_load * SCHED_CAPACITY_SCALE) /
  9645. sds.total_capacity;
  9646. /*
  9647. * Don't pull any tasks if this group is already above the
  9648. * domain average load.
  9649. */
  9650. if (local->avg_load >= sds.avg_load)
  9651. goto out_balanced;
  9652. /*
  9653. * If the busiest group is more loaded, use imbalance_pct to be
  9654. * conservative.
  9655. */
  9656. if (100 * busiest->avg_load <=
  9657. env->sd->imbalance_pct * local->avg_load)
  9658. goto out_balanced;
  9659. }
  9660. /*
  9661. * Try to move all excess tasks to a sibling domain of the busiest
  9662. * group's child domain.
  9663. */
  9664. if (sds.prefer_sibling && local->group_type == group_has_spare &&
  9665. sibling_imbalance(env, &sds, busiest, local) > 1)
  9666. goto force_balance;
  9667. if (busiest->group_type != group_overloaded) {
  9668. if (!env->idle) {
  9669. /*
  9670. * If the busiest group is not overloaded (and as a
  9671. * result the local one too) but this CPU is already
  9672. * busy, let another idle CPU try to pull task.
  9673. */
  9674. goto out_balanced;
  9675. }
  9676. if (busiest->group_type == group_smt_balance &&
  9677. smt_vs_nonsmt_groups(sds.local, sds.busiest)) {
  9678. /* Let non SMT CPU pull from SMT CPU sharing with sibling */
  9679. goto force_balance;
  9680. }
  9681. if (busiest->group_weight > 1 &&
  9682. local->idle_cpus <= (busiest->idle_cpus + 1)) {
  9683. /*
  9684. * If the busiest group is not overloaded
  9685. * and there is no imbalance between this and busiest
  9686. * group wrt idle CPUs, it is balanced. The imbalance
  9687. * becomes significant if the diff is greater than 1
  9688. * otherwise we might end up to just move the imbalance
  9689. * on another group. Of course this applies only if
  9690. * there is more than 1 CPU per group.
  9691. */
  9692. goto out_balanced;
  9693. }
  9694. if (busiest->sum_h_nr_running == 1) {
  9695. /*
  9696. * busiest doesn't have any tasks waiting to run
  9697. */
  9698. goto out_balanced;
  9699. }
  9700. }
  9701. force_balance:
  9702. /* Looks like there is an imbalance. Compute it */
  9703. calculate_imbalance(env, &sds);
  9704. return env->imbalance ? sds.busiest : NULL;
  9705. out_balanced:
  9706. env->imbalance = 0;
  9707. return NULL;
  9708. }
  9709. /*
  9710. * sched_balance_find_src_rq - find the busiest runqueue among the CPUs in the group.
  9711. */
  9712. static struct rq *sched_balance_find_src_rq(struct lb_env *env,
  9713. struct sched_group *group)
  9714. {
  9715. struct rq *busiest = NULL, *rq;
  9716. unsigned long busiest_util = 0, busiest_load = 0, busiest_capacity = 1;
  9717. unsigned int busiest_nr = 0;
  9718. int i;
  9719. for_each_cpu_and(i, sched_group_span(group), env->cpus) {
  9720. unsigned long capacity, load, util;
  9721. unsigned int nr_running;
  9722. enum fbq_type rt;
  9723. rq = cpu_rq(i);
  9724. rt = fbq_classify_rq(rq);
  9725. /*
  9726. * We classify groups/runqueues into three groups:
  9727. * - regular: there are !numa tasks
  9728. * - remote: there are numa tasks that run on the 'wrong' node
  9729. * - all: there is no distinction
  9730. *
  9731. * In order to avoid migrating ideally placed numa tasks,
  9732. * ignore those when there's better options.
  9733. *
  9734. * If we ignore the actual busiest queue to migrate another
  9735. * task, the next balance pass can still reduce the busiest
  9736. * queue by moving tasks around inside the node.
  9737. *
  9738. * If we cannot move enough load due to this classification
  9739. * the next pass will adjust the group classification and
  9740. * allow migration of more tasks.
  9741. *
  9742. * Both cases only affect the total convergence complexity.
  9743. */
  9744. if (rt > env->fbq_type)
  9745. continue;
  9746. nr_running = rq->cfs.h_nr_queued;
  9747. if (!nr_running)
  9748. continue;
  9749. capacity = capacity_of(i);
  9750. /*
  9751. * For ASYM_CPUCAPACITY domains, don't pick a CPU that could
  9752. * eventually lead to active_balancing high->low capacity.
  9753. * Higher per-CPU capacity is considered better than balancing
  9754. * average load.
  9755. */
  9756. if (env->sd->flags & SD_ASYM_CPUCAPACITY &&
  9757. !capacity_greater(capacity_of(env->dst_cpu), capacity) &&
  9758. nr_running == 1)
  9759. continue;
  9760. /*
  9761. * Make sure we only pull tasks from a CPU of lower priority
  9762. * when balancing between SMT siblings.
  9763. *
  9764. * If balancing between cores, let lower priority CPUs help
  9765. * SMT cores with more than one busy sibling.
  9766. */
  9767. if (sched_asym(env->sd, i, env->dst_cpu) && nr_running == 1)
  9768. continue;
  9769. switch (env->migration_type) {
  9770. case migrate_load:
  9771. /*
  9772. * When comparing with load imbalance, use cpu_load()
  9773. * which is not scaled with the CPU capacity.
  9774. */
  9775. load = cpu_load(rq);
  9776. if (nr_running == 1 && load > env->imbalance &&
  9777. !check_cpu_capacity(rq, env->sd))
  9778. break;
  9779. /*
  9780. * For the load comparisons with the other CPUs,
  9781. * consider the cpu_load() scaled with the CPU
  9782. * capacity, so that the load can be moved away
  9783. * from the CPU that is potentially running at a
  9784. * lower capacity.
  9785. *
  9786. * Thus we're looking for max(load_i / capacity_i),
  9787. * crosswise multiplication to rid ourselves of the
  9788. * division works out to:
  9789. * load_i * capacity_j > load_j * capacity_i;
  9790. * where j is our previous maximum.
  9791. */
  9792. if (load * busiest_capacity > busiest_load * capacity) {
  9793. busiest_load = load;
  9794. busiest_capacity = capacity;
  9795. busiest = rq;
  9796. }
  9797. break;
  9798. case migrate_util:
  9799. util = cpu_util_cfs_boost(i);
  9800. /*
  9801. * Don't try to pull utilization from a CPU with one
  9802. * running task. Whatever its utilization, we will fail
  9803. * detach the task.
  9804. */
  9805. if (nr_running <= 1)
  9806. continue;
  9807. if (busiest_util < util) {
  9808. busiest_util = util;
  9809. busiest = rq;
  9810. }
  9811. break;
  9812. case migrate_task:
  9813. if (busiest_nr < nr_running) {
  9814. busiest_nr = nr_running;
  9815. busiest = rq;
  9816. }
  9817. break;
  9818. case migrate_misfit:
  9819. /*
  9820. * For ASYM_CPUCAPACITY domains with misfit tasks we
  9821. * simply seek the "biggest" misfit task.
  9822. */
  9823. if (rq->misfit_task_load > busiest_load) {
  9824. busiest_load = rq->misfit_task_load;
  9825. busiest = rq;
  9826. }
  9827. break;
  9828. }
  9829. }
  9830. return busiest;
  9831. }
  9832. /*
  9833. * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
  9834. * so long as it is large enough.
  9835. */
  9836. #define MAX_PINNED_INTERVAL 512
  9837. static inline bool
  9838. asym_active_balance(struct lb_env *env)
  9839. {
  9840. /*
  9841. * ASYM_PACKING needs to force migrate tasks from busy but lower
  9842. * priority CPUs in order to pack all tasks in the highest priority
  9843. * CPUs. When done between cores, do it only if the whole core if the
  9844. * whole core is idle.
  9845. *
  9846. * If @env::src_cpu is an SMT core with busy siblings, let
  9847. * the lower priority @env::dst_cpu help it. Do not follow
  9848. * CPU priority.
  9849. */
  9850. return env->idle && sched_use_asym_prio(env->sd, env->dst_cpu) &&
  9851. (sched_asym_prefer(env->dst_cpu, env->src_cpu) ||
  9852. !sched_use_asym_prio(env->sd, env->src_cpu));
  9853. }
  9854. static inline bool
  9855. imbalanced_active_balance(struct lb_env *env)
  9856. {
  9857. struct sched_domain *sd = env->sd;
  9858. /*
  9859. * The imbalanced case includes the case of pinned tasks preventing a fair
  9860. * distribution of the load on the system but also the even distribution of the
  9861. * threads on a system with spare capacity
  9862. */
  9863. if ((env->migration_type == migrate_task) &&
  9864. (sd->nr_balance_failed > sd->cache_nice_tries+2))
  9865. return 1;
  9866. return 0;
  9867. }
  9868. static int need_active_balance(struct lb_env *env)
  9869. {
  9870. struct sched_domain *sd = env->sd;
  9871. if (asym_active_balance(env))
  9872. return 1;
  9873. if (imbalanced_active_balance(env))
  9874. return 1;
  9875. /*
  9876. * The dst_cpu is idle and the src_cpu CPU has only 1 CFS task.
  9877. * It's worth migrating the task if the src_cpu's capacity is reduced
  9878. * because of other sched_class or IRQs if more capacity stays
  9879. * available on dst_cpu.
  9880. */
  9881. if (env->idle &&
  9882. (env->src_rq->cfs.h_nr_queued == 1)) {
  9883. if ((check_cpu_capacity(env->src_rq, sd)) &&
  9884. (capacity_of(env->src_cpu)*sd->imbalance_pct < capacity_of(env->dst_cpu)*100))
  9885. return 1;
  9886. }
  9887. if (env->migration_type == migrate_misfit)
  9888. return 1;
  9889. return 0;
  9890. }
  9891. static int active_load_balance_cpu_stop(void *data);
  9892. static int should_we_balance(struct lb_env *env)
  9893. {
  9894. struct cpumask *swb_cpus = this_cpu_cpumask_var_ptr(should_we_balance_tmpmask);
  9895. struct sched_group *sg = env->sd->groups;
  9896. int cpu, idle_smt = -1;
  9897. /*
  9898. * Ensure the balancing environment is consistent; can happen
  9899. * when the softirq triggers 'during' hotplug.
  9900. */
  9901. if (!cpumask_test_cpu(env->dst_cpu, env->cpus))
  9902. return 0;
  9903. /*
  9904. * In the newly idle case, we will allow all the CPUs
  9905. * to do the newly idle load balance.
  9906. *
  9907. * However, we bail out if we already have tasks or a wakeup pending,
  9908. * to optimize wakeup latency.
  9909. */
  9910. if (env->idle == CPU_NEWLY_IDLE) {
  9911. if (env->dst_rq->nr_running > 0 || env->dst_rq->ttwu_pending)
  9912. return 0;
  9913. return 1;
  9914. }
  9915. cpumask_copy(swb_cpus, group_balance_mask(sg));
  9916. /* Try to find first idle CPU */
  9917. for_each_cpu_and(cpu, swb_cpus, env->cpus) {
  9918. if (!idle_cpu(cpu))
  9919. continue;
  9920. /*
  9921. * Don't balance to idle SMT in busy core right away when
  9922. * balancing cores, but remember the first idle SMT CPU for
  9923. * later consideration. Find CPU on an idle core first.
  9924. */
  9925. if (!(env->sd->flags & SD_SHARE_CPUCAPACITY) && !is_core_idle(cpu)) {
  9926. if (idle_smt == -1)
  9927. idle_smt = cpu;
  9928. /*
  9929. * If the core is not idle, and first SMT sibling which is
  9930. * idle has been found, then its not needed to check other
  9931. * SMT siblings for idleness:
  9932. */
  9933. #ifdef CONFIG_SCHED_SMT
  9934. cpumask_andnot(swb_cpus, swb_cpus, cpu_smt_mask(cpu));
  9935. #endif
  9936. continue;
  9937. }
  9938. /*
  9939. * Are we the first idle core in a non-SMT domain or higher,
  9940. * or the first idle CPU in a SMT domain?
  9941. */
  9942. return cpu == env->dst_cpu;
  9943. }
  9944. /* Are we the first idle CPU with busy siblings? */
  9945. if (idle_smt != -1)
  9946. return idle_smt == env->dst_cpu;
  9947. /* Are we the first CPU of this group ? */
  9948. return group_balance_cpu(sg) == env->dst_cpu;
  9949. }
  9950. /*
  9951. * Check this_cpu to ensure it is balanced within domain. Attempt to move
  9952. * tasks if there is an imbalance.
  9953. */
  9954. static int sched_balance_rq(int this_cpu, struct rq *this_rq,
  9955. struct sched_domain *sd, enum cpu_idle_type idle,
  9956. int *continue_balancing)
  9957. {
  9958. int ld_moved, cur_ld_moved, active_balance = 0;
  9959. struct sched_domain *sd_parent = sd->parent;
  9960. struct sched_group *group;
  9961. struct rq *busiest;
  9962. struct rq_flags rf;
  9963. struct cpumask *cpus = this_cpu_cpumask_var_ptr(load_balance_mask);
  9964. struct lb_env env = {
  9965. .sd = sd,
  9966. .dst_cpu = this_cpu,
  9967. .dst_rq = this_rq,
  9968. .dst_grpmask = group_balance_mask(sd->groups),
  9969. .idle = idle,
  9970. .loop_break = SCHED_NR_MIGRATE_BREAK,
  9971. .cpus = cpus,
  9972. .fbq_type = all,
  9973. .tasks = LIST_HEAD_INIT(env.tasks),
  9974. };
  9975. cpumask_and(cpus, sched_domain_span(sd), cpu_active_mask);
  9976. schedstat_inc(sd->lb_count[idle]);
  9977. redo:
  9978. if (!should_we_balance(&env)) {
  9979. *continue_balancing = 0;
  9980. goto out_balanced;
  9981. }
  9982. group = sched_balance_find_src_group(&env);
  9983. if (!group) {
  9984. schedstat_inc(sd->lb_nobusyg[idle]);
  9985. goto out_balanced;
  9986. }
  9987. busiest = sched_balance_find_src_rq(&env, group);
  9988. if (!busiest) {
  9989. schedstat_inc(sd->lb_nobusyq[idle]);
  9990. goto out_balanced;
  9991. }
  9992. WARN_ON_ONCE(busiest == env.dst_rq);
  9993. schedstat_add(sd->lb_imbalance[idle], env.imbalance);
  9994. env.src_cpu = busiest->cpu;
  9995. env.src_rq = busiest;
  9996. ld_moved = 0;
  9997. /* Clear this flag as soon as we find a pullable task */
  9998. env.flags |= LBF_ALL_PINNED;
  9999. if (busiest->nr_running > 1) {
  10000. /*
  10001. * Attempt to move tasks. If sched_balance_find_src_group has found
  10002. * an imbalance but busiest->nr_running <= 1, the group is
  10003. * still unbalanced. ld_moved simply stays zero, so it is
  10004. * correctly treated as an imbalance.
  10005. */
  10006. env.loop_max = min(sysctl_sched_nr_migrate, busiest->nr_running);
  10007. more_balance:
  10008. rq_lock_irqsave(busiest, &rf);
  10009. update_rq_clock(busiest);
  10010. /*
  10011. * cur_ld_moved - load moved in current iteration
  10012. * ld_moved - cumulative load moved across iterations
  10013. */
  10014. cur_ld_moved = detach_tasks(&env);
  10015. /*
  10016. * We've detached some tasks from busiest_rq. Every
  10017. * task is masked "TASK_ON_RQ_MIGRATING", so we can safely
  10018. * unlock busiest->lock, and we are able to be sure
  10019. * that nobody can manipulate the tasks in parallel.
  10020. * See task_rq_lock() family for the details.
  10021. */
  10022. rq_unlock(busiest, &rf);
  10023. if (cur_ld_moved) {
  10024. attach_tasks(&env);
  10025. ld_moved += cur_ld_moved;
  10026. }
  10027. local_irq_restore(rf.flags);
  10028. if (env.flags & LBF_NEED_BREAK) {
  10029. env.flags &= ~LBF_NEED_BREAK;
  10030. goto more_balance;
  10031. }
  10032. /*
  10033. * Revisit (affine) tasks on src_cpu that couldn't be moved to
  10034. * us and move them to an alternate dst_cpu in our sched_group
  10035. * where they can run. The upper limit on how many times we
  10036. * iterate on same src_cpu is dependent on number of CPUs in our
  10037. * sched_group.
  10038. *
  10039. * This changes load balance semantics a bit on who can move
  10040. * load to a given_cpu. In addition to the given_cpu itself
  10041. * (or a ilb_cpu acting on its behalf where given_cpu is
  10042. * nohz-idle), we now have balance_cpu in a position to move
  10043. * load to given_cpu. In rare situations, this may cause
  10044. * conflicts (balance_cpu and given_cpu/ilb_cpu deciding
  10045. * _independently_ and at _same_ time to move some load to
  10046. * given_cpu) causing excess load to be moved to given_cpu.
  10047. * This however should not happen so much in practice and
  10048. * moreover subsequent load balance cycles should correct the
  10049. * excess load moved.
  10050. */
  10051. if ((env.flags & LBF_DST_PINNED) && env.imbalance > 0) {
  10052. /* Prevent to re-select dst_cpu via env's CPUs */
  10053. __cpumask_clear_cpu(env.dst_cpu, env.cpus);
  10054. env.dst_rq = cpu_rq(env.new_dst_cpu);
  10055. env.dst_cpu = env.new_dst_cpu;
  10056. env.flags &= ~LBF_DST_PINNED;
  10057. env.loop = 0;
  10058. env.loop_break = SCHED_NR_MIGRATE_BREAK;
  10059. /*
  10060. * Go back to "more_balance" rather than "redo" since we
  10061. * need to continue with same src_cpu.
  10062. */
  10063. goto more_balance;
  10064. }
  10065. /*
  10066. * We failed to reach balance because of affinity.
  10067. */
  10068. if (sd_parent) {
  10069. int *group_imbalance = &sd_parent->groups->sgc->imbalance;
  10070. if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0)
  10071. *group_imbalance = 1;
  10072. }
  10073. /* All tasks on this runqueue were pinned by CPU affinity */
  10074. if (unlikely(env.flags & LBF_ALL_PINNED)) {
  10075. __cpumask_clear_cpu(cpu_of(busiest), cpus);
  10076. /*
  10077. * Attempting to continue load balancing at the current
  10078. * sched_domain level only makes sense if there are
  10079. * active CPUs remaining as possible busiest CPUs to
  10080. * pull load from which are not contained within the
  10081. * destination group that is receiving any migrated
  10082. * load.
  10083. */
  10084. if (!cpumask_subset(cpus, env.dst_grpmask)) {
  10085. env.loop = 0;
  10086. env.loop_break = SCHED_NR_MIGRATE_BREAK;
  10087. goto redo;
  10088. }
  10089. goto out_all_pinned;
  10090. }
  10091. }
  10092. if (!ld_moved) {
  10093. schedstat_inc(sd->lb_failed[idle]);
  10094. /*
  10095. * Increment the failure counter only on periodic balance.
  10096. * We do not want newidle balance, which can be very
  10097. * frequent, pollute the failure counter causing
  10098. * excessive cache_hot migrations and active balances.
  10099. *
  10100. * Similarly for migration_misfit which is not related to
  10101. * load/util migration, don't pollute nr_balance_failed.
  10102. */
  10103. if (idle != CPU_NEWLY_IDLE &&
  10104. env.migration_type != migrate_misfit)
  10105. sd->nr_balance_failed++;
  10106. if (need_active_balance(&env)) {
  10107. unsigned long flags;
  10108. raw_spin_rq_lock_irqsave(busiest, flags);
  10109. /*
  10110. * Don't kick the active_load_balance_cpu_stop,
  10111. * if the curr task on busiest CPU can't be
  10112. * moved to this_cpu:
  10113. */
  10114. if (!cpumask_test_cpu(this_cpu, busiest->curr->cpus_ptr)) {
  10115. raw_spin_rq_unlock_irqrestore(busiest, flags);
  10116. goto out_one_pinned;
  10117. }
  10118. /* Record that we found at least one task that could run on this_cpu */
  10119. env.flags &= ~LBF_ALL_PINNED;
  10120. /*
  10121. * ->active_balance synchronizes accesses to
  10122. * ->active_balance_work. Once set, it's cleared
  10123. * only after active load balance is finished.
  10124. */
  10125. if (!busiest->active_balance) {
  10126. busiest->active_balance = 1;
  10127. busiest->push_cpu = this_cpu;
  10128. active_balance = 1;
  10129. }
  10130. preempt_disable();
  10131. raw_spin_rq_unlock_irqrestore(busiest, flags);
  10132. if (active_balance) {
  10133. stop_one_cpu_nowait(cpu_of(busiest),
  10134. active_load_balance_cpu_stop, busiest,
  10135. &busiest->active_balance_work);
  10136. }
  10137. preempt_enable();
  10138. }
  10139. } else {
  10140. sd->nr_balance_failed = 0;
  10141. }
  10142. if (likely(!active_balance) || need_active_balance(&env)) {
  10143. /* We were unbalanced, so reset the balancing interval */
  10144. sd->balance_interval = sd->min_interval;
  10145. }
  10146. goto out;
  10147. out_balanced:
  10148. /*
  10149. * We reach balance although we may have faced some affinity
  10150. * constraints. Clear the imbalance flag only if other tasks got
  10151. * a chance to move and fix the imbalance.
  10152. */
  10153. if (sd_parent && !(env.flags & LBF_ALL_PINNED)) {
  10154. int *group_imbalance = &sd_parent->groups->sgc->imbalance;
  10155. if (*group_imbalance)
  10156. *group_imbalance = 0;
  10157. }
  10158. out_all_pinned:
  10159. /*
  10160. * We reach balance because all tasks are pinned at this level so
  10161. * we can't migrate them. Let the imbalance flag set so parent level
  10162. * can try to migrate them.
  10163. */
  10164. schedstat_inc(sd->lb_balanced[idle]);
  10165. sd->nr_balance_failed = 0;
  10166. out_one_pinned:
  10167. ld_moved = 0;
  10168. /*
  10169. * sched_balance_newidle() disregards balance intervals, so we could
  10170. * repeatedly reach this code, which would lead to balance_interval
  10171. * skyrocketing in a short amount of time. Skip the balance_interval
  10172. * increase logic to avoid that.
  10173. *
  10174. * Similarly misfit migration which is not necessarily an indication of
  10175. * the system being busy and requires lb to backoff to let it settle
  10176. * down.
  10177. */
  10178. if (env.idle == CPU_NEWLY_IDLE ||
  10179. env.migration_type == migrate_misfit)
  10180. goto out;
  10181. /* tune up the balancing interval */
  10182. if ((env.flags & LBF_ALL_PINNED &&
  10183. sd->balance_interval < MAX_PINNED_INTERVAL) ||
  10184. sd->balance_interval < sd->max_interval)
  10185. sd->balance_interval *= 2;
  10186. out:
  10187. return ld_moved;
  10188. }
  10189. static inline unsigned long
  10190. get_sd_balance_interval(struct sched_domain *sd, int cpu_busy)
  10191. {
  10192. unsigned long interval = sd->balance_interval;
  10193. if (cpu_busy)
  10194. interval *= sd->busy_factor;
  10195. /* scale ms to jiffies */
  10196. interval = msecs_to_jiffies(interval);
  10197. /*
  10198. * Reduce likelihood of busy balancing at higher domains racing with
  10199. * balancing at lower domains by preventing their balancing periods
  10200. * from being multiples of each other.
  10201. */
  10202. if (cpu_busy)
  10203. interval -= 1;
  10204. interval = clamp(interval, 1UL, max_load_balance_interval);
  10205. return interval;
  10206. }
  10207. static inline void
  10208. update_next_balance(struct sched_domain *sd, unsigned long *next_balance)
  10209. {
  10210. unsigned long interval, next;
  10211. /* used by idle balance, so cpu_busy = 0 */
  10212. interval = get_sd_balance_interval(sd, 0);
  10213. next = sd->last_balance + interval;
  10214. if (time_after(*next_balance, next))
  10215. *next_balance = next;
  10216. }
  10217. /*
  10218. * active_load_balance_cpu_stop is run by the CPU stopper. It pushes
  10219. * running tasks off the busiest CPU onto idle CPUs. It requires at
  10220. * least 1 task to be running on each physical CPU where possible, and
  10221. * avoids physical / logical imbalances.
  10222. */
  10223. static int active_load_balance_cpu_stop(void *data)
  10224. {
  10225. struct rq *busiest_rq = data;
  10226. int busiest_cpu = cpu_of(busiest_rq);
  10227. int target_cpu = busiest_rq->push_cpu;
  10228. struct rq *target_rq = cpu_rq(target_cpu);
  10229. struct sched_domain *sd;
  10230. struct task_struct *p = NULL;
  10231. struct rq_flags rf;
  10232. rq_lock_irq(busiest_rq, &rf);
  10233. /*
  10234. * Between queueing the stop-work and running it is a hole in which
  10235. * CPUs can become inactive. We should not move tasks from or to
  10236. * inactive CPUs.
  10237. */
  10238. if (!cpu_active(busiest_cpu) || !cpu_active(target_cpu))
  10239. goto out_unlock;
  10240. /* Make sure the requested CPU hasn't gone down in the meantime: */
  10241. if (unlikely(busiest_cpu != smp_processor_id() ||
  10242. !busiest_rq->active_balance))
  10243. goto out_unlock;
  10244. /* Is there any task to move? */
  10245. if (busiest_rq->nr_running <= 1)
  10246. goto out_unlock;
  10247. /*
  10248. * This condition is "impossible", if it occurs
  10249. * we need to fix it. Originally reported by
  10250. * Bjorn Helgaas on a 128-CPU setup.
  10251. */
  10252. WARN_ON_ONCE(busiest_rq == target_rq);
  10253. /* Search for an sd spanning us and the target CPU. */
  10254. rcu_read_lock();
  10255. for_each_domain(target_cpu, sd) {
  10256. if (cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
  10257. break;
  10258. }
  10259. if (likely(sd)) {
  10260. struct lb_env env = {
  10261. .sd = sd,
  10262. .dst_cpu = target_cpu,
  10263. .dst_rq = target_rq,
  10264. .src_cpu = busiest_rq->cpu,
  10265. .src_rq = busiest_rq,
  10266. .idle = CPU_IDLE,
  10267. .flags = LBF_ACTIVE_LB,
  10268. };
  10269. schedstat_inc(sd->alb_count);
  10270. update_rq_clock(busiest_rq);
  10271. p = detach_one_task(&env);
  10272. if (p) {
  10273. schedstat_inc(sd->alb_pushed);
  10274. /* Active balancing done, reset the failure counter. */
  10275. sd->nr_balance_failed = 0;
  10276. } else {
  10277. schedstat_inc(sd->alb_failed);
  10278. }
  10279. }
  10280. rcu_read_unlock();
  10281. out_unlock:
  10282. busiest_rq->active_balance = 0;
  10283. rq_unlock(busiest_rq, &rf);
  10284. if (p)
  10285. attach_one_task(target_rq, p);
  10286. local_irq_enable();
  10287. return 0;
  10288. }
  10289. /*
  10290. * This flag serializes load-balancing passes over large domains
  10291. * (above the NODE topology level) - only one load-balancing instance
  10292. * may run at a time, to reduce overhead on very large systems with
  10293. * lots of CPUs and large NUMA distances.
  10294. *
  10295. * - Note that load-balancing passes triggered while another one
  10296. * is executing are skipped and not re-tried.
  10297. *
  10298. * - Also note that this does not serialize rebalance_domains()
  10299. * execution, as non-SD_SERIALIZE domains will still be
  10300. * load-balanced in parallel.
  10301. */
  10302. static atomic_t sched_balance_running = ATOMIC_INIT(0);
  10303. /*
  10304. * Scale the max sched_balance_rq interval with the number of CPUs in the system.
  10305. * This trades load-balance latency on larger machines for less cross talk.
  10306. */
  10307. void update_max_interval(void)
  10308. {
  10309. max_load_balance_interval = HZ*num_online_cpus()/10;
  10310. }
  10311. static inline bool update_newidle_cost(struct sched_domain *sd, u64 cost)
  10312. {
  10313. if (cost > sd->max_newidle_lb_cost) {
  10314. /*
  10315. * Track max cost of a domain to make sure to not delay the
  10316. * next wakeup on the CPU.
  10317. *
  10318. * sched_balance_newidle() bumps the cost whenever newidle
  10319. * balance fails, and we don't want things to grow out of
  10320. * control. Use the sysctl_sched_migration_cost as the upper
  10321. * limit, plus a litle extra to avoid off by ones.
  10322. */
  10323. sd->max_newidle_lb_cost =
  10324. min(cost, sysctl_sched_migration_cost + 200);
  10325. sd->last_decay_max_lb_cost = jiffies;
  10326. } else if (time_after(jiffies, sd->last_decay_max_lb_cost + HZ)) {
  10327. /*
  10328. * Decay the newidle max times by ~1% per second to ensure that
  10329. * it is not outdated and the current max cost is actually
  10330. * shorter.
  10331. */
  10332. sd->max_newidle_lb_cost = (sd->max_newidle_lb_cost * 253) / 256;
  10333. sd->last_decay_max_lb_cost = jiffies;
  10334. return true;
  10335. }
  10336. return false;
  10337. }
  10338. /*
  10339. * It checks each scheduling domain to see if it is due to be balanced,
  10340. * and initiates a balancing operation if so.
  10341. *
  10342. * Balancing parameters are set up in init_sched_domains.
  10343. */
  10344. static void sched_balance_domains(struct rq *rq, enum cpu_idle_type idle)
  10345. {
  10346. int continue_balancing = 1;
  10347. int cpu = rq->cpu;
  10348. int busy = idle != CPU_IDLE && !sched_idle_cpu(cpu);
  10349. unsigned long interval;
  10350. struct sched_domain *sd;
  10351. /* Earliest time when we have to do rebalance again */
  10352. unsigned long next_balance = jiffies + 60*HZ;
  10353. int update_next_balance = 0;
  10354. int need_serialize, need_decay = 0;
  10355. u64 max_cost = 0;
  10356. rcu_read_lock();
  10357. for_each_domain(cpu, sd) {
  10358. /*
  10359. * Decay the newidle max times here because this is a regular
  10360. * visit to all the domains.
  10361. */
  10362. need_decay = update_newidle_cost(sd, 0);
  10363. max_cost += sd->max_newidle_lb_cost;
  10364. /*
  10365. * Stop the load balance at this level. There is another
  10366. * CPU in our sched group which is doing load balancing more
  10367. * actively.
  10368. */
  10369. if (!continue_balancing) {
  10370. if (need_decay)
  10371. continue;
  10372. break;
  10373. }
  10374. interval = get_sd_balance_interval(sd, busy);
  10375. need_serialize = sd->flags & SD_SERIALIZE;
  10376. if (need_serialize) {
  10377. if (atomic_cmpxchg_acquire(&sched_balance_running, 0, 1))
  10378. goto out;
  10379. }
  10380. if (time_after_eq(jiffies, sd->last_balance + interval)) {
  10381. if (sched_balance_rq(cpu, rq, sd, idle, &continue_balancing)) {
  10382. /*
  10383. * The LBF_DST_PINNED logic could have changed
  10384. * env->dst_cpu, so we can't know our idle
  10385. * state even if we migrated tasks. Update it.
  10386. */
  10387. idle = idle_cpu(cpu);
  10388. busy = !idle && !sched_idle_cpu(cpu);
  10389. }
  10390. sd->last_balance = jiffies;
  10391. interval = get_sd_balance_interval(sd, busy);
  10392. }
  10393. if (need_serialize)
  10394. atomic_set_release(&sched_balance_running, 0);
  10395. out:
  10396. if (time_after(next_balance, sd->last_balance + interval)) {
  10397. next_balance = sd->last_balance + interval;
  10398. update_next_balance = 1;
  10399. }
  10400. }
  10401. if (need_decay) {
  10402. /*
  10403. * Ensure the rq-wide value also decays but keep it at a
  10404. * reasonable floor to avoid funnies with rq->avg_idle.
  10405. */
  10406. rq->max_idle_balance_cost =
  10407. max((u64)sysctl_sched_migration_cost, max_cost);
  10408. }
  10409. rcu_read_unlock();
  10410. /*
  10411. * next_balance will be updated only when there is a need.
  10412. * When the cpu is attached to null domain for ex, it will not be
  10413. * updated.
  10414. */
  10415. if (likely(update_next_balance))
  10416. rq->next_balance = next_balance;
  10417. }
  10418. static inline int on_null_domain(struct rq *rq)
  10419. {
  10420. return unlikely(!rcu_dereference_sched(rq->sd));
  10421. }
  10422. #ifdef CONFIG_NO_HZ_COMMON
  10423. /*
  10424. * NOHZ idle load balancing (ILB) details:
  10425. *
  10426. * - When one of the busy CPUs notices that there may be an idle rebalancing
  10427. * needed, they will kick the idle load balancer, which then does idle
  10428. * load balancing for all the idle CPUs.
  10429. *
  10430. * - HK_TYPE_MISC CPUs are used for this task, because HK_TYPE_SCHED is not set
  10431. * anywhere yet.
  10432. */
  10433. static inline int find_new_ilb(void)
  10434. {
  10435. const struct cpumask *hk_mask;
  10436. int ilb_cpu;
  10437. hk_mask = housekeeping_cpumask(HK_TYPE_MISC);
  10438. for_each_cpu_and(ilb_cpu, nohz.idle_cpus_mask, hk_mask) {
  10439. if (ilb_cpu == smp_processor_id())
  10440. continue;
  10441. if (idle_cpu(ilb_cpu))
  10442. return ilb_cpu;
  10443. }
  10444. return -1;
  10445. }
  10446. /*
  10447. * Kick a CPU to do the NOHZ balancing, if it is time for it, via a cross-CPU
  10448. * SMP function call (IPI).
  10449. *
  10450. * We pick the first idle CPU in the HK_TYPE_MISC housekeeping set (if there is one).
  10451. */
  10452. static void kick_ilb(unsigned int flags)
  10453. {
  10454. int ilb_cpu;
  10455. /*
  10456. * Increase nohz.next_balance only when if full ilb is triggered but
  10457. * not if we only update stats.
  10458. */
  10459. if (flags & NOHZ_BALANCE_KICK)
  10460. nohz.next_balance = jiffies+1;
  10461. ilb_cpu = find_new_ilb();
  10462. if (ilb_cpu < 0)
  10463. return;
  10464. /*
  10465. * Don't bother if no new NOHZ balance work items for ilb_cpu,
  10466. * i.e. all bits in flags are already set in ilb_cpu.
  10467. */
  10468. if ((atomic_read(nohz_flags(ilb_cpu)) & flags) == flags)
  10469. return;
  10470. /*
  10471. * Access to rq::nohz_csd is serialized by NOHZ_KICK_MASK; he who sets
  10472. * the first flag owns it; cleared by nohz_csd_func().
  10473. */
  10474. flags = atomic_fetch_or(flags, nohz_flags(ilb_cpu));
  10475. if (flags & NOHZ_KICK_MASK)
  10476. return;
  10477. /*
  10478. * This way we generate an IPI on the target CPU which
  10479. * is idle, and the softirq performing NOHZ idle load balancing
  10480. * will be run before returning from the IPI.
  10481. */
  10482. smp_call_function_single_async(ilb_cpu, &cpu_rq(ilb_cpu)->nohz_csd);
  10483. }
  10484. /*
  10485. * Current decision point for kicking the idle load balancer in the presence
  10486. * of idle CPUs in the system.
  10487. */
  10488. static void nohz_balancer_kick(struct rq *rq)
  10489. {
  10490. unsigned long now = jiffies;
  10491. struct sched_domain_shared *sds;
  10492. struct sched_domain *sd;
  10493. int nr_busy, i, cpu = rq->cpu;
  10494. unsigned int flags = 0;
  10495. if (unlikely(rq->idle_balance))
  10496. return;
  10497. /*
  10498. * We may be recently in ticked or tickless idle mode. At the first
  10499. * busy tick after returning from idle, we will update the busy stats.
  10500. */
  10501. nohz_balance_exit_idle(rq);
  10502. /*
  10503. * None are in tickless mode and hence no need for NOHZ idle load
  10504. * balancing:
  10505. */
  10506. if (likely(!atomic_read(&nohz.nr_cpus)))
  10507. return;
  10508. if (READ_ONCE(nohz.has_blocked) &&
  10509. time_after(now, READ_ONCE(nohz.next_blocked)))
  10510. flags = NOHZ_STATS_KICK;
  10511. if (time_before(now, nohz.next_balance))
  10512. goto out;
  10513. if (rq->nr_running >= 2) {
  10514. flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
  10515. goto out;
  10516. }
  10517. rcu_read_lock();
  10518. sd = rcu_dereference(rq->sd);
  10519. if (sd) {
  10520. /*
  10521. * If there's a runnable CFS task and the current CPU has reduced
  10522. * capacity, kick the ILB to see if there's a better CPU to run on:
  10523. */
  10524. if (rq->cfs.h_nr_queued >= 1 && check_cpu_capacity(rq, sd)) {
  10525. flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
  10526. goto unlock;
  10527. }
  10528. }
  10529. sd = rcu_dereference(per_cpu(sd_asym_packing, cpu));
  10530. if (sd) {
  10531. /*
  10532. * When ASYM_PACKING; see if there's a more preferred CPU
  10533. * currently idle; in which case, kick the ILB to move tasks
  10534. * around.
  10535. *
  10536. * When balancing between cores, all the SMT siblings of the
  10537. * preferred CPU must be idle.
  10538. */
  10539. for_each_cpu_and(i, sched_domain_span(sd), nohz.idle_cpus_mask) {
  10540. if (sched_asym(sd, i, cpu)) {
  10541. flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
  10542. goto unlock;
  10543. }
  10544. }
  10545. }
  10546. sd = rcu_dereference(per_cpu(sd_asym_cpucapacity, cpu));
  10547. if (sd) {
  10548. /*
  10549. * When ASYM_CPUCAPACITY; see if there's a higher capacity CPU
  10550. * to run the misfit task on.
  10551. */
  10552. if (check_misfit_status(rq)) {
  10553. flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
  10554. goto unlock;
  10555. }
  10556. /*
  10557. * For asymmetric systems, we do not want to nicely balance
  10558. * cache use, instead we want to embrace asymmetry and only
  10559. * ensure tasks have enough CPU capacity.
  10560. *
  10561. * Skip the LLC logic because it's not relevant in that case.
  10562. */
  10563. goto unlock;
  10564. }
  10565. sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
  10566. if (sds) {
  10567. /*
  10568. * If there is an imbalance between LLC domains (IOW we could
  10569. * increase the overall cache utilization), we need a less-loaded LLC
  10570. * domain to pull some load from. Likewise, we may need to spread
  10571. * load within the current LLC domain (e.g. packed SMT cores but
  10572. * other CPUs are idle). We can't really know from here how busy
  10573. * the others are - so just get a NOHZ balance going if it looks
  10574. * like this LLC domain has tasks we could move.
  10575. */
  10576. nr_busy = atomic_read(&sds->nr_busy_cpus);
  10577. if (nr_busy > 1) {
  10578. flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
  10579. goto unlock;
  10580. }
  10581. }
  10582. unlock:
  10583. rcu_read_unlock();
  10584. out:
  10585. if (READ_ONCE(nohz.needs_update))
  10586. flags |= NOHZ_NEXT_KICK;
  10587. if (flags)
  10588. kick_ilb(flags);
  10589. }
  10590. static void set_cpu_sd_state_busy(int cpu)
  10591. {
  10592. struct sched_domain *sd;
  10593. rcu_read_lock();
  10594. sd = rcu_dereference(per_cpu(sd_llc, cpu));
  10595. if (!sd || !sd->nohz_idle)
  10596. goto unlock;
  10597. sd->nohz_idle = 0;
  10598. atomic_inc(&sd->shared->nr_busy_cpus);
  10599. unlock:
  10600. rcu_read_unlock();
  10601. }
  10602. void nohz_balance_exit_idle(struct rq *rq)
  10603. {
  10604. SCHED_WARN_ON(rq != this_rq());
  10605. if (likely(!rq->nohz_tick_stopped))
  10606. return;
  10607. rq->nohz_tick_stopped = 0;
  10608. cpumask_clear_cpu(rq->cpu, nohz.idle_cpus_mask);
  10609. atomic_dec(&nohz.nr_cpus);
  10610. set_cpu_sd_state_busy(rq->cpu);
  10611. }
  10612. static void set_cpu_sd_state_idle(int cpu)
  10613. {
  10614. struct sched_domain *sd;
  10615. rcu_read_lock();
  10616. sd = rcu_dereference(per_cpu(sd_llc, cpu));
  10617. if (!sd || sd->nohz_idle)
  10618. goto unlock;
  10619. sd->nohz_idle = 1;
  10620. atomic_dec(&sd->shared->nr_busy_cpus);
  10621. unlock:
  10622. rcu_read_unlock();
  10623. }
  10624. /*
  10625. * This routine will record that the CPU is going idle with tick stopped.
  10626. * This info will be used in performing idle load balancing in the future.
  10627. */
  10628. void nohz_balance_enter_idle(int cpu)
  10629. {
  10630. struct rq *rq = cpu_rq(cpu);
  10631. SCHED_WARN_ON(cpu != smp_processor_id());
  10632. /* If this CPU is going down, then nothing needs to be done: */
  10633. if (!cpu_active(cpu))
  10634. return;
  10635. /* Spare idle load balancing on CPUs that don't want to be disturbed: */
  10636. if (!housekeeping_cpu(cpu, HK_TYPE_SCHED))
  10637. return;
  10638. /*
  10639. * Can be set safely without rq->lock held
  10640. * If a clear happens, it will have evaluated last additions because
  10641. * rq->lock is held during the check and the clear
  10642. */
  10643. rq->has_blocked_load = 1;
  10644. /*
  10645. * The tick is still stopped but load could have been added in the
  10646. * meantime. We set the nohz.has_blocked flag to trig a check of the
  10647. * *_avg. The CPU is already part of nohz.idle_cpus_mask so the clear
  10648. * of nohz.has_blocked can only happen after checking the new load
  10649. */
  10650. if (rq->nohz_tick_stopped)
  10651. goto out;
  10652. /* If we're a completely isolated CPU, we don't play: */
  10653. if (on_null_domain(rq))
  10654. return;
  10655. rq->nohz_tick_stopped = 1;
  10656. cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
  10657. atomic_inc(&nohz.nr_cpus);
  10658. /*
  10659. * Ensures that if nohz_idle_balance() fails to observe our
  10660. * @idle_cpus_mask store, it must observe the @has_blocked
  10661. * and @needs_update stores.
  10662. */
  10663. smp_mb__after_atomic();
  10664. set_cpu_sd_state_idle(cpu);
  10665. WRITE_ONCE(nohz.needs_update, 1);
  10666. out:
  10667. /*
  10668. * Each time a cpu enter idle, we assume that it has blocked load and
  10669. * enable the periodic update of the load of idle CPUs
  10670. */
  10671. WRITE_ONCE(nohz.has_blocked, 1);
  10672. }
  10673. static bool update_nohz_stats(struct rq *rq)
  10674. {
  10675. unsigned int cpu = rq->cpu;
  10676. if (!rq->has_blocked_load)
  10677. return false;
  10678. if (!cpumask_test_cpu(cpu, nohz.idle_cpus_mask))
  10679. return false;
  10680. if (!time_after(jiffies, READ_ONCE(rq->last_blocked_load_update_tick)))
  10681. return true;
  10682. sched_balance_update_blocked_averages(cpu);
  10683. return rq->has_blocked_load;
  10684. }
  10685. /*
  10686. * Internal function that runs load balance for all idle CPUs. The load balance
  10687. * can be a simple update of blocked load or a complete load balance with
  10688. * tasks movement depending of flags.
  10689. */
  10690. static void _nohz_idle_balance(struct rq *this_rq, unsigned int flags)
  10691. {
  10692. /* Earliest time when we have to do rebalance again */
  10693. unsigned long now = jiffies;
  10694. unsigned long next_balance = now + 60*HZ;
  10695. bool has_blocked_load = false;
  10696. int update_next_balance = 0;
  10697. int this_cpu = this_rq->cpu;
  10698. int balance_cpu;
  10699. struct rq *rq;
  10700. SCHED_WARN_ON((flags & NOHZ_KICK_MASK) == NOHZ_BALANCE_KICK);
  10701. /*
  10702. * We assume there will be no idle load after this update and clear
  10703. * the has_blocked flag. If a cpu enters idle in the mean time, it will
  10704. * set the has_blocked flag and trigger another update of idle load.
  10705. * Because a cpu that becomes idle, is added to idle_cpus_mask before
  10706. * setting the flag, we are sure to not clear the state and not
  10707. * check the load of an idle cpu.
  10708. *
  10709. * Same applies to idle_cpus_mask vs needs_update.
  10710. */
  10711. if (flags & NOHZ_STATS_KICK)
  10712. WRITE_ONCE(nohz.has_blocked, 0);
  10713. if (flags & NOHZ_NEXT_KICK)
  10714. WRITE_ONCE(nohz.needs_update, 0);
  10715. /*
  10716. * Ensures that if we miss the CPU, we must see the has_blocked
  10717. * store from nohz_balance_enter_idle().
  10718. */
  10719. smp_mb();
  10720. /*
  10721. * Start with the next CPU after this_cpu so we will end with this_cpu and let a
  10722. * chance for other idle cpu to pull load.
  10723. */
  10724. for_each_cpu_wrap(balance_cpu, nohz.idle_cpus_mask, this_cpu+1) {
  10725. if (!idle_cpu(balance_cpu))
  10726. continue;
  10727. /*
  10728. * If this CPU gets work to do, stop the load balancing
  10729. * work being done for other CPUs. Next load
  10730. * balancing owner will pick it up.
  10731. */
  10732. if (!idle_cpu(this_cpu) && need_resched()) {
  10733. if (flags & NOHZ_STATS_KICK)
  10734. has_blocked_load = true;
  10735. if (flags & NOHZ_NEXT_KICK)
  10736. WRITE_ONCE(nohz.needs_update, 1);
  10737. goto abort;
  10738. }
  10739. rq = cpu_rq(balance_cpu);
  10740. if (flags & NOHZ_STATS_KICK)
  10741. has_blocked_load |= update_nohz_stats(rq);
  10742. /*
  10743. * If time for next balance is due,
  10744. * do the balance.
  10745. */
  10746. if (time_after_eq(jiffies, rq->next_balance)) {
  10747. struct rq_flags rf;
  10748. rq_lock_irqsave(rq, &rf);
  10749. update_rq_clock(rq);
  10750. rq_unlock_irqrestore(rq, &rf);
  10751. if (flags & NOHZ_BALANCE_KICK)
  10752. sched_balance_domains(rq, CPU_IDLE);
  10753. }
  10754. if (time_after(next_balance, rq->next_balance)) {
  10755. next_balance = rq->next_balance;
  10756. update_next_balance = 1;
  10757. }
  10758. }
  10759. /*
  10760. * next_balance will be updated only when there is a need.
  10761. * When the CPU is attached to null domain for ex, it will not be
  10762. * updated.
  10763. */
  10764. if (likely(update_next_balance))
  10765. nohz.next_balance = next_balance;
  10766. if (flags & NOHZ_STATS_KICK)
  10767. WRITE_ONCE(nohz.next_blocked,
  10768. now + msecs_to_jiffies(LOAD_AVG_PERIOD));
  10769. abort:
  10770. /* There is still blocked load, enable periodic update */
  10771. if (has_blocked_load)
  10772. WRITE_ONCE(nohz.has_blocked, 1);
  10773. }
  10774. /*
  10775. * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the
  10776. * rebalancing for all the CPUs for whom scheduler ticks are stopped.
  10777. */
  10778. static bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
  10779. {
  10780. unsigned int flags = this_rq->nohz_idle_balance;
  10781. if (!flags)
  10782. return false;
  10783. this_rq->nohz_idle_balance = 0;
  10784. if (idle != CPU_IDLE)
  10785. return false;
  10786. _nohz_idle_balance(this_rq, flags);
  10787. return true;
  10788. }
  10789. /*
  10790. * Check if we need to directly run the ILB for updating blocked load before
  10791. * entering idle state. Here we run ILB directly without issuing IPIs.
  10792. *
  10793. * Note that when this function is called, the tick may not yet be stopped on
  10794. * this CPU yet. nohz.idle_cpus_mask is updated only when tick is stopped and
  10795. * cleared on the next busy tick. In other words, nohz.idle_cpus_mask updates
  10796. * don't align with CPUs enter/exit idle to avoid bottlenecks due to high idle
  10797. * entry/exit rate (usec). So it is possible that _nohz_idle_balance() is
  10798. * called from this function on (this) CPU that's not yet in the mask. That's
  10799. * OK because the goal of nohz_run_idle_balance() is to run ILB only for
  10800. * updating the blocked load of already idle CPUs without waking up one of
  10801. * those idle CPUs and outside the preempt disable / IRQ off phase of the local
  10802. * cpu about to enter idle, because it can take a long time.
  10803. */
  10804. void nohz_run_idle_balance(int cpu)
  10805. {
  10806. unsigned int flags;
  10807. flags = atomic_fetch_andnot(NOHZ_NEWILB_KICK, nohz_flags(cpu));
  10808. /*
  10809. * Update the blocked load only if no SCHED_SOFTIRQ is about to happen
  10810. * (i.e. NOHZ_STATS_KICK set) and will do the same.
  10811. */
  10812. if ((flags == NOHZ_NEWILB_KICK) && !need_resched())
  10813. _nohz_idle_balance(cpu_rq(cpu), NOHZ_STATS_KICK);
  10814. }
  10815. static void nohz_newidle_balance(struct rq *this_rq)
  10816. {
  10817. int this_cpu = this_rq->cpu;
  10818. /*
  10819. * This CPU doesn't want to be disturbed by scheduler
  10820. * housekeeping
  10821. */
  10822. if (!housekeeping_cpu(this_cpu, HK_TYPE_SCHED))
  10823. return;
  10824. /* Will wake up very soon. No time for doing anything else*/
  10825. if (this_rq->avg_idle < sysctl_sched_migration_cost)
  10826. return;
  10827. /* Don't need to update blocked load of idle CPUs*/
  10828. if (!READ_ONCE(nohz.has_blocked) ||
  10829. time_before(jiffies, READ_ONCE(nohz.next_blocked)))
  10830. return;
  10831. /*
  10832. * Set the need to trigger ILB in order to update blocked load
  10833. * before entering idle state.
  10834. */
  10835. atomic_or(NOHZ_NEWILB_KICK, nohz_flags(this_cpu));
  10836. }
  10837. #else /* !CONFIG_NO_HZ_COMMON */
  10838. static inline void nohz_balancer_kick(struct rq *rq) { }
  10839. static inline bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
  10840. {
  10841. return false;
  10842. }
  10843. static inline void nohz_newidle_balance(struct rq *this_rq) { }
  10844. #endif /* CONFIG_NO_HZ_COMMON */
  10845. /*
  10846. * sched_balance_newidle is called by schedule() if this_cpu is about to become
  10847. * idle. Attempts to pull tasks from other CPUs.
  10848. *
  10849. * Returns:
  10850. * < 0 - we released the lock and there are !fair tasks present
  10851. * 0 - failed, no new tasks
  10852. * > 0 - success, new (fair) tasks present
  10853. */
  10854. static int sched_balance_newidle(struct rq *this_rq, struct rq_flags *rf)
  10855. {
  10856. unsigned long next_balance = jiffies + HZ;
  10857. int this_cpu = this_rq->cpu;
  10858. int continue_balancing = 1;
  10859. u64 t0, t1, curr_cost = 0;
  10860. struct sched_domain *sd;
  10861. int pulled_task = 0;
  10862. update_misfit_status(NULL, this_rq);
  10863. /*
  10864. * There is a task waiting to run. No need to search for one.
  10865. * Return 0; the task will be enqueued when switching to idle.
  10866. */
  10867. if (this_rq->ttwu_pending)
  10868. return 0;
  10869. /*
  10870. * We must set idle_stamp _before_ calling sched_balance_rq()
  10871. * for CPU_NEWLY_IDLE, such that we measure the this duration
  10872. * as idle time.
  10873. */
  10874. this_rq->idle_stamp = rq_clock(this_rq);
  10875. /*
  10876. * Do not pull tasks towards !active CPUs...
  10877. */
  10878. if (!cpu_active(this_cpu))
  10879. return 0;
  10880. /*
  10881. * This is OK, because current is on_cpu, which avoids it being picked
  10882. * for load-balance and preemption/IRQs are still disabled avoiding
  10883. * further scheduler activity on it and we're being very careful to
  10884. * re-start the picking loop.
  10885. */
  10886. rq_unpin_lock(this_rq, rf);
  10887. rcu_read_lock();
  10888. sd = rcu_dereference_check_sched_domain(this_rq->sd);
  10889. if (!get_rd_overloaded(this_rq->rd) ||
  10890. (sd && this_rq->avg_idle < sd->max_newidle_lb_cost)) {
  10891. if (sd)
  10892. update_next_balance(sd, &next_balance);
  10893. rcu_read_unlock();
  10894. goto out;
  10895. }
  10896. rcu_read_unlock();
  10897. raw_spin_rq_unlock(this_rq);
  10898. t0 = sched_clock_cpu(this_cpu);
  10899. sched_balance_update_blocked_averages(this_cpu);
  10900. rcu_read_lock();
  10901. for_each_domain(this_cpu, sd) {
  10902. u64 domain_cost;
  10903. update_next_balance(sd, &next_balance);
  10904. if (this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost)
  10905. break;
  10906. if (sd->flags & SD_BALANCE_NEWIDLE) {
  10907. pulled_task = sched_balance_rq(this_cpu, this_rq,
  10908. sd, CPU_NEWLY_IDLE,
  10909. &continue_balancing);
  10910. t1 = sched_clock_cpu(this_cpu);
  10911. domain_cost = t1 - t0;
  10912. curr_cost += domain_cost;
  10913. t0 = t1;
  10914. /*
  10915. * Failing newidle means it is not effective;
  10916. * bump the cost so we end up doing less of it.
  10917. */
  10918. if (!pulled_task)
  10919. domain_cost = (3 * sd->max_newidle_lb_cost) / 2;
  10920. update_newidle_cost(sd, domain_cost);
  10921. }
  10922. /*
  10923. * Stop searching for tasks to pull if there are
  10924. * now runnable tasks on this rq.
  10925. */
  10926. if (pulled_task || !continue_balancing)
  10927. break;
  10928. }
  10929. rcu_read_unlock();
  10930. raw_spin_rq_lock(this_rq);
  10931. if (curr_cost > this_rq->max_idle_balance_cost)
  10932. this_rq->max_idle_balance_cost = curr_cost;
  10933. /*
  10934. * While browsing the domains, we released the rq lock, a task could
  10935. * have been enqueued in the meantime. Since we're not going idle,
  10936. * pretend we pulled a task.
  10937. */
  10938. if (this_rq->cfs.h_nr_queued && !pulled_task)
  10939. pulled_task = 1;
  10940. /* Is there a task of a high priority class? */
  10941. if (this_rq->nr_running != this_rq->cfs.h_nr_queued)
  10942. pulled_task = -1;
  10943. out:
  10944. /* Move the next balance forward */
  10945. if (time_after(this_rq->next_balance, next_balance))
  10946. this_rq->next_balance = next_balance;
  10947. if (pulled_task)
  10948. this_rq->idle_stamp = 0;
  10949. else
  10950. nohz_newidle_balance(this_rq);
  10951. rq_repin_lock(this_rq, rf);
  10952. return pulled_task;
  10953. }
  10954. /*
  10955. * This softirq handler is triggered via SCHED_SOFTIRQ from two places:
  10956. *
  10957. * - directly from the local scheduler_tick() for periodic load balancing
  10958. *
  10959. * - indirectly from a remote scheduler_tick() for NOHZ idle balancing
  10960. * through the SMP cross-call nohz_csd_func()
  10961. */
  10962. static __latent_entropy void sched_balance_softirq(void)
  10963. {
  10964. struct rq *this_rq = this_rq();
  10965. enum cpu_idle_type idle = this_rq->idle_balance;
  10966. /*
  10967. * If this CPU has a pending NOHZ_BALANCE_KICK, then do the
  10968. * balancing on behalf of the other idle CPUs whose ticks are
  10969. * stopped. Do nohz_idle_balance *before* sched_balance_domains to
  10970. * give the idle CPUs a chance to load balance. Else we may
  10971. * load balance only within the local sched_domain hierarchy
  10972. * and abort nohz_idle_balance altogether if we pull some load.
  10973. */
  10974. if (nohz_idle_balance(this_rq, idle))
  10975. return;
  10976. /* normal load balance */
  10977. sched_balance_update_blocked_averages(this_rq->cpu);
  10978. sched_balance_domains(this_rq, idle);
  10979. }
  10980. /*
  10981. * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
  10982. */
  10983. void sched_balance_trigger(struct rq *rq)
  10984. {
  10985. /*
  10986. * Don't need to rebalance while attached to NULL domain or
  10987. * runqueue CPU is not active
  10988. */
  10989. if (unlikely(on_null_domain(rq) || !cpu_active(cpu_of(rq))))
  10990. return;
  10991. if (time_after_eq(jiffies, rq->next_balance))
  10992. raise_softirq(SCHED_SOFTIRQ);
  10993. nohz_balancer_kick(rq);
  10994. }
  10995. static void rq_online_fair(struct rq *rq)
  10996. {
  10997. update_sysctl();
  10998. update_runtime_enabled(rq);
  10999. }
  11000. static void rq_offline_fair(struct rq *rq)
  11001. {
  11002. update_sysctl();
  11003. /* Ensure any throttled groups are reachable by pick_next_task */
  11004. unthrottle_offline_cfs_rqs(rq);
  11005. /* Ensure that we remove rq contribution to group share: */
  11006. clear_tg_offline_cfs_rqs(rq);
  11007. }
  11008. #endif /* CONFIG_SMP */
  11009. #ifdef CONFIG_SCHED_CORE
  11010. static inline bool
  11011. __entity_slice_used(struct sched_entity *se, int min_nr_tasks)
  11012. {
  11013. u64 rtime = se->sum_exec_runtime - se->prev_sum_exec_runtime;
  11014. u64 slice = se->slice;
  11015. return (rtime * min_nr_tasks > slice);
  11016. }
  11017. #define MIN_NR_TASKS_DURING_FORCEIDLE 2
  11018. static inline void task_tick_core(struct rq *rq, struct task_struct *curr)
  11019. {
  11020. if (!sched_core_enabled(rq))
  11021. return;
  11022. /*
  11023. * If runqueue has only one task which used up its slice and
  11024. * if the sibling is forced idle, then trigger schedule to
  11025. * give forced idle task a chance.
  11026. *
  11027. * sched_slice() considers only this active rq and it gets the
  11028. * whole slice. But during force idle, we have siblings acting
  11029. * like a single runqueue and hence we need to consider runnable
  11030. * tasks on this CPU and the forced idle CPU. Ideally, we should
  11031. * go through the forced idle rq, but that would be a perf hit.
  11032. * We can assume that the forced idle CPU has at least
  11033. * MIN_NR_TASKS_DURING_FORCEIDLE - 1 tasks and use that to check
  11034. * if we need to give up the CPU.
  11035. */
  11036. if (rq->core->core_forceidle_count && rq->cfs.nr_running == 1 &&
  11037. __entity_slice_used(&curr->se, MIN_NR_TASKS_DURING_FORCEIDLE))
  11038. resched_curr(rq);
  11039. }
  11040. /*
  11041. * se_fi_update - Update the cfs_rq->min_vruntime_fi in a CFS hierarchy if needed.
  11042. */
  11043. static void se_fi_update(const struct sched_entity *se, unsigned int fi_seq,
  11044. bool forceidle)
  11045. {
  11046. for_each_sched_entity(se) {
  11047. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  11048. if (forceidle) {
  11049. if (cfs_rq->forceidle_seq == fi_seq)
  11050. break;
  11051. cfs_rq->forceidle_seq = fi_seq;
  11052. }
  11053. cfs_rq->min_vruntime_fi = cfs_rq->min_vruntime;
  11054. }
  11055. }
  11056. void task_vruntime_update(struct rq *rq, struct task_struct *p, bool in_fi)
  11057. {
  11058. struct sched_entity *se = &p->se;
  11059. if (p->sched_class != &fair_sched_class)
  11060. return;
  11061. se_fi_update(se, rq->core->core_forceidle_seq, in_fi);
  11062. }
  11063. bool cfs_prio_less(const struct task_struct *a, const struct task_struct *b,
  11064. bool in_fi)
  11065. {
  11066. struct rq *rq = task_rq(a);
  11067. const struct sched_entity *sea = &a->se;
  11068. const struct sched_entity *seb = &b->se;
  11069. struct cfs_rq *cfs_rqa;
  11070. struct cfs_rq *cfs_rqb;
  11071. s64 delta;
  11072. SCHED_WARN_ON(task_rq(b)->core != rq->core);
  11073. #ifdef CONFIG_FAIR_GROUP_SCHED
  11074. /*
  11075. * Find an se in the hierarchy for tasks a and b, such that the se's
  11076. * are immediate siblings.
  11077. */
  11078. while (sea->cfs_rq->tg != seb->cfs_rq->tg) {
  11079. int sea_depth = sea->depth;
  11080. int seb_depth = seb->depth;
  11081. if (sea_depth >= seb_depth)
  11082. sea = parent_entity(sea);
  11083. if (sea_depth <= seb_depth)
  11084. seb = parent_entity(seb);
  11085. }
  11086. se_fi_update(sea, rq->core->core_forceidle_seq, in_fi);
  11087. se_fi_update(seb, rq->core->core_forceidle_seq, in_fi);
  11088. cfs_rqa = sea->cfs_rq;
  11089. cfs_rqb = seb->cfs_rq;
  11090. #else
  11091. cfs_rqa = &task_rq(a)->cfs;
  11092. cfs_rqb = &task_rq(b)->cfs;
  11093. #endif
  11094. /*
  11095. * Find delta after normalizing se's vruntime with its cfs_rq's
  11096. * min_vruntime_fi, which would have been updated in prior calls
  11097. * to se_fi_update().
  11098. */
  11099. delta = (s64)(sea->vruntime - seb->vruntime) +
  11100. (s64)(cfs_rqb->min_vruntime_fi - cfs_rqa->min_vruntime_fi);
  11101. return delta > 0;
  11102. }
  11103. static int task_is_throttled_fair(struct task_struct *p, int cpu)
  11104. {
  11105. struct cfs_rq *cfs_rq;
  11106. #ifdef CONFIG_FAIR_GROUP_SCHED
  11107. cfs_rq = task_group(p)->cfs_rq[cpu];
  11108. #else
  11109. cfs_rq = &cpu_rq(cpu)->cfs;
  11110. #endif
  11111. return throttled_hierarchy(cfs_rq);
  11112. }
  11113. #else
  11114. static inline void task_tick_core(struct rq *rq, struct task_struct *curr) {}
  11115. #endif
  11116. /*
  11117. * scheduler tick hitting a task of our scheduling class.
  11118. *
  11119. * NOTE: This function can be called remotely by the tick offload that
  11120. * goes along full dynticks. Therefore no local assumption can be made
  11121. * and everything must be accessed through the @rq and @curr passed in
  11122. * parameters.
  11123. */
  11124. static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)
  11125. {
  11126. struct cfs_rq *cfs_rq;
  11127. struct sched_entity *se = &curr->se;
  11128. for_each_sched_entity(se) {
  11129. cfs_rq = cfs_rq_of(se);
  11130. entity_tick(cfs_rq, se, queued);
  11131. }
  11132. if (static_branch_unlikely(&sched_numa_balancing))
  11133. task_tick_numa(rq, curr);
  11134. update_misfit_status(curr, rq);
  11135. check_update_overutilized_status(task_rq(curr));
  11136. task_tick_core(rq, curr);
  11137. }
  11138. /*
  11139. * called on fork with the child task as argument from the parent's context
  11140. * - child not yet on the tasklist
  11141. * - preemption disabled
  11142. */
  11143. static void task_fork_fair(struct task_struct *p)
  11144. {
  11145. set_task_max_allowed_capacity(p);
  11146. }
  11147. /*
  11148. * Priority of the task has changed. Check to see if we preempt
  11149. * the current task.
  11150. */
  11151. static void
  11152. prio_changed_fair(struct rq *rq, struct task_struct *p, int oldprio)
  11153. {
  11154. if (!task_on_rq_queued(p))
  11155. return;
  11156. if (rq->cfs.nr_running == 1)
  11157. return;
  11158. /*
  11159. * Reschedule if we are currently running on this runqueue and
  11160. * our priority decreased, or if we are not currently running on
  11161. * this runqueue and our priority is higher than the current's
  11162. */
  11163. if (task_current(rq, p)) {
  11164. if (p->prio > oldprio)
  11165. resched_curr(rq);
  11166. } else
  11167. wakeup_preempt(rq, p, 0);
  11168. }
  11169. #ifdef CONFIG_FAIR_GROUP_SCHED
  11170. /*
  11171. * Propagate the changes of the sched_entity across the tg tree to make it
  11172. * visible to the root
  11173. */
  11174. static void propagate_entity_cfs_rq(struct sched_entity *se)
  11175. {
  11176. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  11177. if (cfs_rq_throttled(cfs_rq))
  11178. return;
  11179. if (!throttled_hierarchy(cfs_rq))
  11180. list_add_leaf_cfs_rq(cfs_rq);
  11181. /* Start to propagate at parent */
  11182. se = se->parent;
  11183. for_each_sched_entity(se) {
  11184. cfs_rq = cfs_rq_of(se);
  11185. update_load_avg(cfs_rq, se, UPDATE_TG);
  11186. if (cfs_rq_throttled(cfs_rq))
  11187. break;
  11188. if (!throttled_hierarchy(cfs_rq))
  11189. list_add_leaf_cfs_rq(cfs_rq);
  11190. }
  11191. }
  11192. #else
  11193. static void propagate_entity_cfs_rq(struct sched_entity *se) { }
  11194. #endif
  11195. static void detach_entity_cfs_rq(struct sched_entity *se)
  11196. {
  11197. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  11198. #ifdef CONFIG_SMP
  11199. /*
  11200. * In case the task sched_avg hasn't been attached:
  11201. * - A forked task which hasn't been woken up by wake_up_new_task().
  11202. * - A task which has been woken up by try_to_wake_up() but is
  11203. * waiting for actually being woken up by sched_ttwu_pending().
  11204. */
  11205. if (!se->avg.last_update_time)
  11206. return;
  11207. #endif
  11208. /* Catch up with the cfs_rq and remove our load when we leave */
  11209. update_load_avg(cfs_rq, se, 0);
  11210. detach_entity_load_avg(cfs_rq, se);
  11211. update_tg_load_avg(cfs_rq);
  11212. propagate_entity_cfs_rq(se);
  11213. }
  11214. static void attach_entity_cfs_rq(struct sched_entity *se)
  11215. {
  11216. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  11217. /* Synchronize entity with its cfs_rq */
  11218. update_load_avg(cfs_rq, se, sched_feat(ATTACH_AGE_LOAD) ? 0 : SKIP_AGE_LOAD);
  11219. attach_entity_load_avg(cfs_rq, se);
  11220. update_tg_load_avg(cfs_rq);
  11221. propagate_entity_cfs_rq(se);
  11222. }
  11223. static void detach_task_cfs_rq(struct task_struct *p)
  11224. {
  11225. struct sched_entity *se = &p->se;
  11226. detach_entity_cfs_rq(se);
  11227. }
  11228. static void attach_task_cfs_rq(struct task_struct *p)
  11229. {
  11230. struct sched_entity *se = &p->se;
  11231. attach_entity_cfs_rq(se);
  11232. }
  11233. static void switched_from_fair(struct rq *rq, struct task_struct *p)
  11234. {
  11235. detach_task_cfs_rq(p);
  11236. }
  11237. static void switched_to_fair(struct rq *rq, struct task_struct *p)
  11238. {
  11239. SCHED_WARN_ON(p->se.sched_delayed);
  11240. attach_task_cfs_rq(p);
  11241. set_task_max_allowed_capacity(p);
  11242. if (task_on_rq_queued(p)) {
  11243. /*
  11244. * We were most likely switched from sched_rt, so
  11245. * kick off the schedule if running, otherwise just see
  11246. * if we can still preempt the current task.
  11247. */
  11248. if (task_current(rq, p))
  11249. resched_curr(rq);
  11250. else
  11251. wakeup_preempt(rq, p, 0);
  11252. }
  11253. }
  11254. static void __set_next_task_fair(struct rq *rq, struct task_struct *p, bool first)
  11255. {
  11256. struct sched_entity *se = &p->se;
  11257. #ifdef CONFIG_SMP
  11258. if (task_on_rq_queued(p)) {
  11259. /*
  11260. * Move the next running task to the front of the list, so our
  11261. * cfs_tasks list becomes MRU one.
  11262. */
  11263. list_move(&se->group_node, &rq->cfs_tasks);
  11264. }
  11265. #endif
  11266. if (!first)
  11267. return;
  11268. SCHED_WARN_ON(se->sched_delayed);
  11269. if (hrtick_enabled_fair(rq))
  11270. hrtick_start_fair(rq, p);
  11271. update_misfit_status(p, rq);
  11272. sched_fair_update_stop_tick(rq, p);
  11273. }
  11274. /*
  11275. * Account for a task changing its policy or group.
  11276. *
  11277. * This routine is mostly called to set cfs_rq->curr field when a task
  11278. * migrates between groups/classes.
  11279. */
  11280. static void set_next_task_fair(struct rq *rq, struct task_struct *p, bool first)
  11281. {
  11282. struct sched_entity *se = &p->se;
  11283. for_each_sched_entity(se) {
  11284. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  11285. set_next_entity(cfs_rq, se);
  11286. /* ensure bandwidth has been allocated on our new cfs_rq */
  11287. account_cfs_rq_runtime(cfs_rq, 0);
  11288. }
  11289. __set_next_task_fair(rq, p, first);
  11290. }
  11291. void init_cfs_rq(struct cfs_rq *cfs_rq)
  11292. {
  11293. cfs_rq->tasks_timeline = RB_ROOT_CACHED;
  11294. cfs_rq->min_vruntime = (u64)(-(1LL << 20));
  11295. #ifdef CONFIG_SMP
  11296. raw_spin_lock_init(&cfs_rq->removed.lock);
  11297. #endif
  11298. }
  11299. #ifdef CONFIG_FAIR_GROUP_SCHED
  11300. static void task_change_group_fair(struct task_struct *p)
  11301. {
  11302. /*
  11303. * We couldn't detach or attach a forked task which
  11304. * hasn't been woken up by wake_up_new_task().
  11305. */
  11306. if (READ_ONCE(p->__state) == TASK_NEW)
  11307. return;
  11308. detach_task_cfs_rq(p);
  11309. #ifdef CONFIG_SMP
  11310. /* Tell se's cfs_rq has been changed -- migrated */
  11311. p->se.avg.last_update_time = 0;
  11312. #endif
  11313. set_task_rq(p, task_cpu(p));
  11314. attach_task_cfs_rq(p);
  11315. }
  11316. void free_fair_sched_group(struct task_group *tg)
  11317. {
  11318. int i;
  11319. for_each_possible_cpu(i) {
  11320. if (tg->cfs_rq)
  11321. kfree(tg->cfs_rq[i]);
  11322. if (tg->se)
  11323. kfree(tg->se[i]);
  11324. }
  11325. kfree(tg->cfs_rq);
  11326. kfree(tg->se);
  11327. }
  11328. int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
  11329. {
  11330. struct sched_entity *se;
  11331. struct cfs_rq *cfs_rq;
  11332. int i;
  11333. tg->cfs_rq = kcalloc(nr_cpu_ids, sizeof(cfs_rq), GFP_KERNEL);
  11334. if (!tg->cfs_rq)
  11335. goto err;
  11336. tg->se = kcalloc(nr_cpu_ids, sizeof(se), GFP_KERNEL);
  11337. if (!tg->se)
  11338. goto err;
  11339. tg->shares = NICE_0_LOAD;
  11340. init_cfs_bandwidth(tg_cfs_bandwidth(tg), tg_cfs_bandwidth(parent));
  11341. for_each_possible_cpu(i) {
  11342. cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
  11343. GFP_KERNEL, cpu_to_node(i));
  11344. if (!cfs_rq)
  11345. goto err;
  11346. se = kzalloc_node(sizeof(struct sched_entity_stats),
  11347. GFP_KERNEL, cpu_to_node(i));
  11348. if (!se)
  11349. goto err_free_rq;
  11350. init_cfs_rq(cfs_rq);
  11351. init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
  11352. init_entity_runnable_average(se);
  11353. }
  11354. return 1;
  11355. err_free_rq:
  11356. kfree(cfs_rq);
  11357. err:
  11358. return 0;
  11359. }
  11360. void online_fair_sched_group(struct task_group *tg)
  11361. {
  11362. struct sched_entity *se;
  11363. struct rq_flags rf;
  11364. struct rq *rq;
  11365. int i;
  11366. for_each_possible_cpu(i) {
  11367. rq = cpu_rq(i);
  11368. se = tg->se[i];
  11369. rq_lock_irq(rq, &rf);
  11370. update_rq_clock(rq);
  11371. attach_entity_cfs_rq(se);
  11372. sync_throttle(tg, i);
  11373. rq_unlock_irq(rq, &rf);
  11374. }
  11375. }
  11376. void unregister_fair_sched_group(struct task_group *tg)
  11377. {
  11378. int cpu;
  11379. destroy_cfs_bandwidth(tg_cfs_bandwidth(tg));
  11380. for_each_possible_cpu(cpu) {
  11381. struct cfs_rq *cfs_rq = tg->cfs_rq[cpu];
  11382. struct sched_entity *se = tg->se[cpu];
  11383. struct rq *rq = cpu_rq(cpu);
  11384. if (se) {
  11385. if (se->sched_delayed) {
  11386. guard(rq_lock_irqsave)(rq);
  11387. if (se->sched_delayed) {
  11388. update_rq_clock(rq);
  11389. dequeue_entities(rq, se, DEQUEUE_SLEEP | DEQUEUE_DELAYED);
  11390. }
  11391. list_del_leaf_cfs_rq(cfs_rq);
  11392. }
  11393. remove_entity_load_avg(se);
  11394. }
  11395. /*
  11396. * Only empty task groups can be destroyed; so we can speculatively
  11397. * check on_list without danger of it being re-added.
  11398. */
  11399. if (cfs_rq->on_list) {
  11400. guard(rq_lock_irqsave)(rq);
  11401. list_del_leaf_cfs_rq(cfs_rq);
  11402. }
  11403. }
  11404. }
  11405. void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
  11406. struct sched_entity *se, int cpu,
  11407. struct sched_entity *parent)
  11408. {
  11409. struct rq *rq = cpu_rq(cpu);
  11410. cfs_rq->tg = tg;
  11411. cfs_rq->rq = rq;
  11412. init_cfs_rq_runtime(cfs_rq);
  11413. tg->cfs_rq[cpu] = cfs_rq;
  11414. tg->se[cpu] = se;
  11415. /* se could be NULL for root_task_group */
  11416. if (!se)
  11417. return;
  11418. if (!parent) {
  11419. se->cfs_rq = &rq->cfs;
  11420. se->depth = 0;
  11421. } else {
  11422. se->cfs_rq = parent->my_q;
  11423. se->depth = parent->depth + 1;
  11424. }
  11425. se->my_q = cfs_rq;
  11426. /* guarantee group entities always have weight */
  11427. update_load_set(&se->load, NICE_0_LOAD);
  11428. se->parent = parent;
  11429. }
  11430. static DEFINE_MUTEX(shares_mutex);
  11431. static int __sched_group_set_shares(struct task_group *tg, unsigned long shares)
  11432. {
  11433. int i;
  11434. lockdep_assert_held(&shares_mutex);
  11435. /*
  11436. * We can't change the weight of the root cgroup.
  11437. */
  11438. if (!tg->se[0])
  11439. return -EINVAL;
  11440. shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
  11441. if (tg->shares == shares)
  11442. return 0;
  11443. tg->shares = shares;
  11444. for_each_possible_cpu(i) {
  11445. struct rq *rq = cpu_rq(i);
  11446. struct sched_entity *se = tg->se[i];
  11447. struct rq_flags rf;
  11448. /* Propagate contribution to hierarchy */
  11449. rq_lock_irqsave(rq, &rf);
  11450. update_rq_clock(rq);
  11451. for_each_sched_entity(se) {
  11452. update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
  11453. update_cfs_group(se);
  11454. }
  11455. rq_unlock_irqrestore(rq, &rf);
  11456. }
  11457. return 0;
  11458. }
  11459. int sched_group_set_shares(struct task_group *tg, unsigned long shares)
  11460. {
  11461. int ret;
  11462. mutex_lock(&shares_mutex);
  11463. if (tg_is_idle(tg))
  11464. ret = -EINVAL;
  11465. else
  11466. ret = __sched_group_set_shares(tg, shares);
  11467. mutex_unlock(&shares_mutex);
  11468. return ret;
  11469. }
  11470. int sched_group_set_idle(struct task_group *tg, long idle)
  11471. {
  11472. int i;
  11473. if (tg == &root_task_group)
  11474. return -EINVAL;
  11475. if (idle < 0 || idle > 1)
  11476. return -EINVAL;
  11477. mutex_lock(&shares_mutex);
  11478. if (tg->idle == idle) {
  11479. mutex_unlock(&shares_mutex);
  11480. return 0;
  11481. }
  11482. tg->idle = idle;
  11483. for_each_possible_cpu(i) {
  11484. struct rq *rq = cpu_rq(i);
  11485. struct sched_entity *se = tg->se[i];
  11486. struct cfs_rq *parent_cfs_rq, *grp_cfs_rq = tg->cfs_rq[i];
  11487. bool was_idle = cfs_rq_is_idle(grp_cfs_rq);
  11488. long idle_task_delta;
  11489. struct rq_flags rf;
  11490. rq_lock_irqsave(rq, &rf);
  11491. grp_cfs_rq->idle = idle;
  11492. if (WARN_ON_ONCE(was_idle == cfs_rq_is_idle(grp_cfs_rq)))
  11493. goto next_cpu;
  11494. if (se->on_rq) {
  11495. parent_cfs_rq = cfs_rq_of(se);
  11496. if (cfs_rq_is_idle(grp_cfs_rq))
  11497. parent_cfs_rq->idle_nr_running++;
  11498. else
  11499. parent_cfs_rq->idle_nr_running--;
  11500. }
  11501. idle_task_delta = grp_cfs_rq->h_nr_queued -
  11502. grp_cfs_rq->idle_h_nr_running;
  11503. if (!cfs_rq_is_idle(grp_cfs_rq))
  11504. idle_task_delta *= -1;
  11505. for_each_sched_entity(se) {
  11506. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  11507. if (!se->on_rq)
  11508. break;
  11509. cfs_rq->idle_h_nr_running += idle_task_delta;
  11510. /* Already accounted at parent level and above. */
  11511. if (cfs_rq_is_idle(cfs_rq))
  11512. break;
  11513. }
  11514. next_cpu:
  11515. rq_unlock_irqrestore(rq, &rf);
  11516. }
  11517. /* Idle groups have minimum weight. */
  11518. if (tg_is_idle(tg))
  11519. __sched_group_set_shares(tg, scale_load(WEIGHT_IDLEPRIO));
  11520. else
  11521. __sched_group_set_shares(tg, NICE_0_LOAD);
  11522. mutex_unlock(&shares_mutex);
  11523. return 0;
  11524. }
  11525. #endif /* CONFIG_FAIR_GROUP_SCHED */
  11526. static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task)
  11527. {
  11528. struct sched_entity *se = &task->se;
  11529. unsigned int rr_interval = 0;
  11530. /*
  11531. * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
  11532. * idle runqueue:
  11533. */
  11534. if (rq->cfs.load.weight)
  11535. rr_interval = NS_TO_JIFFIES(se->slice);
  11536. return rr_interval;
  11537. }
  11538. /*
  11539. * All the scheduling class methods:
  11540. */
  11541. DEFINE_SCHED_CLASS(fair) = {
  11542. .enqueue_task = enqueue_task_fair,
  11543. .dequeue_task = dequeue_task_fair,
  11544. .yield_task = yield_task_fair,
  11545. .yield_to_task = yield_to_task_fair,
  11546. .wakeup_preempt = check_preempt_wakeup_fair,
  11547. .pick_task = pick_task_fair,
  11548. .pick_next_task = __pick_next_task_fair,
  11549. .put_prev_task = put_prev_task_fair,
  11550. .set_next_task = set_next_task_fair,
  11551. #ifdef CONFIG_SMP
  11552. .balance = balance_fair,
  11553. .select_task_rq = select_task_rq_fair,
  11554. .migrate_task_rq = migrate_task_rq_fair,
  11555. .rq_online = rq_online_fair,
  11556. .rq_offline = rq_offline_fair,
  11557. .task_dead = task_dead_fair,
  11558. .set_cpus_allowed = set_cpus_allowed_fair,
  11559. #endif
  11560. .task_tick = task_tick_fair,
  11561. .task_fork = task_fork_fair,
  11562. .reweight_task = reweight_task_fair,
  11563. .prio_changed = prio_changed_fair,
  11564. .switched_from = switched_from_fair,
  11565. .switched_to = switched_to_fair,
  11566. .get_rr_interval = get_rr_interval_fair,
  11567. .update_curr = update_curr_fair,
  11568. #ifdef CONFIG_FAIR_GROUP_SCHED
  11569. .task_change_group = task_change_group_fair,
  11570. #endif
  11571. #ifdef CONFIG_SCHED_CORE
  11572. .task_is_throttled = task_is_throttled_fair,
  11573. #endif
  11574. #ifdef CONFIG_UCLAMP_TASK
  11575. .uclamp_enabled = 1,
  11576. #endif
  11577. };
  11578. #ifdef CONFIG_SCHED_DEBUG
  11579. void print_cfs_stats(struct seq_file *m, int cpu)
  11580. {
  11581. struct cfs_rq *cfs_rq, *pos;
  11582. rcu_read_lock();
  11583. for_each_leaf_cfs_rq_safe(cpu_rq(cpu), cfs_rq, pos)
  11584. print_cfs_rq(m, cpu, cfs_rq);
  11585. rcu_read_unlock();
  11586. }
  11587. #ifdef CONFIG_NUMA_BALANCING
  11588. void show_numa_stats(struct task_struct *p, struct seq_file *m)
  11589. {
  11590. int node;
  11591. unsigned long tsf = 0, tpf = 0, gsf = 0, gpf = 0;
  11592. struct numa_group *ng;
  11593. rcu_read_lock();
  11594. ng = rcu_dereference(p->numa_group);
  11595. for_each_online_node(node) {
  11596. if (p->numa_faults) {
  11597. tsf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 0)];
  11598. tpf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 1)];
  11599. }
  11600. if (ng) {
  11601. gsf = ng->faults[task_faults_idx(NUMA_MEM, node, 0)],
  11602. gpf = ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
  11603. }
  11604. print_numa_stats(m, node, tsf, tpf, gsf, gpf);
  11605. }
  11606. rcu_read_unlock();
  11607. }
  11608. #endif /* CONFIG_NUMA_BALANCING */
  11609. #endif /* CONFIG_SCHED_DEBUG */
  11610. __init void init_sched_fair_class(void)
  11611. {
  11612. #ifdef CONFIG_SMP
  11613. int i;
  11614. for_each_possible_cpu(i) {
  11615. zalloc_cpumask_var_node(&per_cpu(load_balance_mask, i), GFP_KERNEL, cpu_to_node(i));
  11616. zalloc_cpumask_var_node(&per_cpu(select_rq_mask, i), GFP_KERNEL, cpu_to_node(i));
  11617. zalloc_cpumask_var_node(&per_cpu(should_we_balance_tmpmask, i),
  11618. GFP_KERNEL, cpu_to_node(i));
  11619. #ifdef CONFIG_CFS_BANDWIDTH
  11620. INIT_CSD(&cpu_rq(i)->cfsb_csd, __cfsb_csd_unthrottle, cpu_rq(i));
  11621. INIT_LIST_HEAD(&cpu_rq(i)->cfsb_csd_list);
  11622. #endif
  11623. }
  11624. open_softirq(SCHED_SOFTIRQ, sched_balance_softirq);
  11625. #ifdef CONFIG_NO_HZ_COMMON
  11626. nohz.next_balance = jiffies;
  11627. nohz.next_blocked = jiffies;
  11628. zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);
  11629. #endif
  11630. #endif /* SMP */
  11631. }