fair.c 217 KB

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