fair.c 265 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104
  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 "sched.h"
  24. #include <trace/events/sched.h>
  25. /*
  26. * Targeted preemption latency for CPU-bound tasks:
  27. *
  28. * NOTE: this latency value is not the same as the concept of
  29. * 'timeslice length' - timeslices in CFS are of variable length
  30. * and have no persistent notion like in traditional, time-slice
  31. * based scheduling concepts.
  32. *
  33. * (to see the precise effective timeslice length of your workload,
  34. * run vmstat and monitor the context-switches (cs) field)
  35. *
  36. * (default: 6ms * (1 + ilog(ncpus)), units: nanoseconds)
  37. */
  38. unsigned int sysctl_sched_latency = 6000000ULL;
  39. unsigned int normalized_sysctl_sched_latency = 6000000ULL;
  40. /*
  41. * The initial- and re-scaling of tunables is configurable
  42. *
  43. * Options are:
  44. *
  45. * SCHED_TUNABLESCALING_NONE - unscaled, always *1
  46. * SCHED_TUNABLESCALING_LOG - scaled logarithmical, *1+ilog(ncpus)
  47. * SCHED_TUNABLESCALING_LINEAR - scaled linear, *ncpus
  48. *
  49. * (default SCHED_TUNABLESCALING_LOG = *(1+ilog(ncpus))
  50. */
  51. enum sched_tunable_scaling sysctl_sched_tunable_scaling = SCHED_TUNABLESCALING_LOG;
  52. /*
  53. * Minimal preemption granularity for CPU-bound tasks:
  54. *
  55. * (default: 0.75 msec * (1 + ilog(ncpus)), units: nanoseconds)
  56. */
  57. unsigned int sysctl_sched_min_granularity = 750000ULL;
  58. unsigned int normalized_sysctl_sched_min_granularity = 750000ULL;
  59. /*
  60. * This value is kept at sysctl_sched_latency/sysctl_sched_min_granularity
  61. */
  62. static unsigned int sched_nr_latency = 8;
  63. /*
  64. * After fork, child runs first. If set to 0 (default) then
  65. * parent will (try to) run first.
  66. */
  67. unsigned int sysctl_sched_child_runs_first __read_mostly;
  68. /*
  69. * SCHED_OTHER wake-up granularity.
  70. *
  71. * This option delays the preemption effects of decoupled workloads
  72. * and reduces their over-scheduling. Synchronous workloads will still
  73. * have immediate wakeup/sleep latencies.
  74. *
  75. * (default: 1 msec * (1 + ilog(ncpus)), units: nanoseconds)
  76. */
  77. unsigned int sysctl_sched_wakeup_granularity = 1000000UL;
  78. unsigned int normalized_sysctl_sched_wakeup_granularity = 1000000UL;
  79. const_debug unsigned int sysctl_sched_migration_cost = 500000UL;
  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. #endif
  89. #ifdef CONFIG_CFS_BANDWIDTH
  90. /*
  91. * Amount of runtime to allocate from global (tg) to local (per-cfs_rq) pool
  92. * each time a cfs_rq requests quota.
  93. *
  94. * Note: in the case that the slice exceeds the runtime remaining (either due
  95. * to consumption or the quota being specified to be smaller than the slice)
  96. * we will always only issue the remaining available time.
  97. *
  98. * (default: 5 msec, units: microseconds)
  99. */
  100. unsigned int sysctl_sched_cfs_bandwidth_slice = 5000UL;
  101. #endif
  102. /*
  103. * The margin used when comparing utilization with CPU capacity:
  104. * util * margin < capacity * 1024
  105. *
  106. * (default: ~20%)
  107. */
  108. unsigned int capacity_margin = 1280;
  109. static inline void update_load_add(struct load_weight *lw, unsigned long inc)
  110. {
  111. lw->weight += inc;
  112. lw->inv_weight = 0;
  113. }
  114. static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
  115. {
  116. lw->weight -= dec;
  117. lw->inv_weight = 0;
  118. }
  119. static inline void update_load_set(struct load_weight *lw, unsigned long w)
  120. {
  121. lw->weight = w;
  122. lw->inv_weight = 0;
  123. }
  124. /*
  125. * Increase the granularity value when there are more CPUs,
  126. * because with more CPUs the 'effective latency' as visible
  127. * to users decreases. But the relationship is not linear,
  128. * so pick a second-best guess by going with the log2 of the
  129. * number of CPUs.
  130. *
  131. * This idea comes from the SD scheduler of Con Kolivas:
  132. */
  133. static unsigned int get_update_sysctl_factor(void)
  134. {
  135. unsigned int cpus = min_t(unsigned int, num_online_cpus(), 8);
  136. unsigned int factor;
  137. switch (sysctl_sched_tunable_scaling) {
  138. case SCHED_TUNABLESCALING_NONE:
  139. factor = 1;
  140. break;
  141. case SCHED_TUNABLESCALING_LINEAR:
  142. factor = cpus;
  143. break;
  144. case SCHED_TUNABLESCALING_LOG:
  145. default:
  146. factor = 1 + ilog2(cpus);
  147. break;
  148. }
  149. return factor;
  150. }
  151. static void update_sysctl(void)
  152. {
  153. unsigned int factor = get_update_sysctl_factor();
  154. #define SET_SYSCTL(name) \
  155. (sysctl_##name = (factor) * normalized_sysctl_##name)
  156. SET_SYSCTL(sched_min_granularity);
  157. SET_SYSCTL(sched_latency);
  158. SET_SYSCTL(sched_wakeup_granularity);
  159. #undef SET_SYSCTL
  160. }
  161. void sched_init_granularity(void)
  162. {
  163. update_sysctl();
  164. }
  165. #define WMULT_CONST (~0U)
  166. #define WMULT_SHIFT 32
  167. static void __update_inv_weight(struct load_weight *lw)
  168. {
  169. unsigned long w;
  170. if (likely(lw->inv_weight))
  171. return;
  172. w = scale_load_down(lw->weight);
  173. if (BITS_PER_LONG > 32 && unlikely(w >= WMULT_CONST))
  174. lw->inv_weight = 1;
  175. else if (unlikely(!w))
  176. lw->inv_weight = WMULT_CONST;
  177. else
  178. lw->inv_weight = WMULT_CONST / w;
  179. }
  180. /*
  181. * delta_exec * weight / lw.weight
  182. * OR
  183. * (delta_exec * (weight * lw->inv_weight)) >> WMULT_SHIFT
  184. *
  185. * Either weight := NICE_0_LOAD and lw \e sched_prio_to_wmult[], in which case
  186. * we're guaranteed shift stays positive because inv_weight is guaranteed to
  187. * fit 32 bits, and NICE_0_LOAD gives another 10 bits; therefore shift >= 22.
  188. *
  189. * Or, weight =< lw.weight (because lw.weight is the runqueue weight), thus
  190. * weight/lw.weight <= 1, and therefore our shift will also be positive.
  191. */
  192. static u64 __calc_delta(u64 delta_exec, unsigned long weight, struct load_weight *lw)
  193. {
  194. u64 fact = scale_load_down(weight);
  195. int shift = WMULT_SHIFT;
  196. __update_inv_weight(lw);
  197. if (unlikely(fact >> 32)) {
  198. while (fact >> 32) {
  199. fact >>= 1;
  200. shift--;
  201. }
  202. }
  203. /* hint to use a 32x32->64 mul */
  204. fact = (u64)(u32)fact * lw->inv_weight;
  205. while (fact >> 32) {
  206. fact >>= 1;
  207. shift--;
  208. }
  209. return mul_u64_u32_shr(delta_exec, fact, shift);
  210. }
  211. const struct sched_class fair_sched_class;
  212. /**************************************************************
  213. * CFS operations on generic schedulable entities:
  214. */
  215. #ifdef CONFIG_FAIR_GROUP_SCHED
  216. /* cpu runqueue to which this cfs_rq is attached */
  217. static inline struct rq *rq_of(struct cfs_rq *cfs_rq)
  218. {
  219. return cfs_rq->rq;
  220. }
  221. static inline struct task_struct *task_of(struct sched_entity *se)
  222. {
  223. SCHED_WARN_ON(!entity_is_task(se));
  224. return container_of(se, struct task_struct, se);
  225. }
  226. /* Walk up scheduling entities hierarchy */
  227. #define for_each_sched_entity(se) \
  228. for (; se; se = se->parent)
  229. static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
  230. {
  231. return p->se.cfs_rq;
  232. }
  233. /* runqueue on which this entity is (to be) queued */
  234. static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se)
  235. {
  236. return se->cfs_rq;
  237. }
  238. /* runqueue "owned" by this group */
  239. static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
  240. {
  241. return grp->my_q;
  242. }
  243. static inline void list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
  244. {
  245. if (!cfs_rq->on_list) {
  246. struct rq *rq = rq_of(cfs_rq);
  247. int cpu = cpu_of(rq);
  248. /*
  249. * Ensure we either appear before our parent (if already
  250. * enqueued) or force our parent to appear after us when it is
  251. * enqueued. The fact that we always enqueue bottom-up
  252. * reduces this to two cases and a special case for the root
  253. * cfs_rq. Furthermore, it also means that we will always reset
  254. * tmp_alone_branch either when the branch is connected
  255. * to a tree or when we reach the beg of the tree
  256. */
  257. if (cfs_rq->tg->parent &&
  258. cfs_rq->tg->parent->cfs_rq[cpu]->on_list) {
  259. /*
  260. * If parent is already on the list, we add the child
  261. * just before. Thanks to circular linked property of
  262. * the list, this means to put the child at the tail
  263. * of the list that starts by parent.
  264. */
  265. list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
  266. &(cfs_rq->tg->parent->cfs_rq[cpu]->leaf_cfs_rq_list));
  267. /*
  268. * The branch is now connected to its tree so we can
  269. * reset tmp_alone_branch to the beginning of the
  270. * list.
  271. */
  272. rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
  273. } else if (!cfs_rq->tg->parent) {
  274. /*
  275. * cfs rq without parent should be put
  276. * at the tail of the list.
  277. */
  278. list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
  279. &rq->leaf_cfs_rq_list);
  280. /*
  281. * We have reach the beg of a tree so we can reset
  282. * tmp_alone_branch to the beginning of the list.
  283. */
  284. rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
  285. } else {
  286. /*
  287. * The parent has not already been added so we want to
  288. * make sure that it will be put after us.
  289. * tmp_alone_branch points to the beg of the branch
  290. * where we will add parent.
  291. */
  292. list_add_rcu(&cfs_rq->leaf_cfs_rq_list,
  293. rq->tmp_alone_branch);
  294. /*
  295. * update tmp_alone_branch to points to the new beg
  296. * of the branch
  297. */
  298. rq->tmp_alone_branch = &cfs_rq->leaf_cfs_rq_list;
  299. }
  300. cfs_rq->on_list = 1;
  301. }
  302. }
  303. static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
  304. {
  305. if (cfs_rq->on_list) {
  306. list_del_rcu(&cfs_rq->leaf_cfs_rq_list);
  307. cfs_rq->on_list = 0;
  308. }
  309. }
  310. /* Iterate thr' all leaf cfs_rq's on a runqueue */
  311. #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) \
  312. list_for_each_entry_safe(cfs_rq, pos, &rq->leaf_cfs_rq_list, \
  313. leaf_cfs_rq_list)
  314. /* Do the two (enqueued) entities belong to the same group ? */
  315. static inline struct cfs_rq *
  316. is_same_group(struct sched_entity *se, struct sched_entity *pse)
  317. {
  318. if (se->cfs_rq == pse->cfs_rq)
  319. return se->cfs_rq;
  320. return NULL;
  321. }
  322. static inline struct sched_entity *parent_entity(struct sched_entity *se)
  323. {
  324. return se->parent;
  325. }
  326. static void
  327. find_matching_se(struct sched_entity **se, struct sched_entity **pse)
  328. {
  329. int se_depth, pse_depth;
  330. /*
  331. * preemption test can be made between sibling entities who are in the
  332. * same cfs_rq i.e who have a common parent. Walk up the hierarchy of
  333. * both tasks until we find their ancestors who are siblings of common
  334. * parent.
  335. */
  336. /* First walk up until both entities are at same depth */
  337. se_depth = (*se)->depth;
  338. pse_depth = (*pse)->depth;
  339. while (se_depth > pse_depth) {
  340. se_depth--;
  341. *se = parent_entity(*se);
  342. }
  343. while (pse_depth > se_depth) {
  344. pse_depth--;
  345. *pse = parent_entity(*pse);
  346. }
  347. while (!is_same_group(*se, *pse)) {
  348. *se = parent_entity(*se);
  349. *pse = parent_entity(*pse);
  350. }
  351. }
  352. #else /* !CONFIG_FAIR_GROUP_SCHED */
  353. static inline struct task_struct *task_of(struct sched_entity *se)
  354. {
  355. return container_of(se, struct task_struct, se);
  356. }
  357. static inline struct rq *rq_of(struct cfs_rq *cfs_rq)
  358. {
  359. return container_of(cfs_rq, struct rq, cfs);
  360. }
  361. #define for_each_sched_entity(se) \
  362. for (; se; se = NULL)
  363. static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
  364. {
  365. return &task_rq(p)->cfs;
  366. }
  367. static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se)
  368. {
  369. struct task_struct *p = task_of(se);
  370. struct rq *rq = task_rq(p);
  371. return &rq->cfs;
  372. }
  373. /* runqueue "owned" by this group */
  374. static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
  375. {
  376. return NULL;
  377. }
  378. static inline void list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
  379. {
  380. }
  381. static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
  382. {
  383. }
  384. #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) \
  385. for (cfs_rq = &rq->cfs, pos = NULL; cfs_rq; cfs_rq = pos)
  386. static inline struct sched_entity *parent_entity(struct sched_entity *se)
  387. {
  388. return NULL;
  389. }
  390. static inline void
  391. find_matching_se(struct sched_entity **se, struct sched_entity **pse)
  392. {
  393. }
  394. #endif /* CONFIG_FAIR_GROUP_SCHED */
  395. static __always_inline
  396. void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec);
  397. /**************************************************************
  398. * Scheduling class tree data structure manipulation methods:
  399. */
  400. static inline u64 max_vruntime(u64 max_vruntime, u64 vruntime)
  401. {
  402. s64 delta = (s64)(vruntime - max_vruntime);
  403. if (delta > 0)
  404. max_vruntime = vruntime;
  405. return max_vruntime;
  406. }
  407. static inline u64 min_vruntime(u64 min_vruntime, u64 vruntime)
  408. {
  409. s64 delta = (s64)(vruntime - min_vruntime);
  410. if (delta < 0)
  411. min_vruntime = vruntime;
  412. return min_vruntime;
  413. }
  414. static inline int entity_before(struct sched_entity *a,
  415. struct sched_entity *b)
  416. {
  417. return (s64)(a->vruntime - b->vruntime) < 0;
  418. }
  419. static void update_min_vruntime(struct cfs_rq *cfs_rq)
  420. {
  421. struct sched_entity *curr = cfs_rq->curr;
  422. struct rb_node *leftmost = rb_first_cached(&cfs_rq->tasks_timeline);
  423. u64 vruntime = cfs_rq->min_vruntime;
  424. if (curr) {
  425. if (curr->on_rq)
  426. vruntime = curr->vruntime;
  427. else
  428. curr = NULL;
  429. }
  430. if (leftmost) { /* non-empty tree */
  431. struct sched_entity *se;
  432. se = rb_entry(leftmost, struct sched_entity, run_node);
  433. if (!curr)
  434. vruntime = se->vruntime;
  435. else
  436. vruntime = min_vruntime(vruntime, se->vruntime);
  437. }
  438. /* ensure we never gain time by being placed backwards. */
  439. cfs_rq->min_vruntime = max_vruntime(cfs_rq->min_vruntime, vruntime);
  440. #ifndef CONFIG_64BIT
  441. smp_wmb();
  442. cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
  443. #endif
  444. }
  445. /*
  446. * Enqueue an entity into the rb-tree:
  447. */
  448. static void __enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
  449. {
  450. struct rb_node **link = &cfs_rq->tasks_timeline.rb_root.rb_node;
  451. struct rb_node *parent = NULL;
  452. struct sched_entity *entry;
  453. bool leftmost = true;
  454. /*
  455. * Find the right place in the rbtree:
  456. */
  457. while (*link) {
  458. parent = *link;
  459. entry = rb_entry(parent, struct sched_entity, run_node);
  460. /*
  461. * We dont care about collisions. Nodes with
  462. * the same key stay together.
  463. */
  464. if (entity_before(se, entry)) {
  465. link = &parent->rb_left;
  466. } else {
  467. link = &parent->rb_right;
  468. leftmost = false;
  469. }
  470. }
  471. rb_link_node(&se->run_node, parent, link);
  472. rb_insert_color_cached(&se->run_node,
  473. &cfs_rq->tasks_timeline, leftmost);
  474. }
  475. static void __dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
  476. {
  477. rb_erase_cached(&se->run_node, &cfs_rq->tasks_timeline);
  478. }
  479. struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq)
  480. {
  481. struct rb_node *left = rb_first_cached(&cfs_rq->tasks_timeline);
  482. if (!left)
  483. return NULL;
  484. return rb_entry(left, struct sched_entity, run_node);
  485. }
  486. static struct sched_entity *__pick_next_entity(struct sched_entity *se)
  487. {
  488. struct rb_node *next = rb_next(&se->run_node);
  489. if (!next)
  490. return NULL;
  491. return rb_entry(next, struct sched_entity, run_node);
  492. }
  493. #ifdef CONFIG_SCHED_DEBUG
  494. struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq)
  495. {
  496. struct rb_node *last = rb_last(&cfs_rq->tasks_timeline.rb_root);
  497. if (!last)
  498. return NULL;
  499. return rb_entry(last, struct sched_entity, run_node);
  500. }
  501. /**************************************************************
  502. * Scheduling class statistics methods:
  503. */
  504. int sched_proc_update_handler(struct ctl_table *table, int write,
  505. void __user *buffer, size_t *lenp,
  506. loff_t *ppos)
  507. {
  508. int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
  509. unsigned int factor = get_update_sysctl_factor();
  510. if (ret || !write)
  511. return ret;
  512. sched_nr_latency = DIV_ROUND_UP(sysctl_sched_latency,
  513. sysctl_sched_min_granularity);
  514. #define WRT_SYSCTL(name) \
  515. (normalized_sysctl_##name = sysctl_##name / (factor))
  516. WRT_SYSCTL(sched_min_granularity);
  517. WRT_SYSCTL(sched_latency);
  518. WRT_SYSCTL(sched_wakeup_granularity);
  519. #undef WRT_SYSCTL
  520. return 0;
  521. }
  522. #endif
  523. /*
  524. * delta /= w
  525. */
  526. static inline u64 calc_delta_fair(u64 delta, struct sched_entity *se)
  527. {
  528. if (unlikely(se->load.weight != NICE_0_LOAD))
  529. delta = __calc_delta(delta, NICE_0_LOAD, &se->load);
  530. return delta;
  531. }
  532. /*
  533. * The idea is to set a period in which each task runs once.
  534. *
  535. * When there are too many tasks (sched_nr_latency) we have to stretch
  536. * this period because otherwise the slices get too small.
  537. *
  538. * p = (nr <= nl) ? l : l*nr/nl
  539. */
  540. static u64 __sched_period(unsigned long nr_running)
  541. {
  542. if (unlikely(nr_running > sched_nr_latency))
  543. return nr_running * sysctl_sched_min_granularity;
  544. else
  545. return sysctl_sched_latency;
  546. }
  547. /*
  548. * We calculate the wall-time slice from the period by taking a part
  549. * proportional to the weight.
  550. *
  551. * s = p*P[w/rw]
  552. */
  553. static u64 sched_slice(struct cfs_rq *cfs_rq, struct sched_entity *se)
  554. {
  555. u64 slice = __sched_period(cfs_rq->nr_running + !se->on_rq);
  556. for_each_sched_entity(se) {
  557. struct load_weight *load;
  558. struct load_weight lw;
  559. cfs_rq = cfs_rq_of(se);
  560. load = &cfs_rq->load;
  561. if (unlikely(!se->on_rq)) {
  562. lw = cfs_rq->load;
  563. update_load_add(&lw, se->load.weight);
  564. load = &lw;
  565. }
  566. slice = __calc_delta(slice, se->load.weight, load);
  567. }
  568. return slice;
  569. }
  570. /*
  571. * We calculate the vruntime slice of a to-be-inserted task.
  572. *
  573. * vs = s/w
  574. */
  575. static u64 sched_vslice(struct cfs_rq *cfs_rq, struct sched_entity *se)
  576. {
  577. return calc_delta_fair(sched_slice(cfs_rq, se), se);
  578. }
  579. #ifdef CONFIG_SMP
  580. #include "pelt.h"
  581. #include "sched-pelt.h"
  582. static int select_idle_sibling(struct task_struct *p, int prev_cpu, int cpu);
  583. static unsigned long task_h_load(struct task_struct *p);
  584. /* Give new sched_entity start runnable values to heavy its load in infant time */
  585. void init_entity_runnable_average(struct sched_entity *se)
  586. {
  587. struct sched_avg *sa = &se->avg;
  588. memset(sa, 0, sizeof(*sa));
  589. /*
  590. * Tasks are intialized with full load to be seen as heavy tasks until
  591. * they get a chance to stabilize to their real load level.
  592. * Group entities are intialized with zero load to reflect the fact that
  593. * nothing has been attached to the task group yet.
  594. */
  595. if (entity_is_task(se))
  596. sa->runnable_load_avg = sa->load_avg = scale_load_down(se->load.weight);
  597. se->runnable_weight = se->load.weight;
  598. /* when this task enqueue'ed, it will contribute to its cfs_rq's load_avg */
  599. }
  600. static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq);
  601. static void attach_entity_cfs_rq(struct sched_entity *se);
  602. /*
  603. * With new tasks being created, their initial util_avgs are extrapolated
  604. * based on the cfs_rq's current util_avg:
  605. *
  606. * util_avg = cfs_rq->util_avg / (cfs_rq->load_avg + 1) * se.load.weight
  607. *
  608. * However, in many cases, the above util_avg does not give a desired
  609. * value. Moreover, the sum of the util_avgs may be divergent, such
  610. * as when the series is a harmonic series.
  611. *
  612. * To solve this problem, we also cap the util_avg of successive tasks to
  613. * only 1/2 of the left utilization budget:
  614. *
  615. * util_avg_cap = (cpu_scale - cfs_rq->avg.util_avg) / 2^n
  616. *
  617. * where n denotes the nth task and cpu_scale the CPU capacity.
  618. *
  619. * For example, for a CPU with 1024 of capacity, a simplest series from
  620. * the beginning would be like:
  621. *
  622. * task util_avg: 512, 256, 128, 64, 32, 16, 8, ...
  623. * cfs_rq util_avg: 512, 768, 896, 960, 992, 1008, 1016, ...
  624. *
  625. * Finally, that extrapolated util_avg is clamped to the cap (util_avg_cap)
  626. * if util_avg > util_avg_cap.
  627. */
  628. void post_init_entity_util_avg(struct sched_entity *se)
  629. {
  630. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  631. struct sched_avg *sa = &se->avg;
  632. long cpu_scale = arch_scale_cpu_capacity(NULL, cpu_of(rq_of(cfs_rq)));
  633. long cap = (long)(cpu_scale - cfs_rq->avg.util_avg) / 2;
  634. if (cap > 0) {
  635. if (cfs_rq->avg.util_avg != 0) {
  636. sa->util_avg = cfs_rq->avg.util_avg * se->load.weight;
  637. sa->util_avg /= (cfs_rq->avg.load_avg + 1);
  638. if (sa->util_avg > cap)
  639. sa->util_avg = cap;
  640. } else {
  641. sa->util_avg = cap;
  642. }
  643. }
  644. if (entity_is_task(se)) {
  645. struct task_struct *p = task_of(se);
  646. if (p->sched_class != &fair_sched_class) {
  647. /*
  648. * For !fair tasks do:
  649. *
  650. update_cfs_rq_load_avg(now, cfs_rq);
  651. attach_entity_load_avg(cfs_rq, se, 0);
  652. switched_from_fair(rq, p);
  653. *
  654. * such that the next switched_to_fair() has the
  655. * expected state.
  656. */
  657. se->avg.last_update_time = cfs_rq_clock_task(cfs_rq);
  658. return;
  659. }
  660. }
  661. attach_entity_cfs_rq(se);
  662. }
  663. #else /* !CONFIG_SMP */
  664. void init_entity_runnable_average(struct sched_entity *se)
  665. {
  666. }
  667. void post_init_entity_util_avg(struct sched_entity *se)
  668. {
  669. }
  670. static void update_tg_load_avg(struct cfs_rq *cfs_rq, int force)
  671. {
  672. }
  673. #endif /* CONFIG_SMP */
  674. /*
  675. * Update the current task's runtime statistics.
  676. */
  677. static void update_curr(struct cfs_rq *cfs_rq)
  678. {
  679. struct sched_entity *curr = cfs_rq->curr;
  680. u64 now = rq_clock_task(rq_of(cfs_rq));
  681. u64 delta_exec;
  682. if (unlikely(!curr))
  683. return;
  684. delta_exec = now - curr->exec_start;
  685. if (unlikely((s64)delta_exec <= 0))
  686. return;
  687. curr->exec_start = now;
  688. schedstat_set(curr->statistics.exec_max,
  689. max(delta_exec, curr->statistics.exec_max));
  690. curr->sum_exec_runtime += delta_exec;
  691. schedstat_add(cfs_rq->exec_clock, delta_exec);
  692. curr->vruntime += calc_delta_fair(delta_exec, curr);
  693. update_min_vruntime(cfs_rq);
  694. if (entity_is_task(curr)) {
  695. struct task_struct *curtask = task_of(curr);
  696. trace_sched_stat_runtime(curtask, delta_exec, curr->vruntime);
  697. cgroup_account_cputime(curtask, delta_exec);
  698. account_group_exec_runtime(curtask, delta_exec);
  699. }
  700. account_cfs_rq_runtime(cfs_rq, delta_exec);
  701. }
  702. static void update_curr_fair(struct rq *rq)
  703. {
  704. update_curr(cfs_rq_of(&rq->curr->se));
  705. }
  706. static inline void
  707. update_stats_wait_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
  708. {
  709. u64 wait_start, prev_wait_start;
  710. if (!schedstat_enabled())
  711. return;
  712. wait_start = rq_clock(rq_of(cfs_rq));
  713. prev_wait_start = schedstat_val(se->statistics.wait_start);
  714. if (entity_is_task(se) && task_on_rq_migrating(task_of(se)) &&
  715. likely(wait_start > prev_wait_start))
  716. wait_start -= prev_wait_start;
  717. __schedstat_set(se->statistics.wait_start, wait_start);
  718. }
  719. static inline void
  720. update_stats_wait_end(struct cfs_rq *cfs_rq, struct sched_entity *se)
  721. {
  722. struct task_struct *p;
  723. u64 delta;
  724. if (!schedstat_enabled())
  725. return;
  726. delta = rq_clock(rq_of(cfs_rq)) - schedstat_val(se->statistics.wait_start);
  727. if (entity_is_task(se)) {
  728. p = task_of(se);
  729. if (task_on_rq_migrating(p)) {
  730. /*
  731. * Preserve migrating task's wait time so wait_start
  732. * time stamp can be adjusted to accumulate wait time
  733. * prior to migration.
  734. */
  735. __schedstat_set(se->statistics.wait_start, delta);
  736. return;
  737. }
  738. trace_sched_stat_wait(p, delta);
  739. }
  740. __schedstat_set(se->statistics.wait_max,
  741. max(schedstat_val(se->statistics.wait_max), delta));
  742. __schedstat_inc(se->statistics.wait_count);
  743. __schedstat_add(se->statistics.wait_sum, delta);
  744. __schedstat_set(se->statistics.wait_start, 0);
  745. }
  746. static inline void
  747. update_stats_enqueue_sleeper(struct cfs_rq *cfs_rq, struct sched_entity *se)
  748. {
  749. struct task_struct *tsk = NULL;
  750. u64 sleep_start, block_start;
  751. if (!schedstat_enabled())
  752. return;
  753. sleep_start = schedstat_val(se->statistics.sleep_start);
  754. block_start = schedstat_val(se->statistics.block_start);
  755. if (entity_is_task(se))
  756. tsk = task_of(se);
  757. if (sleep_start) {
  758. u64 delta = rq_clock(rq_of(cfs_rq)) - sleep_start;
  759. if ((s64)delta < 0)
  760. delta = 0;
  761. if (unlikely(delta > schedstat_val(se->statistics.sleep_max)))
  762. __schedstat_set(se->statistics.sleep_max, delta);
  763. __schedstat_set(se->statistics.sleep_start, 0);
  764. __schedstat_add(se->statistics.sum_sleep_runtime, delta);
  765. if (tsk) {
  766. account_scheduler_latency(tsk, delta >> 10, 1);
  767. trace_sched_stat_sleep(tsk, delta);
  768. }
  769. }
  770. if (block_start) {
  771. u64 delta = rq_clock(rq_of(cfs_rq)) - block_start;
  772. if ((s64)delta < 0)
  773. delta = 0;
  774. if (unlikely(delta > schedstat_val(se->statistics.block_max)))
  775. __schedstat_set(se->statistics.block_max, delta);
  776. __schedstat_set(se->statistics.block_start, 0);
  777. __schedstat_add(se->statistics.sum_sleep_runtime, delta);
  778. if (tsk) {
  779. if (tsk->in_iowait) {
  780. __schedstat_add(se->statistics.iowait_sum, delta);
  781. __schedstat_inc(se->statistics.iowait_count);
  782. trace_sched_stat_iowait(tsk, delta);
  783. }
  784. trace_sched_stat_blocked(tsk, delta);
  785. /*
  786. * Blocking time is in units of nanosecs, so shift by
  787. * 20 to get a milliseconds-range estimation of the
  788. * amount of time that the task spent sleeping:
  789. */
  790. if (unlikely(prof_on == SLEEP_PROFILING)) {
  791. profile_hits(SLEEP_PROFILING,
  792. (void *)get_wchan(tsk),
  793. delta >> 20);
  794. }
  795. account_scheduler_latency(tsk, delta >> 10, 0);
  796. }
  797. }
  798. }
  799. /*
  800. * Task is being enqueued - update stats:
  801. */
  802. static inline void
  803. update_stats_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
  804. {
  805. if (!schedstat_enabled())
  806. return;
  807. /*
  808. * Are we enqueueing a waiting task? (for current tasks
  809. * a dequeue/enqueue event is a NOP)
  810. */
  811. if (se != cfs_rq->curr)
  812. update_stats_wait_start(cfs_rq, se);
  813. if (flags & ENQUEUE_WAKEUP)
  814. update_stats_enqueue_sleeper(cfs_rq, se);
  815. }
  816. static inline void
  817. update_stats_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
  818. {
  819. if (!schedstat_enabled())
  820. return;
  821. /*
  822. * Mark the end of the wait period if dequeueing a
  823. * waiting task:
  824. */
  825. if (se != cfs_rq->curr)
  826. update_stats_wait_end(cfs_rq, se);
  827. if ((flags & DEQUEUE_SLEEP) && entity_is_task(se)) {
  828. struct task_struct *tsk = task_of(se);
  829. if (tsk->state & TASK_INTERRUPTIBLE)
  830. __schedstat_set(se->statistics.sleep_start,
  831. rq_clock(rq_of(cfs_rq)));
  832. if (tsk->state & TASK_UNINTERRUPTIBLE)
  833. __schedstat_set(se->statistics.block_start,
  834. rq_clock(rq_of(cfs_rq)));
  835. }
  836. }
  837. /*
  838. * We are picking a new current task - update its stats:
  839. */
  840. static inline void
  841. update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
  842. {
  843. /*
  844. * We are starting a new run period:
  845. */
  846. se->exec_start = rq_clock_task(rq_of(cfs_rq));
  847. }
  848. /**************************************************
  849. * Scheduling class queueing methods:
  850. */
  851. #ifdef CONFIG_NUMA_BALANCING
  852. /*
  853. * Approximate time to scan a full NUMA task in ms. The task scan period is
  854. * calculated based on the tasks virtual memory size and
  855. * numa_balancing_scan_size.
  856. */
  857. unsigned int sysctl_numa_balancing_scan_period_min = 1000;
  858. unsigned int sysctl_numa_balancing_scan_period_max = 60000;
  859. /* Portion of address space to scan in MB */
  860. unsigned int sysctl_numa_balancing_scan_size = 256;
  861. /* Scan @scan_size MB every @scan_period after an initial @scan_delay in ms */
  862. unsigned int sysctl_numa_balancing_scan_delay = 1000;
  863. struct numa_group {
  864. atomic_t refcount;
  865. spinlock_t lock; /* nr_tasks, tasks */
  866. int nr_tasks;
  867. pid_t gid;
  868. int active_nodes;
  869. struct rcu_head rcu;
  870. unsigned long total_faults;
  871. unsigned long max_faults_cpu;
  872. /*
  873. * Faults_cpu is used to decide whether memory should move
  874. * towards the CPU. As a consequence, these stats are weighted
  875. * more by CPU use than by memory faults.
  876. */
  877. unsigned long *faults_cpu;
  878. unsigned long faults[0];
  879. };
  880. static inline unsigned long group_faults_priv(struct numa_group *ng);
  881. static inline unsigned long group_faults_shared(struct numa_group *ng);
  882. static unsigned int task_nr_scan_windows(struct task_struct *p)
  883. {
  884. unsigned long rss = 0;
  885. unsigned long nr_scan_pages;
  886. /*
  887. * Calculations based on RSS as non-present and empty pages are skipped
  888. * by the PTE scanner and NUMA hinting faults should be trapped based
  889. * on resident pages
  890. */
  891. nr_scan_pages = sysctl_numa_balancing_scan_size << (20 - PAGE_SHIFT);
  892. rss = get_mm_rss(p->mm);
  893. if (!rss)
  894. rss = nr_scan_pages;
  895. rss = round_up(rss, nr_scan_pages);
  896. return rss / nr_scan_pages;
  897. }
  898. /* For sanitys sake, never scan more PTEs than MAX_SCAN_WINDOW MB/sec. */
  899. #define MAX_SCAN_WINDOW 2560
  900. static unsigned int task_scan_min(struct task_struct *p)
  901. {
  902. unsigned int scan_size = READ_ONCE(sysctl_numa_balancing_scan_size);
  903. unsigned int scan, floor;
  904. unsigned int windows = 1;
  905. if (scan_size < MAX_SCAN_WINDOW)
  906. windows = MAX_SCAN_WINDOW / scan_size;
  907. floor = 1000 / windows;
  908. scan = sysctl_numa_balancing_scan_period_min / task_nr_scan_windows(p);
  909. return max_t(unsigned int, floor, scan);
  910. }
  911. static unsigned int task_scan_start(struct task_struct *p)
  912. {
  913. unsigned long smin = task_scan_min(p);
  914. unsigned long period = smin;
  915. /* Scale the maximum scan period with the amount of shared memory. */
  916. if (p->numa_group) {
  917. struct numa_group *ng = p->numa_group;
  918. unsigned long shared = group_faults_shared(ng);
  919. unsigned long private = group_faults_priv(ng);
  920. period *= atomic_read(&ng->refcount);
  921. period *= shared + 1;
  922. period /= private + shared + 1;
  923. }
  924. return max(smin, period);
  925. }
  926. static unsigned int task_scan_max(struct task_struct *p)
  927. {
  928. unsigned long smin = task_scan_min(p);
  929. unsigned long smax;
  930. /* Watch for min being lower than max due to floor calculations */
  931. smax = sysctl_numa_balancing_scan_period_max / task_nr_scan_windows(p);
  932. /* Scale the maximum scan period with the amount of shared memory. */
  933. if (p->numa_group) {
  934. struct numa_group *ng = p->numa_group;
  935. unsigned long shared = group_faults_shared(ng);
  936. unsigned long private = group_faults_priv(ng);
  937. unsigned long period = smax;
  938. period *= atomic_read(&ng->refcount);
  939. period *= shared + 1;
  940. period /= private + shared + 1;
  941. smax = max(smax, period);
  942. }
  943. return max(smin, smax);
  944. }
  945. void init_numa_balancing(unsigned long clone_flags, struct task_struct *p)
  946. {
  947. int mm_users = 0;
  948. struct mm_struct *mm = p->mm;
  949. if (mm) {
  950. mm_users = atomic_read(&mm->mm_users);
  951. if (mm_users == 1) {
  952. mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
  953. mm->numa_scan_seq = 0;
  954. }
  955. }
  956. p->node_stamp = 0;
  957. p->numa_scan_seq = mm ? mm->numa_scan_seq : 0;
  958. p->numa_scan_period = sysctl_numa_balancing_scan_delay;
  959. p->numa_work.next = &p->numa_work;
  960. p->numa_faults = NULL;
  961. p->numa_group = NULL;
  962. p->last_task_numa_placement = 0;
  963. p->last_sum_exec_runtime = 0;
  964. /* New address space, reset the preferred nid */
  965. if (!(clone_flags & CLONE_VM)) {
  966. p->numa_preferred_nid = -1;
  967. return;
  968. }
  969. /*
  970. * New thread, keep existing numa_preferred_nid which should be copied
  971. * already by arch_dup_task_struct but stagger when scans start.
  972. */
  973. if (mm) {
  974. unsigned int delay;
  975. delay = min_t(unsigned int, task_scan_max(current),
  976. current->numa_scan_period * mm_users * NSEC_PER_MSEC);
  977. delay += 2 * TICK_NSEC;
  978. p->node_stamp = delay;
  979. }
  980. }
  981. static void account_numa_enqueue(struct rq *rq, struct task_struct *p)
  982. {
  983. rq->nr_numa_running += (p->numa_preferred_nid != -1);
  984. rq->nr_preferred_running += (p->numa_preferred_nid == task_node(p));
  985. }
  986. static void account_numa_dequeue(struct rq *rq, struct task_struct *p)
  987. {
  988. rq->nr_numa_running -= (p->numa_preferred_nid != -1);
  989. rq->nr_preferred_running -= (p->numa_preferred_nid == task_node(p));
  990. }
  991. /* Shared or private faults. */
  992. #define NR_NUMA_HINT_FAULT_TYPES 2
  993. /* Memory and CPU locality */
  994. #define NR_NUMA_HINT_FAULT_STATS (NR_NUMA_HINT_FAULT_TYPES * 2)
  995. /* Averaged statistics, and temporary buffers. */
  996. #define NR_NUMA_HINT_FAULT_BUCKETS (NR_NUMA_HINT_FAULT_STATS * 2)
  997. pid_t task_numa_group_id(struct task_struct *p)
  998. {
  999. return p->numa_group ? p->numa_group->gid : 0;
  1000. }
  1001. /*
  1002. * The averaged statistics, shared & private, memory & CPU,
  1003. * occupy the first half of the array. The second half of the
  1004. * array is for current counters, which are averaged into the
  1005. * first set by task_numa_placement.
  1006. */
  1007. static inline int task_faults_idx(enum numa_faults_stats s, int nid, int priv)
  1008. {
  1009. return NR_NUMA_HINT_FAULT_TYPES * (s * nr_node_ids + nid) + priv;
  1010. }
  1011. static inline unsigned long task_faults(struct task_struct *p, int nid)
  1012. {
  1013. if (!p->numa_faults)
  1014. return 0;
  1015. return p->numa_faults[task_faults_idx(NUMA_MEM, nid, 0)] +
  1016. p->numa_faults[task_faults_idx(NUMA_MEM, nid, 1)];
  1017. }
  1018. static inline unsigned long group_faults(struct task_struct *p, int nid)
  1019. {
  1020. if (!p->numa_group)
  1021. return 0;
  1022. return p->numa_group->faults[task_faults_idx(NUMA_MEM, nid, 0)] +
  1023. p->numa_group->faults[task_faults_idx(NUMA_MEM, nid, 1)];
  1024. }
  1025. static inline unsigned long group_faults_cpu(struct numa_group *group, int nid)
  1026. {
  1027. return group->faults_cpu[task_faults_idx(NUMA_MEM, nid, 0)] +
  1028. group->faults_cpu[task_faults_idx(NUMA_MEM, nid, 1)];
  1029. }
  1030. static inline unsigned long group_faults_priv(struct numa_group *ng)
  1031. {
  1032. unsigned long faults = 0;
  1033. int node;
  1034. for_each_online_node(node) {
  1035. faults += ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
  1036. }
  1037. return faults;
  1038. }
  1039. static inline unsigned long group_faults_shared(struct numa_group *ng)
  1040. {
  1041. unsigned long faults = 0;
  1042. int node;
  1043. for_each_online_node(node) {
  1044. faults += ng->faults[task_faults_idx(NUMA_MEM, node, 0)];
  1045. }
  1046. return faults;
  1047. }
  1048. /*
  1049. * A node triggering more than 1/3 as many NUMA faults as the maximum is
  1050. * considered part of a numa group's pseudo-interleaving set. Migrations
  1051. * between these nodes are slowed down, to allow things to settle down.
  1052. */
  1053. #define ACTIVE_NODE_FRACTION 3
  1054. static bool numa_is_active_node(int nid, struct numa_group *ng)
  1055. {
  1056. return group_faults_cpu(ng, nid) * ACTIVE_NODE_FRACTION > ng->max_faults_cpu;
  1057. }
  1058. /* Handle placement on systems where not all nodes are directly connected. */
  1059. static unsigned long score_nearby_nodes(struct task_struct *p, int nid,
  1060. int maxdist, bool task)
  1061. {
  1062. unsigned long score = 0;
  1063. int node;
  1064. /*
  1065. * All nodes are directly connected, and the same distance
  1066. * from each other. No need for fancy placement algorithms.
  1067. */
  1068. if (sched_numa_topology_type == NUMA_DIRECT)
  1069. return 0;
  1070. /*
  1071. * This code is called for each node, introducing N^2 complexity,
  1072. * which should be ok given the number of nodes rarely exceeds 8.
  1073. */
  1074. for_each_online_node(node) {
  1075. unsigned long faults;
  1076. int dist = node_distance(nid, node);
  1077. /*
  1078. * The furthest away nodes in the system are not interesting
  1079. * for placement; nid was already counted.
  1080. */
  1081. if (dist == sched_max_numa_distance || node == nid)
  1082. continue;
  1083. /*
  1084. * On systems with a backplane NUMA topology, compare groups
  1085. * of nodes, and move tasks towards the group with the most
  1086. * memory accesses. When comparing two nodes at distance
  1087. * "hoplimit", only nodes closer by than "hoplimit" are part
  1088. * of each group. Skip other nodes.
  1089. */
  1090. if (sched_numa_topology_type == NUMA_BACKPLANE &&
  1091. dist >= maxdist)
  1092. continue;
  1093. /* Add up the faults from nearby nodes. */
  1094. if (task)
  1095. faults = task_faults(p, node);
  1096. else
  1097. faults = group_faults(p, node);
  1098. /*
  1099. * On systems with a glueless mesh NUMA topology, there are
  1100. * no fixed "groups of nodes". Instead, nodes that are not
  1101. * directly connected bounce traffic through intermediate
  1102. * nodes; a numa_group can occupy any set of nodes.
  1103. * The further away a node is, the less the faults count.
  1104. * This seems to result in good task placement.
  1105. */
  1106. if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
  1107. faults *= (sched_max_numa_distance - dist);
  1108. faults /= (sched_max_numa_distance - LOCAL_DISTANCE);
  1109. }
  1110. score += faults;
  1111. }
  1112. return score;
  1113. }
  1114. /*
  1115. * These return the fraction of accesses done by a particular task, or
  1116. * task group, on a particular numa node. The group weight is given a
  1117. * larger multiplier, in order to group tasks together that are almost
  1118. * evenly spread out between numa nodes.
  1119. */
  1120. static inline unsigned long task_weight(struct task_struct *p, int nid,
  1121. int dist)
  1122. {
  1123. unsigned long faults, total_faults;
  1124. if (!p->numa_faults)
  1125. return 0;
  1126. total_faults = p->total_numa_faults;
  1127. if (!total_faults)
  1128. return 0;
  1129. faults = task_faults(p, nid);
  1130. faults += score_nearby_nodes(p, nid, dist, true);
  1131. return 1000 * faults / total_faults;
  1132. }
  1133. static inline unsigned long group_weight(struct task_struct *p, int nid,
  1134. int dist)
  1135. {
  1136. unsigned long faults, total_faults;
  1137. if (!p->numa_group)
  1138. return 0;
  1139. total_faults = p->numa_group->total_faults;
  1140. if (!total_faults)
  1141. return 0;
  1142. faults = group_faults(p, nid);
  1143. faults += score_nearby_nodes(p, nid, dist, false);
  1144. return 1000 * faults / total_faults;
  1145. }
  1146. bool should_numa_migrate_memory(struct task_struct *p, struct page * page,
  1147. int src_nid, int dst_cpu)
  1148. {
  1149. struct numa_group *ng = p->numa_group;
  1150. int dst_nid = cpu_to_node(dst_cpu);
  1151. int last_cpupid, this_cpupid;
  1152. this_cpupid = cpu_pid_to_cpupid(dst_cpu, current->pid);
  1153. /*
  1154. * Multi-stage node selection is used in conjunction with a periodic
  1155. * migration fault to build a temporal task<->page relation. By using
  1156. * a two-stage filter we remove short/unlikely relations.
  1157. *
  1158. * Using P(p) ~ n_p / n_t as per frequentist probability, we can equate
  1159. * a task's usage of a particular page (n_p) per total usage of this
  1160. * page (n_t) (in a given time-span) to a probability.
  1161. *
  1162. * Our periodic faults will sample this probability and getting the
  1163. * same result twice in a row, given these samples are fully
  1164. * independent, is then given by P(n)^2, provided our sample period
  1165. * is sufficiently short compared to the usage pattern.
  1166. *
  1167. * This quadric squishes small probabilities, making it less likely we
  1168. * act on an unlikely task<->page relation.
  1169. */
  1170. last_cpupid = page_cpupid_xchg_last(page, this_cpupid);
  1171. if (!cpupid_pid_unset(last_cpupid) &&
  1172. cpupid_to_nid(last_cpupid) != dst_nid)
  1173. return false;
  1174. /* Always allow migrate on private faults */
  1175. if (cpupid_match_pid(p, last_cpupid))
  1176. return true;
  1177. /* A shared fault, but p->numa_group has not been set up yet. */
  1178. if (!ng)
  1179. return true;
  1180. /*
  1181. * Destination node is much more heavily used than the source
  1182. * node? Allow migration.
  1183. */
  1184. if (group_faults_cpu(ng, dst_nid) > group_faults_cpu(ng, src_nid) *
  1185. ACTIVE_NODE_FRACTION)
  1186. return true;
  1187. /*
  1188. * Distribute memory according to CPU & memory use on each node,
  1189. * with 3/4 hysteresis to avoid unnecessary memory migrations:
  1190. *
  1191. * faults_cpu(dst) 3 faults_cpu(src)
  1192. * --------------- * - > ---------------
  1193. * faults_mem(dst) 4 faults_mem(src)
  1194. */
  1195. return group_faults_cpu(ng, dst_nid) * group_faults(p, src_nid) * 3 >
  1196. group_faults_cpu(ng, src_nid) * group_faults(p, dst_nid) * 4;
  1197. }
  1198. static unsigned long weighted_cpuload(struct rq *rq);
  1199. static unsigned long source_load(int cpu, int type);
  1200. static unsigned long target_load(int cpu, int type);
  1201. static unsigned long capacity_of(int cpu);
  1202. /* Cached statistics for all CPUs within a node */
  1203. struct numa_stats {
  1204. unsigned long load;
  1205. /* Total compute capacity of CPUs on a node */
  1206. unsigned long compute_capacity;
  1207. unsigned int nr_running;
  1208. };
  1209. /*
  1210. * XXX borrowed from update_sg_lb_stats
  1211. */
  1212. static void update_numa_stats(struct numa_stats *ns, int nid)
  1213. {
  1214. int smt, cpu, cpus = 0;
  1215. unsigned long capacity;
  1216. memset(ns, 0, sizeof(*ns));
  1217. for_each_cpu(cpu, cpumask_of_node(nid)) {
  1218. struct rq *rq = cpu_rq(cpu);
  1219. ns->nr_running += rq->nr_running;
  1220. ns->load += weighted_cpuload(rq);
  1221. ns->compute_capacity += capacity_of(cpu);
  1222. cpus++;
  1223. }
  1224. /*
  1225. * If we raced with hotplug and there are no CPUs left in our mask
  1226. * the @ns structure is NULL'ed and task_numa_compare() will
  1227. * not find this node attractive.
  1228. *
  1229. * We'll detect a huge imbalance and bail there.
  1230. */
  1231. if (!cpus)
  1232. return;
  1233. /* smt := ceil(cpus / capacity), assumes: 1 < smt_power < 2 */
  1234. smt = DIV_ROUND_UP(SCHED_CAPACITY_SCALE * cpus, ns->compute_capacity);
  1235. capacity = cpus / smt; /* cores */
  1236. capacity = min_t(unsigned, capacity,
  1237. DIV_ROUND_CLOSEST(ns->compute_capacity, SCHED_CAPACITY_SCALE));
  1238. }
  1239. struct task_numa_env {
  1240. struct task_struct *p;
  1241. int src_cpu, src_nid;
  1242. int dst_cpu, dst_nid;
  1243. struct numa_stats src_stats, dst_stats;
  1244. int imbalance_pct;
  1245. int dist;
  1246. struct task_struct *best_task;
  1247. long best_imp;
  1248. int best_cpu;
  1249. };
  1250. static void task_numa_assign(struct task_numa_env *env,
  1251. struct task_struct *p, long imp)
  1252. {
  1253. if (env->best_task)
  1254. put_task_struct(env->best_task);
  1255. if (p)
  1256. get_task_struct(p);
  1257. env->best_task = p;
  1258. env->best_imp = imp;
  1259. env->best_cpu = env->dst_cpu;
  1260. }
  1261. static bool load_too_imbalanced(long src_load, long dst_load,
  1262. struct task_numa_env *env)
  1263. {
  1264. long imb, old_imb;
  1265. long orig_src_load, orig_dst_load;
  1266. long src_capacity, dst_capacity;
  1267. /*
  1268. * The load is corrected for the CPU capacity available on each node.
  1269. *
  1270. * src_load dst_load
  1271. * ------------ vs ---------
  1272. * src_capacity dst_capacity
  1273. */
  1274. src_capacity = env->src_stats.compute_capacity;
  1275. dst_capacity = env->dst_stats.compute_capacity;
  1276. imb = abs(dst_load * src_capacity - src_load * dst_capacity);
  1277. orig_src_load = env->src_stats.load;
  1278. orig_dst_load = env->dst_stats.load;
  1279. old_imb = abs(orig_dst_load * src_capacity - orig_src_load * dst_capacity);
  1280. /* Would this change make things worse? */
  1281. return (imb > old_imb);
  1282. }
  1283. /*
  1284. * This checks if the overall compute and NUMA accesses of the system would
  1285. * be improved if the source tasks was migrated to the target dst_cpu taking
  1286. * into account that it might be best if task running on the dst_cpu should
  1287. * be exchanged with the source task
  1288. */
  1289. static void task_numa_compare(struct task_numa_env *env,
  1290. long taskimp, long groupimp, bool maymove)
  1291. {
  1292. struct rq *dst_rq = cpu_rq(env->dst_cpu);
  1293. struct task_struct *cur;
  1294. long src_load, dst_load;
  1295. long load;
  1296. long imp = env->p->numa_group ? groupimp : taskimp;
  1297. long moveimp = imp;
  1298. int dist = env->dist;
  1299. rcu_read_lock();
  1300. cur = task_rcu_dereference(&dst_rq->curr);
  1301. if (cur && ((cur->flags & PF_EXITING) || is_idle_task(cur)))
  1302. cur = NULL;
  1303. /*
  1304. * Because we have preemption enabled we can get migrated around and
  1305. * end try selecting ourselves (current == env->p) as a swap candidate.
  1306. */
  1307. if (cur == env->p)
  1308. goto unlock;
  1309. if (!cur) {
  1310. if (maymove || imp > env->best_imp)
  1311. goto assign;
  1312. else
  1313. goto unlock;
  1314. }
  1315. /*
  1316. * "imp" is the fault differential for the source task between the
  1317. * source and destination node. Calculate the total differential for
  1318. * the source task and potential destination task. The more negative
  1319. * the value is, the more remote accesses that would be expected to
  1320. * be incurred if the tasks were swapped.
  1321. */
  1322. /* Skip this swap candidate if cannot move to the source cpu */
  1323. if (!cpumask_test_cpu(env->src_cpu, &cur->cpus_allowed))
  1324. goto unlock;
  1325. /*
  1326. * If dst and source tasks are in the same NUMA group, or not
  1327. * in any group then look only at task weights.
  1328. */
  1329. if (cur->numa_group == env->p->numa_group) {
  1330. imp = taskimp + task_weight(cur, env->src_nid, dist) -
  1331. task_weight(cur, env->dst_nid, dist);
  1332. /*
  1333. * Add some hysteresis to prevent swapping the
  1334. * tasks within a group over tiny differences.
  1335. */
  1336. if (cur->numa_group)
  1337. imp -= imp / 16;
  1338. } else {
  1339. /*
  1340. * Compare the group weights. If a task is all by itself
  1341. * (not part of a group), use the task weight instead.
  1342. */
  1343. if (cur->numa_group && env->p->numa_group)
  1344. imp += group_weight(cur, env->src_nid, dist) -
  1345. group_weight(cur, env->dst_nid, dist);
  1346. else
  1347. imp += task_weight(cur, env->src_nid, dist) -
  1348. task_weight(cur, env->dst_nid, dist);
  1349. }
  1350. if (imp <= env->best_imp)
  1351. goto unlock;
  1352. if (maymove && moveimp > imp && moveimp > env->best_imp) {
  1353. imp = moveimp - 1;
  1354. cur = NULL;
  1355. goto assign;
  1356. }
  1357. /*
  1358. * In the overloaded case, try and keep the load balanced.
  1359. */
  1360. load = task_h_load(env->p) - task_h_load(cur);
  1361. if (!load)
  1362. goto assign;
  1363. dst_load = env->dst_stats.load + load;
  1364. src_load = env->src_stats.load - load;
  1365. if (load_too_imbalanced(src_load, dst_load, env))
  1366. goto unlock;
  1367. assign:
  1368. /*
  1369. * One idle CPU per node is evaluated for a task numa move.
  1370. * Call select_idle_sibling to maybe find a better one.
  1371. */
  1372. if (!cur) {
  1373. /*
  1374. * select_idle_siblings() uses an per-CPU cpumask that
  1375. * can be used from IRQ context.
  1376. */
  1377. local_irq_disable();
  1378. env->dst_cpu = select_idle_sibling(env->p, env->src_cpu,
  1379. env->dst_cpu);
  1380. local_irq_enable();
  1381. }
  1382. task_numa_assign(env, cur, imp);
  1383. unlock:
  1384. rcu_read_unlock();
  1385. }
  1386. static void task_numa_find_cpu(struct task_numa_env *env,
  1387. long taskimp, long groupimp)
  1388. {
  1389. long src_load, dst_load, load;
  1390. bool maymove = false;
  1391. int cpu;
  1392. load = task_h_load(env->p);
  1393. dst_load = env->dst_stats.load + load;
  1394. src_load = env->src_stats.load - load;
  1395. /*
  1396. * If the improvement from just moving env->p direction is better
  1397. * than swapping tasks around, check if a move is possible.
  1398. */
  1399. maymove = !load_too_imbalanced(src_load, dst_load, env);
  1400. for_each_cpu(cpu, cpumask_of_node(env->dst_nid)) {
  1401. /* Skip this CPU if the source task cannot migrate */
  1402. if (!cpumask_test_cpu(cpu, &env->p->cpus_allowed))
  1403. continue;
  1404. env->dst_cpu = cpu;
  1405. task_numa_compare(env, taskimp, groupimp, maymove);
  1406. }
  1407. }
  1408. static int task_numa_migrate(struct task_struct *p)
  1409. {
  1410. struct task_numa_env env = {
  1411. .p = p,
  1412. .src_cpu = task_cpu(p),
  1413. .src_nid = task_node(p),
  1414. .imbalance_pct = 112,
  1415. .best_task = NULL,
  1416. .best_imp = 0,
  1417. .best_cpu = -1,
  1418. };
  1419. struct sched_domain *sd;
  1420. unsigned long taskweight, groupweight;
  1421. int nid, ret, dist;
  1422. long taskimp, groupimp;
  1423. /*
  1424. * Pick the lowest SD_NUMA domain, as that would have the smallest
  1425. * imbalance and would be the first to start moving tasks about.
  1426. *
  1427. * And we want to avoid any moving of tasks about, as that would create
  1428. * random movement of tasks -- counter the numa conditions we're trying
  1429. * to satisfy here.
  1430. */
  1431. rcu_read_lock();
  1432. sd = rcu_dereference(per_cpu(sd_numa, env.src_cpu));
  1433. if (sd)
  1434. env.imbalance_pct = 100 + (sd->imbalance_pct - 100) / 2;
  1435. rcu_read_unlock();
  1436. /*
  1437. * Cpusets can break the scheduler domain tree into smaller
  1438. * balance domains, some of which do not cross NUMA boundaries.
  1439. * Tasks that are "trapped" in such domains cannot be migrated
  1440. * elsewhere, so there is no point in (re)trying.
  1441. */
  1442. if (unlikely(!sd)) {
  1443. sched_setnuma(p, task_node(p));
  1444. return -EINVAL;
  1445. }
  1446. env.dst_nid = p->numa_preferred_nid;
  1447. dist = env.dist = node_distance(env.src_nid, env.dst_nid);
  1448. taskweight = task_weight(p, env.src_nid, dist);
  1449. groupweight = group_weight(p, env.src_nid, dist);
  1450. update_numa_stats(&env.src_stats, env.src_nid);
  1451. taskimp = task_weight(p, env.dst_nid, dist) - taskweight;
  1452. groupimp = group_weight(p, env.dst_nid, dist) - groupweight;
  1453. update_numa_stats(&env.dst_stats, env.dst_nid);
  1454. /* Try to find a spot on the preferred nid. */
  1455. task_numa_find_cpu(&env, taskimp, groupimp);
  1456. /*
  1457. * Look at other nodes in these cases:
  1458. * - there is no space available on the preferred_nid
  1459. * - the task is part of a numa_group that is interleaved across
  1460. * multiple NUMA nodes; in order to better consolidate the group,
  1461. * we need to check other locations.
  1462. */
  1463. if (env.best_cpu == -1 || (p->numa_group && p->numa_group->active_nodes > 1)) {
  1464. for_each_online_node(nid) {
  1465. if (nid == env.src_nid || nid == p->numa_preferred_nid)
  1466. continue;
  1467. dist = node_distance(env.src_nid, env.dst_nid);
  1468. if (sched_numa_topology_type == NUMA_BACKPLANE &&
  1469. dist != env.dist) {
  1470. taskweight = task_weight(p, env.src_nid, dist);
  1471. groupweight = group_weight(p, env.src_nid, dist);
  1472. }
  1473. /* Only consider nodes where both task and groups benefit */
  1474. taskimp = task_weight(p, nid, dist) - taskweight;
  1475. groupimp = group_weight(p, nid, dist) - groupweight;
  1476. if (taskimp < 0 && groupimp < 0)
  1477. continue;
  1478. env.dist = dist;
  1479. env.dst_nid = nid;
  1480. update_numa_stats(&env.dst_stats, env.dst_nid);
  1481. task_numa_find_cpu(&env, taskimp, groupimp);
  1482. }
  1483. }
  1484. /*
  1485. * If the task is part of a workload that spans multiple NUMA nodes,
  1486. * and is migrating into one of the workload's active nodes, remember
  1487. * this node as the task's preferred numa node, so the workload can
  1488. * settle down.
  1489. * A task that migrated to a second choice node will be better off
  1490. * trying for a better one later. Do not set the preferred node here.
  1491. */
  1492. if (p->numa_group) {
  1493. if (env.best_cpu == -1)
  1494. nid = env.src_nid;
  1495. else
  1496. nid = cpu_to_node(env.best_cpu);
  1497. if (nid != p->numa_preferred_nid)
  1498. sched_setnuma(p, nid);
  1499. }
  1500. /* No better CPU than the current one was found. */
  1501. if (env.best_cpu == -1)
  1502. return -EAGAIN;
  1503. /*
  1504. * Reset the scan period if the task is being rescheduled on an
  1505. * alternative node to recheck if the tasks is now properly placed.
  1506. */
  1507. p->numa_scan_period = task_scan_start(p);
  1508. if (env.best_task == NULL) {
  1509. ret = migrate_task_to(p, env.best_cpu);
  1510. if (ret != 0)
  1511. trace_sched_stick_numa(p, env.src_cpu, env.best_cpu);
  1512. return ret;
  1513. }
  1514. ret = migrate_swap(p, env.best_task, env.best_cpu, env.src_cpu);
  1515. if (ret != 0)
  1516. trace_sched_stick_numa(p, env.src_cpu, task_cpu(env.best_task));
  1517. put_task_struct(env.best_task);
  1518. return ret;
  1519. }
  1520. /* Attempt to migrate a task to a CPU on the preferred node. */
  1521. static void numa_migrate_preferred(struct task_struct *p)
  1522. {
  1523. unsigned long interval = HZ;
  1524. /* This task has no NUMA fault statistics yet */
  1525. if (unlikely(p->numa_preferred_nid == -1 || !p->numa_faults))
  1526. return;
  1527. /* Periodically retry migrating the task to the preferred node */
  1528. interval = min(interval, msecs_to_jiffies(p->numa_scan_period) / 16);
  1529. p->numa_migrate_retry = jiffies + interval;
  1530. /* Success if task is already running on preferred CPU */
  1531. if (task_node(p) == p->numa_preferred_nid)
  1532. return;
  1533. /* Otherwise, try migrate to a CPU on the preferred node */
  1534. task_numa_migrate(p);
  1535. }
  1536. /*
  1537. * Find out how many nodes on the workload is actively running on. Do this by
  1538. * tracking the nodes from which NUMA hinting faults are triggered. This can
  1539. * be different from the set of nodes where the workload's memory is currently
  1540. * located.
  1541. */
  1542. static void numa_group_count_active_nodes(struct numa_group *numa_group)
  1543. {
  1544. unsigned long faults, max_faults = 0;
  1545. int nid, active_nodes = 0;
  1546. for_each_online_node(nid) {
  1547. faults = group_faults_cpu(numa_group, nid);
  1548. if (faults > max_faults)
  1549. max_faults = faults;
  1550. }
  1551. for_each_online_node(nid) {
  1552. faults = group_faults_cpu(numa_group, nid);
  1553. if (faults * ACTIVE_NODE_FRACTION > max_faults)
  1554. active_nodes++;
  1555. }
  1556. numa_group->max_faults_cpu = max_faults;
  1557. numa_group->active_nodes = active_nodes;
  1558. }
  1559. /*
  1560. * When adapting the scan rate, the period is divided into NUMA_PERIOD_SLOTS
  1561. * increments. The more local the fault statistics are, the higher the scan
  1562. * period will be for the next scan window. If local/(local+remote) ratio is
  1563. * below NUMA_PERIOD_THRESHOLD (where range of ratio is 1..NUMA_PERIOD_SLOTS)
  1564. * the scan period will decrease. Aim for 70% local accesses.
  1565. */
  1566. #define NUMA_PERIOD_SLOTS 10
  1567. #define NUMA_PERIOD_THRESHOLD 7
  1568. /*
  1569. * Increase the scan period (slow down scanning) if the majority of
  1570. * our memory is already on our local node, or if the majority of
  1571. * the page accesses are shared with other processes.
  1572. * Otherwise, decrease the scan period.
  1573. */
  1574. static void update_task_scan_period(struct task_struct *p,
  1575. unsigned long shared, unsigned long private)
  1576. {
  1577. unsigned int period_slot;
  1578. int lr_ratio, ps_ratio;
  1579. int diff;
  1580. unsigned long remote = p->numa_faults_locality[0];
  1581. unsigned long local = p->numa_faults_locality[1];
  1582. /*
  1583. * If there were no record hinting faults then either the task is
  1584. * completely idle or all activity is areas that are not of interest
  1585. * to automatic numa balancing. Related to that, if there were failed
  1586. * migration then it implies we are migrating too quickly or the local
  1587. * node is overloaded. In either case, scan slower
  1588. */
  1589. if (local + shared == 0 || p->numa_faults_locality[2]) {
  1590. p->numa_scan_period = min(p->numa_scan_period_max,
  1591. p->numa_scan_period << 1);
  1592. p->mm->numa_next_scan = jiffies +
  1593. msecs_to_jiffies(p->numa_scan_period);
  1594. return;
  1595. }
  1596. /*
  1597. * Prepare to scale scan period relative to the current period.
  1598. * == NUMA_PERIOD_THRESHOLD scan period stays the same
  1599. * < NUMA_PERIOD_THRESHOLD scan period decreases (scan faster)
  1600. * >= NUMA_PERIOD_THRESHOLD scan period increases (scan slower)
  1601. */
  1602. period_slot = DIV_ROUND_UP(p->numa_scan_period, NUMA_PERIOD_SLOTS);
  1603. lr_ratio = (local * NUMA_PERIOD_SLOTS) / (local + remote);
  1604. ps_ratio = (private * NUMA_PERIOD_SLOTS) / (private + shared);
  1605. if (ps_ratio >= NUMA_PERIOD_THRESHOLD) {
  1606. /*
  1607. * Most memory accesses are local. There is no need to
  1608. * do fast NUMA scanning, since memory is already local.
  1609. */
  1610. int slot = ps_ratio - NUMA_PERIOD_THRESHOLD;
  1611. if (!slot)
  1612. slot = 1;
  1613. diff = slot * period_slot;
  1614. } else if (lr_ratio >= NUMA_PERIOD_THRESHOLD) {
  1615. /*
  1616. * Most memory accesses are shared with other tasks.
  1617. * There is no point in continuing fast NUMA scanning,
  1618. * since other tasks may just move the memory elsewhere.
  1619. */
  1620. int slot = lr_ratio - NUMA_PERIOD_THRESHOLD;
  1621. if (!slot)
  1622. slot = 1;
  1623. diff = slot * period_slot;
  1624. } else {
  1625. /*
  1626. * Private memory faults exceed (SLOTS-THRESHOLD)/SLOTS,
  1627. * yet they are not on the local NUMA node. Speed up
  1628. * NUMA scanning to get the memory moved over.
  1629. */
  1630. int ratio = max(lr_ratio, ps_ratio);
  1631. diff = -(NUMA_PERIOD_THRESHOLD - ratio) * period_slot;
  1632. }
  1633. p->numa_scan_period = clamp(p->numa_scan_period + diff,
  1634. task_scan_min(p), task_scan_max(p));
  1635. memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
  1636. }
  1637. /*
  1638. * Get the fraction of time the task has been running since the last
  1639. * NUMA placement cycle. The scheduler keeps similar statistics, but
  1640. * decays those on a 32ms period, which is orders of magnitude off
  1641. * from the dozens-of-seconds NUMA balancing period. Use the scheduler
  1642. * stats only if the task is so new there are no NUMA statistics yet.
  1643. */
  1644. static u64 numa_get_avg_runtime(struct task_struct *p, u64 *period)
  1645. {
  1646. u64 runtime, delta, now;
  1647. /* Use the start of this time slice to avoid calculations. */
  1648. now = p->se.exec_start;
  1649. runtime = p->se.sum_exec_runtime;
  1650. if (p->last_task_numa_placement) {
  1651. delta = runtime - p->last_sum_exec_runtime;
  1652. *period = now - p->last_task_numa_placement;
  1653. } else {
  1654. delta = p->se.avg.load_sum;
  1655. *period = LOAD_AVG_MAX;
  1656. }
  1657. p->last_sum_exec_runtime = runtime;
  1658. p->last_task_numa_placement = now;
  1659. return delta;
  1660. }
  1661. /*
  1662. * Determine the preferred nid for a task in a numa_group. This needs to
  1663. * be done in a way that produces consistent results with group_weight,
  1664. * otherwise workloads might not converge.
  1665. */
  1666. static int preferred_group_nid(struct task_struct *p, int nid)
  1667. {
  1668. nodemask_t nodes;
  1669. int dist;
  1670. /* Direct connections between all NUMA nodes. */
  1671. if (sched_numa_topology_type == NUMA_DIRECT)
  1672. return nid;
  1673. /*
  1674. * On a system with glueless mesh NUMA topology, group_weight
  1675. * scores nodes according to the number of NUMA hinting faults on
  1676. * both the node itself, and on nearby nodes.
  1677. */
  1678. if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
  1679. unsigned long score, max_score = 0;
  1680. int node, max_node = nid;
  1681. dist = sched_max_numa_distance;
  1682. for_each_online_node(node) {
  1683. score = group_weight(p, node, dist);
  1684. if (score > max_score) {
  1685. max_score = score;
  1686. max_node = node;
  1687. }
  1688. }
  1689. return max_node;
  1690. }
  1691. /*
  1692. * Finding the preferred nid in a system with NUMA backplane
  1693. * interconnect topology is more involved. The goal is to locate
  1694. * tasks from numa_groups near each other in the system, and
  1695. * untangle workloads from different sides of the system. This requires
  1696. * searching down the hierarchy of node groups, recursively searching
  1697. * inside the highest scoring group of nodes. The nodemask tricks
  1698. * keep the complexity of the search down.
  1699. */
  1700. nodes = node_online_map;
  1701. for (dist = sched_max_numa_distance; dist > LOCAL_DISTANCE; dist--) {
  1702. unsigned long max_faults = 0;
  1703. nodemask_t max_group = NODE_MASK_NONE;
  1704. int a, b;
  1705. /* Are there nodes at this distance from each other? */
  1706. if (!find_numa_distance(dist))
  1707. continue;
  1708. for_each_node_mask(a, nodes) {
  1709. unsigned long faults = 0;
  1710. nodemask_t this_group;
  1711. nodes_clear(this_group);
  1712. /* Sum group's NUMA faults; includes a==b case. */
  1713. for_each_node_mask(b, nodes) {
  1714. if (node_distance(a, b) < dist) {
  1715. faults += group_faults(p, b);
  1716. node_set(b, this_group);
  1717. node_clear(b, nodes);
  1718. }
  1719. }
  1720. /* Remember the top group. */
  1721. if (faults > max_faults) {
  1722. max_faults = faults;
  1723. max_group = this_group;
  1724. /*
  1725. * subtle: at the smallest distance there is
  1726. * just one node left in each "group", the
  1727. * winner is the preferred nid.
  1728. */
  1729. nid = a;
  1730. }
  1731. }
  1732. /* Next round, evaluate the nodes within max_group. */
  1733. if (!max_faults)
  1734. break;
  1735. nodes = max_group;
  1736. }
  1737. return nid;
  1738. }
  1739. static void task_numa_placement(struct task_struct *p)
  1740. {
  1741. int seq, nid, max_nid = -1;
  1742. unsigned long max_faults = 0;
  1743. unsigned long fault_types[2] = { 0, 0 };
  1744. unsigned long total_faults;
  1745. u64 runtime, period;
  1746. spinlock_t *group_lock = NULL;
  1747. /*
  1748. * The p->mm->numa_scan_seq field gets updated without
  1749. * exclusive access. Use READ_ONCE() here to ensure
  1750. * that the field is read in a single access:
  1751. */
  1752. seq = READ_ONCE(p->mm->numa_scan_seq);
  1753. if (p->numa_scan_seq == seq)
  1754. return;
  1755. p->numa_scan_seq = seq;
  1756. p->numa_scan_period_max = task_scan_max(p);
  1757. total_faults = p->numa_faults_locality[0] +
  1758. p->numa_faults_locality[1];
  1759. runtime = numa_get_avg_runtime(p, &period);
  1760. /* If the task is part of a group prevent parallel updates to group stats */
  1761. if (p->numa_group) {
  1762. group_lock = &p->numa_group->lock;
  1763. spin_lock_irq(group_lock);
  1764. }
  1765. /* Find the node with the highest number of faults */
  1766. for_each_online_node(nid) {
  1767. /* Keep track of the offsets in numa_faults array */
  1768. int mem_idx, membuf_idx, cpu_idx, cpubuf_idx;
  1769. unsigned long faults = 0, group_faults = 0;
  1770. int priv;
  1771. for (priv = 0; priv < NR_NUMA_HINT_FAULT_TYPES; priv++) {
  1772. long diff, f_diff, f_weight;
  1773. mem_idx = task_faults_idx(NUMA_MEM, nid, priv);
  1774. membuf_idx = task_faults_idx(NUMA_MEMBUF, nid, priv);
  1775. cpu_idx = task_faults_idx(NUMA_CPU, nid, priv);
  1776. cpubuf_idx = task_faults_idx(NUMA_CPUBUF, nid, priv);
  1777. /* Decay existing window, copy faults since last scan */
  1778. diff = p->numa_faults[membuf_idx] - p->numa_faults[mem_idx] / 2;
  1779. fault_types[priv] += p->numa_faults[membuf_idx];
  1780. p->numa_faults[membuf_idx] = 0;
  1781. /*
  1782. * Normalize the faults_from, so all tasks in a group
  1783. * count according to CPU use, instead of by the raw
  1784. * number of faults. Tasks with little runtime have
  1785. * little over-all impact on throughput, and thus their
  1786. * faults are less important.
  1787. */
  1788. f_weight = div64_u64(runtime << 16, period + 1);
  1789. f_weight = (f_weight * p->numa_faults[cpubuf_idx]) /
  1790. (total_faults + 1);
  1791. f_diff = f_weight - p->numa_faults[cpu_idx] / 2;
  1792. p->numa_faults[cpubuf_idx] = 0;
  1793. p->numa_faults[mem_idx] += diff;
  1794. p->numa_faults[cpu_idx] += f_diff;
  1795. faults += p->numa_faults[mem_idx];
  1796. p->total_numa_faults += diff;
  1797. if (p->numa_group) {
  1798. /*
  1799. * safe because we can only change our own group
  1800. *
  1801. * mem_idx represents the offset for a given
  1802. * nid and priv in a specific region because it
  1803. * is at the beginning of the numa_faults array.
  1804. */
  1805. p->numa_group->faults[mem_idx] += diff;
  1806. p->numa_group->faults_cpu[mem_idx] += f_diff;
  1807. p->numa_group->total_faults += diff;
  1808. group_faults += p->numa_group->faults[mem_idx];
  1809. }
  1810. }
  1811. if (!p->numa_group) {
  1812. if (faults > max_faults) {
  1813. max_faults = faults;
  1814. max_nid = nid;
  1815. }
  1816. } else if (group_faults > max_faults) {
  1817. max_faults = group_faults;
  1818. max_nid = nid;
  1819. }
  1820. }
  1821. if (p->numa_group) {
  1822. numa_group_count_active_nodes(p->numa_group);
  1823. spin_unlock_irq(group_lock);
  1824. max_nid = preferred_group_nid(p, max_nid);
  1825. }
  1826. if (max_faults) {
  1827. /* Set the new preferred node */
  1828. if (max_nid != p->numa_preferred_nid)
  1829. sched_setnuma(p, max_nid);
  1830. }
  1831. update_task_scan_period(p, fault_types[0], fault_types[1]);
  1832. }
  1833. static inline int get_numa_group(struct numa_group *grp)
  1834. {
  1835. return atomic_inc_not_zero(&grp->refcount);
  1836. }
  1837. static inline void put_numa_group(struct numa_group *grp)
  1838. {
  1839. if (atomic_dec_and_test(&grp->refcount))
  1840. kfree_rcu(grp, rcu);
  1841. }
  1842. static void task_numa_group(struct task_struct *p, int cpupid, int flags,
  1843. int *priv)
  1844. {
  1845. struct numa_group *grp, *my_grp;
  1846. struct task_struct *tsk;
  1847. bool join = false;
  1848. int cpu = cpupid_to_cpu(cpupid);
  1849. int i;
  1850. if (unlikely(!p->numa_group)) {
  1851. unsigned int size = sizeof(struct numa_group) +
  1852. 4*nr_node_ids*sizeof(unsigned long);
  1853. grp = kzalloc(size, GFP_KERNEL | __GFP_NOWARN);
  1854. if (!grp)
  1855. return;
  1856. atomic_set(&grp->refcount, 1);
  1857. grp->active_nodes = 1;
  1858. grp->max_faults_cpu = 0;
  1859. spin_lock_init(&grp->lock);
  1860. grp->gid = p->pid;
  1861. /* Second half of the array tracks nids where faults happen */
  1862. grp->faults_cpu = grp->faults + NR_NUMA_HINT_FAULT_TYPES *
  1863. nr_node_ids;
  1864. for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
  1865. grp->faults[i] = p->numa_faults[i];
  1866. grp->total_faults = p->total_numa_faults;
  1867. grp->nr_tasks++;
  1868. rcu_assign_pointer(p->numa_group, grp);
  1869. }
  1870. rcu_read_lock();
  1871. tsk = READ_ONCE(cpu_rq(cpu)->curr);
  1872. if (!cpupid_match_pid(tsk, cpupid))
  1873. goto no_join;
  1874. grp = rcu_dereference(tsk->numa_group);
  1875. if (!grp)
  1876. goto no_join;
  1877. my_grp = p->numa_group;
  1878. if (grp == my_grp)
  1879. goto no_join;
  1880. /*
  1881. * Only join the other group if its bigger; if we're the bigger group,
  1882. * the other task will join us.
  1883. */
  1884. if (my_grp->nr_tasks > grp->nr_tasks)
  1885. goto no_join;
  1886. /*
  1887. * Tie-break on the grp address.
  1888. */
  1889. if (my_grp->nr_tasks == grp->nr_tasks && my_grp > grp)
  1890. goto no_join;
  1891. /* Always join threads in the same process. */
  1892. if (tsk->mm == current->mm)
  1893. join = true;
  1894. /* Simple filter to avoid false positives due to PID collisions */
  1895. if (flags & TNF_SHARED)
  1896. join = true;
  1897. /* Update priv based on whether false sharing was detected */
  1898. *priv = !join;
  1899. if (join && !get_numa_group(grp))
  1900. goto no_join;
  1901. rcu_read_unlock();
  1902. if (!join)
  1903. return;
  1904. BUG_ON(irqs_disabled());
  1905. double_lock_irq(&my_grp->lock, &grp->lock);
  1906. for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) {
  1907. my_grp->faults[i] -= p->numa_faults[i];
  1908. grp->faults[i] += p->numa_faults[i];
  1909. }
  1910. my_grp->total_faults -= p->total_numa_faults;
  1911. grp->total_faults += p->total_numa_faults;
  1912. my_grp->nr_tasks--;
  1913. grp->nr_tasks++;
  1914. spin_unlock(&my_grp->lock);
  1915. spin_unlock_irq(&grp->lock);
  1916. rcu_assign_pointer(p->numa_group, grp);
  1917. put_numa_group(my_grp);
  1918. return;
  1919. no_join:
  1920. rcu_read_unlock();
  1921. return;
  1922. }
  1923. void task_numa_free(struct task_struct *p)
  1924. {
  1925. struct numa_group *grp = p->numa_group;
  1926. void *numa_faults = p->numa_faults;
  1927. unsigned long flags;
  1928. int i;
  1929. if (grp) {
  1930. spin_lock_irqsave(&grp->lock, flags);
  1931. for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
  1932. grp->faults[i] -= p->numa_faults[i];
  1933. grp->total_faults -= p->total_numa_faults;
  1934. grp->nr_tasks--;
  1935. spin_unlock_irqrestore(&grp->lock, flags);
  1936. RCU_INIT_POINTER(p->numa_group, NULL);
  1937. put_numa_group(grp);
  1938. }
  1939. p->numa_faults = NULL;
  1940. kfree(numa_faults);
  1941. }
  1942. /*
  1943. * Got a PROT_NONE fault for a page on @node.
  1944. */
  1945. void task_numa_fault(int last_cpupid, int mem_node, int pages, int flags)
  1946. {
  1947. struct task_struct *p = current;
  1948. bool migrated = flags & TNF_MIGRATED;
  1949. int cpu_node = task_node(current);
  1950. int local = !!(flags & TNF_FAULT_LOCAL);
  1951. struct numa_group *ng;
  1952. int priv;
  1953. if (!static_branch_likely(&sched_numa_balancing))
  1954. return;
  1955. /* for example, ksmd faulting in a user's mm */
  1956. if (!p->mm)
  1957. return;
  1958. /* Allocate buffer to track faults on a per-node basis */
  1959. if (unlikely(!p->numa_faults)) {
  1960. int size = sizeof(*p->numa_faults) *
  1961. NR_NUMA_HINT_FAULT_BUCKETS * nr_node_ids;
  1962. p->numa_faults = kzalloc(size, GFP_KERNEL|__GFP_NOWARN);
  1963. if (!p->numa_faults)
  1964. return;
  1965. p->total_numa_faults = 0;
  1966. memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
  1967. }
  1968. /*
  1969. * First accesses are treated as private, otherwise consider accesses
  1970. * to be private if the accessing pid has not changed
  1971. */
  1972. if (unlikely(last_cpupid == (-1 & LAST_CPUPID_MASK))) {
  1973. priv = 1;
  1974. } else {
  1975. priv = cpupid_match_pid(p, last_cpupid);
  1976. if (!priv && !(flags & TNF_NO_GROUP))
  1977. task_numa_group(p, last_cpupid, flags, &priv);
  1978. }
  1979. /*
  1980. * If a workload spans multiple NUMA nodes, a shared fault that
  1981. * occurs wholly within the set of nodes that the workload is
  1982. * actively using should be counted as local. This allows the
  1983. * scan rate to slow down when a workload has settled down.
  1984. */
  1985. ng = p->numa_group;
  1986. if (!priv && !local && ng && ng->active_nodes > 1 &&
  1987. numa_is_active_node(cpu_node, ng) &&
  1988. numa_is_active_node(mem_node, ng))
  1989. local = 1;
  1990. /*
  1991. * Retry task to preferred node migration periodically, in case it
  1992. * case it previously failed, or the scheduler moved us.
  1993. */
  1994. if (time_after(jiffies, p->numa_migrate_retry)) {
  1995. task_numa_placement(p);
  1996. numa_migrate_preferred(p);
  1997. }
  1998. if (migrated)
  1999. p->numa_pages_migrated += pages;
  2000. if (flags & TNF_MIGRATE_FAIL)
  2001. p->numa_faults_locality[2] += pages;
  2002. p->numa_faults[task_faults_idx(NUMA_MEMBUF, mem_node, priv)] += pages;
  2003. p->numa_faults[task_faults_idx(NUMA_CPUBUF, cpu_node, priv)] += pages;
  2004. p->numa_faults_locality[local] += pages;
  2005. }
  2006. static void reset_ptenuma_scan(struct task_struct *p)
  2007. {
  2008. /*
  2009. * We only did a read acquisition of the mmap sem, so
  2010. * p->mm->numa_scan_seq is written to without exclusive access
  2011. * and the update is not guaranteed to be atomic. That's not
  2012. * much of an issue though, since this is just used for
  2013. * statistical sampling. Use READ_ONCE/WRITE_ONCE, which are not
  2014. * expensive, to avoid any form of compiler optimizations:
  2015. */
  2016. WRITE_ONCE(p->mm->numa_scan_seq, READ_ONCE(p->mm->numa_scan_seq) + 1);
  2017. p->mm->numa_scan_offset = 0;
  2018. }
  2019. /*
  2020. * The expensive part of numa migration is done from task_work context.
  2021. * Triggered from task_tick_numa().
  2022. */
  2023. void task_numa_work(struct callback_head *work)
  2024. {
  2025. unsigned long migrate, next_scan, now = jiffies;
  2026. struct task_struct *p = current;
  2027. struct mm_struct *mm = p->mm;
  2028. u64 runtime = p->se.sum_exec_runtime;
  2029. struct vm_area_struct *vma;
  2030. unsigned long start, end;
  2031. unsigned long nr_pte_updates = 0;
  2032. long pages, virtpages;
  2033. SCHED_WARN_ON(p != container_of(work, struct task_struct, numa_work));
  2034. work->next = work; /* protect against double add */
  2035. /*
  2036. * Who cares about NUMA placement when they're dying.
  2037. *
  2038. * NOTE: make sure not to dereference p->mm before this check,
  2039. * exit_task_work() happens _after_ exit_mm() so we could be called
  2040. * without p->mm even though we still had it when we enqueued this
  2041. * work.
  2042. */
  2043. if (p->flags & PF_EXITING)
  2044. return;
  2045. if (!mm->numa_next_scan) {
  2046. mm->numa_next_scan = now +
  2047. msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
  2048. }
  2049. /*
  2050. * Enforce maximal scan/migration frequency..
  2051. */
  2052. migrate = mm->numa_next_scan;
  2053. if (time_before(now, migrate))
  2054. return;
  2055. if (p->numa_scan_period == 0) {
  2056. p->numa_scan_period_max = task_scan_max(p);
  2057. p->numa_scan_period = task_scan_start(p);
  2058. }
  2059. next_scan = now + msecs_to_jiffies(p->numa_scan_period);
  2060. if (cmpxchg(&mm->numa_next_scan, migrate, next_scan) != migrate)
  2061. return;
  2062. /*
  2063. * Delay this task enough that another task of this mm will likely win
  2064. * the next time around.
  2065. */
  2066. p->node_stamp += 2 * TICK_NSEC;
  2067. start = mm->numa_scan_offset;
  2068. pages = sysctl_numa_balancing_scan_size;
  2069. pages <<= 20 - PAGE_SHIFT; /* MB in pages */
  2070. virtpages = pages * 8; /* Scan up to this much virtual space */
  2071. if (!pages)
  2072. return;
  2073. if (!down_read_trylock(&mm->mmap_sem))
  2074. return;
  2075. vma = find_vma(mm, start);
  2076. if (!vma) {
  2077. reset_ptenuma_scan(p);
  2078. start = 0;
  2079. vma = mm->mmap;
  2080. }
  2081. for (; vma; vma = vma->vm_next) {
  2082. if (!vma_migratable(vma) || !vma_policy_mof(vma) ||
  2083. is_vm_hugetlb_page(vma) || (vma->vm_flags & VM_MIXEDMAP)) {
  2084. continue;
  2085. }
  2086. /*
  2087. * Shared library pages mapped by multiple processes are not
  2088. * migrated as it is expected they are cache replicated. Avoid
  2089. * hinting faults in read-only file-backed mappings or the vdso
  2090. * as migrating the pages will be of marginal benefit.
  2091. */
  2092. if (!vma->vm_mm ||
  2093. (vma->vm_file && (vma->vm_flags & (VM_READ|VM_WRITE)) == (VM_READ)))
  2094. continue;
  2095. /*
  2096. * Skip inaccessible VMAs to avoid any confusion between
  2097. * PROT_NONE and NUMA hinting ptes
  2098. */
  2099. if (!(vma->vm_flags & (VM_READ | VM_EXEC | VM_WRITE)))
  2100. continue;
  2101. do {
  2102. start = max(start, vma->vm_start);
  2103. end = ALIGN(start + (pages << PAGE_SHIFT), HPAGE_SIZE);
  2104. end = min(end, vma->vm_end);
  2105. nr_pte_updates = change_prot_numa(vma, start, end);
  2106. /*
  2107. * Try to scan sysctl_numa_balancing_size worth of
  2108. * hpages that have at least one present PTE that
  2109. * is not already pte-numa. If the VMA contains
  2110. * areas that are unused or already full of prot_numa
  2111. * PTEs, scan up to virtpages, to skip through those
  2112. * areas faster.
  2113. */
  2114. if (nr_pte_updates)
  2115. pages -= (end - start) >> PAGE_SHIFT;
  2116. virtpages -= (end - start) >> PAGE_SHIFT;
  2117. start = end;
  2118. if (pages <= 0 || virtpages <= 0)
  2119. goto out;
  2120. cond_resched();
  2121. } while (end != vma->vm_end);
  2122. }
  2123. out:
  2124. /*
  2125. * It is possible to reach the end of the VMA list but the last few
  2126. * VMAs are not guaranteed to the vma_migratable. If they are not, we
  2127. * would find the !migratable VMA on the next scan but not reset the
  2128. * scanner to the start so check it now.
  2129. */
  2130. if (vma)
  2131. mm->numa_scan_offset = start;
  2132. else
  2133. reset_ptenuma_scan(p);
  2134. up_read(&mm->mmap_sem);
  2135. /*
  2136. * Make sure tasks use at least 32x as much time to run other code
  2137. * than they used here, to limit NUMA PTE scanning overhead to 3% max.
  2138. * Usually update_task_scan_period slows down scanning enough; on an
  2139. * overloaded system we need to limit overhead on a per task basis.
  2140. */
  2141. if (unlikely(p->se.sum_exec_runtime != runtime)) {
  2142. u64 diff = p->se.sum_exec_runtime - runtime;
  2143. p->node_stamp += 32 * diff;
  2144. }
  2145. }
  2146. /*
  2147. * Drive the periodic memory faults..
  2148. */
  2149. void task_tick_numa(struct rq *rq, struct task_struct *curr)
  2150. {
  2151. struct callback_head *work = &curr->numa_work;
  2152. u64 period, now;
  2153. /*
  2154. * We don't care about NUMA placement if we don't have memory.
  2155. */
  2156. if (!curr->mm || (curr->flags & PF_EXITING) || work->next != work)
  2157. return;
  2158. /*
  2159. * Using runtime rather than walltime has the dual advantage that
  2160. * we (mostly) drive the selection from busy threads and that the
  2161. * task needs to have done some actual work before we bother with
  2162. * NUMA placement.
  2163. */
  2164. now = curr->se.sum_exec_runtime;
  2165. period = (u64)curr->numa_scan_period * NSEC_PER_MSEC;
  2166. if (now > curr->node_stamp + period) {
  2167. if (!curr->node_stamp)
  2168. curr->numa_scan_period = task_scan_start(curr);
  2169. curr->node_stamp += period;
  2170. if (!time_before(jiffies, curr->mm->numa_next_scan)) {
  2171. init_task_work(work, task_numa_work); /* TODO: move this into sched_fork() */
  2172. task_work_add(curr, work, true);
  2173. }
  2174. }
  2175. }
  2176. #else
  2177. static void task_tick_numa(struct rq *rq, struct task_struct *curr)
  2178. {
  2179. }
  2180. static inline void account_numa_enqueue(struct rq *rq, struct task_struct *p)
  2181. {
  2182. }
  2183. static inline void account_numa_dequeue(struct rq *rq, struct task_struct *p)
  2184. {
  2185. }
  2186. #endif /* CONFIG_NUMA_BALANCING */
  2187. static void
  2188. account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
  2189. {
  2190. update_load_add(&cfs_rq->load, se->load.weight);
  2191. if (!parent_entity(se))
  2192. update_load_add(&rq_of(cfs_rq)->load, se->load.weight);
  2193. #ifdef CONFIG_SMP
  2194. if (entity_is_task(se)) {
  2195. struct rq *rq = rq_of(cfs_rq);
  2196. account_numa_enqueue(rq, task_of(se));
  2197. list_add(&se->group_node, &rq->cfs_tasks);
  2198. }
  2199. #endif
  2200. cfs_rq->nr_running++;
  2201. }
  2202. static void
  2203. account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
  2204. {
  2205. update_load_sub(&cfs_rq->load, se->load.weight);
  2206. if (!parent_entity(se))
  2207. update_load_sub(&rq_of(cfs_rq)->load, se->load.weight);
  2208. #ifdef CONFIG_SMP
  2209. if (entity_is_task(se)) {
  2210. account_numa_dequeue(rq_of(cfs_rq), task_of(se));
  2211. list_del_init(&se->group_node);
  2212. }
  2213. #endif
  2214. cfs_rq->nr_running--;
  2215. }
  2216. /*
  2217. * Signed add and clamp on underflow.
  2218. *
  2219. * Explicitly do a load-store to ensure the intermediate value never hits
  2220. * memory. This allows lockless observations without ever seeing the negative
  2221. * values.
  2222. */
  2223. #define add_positive(_ptr, _val) do { \
  2224. typeof(_ptr) ptr = (_ptr); \
  2225. typeof(_val) val = (_val); \
  2226. typeof(*ptr) res, var = READ_ONCE(*ptr); \
  2227. \
  2228. res = var + val; \
  2229. \
  2230. if (val < 0 && res > var) \
  2231. res = 0; \
  2232. \
  2233. WRITE_ONCE(*ptr, res); \
  2234. } while (0)
  2235. /*
  2236. * Unsigned subtract and clamp on underflow.
  2237. *
  2238. * Explicitly do a load-store to ensure the intermediate value never hits
  2239. * memory. This allows lockless observations without ever seeing the negative
  2240. * values.
  2241. */
  2242. #define sub_positive(_ptr, _val) do { \
  2243. typeof(_ptr) ptr = (_ptr); \
  2244. typeof(*ptr) val = (_val); \
  2245. typeof(*ptr) res, var = READ_ONCE(*ptr); \
  2246. res = var - val; \
  2247. if (res > var) \
  2248. res = 0; \
  2249. WRITE_ONCE(*ptr, res); \
  2250. } while (0)
  2251. #ifdef CONFIG_SMP
  2252. static inline void
  2253. enqueue_runnable_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
  2254. {
  2255. cfs_rq->runnable_weight += se->runnable_weight;
  2256. cfs_rq->avg.runnable_load_avg += se->avg.runnable_load_avg;
  2257. cfs_rq->avg.runnable_load_sum += se_runnable(se) * se->avg.runnable_load_sum;
  2258. }
  2259. static inline void
  2260. dequeue_runnable_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
  2261. {
  2262. cfs_rq->runnable_weight -= se->runnable_weight;
  2263. sub_positive(&cfs_rq->avg.runnable_load_avg, se->avg.runnable_load_avg);
  2264. sub_positive(&cfs_rq->avg.runnable_load_sum,
  2265. se_runnable(se) * se->avg.runnable_load_sum);
  2266. }
  2267. static inline void
  2268. enqueue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
  2269. {
  2270. cfs_rq->avg.load_avg += se->avg.load_avg;
  2271. cfs_rq->avg.load_sum += se_weight(se) * se->avg.load_sum;
  2272. }
  2273. static inline void
  2274. dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
  2275. {
  2276. sub_positive(&cfs_rq->avg.load_avg, se->avg.load_avg);
  2277. sub_positive(&cfs_rq->avg.load_sum, se_weight(se) * se->avg.load_sum);
  2278. }
  2279. #else
  2280. static inline void
  2281. enqueue_runnable_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) { }
  2282. static inline void
  2283. dequeue_runnable_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) { }
  2284. static inline void
  2285. enqueue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) { }
  2286. static inline void
  2287. dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) { }
  2288. #endif
  2289. static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se,
  2290. unsigned long weight, unsigned long runnable)
  2291. {
  2292. if (se->on_rq) {
  2293. /* commit outstanding execution time */
  2294. if (cfs_rq->curr == se)
  2295. update_curr(cfs_rq);
  2296. account_entity_dequeue(cfs_rq, se);
  2297. dequeue_runnable_load_avg(cfs_rq, se);
  2298. }
  2299. dequeue_load_avg(cfs_rq, se);
  2300. se->runnable_weight = runnable;
  2301. update_load_set(&se->load, weight);
  2302. #ifdef CONFIG_SMP
  2303. do {
  2304. u32 divider = LOAD_AVG_MAX - 1024 + se->avg.period_contrib;
  2305. se->avg.load_avg = div_u64(se_weight(se) * se->avg.load_sum, divider);
  2306. se->avg.runnable_load_avg =
  2307. div_u64(se_runnable(se) * se->avg.runnable_load_sum, divider);
  2308. } while (0);
  2309. #endif
  2310. enqueue_load_avg(cfs_rq, se);
  2311. if (se->on_rq) {
  2312. account_entity_enqueue(cfs_rq, se);
  2313. enqueue_runnable_load_avg(cfs_rq, se);
  2314. }
  2315. }
  2316. void reweight_task(struct task_struct *p, int prio)
  2317. {
  2318. struct sched_entity *se = &p->se;
  2319. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  2320. struct load_weight *load = &se->load;
  2321. unsigned long weight = scale_load(sched_prio_to_weight[prio]);
  2322. reweight_entity(cfs_rq, se, weight, weight);
  2323. load->inv_weight = sched_prio_to_wmult[prio];
  2324. }
  2325. #ifdef CONFIG_FAIR_GROUP_SCHED
  2326. #ifdef CONFIG_SMP
  2327. /*
  2328. * All this does is approximate the hierarchical proportion which includes that
  2329. * global sum we all love to hate.
  2330. *
  2331. * That is, the weight of a group entity, is the proportional share of the
  2332. * group weight based on the group runqueue weights. That is:
  2333. *
  2334. * tg->weight * grq->load.weight
  2335. * ge->load.weight = ----------------------------- (1)
  2336. * \Sum grq->load.weight
  2337. *
  2338. * Now, because computing that sum is prohibitively expensive to compute (been
  2339. * there, done that) we approximate it with this average stuff. The average
  2340. * moves slower and therefore the approximation is cheaper and more stable.
  2341. *
  2342. * So instead of the above, we substitute:
  2343. *
  2344. * grq->load.weight -> grq->avg.load_avg (2)
  2345. *
  2346. * which yields the following:
  2347. *
  2348. * tg->weight * grq->avg.load_avg
  2349. * ge->load.weight = ------------------------------ (3)
  2350. * tg->load_avg
  2351. *
  2352. * Where: tg->load_avg ~= \Sum grq->avg.load_avg
  2353. *
  2354. * That is shares_avg, and it is right (given the approximation (2)).
  2355. *
  2356. * The problem with it is that because the average is slow -- it was designed
  2357. * to be exactly that of course -- this leads to transients in boundary
  2358. * conditions. In specific, the case where the group was idle and we start the
  2359. * one task. It takes time for our CPU's grq->avg.load_avg to build up,
  2360. * yielding bad latency etc..
  2361. *
  2362. * Now, in that special case (1) reduces to:
  2363. *
  2364. * tg->weight * grq->load.weight
  2365. * ge->load.weight = ----------------------------- = tg->weight (4)
  2366. * grp->load.weight
  2367. *
  2368. * That is, the sum collapses because all other CPUs are idle; the UP scenario.
  2369. *
  2370. * So what we do is modify our approximation (3) to approach (4) in the (near)
  2371. * UP case, like:
  2372. *
  2373. * ge->load.weight =
  2374. *
  2375. * tg->weight * grq->load.weight
  2376. * --------------------------------------------------- (5)
  2377. * tg->load_avg - grq->avg.load_avg + grq->load.weight
  2378. *
  2379. * But because grq->load.weight can drop to 0, resulting in a divide by zero,
  2380. * we need to use grq->avg.load_avg as its lower bound, which then gives:
  2381. *
  2382. *
  2383. * tg->weight * grq->load.weight
  2384. * ge->load.weight = ----------------------------- (6)
  2385. * tg_load_avg'
  2386. *
  2387. * Where:
  2388. *
  2389. * tg_load_avg' = tg->load_avg - grq->avg.load_avg +
  2390. * max(grq->load.weight, grq->avg.load_avg)
  2391. *
  2392. * And that is shares_weight and is icky. In the (near) UP case it approaches
  2393. * (4) while in the normal case it approaches (3). It consistently
  2394. * overestimates the ge->load.weight and therefore:
  2395. *
  2396. * \Sum ge->load.weight >= tg->weight
  2397. *
  2398. * hence icky!
  2399. */
  2400. static long calc_group_shares(struct cfs_rq *cfs_rq)
  2401. {
  2402. long tg_weight, tg_shares, load, shares;
  2403. struct task_group *tg = cfs_rq->tg;
  2404. tg_shares = READ_ONCE(tg->shares);
  2405. load = max(scale_load_down(cfs_rq->load.weight), cfs_rq->avg.load_avg);
  2406. tg_weight = atomic_long_read(&tg->load_avg);
  2407. /* Ensure tg_weight >= load */
  2408. tg_weight -= cfs_rq->tg_load_avg_contrib;
  2409. tg_weight += load;
  2410. shares = (tg_shares * load);
  2411. if (tg_weight)
  2412. shares /= tg_weight;
  2413. /*
  2414. * MIN_SHARES has to be unscaled here to support per-CPU partitioning
  2415. * of a group with small tg->shares value. It is a floor value which is
  2416. * assigned as a minimum load.weight to the sched_entity representing
  2417. * the group on a CPU.
  2418. *
  2419. * E.g. on 64-bit for a group with tg->shares of scale_load(15)=15*1024
  2420. * on an 8-core system with 8 tasks each runnable on one CPU shares has
  2421. * to be 15*1024*1/8=1920 instead of scale_load(MIN_SHARES)=2*1024. In
  2422. * case no task is runnable on a CPU MIN_SHARES=2 should be returned
  2423. * instead of 0.
  2424. */
  2425. return clamp_t(long, shares, MIN_SHARES, tg_shares);
  2426. }
  2427. /*
  2428. * This calculates the effective runnable weight for a group entity based on
  2429. * the group entity weight calculated above.
  2430. *
  2431. * Because of the above approximation (2), our group entity weight is
  2432. * an load_avg based ratio (3). This means that it includes blocked load and
  2433. * does not represent the runnable weight.
  2434. *
  2435. * Approximate the group entity's runnable weight per ratio from the group
  2436. * runqueue:
  2437. *
  2438. * grq->avg.runnable_load_avg
  2439. * ge->runnable_weight = ge->load.weight * -------------------------- (7)
  2440. * grq->avg.load_avg
  2441. *
  2442. * However, analogous to above, since the avg numbers are slow, this leads to
  2443. * transients in the from-idle case. Instead we use:
  2444. *
  2445. * ge->runnable_weight = ge->load.weight *
  2446. *
  2447. * max(grq->avg.runnable_load_avg, grq->runnable_weight)
  2448. * ----------------------------------------------------- (8)
  2449. * max(grq->avg.load_avg, grq->load.weight)
  2450. *
  2451. * Where these max() serve both to use the 'instant' values to fix the slow
  2452. * from-idle and avoid the /0 on to-idle, similar to (6).
  2453. */
  2454. static long calc_group_runnable(struct cfs_rq *cfs_rq, long shares)
  2455. {
  2456. long runnable, load_avg;
  2457. load_avg = max(cfs_rq->avg.load_avg,
  2458. scale_load_down(cfs_rq->load.weight));
  2459. runnable = max(cfs_rq->avg.runnable_load_avg,
  2460. scale_load_down(cfs_rq->runnable_weight));
  2461. runnable *= shares;
  2462. if (load_avg)
  2463. runnable /= load_avg;
  2464. return clamp_t(long, runnable, MIN_SHARES, shares);
  2465. }
  2466. #endif /* CONFIG_SMP */
  2467. static inline int throttled_hierarchy(struct cfs_rq *cfs_rq);
  2468. /*
  2469. * Recomputes the group entity based on the current state of its group
  2470. * runqueue.
  2471. */
  2472. static void update_cfs_group(struct sched_entity *se)
  2473. {
  2474. struct cfs_rq *gcfs_rq = group_cfs_rq(se);
  2475. long shares, runnable;
  2476. if (!gcfs_rq)
  2477. return;
  2478. if (throttled_hierarchy(gcfs_rq))
  2479. return;
  2480. #ifndef CONFIG_SMP
  2481. runnable = shares = READ_ONCE(gcfs_rq->tg->shares);
  2482. if (likely(se->load.weight == shares))
  2483. return;
  2484. #else
  2485. shares = calc_group_shares(gcfs_rq);
  2486. runnable = calc_group_runnable(gcfs_rq, shares);
  2487. #endif
  2488. reweight_entity(cfs_rq_of(se), se, shares, runnable);
  2489. }
  2490. #else /* CONFIG_FAIR_GROUP_SCHED */
  2491. static inline void update_cfs_group(struct sched_entity *se)
  2492. {
  2493. }
  2494. #endif /* CONFIG_FAIR_GROUP_SCHED */
  2495. static inline void cfs_rq_util_change(struct cfs_rq *cfs_rq, int flags)
  2496. {
  2497. struct rq *rq = rq_of(cfs_rq);
  2498. if (&rq->cfs == cfs_rq || (flags & SCHED_CPUFREQ_MIGRATION)) {
  2499. /*
  2500. * There are a few boundary cases this might miss but it should
  2501. * get called often enough that that should (hopefully) not be
  2502. * a real problem.
  2503. *
  2504. * It will not get called when we go idle, because the idle
  2505. * thread is a different class (!fair), nor will the utilization
  2506. * number include things like RT tasks.
  2507. *
  2508. * As is, the util number is not freq-invariant (we'd have to
  2509. * implement arch_scale_freq_capacity() for that).
  2510. *
  2511. * See cpu_util().
  2512. */
  2513. cpufreq_update_util(rq, flags);
  2514. }
  2515. }
  2516. #ifdef CONFIG_SMP
  2517. #ifdef CONFIG_FAIR_GROUP_SCHED
  2518. /**
  2519. * update_tg_load_avg - update the tg's load avg
  2520. * @cfs_rq: the cfs_rq whose avg changed
  2521. * @force: update regardless of how small the difference
  2522. *
  2523. * This function 'ensures': tg->load_avg := \Sum tg->cfs_rq[]->avg.load.
  2524. * However, because tg->load_avg is a global value there are performance
  2525. * considerations.
  2526. *
  2527. * In order to avoid having to look at the other cfs_rq's, we use a
  2528. * differential update where we store the last value we propagated. This in
  2529. * turn allows skipping updates if the differential is 'small'.
  2530. *
  2531. * Updating tg's load_avg is necessary before update_cfs_share().
  2532. */
  2533. static inline void update_tg_load_avg(struct cfs_rq *cfs_rq, int force)
  2534. {
  2535. long delta = cfs_rq->avg.load_avg - cfs_rq->tg_load_avg_contrib;
  2536. /*
  2537. * No need to update load_avg for root_task_group as it is not used.
  2538. */
  2539. if (cfs_rq->tg == &root_task_group)
  2540. return;
  2541. if (force || abs(delta) > cfs_rq->tg_load_avg_contrib / 64) {
  2542. atomic_long_add(delta, &cfs_rq->tg->load_avg);
  2543. cfs_rq->tg_load_avg_contrib = cfs_rq->avg.load_avg;
  2544. }
  2545. }
  2546. /*
  2547. * Called within set_task_rq() right before setting a task's CPU. The
  2548. * caller only guarantees p->pi_lock is held; no other assumptions,
  2549. * including the state of rq->lock, should be made.
  2550. */
  2551. void set_task_rq_fair(struct sched_entity *se,
  2552. struct cfs_rq *prev, struct cfs_rq *next)
  2553. {
  2554. u64 p_last_update_time;
  2555. u64 n_last_update_time;
  2556. if (!sched_feat(ATTACH_AGE_LOAD))
  2557. return;
  2558. /*
  2559. * We are supposed to update the task to "current" time, then its up to
  2560. * date and ready to go to new CPU/cfs_rq. But we have difficulty in
  2561. * getting what current time is, so simply throw away the out-of-date
  2562. * time. This will result in the wakee task is less decayed, but giving
  2563. * the wakee more load sounds not bad.
  2564. */
  2565. if (!(se->avg.last_update_time && prev))
  2566. return;
  2567. #ifndef CONFIG_64BIT
  2568. {
  2569. u64 p_last_update_time_copy;
  2570. u64 n_last_update_time_copy;
  2571. do {
  2572. p_last_update_time_copy = prev->load_last_update_time_copy;
  2573. n_last_update_time_copy = next->load_last_update_time_copy;
  2574. smp_rmb();
  2575. p_last_update_time = prev->avg.last_update_time;
  2576. n_last_update_time = next->avg.last_update_time;
  2577. } while (p_last_update_time != p_last_update_time_copy ||
  2578. n_last_update_time != n_last_update_time_copy);
  2579. }
  2580. #else
  2581. p_last_update_time = prev->avg.last_update_time;
  2582. n_last_update_time = next->avg.last_update_time;
  2583. #endif
  2584. __update_load_avg_blocked_se(p_last_update_time, cpu_of(rq_of(prev)), se);
  2585. se->avg.last_update_time = n_last_update_time;
  2586. }
  2587. /*
  2588. * When on migration a sched_entity joins/leaves the PELT hierarchy, we need to
  2589. * propagate its contribution. The key to this propagation is the invariant
  2590. * that for each group:
  2591. *
  2592. * ge->avg == grq->avg (1)
  2593. *
  2594. * _IFF_ we look at the pure running and runnable sums. Because they
  2595. * represent the very same entity, just at different points in the hierarchy.
  2596. *
  2597. * Per the above update_tg_cfs_util() is trivial and simply copies the running
  2598. * sum over (but still wrong, because the group entity and group rq do not have
  2599. * their PELT windows aligned).
  2600. *
  2601. * However, update_tg_cfs_runnable() is more complex. So we have:
  2602. *
  2603. * ge->avg.load_avg = ge->load.weight * ge->avg.runnable_avg (2)
  2604. *
  2605. * And since, like util, the runnable part should be directly transferable,
  2606. * the following would _appear_ to be the straight forward approach:
  2607. *
  2608. * grq->avg.load_avg = grq->load.weight * grq->avg.runnable_avg (3)
  2609. *
  2610. * And per (1) we have:
  2611. *
  2612. * ge->avg.runnable_avg == grq->avg.runnable_avg
  2613. *
  2614. * Which gives:
  2615. *
  2616. * ge->load.weight * grq->avg.load_avg
  2617. * ge->avg.load_avg = ----------------------------------- (4)
  2618. * grq->load.weight
  2619. *
  2620. * Except that is wrong!
  2621. *
  2622. * Because while for entities historical weight is not important and we
  2623. * really only care about our future and therefore can consider a pure
  2624. * runnable sum, runqueues can NOT do this.
  2625. *
  2626. * We specifically want runqueues to have a load_avg that includes
  2627. * historical weights. Those represent the blocked load, the load we expect
  2628. * to (shortly) return to us. This only works by keeping the weights as
  2629. * integral part of the sum. We therefore cannot decompose as per (3).
  2630. *
  2631. * Another reason this doesn't work is that runnable isn't a 0-sum entity.
  2632. * Imagine a rq with 2 tasks that each are runnable 2/3 of the time. Then the
  2633. * rq itself is runnable anywhere between 2/3 and 1 depending on how the
  2634. * runnable section of these tasks overlap (or not). If they were to perfectly
  2635. * align the rq as a whole would be runnable 2/3 of the time. If however we
  2636. * always have at least 1 runnable task, the rq as a whole is always runnable.
  2637. *
  2638. * So we'll have to approximate.. :/
  2639. *
  2640. * Given the constraint:
  2641. *
  2642. * ge->avg.running_sum <= ge->avg.runnable_sum <= LOAD_AVG_MAX
  2643. *
  2644. * We can construct a rule that adds runnable to a rq by assuming minimal
  2645. * overlap.
  2646. *
  2647. * On removal, we'll assume each task is equally runnable; which yields:
  2648. *
  2649. * grq->avg.runnable_sum = grq->avg.load_sum / grq->load.weight
  2650. *
  2651. * XXX: only do this for the part of runnable > running ?
  2652. *
  2653. */
  2654. static inline void
  2655. update_tg_cfs_util(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
  2656. {
  2657. long delta = gcfs_rq->avg.util_avg - se->avg.util_avg;
  2658. /* Nothing to update */
  2659. if (!delta)
  2660. return;
  2661. /*
  2662. * The relation between sum and avg is:
  2663. *
  2664. * LOAD_AVG_MAX - 1024 + sa->period_contrib
  2665. *
  2666. * however, the PELT windows are not aligned between grq and gse.
  2667. */
  2668. /* Set new sched_entity's utilization */
  2669. se->avg.util_avg = gcfs_rq->avg.util_avg;
  2670. se->avg.util_sum = se->avg.util_avg * LOAD_AVG_MAX;
  2671. /* Update parent cfs_rq utilization */
  2672. add_positive(&cfs_rq->avg.util_avg, delta);
  2673. cfs_rq->avg.util_sum = cfs_rq->avg.util_avg * LOAD_AVG_MAX;
  2674. }
  2675. static inline void
  2676. update_tg_cfs_runnable(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
  2677. {
  2678. long delta_avg, running_sum, runnable_sum = gcfs_rq->prop_runnable_sum;
  2679. unsigned long runnable_load_avg, load_avg;
  2680. u64 runnable_load_sum, load_sum = 0;
  2681. s64 delta_sum;
  2682. if (!runnable_sum)
  2683. return;
  2684. gcfs_rq->prop_runnable_sum = 0;
  2685. if (runnable_sum >= 0) {
  2686. /*
  2687. * Add runnable; clip at LOAD_AVG_MAX. Reflects that until
  2688. * the CPU is saturated running == runnable.
  2689. */
  2690. runnable_sum += se->avg.load_sum;
  2691. runnable_sum = min(runnable_sum, (long)LOAD_AVG_MAX);
  2692. } else {
  2693. /*
  2694. * Estimate the new unweighted runnable_sum of the gcfs_rq by
  2695. * assuming all tasks are equally runnable.
  2696. */
  2697. if (scale_load_down(gcfs_rq->load.weight)) {
  2698. load_sum = div_s64(gcfs_rq->avg.load_sum,
  2699. scale_load_down(gcfs_rq->load.weight));
  2700. }
  2701. /* But make sure to not inflate se's runnable */
  2702. runnable_sum = min(se->avg.load_sum, load_sum);
  2703. }
  2704. /*
  2705. * runnable_sum can't be lower than running_sum
  2706. * As running sum is scale with CPU capacity wehreas the runnable sum
  2707. * is not we rescale running_sum 1st
  2708. */
  2709. running_sum = se->avg.util_sum /
  2710. arch_scale_cpu_capacity(NULL, cpu_of(rq_of(cfs_rq)));
  2711. runnable_sum = max(runnable_sum, running_sum);
  2712. load_sum = (s64)se_weight(se) * runnable_sum;
  2713. load_avg = div_s64(load_sum, LOAD_AVG_MAX);
  2714. delta_sum = load_sum - (s64)se_weight(se) * se->avg.load_sum;
  2715. delta_avg = load_avg - se->avg.load_avg;
  2716. se->avg.load_sum = runnable_sum;
  2717. se->avg.load_avg = load_avg;
  2718. add_positive(&cfs_rq->avg.load_avg, delta_avg);
  2719. add_positive(&cfs_rq->avg.load_sum, delta_sum);
  2720. runnable_load_sum = (s64)se_runnable(se) * runnable_sum;
  2721. runnable_load_avg = div_s64(runnable_load_sum, LOAD_AVG_MAX);
  2722. delta_sum = runnable_load_sum - se_weight(se) * se->avg.runnable_load_sum;
  2723. delta_avg = runnable_load_avg - se->avg.runnable_load_avg;
  2724. se->avg.runnable_load_sum = runnable_sum;
  2725. se->avg.runnable_load_avg = runnable_load_avg;
  2726. if (se->on_rq) {
  2727. add_positive(&cfs_rq->avg.runnable_load_avg, delta_avg);
  2728. add_positive(&cfs_rq->avg.runnable_load_sum, delta_sum);
  2729. }
  2730. }
  2731. static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum)
  2732. {
  2733. cfs_rq->propagate = 1;
  2734. cfs_rq->prop_runnable_sum += runnable_sum;
  2735. }
  2736. /* Update task and its cfs_rq load average */
  2737. static inline int propagate_entity_load_avg(struct sched_entity *se)
  2738. {
  2739. struct cfs_rq *cfs_rq, *gcfs_rq;
  2740. if (entity_is_task(se))
  2741. return 0;
  2742. gcfs_rq = group_cfs_rq(se);
  2743. if (!gcfs_rq->propagate)
  2744. return 0;
  2745. gcfs_rq->propagate = 0;
  2746. cfs_rq = cfs_rq_of(se);
  2747. add_tg_cfs_propagate(cfs_rq, gcfs_rq->prop_runnable_sum);
  2748. update_tg_cfs_util(cfs_rq, se, gcfs_rq);
  2749. update_tg_cfs_runnable(cfs_rq, se, gcfs_rq);
  2750. return 1;
  2751. }
  2752. /*
  2753. * Check if we need to update the load and the utilization of a blocked
  2754. * group_entity:
  2755. */
  2756. static inline bool skip_blocked_update(struct sched_entity *se)
  2757. {
  2758. struct cfs_rq *gcfs_rq = group_cfs_rq(se);
  2759. /*
  2760. * If sched_entity still have not zero load or utilization, we have to
  2761. * decay it:
  2762. */
  2763. if (se->avg.load_avg || se->avg.util_avg)
  2764. return false;
  2765. /*
  2766. * If there is a pending propagation, we have to update the load and
  2767. * the utilization of the sched_entity:
  2768. */
  2769. if (gcfs_rq->propagate)
  2770. return false;
  2771. /*
  2772. * Otherwise, the load and the utilization of the sched_entity is
  2773. * already zero and there is no pending propagation, so it will be a
  2774. * waste of time to try to decay it:
  2775. */
  2776. return true;
  2777. }
  2778. #else /* CONFIG_FAIR_GROUP_SCHED */
  2779. static inline void update_tg_load_avg(struct cfs_rq *cfs_rq, int force) {}
  2780. static inline int propagate_entity_load_avg(struct sched_entity *se)
  2781. {
  2782. return 0;
  2783. }
  2784. static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum) {}
  2785. #endif /* CONFIG_FAIR_GROUP_SCHED */
  2786. /**
  2787. * update_cfs_rq_load_avg - update the cfs_rq's load/util averages
  2788. * @now: current time, as per cfs_rq_clock_task()
  2789. * @cfs_rq: cfs_rq to update
  2790. *
  2791. * The cfs_rq avg is the direct sum of all its entities (blocked and runnable)
  2792. * avg. The immediate corollary is that all (fair) tasks must be attached, see
  2793. * post_init_entity_util_avg().
  2794. *
  2795. * cfs_rq->avg is used for task_h_load() and update_cfs_share() for example.
  2796. *
  2797. * Returns true if the load decayed or we removed load.
  2798. *
  2799. * Since both these conditions indicate a changed cfs_rq->avg.load we should
  2800. * call update_tg_load_avg() when this function returns true.
  2801. */
  2802. static inline int
  2803. update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq)
  2804. {
  2805. unsigned long removed_load = 0, removed_util = 0, removed_runnable_sum = 0;
  2806. struct sched_avg *sa = &cfs_rq->avg;
  2807. int decayed = 0;
  2808. if (cfs_rq->removed.nr) {
  2809. unsigned long r;
  2810. u32 divider = LOAD_AVG_MAX - 1024 + sa->period_contrib;
  2811. raw_spin_lock(&cfs_rq->removed.lock);
  2812. swap(cfs_rq->removed.util_avg, removed_util);
  2813. swap(cfs_rq->removed.load_avg, removed_load);
  2814. swap(cfs_rq->removed.runnable_sum, removed_runnable_sum);
  2815. cfs_rq->removed.nr = 0;
  2816. raw_spin_unlock(&cfs_rq->removed.lock);
  2817. r = removed_load;
  2818. sub_positive(&sa->load_avg, r);
  2819. sub_positive(&sa->load_sum, r * divider);
  2820. r = removed_util;
  2821. sub_positive(&sa->util_avg, r);
  2822. sub_positive(&sa->util_sum, r * divider);
  2823. add_tg_cfs_propagate(cfs_rq, -(long)removed_runnable_sum);
  2824. decayed = 1;
  2825. }
  2826. decayed |= __update_load_avg_cfs_rq(now, cpu_of(rq_of(cfs_rq)), cfs_rq);
  2827. #ifndef CONFIG_64BIT
  2828. smp_wmb();
  2829. cfs_rq->load_last_update_time_copy = sa->last_update_time;
  2830. #endif
  2831. if (decayed)
  2832. cfs_rq_util_change(cfs_rq, 0);
  2833. return decayed;
  2834. }
  2835. /**
  2836. * attach_entity_load_avg - attach this entity to its cfs_rq load avg
  2837. * @cfs_rq: cfs_rq to attach to
  2838. * @se: sched_entity to attach
  2839. *
  2840. * Must call update_cfs_rq_load_avg() before this, since we rely on
  2841. * cfs_rq->avg.last_update_time being current.
  2842. */
  2843. static void attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
  2844. {
  2845. u32 divider = LOAD_AVG_MAX - 1024 + cfs_rq->avg.period_contrib;
  2846. /*
  2847. * When we attach the @se to the @cfs_rq, we must align the decay
  2848. * window because without that, really weird and wonderful things can
  2849. * happen.
  2850. *
  2851. * XXX illustrate
  2852. */
  2853. se->avg.last_update_time = cfs_rq->avg.last_update_time;
  2854. se->avg.period_contrib = cfs_rq->avg.period_contrib;
  2855. /*
  2856. * Hell(o) Nasty stuff.. we need to recompute _sum based on the new
  2857. * period_contrib. This isn't strictly correct, but since we're
  2858. * entirely outside of the PELT hierarchy, nobody cares if we truncate
  2859. * _sum a little.
  2860. */
  2861. se->avg.util_sum = se->avg.util_avg * divider;
  2862. se->avg.load_sum = divider;
  2863. if (se_weight(se)) {
  2864. se->avg.load_sum =
  2865. div_u64(se->avg.load_avg * se->avg.load_sum, se_weight(se));
  2866. }
  2867. se->avg.runnable_load_sum = se->avg.load_sum;
  2868. enqueue_load_avg(cfs_rq, se);
  2869. cfs_rq->avg.util_avg += se->avg.util_avg;
  2870. cfs_rq->avg.util_sum += se->avg.util_sum;
  2871. add_tg_cfs_propagate(cfs_rq, se->avg.load_sum);
  2872. cfs_rq_util_change(cfs_rq, flags);
  2873. }
  2874. /**
  2875. * detach_entity_load_avg - detach this entity from its cfs_rq load avg
  2876. * @cfs_rq: cfs_rq to detach from
  2877. * @se: sched_entity to detach
  2878. *
  2879. * Must call update_cfs_rq_load_avg() before this, since we rely on
  2880. * cfs_rq->avg.last_update_time being current.
  2881. */
  2882. static void detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
  2883. {
  2884. dequeue_load_avg(cfs_rq, se);
  2885. sub_positive(&cfs_rq->avg.util_avg, se->avg.util_avg);
  2886. sub_positive(&cfs_rq->avg.util_sum, se->avg.util_sum);
  2887. add_tg_cfs_propagate(cfs_rq, -se->avg.load_sum);
  2888. cfs_rq_util_change(cfs_rq, 0);
  2889. }
  2890. /*
  2891. * Optional action to be done while updating the load average
  2892. */
  2893. #define UPDATE_TG 0x1
  2894. #define SKIP_AGE_LOAD 0x2
  2895. #define DO_ATTACH 0x4
  2896. /* Update task and its cfs_rq load average */
  2897. static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
  2898. {
  2899. u64 now = cfs_rq_clock_task(cfs_rq);
  2900. struct rq *rq = rq_of(cfs_rq);
  2901. int cpu = cpu_of(rq);
  2902. int decayed;
  2903. /*
  2904. * Track task load average for carrying it to new CPU after migrated, and
  2905. * track group sched_entity load average for task_h_load calc in migration
  2906. */
  2907. if (se->avg.last_update_time && !(flags & SKIP_AGE_LOAD))
  2908. __update_load_avg_se(now, cpu, cfs_rq, se);
  2909. decayed = update_cfs_rq_load_avg(now, cfs_rq);
  2910. decayed |= propagate_entity_load_avg(se);
  2911. if (!se->avg.last_update_time && (flags & DO_ATTACH)) {
  2912. /*
  2913. * DO_ATTACH means we're here from enqueue_entity().
  2914. * !last_update_time means we've passed through
  2915. * migrate_task_rq_fair() indicating we migrated.
  2916. *
  2917. * IOW we're enqueueing a task on a new CPU.
  2918. */
  2919. attach_entity_load_avg(cfs_rq, se, SCHED_CPUFREQ_MIGRATION);
  2920. update_tg_load_avg(cfs_rq, 0);
  2921. } else if (decayed && (flags & UPDATE_TG))
  2922. update_tg_load_avg(cfs_rq, 0);
  2923. }
  2924. #ifndef CONFIG_64BIT
  2925. static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq)
  2926. {
  2927. u64 last_update_time_copy;
  2928. u64 last_update_time;
  2929. do {
  2930. last_update_time_copy = cfs_rq->load_last_update_time_copy;
  2931. smp_rmb();
  2932. last_update_time = cfs_rq->avg.last_update_time;
  2933. } while (last_update_time != last_update_time_copy);
  2934. return last_update_time;
  2935. }
  2936. #else
  2937. static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq)
  2938. {
  2939. return cfs_rq->avg.last_update_time;
  2940. }
  2941. #endif
  2942. /*
  2943. * Synchronize entity load avg of dequeued entity without locking
  2944. * the previous rq.
  2945. */
  2946. void sync_entity_load_avg(struct sched_entity *se)
  2947. {
  2948. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  2949. u64 last_update_time;
  2950. last_update_time = cfs_rq_last_update_time(cfs_rq);
  2951. __update_load_avg_blocked_se(last_update_time, cpu_of(rq_of(cfs_rq)), se);
  2952. }
  2953. /*
  2954. * Task first catches up with cfs_rq, and then subtract
  2955. * itself from the cfs_rq (task must be off the queue now).
  2956. */
  2957. void remove_entity_load_avg(struct sched_entity *se)
  2958. {
  2959. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  2960. unsigned long flags;
  2961. /*
  2962. * tasks cannot exit without having gone through wake_up_new_task() ->
  2963. * post_init_entity_util_avg() which will have added things to the
  2964. * cfs_rq, so we can remove unconditionally.
  2965. *
  2966. * Similarly for groups, they will have passed through
  2967. * post_init_entity_util_avg() before unregister_sched_fair_group()
  2968. * calls this.
  2969. */
  2970. sync_entity_load_avg(se);
  2971. raw_spin_lock_irqsave(&cfs_rq->removed.lock, flags);
  2972. ++cfs_rq->removed.nr;
  2973. cfs_rq->removed.util_avg += se->avg.util_avg;
  2974. cfs_rq->removed.load_avg += se->avg.load_avg;
  2975. cfs_rq->removed.runnable_sum += se->avg.load_sum; /* == runnable_sum */
  2976. raw_spin_unlock_irqrestore(&cfs_rq->removed.lock, flags);
  2977. }
  2978. static inline unsigned long cfs_rq_runnable_load_avg(struct cfs_rq *cfs_rq)
  2979. {
  2980. return cfs_rq->avg.runnable_load_avg;
  2981. }
  2982. static inline unsigned long cfs_rq_load_avg(struct cfs_rq *cfs_rq)
  2983. {
  2984. return cfs_rq->avg.load_avg;
  2985. }
  2986. static int idle_balance(struct rq *this_rq, struct rq_flags *rf);
  2987. static inline unsigned long task_util(struct task_struct *p)
  2988. {
  2989. return READ_ONCE(p->se.avg.util_avg);
  2990. }
  2991. static inline unsigned long _task_util_est(struct task_struct *p)
  2992. {
  2993. struct util_est ue = READ_ONCE(p->se.avg.util_est);
  2994. return max(ue.ewma, ue.enqueued);
  2995. }
  2996. static inline unsigned long task_util_est(struct task_struct *p)
  2997. {
  2998. return max(task_util(p), _task_util_est(p));
  2999. }
  3000. static inline void util_est_enqueue(struct cfs_rq *cfs_rq,
  3001. struct task_struct *p)
  3002. {
  3003. unsigned int enqueued;
  3004. if (!sched_feat(UTIL_EST))
  3005. return;
  3006. /* Update root cfs_rq's estimated utilization */
  3007. enqueued = cfs_rq->avg.util_est.enqueued;
  3008. enqueued += (_task_util_est(p) | UTIL_AVG_UNCHANGED);
  3009. WRITE_ONCE(cfs_rq->avg.util_est.enqueued, enqueued);
  3010. }
  3011. /*
  3012. * Check if a (signed) value is within a specified (unsigned) margin,
  3013. * based on the observation that:
  3014. *
  3015. * abs(x) < y := (unsigned)(x + y - 1) < (2 * y - 1)
  3016. *
  3017. * NOTE: this only works when value + maring < INT_MAX.
  3018. */
  3019. static inline bool within_margin(int value, int margin)
  3020. {
  3021. return ((unsigned int)(value + margin - 1) < (2 * margin - 1));
  3022. }
  3023. static void
  3024. util_est_dequeue(struct cfs_rq *cfs_rq, struct task_struct *p, bool task_sleep)
  3025. {
  3026. long last_ewma_diff;
  3027. struct util_est ue;
  3028. if (!sched_feat(UTIL_EST))
  3029. return;
  3030. /* Update root cfs_rq's estimated utilization */
  3031. ue.enqueued = cfs_rq->avg.util_est.enqueued;
  3032. ue.enqueued -= min_t(unsigned int, ue.enqueued,
  3033. (_task_util_est(p) | UTIL_AVG_UNCHANGED));
  3034. WRITE_ONCE(cfs_rq->avg.util_est.enqueued, ue.enqueued);
  3035. /*
  3036. * Skip update of task's estimated utilization when the task has not
  3037. * yet completed an activation, e.g. being migrated.
  3038. */
  3039. if (!task_sleep)
  3040. return;
  3041. /*
  3042. * If the PELT values haven't changed since enqueue time,
  3043. * skip the util_est update.
  3044. */
  3045. ue = p->se.avg.util_est;
  3046. if (ue.enqueued & UTIL_AVG_UNCHANGED)
  3047. return;
  3048. /*
  3049. * Skip update of task's estimated utilization when its EWMA is
  3050. * already ~1% close to its last activation value.
  3051. */
  3052. ue.enqueued = (task_util(p) | UTIL_AVG_UNCHANGED);
  3053. last_ewma_diff = ue.enqueued - ue.ewma;
  3054. if (within_margin(last_ewma_diff, (SCHED_CAPACITY_SCALE / 100)))
  3055. return;
  3056. /*
  3057. * Update Task's estimated utilization
  3058. *
  3059. * When *p completes an activation we can consolidate another sample
  3060. * of the task size. This is done by storing the current PELT value
  3061. * as ue.enqueued and by using this value to update the Exponential
  3062. * Weighted Moving Average (EWMA):
  3063. *
  3064. * ewma(t) = w * task_util(p) + (1-w) * ewma(t-1)
  3065. * = w * task_util(p) + ewma(t-1) - w * ewma(t-1)
  3066. * = w * (task_util(p) - ewma(t-1)) + ewma(t-1)
  3067. * = w * ( last_ewma_diff ) + ewma(t-1)
  3068. * = w * (last_ewma_diff + ewma(t-1) / w)
  3069. *
  3070. * Where 'w' is the weight of new samples, which is configured to be
  3071. * 0.25, thus making w=1/4 ( >>= UTIL_EST_WEIGHT_SHIFT)
  3072. */
  3073. ue.ewma <<= UTIL_EST_WEIGHT_SHIFT;
  3074. ue.ewma += last_ewma_diff;
  3075. ue.ewma >>= UTIL_EST_WEIGHT_SHIFT;
  3076. WRITE_ONCE(p->se.avg.util_est, ue);
  3077. }
  3078. #else /* CONFIG_SMP */
  3079. #define UPDATE_TG 0x0
  3080. #define SKIP_AGE_LOAD 0x0
  3081. #define DO_ATTACH 0x0
  3082. static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int not_used1)
  3083. {
  3084. cfs_rq_util_change(cfs_rq, 0);
  3085. }
  3086. static inline void remove_entity_load_avg(struct sched_entity *se) {}
  3087. static inline void
  3088. attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) {}
  3089. static inline void
  3090. detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
  3091. static inline int idle_balance(struct rq *rq, struct rq_flags *rf)
  3092. {
  3093. return 0;
  3094. }
  3095. static inline void
  3096. util_est_enqueue(struct cfs_rq *cfs_rq, struct task_struct *p) {}
  3097. static inline void
  3098. util_est_dequeue(struct cfs_rq *cfs_rq, struct task_struct *p,
  3099. bool task_sleep) {}
  3100. #endif /* CONFIG_SMP */
  3101. static void check_spread(struct cfs_rq *cfs_rq, struct sched_entity *se)
  3102. {
  3103. #ifdef CONFIG_SCHED_DEBUG
  3104. s64 d = se->vruntime - cfs_rq->min_vruntime;
  3105. if (d < 0)
  3106. d = -d;
  3107. if (d > 3*sysctl_sched_latency)
  3108. schedstat_inc(cfs_rq->nr_spread_over);
  3109. #endif
  3110. }
  3111. static void
  3112. place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int initial)
  3113. {
  3114. u64 vruntime = cfs_rq->min_vruntime;
  3115. /*
  3116. * The 'current' period is already promised to the current tasks,
  3117. * however the extra weight of the new task will slow them down a
  3118. * little, place the new task so that it fits in the slot that
  3119. * stays open at the end.
  3120. */
  3121. if (initial && sched_feat(START_DEBIT))
  3122. vruntime += sched_vslice(cfs_rq, se);
  3123. /* sleeps up to a single latency don't count. */
  3124. if (!initial) {
  3125. unsigned long thresh = sysctl_sched_latency;
  3126. /*
  3127. * Halve their sleep time's effect, to allow
  3128. * for a gentler effect of sleepers:
  3129. */
  3130. if (sched_feat(GENTLE_FAIR_SLEEPERS))
  3131. thresh >>= 1;
  3132. vruntime -= thresh;
  3133. }
  3134. /* ensure we never gain time by being placed backwards. */
  3135. se->vruntime = max_vruntime(se->vruntime, vruntime);
  3136. }
  3137. static void check_enqueue_throttle(struct cfs_rq *cfs_rq);
  3138. static inline void check_schedstat_required(void)
  3139. {
  3140. #ifdef CONFIG_SCHEDSTATS
  3141. if (schedstat_enabled())
  3142. return;
  3143. /* Force schedstat enabled if a dependent tracepoint is active */
  3144. if (trace_sched_stat_wait_enabled() ||
  3145. trace_sched_stat_sleep_enabled() ||
  3146. trace_sched_stat_iowait_enabled() ||
  3147. trace_sched_stat_blocked_enabled() ||
  3148. trace_sched_stat_runtime_enabled()) {
  3149. printk_deferred_once("Scheduler tracepoints stat_sleep, stat_iowait, "
  3150. "stat_blocked and stat_runtime require the "
  3151. "kernel parameter schedstats=enable or "
  3152. "kernel.sched_schedstats=1\n");
  3153. }
  3154. #endif
  3155. }
  3156. /*
  3157. * MIGRATION
  3158. *
  3159. * dequeue
  3160. * update_curr()
  3161. * update_min_vruntime()
  3162. * vruntime -= min_vruntime
  3163. *
  3164. * enqueue
  3165. * update_curr()
  3166. * update_min_vruntime()
  3167. * vruntime += min_vruntime
  3168. *
  3169. * this way the vruntime transition between RQs is done when both
  3170. * min_vruntime are up-to-date.
  3171. *
  3172. * WAKEUP (remote)
  3173. *
  3174. * ->migrate_task_rq_fair() (p->state == TASK_WAKING)
  3175. * vruntime -= min_vruntime
  3176. *
  3177. * enqueue
  3178. * update_curr()
  3179. * update_min_vruntime()
  3180. * vruntime += min_vruntime
  3181. *
  3182. * this way we don't have the most up-to-date min_vruntime on the originating
  3183. * CPU and an up-to-date min_vruntime on the destination CPU.
  3184. */
  3185. static void
  3186. enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
  3187. {
  3188. bool renorm = !(flags & ENQUEUE_WAKEUP) || (flags & ENQUEUE_MIGRATED);
  3189. bool curr = cfs_rq->curr == se;
  3190. /*
  3191. * If we're the current task, we must renormalise before calling
  3192. * update_curr().
  3193. */
  3194. if (renorm && curr)
  3195. se->vruntime += cfs_rq->min_vruntime;
  3196. update_curr(cfs_rq);
  3197. /*
  3198. * Otherwise, renormalise after, such that we're placed at the current
  3199. * moment in time, instead of some random moment in the past. Being
  3200. * placed in the past could significantly boost this task to the
  3201. * fairness detriment of existing tasks.
  3202. */
  3203. if (renorm && !curr)
  3204. se->vruntime += cfs_rq->min_vruntime;
  3205. /*
  3206. * When enqueuing a sched_entity, we must:
  3207. * - Update loads to have both entity and cfs_rq synced with now.
  3208. * - Add its load to cfs_rq->runnable_avg
  3209. * - For group_entity, update its weight to reflect the new share of
  3210. * its group cfs_rq
  3211. * - Add its new weight to cfs_rq->load.weight
  3212. */
  3213. update_load_avg(cfs_rq, se, UPDATE_TG | DO_ATTACH);
  3214. update_cfs_group(se);
  3215. enqueue_runnable_load_avg(cfs_rq, se);
  3216. account_entity_enqueue(cfs_rq, se);
  3217. if (flags & ENQUEUE_WAKEUP)
  3218. place_entity(cfs_rq, se, 0);
  3219. check_schedstat_required();
  3220. update_stats_enqueue(cfs_rq, se, flags);
  3221. check_spread(cfs_rq, se);
  3222. if (!curr)
  3223. __enqueue_entity(cfs_rq, se);
  3224. se->on_rq = 1;
  3225. if (cfs_rq->nr_running == 1) {
  3226. list_add_leaf_cfs_rq(cfs_rq);
  3227. check_enqueue_throttle(cfs_rq);
  3228. }
  3229. }
  3230. static void __clear_buddies_last(struct sched_entity *se)
  3231. {
  3232. for_each_sched_entity(se) {
  3233. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  3234. if (cfs_rq->last != se)
  3235. break;
  3236. cfs_rq->last = NULL;
  3237. }
  3238. }
  3239. static void __clear_buddies_next(struct sched_entity *se)
  3240. {
  3241. for_each_sched_entity(se) {
  3242. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  3243. if (cfs_rq->next != se)
  3244. break;
  3245. cfs_rq->next = NULL;
  3246. }
  3247. }
  3248. static void __clear_buddies_skip(struct sched_entity *se)
  3249. {
  3250. for_each_sched_entity(se) {
  3251. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  3252. if (cfs_rq->skip != se)
  3253. break;
  3254. cfs_rq->skip = NULL;
  3255. }
  3256. }
  3257. static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
  3258. {
  3259. if (cfs_rq->last == se)
  3260. __clear_buddies_last(se);
  3261. if (cfs_rq->next == se)
  3262. __clear_buddies_next(se);
  3263. if (cfs_rq->skip == se)
  3264. __clear_buddies_skip(se);
  3265. }
  3266. static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq);
  3267. static void
  3268. dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
  3269. {
  3270. /*
  3271. * Update run-time statistics of the 'current'.
  3272. */
  3273. update_curr(cfs_rq);
  3274. /*
  3275. * When dequeuing a sched_entity, we must:
  3276. * - Update loads to have both entity and cfs_rq synced with now.
  3277. * - Substract its load from the cfs_rq->runnable_avg.
  3278. * - Substract its previous weight from cfs_rq->load.weight.
  3279. * - For group entity, update its weight to reflect the new share
  3280. * of its group cfs_rq.
  3281. */
  3282. update_load_avg(cfs_rq, se, UPDATE_TG);
  3283. dequeue_runnable_load_avg(cfs_rq, se);
  3284. update_stats_dequeue(cfs_rq, se, flags);
  3285. clear_buddies(cfs_rq, se);
  3286. if (se != cfs_rq->curr)
  3287. __dequeue_entity(cfs_rq, se);
  3288. se->on_rq = 0;
  3289. account_entity_dequeue(cfs_rq, se);
  3290. /*
  3291. * Normalize after update_curr(); which will also have moved
  3292. * min_vruntime if @se is the one holding it back. But before doing
  3293. * update_min_vruntime() again, which will discount @se's position and
  3294. * can move min_vruntime forward still more.
  3295. */
  3296. if (!(flags & DEQUEUE_SLEEP))
  3297. se->vruntime -= cfs_rq->min_vruntime;
  3298. /* return excess runtime on last dequeue */
  3299. return_cfs_rq_runtime(cfs_rq);
  3300. update_cfs_group(se);
  3301. /*
  3302. * Now advance min_vruntime if @se was the entity holding it back,
  3303. * except when: DEQUEUE_SAVE && !DEQUEUE_MOVE, in this case we'll be
  3304. * put back on, and if we advance min_vruntime, we'll be placed back
  3305. * further than we started -- ie. we'll be penalized.
  3306. */
  3307. if ((flags & (DEQUEUE_SAVE | DEQUEUE_MOVE)) == DEQUEUE_SAVE)
  3308. update_min_vruntime(cfs_rq);
  3309. }
  3310. /*
  3311. * Preempt the current task with a newly woken task if needed:
  3312. */
  3313. static void
  3314. check_preempt_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr)
  3315. {
  3316. unsigned long ideal_runtime, delta_exec;
  3317. struct sched_entity *se;
  3318. s64 delta;
  3319. ideal_runtime = sched_slice(cfs_rq, curr);
  3320. delta_exec = curr->sum_exec_runtime - curr->prev_sum_exec_runtime;
  3321. if (delta_exec > ideal_runtime) {
  3322. resched_curr(rq_of(cfs_rq));
  3323. /*
  3324. * The current task ran long enough, ensure it doesn't get
  3325. * re-elected due to buddy favours.
  3326. */
  3327. clear_buddies(cfs_rq, curr);
  3328. return;
  3329. }
  3330. /*
  3331. * Ensure that a task that missed wakeup preemption by a
  3332. * narrow margin doesn't have to wait for a full slice.
  3333. * This also mitigates buddy induced latencies under load.
  3334. */
  3335. if (delta_exec < sysctl_sched_min_granularity)
  3336. return;
  3337. se = __pick_first_entity(cfs_rq);
  3338. delta = curr->vruntime - se->vruntime;
  3339. if (delta < 0)
  3340. return;
  3341. if (delta > ideal_runtime)
  3342. resched_curr(rq_of(cfs_rq));
  3343. }
  3344. static void
  3345. set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
  3346. {
  3347. /* 'current' is not kept within the tree. */
  3348. if (se->on_rq) {
  3349. /*
  3350. * Any task has to be enqueued before it get to execute on
  3351. * a CPU. So account for the time it spent waiting on the
  3352. * runqueue.
  3353. */
  3354. update_stats_wait_end(cfs_rq, se);
  3355. __dequeue_entity(cfs_rq, se);
  3356. update_load_avg(cfs_rq, se, UPDATE_TG);
  3357. }
  3358. update_stats_curr_start(cfs_rq, se);
  3359. cfs_rq->curr = se;
  3360. /*
  3361. * Track our maximum slice length, if the CPU's load is at
  3362. * least twice that of our own weight (i.e. dont track it
  3363. * when there are only lesser-weight tasks around):
  3364. */
  3365. if (schedstat_enabled() && rq_of(cfs_rq)->load.weight >= 2*se->load.weight) {
  3366. schedstat_set(se->statistics.slice_max,
  3367. max((u64)schedstat_val(se->statistics.slice_max),
  3368. se->sum_exec_runtime - se->prev_sum_exec_runtime));
  3369. }
  3370. se->prev_sum_exec_runtime = se->sum_exec_runtime;
  3371. }
  3372. static int
  3373. wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se);
  3374. /*
  3375. * Pick the next process, keeping these things in mind, in this order:
  3376. * 1) keep things fair between processes/task groups
  3377. * 2) pick the "next" process, since someone really wants that to run
  3378. * 3) pick the "last" process, for cache locality
  3379. * 4) do not run the "skip" process, if something else is available
  3380. */
  3381. static struct sched_entity *
  3382. pick_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *curr)
  3383. {
  3384. struct sched_entity *left = __pick_first_entity(cfs_rq);
  3385. struct sched_entity *se;
  3386. /*
  3387. * If curr is set we have to see if its left of the leftmost entity
  3388. * still in the tree, provided there was anything in the tree at all.
  3389. */
  3390. if (!left || (curr && entity_before(curr, left)))
  3391. left = curr;
  3392. se = left; /* ideally we run the leftmost entity */
  3393. /*
  3394. * Avoid running the skip buddy, if running something else can
  3395. * be done without getting too unfair.
  3396. */
  3397. if (cfs_rq->skip == se) {
  3398. struct sched_entity *second;
  3399. if (se == curr) {
  3400. second = __pick_first_entity(cfs_rq);
  3401. } else {
  3402. second = __pick_next_entity(se);
  3403. if (!second || (curr && entity_before(curr, second)))
  3404. second = curr;
  3405. }
  3406. if (second && wakeup_preempt_entity(second, left) < 1)
  3407. se = second;
  3408. }
  3409. /*
  3410. * Prefer last buddy, try to return the CPU to a preempted task.
  3411. */
  3412. if (cfs_rq->last && wakeup_preempt_entity(cfs_rq->last, left) < 1)
  3413. se = cfs_rq->last;
  3414. /*
  3415. * Someone really wants this to run. If it's not unfair, run it.
  3416. */
  3417. if (cfs_rq->next && wakeup_preempt_entity(cfs_rq->next, left) < 1)
  3418. se = cfs_rq->next;
  3419. clear_buddies(cfs_rq, se);
  3420. return se;
  3421. }
  3422. static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq);
  3423. static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
  3424. {
  3425. /*
  3426. * If still on the runqueue then deactivate_task()
  3427. * was not called and update_curr() has to be done:
  3428. */
  3429. if (prev->on_rq)
  3430. update_curr(cfs_rq);
  3431. /* throttle cfs_rqs exceeding runtime */
  3432. check_cfs_rq_runtime(cfs_rq);
  3433. check_spread(cfs_rq, prev);
  3434. if (prev->on_rq) {
  3435. update_stats_wait_start(cfs_rq, prev);
  3436. /* Put 'current' back into the tree. */
  3437. __enqueue_entity(cfs_rq, prev);
  3438. /* in !on_rq case, update occurred at dequeue */
  3439. update_load_avg(cfs_rq, prev, 0);
  3440. }
  3441. cfs_rq->curr = NULL;
  3442. }
  3443. static void
  3444. entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
  3445. {
  3446. /*
  3447. * Update run-time statistics of the 'current'.
  3448. */
  3449. update_curr(cfs_rq);
  3450. /*
  3451. * Ensure that runnable average is periodically updated.
  3452. */
  3453. update_load_avg(cfs_rq, curr, UPDATE_TG);
  3454. update_cfs_group(curr);
  3455. #ifdef CONFIG_SCHED_HRTICK
  3456. /*
  3457. * queued ticks are scheduled to match the slice, so don't bother
  3458. * validating it and just reschedule.
  3459. */
  3460. if (queued) {
  3461. resched_curr(rq_of(cfs_rq));
  3462. return;
  3463. }
  3464. /*
  3465. * don't let the period tick interfere with the hrtick preemption
  3466. */
  3467. if (!sched_feat(DOUBLE_TICK) &&
  3468. hrtimer_active(&rq_of(cfs_rq)->hrtick_timer))
  3469. return;
  3470. #endif
  3471. if (cfs_rq->nr_running > 1)
  3472. check_preempt_tick(cfs_rq, curr);
  3473. }
  3474. /**************************************************
  3475. * CFS bandwidth control machinery
  3476. */
  3477. #ifdef CONFIG_CFS_BANDWIDTH
  3478. #ifdef HAVE_JUMP_LABEL
  3479. static struct static_key __cfs_bandwidth_used;
  3480. static inline bool cfs_bandwidth_used(void)
  3481. {
  3482. return static_key_false(&__cfs_bandwidth_used);
  3483. }
  3484. void cfs_bandwidth_usage_inc(void)
  3485. {
  3486. static_key_slow_inc_cpuslocked(&__cfs_bandwidth_used);
  3487. }
  3488. void cfs_bandwidth_usage_dec(void)
  3489. {
  3490. static_key_slow_dec_cpuslocked(&__cfs_bandwidth_used);
  3491. }
  3492. #else /* HAVE_JUMP_LABEL */
  3493. static bool cfs_bandwidth_used(void)
  3494. {
  3495. return true;
  3496. }
  3497. void cfs_bandwidth_usage_inc(void) {}
  3498. void cfs_bandwidth_usage_dec(void) {}
  3499. #endif /* HAVE_JUMP_LABEL */
  3500. /*
  3501. * default period for cfs group bandwidth.
  3502. * default: 0.1s, units: nanoseconds
  3503. */
  3504. static inline u64 default_cfs_period(void)
  3505. {
  3506. return 100000000ULL;
  3507. }
  3508. static inline u64 sched_cfs_bandwidth_slice(void)
  3509. {
  3510. return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC;
  3511. }
  3512. /*
  3513. * Replenish runtime according to assigned quota and update expiration time.
  3514. * We use sched_clock_cpu directly instead of rq->clock to avoid adding
  3515. * additional synchronization around rq->lock.
  3516. *
  3517. * requires cfs_b->lock
  3518. */
  3519. void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
  3520. {
  3521. u64 now;
  3522. if (cfs_b->quota == RUNTIME_INF)
  3523. return;
  3524. now = sched_clock_cpu(smp_processor_id());
  3525. cfs_b->runtime = cfs_b->quota;
  3526. cfs_b->runtime_expires = now + ktime_to_ns(cfs_b->period);
  3527. cfs_b->expires_seq++;
  3528. }
  3529. static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
  3530. {
  3531. return &tg->cfs_bandwidth;
  3532. }
  3533. /* rq->task_clock normalized against any time this cfs_rq has spent throttled */
  3534. static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq)
  3535. {
  3536. if (unlikely(cfs_rq->throttle_count))
  3537. return cfs_rq->throttled_clock_task - cfs_rq->throttled_clock_task_time;
  3538. return rq_clock_task(rq_of(cfs_rq)) - cfs_rq->throttled_clock_task_time;
  3539. }
  3540. /* returns 0 on failure to allocate runtime */
  3541. static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  3542. {
  3543. struct task_group *tg = cfs_rq->tg;
  3544. struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(tg);
  3545. u64 amount = 0, min_amount, expires;
  3546. int expires_seq;
  3547. /* note: this is a positive sum as runtime_remaining <= 0 */
  3548. min_amount = sched_cfs_bandwidth_slice() - cfs_rq->runtime_remaining;
  3549. raw_spin_lock(&cfs_b->lock);
  3550. if (cfs_b->quota == RUNTIME_INF)
  3551. amount = min_amount;
  3552. else {
  3553. start_cfs_bandwidth(cfs_b);
  3554. if (cfs_b->runtime > 0) {
  3555. amount = min(cfs_b->runtime, min_amount);
  3556. cfs_b->runtime -= amount;
  3557. cfs_b->idle = 0;
  3558. }
  3559. }
  3560. expires_seq = cfs_b->expires_seq;
  3561. expires = cfs_b->runtime_expires;
  3562. raw_spin_unlock(&cfs_b->lock);
  3563. cfs_rq->runtime_remaining += amount;
  3564. /*
  3565. * we may have advanced our local expiration to account for allowed
  3566. * spread between our sched_clock and the one on which runtime was
  3567. * issued.
  3568. */
  3569. if (cfs_rq->expires_seq != expires_seq) {
  3570. cfs_rq->expires_seq = expires_seq;
  3571. cfs_rq->runtime_expires = expires;
  3572. }
  3573. return cfs_rq->runtime_remaining > 0;
  3574. }
  3575. /*
  3576. * Note: This depends on the synchronization provided by sched_clock and the
  3577. * fact that rq->clock snapshots this value.
  3578. */
  3579. static void expire_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  3580. {
  3581. struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
  3582. /* if the deadline is ahead of our clock, nothing to do */
  3583. if (likely((s64)(rq_clock(rq_of(cfs_rq)) - cfs_rq->runtime_expires) < 0))
  3584. return;
  3585. if (cfs_rq->runtime_remaining < 0)
  3586. return;
  3587. /*
  3588. * If the local deadline has passed we have to consider the
  3589. * possibility that our sched_clock is 'fast' and the global deadline
  3590. * has not truly expired.
  3591. *
  3592. * Fortunately we can check determine whether this the case by checking
  3593. * whether the global deadline(cfs_b->expires_seq) has advanced.
  3594. */
  3595. if (cfs_rq->expires_seq == cfs_b->expires_seq) {
  3596. /* extend local deadline, drift is bounded above by 2 ticks */
  3597. cfs_rq->runtime_expires += TICK_NSEC;
  3598. } else {
  3599. /* global deadline is ahead, expiration has passed */
  3600. cfs_rq->runtime_remaining = 0;
  3601. }
  3602. }
  3603. static void __account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
  3604. {
  3605. /* dock delta_exec before expiring quota (as it could span periods) */
  3606. cfs_rq->runtime_remaining -= delta_exec;
  3607. expire_cfs_rq_runtime(cfs_rq);
  3608. if (likely(cfs_rq->runtime_remaining > 0))
  3609. return;
  3610. /*
  3611. * if we're unable to extend our runtime we resched so that the active
  3612. * hierarchy can be throttled
  3613. */
  3614. if (!assign_cfs_rq_runtime(cfs_rq) && likely(cfs_rq->curr))
  3615. resched_curr(rq_of(cfs_rq));
  3616. }
  3617. static __always_inline
  3618. void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
  3619. {
  3620. if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled)
  3621. return;
  3622. __account_cfs_rq_runtime(cfs_rq, delta_exec);
  3623. }
  3624. static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
  3625. {
  3626. return cfs_bandwidth_used() && cfs_rq->throttled;
  3627. }
  3628. /* check whether cfs_rq, or any parent, is throttled */
  3629. static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
  3630. {
  3631. return cfs_bandwidth_used() && cfs_rq->throttle_count;
  3632. }
  3633. /*
  3634. * Ensure that neither of the group entities corresponding to src_cpu or
  3635. * dest_cpu are members of a throttled hierarchy when performing group
  3636. * load-balance operations.
  3637. */
  3638. static inline int throttled_lb_pair(struct task_group *tg,
  3639. int src_cpu, int dest_cpu)
  3640. {
  3641. struct cfs_rq *src_cfs_rq, *dest_cfs_rq;
  3642. src_cfs_rq = tg->cfs_rq[src_cpu];
  3643. dest_cfs_rq = tg->cfs_rq[dest_cpu];
  3644. return throttled_hierarchy(src_cfs_rq) ||
  3645. throttled_hierarchy(dest_cfs_rq);
  3646. }
  3647. static int tg_unthrottle_up(struct task_group *tg, void *data)
  3648. {
  3649. struct rq *rq = data;
  3650. struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
  3651. cfs_rq->throttle_count--;
  3652. if (!cfs_rq->throttle_count) {
  3653. /* adjust cfs_rq_clock_task() */
  3654. cfs_rq->throttled_clock_task_time += rq_clock_task(rq) -
  3655. cfs_rq->throttled_clock_task;
  3656. }
  3657. return 0;
  3658. }
  3659. static int tg_throttle_down(struct task_group *tg, void *data)
  3660. {
  3661. struct rq *rq = data;
  3662. struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
  3663. /* group is entering throttled state, stop time */
  3664. if (!cfs_rq->throttle_count)
  3665. cfs_rq->throttled_clock_task = rq_clock_task(rq);
  3666. cfs_rq->throttle_count++;
  3667. return 0;
  3668. }
  3669. static void throttle_cfs_rq(struct cfs_rq *cfs_rq)
  3670. {
  3671. struct rq *rq = rq_of(cfs_rq);
  3672. struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
  3673. struct sched_entity *se;
  3674. long task_delta, dequeue = 1;
  3675. bool empty;
  3676. se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))];
  3677. /* freeze hierarchy runnable averages while throttled */
  3678. rcu_read_lock();
  3679. walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq);
  3680. rcu_read_unlock();
  3681. task_delta = cfs_rq->h_nr_running;
  3682. for_each_sched_entity(se) {
  3683. struct cfs_rq *qcfs_rq = cfs_rq_of(se);
  3684. /* throttled entity or throttle-on-deactivate */
  3685. if (!se->on_rq)
  3686. break;
  3687. if (dequeue)
  3688. dequeue_entity(qcfs_rq, se, DEQUEUE_SLEEP);
  3689. qcfs_rq->h_nr_running -= task_delta;
  3690. if (qcfs_rq->load.weight)
  3691. dequeue = 0;
  3692. }
  3693. if (!se)
  3694. sub_nr_running(rq, task_delta);
  3695. cfs_rq->throttled = 1;
  3696. cfs_rq->throttled_clock = rq_clock(rq);
  3697. raw_spin_lock(&cfs_b->lock);
  3698. empty = list_empty(&cfs_b->throttled_cfs_rq);
  3699. /*
  3700. * Add to the _head_ of the list, so that an already-started
  3701. * distribute_cfs_runtime will not see us
  3702. */
  3703. list_add_rcu(&cfs_rq->throttled_list, &cfs_b->throttled_cfs_rq);
  3704. /*
  3705. * If we're the first throttled task, make sure the bandwidth
  3706. * timer is running.
  3707. */
  3708. if (empty)
  3709. start_cfs_bandwidth(cfs_b);
  3710. raw_spin_unlock(&cfs_b->lock);
  3711. }
  3712. void unthrottle_cfs_rq(struct cfs_rq *cfs_rq)
  3713. {
  3714. struct rq *rq = rq_of(cfs_rq);
  3715. struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
  3716. struct sched_entity *se;
  3717. int enqueue = 1;
  3718. long task_delta;
  3719. se = cfs_rq->tg->se[cpu_of(rq)];
  3720. cfs_rq->throttled = 0;
  3721. update_rq_clock(rq);
  3722. raw_spin_lock(&cfs_b->lock);
  3723. cfs_b->throttled_time += rq_clock(rq) - cfs_rq->throttled_clock;
  3724. list_del_rcu(&cfs_rq->throttled_list);
  3725. raw_spin_unlock(&cfs_b->lock);
  3726. /* update hierarchical throttle state */
  3727. walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq);
  3728. if (!cfs_rq->load.weight)
  3729. return;
  3730. task_delta = cfs_rq->h_nr_running;
  3731. for_each_sched_entity(se) {
  3732. if (se->on_rq)
  3733. enqueue = 0;
  3734. cfs_rq = cfs_rq_of(se);
  3735. if (enqueue)
  3736. enqueue_entity(cfs_rq, se, ENQUEUE_WAKEUP);
  3737. cfs_rq->h_nr_running += task_delta;
  3738. if (cfs_rq_throttled(cfs_rq))
  3739. break;
  3740. }
  3741. if (!se)
  3742. add_nr_running(rq, task_delta);
  3743. /* Determine whether we need to wake up potentially idle CPU: */
  3744. if (rq->curr == rq->idle && rq->cfs.nr_running)
  3745. resched_curr(rq);
  3746. }
  3747. static u64 distribute_cfs_runtime(struct cfs_bandwidth *cfs_b,
  3748. u64 remaining, u64 expires)
  3749. {
  3750. struct cfs_rq *cfs_rq;
  3751. u64 runtime;
  3752. u64 starting_runtime = remaining;
  3753. rcu_read_lock();
  3754. list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
  3755. throttled_list) {
  3756. struct rq *rq = rq_of(cfs_rq);
  3757. struct rq_flags rf;
  3758. rq_lock(rq, &rf);
  3759. if (!cfs_rq_throttled(cfs_rq))
  3760. goto next;
  3761. runtime = -cfs_rq->runtime_remaining + 1;
  3762. if (runtime > remaining)
  3763. runtime = remaining;
  3764. remaining -= runtime;
  3765. cfs_rq->runtime_remaining += runtime;
  3766. cfs_rq->runtime_expires = expires;
  3767. /* we check whether we're throttled above */
  3768. if (cfs_rq->runtime_remaining > 0)
  3769. unthrottle_cfs_rq(cfs_rq);
  3770. next:
  3771. rq_unlock(rq, &rf);
  3772. if (!remaining)
  3773. break;
  3774. }
  3775. rcu_read_unlock();
  3776. return starting_runtime - remaining;
  3777. }
  3778. /*
  3779. * Responsible for refilling a task_group's bandwidth and unthrottling its
  3780. * cfs_rqs as appropriate. If there has been no activity within the last
  3781. * period the timer is deactivated until scheduling resumes; cfs_b->idle is
  3782. * used to track this state.
  3783. */
  3784. static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun)
  3785. {
  3786. u64 runtime, runtime_expires;
  3787. int throttled;
  3788. /* no need to continue the timer with no bandwidth constraint */
  3789. if (cfs_b->quota == RUNTIME_INF)
  3790. goto out_deactivate;
  3791. throttled = !list_empty(&cfs_b->throttled_cfs_rq);
  3792. cfs_b->nr_periods += overrun;
  3793. /*
  3794. * idle depends on !throttled (for the case of a large deficit), and if
  3795. * we're going inactive then everything else can be deferred
  3796. */
  3797. if (cfs_b->idle && !throttled)
  3798. goto out_deactivate;
  3799. __refill_cfs_bandwidth_runtime(cfs_b);
  3800. if (!throttled) {
  3801. /* mark as potentially idle for the upcoming period */
  3802. cfs_b->idle = 1;
  3803. return 0;
  3804. }
  3805. /* account preceding periods in which throttling occurred */
  3806. cfs_b->nr_throttled += overrun;
  3807. runtime_expires = cfs_b->runtime_expires;
  3808. /*
  3809. * This check is repeated as we are holding onto the new bandwidth while
  3810. * we unthrottle. This can potentially race with an unthrottled group
  3811. * trying to acquire new bandwidth from the global pool. This can result
  3812. * in us over-using our runtime if it is all used during this loop, but
  3813. * only by limited amounts in that extreme case.
  3814. */
  3815. while (throttled && cfs_b->runtime > 0) {
  3816. runtime = cfs_b->runtime;
  3817. raw_spin_unlock(&cfs_b->lock);
  3818. /* we can't nest cfs_b->lock while distributing bandwidth */
  3819. runtime = distribute_cfs_runtime(cfs_b, runtime,
  3820. runtime_expires);
  3821. raw_spin_lock(&cfs_b->lock);
  3822. throttled = !list_empty(&cfs_b->throttled_cfs_rq);
  3823. cfs_b->runtime -= min(runtime, cfs_b->runtime);
  3824. }
  3825. /*
  3826. * While we are ensured activity in the period following an
  3827. * unthrottle, this also covers the case in which the new bandwidth is
  3828. * insufficient to cover the existing bandwidth deficit. (Forcing the
  3829. * timer to remain active while there are any throttled entities.)
  3830. */
  3831. cfs_b->idle = 0;
  3832. return 0;
  3833. out_deactivate:
  3834. return 1;
  3835. }
  3836. /* a cfs_rq won't donate quota below this amount */
  3837. static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC;
  3838. /* minimum remaining period time to redistribute slack quota */
  3839. static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC;
  3840. /* how long we wait to gather additional slack before distributing */
  3841. static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC;
  3842. /*
  3843. * Are we near the end of the current quota period?
  3844. *
  3845. * Requires cfs_b->lock for hrtimer_expires_remaining to be safe against the
  3846. * hrtimer base being cleared by hrtimer_start. In the case of
  3847. * migrate_hrtimers, base is never cleared, so we are fine.
  3848. */
  3849. static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire)
  3850. {
  3851. struct hrtimer *refresh_timer = &cfs_b->period_timer;
  3852. u64 remaining;
  3853. /* if the call-back is running a quota refresh is already occurring */
  3854. if (hrtimer_callback_running(refresh_timer))
  3855. return 1;
  3856. /* is a quota refresh about to occur? */
  3857. remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer));
  3858. if (remaining < min_expire)
  3859. return 1;
  3860. return 0;
  3861. }
  3862. static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b)
  3863. {
  3864. u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration;
  3865. /* if there's a quota refresh soon don't bother with slack */
  3866. if (runtime_refresh_within(cfs_b, min_left))
  3867. return;
  3868. hrtimer_start(&cfs_b->slack_timer,
  3869. ns_to_ktime(cfs_bandwidth_slack_period),
  3870. HRTIMER_MODE_REL);
  3871. }
  3872. /* we know any runtime found here is valid as update_curr() precedes return */
  3873. static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  3874. {
  3875. struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
  3876. s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;
  3877. if (slack_runtime <= 0)
  3878. return;
  3879. raw_spin_lock(&cfs_b->lock);
  3880. if (cfs_b->quota != RUNTIME_INF &&
  3881. cfs_rq->runtime_expires == cfs_b->runtime_expires) {
  3882. cfs_b->runtime += slack_runtime;
  3883. /* we are under rq->lock, defer unthrottling using a timer */
  3884. if (cfs_b->runtime > sched_cfs_bandwidth_slice() &&
  3885. !list_empty(&cfs_b->throttled_cfs_rq))
  3886. start_cfs_slack_bandwidth(cfs_b);
  3887. }
  3888. raw_spin_unlock(&cfs_b->lock);
  3889. /* even if it's not valid for return we don't want to try again */
  3890. cfs_rq->runtime_remaining -= slack_runtime;
  3891. }
  3892. static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  3893. {
  3894. if (!cfs_bandwidth_used())
  3895. return;
  3896. if (!cfs_rq->runtime_enabled || cfs_rq->nr_running)
  3897. return;
  3898. __return_cfs_rq_runtime(cfs_rq);
  3899. }
  3900. /*
  3901. * This is done with a timer (instead of inline with bandwidth return) since
  3902. * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
  3903. */
  3904. static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)
  3905. {
  3906. u64 runtime = 0, slice = sched_cfs_bandwidth_slice();
  3907. u64 expires;
  3908. /* confirm we're still not at a refresh boundary */
  3909. raw_spin_lock(&cfs_b->lock);
  3910. if (runtime_refresh_within(cfs_b, min_bandwidth_expiration)) {
  3911. raw_spin_unlock(&cfs_b->lock);
  3912. return;
  3913. }
  3914. if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice)
  3915. runtime = cfs_b->runtime;
  3916. expires = cfs_b->runtime_expires;
  3917. raw_spin_unlock(&cfs_b->lock);
  3918. if (!runtime)
  3919. return;
  3920. runtime = distribute_cfs_runtime(cfs_b, runtime, expires);
  3921. raw_spin_lock(&cfs_b->lock);
  3922. if (expires == cfs_b->runtime_expires)
  3923. cfs_b->runtime -= min(runtime, cfs_b->runtime);
  3924. raw_spin_unlock(&cfs_b->lock);
  3925. }
  3926. /*
  3927. * When a group wakes up we want to make sure that its quota is not already
  3928. * expired/exceeded, otherwise it may be allowed to steal additional ticks of
  3929. * runtime as update_curr() throttling can not not trigger until it's on-rq.
  3930. */
  3931. static void check_enqueue_throttle(struct cfs_rq *cfs_rq)
  3932. {
  3933. if (!cfs_bandwidth_used())
  3934. return;
  3935. /* an active group must be handled by the update_curr()->put() path */
  3936. if (!cfs_rq->runtime_enabled || cfs_rq->curr)
  3937. return;
  3938. /* ensure the group is not already throttled */
  3939. if (cfs_rq_throttled(cfs_rq))
  3940. return;
  3941. /* update runtime allocation */
  3942. account_cfs_rq_runtime(cfs_rq, 0);
  3943. if (cfs_rq->runtime_remaining <= 0)
  3944. throttle_cfs_rq(cfs_rq);
  3945. }
  3946. static void sync_throttle(struct task_group *tg, int cpu)
  3947. {
  3948. struct cfs_rq *pcfs_rq, *cfs_rq;
  3949. if (!cfs_bandwidth_used())
  3950. return;
  3951. if (!tg->parent)
  3952. return;
  3953. cfs_rq = tg->cfs_rq[cpu];
  3954. pcfs_rq = tg->parent->cfs_rq[cpu];
  3955. cfs_rq->throttle_count = pcfs_rq->throttle_count;
  3956. cfs_rq->throttled_clock_task = rq_clock_task(cpu_rq(cpu));
  3957. }
  3958. /* conditionally throttle active cfs_rq's from put_prev_entity() */
  3959. static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  3960. {
  3961. if (!cfs_bandwidth_used())
  3962. return false;
  3963. if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0))
  3964. return false;
  3965. /*
  3966. * it's possible for a throttled entity to be forced into a running
  3967. * state (e.g. set_curr_task), in this case we're finished.
  3968. */
  3969. if (cfs_rq_throttled(cfs_rq))
  3970. return true;
  3971. throttle_cfs_rq(cfs_rq);
  3972. return true;
  3973. }
  3974. static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer)
  3975. {
  3976. struct cfs_bandwidth *cfs_b =
  3977. container_of(timer, struct cfs_bandwidth, slack_timer);
  3978. do_sched_cfs_slack_timer(cfs_b);
  3979. return HRTIMER_NORESTART;
  3980. }
  3981. static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)
  3982. {
  3983. struct cfs_bandwidth *cfs_b =
  3984. container_of(timer, struct cfs_bandwidth, period_timer);
  3985. int overrun;
  3986. int idle = 0;
  3987. raw_spin_lock(&cfs_b->lock);
  3988. for (;;) {
  3989. overrun = hrtimer_forward_now(timer, cfs_b->period);
  3990. if (!overrun)
  3991. break;
  3992. idle = do_sched_cfs_period_timer(cfs_b, overrun);
  3993. }
  3994. if (idle)
  3995. cfs_b->period_active = 0;
  3996. raw_spin_unlock(&cfs_b->lock);
  3997. return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
  3998. }
  3999. void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
  4000. {
  4001. raw_spin_lock_init(&cfs_b->lock);
  4002. cfs_b->runtime = 0;
  4003. cfs_b->quota = RUNTIME_INF;
  4004. cfs_b->period = ns_to_ktime(default_cfs_period());
  4005. INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq);
  4006. hrtimer_init(&cfs_b->period_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED);
  4007. cfs_b->period_timer.function = sched_cfs_period_timer;
  4008. hrtimer_init(&cfs_b->slack_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
  4009. cfs_b->slack_timer.function = sched_cfs_slack_timer;
  4010. }
  4011. static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  4012. {
  4013. cfs_rq->runtime_enabled = 0;
  4014. INIT_LIST_HEAD(&cfs_rq->throttled_list);
  4015. }
  4016. void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
  4017. {
  4018. u64 overrun;
  4019. lockdep_assert_held(&cfs_b->lock);
  4020. if (cfs_b->period_active)
  4021. return;
  4022. cfs_b->period_active = 1;
  4023. overrun = hrtimer_forward_now(&cfs_b->period_timer, cfs_b->period);
  4024. cfs_b->runtime_expires += (overrun + 1) * ktime_to_ns(cfs_b->period);
  4025. cfs_b->expires_seq++;
  4026. hrtimer_start_expires(&cfs_b->period_timer, HRTIMER_MODE_ABS_PINNED);
  4027. }
  4028. static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
  4029. {
  4030. /* init_cfs_bandwidth() was not called */
  4031. if (!cfs_b->throttled_cfs_rq.next)
  4032. return;
  4033. hrtimer_cancel(&cfs_b->period_timer);
  4034. hrtimer_cancel(&cfs_b->slack_timer);
  4035. }
  4036. /*
  4037. * Both these CPU hotplug callbacks race against unregister_fair_sched_group()
  4038. *
  4039. * The race is harmless, since modifying bandwidth settings of unhooked group
  4040. * bits doesn't do much.
  4041. */
  4042. /* cpu online calback */
  4043. static void __maybe_unused update_runtime_enabled(struct rq *rq)
  4044. {
  4045. struct task_group *tg;
  4046. lockdep_assert_held(&rq->lock);
  4047. rcu_read_lock();
  4048. list_for_each_entry_rcu(tg, &task_groups, list) {
  4049. struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
  4050. struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
  4051. raw_spin_lock(&cfs_b->lock);
  4052. cfs_rq->runtime_enabled = cfs_b->quota != RUNTIME_INF;
  4053. raw_spin_unlock(&cfs_b->lock);
  4054. }
  4055. rcu_read_unlock();
  4056. }
  4057. /* cpu offline callback */
  4058. static void __maybe_unused unthrottle_offline_cfs_rqs(struct rq *rq)
  4059. {
  4060. struct task_group *tg;
  4061. lockdep_assert_held(&rq->lock);
  4062. rcu_read_lock();
  4063. list_for_each_entry_rcu(tg, &task_groups, list) {
  4064. struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
  4065. if (!cfs_rq->runtime_enabled)
  4066. continue;
  4067. /*
  4068. * clock_task is not advancing so we just need to make sure
  4069. * there's some valid quota amount
  4070. */
  4071. cfs_rq->runtime_remaining = 1;
  4072. /*
  4073. * Offline rq is schedulable till CPU is completely disabled
  4074. * in take_cpu_down(), so we prevent new cfs throttling here.
  4075. */
  4076. cfs_rq->runtime_enabled = 0;
  4077. if (cfs_rq_throttled(cfs_rq))
  4078. unthrottle_cfs_rq(cfs_rq);
  4079. }
  4080. rcu_read_unlock();
  4081. }
  4082. #else /* CONFIG_CFS_BANDWIDTH */
  4083. static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq)
  4084. {
  4085. return rq_clock_task(rq_of(cfs_rq));
  4086. }
  4087. static void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) {}
  4088. static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq) { return false; }
  4089. static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {}
  4090. static inline void sync_throttle(struct task_group *tg, int cpu) {}
  4091. static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
  4092. static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
  4093. {
  4094. return 0;
  4095. }
  4096. static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
  4097. {
  4098. return 0;
  4099. }
  4100. static inline int throttled_lb_pair(struct task_group *tg,
  4101. int src_cpu, int dest_cpu)
  4102. {
  4103. return 0;
  4104. }
  4105. void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
  4106. #ifdef CONFIG_FAIR_GROUP_SCHED
  4107. static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
  4108. #endif
  4109. static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
  4110. {
  4111. return NULL;
  4112. }
  4113. static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
  4114. static inline void update_runtime_enabled(struct rq *rq) {}
  4115. static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {}
  4116. #endif /* CONFIG_CFS_BANDWIDTH */
  4117. /**************************************************
  4118. * CFS operations on tasks:
  4119. */
  4120. #ifdef CONFIG_SCHED_HRTICK
  4121. static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
  4122. {
  4123. struct sched_entity *se = &p->se;
  4124. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  4125. SCHED_WARN_ON(task_rq(p) != rq);
  4126. if (rq->cfs.h_nr_running > 1) {
  4127. u64 slice = sched_slice(cfs_rq, se);
  4128. u64 ran = se->sum_exec_runtime - se->prev_sum_exec_runtime;
  4129. s64 delta = slice - ran;
  4130. if (delta < 0) {
  4131. if (rq->curr == p)
  4132. resched_curr(rq);
  4133. return;
  4134. }
  4135. hrtick_start(rq, delta);
  4136. }
  4137. }
  4138. /*
  4139. * called from enqueue/dequeue and updates the hrtick when the
  4140. * current task is from our class and nr_running is low enough
  4141. * to matter.
  4142. */
  4143. static void hrtick_update(struct rq *rq)
  4144. {
  4145. struct task_struct *curr = rq->curr;
  4146. if (!hrtick_enabled(rq) || curr->sched_class != &fair_sched_class)
  4147. return;
  4148. if (cfs_rq_of(&curr->se)->nr_running < sched_nr_latency)
  4149. hrtick_start_fair(rq, curr);
  4150. }
  4151. #else /* !CONFIG_SCHED_HRTICK */
  4152. static inline void
  4153. hrtick_start_fair(struct rq *rq, struct task_struct *p)
  4154. {
  4155. }
  4156. static inline void hrtick_update(struct rq *rq)
  4157. {
  4158. }
  4159. #endif
  4160. /*
  4161. * The enqueue_task method is called before nr_running is
  4162. * increased. Here we update the fair scheduling stats and
  4163. * then put the task into the rbtree:
  4164. */
  4165. static void
  4166. enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
  4167. {
  4168. struct cfs_rq *cfs_rq;
  4169. struct sched_entity *se = &p->se;
  4170. /*
  4171. * The code below (indirectly) updates schedutil which looks at
  4172. * the cfs_rq utilization to select a frequency.
  4173. * Let's add the task's estimated utilization to the cfs_rq's
  4174. * estimated utilization, before we update schedutil.
  4175. */
  4176. util_est_enqueue(&rq->cfs, p);
  4177. /*
  4178. * If in_iowait is set, the code below may not trigger any cpufreq
  4179. * utilization updates, so do it here explicitly with the IOWAIT flag
  4180. * passed.
  4181. */
  4182. if (p->in_iowait)
  4183. cpufreq_update_util(rq, SCHED_CPUFREQ_IOWAIT);
  4184. for_each_sched_entity(se) {
  4185. if (se->on_rq)
  4186. break;
  4187. cfs_rq = cfs_rq_of(se);
  4188. enqueue_entity(cfs_rq, se, flags);
  4189. /*
  4190. * end evaluation on encountering a throttled cfs_rq
  4191. *
  4192. * note: in the case of encountering a throttled cfs_rq we will
  4193. * post the final h_nr_running increment below.
  4194. */
  4195. if (cfs_rq_throttled(cfs_rq))
  4196. break;
  4197. cfs_rq->h_nr_running++;
  4198. flags = ENQUEUE_WAKEUP;
  4199. }
  4200. for_each_sched_entity(se) {
  4201. cfs_rq = cfs_rq_of(se);
  4202. cfs_rq->h_nr_running++;
  4203. if (cfs_rq_throttled(cfs_rq))
  4204. break;
  4205. update_load_avg(cfs_rq, se, UPDATE_TG);
  4206. update_cfs_group(se);
  4207. }
  4208. if (!se)
  4209. add_nr_running(rq, 1);
  4210. hrtick_update(rq);
  4211. }
  4212. static void set_next_buddy(struct sched_entity *se);
  4213. /*
  4214. * The dequeue_task method is called before nr_running is
  4215. * decreased. We remove the task from the rbtree and
  4216. * update the fair scheduling stats:
  4217. */
  4218. static void dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
  4219. {
  4220. struct cfs_rq *cfs_rq;
  4221. struct sched_entity *se = &p->se;
  4222. int task_sleep = flags & DEQUEUE_SLEEP;
  4223. for_each_sched_entity(se) {
  4224. cfs_rq = cfs_rq_of(se);
  4225. dequeue_entity(cfs_rq, se, flags);
  4226. /*
  4227. * end evaluation on encountering a throttled cfs_rq
  4228. *
  4229. * note: in the case of encountering a throttled cfs_rq we will
  4230. * post the final h_nr_running decrement below.
  4231. */
  4232. if (cfs_rq_throttled(cfs_rq))
  4233. break;
  4234. cfs_rq->h_nr_running--;
  4235. /* Don't dequeue parent if it has other entities besides us */
  4236. if (cfs_rq->load.weight) {
  4237. /* Avoid re-evaluating load for this entity: */
  4238. se = parent_entity(se);
  4239. /*
  4240. * Bias pick_next to pick a task from this cfs_rq, as
  4241. * p is sleeping when it is within its sched_slice.
  4242. */
  4243. if (task_sleep && se && !throttled_hierarchy(cfs_rq))
  4244. set_next_buddy(se);
  4245. break;
  4246. }
  4247. flags |= DEQUEUE_SLEEP;
  4248. }
  4249. for_each_sched_entity(se) {
  4250. cfs_rq = cfs_rq_of(se);
  4251. cfs_rq->h_nr_running--;
  4252. if (cfs_rq_throttled(cfs_rq))
  4253. break;
  4254. update_load_avg(cfs_rq, se, UPDATE_TG);
  4255. update_cfs_group(se);
  4256. }
  4257. if (!se)
  4258. sub_nr_running(rq, 1);
  4259. util_est_dequeue(&rq->cfs, p, task_sleep);
  4260. hrtick_update(rq);
  4261. }
  4262. #ifdef CONFIG_SMP
  4263. /* Working cpumask for: load_balance, load_balance_newidle. */
  4264. DEFINE_PER_CPU(cpumask_var_t, load_balance_mask);
  4265. DEFINE_PER_CPU(cpumask_var_t, select_idle_mask);
  4266. #ifdef CONFIG_NO_HZ_COMMON
  4267. /*
  4268. * per rq 'load' arrray crap; XXX kill this.
  4269. */
  4270. /*
  4271. * The exact cpuload calculated at every tick would be:
  4272. *
  4273. * load' = (1 - 1/2^i) * load + (1/2^i) * cur_load
  4274. *
  4275. * If a CPU misses updates for n ticks (as it was idle) and update gets
  4276. * called on the n+1-th tick when CPU may be busy, then we have:
  4277. *
  4278. * load_n = (1 - 1/2^i)^n * load_0
  4279. * load_n+1 = (1 - 1/2^i) * load_n + (1/2^i) * cur_load
  4280. *
  4281. * decay_load_missed() below does efficient calculation of
  4282. *
  4283. * load' = (1 - 1/2^i)^n * load
  4284. *
  4285. * Because x^(n+m) := x^n * x^m we can decompose any x^n in power-of-2 factors.
  4286. * This allows us to precompute the above in said factors, thereby allowing the
  4287. * reduction of an arbitrary n in O(log_2 n) steps. (See also
  4288. * fixed_power_int())
  4289. *
  4290. * The calculation is approximated on a 128 point scale.
  4291. */
  4292. #define DEGRADE_SHIFT 7
  4293. static const u8 degrade_zero_ticks[CPU_LOAD_IDX_MAX] = {0, 8, 32, 64, 128};
  4294. static const u8 degrade_factor[CPU_LOAD_IDX_MAX][DEGRADE_SHIFT + 1] = {
  4295. { 0, 0, 0, 0, 0, 0, 0, 0 },
  4296. { 64, 32, 8, 0, 0, 0, 0, 0 },
  4297. { 96, 72, 40, 12, 1, 0, 0, 0 },
  4298. { 112, 98, 75, 43, 15, 1, 0, 0 },
  4299. { 120, 112, 98, 76, 45, 16, 2, 0 }
  4300. };
  4301. /*
  4302. * Update cpu_load for any missed ticks, due to tickless idle. The backlog
  4303. * would be when CPU is idle and so we just decay the old load without
  4304. * adding any new load.
  4305. */
  4306. static unsigned long
  4307. decay_load_missed(unsigned long load, unsigned long missed_updates, int idx)
  4308. {
  4309. int j = 0;
  4310. if (!missed_updates)
  4311. return load;
  4312. if (missed_updates >= degrade_zero_ticks[idx])
  4313. return 0;
  4314. if (idx == 1)
  4315. return load >> missed_updates;
  4316. while (missed_updates) {
  4317. if (missed_updates % 2)
  4318. load = (load * degrade_factor[idx][j]) >> DEGRADE_SHIFT;
  4319. missed_updates >>= 1;
  4320. j++;
  4321. }
  4322. return load;
  4323. }
  4324. static struct {
  4325. cpumask_var_t idle_cpus_mask;
  4326. atomic_t nr_cpus;
  4327. int has_blocked; /* Idle CPUS has blocked load */
  4328. unsigned long next_balance; /* in jiffy units */
  4329. unsigned long next_blocked; /* Next update of blocked load in jiffies */
  4330. } nohz ____cacheline_aligned;
  4331. #endif /* CONFIG_NO_HZ_COMMON */
  4332. /**
  4333. * __cpu_load_update - update the rq->cpu_load[] statistics
  4334. * @this_rq: The rq to update statistics for
  4335. * @this_load: The current load
  4336. * @pending_updates: The number of missed updates
  4337. *
  4338. * Update rq->cpu_load[] statistics. This function is usually called every
  4339. * scheduler tick (TICK_NSEC).
  4340. *
  4341. * This function computes a decaying average:
  4342. *
  4343. * load[i]' = (1 - 1/2^i) * load[i] + (1/2^i) * load
  4344. *
  4345. * Because of NOHZ it might not get called on every tick which gives need for
  4346. * the @pending_updates argument.
  4347. *
  4348. * load[i]_n = (1 - 1/2^i) * load[i]_n-1 + (1/2^i) * load_n-1
  4349. * = A * load[i]_n-1 + B ; A := (1 - 1/2^i), B := (1/2^i) * load
  4350. * = A * (A * load[i]_n-2 + B) + B
  4351. * = A * (A * (A * load[i]_n-3 + B) + B) + B
  4352. * = A^3 * load[i]_n-3 + (A^2 + A + 1) * B
  4353. * = A^n * load[i]_0 + (A^(n-1) + A^(n-2) + ... + 1) * B
  4354. * = A^n * load[i]_0 + ((1 - A^n) / (1 - A)) * B
  4355. * = (1 - 1/2^i)^n * (load[i]_0 - load) + load
  4356. *
  4357. * In the above we've assumed load_n := load, which is true for NOHZ_FULL as
  4358. * any change in load would have resulted in the tick being turned back on.
  4359. *
  4360. * For regular NOHZ, this reduces to:
  4361. *
  4362. * load[i]_n = (1 - 1/2^i)^n * load[i]_0
  4363. *
  4364. * see decay_load_misses(). For NOHZ_FULL we get to subtract and add the extra
  4365. * term.
  4366. */
  4367. static void cpu_load_update(struct rq *this_rq, unsigned long this_load,
  4368. unsigned long pending_updates)
  4369. {
  4370. unsigned long __maybe_unused tickless_load = this_rq->cpu_load[0];
  4371. int i, scale;
  4372. this_rq->nr_load_updates++;
  4373. /* Update our load: */
  4374. this_rq->cpu_load[0] = this_load; /* Fasttrack for idx 0 */
  4375. for (i = 1, scale = 2; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
  4376. unsigned long old_load, new_load;
  4377. /* scale is effectively 1 << i now, and >> i divides by scale */
  4378. old_load = this_rq->cpu_load[i];
  4379. #ifdef CONFIG_NO_HZ_COMMON
  4380. old_load = decay_load_missed(old_load, pending_updates - 1, i);
  4381. if (tickless_load) {
  4382. old_load -= decay_load_missed(tickless_load, pending_updates - 1, i);
  4383. /*
  4384. * old_load can never be a negative value because a
  4385. * decayed tickless_load cannot be greater than the
  4386. * original tickless_load.
  4387. */
  4388. old_load += tickless_load;
  4389. }
  4390. #endif
  4391. new_load = this_load;
  4392. /*
  4393. * Round up the averaging division if load is increasing. This
  4394. * prevents us from getting stuck on 9 if the load is 10, for
  4395. * example.
  4396. */
  4397. if (new_load > old_load)
  4398. new_load += scale - 1;
  4399. this_rq->cpu_load[i] = (old_load * (scale - 1) + new_load) >> i;
  4400. }
  4401. }
  4402. /* Used instead of source_load when we know the type == 0 */
  4403. static unsigned long weighted_cpuload(struct rq *rq)
  4404. {
  4405. return cfs_rq_runnable_load_avg(&rq->cfs);
  4406. }
  4407. #ifdef CONFIG_NO_HZ_COMMON
  4408. /*
  4409. * There is no sane way to deal with nohz on smp when using jiffies because the
  4410. * CPU doing the jiffies update might drift wrt the CPU doing the jiffy reading
  4411. * causing off-by-one errors in observed deltas; {0,2} instead of {1,1}.
  4412. *
  4413. * Therefore we need to avoid the delta approach from the regular tick when
  4414. * possible since that would seriously skew the load calculation. This is why we
  4415. * use cpu_load_update_periodic() for CPUs out of nohz. However we'll rely on
  4416. * jiffies deltas for updates happening while in nohz mode (idle ticks, idle
  4417. * loop exit, nohz_idle_balance, nohz full exit...)
  4418. *
  4419. * This means we might still be one tick off for nohz periods.
  4420. */
  4421. static void cpu_load_update_nohz(struct rq *this_rq,
  4422. unsigned long curr_jiffies,
  4423. unsigned long load)
  4424. {
  4425. unsigned long pending_updates;
  4426. pending_updates = curr_jiffies - this_rq->last_load_update_tick;
  4427. if (pending_updates) {
  4428. this_rq->last_load_update_tick = curr_jiffies;
  4429. /*
  4430. * In the regular NOHZ case, we were idle, this means load 0.
  4431. * In the NOHZ_FULL case, we were non-idle, we should consider
  4432. * its weighted load.
  4433. */
  4434. cpu_load_update(this_rq, load, pending_updates);
  4435. }
  4436. }
  4437. /*
  4438. * Called from nohz_idle_balance() to update the load ratings before doing the
  4439. * idle balance.
  4440. */
  4441. static void cpu_load_update_idle(struct rq *this_rq)
  4442. {
  4443. /*
  4444. * bail if there's load or we're actually up-to-date.
  4445. */
  4446. if (weighted_cpuload(this_rq))
  4447. return;
  4448. cpu_load_update_nohz(this_rq, READ_ONCE(jiffies), 0);
  4449. }
  4450. /*
  4451. * Record CPU load on nohz entry so we know the tickless load to account
  4452. * on nohz exit. cpu_load[0] happens then to be updated more frequently
  4453. * than other cpu_load[idx] but it should be fine as cpu_load readers
  4454. * shouldn't rely into synchronized cpu_load[*] updates.
  4455. */
  4456. void cpu_load_update_nohz_start(void)
  4457. {
  4458. struct rq *this_rq = this_rq();
  4459. /*
  4460. * This is all lockless but should be fine. If weighted_cpuload changes
  4461. * concurrently we'll exit nohz. And cpu_load write can race with
  4462. * cpu_load_update_idle() but both updater would be writing the same.
  4463. */
  4464. this_rq->cpu_load[0] = weighted_cpuload(this_rq);
  4465. }
  4466. /*
  4467. * Account the tickless load in the end of a nohz frame.
  4468. */
  4469. void cpu_load_update_nohz_stop(void)
  4470. {
  4471. unsigned long curr_jiffies = READ_ONCE(jiffies);
  4472. struct rq *this_rq = this_rq();
  4473. unsigned long load;
  4474. struct rq_flags rf;
  4475. if (curr_jiffies == this_rq->last_load_update_tick)
  4476. return;
  4477. load = weighted_cpuload(this_rq);
  4478. rq_lock(this_rq, &rf);
  4479. update_rq_clock(this_rq);
  4480. cpu_load_update_nohz(this_rq, curr_jiffies, load);
  4481. rq_unlock(this_rq, &rf);
  4482. }
  4483. #else /* !CONFIG_NO_HZ_COMMON */
  4484. static inline void cpu_load_update_nohz(struct rq *this_rq,
  4485. unsigned long curr_jiffies,
  4486. unsigned long load) { }
  4487. #endif /* CONFIG_NO_HZ_COMMON */
  4488. static void cpu_load_update_periodic(struct rq *this_rq, unsigned long load)
  4489. {
  4490. #ifdef CONFIG_NO_HZ_COMMON
  4491. /* See the mess around cpu_load_update_nohz(). */
  4492. this_rq->last_load_update_tick = READ_ONCE(jiffies);
  4493. #endif
  4494. cpu_load_update(this_rq, load, 1);
  4495. }
  4496. /*
  4497. * Called from scheduler_tick()
  4498. */
  4499. void cpu_load_update_active(struct rq *this_rq)
  4500. {
  4501. unsigned long load = weighted_cpuload(this_rq);
  4502. if (tick_nohz_tick_stopped())
  4503. cpu_load_update_nohz(this_rq, READ_ONCE(jiffies), load);
  4504. else
  4505. cpu_load_update_periodic(this_rq, load);
  4506. }
  4507. /*
  4508. * Return a low guess at the load of a migration-source CPU weighted
  4509. * according to the scheduling class and "nice" value.
  4510. *
  4511. * We want to under-estimate the load of migration sources, to
  4512. * balance conservatively.
  4513. */
  4514. static unsigned long source_load(int cpu, int type)
  4515. {
  4516. struct rq *rq = cpu_rq(cpu);
  4517. unsigned long total = weighted_cpuload(rq);
  4518. if (type == 0 || !sched_feat(LB_BIAS))
  4519. return total;
  4520. return min(rq->cpu_load[type-1], total);
  4521. }
  4522. /*
  4523. * Return a high guess at the load of a migration-target CPU weighted
  4524. * according to the scheduling class and "nice" value.
  4525. */
  4526. static unsigned long target_load(int cpu, int type)
  4527. {
  4528. struct rq *rq = cpu_rq(cpu);
  4529. unsigned long total = weighted_cpuload(rq);
  4530. if (type == 0 || !sched_feat(LB_BIAS))
  4531. return total;
  4532. return max(rq->cpu_load[type-1], total);
  4533. }
  4534. static unsigned long capacity_of(int cpu)
  4535. {
  4536. return cpu_rq(cpu)->cpu_capacity;
  4537. }
  4538. static unsigned long capacity_orig_of(int cpu)
  4539. {
  4540. return cpu_rq(cpu)->cpu_capacity_orig;
  4541. }
  4542. static unsigned long cpu_avg_load_per_task(int cpu)
  4543. {
  4544. struct rq *rq = cpu_rq(cpu);
  4545. unsigned long nr_running = READ_ONCE(rq->cfs.h_nr_running);
  4546. unsigned long load_avg = weighted_cpuload(rq);
  4547. if (nr_running)
  4548. return load_avg / nr_running;
  4549. return 0;
  4550. }
  4551. static void record_wakee(struct task_struct *p)
  4552. {
  4553. /*
  4554. * Only decay a single time; tasks that have less then 1 wakeup per
  4555. * jiffy will not have built up many flips.
  4556. */
  4557. if (time_after(jiffies, current->wakee_flip_decay_ts + HZ)) {
  4558. current->wakee_flips >>= 1;
  4559. current->wakee_flip_decay_ts = jiffies;
  4560. }
  4561. if (current->last_wakee != p) {
  4562. current->last_wakee = p;
  4563. current->wakee_flips++;
  4564. }
  4565. }
  4566. /*
  4567. * Detect M:N waker/wakee relationships via a switching-frequency heuristic.
  4568. *
  4569. * A waker of many should wake a different task than the one last awakened
  4570. * at a frequency roughly N times higher than one of its wakees.
  4571. *
  4572. * In order to determine whether we should let the load spread vs consolidating
  4573. * to shared cache, we look for a minimum 'flip' frequency of llc_size in one
  4574. * partner, and a factor of lls_size higher frequency in the other.
  4575. *
  4576. * With both conditions met, we can be relatively sure that the relationship is
  4577. * non-monogamous, with partner count exceeding socket size.
  4578. *
  4579. * Waker/wakee being client/server, worker/dispatcher, interrupt source or
  4580. * whatever is irrelevant, spread criteria is apparent partner count exceeds
  4581. * socket size.
  4582. */
  4583. static int wake_wide(struct task_struct *p)
  4584. {
  4585. unsigned int master = current->wakee_flips;
  4586. unsigned int slave = p->wakee_flips;
  4587. int factor = this_cpu_read(sd_llc_size);
  4588. if (master < slave)
  4589. swap(master, slave);
  4590. if (slave < factor || master < slave * factor)
  4591. return 0;
  4592. return 1;
  4593. }
  4594. /*
  4595. * The purpose of wake_affine() is to quickly determine on which CPU we can run
  4596. * soonest. For the purpose of speed we only consider the waking and previous
  4597. * CPU.
  4598. *
  4599. * wake_affine_idle() - only considers 'now', it check if the waking CPU is
  4600. * cache-affine and is (or will be) idle.
  4601. *
  4602. * wake_affine_weight() - considers the weight to reflect the average
  4603. * scheduling latency of the CPUs. This seems to work
  4604. * for the overloaded case.
  4605. */
  4606. static int
  4607. wake_affine_idle(int this_cpu, int prev_cpu, int sync)
  4608. {
  4609. /*
  4610. * If this_cpu is idle, it implies the wakeup is from interrupt
  4611. * context. Only allow the move if cache is shared. Otherwise an
  4612. * interrupt intensive workload could force all tasks onto one
  4613. * node depending on the IO topology or IRQ affinity settings.
  4614. *
  4615. * If the prev_cpu is idle and cache affine then avoid a migration.
  4616. * There is no guarantee that the cache hot data from an interrupt
  4617. * is more important than cache hot data on the prev_cpu and from
  4618. * a cpufreq perspective, it's better to have higher utilisation
  4619. * on one CPU.
  4620. */
  4621. if (available_idle_cpu(this_cpu) && cpus_share_cache(this_cpu, prev_cpu))
  4622. return available_idle_cpu(prev_cpu) ? prev_cpu : this_cpu;
  4623. if (sync && cpu_rq(this_cpu)->nr_running == 1)
  4624. return this_cpu;
  4625. return nr_cpumask_bits;
  4626. }
  4627. static int
  4628. wake_affine_weight(struct sched_domain *sd, struct task_struct *p,
  4629. int this_cpu, int prev_cpu, int sync)
  4630. {
  4631. s64 this_eff_load, prev_eff_load;
  4632. unsigned long task_load;
  4633. this_eff_load = target_load(this_cpu, sd->wake_idx);
  4634. if (sync) {
  4635. unsigned long current_load = task_h_load(current);
  4636. if (current_load > this_eff_load)
  4637. return this_cpu;
  4638. this_eff_load -= current_load;
  4639. }
  4640. task_load = task_h_load(p);
  4641. this_eff_load += task_load;
  4642. if (sched_feat(WA_BIAS))
  4643. this_eff_load *= 100;
  4644. this_eff_load *= capacity_of(prev_cpu);
  4645. prev_eff_load = source_load(prev_cpu, sd->wake_idx);
  4646. prev_eff_load -= task_load;
  4647. if (sched_feat(WA_BIAS))
  4648. prev_eff_load *= 100 + (sd->imbalance_pct - 100) / 2;
  4649. prev_eff_load *= capacity_of(this_cpu);
  4650. /*
  4651. * If sync, adjust the weight of prev_eff_load such that if
  4652. * prev_eff == this_eff that select_idle_sibling() will consider
  4653. * stacking the wakee on top of the waker if no other CPU is
  4654. * idle.
  4655. */
  4656. if (sync)
  4657. prev_eff_load += 1;
  4658. return this_eff_load < prev_eff_load ? this_cpu : nr_cpumask_bits;
  4659. }
  4660. static int wake_affine(struct sched_domain *sd, struct task_struct *p,
  4661. int this_cpu, int prev_cpu, int sync)
  4662. {
  4663. int target = nr_cpumask_bits;
  4664. if (sched_feat(WA_IDLE))
  4665. target = wake_affine_idle(this_cpu, prev_cpu, sync);
  4666. if (sched_feat(WA_WEIGHT) && target == nr_cpumask_bits)
  4667. target = wake_affine_weight(sd, p, this_cpu, prev_cpu, sync);
  4668. schedstat_inc(p->se.statistics.nr_wakeups_affine_attempts);
  4669. if (target == nr_cpumask_bits)
  4670. return prev_cpu;
  4671. schedstat_inc(sd->ttwu_move_affine);
  4672. schedstat_inc(p->se.statistics.nr_wakeups_affine);
  4673. return target;
  4674. }
  4675. static unsigned long cpu_util_wake(int cpu, struct task_struct *p);
  4676. static unsigned long capacity_spare_wake(int cpu, struct task_struct *p)
  4677. {
  4678. return max_t(long, capacity_of(cpu) - cpu_util_wake(cpu, p), 0);
  4679. }
  4680. /*
  4681. * find_idlest_group finds and returns the least busy CPU group within the
  4682. * domain.
  4683. *
  4684. * Assumes p is allowed on at least one CPU in sd.
  4685. */
  4686. static struct sched_group *
  4687. find_idlest_group(struct sched_domain *sd, struct task_struct *p,
  4688. int this_cpu, int sd_flag)
  4689. {
  4690. struct sched_group *idlest = NULL, *group = sd->groups;
  4691. struct sched_group *most_spare_sg = NULL;
  4692. unsigned long min_runnable_load = ULONG_MAX;
  4693. unsigned long this_runnable_load = ULONG_MAX;
  4694. unsigned long min_avg_load = ULONG_MAX, this_avg_load = ULONG_MAX;
  4695. unsigned long most_spare = 0, this_spare = 0;
  4696. int load_idx = sd->forkexec_idx;
  4697. int imbalance_scale = 100 + (sd->imbalance_pct-100)/2;
  4698. unsigned long imbalance = scale_load_down(NICE_0_LOAD) *
  4699. (sd->imbalance_pct-100) / 100;
  4700. if (sd_flag & SD_BALANCE_WAKE)
  4701. load_idx = sd->wake_idx;
  4702. do {
  4703. unsigned long load, avg_load, runnable_load;
  4704. unsigned long spare_cap, max_spare_cap;
  4705. int local_group;
  4706. int i;
  4707. /* Skip over this group if it has no CPUs allowed */
  4708. if (!cpumask_intersects(sched_group_span(group),
  4709. &p->cpus_allowed))
  4710. continue;
  4711. local_group = cpumask_test_cpu(this_cpu,
  4712. sched_group_span(group));
  4713. /*
  4714. * Tally up the load of all CPUs in the group and find
  4715. * the group containing the CPU with most spare capacity.
  4716. */
  4717. avg_load = 0;
  4718. runnable_load = 0;
  4719. max_spare_cap = 0;
  4720. for_each_cpu(i, sched_group_span(group)) {
  4721. /* Bias balancing toward CPUs of our domain */
  4722. if (local_group)
  4723. load = source_load(i, load_idx);
  4724. else
  4725. load = target_load(i, load_idx);
  4726. runnable_load += load;
  4727. avg_load += cfs_rq_load_avg(&cpu_rq(i)->cfs);
  4728. spare_cap = capacity_spare_wake(i, p);
  4729. if (spare_cap > max_spare_cap)
  4730. max_spare_cap = spare_cap;
  4731. }
  4732. /* Adjust by relative CPU capacity of the group */
  4733. avg_load = (avg_load * SCHED_CAPACITY_SCALE) /
  4734. group->sgc->capacity;
  4735. runnable_load = (runnable_load * SCHED_CAPACITY_SCALE) /
  4736. group->sgc->capacity;
  4737. if (local_group) {
  4738. this_runnable_load = runnable_load;
  4739. this_avg_load = avg_load;
  4740. this_spare = max_spare_cap;
  4741. } else {
  4742. if (min_runnable_load > (runnable_load + imbalance)) {
  4743. /*
  4744. * The runnable load is significantly smaller
  4745. * so we can pick this new CPU:
  4746. */
  4747. min_runnable_load = runnable_load;
  4748. min_avg_load = avg_load;
  4749. idlest = group;
  4750. } else if ((runnable_load < (min_runnable_load + imbalance)) &&
  4751. (100*min_avg_load > imbalance_scale*avg_load)) {
  4752. /*
  4753. * The runnable loads are close so take the
  4754. * blocked load into account through avg_load:
  4755. */
  4756. min_avg_load = avg_load;
  4757. idlest = group;
  4758. }
  4759. if (most_spare < max_spare_cap) {
  4760. most_spare = max_spare_cap;
  4761. most_spare_sg = group;
  4762. }
  4763. }
  4764. } while (group = group->next, group != sd->groups);
  4765. /*
  4766. * The cross-over point between using spare capacity or least load
  4767. * is too conservative for high utilization tasks on partially
  4768. * utilized systems if we require spare_capacity > task_util(p),
  4769. * so we allow for some task stuffing by using
  4770. * spare_capacity > task_util(p)/2.
  4771. *
  4772. * Spare capacity can't be used for fork because the utilization has
  4773. * not been set yet, we must first select a rq to compute the initial
  4774. * utilization.
  4775. */
  4776. if (sd_flag & SD_BALANCE_FORK)
  4777. goto skip_spare;
  4778. if (this_spare > task_util(p) / 2 &&
  4779. imbalance_scale*this_spare > 100*most_spare)
  4780. return NULL;
  4781. if (most_spare > task_util(p) / 2)
  4782. return most_spare_sg;
  4783. skip_spare:
  4784. if (!idlest)
  4785. return NULL;
  4786. /*
  4787. * When comparing groups across NUMA domains, it's possible for the
  4788. * local domain to be very lightly loaded relative to the remote
  4789. * domains but "imbalance" skews the comparison making remote CPUs
  4790. * look much more favourable. When considering cross-domain, add
  4791. * imbalance to the runnable load on the remote node and consider
  4792. * staying local.
  4793. */
  4794. if ((sd->flags & SD_NUMA) &&
  4795. min_runnable_load + imbalance >= this_runnable_load)
  4796. return NULL;
  4797. if (min_runnable_load > (this_runnable_load + imbalance))
  4798. return NULL;
  4799. if ((this_runnable_load < (min_runnable_load + imbalance)) &&
  4800. (100*this_avg_load < imbalance_scale*min_avg_load))
  4801. return NULL;
  4802. return idlest;
  4803. }
  4804. /*
  4805. * find_idlest_group_cpu - find the idlest CPU among the CPUs in the group.
  4806. */
  4807. static int
  4808. find_idlest_group_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
  4809. {
  4810. unsigned long load, min_load = ULONG_MAX;
  4811. unsigned int min_exit_latency = UINT_MAX;
  4812. u64 latest_idle_timestamp = 0;
  4813. int least_loaded_cpu = this_cpu;
  4814. int shallowest_idle_cpu = -1;
  4815. int i;
  4816. /* Check if we have any choice: */
  4817. if (group->group_weight == 1)
  4818. return cpumask_first(sched_group_span(group));
  4819. /* Traverse only the allowed CPUs */
  4820. for_each_cpu_and(i, sched_group_span(group), &p->cpus_allowed) {
  4821. if (available_idle_cpu(i)) {
  4822. struct rq *rq = cpu_rq(i);
  4823. struct cpuidle_state *idle = idle_get_state(rq);
  4824. if (idle && idle->exit_latency < min_exit_latency) {
  4825. /*
  4826. * We give priority to a CPU whose idle state
  4827. * has the smallest exit latency irrespective
  4828. * of any idle timestamp.
  4829. */
  4830. min_exit_latency = idle->exit_latency;
  4831. latest_idle_timestamp = rq->idle_stamp;
  4832. shallowest_idle_cpu = i;
  4833. } else if ((!idle || idle->exit_latency == min_exit_latency) &&
  4834. rq->idle_stamp > latest_idle_timestamp) {
  4835. /*
  4836. * If equal or no active idle state, then
  4837. * the most recently idled CPU might have
  4838. * a warmer cache.
  4839. */
  4840. latest_idle_timestamp = rq->idle_stamp;
  4841. shallowest_idle_cpu = i;
  4842. }
  4843. } else if (shallowest_idle_cpu == -1) {
  4844. load = weighted_cpuload(cpu_rq(i));
  4845. if (load < min_load) {
  4846. min_load = load;
  4847. least_loaded_cpu = i;
  4848. }
  4849. }
  4850. }
  4851. return shallowest_idle_cpu != -1 ? shallowest_idle_cpu : least_loaded_cpu;
  4852. }
  4853. static inline int find_idlest_cpu(struct sched_domain *sd, struct task_struct *p,
  4854. int cpu, int prev_cpu, int sd_flag)
  4855. {
  4856. int new_cpu = cpu;
  4857. if (!cpumask_intersects(sched_domain_span(sd), &p->cpus_allowed))
  4858. return prev_cpu;
  4859. /*
  4860. * We need task's util for capacity_spare_wake, sync it up to prev_cpu's
  4861. * last_update_time.
  4862. */
  4863. if (!(sd_flag & SD_BALANCE_FORK))
  4864. sync_entity_load_avg(&p->se);
  4865. while (sd) {
  4866. struct sched_group *group;
  4867. struct sched_domain *tmp;
  4868. int weight;
  4869. if (!(sd->flags & sd_flag)) {
  4870. sd = sd->child;
  4871. continue;
  4872. }
  4873. group = find_idlest_group(sd, p, cpu, sd_flag);
  4874. if (!group) {
  4875. sd = sd->child;
  4876. continue;
  4877. }
  4878. new_cpu = find_idlest_group_cpu(group, p, cpu);
  4879. if (new_cpu == cpu) {
  4880. /* Now try balancing at a lower domain level of 'cpu': */
  4881. sd = sd->child;
  4882. continue;
  4883. }
  4884. /* Now try balancing at a lower domain level of 'new_cpu': */
  4885. cpu = new_cpu;
  4886. weight = sd->span_weight;
  4887. sd = NULL;
  4888. for_each_domain(cpu, tmp) {
  4889. if (weight <= tmp->span_weight)
  4890. break;
  4891. if (tmp->flags & sd_flag)
  4892. sd = tmp;
  4893. }
  4894. }
  4895. return new_cpu;
  4896. }
  4897. #ifdef CONFIG_SCHED_SMT
  4898. DEFINE_STATIC_KEY_FALSE(sched_smt_present);
  4899. static inline void set_idle_cores(int cpu, int val)
  4900. {
  4901. struct sched_domain_shared *sds;
  4902. sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
  4903. if (sds)
  4904. WRITE_ONCE(sds->has_idle_cores, val);
  4905. }
  4906. static inline bool test_idle_cores(int cpu, bool def)
  4907. {
  4908. struct sched_domain_shared *sds;
  4909. sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
  4910. if (sds)
  4911. return READ_ONCE(sds->has_idle_cores);
  4912. return def;
  4913. }
  4914. /*
  4915. * Scans the local SMT mask to see if the entire core is idle, and records this
  4916. * information in sd_llc_shared->has_idle_cores.
  4917. *
  4918. * Since SMT siblings share all cache levels, inspecting this limited remote
  4919. * state should be fairly cheap.
  4920. */
  4921. void __update_idle_core(struct rq *rq)
  4922. {
  4923. int core = cpu_of(rq);
  4924. int cpu;
  4925. rcu_read_lock();
  4926. if (test_idle_cores(core, true))
  4927. goto unlock;
  4928. for_each_cpu(cpu, cpu_smt_mask(core)) {
  4929. if (cpu == core)
  4930. continue;
  4931. if (!available_idle_cpu(cpu))
  4932. goto unlock;
  4933. }
  4934. set_idle_cores(core, 1);
  4935. unlock:
  4936. rcu_read_unlock();
  4937. }
  4938. /*
  4939. * Scan the entire LLC domain for idle cores; this dynamically switches off if
  4940. * there are no idle cores left in the system; tracked through
  4941. * sd_llc->shared->has_idle_cores and enabled through update_idle_core() above.
  4942. */
  4943. static int select_idle_core(struct task_struct *p, struct sched_domain *sd, int target)
  4944. {
  4945. struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_idle_mask);
  4946. int core, cpu;
  4947. if (!static_branch_likely(&sched_smt_present))
  4948. return -1;
  4949. if (!test_idle_cores(target, false))
  4950. return -1;
  4951. cpumask_and(cpus, sched_domain_span(sd), &p->cpus_allowed);
  4952. for_each_cpu_wrap(core, cpus, target) {
  4953. bool idle = true;
  4954. for_each_cpu(cpu, cpu_smt_mask(core)) {
  4955. cpumask_clear_cpu(cpu, cpus);
  4956. if (!available_idle_cpu(cpu))
  4957. idle = false;
  4958. }
  4959. if (idle)
  4960. return core;
  4961. }
  4962. /*
  4963. * Failed to find an idle core; stop looking for one.
  4964. */
  4965. set_idle_cores(target, 0);
  4966. return -1;
  4967. }
  4968. /*
  4969. * Scan the local SMT mask for idle CPUs.
  4970. */
  4971. static int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target)
  4972. {
  4973. int cpu;
  4974. if (!static_branch_likely(&sched_smt_present))
  4975. return -1;
  4976. for_each_cpu(cpu, cpu_smt_mask(target)) {
  4977. if (!cpumask_test_cpu(cpu, &p->cpus_allowed))
  4978. continue;
  4979. if (available_idle_cpu(cpu))
  4980. return cpu;
  4981. }
  4982. return -1;
  4983. }
  4984. #else /* CONFIG_SCHED_SMT */
  4985. static inline int select_idle_core(struct task_struct *p, struct sched_domain *sd, int target)
  4986. {
  4987. return -1;
  4988. }
  4989. static inline int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target)
  4990. {
  4991. return -1;
  4992. }
  4993. #endif /* CONFIG_SCHED_SMT */
  4994. /*
  4995. * Scan the LLC domain for idle CPUs; this is dynamically regulated by
  4996. * comparing the average scan cost (tracked in sd->avg_scan_cost) against the
  4997. * average idle time for this rq (as found in rq->avg_idle).
  4998. */
  4999. static int select_idle_cpu(struct task_struct *p, struct sched_domain *sd, int target)
  5000. {
  5001. struct sched_domain *this_sd;
  5002. u64 avg_cost, avg_idle;
  5003. u64 time, cost;
  5004. s64 delta;
  5005. int cpu, nr = INT_MAX;
  5006. this_sd = rcu_dereference(*this_cpu_ptr(&sd_llc));
  5007. if (!this_sd)
  5008. return -1;
  5009. /*
  5010. * Due to large variance we need a large fuzz factor; hackbench in
  5011. * particularly is sensitive here.
  5012. */
  5013. avg_idle = this_rq()->avg_idle / 512;
  5014. avg_cost = this_sd->avg_scan_cost + 1;
  5015. if (sched_feat(SIS_AVG_CPU) && avg_idle < avg_cost)
  5016. return -1;
  5017. if (sched_feat(SIS_PROP)) {
  5018. u64 span_avg = sd->span_weight * avg_idle;
  5019. if (span_avg > 4*avg_cost)
  5020. nr = div_u64(span_avg, avg_cost);
  5021. else
  5022. nr = 4;
  5023. }
  5024. time = local_clock();
  5025. for_each_cpu_wrap(cpu, sched_domain_span(sd), target) {
  5026. if (!--nr)
  5027. return -1;
  5028. if (!cpumask_test_cpu(cpu, &p->cpus_allowed))
  5029. continue;
  5030. if (available_idle_cpu(cpu))
  5031. break;
  5032. }
  5033. time = local_clock() - time;
  5034. cost = this_sd->avg_scan_cost;
  5035. delta = (s64)(time - cost) / 8;
  5036. this_sd->avg_scan_cost += delta;
  5037. return cpu;
  5038. }
  5039. /*
  5040. * Try and locate an idle core/thread in the LLC cache domain.
  5041. */
  5042. static int select_idle_sibling(struct task_struct *p, int prev, int target)
  5043. {
  5044. struct sched_domain *sd;
  5045. int i, recent_used_cpu;
  5046. if (available_idle_cpu(target))
  5047. return target;
  5048. /*
  5049. * If the previous CPU is cache affine and idle, don't be stupid:
  5050. */
  5051. if (prev != target && cpus_share_cache(prev, target) && available_idle_cpu(prev))
  5052. return prev;
  5053. /* Check a recently used CPU as a potential idle candidate: */
  5054. recent_used_cpu = p->recent_used_cpu;
  5055. if (recent_used_cpu != prev &&
  5056. recent_used_cpu != target &&
  5057. cpus_share_cache(recent_used_cpu, target) &&
  5058. available_idle_cpu(recent_used_cpu) &&
  5059. cpumask_test_cpu(p->recent_used_cpu, &p->cpus_allowed)) {
  5060. /*
  5061. * Replace recent_used_cpu with prev as it is a potential
  5062. * candidate for the next wake:
  5063. */
  5064. p->recent_used_cpu = prev;
  5065. return recent_used_cpu;
  5066. }
  5067. sd = rcu_dereference(per_cpu(sd_llc, target));
  5068. if (!sd)
  5069. return target;
  5070. i = select_idle_core(p, sd, target);
  5071. if ((unsigned)i < nr_cpumask_bits)
  5072. return i;
  5073. i = select_idle_cpu(p, sd, target);
  5074. if ((unsigned)i < nr_cpumask_bits)
  5075. return i;
  5076. i = select_idle_smt(p, sd, target);
  5077. if ((unsigned)i < nr_cpumask_bits)
  5078. return i;
  5079. return target;
  5080. }
  5081. /**
  5082. * Amount of capacity of a CPU that is (estimated to be) used by CFS tasks
  5083. * @cpu: the CPU to get the utilization of
  5084. *
  5085. * The unit of the return value must be the one of capacity so we can compare
  5086. * the utilization with the capacity of the CPU that is available for CFS task
  5087. * (ie cpu_capacity).
  5088. *
  5089. * cfs_rq.avg.util_avg is the sum of running time of runnable tasks plus the
  5090. * recent utilization of currently non-runnable tasks on a CPU. It represents
  5091. * the amount of utilization of a CPU in the range [0..capacity_orig] where
  5092. * capacity_orig is the cpu_capacity available at the highest frequency
  5093. * (arch_scale_freq_capacity()).
  5094. * The utilization of a CPU converges towards a sum equal to or less than the
  5095. * current capacity (capacity_curr <= capacity_orig) of the CPU because it is
  5096. * the running time on this CPU scaled by capacity_curr.
  5097. *
  5098. * The estimated utilization of a CPU is defined to be the maximum between its
  5099. * cfs_rq.avg.util_avg and the sum of the estimated utilization of the tasks
  5100. * currently RUNNABLE on that CPU.
  5101. * This allows to properly represent the expected utilization of a CPU which
  5102. * has just got a big task running since a long sleep period. At the same time
  5103. * however it preserves the benefits of the "blocked utilization" in
  5104. * describing the potential for other tasks waking up on the same CPU.
  5105. *
  5106. * Nevertheless, cfs_rq.avg.util_avg can be higher than capacity_curr or even
  5107. * higher than capacity_orig because of unfortunate rounding in
  5108. * cfs.avg.util_avg or just after migrating tasks and new task wakeups until
  5109. * the average stabilizes with the new running time. We need to check that the
  5110. * utilization stays within the range of [0..capacity_orig] and cap it if
  5111. * necessary. Without utilization capping, a group could be seen as overloaded
  5112. * (CPU0 utilization at 121% + CPU1 utilization at 80%) whereas CPU1 has 20% of
  5113. * available capacity. We allow utilization to overshoot capacity_curr (but not
  5114. * capacity_orig) as it useful for predicting the capacity required after task
  5115. * migrations (scheduler-driven DVFS).
  5116. *
  5117. * Return: the (estimated) utilization for the specified CPU
  5118. */
  5119. static inline unsigned long cpu_util(int cpu)
  5120. {
  5121. struct cfs_rq *cfs_rq;
  5122. unsigned int util;
  5123. cfs_rq = &cpu_rq(cpu)->cfs;
  5124. util = READ_ONCE(cfs_rq->avg.util_avg);
  5125. if (sched_feat(UTIL_EST))
  5126. util = max(util, READ_ONCE(cfs_rq->avg.util_est.enqueued));
  5127. return min_t(unsigned long, util, capacity_orig_of(cpu));
  5128. }
  5129. /*
  5130. * cpu_util_wake: Compute CPU utilization with any contributions from
  5131. * the waking task p removed.
  5132. */
  5133. static unsigned long cpu_util_wake(int cpu, struct task_struct *p)
  5134. {
  5135. struct cfs_rq *cfs_rq;
  5136. unsigned int util;
  5137. /* Task has no contribution or is new */
  5138. if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
  5139. return cpu_util(cpu);
  5140. cfs_rq = &cpu_rq(cpu)->cfs;
  5141. util = READ_ONCE(cfs_rq->avg.util_avg);
  5142. /* Discount task's blocked util from CPU's util */
  5143. util -= min_t(unsigned int, util, task_util(p));
  5144. /*
  5145. * Covered cases:
  5146. *
  5147. * a) if *p is the only task sleeping on this CPU, then:
  5148. * cpu_util (== task_util) > util_est (== 0)
  5149. * and thus we return:
  5150. * cpu_util_wake = (cpu_util - task_util) = 0
  5151. *
  5152. * b) if other tasks are SLEEPING on this CPU, which is now exiting
  5153. * IDLE, then:
  5154. * cpu_util >= task_util
  5155. * cpu_util > util_est (== 0)
  5156. * and thus we discount *p's blocked utilization to return:
  5157. * cpu_util_wake = (cpu_util - task_util) >= 0
  5158. *
  5159. * c) if other tasks are RUNNABLE on that CPU and
  5160. * util_est > cpu_util
  5161. * then we use util_est since it returns a more restrictive
  5162. * estimation of the spare capacity on that CPU, by just
  5163. * considering the expected utilization of tasks already
  5164. * runnable on that CPU.
  5165. *
  5166. * Cases a) and b) are covered by the above code, while case c) is
  5167. * covered by the following code when estimated utilization is
  5168. * enabled.
  5169. */
  5170. if (sched_feat(UTIL_EST))
  5171. util = max(util, READ_ONCE(cfs_rq->avg.util_est.enqueued));
  5172. /*
  5173. * Utilization (estimated) can exceed the CPU capacity, thus let's
  5174. * clamp to the maximum CPU capacity to ensure consistency with
  5175. * the cpu_util call.
  5176. */
  5177. return min_t(unsigned long, util, capacity_orig_of(cpu));
  5178. }
  5179. /*
  5180. * Disable WAKE_AFFINE in the case where task @p doesn't fit in the
  5181. * capacity of either the waking CPU @cpu or the previous CPU @prev_cpu.
  5182. *
  5183. * In that case WAKE_AFFINE doesn't make sense and we'll let
  5184. * BALANCE_WAKE sort things out.
  5185. */
  5186. static int wake_cap(struct task_struct *p, int cpu, int prev_cpu)
  5187. {
  5188. long min_cap, max_cap;
  5189. min_cap = min(capacity_orig_of(prev_cpu), capacity_orig_of(cpu));
  5190. max_cap = cpu_rq(cpu)->rd->max_cpu_capacity;
  5191. /* Minimum capacity is close to max, no need to abort wake_affine */
  5192. if (max_cap - min_cap < max_cap >> 3)
  5193. return 0;
  5194. /* Bring task utilization in sync with prev_cpu */
  5195. sync_entity_load_avg(&p->se);
  5196. return min_cap * 1024 < task_util(p) * capacity_margin;
  5197. }
  5198. /*
  5199. * select_task_rq_fair: Select target runqueue for the waking task in domains
  5200. * that have the 'sd_flag' flag set. In practice, this is SD_BALANCE_WAKE,
  5201. * SD_BALANCE_FORK, or SD_BALANCE_EXEC.
  5202. *
  5203. * Balances load by selecting the idlest CPU in the idlest group, or under
  5204. * certain conditions an idle sibling CPU if the domain has SD_WAKE_AFFINE set.
  5205. *
  5206. * Returns the target CPU number.
  5207. *
  5208. * preempt must be disabled.
  5209. */
  5210. static int
  5211. select_task_rq_fair(struct task_struct *p, int prev_cpu, int sd_flag, int wake_flags)
  5212. {
  5213. struct sched_domain *tmp, *sd = NULL;
  5214. int cpu = smp_processor_id();
  5215. int new_cpu = prev_cpu;
  5216. int want_affine = 0;
  5217. int sync = (wake_flags & WF_SYNC) && !(current->flags & PF_EXITING);
  5218. if (sd_flag & SD_BALANCE_WAKE) {
  5219. record_wakee(p);
  5220. want_affine = !wake_wide(p) && !wake_cap(p, cpu, prev_cpu)
  5221. && cpumask_test_cpu(cpu, &p->cpus_allowed);
  5222. }
  5223. rcu_read_lock();
  5224. for_each_domain(cpu, tmp) {
  5225. if (!(tmp->flags & SD_LOAD_BALANCE))
  5226. break;
  5227. /*
  5228. * If both 'cpu' and 'prev_cpu' are part of this domain,
  5229. * cpu is a valid SD_WAKE_AFFINE target.
  5230. */
  5231. if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
  5232. cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
  5233. if (cpu != prev_cpu)
  5234. new_cpu = wake_affine(tmp, p, cpu, prev_cpu, sync);
  5235. sd = NULL; /* Prefer wake_affine over balance flags */
  5236. break;
  5237. }
  5238. if (tmp->flags & sd_flag)
  5239. sd = tmp;
  5240. else if (!want_affine)
  5241. break;
  5242. }
  5243. if (unlikely(sd)) {
  5244. /* Slow path */
  5245. new_cpu = find_idlest_cpu(sd, p, cpu, prev_cpu, sd_flag);
  5246. } else if (sd_flag & SD_BALANCE_WAKE) { /* XXX always ? */
  5247. /* Fast path */
  5248. new_cpu = select_idle_sibling(p, prev_cpu, new_cpu);
  5249. if (want_affine)
  5250. current->recent_used_cpu = cpu;
  5251. }
  5252. rcu_read_unlock();
  5253. return new_cpu;
  5254. }
  5255. static void detach_entity_cfs_rq(struct sched_entity *se);
  5256. /*
  5257. * Called immediately before a task is migrated to a new CPU; task_cpu(p) and
  5258. * cfs_rq_of(p) references at time of call are still valid and identify the
  5259. * previous CPU. The caller guarantees p->pi_lock or task_rq(p)->lock is held.
  5260. */
  5261. static void migrate_task_rq_fair(struct task_struct *p)
  5262. {
  5263. /*
  5264. * As blocked tasks retain absolute vruntime the migration needs to
  5265. * deal with this by subtracting the old and adding the new
  5266. * min_vruntime -- the latter is done by enqueue_entity() when placing
  5267. * the task on the new runqueue.
  5268. */
  5269. if (p->state == TASK_WAKING) {
  5270. struct sched_entity *se = &p->se;
  5271. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  5272. u64 min_vruntime;
  5273. #ifndef CONFIG_64BIT
  5274. u64 min_vruntime_copy;
  5275. do {
  5276. min_vruntime_copy = cfs_rq->min_vruntime_copy;
  5277. smp_rmb();
  5278. min_vruntime = cfs_rq->min_vruntime;
  5279. } while (min_vruntime != min_vruntime_copy);
  5280. #else
  5281. min_vruntime = cfs_rq->min_vruntime;
  5282. #endif
  5283. se->vruntime -= min_vruntime;
  5284. }
  5285. if (p->on_rq == TASK_ON_RQ_MIGRATING) {
  5286. /*
  5287. * In case of TASK_ON_RQ_MIGRATING we in fact hold the 'old'
  5288. * rq->lock and can modify state directly.
  5289. */
  5290. lockdep_assert_held(&task_rq(p)->lock);
  5291. detach_entity_cfs_rq(&p->se);
  5292. } else {
  5293. /*
  5294. * We are supposed to update the task to "current" time, then
  5295. * its up to date and ready to go to new CPU/cfs_rq. But we
  5296. * have difficulty in getting what current time is, so simply
  5297. * throw away the out-of-date time. This will result in the
  5298. * wakee task is less decayed, but giving the wakee more load
  5299. * sounds not bad.
  5300. */
  5301. remove_entity_load_avg(&p->se);
  5302. }
  5303. /* Tell new CPU we are migrated */
  5304. p->se.avg.last_update_time = 0;
  5305. /* We have migrated, no longer consider this task hot */
  5306. p->se.exec_start = 0;
  5307. }
  5308. static void task_dead_fair(struct task_struct *p)
  5309. {
  5310. remove_entity_load_avg(&p->se);
  5311. }
  5312. #endif /* CONFIG_SMP */
  5313. static unsigned long wakeup_gran(struct sched_entity *se)
  5314. {
  5315. unsigned long gran = sysctl_sched_wakeup_granularity;
  5316. /*
  5317. * Since its curr running now, convert the gran from real-time
  5318. * to virtual-time in his units.
  5319. *
  5320. * By using 'se' instead of 'curr' we penalize light tasks, so
  5321. * they get preempted easier. That is, if 'se' < 'curr' then
  5322. * the resulting gran will be larger, therefore penalizing the
  5323. * lighter, if otoh 'se' > 'curr' then the resulting gran will
  5324. * be smaller, again penalizing the lighter task.
  5325. *
  5326. * This is especially important for buddies when the leftmost
  5327. * task is higher priority than the buddy.
  5328. */
  5329. return calc_delta_fair(gran, se);
  5330. }
  5331. /*
  5332. * Should 'se' preempt 'curr'.
  5333. *
  5334. * |s1
  5335. * |s2
  5336. * |s3
  5337. * g
  5338. * |<--->|c
  5339. *
  5340. * w(c, s1) = -1
  5341. * w(c, s2) = 0
  5342. * w(c, s3) = 1
  5343. *
  5344. */
  5345. static int
  5346. wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se)
  5347. {
  5348. s64 gran, vdiff = curr->vruntime - se->vruntime;
  5349. if (vdiff <= 0)
  5350. return -1;
  5351. gran = wakeup_gran(se);
  5352. if (vdiff > gran)
  5353. return 1;
  5354. return 0;
  5355. }
  5356. static void set_last_buddy(struct sched_entity *se)
  5357. {
  5358. if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE))
  5359. return;
  5360. for_each_sched_entity(se) {
  5361. if (SCHED_WARN_ON(!se->on_rq))
  5362. return;
  5363. cfs_rq_of(se)->last = se;
  5364. }
  5365. }
  5366. static void set_next_buddy(struct sched_entity *se)
  5367. {
  5368. if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE))
  5369. return;
  5370. for_each_sched_entity(se) {
  5371. if (SCHED_WARN_ON(!se->on_rq))
  5372. return;
  5373. cfs_rq_of(se)->next = se;
  5374. }
  5375. }
  5376. static void set_skip_buddy(struct sched_entity *se)
  5377. {
  5378. for_each_sched_entity(se)
  5379. cfs_rq_of(se)->skip = se;
  5380. }
  5381. /*
  5382. * Preempt the current task with a newly woken task if needed:
  5383. */
  5384. static void check_preempt_wakeup(struct rq *rq, struct task_struct *p, int wake_flags)
  5385. {
  5386. struct task_struct *curr = rq->curr;
  5387. struct sched_entity *se = &curr->se, *pse = &p->se;
  5388. struct cfs_rq *cfs_rq = task_cfs_rq(curr);
  5389. int scale = cfs_rq->nr_running >= sched_nr_latency;
  5390. int next_buddy_marked = 0;
  5391. if (unlikely(se == pse))
  5392. return;
  5393. /*
  5394. * This is possible from callers such as attach_tasks(), in which we
  5395. * unconditionally check_prempt_curr() after an enqueue (which may have
  5396. * lead to a throttle). This both saves work and prevents false
  5397. * next-buddy nomination below.
  5398. */
  5399. if (unlikely(throttled_hierarchy(cfs_rq_of(pse))))
  5400. return;
  5401. if (sched_feat(NEXT_BUDDY) && scale && !(wake_flags & WF_FORK)) {
  5402. set_next_buddy(pse);
  5403. next_buddy_marked = 1;
  5404. }
  5405. /*
  5406. * We can come here with TIF_NEED_RESCHED already set from new task
  5407. * wake up path.
  5408. *
  5409. * Note: this also catches the edge-case of curr being in a throttled
  5410. * group (e.g. via set_curr_task), since update_curr() (in the
  5411. * enqueue of curr) will have resulted in resched being set. This
  5412. * prevents us from potentially nominating it as a false LAST_BUDDY
  5413. * below.
  5414. */
  5415. if (test_tsk_need_resched(curr))
  5416. return;
  5417. /* Idle tasks are by definition preempted by non-idle tasks. */
  5418. if (unlikely(curr->policy == SCHED_IDLE) &&
  5419. likely(p->policy != SCHED_IDLE))
  5420. goto preempt;
  5421. /*
  5422. * Batch and idle tasks do not preempt non-idle tasks (their preemption
  5423. * is driven by the tick):
  5424. */
  5425. if (unlikely(p->policy != SCHED_NORMAL) || !sched_feat(WAKEUP_PREEMPTION))
  5426. return;
  5427. find_matching_se(&se, &pse);
  5428. update_curr(cfs_rq_of(se));
  5429. BUG_ON(!pse);
  5430. if (wakeup_preempt_entity(se, pse) == 1) {
  5431. /*
  5432. * Bias pick_next to pick the sched entity that is
  5433. * triggering this preemption.
  5434. */
  5435. if (!next_buddy_marked)
  5436. set_next_buddy(pse);
  5437. goto preempt;
  5438. }
  5439. return;
  5440. preempt:
  5441. resched_curr(rq);
  5442. /*
  5443. * Only set the backward buddy when the current task is still
  5444. * on the rq. This can happen when a wakeup gets interleaved
  5445. * with schedule on the ->pre_schedule() or idle_balance()
  5446. * point, either of which can * drop the rq lock.
  5447. *
  5448. * Also, during early boot the idle thread is in the fair class,
  5449. * for obvious reasons its a bad idea to schedule back to it.
  5450. */
  5451. if (unlikely(!se->on_rq || curr == rq->idle))
  5452. return;
  5453. if (sched_feat(LAST_BUDDY) && scale && entity_is_task(se))
  5454. set_last_buddy(se);
  5455. }
  5456. static struct task_struct *
  5457. pick_next_task_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
  5458. {
  5459. struct cfs_rq *cfs_rq = &rq->cfs;
  5460. struct sched_entity *se;
  5461. struct task_struct *p;
  5462. int new_tasks;
  5463. again:
  5464. if (!cfs_rq->nr_running)
  5465. goto idle;
  5466. #ifdef CONFIG_FAIR_GROUP_SCHED
  5467. if (prev->sched_class != &fair_sched_class)
  5468. goto simple;
  5469. /*
  5470. * Because of the set_next_buddy() in dequeue_task_fair() it is rather
  5471. * likely that a next task is from the same cgroup as the current.
  5472. *
  5473. * Therefore attempt to avoid putting and setting the entire cgroup
  5474. * hierarchy, only change the part that actually changes.
  5475. */
  5476. do {
  5477. struct sched_entity *curr = cfs_rq->curr;
  5478. /*
  5479. * Since we got here without doing put_prev_entity() we also
  5480. * have to consider cfs_rq->curr. If it is still a runnable
  5481. * entity, update_curr() will update its vruntime, otherwise
  5482. * forget we've ever seen it.
  5483. */
  5484. if (curr) {
  5485. if (curr->on_rq)
  5486. update_curr(cfs_rq);
  5487. else
  5488. curr = NULL;
  5489. /*
  5490. * This call to check_cfs_rq_runtime() will do the
  5491. * throttle and dequeue its entity in the parent(s).
  5492. * Therefore the nr_running test will indeed
  5493. * be correct.
  5494. */
  5495. if (unlikely(check_cfs_rq_runtime(cfs_rq))) {
  5496. cfs_rq = &rq->cfs;
  5497. if (!cfs_rq->nr_running)
  5498. goto idle;
  5499. goto simple;
  5500. }
  5501. }
  5502. se = pick_next_entity(cfs_rq, curr);
  5503. cfs_rq = group_cfs_rq(se);
  5504. } while (cfs_rq);
  5505. p = task_of(se);
  5506. /*
  5507. * Since we haven't yet done put_prev_entity and if the selected task
  5508. * is a different task than we started out with, try and touch the
  5509. * least amount of cfs_rqs.
  5510. */
  5511. if (prev != p) {
  5512. struct sched_entity *pse = &prev->se;
  5513. while (!(cfs_rq = is_same_group(se, pse))) {
  5514. int se_depth = se->depth;
  5515. int pse_depth = pse->depth;
  5516. if (se_depth <= pse_depth) {
  5517. put_prev_entity(cfs_rq_of(pse), pse);
  5518. pse = parent_entity(pse);
  5519. }
  5520. if (se_depth >= pse_depth) {
  5521. set_next_entity(cfs_rq_of(se), se);
  5522. se = parent_entity(se);
  5523. }
  5524. }
  5525. put_prev_entity(cfs_rq, pse);
  5526. set_next_entity(cfs_rq, se);
  5527. }
  5528. goto done;
  5529. simple:
  5530. #endif
  5531. put_prev_task(rq, prev);
  5532. do {
  5533. se = pick_next_entity(cfs_rq, NULL);
  5534. set_next_entity(cfs_rq, se);
  5535. cfs_rq = group_cfs_rq(se);
  5536. } while (cfs_rq);
  5537. p = task_of(se);
  5538. done: __maybe_unused;
  5539. #ifdef CONFIG_SMP
  5540. /*
  5541. * Move the next running task to the front of
  5542. * the list, so our cfs_tasks list becomes MRU
  5543. * one.
  5544. */
  5545. list_move(&p->se.group_node, &rq->cfs_tasks);
  5546. #endif
  5547. if (hrtick_enabled(rq))
  5548. hrtick_start_fair(rq, p);
  5549. return p;
  5550. idle:
  5551. new_tasks = idle_balance(rq, rf);
  5552. /*
  5553. * Because idle_balance() releases (and re-acquires) rq->lock, it is
  5554. * possible for any higher priority task to appear. In that case we
  5555. * must re-start the pick_next_entity() loop.
  5556. */
  5557. if (new_tasks < 0)
  5558. return RETRY_TASK;
  5559. if (new_tasks > 0)
  5560. goto again;
  5561. return NULL;
  5562. }
  5563. /*
  5564. * Account for a descheduled task:
  5565. */
  5566. static void put_prev_task_fair(struct rq *rq, struct task_struct *prev)
  5567. {
  5568. struct sched_entity *se = &prev->se;
  5569. struct cfs_rq *cfs_rq;
  5570. for_each_sched_entity(se) {
  5571. cfs_rq = cfs_rq_of(se);
  5572. put_prev_entity(cfs_rq, se);
  5573. }
  5574. }
  5575. /*
  5576. * sched_yield() is very simple
  5577. *
  5578. * The magic of dealing with the ->skip buddy is in pick_next_entity.
  5579. */
  5580. static void yield_task_fair(struct rq *rq)
  5581. {
  5582. struct task_struct *curr = rq->curr;
  5583. struct cfs_rq *cfs_rq = task_cfs_rq(curr);
  5584. struct sched_entity *se = &curr->se;
  5585. /*
  5586. * Are we the only task in the tree?
  5587. */
  5588. if (unlikely(rq->nr_running == 1))
  5589. return;
  5590. clear_buddies(cfs_rq, se);
  5591. if (curr->policy != SCHED_BATCH) {
  5592. update_rq_clock(rq);
  5593. /*
  5594. * Update run-time statistics of the 'current'.
  5595. */
  5596. update_curr(cfs_rq);
  5597. /*
  5598. * Tell update_rq_clock() that we've just updated,
  5599. * so we don't do microscopic update in schedule()
  5600. * and double the fastpath cost.
  5601. */
  5602. rq_clock_skip_update(rq);
  5603. }
  5604. set_skip_buddy(se);
  5605. }
  5606. static bool yield_to_task_fair(struct rq *rq, struct task_struct *p, bool preempt)
  5607. {
  5608. struct sched_entity *se = &p->se;
  5609. /* throttled hierarchies are not runnable */
  5610. if (!se->on_rq || throttled_hierarchy(cfs_rq_of(se)))
  5611. return false;
  5612. /* Tell the scheduler that we'd really like pse to run next. */
  5613. set_next_buddy(se);
  5614. yield_task_fair(rq);
  5615. return true;
  5616. }
  5617. #ifdef CONFIG_SMP
  5618. /**************************************************
  5619. * Fair scheduling class load-balancing methods.
  5620. *
  5621. * BASICS
  5622. *
  5623. * The purpose of load-balancing is to achieve the same basic fairness the
  5624. * per-CPU scheduler provides, namely provide a proportional amount of compute
  5625. * time to each task. This is expressed in the following equation:
  5626. *
  5627. * W_i,n/P_i == W_j,n/P_j for all i,j (1)
  5628. *
  5629. * Where W_i,n is the n-th weight average for CPU i. The instantaneous weight
  5630. * W_i,0 is defined as:
  5631. *
  5632. * W_i,0 = \Sum_j w_i,j (2)
  5633. *
  5634. * Where w_i,j is the weight of the j-th runnable task on CPU i. This weight
  5635. * is derived from the nice value as per sched_prio_to_weight[].
  5636. *
  5637. * The weight average is an exponential decay average of the instantaneous
  5638. * weight:
  5639. *
  5640. * W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0 (3)
  5641. *
  5642. * C_i is the compute capacity of CPU i, typically it is the
  5643. * fraction of 'recent' time available for SCHED_OTHER task execution. But it
  5644. * can also include other factors [XXX].
  5645. *
  5646. * To achieve this balance we define a measure of imbalance which follows
  5647. * directly from (1):
  5648. *
  5649. * imb_i,j = max{ avg(W/C), W_i/C_i } - min{ avg(W/C), W_j/C_j } (4)
  5650. *
  5651. * We them move tasks around to minimize the imbalance. In the continuous
  5652. * function space it is obvious this converges, in the discrete case we get
  5653. * a few fun cases generally called infeasible weight scenarios.
  5654. *
  5655. * [XXX expand on:
  5656. * - infeasible weights;
  5657. * - local vs global optima in the discrete case. ]
  5658. *
  5659. *
  5660. * SCHED DOMAINS
  5661. *
  5662. * In order to solve the imbalance equation (4), and avoid the obvious O(n^2)
  5663. * for all i,j solution, we create a tree of CPUs that follows the hardware
  5664. * topology where each level pairs two lower groups (or better). This results
  5665. * in O(log n) layers. Furthermore we reduce the number of CPUs going up the
  5666. * tree to only the first of the previous level and we decrease the frequency
  5667. * of load-balance at each level inv. proportional to the number of CPUs in
  5668. * the groups.
  5669. *
  5670. * This yields:
  5671. *
  5672. * log_2 n 1 n
  5673. * \Sum { --- * --- * 2^i } = O(n) (5)
  5674. * i = 0 2^i 2^i
  5675. * `- size of each group
  5676. * | | `- number of CPUs doing load-balance
  5677. * | `- freq
  5678. * `- sum over all levels
  5679. *
  5680. * Coupled with a limit on how many tasks we can migrate every balance pass,
  5681. * this makes (5) the runtime complexity of the balancer.
  5682. *
  5683. * An important property here is that each CPU is still (indirectly) connected
  5684. * to every other CPU in at most O(log n) steps:
  5685. *
  5686. * The adjacency matrix of the resulting graph is given by:
  5687. *
  5688. * log_2 n
  5689. * A_i,j = \Union (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1) (6)
  5690. * k = 0
  5691. *
  5692. * And you'll find that:
  5693. *
  5694. * A^(log_2 n)_i,j != 0 for all i,j (7)
  5695. *
  5696. * Showing there's indeed a path between every CPU in at most O(log n) steps.
  5697. * The task movement gives a factor of O(m), giving a convergence complexity
  5698. * of:
  5699. *
  5700. * O(nm log n), n := nr_cpus, m := nr_tasks (8)
  5701. *
  5702. *
  5703. * WORK CONSERVING
  5704. *
  5705. * In order to avoid CPUs going idle while there's still work to do, new idle
  5706. * balancing is more aggressive and has the newly idle CPU iterate up the domain
  5707. * tree itself instead of relying on other CPUs to bring it work.
  5708. *
  5709. * This adds some complexity to both (5) and (8) but it reduces the total idle
  5710. * time.
  5711. *
  5712. * [XXX more?]
  5713. *
  5714. *
  5715. * CGROUPS
  5716. *
  5717. * Cgroups make a horror show out of (2), instead of a simple sum we get:
  5718. *
  5719. * s_k,i
  5720. * W_i,0 = \Sum_j \Prod_k w_k * ----- (9)
  5721. * S_k
  5722. *
  5723. * Where
  5724. *
  5725. * s_k,i = \Sum_j w_i,j,k and S_k = \Sum_i s_k,i (10)
  5726. *
  5727. * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on CPU i.
  5728. *
  5729. * The big problem is S_k, its a global sum needed to compute a local (W_i)
  5730. * property.
  5731. *
  5732. * [XXX write more on how we solve this.. _after_ merging pjt's patches that
  5733. * rewrite all of this once again.]
  5734. */
  5735. static unsigned long __read_mostly max_load_balance_interval = HZ/10;
  5736. enum fbq_type { regular, remote, all };
  5737. #define LBF_ALL_PINNED 0x01
  5738. #define LBF_NEED_BREAK 0x02
  5739. #define LBF_DST_PINNED 0x04
  5740. #define LBF_SOME_PINNED 0x08
  5741. #define LBF_NOHZ_STATS 0x10
  5742. #define LBF_NOHZ_AGAIN 0x20
  5743. struct lb_env {
  5744. struct sched_domain *sd;
  5745. struct rq *src_rq;
  5746. int src_cpu;
  5747. int dst_cpu;
  5748. struct rq *dst_rq;
  5749. struct cpumask *dst_grpmask;
  5750. int new_dst_cpu;
  5751. enum cpu_idle_type idle;
  5752. long imbalance;
  5753. /* The set of CPUs under consideration for load-balancing */
  5754. struct cpumask *cpus;
  5755. unsigned int flags;
  5756. unsigned int loop;
  5757. unsigned int loop_break;
  5758. unsigned int loop_max;
  5759. enum fbq_type fbq_type;
  5760. struct list_head tasks;
  5761. };
  5762. /*
  5763. * Is this task likely cache-hot:
  5764. */
  5765. static int task_hot(struct task_struct *p, struct lb_env *env)
  5766. {
  5767. s64 delta;
  5768. lockdep_assert_held(&env->src_rq->lock);
  5769. if (p->sched_class != &fair_sched_class)
  5770. return 0;
  5771. if (unlikely(p->policy == SCHED_IDLE))
  5772. return 0;
  5773. /*
  5774. * Buddy candidates are cache hot:
  5775. */
  5776. if (sched_feat(CACHE_HOT_BUDDY) && env->dst_rq->nr_running &&
  5777. (&p->se == cfs_rq_of(&p->se)->next ||
  5778. &p->se == cfs_rq_of(&p->se)->last))
  5779. return 1;
  5780. if (sysctl_sched_migration_cost == -1)
  5781. return 1;
  5782. if (sysctl_sched_migration_cost == 0)
  5783. return 0;
  5784. delta = rq_clock_task(env->src_rq) - p->se.exec_start;
  5785. return delta < (s64)sysctl_sched_migration_cost;
  5786. }
  5787. #ifdef CONFIG_NUMA_BALANCING
  5788. /*
  5789. * Returns 1, if task migration degrades locality
  5790. * Returns 0, if task migration improves locality i.e migration preferred.
  5791. * Returns -1, if task migration is not affected by locality.
  5792. */
  5793. static int migrate_degrades_locality(struct task_struct *p, struct lb_env *env)
  5794. {
  5795. struct numa_group *numa_group = rcu_dereference(p->numa_group);
  5796. unsigned long src_weight, dst_weight;
  5797. int src_nid, dst_nid, dist;
  5798. if (!static_branch_likely(&sched_numa_balancing))
  5799. return -1;
  5800. if (!p->numa_faults || !(env->sd->flags & SD_NUMA))
  5801. return -1;
  5802. src_nid = cpu_to_node(env->src_cpu);
  5803. dst_nid = cpu_to_node(env->dst_cpu);
  5804. if (src_nid == dst_nid)
  5805. return -1;
  5806. /* Migrating away from the preferred node is always bad. */
  5807. if (src_nid == p->numa_preferred_nid) {
  5808. if (env->src_rq->nr_running > env->src_rq->nr_preferred_running)
  5809. return 1;
  5810. else
  5811. return -1;
  5812. }
  5813. /* Encourage migration to the preferred node. */
  5814. if (dst_nid == p->numa_preferred_nid)
  5815. return 0;
  5816. /* Leaving a core idle is often worse than degrading locality. */
  5817. if (env->idle == CPU_IDLE)
  5818. return -1;
  5819. dist = node_distance(src_nid, dst_nid);
  5820. if (numa_group) {
  5821. src_weight = group_weight(p, src_nid, dist);
  5822. dst_weight = group_weight(p, dst_nid, dist);
  5823. } else {
  5824. src_weight = task_weight(p, src_nid, dist);
  5825. dst_weight = task_weight(p, dst_nid, dist);
  5826. }
  5827. return dst_weight < src_weight;
  5828. }
  5829. #else
  5830. static inline int migrate_degrades_locality(struct task_struct *p,
  5831. struct lb_env *env)
  5832. {
  5833. return -1;
  5834. }
  5835. #endif
  5836. /*
  5837. * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
  5838. */
  5839. static
  5840. int can_migrate_task(struct task_struct *p, struct lb_env *env)
  5841. {
  5842. int tsk_cache_hot;
  5843. lockdep_assert_held(&env->src_rq->lock);
  5844. /*
  5845. * We do not migrate tasks that are:
  5846. * 1) throttled_lb_pair, or
  5847. * 2) cannot be migrated to this CPU due to cpus_allowed, or
  5848. * 3) running (obviously), or
  5849. * 4) are cache-hot on their current CPU.
  5850. */
  5851. if (throttled_lb_pair(task_group(p), env->src_cpu, env->dst_cpu))
  5852. return 0;
  5853. if (!cpumask_test_cpu(env->dst_cpu, &p->cpus_allowed)) {
  5854. int cpu;
  5855. schedstat_inc(p->se.statistics.nr_failed_migrations_affine);
  5856. env->flags |= LBF_SOME_PINNED;
  5857. /*
  5858. * Remember if this task can be migrated to any other CPU in
  5859. * our sched_group. We may want to revisit it if we couldn't
  5860. * meet load balance goals by pulling other tasks on src_cpu.
  5861. *
  5862. * Avoid computing new_dst_cpu for NEWLY_IDLE or if we have
  5863. * already computed one in current iteration.
  5864. */
  5865. if (env->idle == CPU_NEWLY_IDLE || (env->flags & LBF_DST_PINNED))
  5866. return 0;
  5867. /* Prevent to re-select dst_cpu via env's CPUs: */
  5868. for_each_cpu_and(cpu, env->dst_grpmask, env->cpus) {
  5869. if (cpumask_test_cpu(cpu, &p->cpus_allowed)) {
  5870. env->flags |= LBF_DST_PINNED;
  5871. env->new_dst_cpu = cpu;
  5872. break;
  5873. }
  5874. }
  5875. return 0;
  5876. }
  5877. /* Record that we found atleast one task that could run on dst_cpu */
  5878. env->flags &= ~LBF_ALL_PINNED;
  5879. if (task_running(env->src_rq, p)) {
  5880. schedstat_inc(p->se.statistics.nr_failed_migrations_running);
  5881. return 0;
  5882. }
  5883. /*
  5884. * Aggressive migration if:
  5885. * 1) destination numa is preferred
  5886. * 2) task is cache cold, or
  5887. * 3) too many balance attempts have failed.
  5888. */
  5889. tsk_cache_hot = migrate_degrades_locality(p, env);
  5890. if (tsk_cache_hot == -1)
  5891. tsk_cache_hot = task_hot(p, env);
  5892. if (tsk_cache_hot <= 0 ||
  5893. env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
  5894. if (tsk_cache_hot == 1) {
  5895. schedstat_inc(env->sd->lb_hot_gained[env->idle]);
  5896. schedstat_inc(p->se.statistics.nr_forced_migrations);
  5897. }
  5898. return 1;
  5899. }
  5900. schedstat_inc(p->se.statistics.nr_failed_migrations_hot);
  5901. return 0;
  5902. }
  5903. /*
  5904. * detach_task() -- detach the task for the migration specified in env
  5905. */
  5906. static void detach_task(struct task_struct *p, struct lb_env *env)
  5907. {
  5908. lockdep_assert_held(&env->src_rq->lock);
  5909. p->on_rq = TASK_ON_RQ_MIGRATING;
  5910. deactivate_task(env->src_rq, p, DEQUEUE_NOCLOCK);
  5911. set_task_cpu(p, env->dst_cpu);
  5912. }
  5913. /*
  5914. * detach_one_task() -- tries to dequeue exactly one task from env->src_rq, as
  5915. * part of active balancing operations within "domain".
  5916. *
  5917. * Returns a task if successful and NULL otherwise.
  5918. */
  5919. static struct task_struct *detach_one_task(struct lb_env *env)
  5920. {
  5921. struct task_struct *p;
  5922. lockdep_assert_held(&env->src_rq->lock);
  5923. list_for_each_entry_reverse(p,
  5924. &env->src_rq->cfs_tasks, se.group_node) {
  5925. if (!can_migrate_task(p, env))
  5926. continue;
  5927. detach_task(p, env);
  5928. /*
  5929. * Right now, this is only the second place where
  5930. * lb_gained[env->idle] is updated (other is detach_tasks)
  5931. * so we can safely collect stats here rather than
  5932. * inside detach_tasks().
  5933. */
  5934. schedstat_inc(env->sd->lb_gained[env->idle]);
  5935. return p;
  5936. }
  5937. return NULL;
  5938. }
  5939. static const unsigned int sched_nr_migrate_break = 32;
  5940. /*
  5941. * detach_tasks() -- tries to detach up to imbalance weighted load from
  5942. * busiest_rq, as part of a balancing operation within domain "sd".
  5943. *
  5944. * Returns number of detached tasks if successful and 0 otherwise.
  5945. */
  5946. static int detach_tasks(struct lb_env *env)
  5947. {
  5948. struct list_head *tasks = &env->src_rq->cfs_tasks;
  5949. struct task_struct *p;
  5950. unsigned long load;
  5951. int detached = 0;
  5952. lockdep_assert_held(&env->src_rq->lock);
  5953. if (env->imbalance <= 0)
  5954. return 0;
  5955. while (!list_empty(tasks)) {
  5956. /*
  5957. * We don't want to steal all, otherwise we may be treated likewise,
  5958. * which could at worst lead to a livelock crash.
  5959. */
  5960. if (env->idle != CPU_NOT_IDLE && env->src_rq->nr_running <= 1)
  5961. break;
  5962. p = list_last_entry(tasks, struct task_struct, se.group_node);
  5963. env->loop++;
  5964. /* We've more or less seen every task there is, call it quits */
  5965. if (env->loop > env->loop_max)
  5966. break;
  5967. /* take a breather every nr_migrate tasks */
  5968. if (env->loop > env->loop_break) {
  5969. env->loop_break += sched_nr_migrate_break;
  5970. env->flags |= LBF_NEED_BREAK;
  5971. break;
  5972. }
  5973. if (!can_migrate_task(p, env))
  5974. goto next;
  5975. load = task_h_load(p);
  5976. if (sched_feat(LB_MIN) && load < 16 && !env->sd->nr_balance_failed)
  5977. goto next;
  5978. if ((load / 2) > env->imbalance)
  5979. goto next;
  5980. detach_task(p, env);
  5981. list_add(&p->se.group_node, &env->tasks);
  5982. detached++;
  5983. env->imbalance -= load;
  5984. #ifdef CONFIG_PREEMPT
  5985. /*
  5986. * NEWIDLE balancing is a source of latency, so preemptible
  5987. * kernels will stop after the first task is detached to minimize
  5988. * the critical section.
  5989. */
  5990. if (env->idle == CPU_NEWLY_IDLE)
  5991. break;
  5992. #endif
  5993. /*
  5994. * We only want to steal up to the prescribed amount of
  5995. * weighted load.
  5996. */
  5997. if (env->imbalance <= 0)
  5998. break;
  5999. continue;
  6000. next:
  6001. list_move(&p->se.group_node, tasks);
  6002. }
  6003. /*
  6004. * Right now, this is one of only two places we collect this stat
  6005. * so we can safely collect detach_one_task() stats here rather
  6006. * than inside detach_one_task().
  6007. */
  6008. schedstat_add(env->sd->lb_gained[env->idle], detached);
  6009. return detached;
  6010. }
  6011. /*
  6012. * attach_task() -- attach the task detached by detach_task() to its new rq.
  6013. */
  6014. static void attach_task(struct rq *rq, struct task_struct *p)
  6015. {
  6016. lockdep_assert_held(&rq->lock);
  6017. BUG_ON(task_rq(p) != rq);
  6018. activate_task(rq, p, ENQUEUE_NOCLOCK);
  6019. p->on_rq = TASK_ON_RQ_QUEUED;
  6020. check_preempt_curr(rq, p, 0);
  6021. }
  6022. /*
  6023. * attach_one_task() -- attaches the task returned from detach_one_task() to
  6024. * its new rq.
  6025. */
  6026. static void attach_one_task(struct rq *rq, struct task_struct *p)
  6027. {
  6028. struct rq_flags rf;
  6029. rq_lock(rq, &rf);
  6030. update_rq_clock(rq);
  6031. attach_task(rq, p);
  6032. rq_unlock(rq, &rf);
  6033. }
  6034. /*
  6035. * attach_tasks() -- attaches all tasks detached by detach_tasks() to their
  6036. * new rq.
  6037. */
  6038. static void attach_tasks(struct lb_env *env)
  6039. {
  6040. struct list_head *tasks = &env->tasks;
  6041. struct task_struct *p;
  6042. struct rq_flags rf;
  6043. rq_lock(env->dst_rq, &rf);
  6044. update_rq_clock(env->dst_rq);
  6045. while (!list_empty(tasks)) {
  6046. p = list_first_entry(tasks, struct task_struct, se.group_node);
  6047. list_del_init(&p->se.group_node);
  6048. attach_task(env->dst_rq, p);
  6049. }
  6050. rq_unlock(env->dst_rq, &rf);
  6051. }
  6052. static inline bool cfs_rq_has_blocked(struct cfs_rq *cfs_rq)
  6053. {
  6054. if (cfs_rq->avg.load_avg)
  6055. return true;
  6056. if (cfs_rq->avg.util_avg)
  6057. return true;
  6058. return false;
  6059. }
  6060. static inline bool others_have_blocked(struct rq *rq)
  6061. {
  6062. if (READ_ONCE(rq->avg_rt.util_avg))
  6063. return true;
  6064. if (READ_ONCE(rq->avg_dl.util_avg))
  6065. return true;
  6066. #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
  6067. if (READ_ONCE(rq->avg_irq.util_avg))
  6068. return true;
  6069. #endif
  6070. return false;
  6071. }
  6072. #ifdef CONFIG_FAIR_GROUP_SCHED
  6073. static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq)
  6074. {
  6075. if (cfs_rq->load.weight)
  6076. return false;
  6077. if (cfs_rq->avg.load_sum)
  6078. return false;
  6079. if (cfs_rq->avg.util_sum)
  6080. return false;
  6081. if (cfs_rq->avg.runnable_load_sum)
  6082. return false;
  6083. return true;
  6084. }
  6085. static void update_blocked_averages(int cpu)
  6086. {
  6087. struct rq *rq = cpu_rq(cpu);
  6088. struct cfs_rq *cfs_rq, *pos;
  6089. struct rq_flags rf;
  6090. bool done = true;
  6091. rq_lock_irqsave(rq, &rf);
  6092. update_rq_clock(rq);
  6093. /*
  6094. * Iterates the task_group tree in a bottom up fashion, see
  6095. * list_add_leaf_cfs_rq() for details.
  6096. */
  6097. for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) {
  6098. struct sched_entity *se;
  6099. /* throttled entities do not contribute to load */
  6100. if (throttled_hierarchy(cfs_rq))
  6101. continue;
  6102. if (update_cfs_rq_load_avg(cfs_rq_clock_task(cfs_rq), cfs_rq))
  6103. update_tg_load_avg(cfs_rq, 0);
  6104. /* Propagate pending load changes to the parent, if any: */
  6105. se = cfs_rq->tg->se[cpu];
  6106. if (se && !skip_blocked_update(se))
  6107. update_load_avg(cfs_rq_of(se), se, 0);
  6108. /*
  6109. * There can be a lot of idle CPU cgroups. Don't let fully
  6110. * decayed cfs_rqs linger on the list.
  6111. */
  6112. if (cfs_rq_is_decayed(cfs_rq))
  6113. list_del_leaf_cfs_rq(cfs_rq);
  6114. /* Don't need periodic decay once load/util_avg are null */
  6115. if (cfs_rq_has_blocked(cfs_rq))
  6116. done = false;
  6117. }
  6118. update_rt_rq_load_avg(rq_clock_task(rq), rq, 0);
  6119. update_dl_rq_load_avg(rq_clock_task(rq), rq, 0);
  6120. update_irq_load_avg(rq, 0);
  6121. /* Don't need periodic decay once load/util_avg are null */
  6122. if (others_have_blocked(rq))
  6123. done = false;
  6124. #ifdef CONFIG_NO_HZ_COMMON
  6125. rq->last_blocked_load_update_tick = jiffies;
  6126. if (done)
  6127. rq->has_blocked_load = 0;
  6128. #endif
  6129. rq_unlock_irqrestore(rq, &rf);
  6130. }
  6131. /*
  6132. * Compute the hierarchical load factor for cfs_rq and all its ascendants.
  6133. * This needs to be done in a top-down fashion because the load of a child
  6134. * group is a fraction of its parents load.
  6135. */
  6136. static void update_cfs_rq_h_load(struct cfs_rq *cfs_rq)
  6137. {
  6138. struct rq *rq = rq_of(cfs_rq);
  6139. struct sched_entity *se = cfs_rq->tg->se[cpu_of(rq)];
  6140. unsigned long now = jiffies;
  6141. unsigned long load;
  6142. if (cfs_rq->last_h_load_update == now)
  6143. return;
  6144. cfs_rq->h_load_next = NULL;
  6145. for_each_sched_entity(se) {
  6146. cfs_rq = cfs_rq_of(se);
  6147. cfs_rq->h_load_next = se;
  6148. if (cfs_rq->last_h_load_update == now)
  6149. break;
  6150. }
  6151. if (!se) {
  6152. cfs_rq->h_load = cfs_rq_load_avg(cfs_rq);
  6153. cfs_rq->last_h_load_update = now;
  6154. }
  6155. while ((se = cfs_rq->h_load_next) != NULL) {
  6156. load = cfs_rq->h_load;
  6157. load = div64_ul(load * se->avg.load_avg,
  6158. cfs_rq_load_avg(cfs_rq) + 1);
  6159. cfs_rq = group_cfs_rq(se);
  6160. cfs_rq->h_load = load;
  6161. cfs_rq->last_h_load_update = now;
  6162. }
  6163. }
  6164. static unsigned long task_h_load(struct task_struct *p)
  6165. {
  6166. struct cfs_rq *cfs_rq = task_cfs_rq(p);
  6167. update_cfs_rq_h_load(cfs_rq);
  6168. return div64_ul(p->se.avg.load_avg * cfs_rq->h_load,
  6169. cfs_rq_load_avg(cfs_rq) + 1);
  6170. }
  6171. #else
  6172. static inline void update_blocked_averages(int cpu)
  6173. {
  6174. struct rq *rq = cpu_rq(cpu);
  6175. struct cfs_rq *cfs_rq = &rq->cfs;
  6176. struct rq_flags rf;
  6177. rq_lock_irqsave(rq, &rf);
  6178. update_rq_clock(rq);
  6179. update_cfs_rq_load_avg(cfs_rq_clock_task(cfs_rq), cfs_rq);
  6180. update_rt_rq_load_avg(rq_clock_task(rq), rq, 0);
  6181. update_dl_rq_load_avg(rq_clock_task(rq), rq, 0);
  6182. update_irq_load_avg(rq, 0);
  6183. #ifdef CONFIG_NO_HZ_COMMON
  6184. rq->last_blocked_load_update_tick = jiffies;
  6185. if (!cfs_rq_has_blocked(cfs_rq) && !others_have_blocked(rq))
  6186. rq->has_blocked_load = 0;
  6187. #endif
  6188. rq_unlock_irqrestore(rq, &rf);
  6189. }
  6190. static unsigned long task_h_load(struct task_struct *p)
  6191. {
  6192. return p->se.avg.load_avg;
  6193. }
  6194. #endif
  6195. /********** Helpers for find_busiest_group ************************/
  6196. enum group_type {
  6197. group_other = 0,
  6198. group_imbalanced,
  6199. group_overloaded,
  6200. };
  6201. /*
  6202. * sg_lb_stats - stats of a sched_group required for load_balancing
  6203. */
  6204. struct sg_lb_stats {
  6205. unsigned long avg_load; /*Avg load across the CPUs of the group */
  6206. unsigned long group_load; /* Total load over the CPUs of the group */
  6207. unsigned long sum_weighted_load; /* Weighted load of group's tasks */
  6208. unsigned long load_per_task;
  6209. unsigned long group_capacity;
  6210. unsigned long group_util; /* Total utilization of the group */
  6211. unsigned int sum_nr_running; /* Nr tasks running in the group */
  6212. unsigned int idle_cpus;
  6213. unsigned int group_weight;
  6214. enum group_type group_type;
  6215. int group_no_capacity;
  6216. #ifdef CONFIG_NUMA_BALANCING
  6217. unsigned int nr_numa_running;
  6218. unsigned int nr_preferred_running;
  6219. #endif
  6220. };
  6221. /*
  6222. * sd_lb_stats - Structure to store the statistics of a sched_domain
  6223. * during load balancing.
  6224. */
  6225. struct sd_lb_stats {
  6226. struct sched_group *busiest; /* Busiest group in this sd */
  6227. struct sched_group *local; /* Local group in this sd */
  6228. unsigned long total_running;
  6229. unsigned long total_load; /* Total load of all groups in sd */
  6230. unsigned long total_capacity; /* Total capacity of all groups in sd */
  6231. unsigned long avg_load; /* Average load across all groups in sd */
  6232. struct sg_lb_stats busiest_stat;/* Statistics of the busiest group */
  6233. struct sg_lb_stats local_stat; /* Statistics of the local group */
  6234. };
  6235. static inline void init_sd_lb_stats(struct sd_lb_stats *sds)
  6236. {
  6237. /*
  6238. * Skimp on the clearing to avoid duplicate work. We can avoid clearing
  6239. * local_stat because update_sg_lb_stats() does a full clear/assignment.
  6240. * We must however clear busiest_stat::avg_load because
  6241. * update_sd_pick_busiest() reads this before assignment.
  6242. */
  6243. *sds = (struct sd_lb_stats){
  6244. .busiest = NULL,
  6245. .local = NULL,
  6246. .total_running = 0UL,
  6247. .total_load = 0UL,
  6248. .total_capacity = 0UL,
  6249. .busiest_stat = {
  6250. .avg_load = 0UL,
  6251. .sum_nr_running = 0,
  6252. .group_type = group_other,
  6253. },
  6254. };
  6255. }
  6256. /**
  6257. * get_sd_load_idx - Obtain the load index for a given sched domain.
  6258. * @sd: The sched_domain whose load_idx is to be obtained.
  6259. * @idle: The idle status of the CPU for whose sd load_idx is obtained.
  6260. *
  6261. * Return: The load index.
  6262. */
  6263. static inline int get_sd_load_idx(struct sched_domain *sd,
  6264. enum cpu_idle_type idle)
  6265. {
  6266. int load_idx;
  6267. switch (idle) {
  6268. case CPU_NOT_IDLE:
  6269. load_idx = sd->busy_idx;
  6270. break;
  6271. case CPU_NEWLY_IDLE:
  6272. load_idx = sd->newidle_idx;
  6273. break;
  6274. default:
  6275. load_idx = sd->idle_idx;
  6276. break;
  6277. }
  6278. return load_idx;
  6279. }
  6280. static unsigned long scale_rt_capacity(int cpu)
  6281. {
  6282. struct rq *rq = cpu_rq(cpu);
  6283. unsigned long max = arch_scale_cpu_capacity(NULL, cpu);
  6284. unsigned long used, free;
  6285. unsigned long irq;
  6286. irq = cpu_util_irq(rq);
  6287. if (unlikely(irq >= max))
  6288. return 1;
  6289. used = READ_ONCE(rq->avg_rt.util_avg);
  6290. used += READ_ONCE(rq->avg_dl.util_avg);
  6291. if (unlikely(used >= max))
  6292. return 1;
  6293. free = max - used;
  6294. return scale_irq_capacity(free, irq, max);
  6295. }
  6296. static void update_cpu_capacity(struct sched_domain *sd, int cpu)
  6297. {
  6298. unsigned long capacity = scale_rt_capacity(cpu);
  6299. struct sched_group *sdg = sd->groups;
  6300. cpu_rq(cpu)->cpu_capacity_orig = arch_scale_cpu_capacity(sd, cpu);
  6301. if (!capacity)
  6302. capacity = 1;
  6303. cpu_rq(cpu)->cpu_capacity = capacity;
  6304. sdg->sgc->capacity = capacity;
  6305. sdg->sgc->min_capacity = capacity;
  6306. }
  6307. void update_group_capacity(struct sched_domain *sd, int cpu)
  6308. {
  6309. struct sched_domain *child = sd->child;
  6310. struct sched_group *group, *sdg = sd->groups;
  6311. unsigned long capacity, min_capacity;
  6312. unsigned long interval;
  6313. interval = msecs_to_jiffies(sd->balance_interval);
  6314. interval = clamp(interval, 1UL, max_load_balance_interval);
  6315. sdg->sgc->next_update = jiffies + interval;
  6316. if (!child) {
  6317. update_cpu_capacity(sd, cpu);
  6318. return;
  6319. }
  6320. capacity = 0;
  6321. min_capacity = ULONG_MAX;
  6322. if (child->flags & SD_OVERLAP) {
  6323. /*
  6324. * SD_OVERLAP domains cannot assume that child groups
  6325. * span the current group.
  6326. */
  6327. for_each_cpu(cpu, sched_group_span(sdg)) {
  6328. struct sched_group_capacity *sgc;
  6329. struct rq *rq = cpu_rq(cpu);
  6330. /*
  6331. * build_sched_domains() -> init_sched_groups_capacity()
  6332. * gets here before we've attached the domains to the
  6333. * runqueues.
  6334. *
  6335. * Use capacity_of(), which is set irrespective of domains
  6336. * in update_cpu_capacity().
  6337. *
  6338. * This avoids capacity from being 0 and
  6339. * causing divide-by-zero issues on boot.
  6340. */
  6341. if (unlikely(!rq->sd)) {
  6342. capacity += capacity_of(cpu);
  6343. } else {
  6344. sgc = rq->sd->groups->sgc;
  6345. capacity += sgc->capacity;
  6346. }
  6347. min_capacity = min(capacity, min_capacity);
  6348. }
  6349. } else {
  6350. /*
  6351. * !SD_OVERLAP domains can assume that child groups
  6352. * span the current group.
  6353. */
  6354. group = child->groups;
  6355. do {
  6356. struct sched_group_capacity *sgc = group->sgc;
  6357. capacity += sgc->capacity;
  6358. min_capacity = min(sgc->min_capacity, min_capacity);
  6359. group = group->next;
  6360. } while (group != child->groups);
  6361. }
  6362. sdg->sgc->capacity = capacity;
  6363. sdg->sgc->min_capacity = min_capacity;
  6364. }
  6365. /*
  6366. * Check whether the capacity of the rq has been noticeably reduced by side
  6367. * activity. The imbalance_pct is used for the threshold.
  6368. * Return true is the capacity is reduced
  6369. */
  6370. static inline int
  6371. check_cpu_capacity(struct rq *rq, struct sched_domain *sd)
  6372. {
  6373. return ((rq->cpu_capacity * sd->imbalance_pct) <
  6374. (rq->cpu_capacity_orig * 100));
  6375. }
  6376. /*
  6377. * Group imbalance indicates (and tries to solve) the problem where balancing
  6378. * groups is inadequate due to ->cpus_allowed constraints.
  6379. *
  6380. * Imagine a situation of two groups of 4 CPUs each and 4 tasks each with a
  6381. * cpumask covering 1 CPU of the first group and 3 CPUs of the second group.
  6382. * Something like:
  6383. *
  6384. * { 0 1 2 3 } { 4 5 6 7 }
  6385. * * * * *
  6386. *
  6387. * If we were to balance group-wise we'd place two tasks in the first group and
  6388. * two tasks in the second group. Clearly this is undesired as it will overload
  6389. * cpu 3 and leave one of the CPUs in the second group unused.
  6390. *
  6391. * The current solution to this issue is detecting the skew in the first group
  6392. * by noticing the lower domain failed to reach balance and had difficulty
  6393. * moving tasks due to affinity constraints.
  6394. *
  6395. * When this is so detected; this group becomes a candidate for busiest; see
  6396. * update_sd_pick_busiest(). And calculate_imbalance() and
  6397. * find_busiest_group() avoid some of the usual balance conditions to allow it
  6398. * to create an effective group imbalance.
  6399. *
  6400. * This is a somewhat tricky proposition since the next run might not find the
  6401. * group imbalance and decide the groups need to be balanced again. A most
  6402. * subtle and fragile situation.
  6403. */
  6404. static inline int sg_imbalanced(struct sched_group *group)
  6405. {
  6406. return group->sgc->imbalance;
  6407. }
  6408. /*
  6409. * group_has_capacity returns true if the group has spare capacity that could
  6410. * be used by some tasks.
  6411. * We consider that a group has spare capacity if the * number of task is
  6412. * smaller than the number of CPUs or if the utilization is lower than the
  6413. * available capacity for CFS tasks.
  6414. * For the latter, we use a threshold to stabilize the state, to take into
  6415. * account the variance of the tasks' load and to return true if the available
  6416. * capacity in meaningful for the load balancer.
  6417. * As an example, an available capacity of 1% can appear but it doesn't make
  6418. * any benefit for the load balance.
  6419. */
  6420. static inline bool
  6421. group_has_capacity(struct lb_env *env, struct sg_lb_stats *sgs)
  6422. {
  6423. if (sgs->sum_nr_running < sgs->group_weight)
  6424. return true;
  6425. if ((sgs->group_capacity * 100) >
  6426. (sgs->group_util * env->sd->imbalance_pct))
  6427. return true;
  6428. return false;
  6429. }
  6430. /*
  6431. * group_is_overloaded returns true if the group has more tasks than it can
  6432. * handle.
  6433. * group_is_overloaded is not equals to !group_has_capacity because a group
  6434. * with the exact right number of tasks, has no more spare capacity but is not
  6435. * overloaded so both group_has_capacity and group_is_overloaded return
  6436. * false.
  6437. */
  6438. static inline bool
  6439. group_is_overloaded(struct lb_env *env, struct sg_lb_stats *sgs)
  6440. {
  6441. if (sgs->sum_nr_running <= sgs->group_weight)
  6442. return false;
  6443. if ((sgs->group_capacity * 100) <
  6444. (sgs->group_util * env->sd->imbalance_pct))
  6445. return true;
  6446. return false;
  6447. }
  6448. /*
  6449. * group_smaller_cpu_capacity: Returns true if sched_group sg has smaller
  6450. * per-CPU capacity than sched_group ref.
  6451. */
  6452. static inline bool
  6453. group_smaller_cpu_capacity(struct sched_group *sg, struct sched_group *ref)
  6454. {
  6455. return sg->sgc->min_capacity * capacity_margin <
  6456. ref->sgc->min_capacity * 1024;
  6457. }
  6458. static inline enum
  6459. group_type group_classify(struct sched_group *group,
  6460. struct sg_lb_stats *sgs)
  6461. {
  6462. if (sgs->group_no_capacity)
  6463. return group_overloaded;
  6464. if (sg_imbalanced(group))
  6465. return group_imbalanced;
  6466. return group_other;
  6467. }
  6468. static bool update_nohz_stats(struct rq *rq, bool force)
  6469. {
  6470. #ifdef CONFIG_NO_HZ_COMMON
  6471. unsigned int cpu = rq->cpu;
  6472. if (!rq->has_blocked_load)
  6473. return false;
  6474. if (!cpumask_test_cpu(cpu, nohz.idle_cpus_mask))
  6475. return false;
  6476. if (!force && !time_after(jiffies, rq->last_blocked_load_update_tick))
  6477. return true;
  6478. update_blocked_averages(cpu);
  6479. return rq->has_blocked_load;
  6480. #else
  6481. return false;
  6482. #endif
  6483. }
  6484. /**
  6485. * update_sg_lb_stats - Update sched_group's statistics for load balancing.
  6486. * @env: The load balancing environment.
  6487. * @group: sched_group whose statistics are to be updated.
  6488. * @load_idx: Load index of sched_domain of this_cpu for load calc.
  6489. * @local_group: Does group contain this_cpu.
  6490. * @sgs: variable to hold the statistics for this group.
  6491. * @overload: Indicate more than one runnable task for any CPU.
  6492. */
  6493. static inline void update_sg_lb_stats(struct lb_env *env,
  6494. struct sched_group *group, int load_idx,
  6495. int local_group, struct sg_lb_stats *sgs,
  6496. bool *overload)
  6497. {
  6498. unsigned long load;
  6499. int i, nr_running;
  6500. memset(sgs, 0, sizeof(*sgs));
  6501. for_each_cpu_and(i, sched_group_span(group), env->cpus) {
  6502. struct rq *rq = cpu_rq(i);
  6503. if ((env->flags & LBF_NOHZ_STATS) && update_nohz_stats(rq, false))
  6504. env->flags |= LBF_NOHZ_AGAIN;
  6505. /* Bias balancing toward CPUs of our domain: */
  6506. if (local_group)
  6507. load = target_load(i, load_idx);
  6508. else
  6509. load = source_load(i, load_idx);
  6510. sgs->group_load += load;
  6511. sgs->group_util += cpu_util(i);
  6512. sgs->sum_nr_running += rq->cfs.h_nr_running;
  6513. nr_running = rq->nr_running;
  6514. if (nr_running > 1)
  6515. *overload = true;
  6516. #ifdef CONFIG_NUMA_BALANCING
  6517. sgs->nr_numa_running += rq->nr_numa_running;
  6518. sgs->nr_preferred_running += rq->nr_preferred_running;
  6519. #endif
  6520. sgs->sum_weighted_load += weighted_cpuload(rq);
  6521. /*
  6522. * No need to call idle_cpu() if nr_running is not 0
  6523. */
  6524. if (!nr_running && idle_cpu(i))
  6525. sgs->idle_cpus++;
  6526. }
  6527. /* Adjust by relative CPU capacity of the group */
  6528. sgs->group_capacity = group->sgc->capacity;
  6529. sgs->avg_load = (sgs->group_load*SCHED_CAPACITY_SCALE) / sgs->group_capacity;
  6530. if (sgs->sum_nr_running)
  6531. sgs->load_per_task = sgs->sum_weighted_load / sgs->sum_nr_running;
  6532. sgs->group_weight = group->group_weight;
  6533. sgs->group_no_capacity = group_is_overloaded(env, sgs);
  6534. sgs->group_type = group_classify(group, sgs);
  6535. }
  6536. /**
  6537. * update_sd_pick_busiest - return 1 on busiest group
  6538. * @env: The load balancing environment.
  6539. * @sds: sched_domain statistics
  6540. * @sg: sched_group candidate to be checked for being the busiest
  6541. * @sgs: sched_group statistics
  6542. *
  6543. * Determine if @sg is a busier group than the previously selected
  6544. * busiest group.
  6545. *
  6546. * Return: %true if @sg is a busier group than the previously selected
  6547. * busiest group. %false otherwise.
  6548. */
  6549. static bool update_sd_pick_busiest(struct lb_env *env,
  6550. struct sd_lb_stats *sds,
  6551. struct sched_group *sg,
  6552. struct sg_lb_stats *sgs)
  6553. {
  6554. struct sg_lb_stats *busiest = &sds->busiest_stat;
  6555. if (sgs->group_type > busiest->group_type)
  6556. return true;
  6557. if (sgs->group_type < busiest->group_type)
  6558. return false;
  6559. if (sgs->avg_load <= busiest->avg_load)
  6560. return false;
  6561. if (!(env->sd->flags & SD_ASYM_CPUCAPACITY))
  6562. goto asym_packing;
  6563. /*
  6564. * Candidate sg has no more than one task per CPU and
  6565. * has higher per-CPU capacity. Migrating tasks to less
  6566. * capable CPUs may harm throughput. Maximize throughput,
  6567. * power/energy consequences are not considered.
  6568. */
  6569. if (sgs->sum_nr_running <= sgs->group_weight &&
  6570. group_smaller_cpu_capacity(sds->local, sg))
  6571. return false;
  6572. asym_packing:
  6573. /* This is the busiest node in its class. */
  6574. if (!(env->sd->flags & SD_ASYM_PACKING))
  6575. return true;
  6576. /* No ASYM_PACKING if target CPU is already busy */
  6577. if (env->idle == CPU_NOT_IDLE)
  6578. return true;
  6579. /*
  6580. * ASYM_PACKING needs to move all the work to the highest
  6581. * prority CPUs in the group, therefore mark all groups
  6582. * of lower priority than ourself as busy.
  6583. */
  6584. if (sgs->sum_nr_running &&
  6585. sched_asym_prefer(env->dst_cpu, sg->asym_prefer_cpu)) {
  6586. if (!sds->busiest)
  6587. return true;
  6588. /* Prefer to move from lowest priority CPU's work */
  6589. if (sched_asym_prefer(sds->busiest->asym_prefer_cpu,
  6590. sg->asym_prefer_cpu))
  6591. return true;
  6592. }
  6593. return false;
  6594. }
  6595. #ifdef CONFIG_NUMA_BALANCING
  6596. static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
  6597. {
  6598. if (sgs->sum_nr_running > sgs->nr_numa_running)
  6599. return regular;
  6600. if (sgs->sum_nr_running > sgs->nr_preferred_running)
  6601. return remote;
  6602. return all;
  6603. }
  6604. static inline enum fbq_type fbq_classify_rq(struct rq *rq)
  6605. {
  6606. if (rq->nr_running > rq->nr_numa_running)
  6607. return regular;
  6608. if (rq->nr_running > rq->nr_preferred_running)
  6609. return remote;
  6610. return all;
  6611. }
  6612. #else
  6613. static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
  6614. {
  6615. return all;
  6616. }
  6617. static inline enum fbq_type fbq_classify_rq(struct rq *rq)
  6618. {
  6619. return regular;
  6620. }
  6621. #endif /* CONFIG_NUMA_BALANCING */
  6622. /**
  6623. * update_sd_lb_stats - Update sched_domain's statistics for load balancing.
  6624. * @env: The load balancing environment.
  6625. * @sds: variable to hold the statistics for this sched_domain.
  6626. */
  6627. static inline void update_sd_lb_stats(struct lb_env *env, struct sd_lb_stats *sds)
  6628. {
  6629. struct sched_domain *child = env->sd->child;
  6630. struct sched_group *sg = env->sd->groups;
  6631. struct sg_lb_stats *local = &sds->local_stat;
  6632. struct sg_lb_stats tmp_sgs;
  6633. int load_idx, prefer_sibling = 0;
  6634. bool overload = false;
  6635. if (child && child->flags & SD_PREFER_SIBLING)
  6636. prefer_sibling = 1;
  6637. #ifdef CONFIG_NO_HZ_COMMON
  6638. if (env->idle == CPU_NEWLY_IDLE && READ_ONCE(nohz.has_blocked))
  6639. env->flags |= LBF_NOHZ_STATS;
  6640. #endif
  6641. load_idx = get_sd_load_idx(env->sd, env->idle);
  6642. do {
  6643. struct sg_lb_stats *sgs = &tmp_sgs;
  6644. int local_group;
  6645. local_group = cpumask_test_cpu(env->dst_cpu, sched_group_span(sg));
  6646. if (local_group) {
  6647. sds->local = sg;
  6648. sgs = local;
  6649. if (env->idle != CPU_NEWLY_IDLE ||
  6650. time_after_eq(jiffies, sg->sgc->next_update))
  6651. update_group_capacity(env->sd, env->dst_cpu);
  6652. }
  6653. update_sg_lb_stats(env, sg, load_idx, local_group, sgs,
  6654. &overload);
  6655. if (local_group)
  6656. goto next_group;
  6657. /*
  6658. * In case the child domain prefers tasks go to siblings
  6659. * first, lower the sg capacity so that we'll try
  6660. * and move all the excess tasks away. We lower the capacity
  6661. * of a group only if the local group has the capacity to fit
  6662. * these excess tasks. The extra check prevents the case where
  6663. * you always pull from the heaviest group when it is already
  6664. * under-utilized (possible with a large weight task outweighs
  6665. * the tasks on the system).
  6666. */
  6667. if (prefer_sibling && sds->local &&
  6668. group_has_capacity(env, local) &&
  6669. (sgs->sum_nr_running > local->sum_nr_running + 1)) {
  6670. sgs->group_no_capacity = 1;
  6671. sgs->group_type = group_classify(sg, sgs);
  6672. }
  6673. if (update_sd_pick_busiest(env, sds, sg, sgs)) {
  6674. sds->busiest = sg;
  6675. sds->busiest_stat = *sgs;
  6676. }
  6677. next_group:
  6678. /* Now, start updating sd_lb_stats */
  6679. sds->total_running += sgs->sum_nr_running;
  6680. sds->total_load += sgs->group_load;
  6681. sds->total_capacity += sgs->group_capacity;
  6682. sg = sg->next;
  6683. } while (sg != env->sd->groups);
  6684. #ifdef CONFIG_NO_HZ_COMMON
  6685. if ((env->flags & LBF_NOHZ_AGAIN) &&
  6686. cpumask_subset(nohz.idle_cpus_mask, sched_domain_span(env->sd))) {
  6687. WRITE_ONCE(nohz.next_blocked,
  6688. jiffies + msecs_to_jiffies(LOAD_AVG_PERIOD));
  6689. }
  6690. #endif
  6691. if (env->sd->flags & SD_NUMA)
  6692. env->fbq_type = fbq_classify_group(&sds->busiest_stat);
  6693. if (!env->sd->parent) {
  6694. /* update overload indicator if we are at root domain */
  6695. if (env->dst_rq->rd->overload != overload)
  6696. env->dst_rq->rd->overload = overload;
  6697. }
  6698. }
  6699. /**
  6700. * check_asym_packing - Check to see if the group is packed into the
  6701. * sched domain.
  6702. *
  6703. * This is primarily intended to used at the sibling level. Some
  6704. * cores like POWER7 prefer to use lower numbered SMT threads. In the
  6705. * case of POWER7, it can move to lower SMT modes only when higher
  6706. * threads are idle. When in lower SMT modes, the threads will
  6707. * perform better since they share less core resources. Hence when we
  6708. * have idle threads, we want them to be the higher ones.
  6709. *
  6710. * This packing function is run on idle threads. It checks to see if
  6711. * the busiest CPU in this domain (core in the P7 case) has a higher
  6712. * CPU number than the packing function is being run on. Here we are
  6713. * assuming lower CPU number will be equivalent to lower a SMT thread
  6714. * number.
  6715. *
  6716. * Return: 1 when packing is required and a task should be moved to
  6717. * this CPU. The amount of the imbalance is returned in env->imbalance.
  6718. *
  6719. * @env: The load balancing environment.
  6720. * @sds: Statistics of the sched_domain which is to be packed
  6721. */
  6722. static int check_asym_packing(struct lb_env *env, struct sd_lb_stats *sds)
  6723. {
  6724. int busiest_cpu;
  6725. if (!(env->sd->flags & SD_ASYM_PACKING))
  6726. return 0;
  6727. if (env->idle == CPU_NOT_IDLE)
  6728. return 0;
  6729. if (!sds->busiest)
  6730. return 0;
  6731. busiest_cpu = sds->busiest->asym_prefer_cpu;
  6732. if (sched_asym_prefer(busiest_cpu, env->dst_cpu))
  6733. return 0;
  6734. env->imbalance = DIV_ROUND_CLOSEST(
  6735. sds->busiest_stat.avg_load * sds->busiest_stat.group_capacity,
  6736. SCHED_CAPACITY_SCALE);
  6737. return 1;
  6738. }
  6739. /**
  6740. * fix_small_imbalance - Calculate the minor imbalance that exists
  6741. * amongst the groups of a sched_domain, during
  6742. * load balancing.
  6743. * @env: The load balancing environment.
  6744. * @sds: Statistics of the sched_domain whose imbalance is to be calculated.
  6745. */
  6746. static inline
  6747. void fix_small_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
  6748. {
  6749. unsigned long tmp, capa_now = 0, capa_move = 0;
  6750. unsigned int imbn = 2;
  6751. unsigned long scaled_busy_load_per_task;
  6752. struct sg_lb_stats *local, *busiest;
  6753. local = &sds->local_stat;
  6754. busiest = &sds->busiest_stat;
  6755. if (!local->sum_nr_running)
  6756. local->load_per_task = cpu_avg_load_per_task(env->dst_cpu);
  6757. else if (busiest->load_per_task > local->load_per_task)
  6758. imbn = 1;
  6759. scaled_busy_load_per_task =
  6760. (busiest->load_per_task * SCHED_CAPACITY_SCALE) /
  6761. busiest->group_capacity;
  6762. if (busiest->avg_load + scaled_busy_load_per_task >=
  6763. local->avg_load + (scaled_busy_load_per_task * imbn)) {
  6764. env->imbalance = busiest->load_per_task;
  6765. return;
  6766. }
  6767. /*
  6768. * OK, we don't have enough imbalance to justify moving tasks,
  6769. * however we may be able to increase total CPU capacity used by
  6770. * moving them.
  6771. */
  6772. capa_now += busiest->group_capacity *
  6773. min(busiest->load_per_task, busiest->avg_load);
  6774. capa_now += local->group_capacity *
  6775. min(local->load_per_task, local->avg_load);
  6776. capa_now /= SCHED_CAPACITY_SCALE;
  6777. /* Amount of load we'd subtract */
  6778. if (busiest->avg_load > scaled_busy_load_per_task) {
  6779. capa_move += busiest->group_capacity *
  6780. min(busiest->load_per_task,
  6781. busiest->avg_load - scaled_busy_load_per_task);
  6782. }
  6783. /* Amount of load we'd add */
  6784. if (busiest->avg_load * busiest->group_capacity <
  6785. busiest->load_per_task * SCHED_CAPACITY_SCALE) {
  6786. tmp = (busiest->avg_load * busiest->group_capacity) /
  6787. local->group_capacity;
  6788. } else {
  6789. tmp = (busiest->load_per_task * SCHED_CAPACITY_SCALE) /
  6790. local->group_capacity;
  6791. }
  6792. capa_move += local->group_capacity *
  6793. min(local->load_per_task, local->avg_load + tmp);
  6794. capa_move /= SCHED_CAPACITY_SCALE;
  6795. /* Move if we gain throughput */
  6796. if (capa_move > capa_now)
  6797. env->imbalance = busiest->load_per_task;
  6798. }
  6799. /**
  6800. * calculate_imbalance - Calculate the amount of imbalance present within the
  6801. * groups of a given sched_domain during load balance.
  6802. * @env: load balance environment
  6803. * @sds: statistics of the sched_domain whose imbalance is to be calculated.
  6804. */
  6805. static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
  6806. {
  6807. unsigned long max_pull, load_above_capacity = ~0UL;
  6808. struct sg_lb_stats *local, *busiest;
  6809. local = &sds->local_stat;
  6810. busiest = &sds->busiest_stat;
  6811. if (busiest->group_type == group_imbalanced) {
  6812. /*
  6813. * In the group_imb case we cannot rely on group-wide averages
  6814. * to ensure CPU-load equilibrium, look at wider averages. XXX
  6815. */
  6816. busiest->load_per_task =
  6817. min(busiest->load_per_task, sds->avg_load);
  6818. }
  6819. /*
  6820. * Avg load of busiest sg can be less and avg load of local sg can
  6821. * be greater than avg load across all sgs of sd because avg load
  6822. * factors in sg capacity and sgs with smaller group_type are
  6823. * skipped when updating the busiest sg:
  6824. */
  6825. if (busiest->avg_load <= sds->avg_load ||
  6826. local->avg_load >= sds->avg_load) {
  6827. env->imbalance = 0;
  6828. return fix_small_imbalance(env, sds);
  6829. }
  6830. /*
  6831. * If there aren't any idle CPUs, avoid creating some.
  6832. */
  6833. if (busiest->group_type == group_overloaded &&
  6834. local->group_type == group_overloaded) {
  6835. load_above_capacity = busiest->sum_nr_running * SCHED_CAPACITY_SCALE;
  6836. if (load_above_capacity > busiest->group_capacity) {
  6837. load_above_capacity -= busiest->group_capacity;
  6838. load_above_capacity *= scale_load_down(NICE_0_LOAD);
  6839. load_above_capacity /= busiest->group_capacity;
  6840. } else
  6841. load_above_capacity = ~0UL;
  6842. }
  6843. /*
  6844. * We're trying to get all the CPUs to the average_load, so we don't
  6845. * want to push ourselves above the average load, nor do we wish to
  6846. * reduce the max loaded CPU below the average load. At the same time,
  6847. * we also don't want to reduce the group load below the group
  6848. * capacity. Thus we look for the minimum possible imbalance.
  6849. */
  6850. max_pull = min(busiest->avg_load - sds->avg_load, load_above_capacity);
  6851. /* How much load to actually move to equalise the imbalance */
  6852. env->imbalance = min(
  6853. max_pull * busiest->group_capacity,
  6854. (sds->avg_load - local->avg_load) * local->group_capacity
  6855. ) / SCHED_CAPACITY_SCALE;
  6856. /*
  6857. * if *imbalance is less than the average load per runnable task
  6858. * there is no guarantee that any tasks will be moved so we'll have
  6859. * a think about bumping its value to force at least one task to be
  6860. * moved
  6861. */
  6862. if (env->imbalance < busiest->load_per_task)
  6863. return fix_small_imbalance(env, sds);
  6864. }
  6865. /******* find_busiest_group() helpers end here *********************/
  6866. /**
  6867. * find_busiest_group - Returns the busiest group within the sched_domain
  6868. * if there is an imbalance.
  6869. *
  6870. * Also calculates the amount of weighted load which should be moved
  6871. * to restore balance.
  6872. *
  6873. * @env: The load balancing environment.
  6874. *
  6875. * Return: - The busiest group if imbalance exists.
  6876. */
  6877. static struct sched_group *find_busiest_group(struct lb_env *env)
  6878. {
  6879. struct sg_lb_stats *local, *busiest;
  6880. struct sd_lb_stats sds;
  6881. init_sd_lb_stats(&sds);
  6882. /*
  6883. * Compute the various statistics relavent for load balancing at
  6884. * this level.
  6885. */
  6886. update_sd_lb_stats(env, &sds);
  6887. local = &sds.local_stat;
  6888. busiest = &sds.busiest_stat;
  6889. /* ASYM feature bypasses nice load balance check */
  6890. if (check_asym_packing(env, &sds))
  6891. return sds.busiest;
  6892. /* There is no busy sibling group to pull tasks from */
  6893. if (!sds.busiest || busiest->sum_nr_running == 0)
  6894. goto out_balanced;
  6895. /* XXX broken for overlapping NUMA groups */
  6896. sds.avg_load = (SCHED_CAPACITY_SCALE * sds.total_load)
  6897. / sds.total_capacity;
  6898. /*
  6899. * If the busiest group is imbalanced the below checks don't
  6900. * work because they assume all things are equal, which typically
  6901. * isn't true due to cpus_allowed constraints and the like.
  6902. */
  6903. if (busiest->group_type == group_imbalanced)
  6904. goto force_balance;
  6905. /*
  6906. * When dst_cpu is idle, prevent SMP nice and/or asymmetric group
  6907. * capacities from resulting in underutilization due to avg_load.
  6908. */
  6909. if (env->idle != CPU_NOT_IDLE && group_has_capacity(env, local) &&
  6910. busiest->group_no_capacity)
  6911. goto force_balance;
  6912. /*
  6913. * If the local group is busier than the selected busiest group
  6914. * don't try and pull any tasks.
  6915. */
  6916. if (local->avg_load >= busiest->avg_load)
  6917. goto out_balanced;
  6918. /*
  6919. * Don't pull any tasks if this group is already above the domain
  6920. * average load.
  6921. */
  6922. if (local->avg_load >= sds.avg_load)
  6923. goto out_balanced;
  6924. if (env->idle == CPU_IDLE) {
  6925. /*
  6926. * This CPU is idle. If the busiest group is not overloaded
  6927. * and there is no imbalance between this and busiest group
  6928. * wrt idle CPUs, it is balanced. The imbalance becomes
  6929. * significant if the diff is greater than 1 otherwise we
  6930. * might end up to just move the imbalance on another group
  6931. */
  6932. if ((busiest->group_type != group_overloaded) &&
  6933. (local->idle_cpus <= (busiest->idle_cpus + 1)))
  6934. goto out_balanced;
  6935. } else {
  6936. /*
  6937. * In the CPU_NEWLY_IDLE, CPU_NOT_IDLE cases, use
  6938. * imbalance_pct to be conservative.
  6939. */
  6940. if (100 * busiest->avg_load <=
  6941. env->sd->imbalance_pct * local->avg_load)
  6942. goto out_balanced;
  6943. }
  6944. force_balance:
  6945. /* Looks like there is an imbalance. Compute it */
  6946. calculate_imbalance(env, &sds);
  6947. return sds.busiest;
  6948. out_balanced:
  6949. env->imbalance = 0;
  6950. return NULL;
  6951. }
  6952. /*
  6953. * find_busiest_queue - find the busiest runqueue among the CPUs in the group.
  6954. */
  6955. static struct rq *find_busiest_queue(struct lb_env *env,
  6956. struct sched_group *group)
  6957. {
  6958. struct rq *busiest = NULL, *rq;
  6959. unsigned long busiest_load = 0, busiest_capacity = 1;
  6960. int i;
  6961. for_each_cpu_and(i, sched_group_span(group), env->cpus) {
  6962. unsigned long capacity, wl;
  6963. enum fbq_type rt;
  6964. rq = cpu_rq(i);
  6965. rt = fbq_classify_rq(rq);
  6966. /*
  6967. * We classify groups/runqueues into three groups:
  6968. * - regular: there are !numa tasks
  6969. * - remote: there are numa tasks that run on the 'wrong' node
  6970. * - all: there is no distinction
  6971. *
  6972. * In order to avoid migrating ideally placed numa tasks,
  6973. * ignore those when there's better options.
  6974. *
  6975. * If we ignore the actual busiest queue to migrate another
  6976. * task, the next balance pass can still reduce the busiest
  6977. * queue by moving tasks around inside the node.
  6978. *
  6979. * If we cannot move enough load due to this classification
  6980. * the next pass will adjust the group classification and
  6981. * allow migration of more tasks.
  6982. *
  6983. * Both cases only affect the total convergence complexity.
  6984. */
  6985. if (rt > env->fbq_type)
  6986. continue;
  6987. capacity = capacity_of(i);
  6988. wl = weighted_cpuload(rq);
  6989. /*
  6990. * When comparing with imbalance, use weighted_cpuload()
  6991. * which is not scaled with the CPU capacity.
  6992. */
  6993. if (rq->nr_running == 1 && wl > env->imbalance &&
  6994. !check_cpu_capacity(rq, env->sd))
  6995. continue;
  6996. /*
  6997. * For the load comparisons with the other CPU's, consider
  6998. * the weighted_cpuload() scaled with the CPU capacity, so
  6999. * that the load can be moved away from the CPU that is
  7000. * potentially running at a lower capacity.
  7001. *
  7002. * Thus we're looking for max(wl_i / capacity_i), crosswise
  7003. * multiplication to rid ourselves of the division works out
  7004. * to: wl_i * capacity_j > wl_j * capacity_i; where j is
  7005. * our previous maximum.
  7006. */
  7007. if (wl * busiest_capacity > busiest_load * capacity) {
  7008. busiest_load = wl;
  7009. busiest_capacity = capacity;
  7010. busiest = rq;
  7011. }
  7012. }
  7013. return busiest;
  7014. }
  7015. /*
  7016. * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
  7017. * so long as it is large enough.
  7018. */
  7019. #define MAX_PINNED_INTERVAL 512
  7020. static int need_active_balance(struct lb_env *env)
  7021. {
  7022. struct sched_domain *sd = env->sd;
  7023. if (env->idle == CPU_NEWLY_IDLE) {
  7024. /*
  7025. * ASYM_PACKING needs to force migrate tasks from busy but
  7026. * lower priority CPUs in order to pack all tasks in the
  7027. * highest priority CPUs.
  7028. */
  7029. if ((sd->flags & SD_ASYM_PACKING) &&
  7030. sched_asym_prefer(env->dst_cpu, env->src_cpu))
  7031. return 1;
  7032. }
  7033. /*
  7034. * The dst_cpu is idle and the src_cpu CPU has only 1 CFS task.
  7035. * It's worth migrating the task if the src_cpu's capacity is reduced
  7036. * because of other sched_class or IRQs if more capacity stays
  7037. * available on dst_cpu.
  7038. */
  7039. if ((env->idle != CPU_NOT_IDLE) &&
  7040. (env->src_rq->cfs.h_nr_running == 1)) {
  7041. if ((check_cpu_capacity(env->src_rq, sd)) &&
  7042. (capacity_of(env->src_cpu)*sd->imbalance_pct < capacity_of(env->dst_cpu)*100))
  7043. return 1;
  7044. }
  7045. return unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2);
  7046. }
  7047. static int active_load_balance_cpu_stop(void *data);
  7048. static int should_we_balance(struct lb_env *env)
  7049. {
  7050. struct sched_group *sg = env->sd->groups;
  7051. int cpu, balance_cpu = -1;
  7052. /*
  7053. * Ensure the balancing environment is consistent; can happen
  7054. * when the softirq triggers 'during' hotplug.
  7055. */
  7056. if (!cpumask_test_cpu(env->dst_cpu, env->cpus))
  7057. return 0;
  7058. /*
  7059. * In the newly idle case, we will allow all the CPUs
  7060. * to do the newly idle load balance.
  7061. */
  7062. if (env->idle == CPU_NEWLY_IDLE)
  7063. return 1;
  7064. /* Try to find first idle CPU */
  7065. for_each_cpu_and(cpu, group_balance_mask(sg), env->cpus) {
  7066. if (!idle_cpu(cpu))
  7067. continue;
  7068. balance_cpu = cpu;
  7069. break;
  7070. }
  7071. if (balance_cpu == -1)
  7072. balance_cpu = group_balance_cpu(sg);
  7073. /*
  7074. * First idle CPU or the first CPU(busiest) in this sched group
  7075. * is eligible for doing load balancing at this and above domains.
  7076. */
  7077. return balance_cpu == env->dst_cpu;
  7078. }
  7079. /*
  7080. * Check this_cpu to ensure it is balanced within domain. Attempt to move
  7081. * tasks if there is an imbalance.
  7082. */
  7083. static int load_balance(int this_cpu, struct rq *this_rq,
  7084. struct sched_domain *sd, enum cpu_idle_type idle,
  7085. int *continue_balancing)
  7086. {
  7087. int ld_moved, cur_ld_moved, active_balance = 0;
  7088. struct sched_domain *sd_parent = sd->parent;
  7089. struct sched_group *group;
  7090. struct rq *busiest;
  7091. struct rq_flags rf;
  7092. struct cpumask *cpus = this_cpu_cpumask_var_ptr(load_balance_mask);
  7093. struct lb_env env = {
  7094. .sd = sd,
  7095. .dst_cpu = this_cpu,
  7096. .dst_rq = this_rq,
  7097. .dst_grpmask = sched_group_span(sd->groups),
  7098. .idle = idle,
  7099. .loop_break = sched_nr_migrate_break,
  7100. .cpus = cpus,
  7101. .fbq_type = all,
  7102. .tasks = LIST_HEAD_INIT(env.tasks),
  7103. };
  7104. cpumask_and(cpus, sched_domain_span(sd), cpu_active_mask);
  7105. schedstat_inc(sd->lb_count[idle]);
  7106. redo:
  7107. if (!should_we_balance(&env)) {
  7108. *continue_balancing = 0;
  7109. goto out_balanced;
  7110. }
  7111. group = find_busiest_group(&env);
  7112. if (!group) {
  7113. schedstat_inc(sd->lb_nobusyg[idle]);
  7114. goto out_balanced;
  7115. }
  7116. busiest = find_busiest_queue(&env, group);
  7117. if (!busiest) {
  7118. schedstat_inc(sd->lb_nobusyq[idle]);
  7119. goto out_balanced;
  7120. }
  7121. BUG_ON(busiest == env.dst_rq);
  7122. schedstat_add(sd->lb_imbalance[idle], env.imbalance);
  7123. env.src_cpu = busiest->cpu;
  7124. env.src_rq = busiest;
  7125. ld_moved = 0;
  7126. if (busiest->nr_running > 1) {
  7127. /*
  7128. * Attempt to move tasks. If find_busiest_group has found
  7129. * an imbalance but busiest->nr_running <= 1, the group is
  7130. * still unbalanced. ld_moved simply stays zero, so it is
  7131. * correctly treated as an imbalance.
  7132. */
  7133. env.flags |= LBF_ALL_PINNED;
  7134. env.loop_max = min(sysctl_sched_nr_migrate, busiest->nr_running);
  7135. more_balance:
  7136. rq_lock_irqsave(busiest, &rf);
  7137. update_rq_clock(busiest);
  7138. /*
  7139. * cur_ld_moved - load moved in current iteration
  7140. * ld_moved - cumulative load moved across iterations
  7141. */
  7142. cur_ld_moved = detach_tasks(&env);
  7143. /*
  7144. * We've detached some tasks from busiest_rq. Every
  7145. * task is masked "TASK_ON_RQ_MIGRATING", so we can safely
  7146. * unlock busiest->lock, and we are able to be sure
  7147. * that nobody can manipulate the tasks in parallel.
  7148. * See task_rq_lock() family for the details.
  7149. */
  7150. rq_unlock(busiest, &rf);
  7151. if (cur_ld_moved) {
  7152. attach_tasks(&env);
  7153. ld_moved += cur_ld_moved;
  7154. }
  7155. local_irq_restore(rf.flags);
  7156. if (env.flags & LBF_NEED_BREAK) {
  7157. env.flags &= ~LBF_NEED_BREAK;
  7158. goto more_balance;
  7159. }
  7160. /*
  7161. * Revisit (affine) tasks on src_cpu that couldn't be moved to
  7162. * us and move them to an alternate dst_cpu in our sched_group
  7163. * where they can run. The upper limit on how many times we
  7164. * iterate on same src_cpu is dependent on number of CPUs in our
  7165. * sched_group.
  7166. *
  7167. * This changes load balance semantics a bit on who can move
  7168. * load to a given_cpu. In addition to the given_cpu itself
  7169. * (or a ilb_cpu acting on its behalf where given_cpu is
  7170. * nohz-idle), we now have balance_cpu in a position to move
  7171. * load to given_cpu. In rare situations, this may cause
  7172. * conflicts (balance_cpu and given_cpu/ilb_cpu deciding
  7173. * _independently_ and at _same_ time to move some load to
  7174. * given_cpu) causing exceess load to be moved to given_cpu.
  7175. * This however should not happen so much in practice and
  7176. * moreover subsequent load balance cycles should correct the
  7177. * excess load moved.
  7178. */
  7179. if ((env.flags & LBF_DST_PINNED) && env.imbalance > 0) {
  7180. /* Prevent to re-select dst_cpu via env's CPUs */
  7181. cpumask_clear_cpu(env.dst_cpu, env.cpus);
  7182. env.dst_rq = cpu_rq(env.new_dst_cpu);
  7183. env.dst_cpu = env.new_dst_cpu;
  7184. env.flags &= ~LBF_DST_PINNED;
  7185. env.loop = 0;
  7186. env.loop_break = sched_nr_migrate_break;
  7187. /*
  7188. * Go back to "more_balance" rather than "redo" since we
  7189. * need to continue with same src_cpu.
  7190. */
  7191. goto more_balance;
  7192. }
  7193. /*
  7194. * We failed to reach balance because of affinity.
  7195. */
  7196. if (sd_parent) {
  7197. int *group_imbalance = &sd_parent->groups->sgc->imbalance;
  7198. if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0)
  7199. *group_imbalance = 1;
  7200. }
  7201. /* All tasks on this runqueue were pinned by CPU affinity */
  7202. if (unlikely(env.flags & LBF_ALL_PINNED)) {
  7203. cpumask_clear_cpu(cpu_of(busiest), cpus);
  7204. /*
  7205. * Attempting to continue load balancing at the current
  7206. * sched_domain level only makes sense if there are
  7207. * active CPUs remaining as possible busiest CPUs to
  7208. * pull load from which are not contained within the
  7209. * destination group that is receiving any migrated
  7210. * load.
  7211. */
  7212. if (!cpumask_subset(cpus, env.dst_grpmask)) {
  7213. env.loop = 0;
  7214. env.loop_break = sched_nr_migrate_break;
  7215. goto redo;
  7216. }
  7217. goto out_all_pinned;
  7218. }
  7219. }
  7220. if (!ld_moved) {
  7221. schedstat_inc(sd->lb_failed[idle]);
  7222. /*
  7223. * Increment the failure counter only on periodic balance.
  7224. * We do not want newidle balance, which can be very
  7225. * frequent, pollute the failure counter causing
  7226. * excessive cache_hot migrations and active balances.
  7227. */
  7228. if (idle != CPU_NEWLY_IDLE)
  7229. sd->nr_balance_failed++;
  7230. if (need_active_balance(&env)) {
  7231. unsigned long flags;
  7232. raw_spin_lock_irqsave(&busiest->lock, flags);
  7233. /*
  7234. * Don't kick the active_load_balance_cpu_stop,
  7235. * if the curr task on busiest CPU can't be
  7236. * moved to this_cpu:
  7237. */
  7238. if (!cpumask_test_cpu(this_cpu, &busiest->curr->cpus_allowed)) {
  7239. raw_spin_unlock_irqrestore(&busiest->lock,
  7240. flags);
  7241. env.flags |= LBF_ALL_PINNED;
  7242. goto out_one_pinned;
  7243. }
  7244. /*
  7245. * ->active_balance synchronizes accesses to
  7246. * ->active_balance_work. Once set, it's cleared
  7247. * only after active load balance is finished.
  7248. */
  7249. if (!busiest->active_balance) {
  7250. busiest->active_balance = 1;
  7251. busiest->push_cpu = this_cpu;
  7252. active_balance = 1;
  7253. }
  7254. raw_spin_unlock_irqrestore(&busiest->lock, flags);
  7255. if (active_balance) {
  7256. stop_one_cpu_nowait(cpu_of(busiest),
  7257. active_load_balance_cpu_stop, busiest,
  7258. &busiest->active_balance_work);
  7259. }
  7260. /* We've kicked active balancing, force task migration. */
  7261. sd->nr_balance_failed = sd->cache_nice_tries+1;
  7262. }
  7263. } else
  7264. sd->nr_balance_failed = 0;
  7265. if (likely(!active_balance)) {
  7266. /* We were unbalanced, so reset the balancing interval */
  7267. sd->balance_interval = sd->min_interval;
  7268. } else {
  7269. /*
  7270. * If we've begun active balancing, start to back off. This
  7271. * case may not be covered by the all_pinned logic if there
  7272. * is only 1 task on the busy runqueue (because we don't call
  7273. * detach_tasks).
  7274. */
  7275. if (sd->balance_interval < sd->max_interval)
  7276. sd->balance_interval *= 2;
  7277. }
  7278. goto out;
  7279. out_balanced:
  7280. /*
  7281. * We reach balance although we may have faced some affinity
  7282. * constraints. Clear the imbalance flag if it was set.
  7283. */
  7284. if (sd_parent) {
  7285. int *group_imbalance = &sd_parent->groups->sgc->imbalance;
  7286. if (*group_imbalance)
  7287. *group_imbalance = 0;
  7288. }
  7289. out_all_pinned:
  7290. /*
  7291. * We reach balance because all tasks are pinned at this level so
  7292. * we can't migrate them. Let the imbalance flag set so parent level
  7293. * can try to migrate them.
  7294. */
  7295. schedstat_inc(sd->lb_balanced[idle]);
  7296. sd->nr_balance_failed = 0;
  7297. out_one_pinned:
  7298. /* tune up the balancing interval */
  7299. if (((env.flags & LBF_ALL_PINNED) &&
  7300. sd->balance_interval < MAX_PINNED_INTERVAL) ||
  7301. (sd->balance_interval < sd->max_interval))
  7302. sd->balance_interval *= 2;
  7303. ld_moved = 0;
  7304. out:
  7305. return ld_moved;
  7306. }
  7307. static inline unsigned long
  7308. get_sd_balance_interval(struct sched_domain *sd, int cpu_busy)
  7309. {
  7310. unsigned long interval = sd->balance_interval;
  7311. if (cpu_busy)
  7312. interval *= sd->busy_factor;
  7313. /* scale ms to jiffies */
  7314. interval = msecs_to_jiffies(interval);
  7315. interval = clamp(interval, 1UL, max_load_balance_interval);
  7316. return interval;
  7317. }
  7318. static inline void
  7319. update_next_balance(struct sched_domain *sd, unsigned long *next_balance)
  7320. {
  7321. unsigned long interval, next;
  7322. /* used by idle balance, so cpu_busy = 0 */
  7323. interval = get_sd_balance_interval(sd, 0);
  7324. next = sd->last_balance + interval;
  7325. if (time_after(*next_balance, next))
  7326. *next_balance = next;
  7327. }
  7328. /*
  7329. * active_load_balance_cpu_stop is run by the CPU stopper. It pushes
  7330. * running tasks off the busiest CPU onto idle CPUs. It requires at
  7331. * least 1 task to be running on each physical CPU where possible, and
  7332. * avoids physical / logical imbalances.
  7333. */
  7334. static int active_load_balance_cpu_stop(void *data)
  7335. {
  7336. struct rq *busiest_rq = data;
  7337. int busiest_cpu = cpu_of(busiest_rq);
  7338. int target_cpu = busiest_rq->push_cpu;
  7339. struct rq *target_rq = cpu_rq(target_cpu);
  7340. struct sched_domain *sd;
  7341. struct task_struct *p = NULL;
  7342. struct rq_flags rf;
  7343. rq_lock_irq(busiest_rq, &rf);
  7344. /*
  7345. * Between queueing the stop-work and running it is a hole in which
  7346. * CPUs can become inactive. We should not move tasks from or to
  7347. * inactive CPUs.
  7348. */
  7349. if (!cpu_active(busiest_cpu) || !cpu_active(target_cpu))
  7350. goto out_unlock;
  7351. /* Make sure the requested CPU hasn't gone down in the meantime: */
  7352. if (unlikely(busiest_cpu != smp_processor_id() ||
  7353. !busiest_rq->active_balance))
  7354. goto out_unlock;
  7355. /* Is there any task to move? */
  7356. if (busiest_rq->nr_running <= 1)
  7357. goto out_unlock;
  7358. /*
  7359. * This condition is "impossible", if it occurs
  7360. * we need to fix it. Originally reported by
  7361. * Bjorn Helgaas on a 128-CPU setup.
  7362. */
  7363. BUG_ON(busiest_rq == target_rq);
  7364. /* Search for an sd spanning us and the target CPU. */
  7365. rcu_read_lock();
  7366. for_each_domain(target_cpu, sd) {
  7367. if ((sd->flags & SD_LOAD_BALANCE) &&
  7368. cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
  7369. break;
  7370. }
  7371. if (likely(sd)) {
  7372. struct lb_env env = {
  7373. .sd = sd,
  7374. .dst_cpu = target_cpu,
  7375. .dst_rq = target_rq,
  7376. .src_cpu = busiest_rq->cpu,
  7377. .src_rq = busiest_rq,
  7378. .idle = CPU_IDLE,
  7379. /*
  7380. * can_migrate_task() doesn't need to compute new_dst_cpu
  7381. * for active balancing. Since we have CPU_IDLE, but no
  7382. * @dst_grpmask we need to make that test go away with lying
  7383. * about DST_PINNED.
  7384. */
  7385. .flags = LBF_DST_PINNED,
  7386. };
  7387. schedstat_inc(sd->alb_count);
  7388. update_rq_clock(busiest_rq);
  7389. p = detach_one_task(&env);
  7390. if (p) {
  7391. schedstat_inc(sd->alb_pushed);
  7392. /* Active balancing done, reset the failure counter. */
  7393. sd->nr_balance_failed = 0;
  7394. } else {
  7395. schedstat_inc(sd->alb_failed);
  7396. }
  7397. }
  7398. rcu_read_unlock();
  7399. out_unlock:
  7400. busiest_rq->active_balance = 0;
  7401. rq_unlock(busiest_rq, &rf);
  7402. if (p)
  7403. attach_one_task(target_rq, p);
  7404. local_irq_enable();
  7405. return 0;
  7406. }
  7407. static DEFINE_SPINLOCK(balancing);
  7408. /*
  7409. * Scale the max load_balance interval with the number of CPUs in the system.
  7410. * This trades load-balance latency on larger machines for less cross talk.
  7411. */
  7412. void update_max_interval(void)
  7413. {
  7414. max_load_balance_interval = HZ*num_online_cpus()/10;
  7415. }
  7416. /*
  7417. * It checks each scheduling domain to see if it is due to be balanced,
  7418. * and initiates a balancing operation if so.
  7419. *
  7420. * Balancing parameters are set up in init_sched_domains.
  7421. */
  7422. static void rebalance_domains(struct rq *rq, enum cpu_idle_type idle)
  7423. {
  7424. int continue_balancing = 1;
  7425. int cpu = rq->cpu;
  7426. unsigned long interval;
  7427. struct sched_domain *sd;
  7428. /* Earliest time when we have to do rebalance again */
  7429. unsigned long next_balance = jiffies + 60*HZ;
  7430. int update_next_balance = 0;
  7431. int need_serialize, need_decay = 0;
  7432. u64 max_cost = 0;
  7433. rcu_read_lock();
  7434. for_each_domain(cpu, sd) {
  7435. /*
  7436. * Decay the newidle max times here because this is a regular
  7437. * visit to all the domains. Decay ~1% per second.
  7438. */
  7439. if (time_after(jiffies, sd->next_decay_max_lb_cost)) {
  7440. sd->max_newidle_lb_cost =
  7441. (sd->max_newidle_lb_cost * 253) / 256;
  7442. sd->next_decay_max_lb_cost = jiffies + HZ;
  7443. need_decay = 1;
  7444. }
  7445. max_cost += sd->max_newidle_lb_cost;
  7446. if (!(sd->flags & SD_LOAD_BALANCE))
  7447. continue;
  7448. /*
  7449. * Stop the load balance at this level. There is another
  7450. * CPU in our sched group which is doing load balancing more
  7451. * actively.
  7452. */
  7453. if (!continue_balancing) {
  7454. if (need_decay)
  7455. continue;
  7456. break;
  7457. }
  7458. interval = get_sd_balance_interval(sd, idle != CPU_IDLE);
  7459. need_serialize = sd->flags & SD_SERIALIZE;
  7460. if (need_serialize) {
  7461. if (!spin_trylock(&balancing))
  7462. goto out;
  7463. }
  7464. if (time_after_eq(jiffies, sd->last_balance + interval)) {
  7465. if (load_balance(cpu, rq, sd, idle, &continue_balancing)) {
  7466. /*
  7467. * The LBF_DST_PINNED logic could have changed
  7468. * env->dst_cpu, so we can't know our idle
  7469. * state even if we migrated tasks. Update it.
  7470. */
  7471. idle = idle_cpu(cpu) ? CPU_IDLE : CPU_NOT_IDLE;
  7472. }
  7473. sd->last_balance = jiffies;
  7474. interval = get_sd_balance_interval(sd, idle != CPU_IDLE);
  7475. }
  7476. if (need_serialize)
  7477. spin_unlock(&balancing);
  7478. out:
  7479. if (time_after(next_balance, sd->last_balance + interval)) {
  7480. next_balance = sd->last_balance + interval;
  7481. update_next_balance = 1;
  7482. }
  7483. }
  7484. if (need_decay) {
  7485. /*
  7486. * Ensure the rq-wide value also decays but keep it at a
  7487. * reasonable floor to avoid funnies with rq->avg_idle.
  7488. */
  7489. rq->max_idle_balance_cost =
  7490. max((u64)sysctl_sched_migration_cost, max_cost);
  7491. }
  7492. rcu_read_unlock();
  7493. /*
  7494. * next_balance will be updated only when there is a need.
  7495. * When the cpu is attached to null domain for ex, it will not be
  7496. * updated.
  7497. */
  7498. if (likely(update_next_balance)) {
  7499. rq->next_balance = next_balance;
  7500. #ifdef CONFIG_NO_HZ_COMMON
  7501. /*
  7502. * If this CPU has been elected to perform the nohz idle
  7503. * balance. Other idle CPUs have already rebalanced with
  7504. * nohz_idle_balance() and nohz.next_balance has been
  7505. * updated accordingly. This CPU is now running the idle load
  7506. * balance for itself and we need to update the
  7507. * nohz.next_balance accordingly.
  7508. */
  7509. if ((idle == CPU_IDLE) && time_after(nohz.next_balance, rq->next_balance))
  7510. nohz.next_balance = rq->next_balance;
  7511. #endif
  7512. }
  7513. }
  7514. static inline int on_null_domain(struct rq *rq)
  7515. {
  7516. return unlikely(!rcu_dereference_sched(rq->sd));
  7517. }
  7518. #ifdef CONFIG_NO_HZ_COMMON
  7519. /*
  7520. * idle load balancing details
  7521. * - When one of the busy CPUs notice that there may be an idle rebalancing
  7522. * needed, they will kick the idle load balancer, which then does idle
  7523. * load balancing for all the idle CPUs.
  7524. */
  7525. static inline int find_new_ilb(void)
  7526. {
  7527. int ilb = cpumask_first(nohz.idle_cpus_mask);
  7528. if (ilb < nr_cpu_ids && idle_cpu(ilb))
  7529. return ilb;
  7530. return nr_cpu_ids;
  7531. }
  7532. /*
  7533. * Kick a CPU to do the nohz balancing, if it is time for it. We pick the
  7534. * nohz_load_balancer CPU (if there is one) otherwise fallback to any idle
  7535. * CPU (if there is one).
  7536. */
  7537. static void kick_ilb(unsigned int flags)
  7538. {
  7539. int ilb_cpu;
  7540. nohz.next_balance++;
  7541. ilb_cpu = find_new_ilb();
  7542. if (ilb_cpu >= nr_cpu_ids)
  7543. return;
  7544. flags = atomic_fetch_or(flags, nohz_flags(ilb_cpu));
  7545. if (flags & NOHZ_KICK_MASK)
  7546. return;
  7547. /*
  7548. * Use smp_send_reschedule() instead of resched_cpu().
  7549. * This way we generate a sched IPI on the target CPU which
  7550. * is idle. And the softirq performing nohz idle load balance
  7551. * will be run before returning from the IPI.
  7552. */
  7553. smp_send_reschedule(ilb_cpu);
  7554. }
  7555. /*
  7556. * Current heuristic for kicking the idle load balancer in the presence
  7557. * of an idle cpu in the system.
  7558. * - This rq has more than one task.
  7559. * - This rq has at least one CFS task and the capacity of the CPU is
  7560. * significantly reduced because of RT tasks or IRQs.
  7561. * - At parent of LLC scheduler domain level, this cpu's scheduler group has
  7562. * multiple busy cpu.
  7563. * - For SD_ASYM_PACKING, if the lower numbered cpu's in the scheduler
  7564. * domain span are idle.
  7565. */
  7566. static void nohz_balancer_kick(struct rq *rq)
  7567. {
  7568. unsigned long now = jiffies;
  7569. struct sched_domain_shared *sds;
  7570. struct sched_domain *sd;
  7571. int nr_busy, i, cpu = rq->cpu;
  7572. unsigned int flags = 0;
  7573. if (unlikely(rq->idle_balance))
  7574. return;
  7575. /*
  7576. * We may be recently in ticked or tickless idle mode. At the first
  7577. * busy tick after returning from idle, we will update the busy stats.
  7578. */
  7579. nohz_balance_exit_idle(rq);
  7580. /*
  7581. * None are in tickless mode and hence no need for NOHZ idle load
  7582. * balancing.
  7583. */
  7584. if (likely(!atomic_read(&nohz.nr_cpus)))
  7585. return;
  7586. if (READ_ONCE(nohz.has_blocked) &&
  7587. time_after(now, READ_ONCE(nohz.next_blocked)))
  7588. flags = NOHZ_STATS_KICK;
  7589. if (time_before(now, nohz.next_balance))
  7590. goto out;
  7591. if (rq->nr_running >= 2) {
  7592. flags = NOHZ_KICK_MASK;
  7593. goto out;
  7594. }
  7595. rcu_read_lock();
  7596. sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
  7597. if (sds) {
  7598. /*
  7599. * XXX: write a coherent comment on why we do this.
  7600. * See also: http://lkml.kernel.org/r/20111202010832.602203411@sbsiddha-desk.sc.intel.com
  7601. */
  7602. nr_busy = atomic_read(&sds->nr_busy_cpus);
  7603. if (nr_busy > 1) {
  7604. flags = NOHZ_KICK_MASK;
  7605. goto unlock;
  7606. }
  7607. }
  7608. sd = rcu_dereference(rq->sd);
  7609. if (sd) {
  7610. if ((rq->cfs.h_nr_running >= 1) &&
  7611. check_cpu_capacity(rq, sd)) {
  7612. flags = NOHZ_KICK_MASK;
  7613. goto unlock;
  7614. }
  7615. }
  7616. sd = rcu_dereference(per_cpu(sd_asym, cpu));
  7617. if (sd) {
  7618. for_each_cpu(i, sched_domain_span(sd)) {
  7619. if (i == cpu ||
  7620. !cpumask_test_cpu(i, nohz.idle_cpus_mask))
  7621. continue;
  7622. if (sched_asym_prefer(i, cpu)) {
  7623. flags = NOHZ_KICK_MASK;
  7624. goto unlock;
  7625. }
  7626. }
  7627. }
  7628. unlock:
  7629. rcu_read_unlock();
  7630. out:
  7631. if (flags)
  7632. kick_ilb(flags);
  7633. }
  7634. static void set_cpu_sd_state_busy(int cpu)
  7635. {
  7636. struct sched_domain *sd;
  7637. rcu_read_lock();
  7638. sd = rcu_dereference(per_cpu(sd_llc, cpu));
  7639. if (!sd || !sd->nohz_idle)
  7640. goto unlock;
  7641. sd->nohz_idle = 0;
  7642. atomic_inc(&sd->shared->nr_busy_cpus);
  7643. unlock:
  7644. rcu_read_unlock();
  7645. }
  7646. void nohz_balance_exit_idle(struct rq *rq)
  7647. {
  7648. SCHED_WARN_ON(rq != this_rq());
  7649. if (likely(!rq->nohz_tick_stopped))
  7650. return;
  7651. rq->nohz_tick_stopped = 0;
  7652. cpumask_clear_cpu(rq->cpu, nohz.idle_cpus_mask);
  7653. atomic_dec(&nohz.nr_cpus);
  7654. set_cpu_sd_state_busy(rq->cpu);
  7655. }
  7656. static void set_cpu_sd_state_idle(int cpu)
  7657. {
  7658. struct sched_domain *sd;
  7659. rcu_read_lock();
  7660. sd = rcu_dereference(per_cpu(sd_llc, cpu));
  7661. if (!sd || sd->nohz_idle)
  7662. goto unlock;
  7663. sd->nohz_idle = 1;
  7664. atomic_dec(&sd->shared->nr_busy_cpus);
  7665. unlock:
  7666. rcu_read_unlock();
  7667. }
  7668. /*
  7669. * This routine will record that the CPU is going idle with tick stopped.
  7670. * This info will be used in performing idle load balancing in the future.
  7671. */
  7672. void nohz_balance_enter_idle(int cpu)
  7673. {
  7674. struct rq *rq = cpu_rq(cpu);
  7675. SCHED_WARN_ON(cpu != smp_processor_id());
  7676. /* If this CPU is going down, then nothing needs to be done: */
  7677. if (!cpu_active(cpu))
  7678. return;
  7679. /* Spare idle load balancing on CPUs that don't want to be disturbed: */
  7680. if (!housekeeping_cpu(cpu, HK_FLAG_SCHED))
  7681. return;
  7682. /*
  7683. * Can be set safely without rq->lock held
  7684. * If a clear happens, it will have evaluated last additions because
  7685. * rq->lock is held during the check and the clear
  7686. */
  7687. rq->has_blocked_load = 1;
  7688. /*
  7689. * The tick is still stopped but load could have been added in the
  7690. * meantime. We set the nohz.has_blocked flag to trig a check of the
  7691. * *_avg. The CPU is already part of nohz.idle_cpus_mask so the clear
  7692. * of nohz.has_blocked can only happen after checking the new load
  7693. */
  7694. if (rq->nohz_tick_stopped)
  7695. goto out;
  7696. /* If we're a completely isolated CPU, we don't play: */
  7697. if (on_null_domain(rq))
  7698. return;
  7699. rq->nohz_tick_stopped = 1;
  7700. cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
  7701. atomic_inc(&nohz.nr_cpus);
  7702. /*
  7703. * Ensures that if nohz_idle_balance() fails to observe our
  7704. * @idle_cpus_mask store, it must observe the @has_blocked
  7705. * store.
  7706. */
  7707. smp_mb__after_atomic();
  7708. set_cpu_sd_state_idle(cpu);
  7709. out:
  7710. /*
  7711. * Each time a cpu enter idle, we assume that it has blocked load and
  7712. * enable the periodic update of the load of idle cpus
  7713. */
  7714. WRITE_ONCE(nohz.has_blocked, 1);
  7715. }
  7716. /*
  7717. * Internal function that runs load balance for all idle cpus. The load balance
  7718. * can be a simple update of blocked load or a complete load balance with
  7719. * tasks movement depending of flags.
  7720. * The function returns false if the loop has stopped before running
  7721. * through all idle CPUs.
  7722. */
  7723. static bool _nohz_idle_balance(struct rq *this_rq, unsigned int flags,
  7724. enum cpu_idle_type idle)
  7725. {
  7726. /* Earliest time when we have to do rebalance again */
  7727. unsigned long now = jiffies;
  7728. unsigned long next_balance = now + 60*HZ;
  7729. bool has_blocked_load = false;
  7730. int update_next_balance = 0;
  7731. int this_cpu = this_rq->cpu;
  7732. int balance_cpu;
  7733. int ret = false;
  7734. struct rq *rq;
  7735. SCHED_WARN_ON((flags & NOHZ_KICK_MASK) == NOHZ_BALANCE_KICK);
  7736. /*
  7737. * We assume there will be no idle load after this update and clear
  7738. * the has_blocked flag. If a cpu enters idle in the mean time, it will
  7739. * set the has_blocked flag and trig another update of idle load.
  7740. * Because a cpu that becomes idle, is added to idle_cpus_mask before
  7741. * setting the flag, we are sure to not clear the state and not
  7742. * check the load of an idle cpu.
  7743. */
  7744. WRITE_ONCE(nohz.has_blocked, 0);
  7745. /*
  7746. * Ensures that if we miss the CPU, we must see the has_blocked
  7747. * store from nohz_balance_enter_idle().
  7748. */
  7749. smp_mb();
  7750. for_each_cpu(balance_cpu, nohz.idle_cpus_mask) {
  7751. if (balance_cpu == this_cpu || !idle_cpu(balance_cpu))
  7752. continue;
  7753. /*
  7754. * If this CPU gets work to do, stop the load balancing
  7755. * work being done for other CPUs. Next load
  7756. * balancing owner will pick it up.
  7757. */
  7758. if (need_resched()) {
  7759. has_blocked_load = true;
  7760. goto abort;
  7761. }
  7762. rq = cpu_rq(balance_cpu);
  7763. has_blocked_load |= update_nohz_stats(rq, true);
  7764. /*
  7765. * If time for next balance is due,
  7766. * do the balance.
  7767. */
  7768. if (time_after_eq(jiffies, rq->next_balance)) {
  7769. struct rq_flags rf;
  7770. rq_lock_irqsave(rq, &rf);
  7771. update_rq_clock(rq);
  7772. cpu_load_update_idle(rq);
  7773. rq_unlock_irqrestore(rq, &rf);
  7774. if (flags & NOHZ_BALANCE_KICK)
  7775. rebalance_domains(rq, CPU_IDLE);
  7776. }
  7777. if (time_after(next_balance, rq->next_balance)) {
  7778. next_balance = rq->next_balance;
  7779. update_next_balance = 1;
  7780. }
  7781. }
  7782. /* Newly idle CPU doesn't need an update */
  7783. if (idle != CPU_NEWLY_IDLE) {
  7784. update_blocked_averages(this_cpu);
  7785. has_blocked_load |= this_rq->has_blocked_load;
  7786. }
  7787. if (flags & NOHZ_BALANCE_KICK)
  7788. rebalance_domains(this_rq, CPU_IDLE);
  7789. WRITE_ONCE(nohz.next_blocked,
  7790. now + msecs_to_jiffies(LOAD_AVG_PERIOD));
  7791. /* The full idle balance loop has been done */
  7792. ret = true;
  7793. abort:
  7794. /* There is still blocked load, enable periodic update */
  7795. if (has_blocked_load)
  7796. WRITE_ONCE(nohz.has_blocked, 1);
  7797. /*
  7798. * next_balance will be updated only when there is a need.
  7799. * When the CPU is attached to null domain for ex, it will not be
  7800. * updated.
  7801. */
  7802. if (likely(update_next_balance))
  7803. nohz.next_balance = next_balance;
  7804. return ret;
  7805. }
  7806. /*
  7807. * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the
  7808. * rebalancing for all the cpus for whom scheduler ticks are stopped.
  7809. */
  7810. static bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
  7811. {
  7812. int this_cpu = this_rq->cpu;
  7813. unsigned int flags;
  7814. if (!(atomic_read(nohz_flags(this_cpu)) & NOHZ_KICK_MASK))
  7815. return false;
  7816. if (idle != CPU_IDLE) {
  7817. atomic_andnot(NOHZ_KICK_MASK, nohz_flags(this_cpu));
  7818. return false;
  7819. }
  7820. /*
  7821. * barrier, pairs with nohz_balance_enter_idle(), ensures ...
  7822. */
  7823. flags = atomic_fetch_andnot(NOHZ_KICK_MASK, nohz_flags(this_cpu));
  7824. if (!(flags & NOHZ_KICK_MASK))
  7825. return false;
  7826. _nohz_idle_balance(this_rq, flags, idle);
  7827. return true;
  7828. }
  7829. static void nohz_newidle_balance(struct rq *this_rq)
  7830. {
  7831. int this_cpu = this_rq->cpu;
  7832. /*
  7833. * This CPU doesn't want to be disturbed by scheduler
  7834. * housekeeping
  7835. */
  7836. if (!housekeeping_cpu(this_cpu, HK_FLAG_SCHED))
  7837. return;
  7838. /* Will wake up very soon. No time for doing anything else*/
  7839. if (this_rq->avg_idle < sysctl_sched_migration_cost)
  7840. return;
  7841. /* Don't need to update blocked load of idle CPUs*/
  7842. if (!READ_ONCE(nohz.has_blocked) ||
  7843. time_before(jiffies, READ_ONCE(nohz.next_blocked)))
  7844. return;
  7845. raw_spin_unlock(&this_rq->lock);
  7846. /*
  7847. * This CPU is going to be idle and blocked load of idle CPUs
  7848. * need to be updated. Run the ilb locally as it is a good
  7849. * candidate for ilb instead of waking up another idle CPU.
  7850. * Kick an normal ilb if we failed to do the update.
  7851. */
  7852. if (!_nohz_idle_balance(this_rq, NOHZ_STATS_KICK, CPU_NEWLY_IDLE))
  7853. kick_ilb(NOHZ_STATS_KICK);
  7854. raw_spin_lock(&this_rq->lock);
  7855. }
  7856. #else /* !CONFIG_NO_HZ_COMMON */
  7857. static inline void nohz_balancer_kick(struct rq *rq) { }
  7858. static inline bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
  7859. {
  7860. return false;
  7861. }
  7862. static inline void nohz_newidle_balance(struct rq *this_rq) { }
  7863. #endif /* CONFIG_NO_HZ_COMMON */
  7864. /*
  7865. * idle_balance is called by schedule() if this_cpu is about to become
  7866. * idle. Attempts to pull tasks from other CPUs.
  7867. */
  7868. static int idle_balance(struct rq *this_rq, struct rq_flags *rf)
  7869. {
  7870. unsigned long next_balance = jiffies + HZ;
  7871. int this_cpu = this_rq->cpu;
  7872. struct sched_domain *sd;
  7873. int pulled_task = 0;
  7874. u64 curr_cost = 0;
  7875. /*
  7876. * We must set idle_stamp _before_ calling idle_balance(), such that we
  7877. * measure the duration of idle_balance() as idle time.
  7878. */
  7879. this_rq->idle_stamp = rq_clock(this_rq);
  7880. /*
  7881. * Do not pull tasks towards !active CPUs...
  7882. */
  7883. if (!cpu_active(this_cpu))
  7884. return 0;
  7885. /*
  7886. * This is OK, because current is on_cpu, which avoids it being picked
  7887. * for load-balance and preemption/IRQs are still disabled avoiding
  7888. * further scheduler activity on it and we're being very careful to
  7889. * re-start the picking loop.
  7890. */
  7891. rq_unpin_lock(this_rq, rf);
  7892. if (this_rq->avg_idle < sysctl_sched_migration_cost ||
  7893. !this_rq->rd->overload) {
  7894. rcu_read_lock();
  7895. sd = rcu_dereference_check_sched_domain(this_rq->sd);
  7896. if (sd)
  7897. update_next_balance(sd, &next_balance);
  7898. rcu_read_unlock();
  7899. nohz_newidle_balance(this_rq);
  7900. goto out;
  7901. }
  7902. raw_spin_unlock(&this_rq->lock);
  7903. update_blocked_averages(this_cpu);
  7904. rcu_read_lock();
  7905. for_each_domain(this_cpu, sd) {
  7906. int continue_balancing = 1;
  7907. u64 t0, domain_cost;
  7908. if (!(sd->flags & SD_LOAD_BALANCE))
  7909. continue;
  7910. if (this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost) {
  7911. update_next_balance(sd, &next_balance);
  7912. break;
  7913. }
  7914. if (sd->flags & SD_BALANCE_NEWIDLE) {
  7915. t0 = sched_clock_cpu(this_cpu);
  7916. pulled_task = load_balance(this_cpu, this_rq,
  7917. sd, CPU_NEWLY_IDLE,
  7918. &continue_balancing);
  7919. domain_cost = sched_clock_cpu(this_cpu) - t0;
  7920. if (domain_cost > sd->max_newidle_lb_cost)
  7921. sd->max_newidle_lb_cost = domain_cost;
  7922. curr_cost += domain_cost;
  7923. }
  7924. update_next_balance(sd, &next_balance);
  7925. /*
  7926. * Stop searching for tasks to pull if there are
  7927. * now runnable tasks on this rq.
  7928. */
  7929. if (pulled_task || this_rq->nr_running > 0)
  7930. break;
  7931. }
  7932. rcu_read_unlock();
  7933. raw_spin_lock(&this_rq->lock);
  7934. if (curr_cost > this_rq->max_idle_balance_cost)
  7935. this_rq->max_idle_balance_cost = curr_cost;
  7936. out:
  7937. /*
  7938. * While browsing the domains, we released the rq lock, a task could
  7939. * have been enqueued in the meantime. Since we're not going idle,
  7940. * pretend we pulled a task.
  7941. */
  7942. if (this_rq->cfs.h_nr_running && !pulled_task)
  7943. pulled_task = 1;
  7944. /* Move the next balance forward */
  7945. if (time_after(this_rq->next_balance, next_balance))
  7946. this_rq->next_balance = next_balance;
  7947. /* Is there a task of a high priority class? */
  7948. if (this_rq->nr_running != this_rq->cfs.h_nr_running)
  7949. pulled_task = -1;
  7950. if (pulled_task)
  7951. this_rq->idle_stamp = 0;
  7952. rq_repin_lock(this_rq, rf);
  7953. return pulled_task;
  7954. }
  7955. /*
  7956. * run_rebalance_domains is triggered when needed from the scheduler tick.
  7957. * Also triggered for nohz idle balancing (with nohz_balancing_kick set).
  7958. */
  7959. static __latent_entropy void run_rebalance_domains(struct softirq_action *h)
  7960. {
  7961. struct rq *this_rq = this_rq();
  7962. enum cpu_idle_type idle = this_rq->idle_balance ?
  7963. CPU_IDLE : CPU_NOT_IDLE;
  7964. /*
  7965. * If this CPU has a pending nohz_balance_kick, then do the
  7966. * balancing on behalf of the other idle CPUs whose ticks are
  7967. * stopped. Do nohz_idle_balance *before* rebalance_domains to
  7968. * give the idle CPUs a chance to load balance. Else we may
  7969. * load balance only within the local sched_domain hierarchy
  7970. * and abort nohz_idle_balance altogether if we pull some load.
  7971. */
  7972. if (nohz_idle_balance(this_rq, idle))
  7973. return;
  7974. /* normal load balance */
  7975. update_blocked_averages(this_rq->cpu);
  7976. rebalance_domains(this_rq, idle);
  7977. }
  7978. /*
  7979. * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
  7980. */
  7981. void trigger_load_balance(struct rq *rq)
  7982. {
  7983. /* Don't need to rebalance while attached to NULL domain */
  7984. if (unlikely(on_null_domain(rq)))
  7985. return;
  7986. if (time_after_eq(jiffies, rq->next_balance))
  7987. raise_softirq(SCHED_SOFTIRQ);
  7988. nohz_balancer_kick(rq);
  7989. }
  7990. static void rq_online_fair(struct rq *rq)
  7991. {
  7992. update_sysctl();
  7993. update_runtime_enabled(rq);
  7994. }
  7995. static void rq_offline_fair(struct rq *rq)
  7996. {
  7997. update_sysctl();
  7998. /* Ensure any throttled groups are reachable by pick_next_task */
  7999. unthrottle_offline_cfs_rqs(rq);
  8000. }
  8001. #endif /* CONFIG_SMP */
  8002. /*
  8003. * scheduler tick hitting a task of our scheduling class.
  8004. *
  8005. * NOTE: This function can be called remotely by the tick offload that
  8006. * goes along full dynticks. Therefore no local assumption can be made
  8007. * and everything must be accessed through the @rq and @curr passed in
  8008. * parameters.
  8009. */
  8010. static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)
  8011. {
  8012. struct cfs_rq *cfs_rq;
  8013. struct sched_entity *se = &curr->se;
  8014. for_each_sched_entity(se) {
  8015. cfs_rq = cfs_rq_of(se);
  8016. entity_tick(cfs_rq, se, queued);
  8017. }
  8018. if (static_branch_unlikely(&sched_numa_balancing))
  8019. task_tick_numa(rq, curr);
  8020. }
  8021. /*
  8022. * called on fork with the child task as argument from the parent's context
  8023. * - child not yet on the tasklist
  8024. * - preemption disabled
  8025. */
  8026. static void task_fork_fair(struct task_struct *p)
  8027. {
  8028. struct cfs_rq *cfs_rq;
  8029. struct sched_entity *se = &p->se, *curr;
  8030. struct rq *rq = this_rq();
  8031. struct rq_flags rf;
  8032. rq_lock(rq, &rf);
  8033. update_rq_clock(rq);
  8034. cfs_rq = task_cfs_rq(current);
  8035. curr = cfs_rq->curr;
  8036. if (curr) {
  8037. update_curr(cfs_rq);
  8038. se->vruntime = curr->vruntime;
  8039. }
  8040. place_entity(cfs_rq, se, 1);
  8041. if (sysctl_sched_child_runs_first && curr && entity_before(curr, se)) {
  8042. /*
  8043. * Upon rescheduling, sched_class::put_prev_task() will place
  8044. * 'current' within the tree based on its new key value.
  8045. */
  8046. swap(curr->vruntime, se->vruntime);
  8047. resched_curr(rq);
  8048. }
  8049. se->vruntime -= cfs_rq->min_vruntime;
  8050. rq_unlock(rq, &rf);
  8051. }
  8052. /*
  8053. * Priority of the task has changed. Check to see if we preempt
  8054. * the current task.
  8055. */
  8056. static void
  8057. prio_changed_fair(struct rq *rq, struct task_struct *p, int oldprio)
  8058. {
  8059. if (!task_on_rq_queued(p))
  8060. return;
  8061. /*
  8062. * Reschedule if we are currently running on this runqueue and
  8063. * our priority decreased, or if we are not currently running on
  8064. * this runqueue and our priority is higher than the current's
  8065. */
  8066. if (rq->curr == p) {
  8067. if (p->prio > oldprio)
  8068. resched_curr(rq);
  8069. } else
  8070. check_preempt_curr(rq, p, 0);
  8071. }
  8072. static inline bool vruntime_normalized(struct task_struct *p)
  8073. {
  8074. struct sched_entity *se = &p->se;
  8075. /*
  8076. * In both the TASK_ON_RQ_QUEUED and TASK_ON_RQ_MIGRATING cases,
  8077. * the dequeue_entity(.flags=0) will already have normalized the
  8078. * vruntime.
  8079. */
  8080. if (p->on_rq)
  8081. return true;
  8082. /*
  8083. * When !on_rq, vruntime of the task has usually NOT been normalized.
  8084. * But there are some cases where it has already been normalized:
  8085. *
  8086. * - A forked child which is waiting for being woken up by
  8087. * wake_up_new_task().
  8088. * - A task which has been woken up by try_to_wake_up() and
  8089. * waiting for actually being woken up by sched_ttwu_pending().
  8090. */
  8091. if (!se->sum_exec_runtime || p->state == TASK_WAKING)
  8092. return true;
  8093. return false;
  8094. }
  8095. #ifdef CONFIG_FAIR_GROUP_SCHED
  8096. /*
  8097. * Propagate the changes of the sched_entity across the tg tree to make it
  8098. * visible to the root
  8099. */
  8100. static void propagate_entity_cfs_rq(struct sched_entity *se)
  8101. {
  8102. struct cfs_rq *cfs_rq;
  8103. /* Start to propagate at parent */
  8104. se = se->parent;
  8105. for_each_sched_entity(se) {
  8106. cfs_rq = cfs_rq_of(se);
  8107. if (cfs_rq_throttled(cfs_rq))
  8108. break;
  8109. update_load_avg(cfs_rq, se, UPDATE_TG);
  8110. }
  8111. }
  8112. #else
  8113. static void propagate_entity_cfs_rq(struct sched_entity *se) { }
  8114. #endif
  8115. static void detach_entity_cfs_rq(struct sched_entity *se)
  8116. {
  8117. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  8118. /* Catch up with the cfs_rq and remove our load when we leave */
  8119. update_load_avg(cfs_rq, se, 0);
  8120. detach_entity_load_avg(cfs_rq, se);
  8121. update_tg_load_avg(cfs_rq, false);
  8122. propagate_entity_cfs_rq(se);
  8123. }
  8124. static void attach_entity_cfs_rq(struct sched_entity *se)
  8125. {
  8126. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  8127. #ifdef CONFIG_FAIR_GROUP_SCHED
  8128. /*
  8129. * Since the real-depth could have been changed (only FAIR
  8130. * class maintain depth value), reset depth properly.
  8131. */
  8132. se->depth = se->parent ? se->parent->depth + 1 : 0;
  8133. #endif
  8134. /* Synchronize entity with its cfs_rq */
  8135. update_load_avg(cfs_rq, se, sched_feat(ATTACH_AGE_LOAD) ? 0 : SKIP_AGE_LOAD);
  8136. attach_entity_load_avg(cfs_rq, se, 0);
  8137. update_tg_load_avg(cfs_rq, false);
  8138. propagate_entity_cfs_rq(se);
  8139. }
  8140. static void detach_task_cfs_rq(struct task_struct *p)
  8141. {
  8142. struct sched_entity *se = &p->se;
  8143. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  8144. if (!vruntime_normalized(p)) {
  8145. /*
  8146. * Fix up our vruntime so that the current sleep doesn't
  8147. * cause 'unlimited' sleep bonus.
  8148. */
  8149. place_entity(cfs_rq, se, 0);
  8150. se->vruntime -= cfs_rq->min_vruntime;
  8151. }
  8152. detach_entity_cfs_rq(se);
  8153. }
  8154. static void attach_task_cfs_rq(struct task_struct *p)
  8155. {
  8156. struct sched_entity *se = &p->se;
  8157. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  8158. attach_entity_cfs_rq(se);
  8159. if (!vruntime_normalized(p))
  8160. se->vruntime += cfs_rq->min_vruntime;
  8161. }
  8162. static void switched_from_fair(struct rq *rq, struct task_struct *p)
  8163. {
  8164. detach_task_cfs_rq(p);
  8165. }
  8166. static void switched_to_fair(struct rq *rq, struct task_struct *p)
  8167. {
  8168. attach_task_cfs_rq(p);
  8169. if (task_on_rq_queued(p)) {
  8170. /*
  8171. * We were most likely switched from sched_rt, so
  8172. * kick off the schedule if running, otherwise just see
  8173. * if we can still preempt the current task.
  8174. */
  8175. if (rq->curr == p)
  8176. resched_curr(rq);
  8177. else
  8178. check_preempt_curr(rq, p, 0);
  8179. }
  8180. }
  8181. /* Account for a task changing its policy or group.
  8182. *
  8183. * This routine is mostly called to set cfs_rq->curr field when a task
  8184. * migrates between groups/classes.
  8185. */
  8186. static void set_curr_task_fair(struct rq *rq)
  8187. {
  8188. struct sched_entity *se = &rq->curr->se;
  8189. for_each_sched_entity(se) {
  8190. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  8191. set_next_entity(cfs_rq, se);
  8192. /* ensure bandwidth has been allocated on our new cfs_rq */
  8193. account_cfs_rq_runtime(cfs_rq, 0);
  8194. }
  8195. }
  8196. void init_cfs_rq(struct cfs_rq *cfs_rq)
  8197. {
  8198. cfs_rq->tasks_timeline = RB_ROOT_CACHED;
  8199. cfs_rq->min_vruntime = (u64)(-(1LL << 20));
  8200. #ifndef CONFIG_64BIT
  8201. cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
  8202. #endif
  8203. #ifdef CONFIG_SMP
  8204. raw_spin_lock_init(&cfs_rq->removed.lock);
  8205. #endif
  8206. }
  8207. #ifdef CONFIG_FAIR_GROUP_SCHED
  8208. static void task_set_group_fair(struct task_struct *p)
  8209. {
  8210. struct sched_entity *se = &p->se;
  8211. set_task_rq(p, task_cpu(p));
  8212. se->depth = se->parent ? se->parent->depth + 1 : 0;
  8213. }
  8214. static void task_move_group_fair(struct task_struct *p)
  8215. {
  8216. detach_task_cfs_rq(p);
  8217. set_task_rq(p, task_cpu(p));
  8218. #ifdef CONFIG_SMP
  8219. /* Tell se's cfs_rq has been changed -- migrated */
  8220. p->se.avg.last_update_time = 0;
  8221. #endif
  8222. attach_task_cfs_rq(p);
  8223. }
  8224. static void task_change_group_fair(struct task_struct *p, int type)
  8225. {
  8226. switch (type) {
  8227. case TASK_SET_GROUP:
  8228. task_set_group_fair(p);
  8229. break;
  8230. case TASK_MOVE_GROUP:
  8231. task_move_group_fair(p);
  8232. break;
  8233. }
  8234. }
  8235. void free_fair_sched_group(struct task_group *tg)
  8236. {
  8237. int i;
  8238. destroy_cfs_bandwidth(tg_cfs_bandwidth(tg));
  8239. for_each_possible_cpu(i) {
  8240. if (tg->cfs_rq)
  8241. kfree(tg->cfs_rq[i]);
  8242. if (tg->se)
  8243. kfree(tg->se[i]);
  8244. }
  8245. kfree(tg->cfs_rq);
  8246. kfree(tg->se);
  8247. }
  8248. int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
  8249. {
  8250. struct sched_entity *se;
  8251. struct cfs_rq *cfs_rq;
  8252. int i;
  8253. tg->cfs_rq = kcalloc(nr_cpu_ids, sizeof(cfs_rq), GFP_KERNEL);
  8254. if (!tg->cfs_rq)
  8255. goto err;
  8256. tg->se = kcalloc(nr_cpu_ids, sizeof(se), GFP_KERNEL);
  8257. if (!tg->se)
  8258. goto err;
  8259. tg->shares = NICE_0_LOAD;
  8260. init_cfs_bandwidth(tg_cfs_bandwidth(tg));
  8261. for_each_possible_cpu(i) {
  8262. cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
  8263. GFP_KERNEL, cpu_to_node(i));
  8264. if (!cfs_rq)
  8265. goto err;
  8266. se = kzalloc_node(sizeof(struct sched_entity),
  8267. GFP_KERNEL, cpu_to_node(i));
  8268. if (!se)
  8269. goto err_free_rq;
  8270. init_cfs_rq(cfs_rq);
  8271. init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
  8272. init_entity_runnable_average(se);
  8273. }
  8274. return 1;
  8275. err_free_rq:
  8276. kfree(cfs_rq);
  8277. err:
  8278. return 0;
  8279. }
  8280. void online_fair_sched_group(struct task_group *tg)
  8281. {
  8282. struct sched_entity *se;
  8283. struct rq *rq;
  8284. int i;
  8285. for_each_possible_cpu(i) {
  8286. rq = cpu_rq(i);
  8287. se = tg->se[i];
  8288. raw_spin_lock_irq(&rq->lock);
  8289. update_rq_clock(rq);
  8290. attach_entity_cfs_rq(se);
  8291. sync_throttle(tg, i);
  8292. raw_spin_unlock_irq(&rq->lock);
  8293. }
  8294. }
  8295. void unregister_fair_sched_group(struct task_group *tg)
  8296. {
  8297. unsigned long flags;
  8298. struct rq *rq;
  8299. int cpu;
  8300. for_each_possible_cpu(cpu) {
  8301. if (tg->se[cpu])
  8302. remove_entity_load_avg(tg->se[cpu]);
  8303. /*
  8304. * Only empty task groups can be destroyed; so we can speculatively
  8305. * check on_list without danger of it being re-added.
  8306. */
  8307. if (!tg->cfs_rq[cpu]->on_list)
  8308. continue;
  8309. rq = cpu_rq(cpu);
  8310. raw_spin_lock_irqsave(&rq->lock, flags);
  8311. list_del_leaf_cfs_rq(tg->cfs_rq[cpu]);
  8312. raw_spin_unlock_irqrestore(&rq->lock, flags);
  8313. }
  8314. }
  8315. void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
  8316. struct sched_entity *se, int cpu,
  8317. struct sched_entity *parent)
  8318. {
  8319. struct rq *rq = cpu_rq(cpu);
  8320. cfs_rq->tg = tg;
  8321. cfs_rq->rq = rq;
  8322. init_cfs_rq_runtime(cfs_rq);
  8323. tg->cfs_rq[cpu] = cfs_rq;
  8324. tg->se[cpu] = se;
  8325. /* se could be NULL for root_task_group */
  8326. if (!se)
  8327. return;
  8328. if (!parent) {
  8329. se->cfs_rq = &rq->cfs;
  8330. se->depth = 0;
  8331. } else {
  8332. se->cfs_rq = parent->my_q;
  8333. se->depth = parent->depth + 1;
  8334. }
  8335. se->my_q = cfs_rq;
  8336. /* guarantee group entities always have weight */
  8337. update_load_set(&se->load, NICE_0_LOAD);
  8338. se->parent = parent;
  8339. }
  8340. static DEFINE_MUTEX(shares_mutex);
  8341. int sched_group_set_shares(struct task_group *tg, unsigned long shares)
  8342. {
  8343. int i;
  8344. /*
  8345. * We can't change the weight of the root cgroup.
  8346. */
  8347. if (!tg->se[0])
  8348. return -EINVAL;
  8349. shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
  8350. mutex_lock(&shares_mutex);
  8351. if (tg->shares == shares)
  8352. goto done;
  8353. tg->shares = shares;
  8354. for_each_possible_cpu(i) {
  8355. struct rq *rq = cpu_rq(i);
  8356. struct sched_entity *se = tg->se[i];
  8357. struct rq_flags rf;
  8358. /* Propagate contribution to hierarchy */
  8359. rq_lock_irqsave(rq, &rf);
  8360. update_rq_clock(rq);
  8361. for_each_sched_entity(se) {
  8362. update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
  8363. update_cfs_group(se);
  8364. }
  8365. rq_unlock_irqrestore(rq, &rf);
  8366. }
  8367. done:
  8368. mutex_unlock(&shares_mutex);
  8369. return 0;
  8370. }
  8371. #else /* CONFIG_FAIR_GROUP_SCHED */
  8372. void free_fair_sched_group(struct task_group *tg) { }
  8373. int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
  8374. {
  8375. return 1;
  8376. }
  8377. void online_fair_sched_group(struct task_group *tg) { }
  8378. void unregister_fair_sched_group(struct task_group *tg) { }
  8379. #endif /* CONFIG_FAIR_GROUP_SCHED */
  8380. static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task)
  8381. {
  8382. struct sched_entity *se = &task->se;
  8383. unsigned int rr_interval = 0;
  8384. /*
  8385. * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
  8386. * idle runqueue:
  8387. */
  8388. if (rq->cfs.load.weight)
  8389. rr_interval = NS_TO_JIFFIES(sched_slice(cfs_rq_of(se), se));
  8390. return rr_interval;
  8391. }
  8392. /*
  8393. * All the scheduling class methods:
  8394. */
  8395. const struct sched_class fair_sched_class = {
  8396. .next = &idle_sched_class,
  8397. .enqueue_task = enqueue_task_fair,
  8398. .dequeue_task = dequeue_task_fair,
  8399. .yield_task = yield_task_fair,
  8400. .yield_to_task = yield_to_task_fair,
  8401. .check_preempt_curr = check_preempt_wakeup,
  8402. .pick_next_task = pick_next_task_fair,
  8403. .put_prev_task = put_prev_task_fair,
  8404. #ifdef CONFIG_SMP
  8405. .select_task_rq = select_task_rq_fair,
  8406. .migrate_task_rq = migrate_task_rq_fair,
  8407. .rq_online = rq_online_fair,
  8408. .rq_offline = rq_offline_fair,
  8409. .task_dead = task_dead_fair,
  8410. .set_cpus_allowed = set_cpus_allowed_common,
  8411. #endif
  8412. .set_curr_task = set_curr_task_fair,
  8413. .task_tick = task_tick_fair,
  8414. .task_fork = task_fork_fair,
  8415. .prio_changed = prio_changed_fair,
  8416. .switched_from = switched_from_fair,
  8417. .switched_to = switched_to_fair,
  8418. .get_rr_interval = get_rr_interval_fair,
  8419. .update_curr = update_curr_fair,
  8420. #ifdef CONFIG_FAIR_GROUP_SCHED
  8421. .task_change_group = task_change_group_fair,
  8422. #endif
  8423. };
  8424. #ifdef CONFIG_SCHED_DEBUG
  8425. void print_cfs_stats(struct seq_file *m, int cpu)
  8426. {
  8427. struct cfs_rq *cfs_rq, *pos;
  8428. rcu_read_lock();
  8429. for_each_leaf_cfs_rq_safe(cpu_rq(cpu), cfs_rq, pos)
  8430. print_cfs_rq(m, cpu, cfs_rq);
  8431. rcu_read_unlock();
  8432. }
  8433. #ifdef CONFIG_NUMA_BALANCING
  8434. void show_numa_stats(struct task_struct *p, struct seq_file *m)
  8435. {
  8436. int node;
  8437. unsigned long tsf = 0, tpf = 0, gsf = 0, gpf = 0;
  8438. for_each_online_node(node) {
  8439. if (p->numa_faults) {
  8440. tsf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 0)];
  8441. tpf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 1)];
  8442. }
  8443. if (p->numa_group) {
  8444. gsf = p->numa_group->faults[task_faults_idx(NUMA_MEM, node, 0)],
  8445. gpf = p->numa_group->faults[task_faults_idx(NUMA_MEM, node, 1)];
  8446. }
  8447. print_numa_stats(m, node, tsf, tpf, gsf, gpf);
  8448. }
  8449. }
  8450. #endif /* CONFIG_NUMA_BALANCING */
  8451. #endif /* CONFIG_SCHED_DEBUG */
  8452. __init void init_sched_fair_class(void)
  8453. {
  8454. #ifdef CONFIG_SMP
  8455. open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
  8456. #ifdef CONFIG_NO_HZ_COMMON
  8457. nohz.next_balance = jiffies;
  8458. nohz.next_blocked = jiffies;
  8459. zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);
  8460. #endif
  8461. #endif /* SMP */
  8462. }