fair.c 224 KB

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