fair.c 237 KB

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