fair.c 177 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897
  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/slab.h>
  26. #include <linux/profile.h>
  27. #include <linux/interrupt.h>
  28. #include <linux/mempolicy.h>
  29. #include <linux/migrate.h>
  30. #include <linux/task_work.h>
  31. #include <trace/events/sched.h>
  32. #include "sched.h"
  33. /*
  34. * Targeted preemption latency for CPU-bound tasks:
  35. * (default: 6ms * (1 + ilog(ncpus)), units: nanoseconds)
  36. *
  37. * NOTE: this latency value is not the same as the concept of
  38. * 'timeslice length' - timeslices in CFS are of variable length
  39. * and have no persistent notion like in traditional, time-slice
  40. * based scheduling concepts.
  41. *
  42. * (to see the precise effective timeslice length of your workload,
  43. * run vmstat and monitor the context-switches (cs) field)
  44. */
  45. unsigned int sysctl_sched_latency = 6000000ULL;
  46. unsigned int normalized_sysctl_sched_latency = 6000000ULL;
  47. /*
  48. * The initial- and re-scaling of tunables is configurable
  49. * (default SCHED_TUNABLESCALING_LOG = *(1+ilog(ncpus))
  50. *
  51. * Options are:
  52. * SCHED_TUNABLESCALING_NONE - unscaled, always *1
  53. * SCHED_TUNABLESCALING_LOG - scaled logarithmical, *1+ilog(ncpus)
  54. * SCHED_TUNABLESCALING_LINEAR - scaled linear, *ncpus
  55. */
  56. enum sched_tunable_scaling sysctl_sched_tunable_scaling
  57. = SCHED_TUNABLESCALING_LOG;
  58. /*
  59. * Minimal preemption granularity for CPU-bound tasks:
  60. * (default: 0.75 msec * (1 + ilog(ncpus)), units: nanoseconds)
  61. */
  62. unsigned int sysctl_sched_min_granularity = 750000ULL;
  63. unsigned int normalized_sysctl_sched_min_granularity = 750000ULL;
  64. /*
  65. * is kept at sysctl_sched_latency / sysctl_sched_min_granularity
  66. */
  67. static unsigned int sched_nr_latency = 8;
  68. /*
  69. * After fork, child runs first. If set to 0 (default) then
  70. * parent will (try to) run first.
  71. */
  72. unsigned int sysctl_sched_child_runs_first __read_mostly;
  73. /*
  74. * SCHED_OTHER wake-up granularity.
  75. * (default: 1 msec * (1 + ilog(ncpus)), units: nanoseconds)
  76. *
  77. * This option delays the preemption effects of decoupled workloads
  78. * and reduces their over-scheduling. Synchronous workloads will still
  79. * have immediate wakeup/sleep latencies.
  80. */
  81. unsigned int sysctl_sched_wakeup_granularity = 1000000UL;
  82. unsigned int normalized_sysctl_sched_wakeup_granularity = 1000000UL;
  83. const_debug unsigned int sysctl_sched_migration_cost = 500000UL;
  84. /*
  85. * The exponential sliding window over which load is averaged for shares
  86. * distribution.
  87. * (default: 10msec)
  88. */
  89. unsigned int __read_mostly sysctl_sched_shares_window = 10000000UL;
  90. #ifdef CONFIG_CFS_BANDWIDTH
  91. /*
  92. * Amount of runtime to allocate from global (tg) to local (per-cfs_rq) pool
  93. * each time a cfs_rq requests quota.
  94. *
  95. * Note: in the case that the slice exceeds the runtime remaining (either due
  96. * to consumption or the quota being specified to be smaller than the slice)
  97. * we will always only issue the remaining available time.
  98. *
  99. * default: 5 msec, units: microseconds
  100. */
  101. unsigned int sysctl_sched_cfs_bandwidth_slice = 5000UL;
  102. #endif
  103. static inline void update_load_add(struct load_weight *lw, unsigned long inc)
  104. {
  105. lw->weight += inc;
  106. lw->inv_weight = 0;
  107. }
  108. static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
  109. {
  110. lw->weight -= dec;
  111. lw->inv_weight = 0;
  112. }
  113. static inline void update_load_set(struct load_weight *lw, unsigned long w)
  114. {
  115. lw->weight = w;
  116. lw->inv_weight = 0;
  117. }
  118. /*
  119. * Increase the granularity value when there are more CPUs,
  120. * because with more CPUs the 'effective latency' as visible
  121. * to users decreases. But the relationship is not linear,
  122. * so pick a second-best guess by going with the log2 of the
  123. * number of CPUs.
  124. *
  125. * This idea comes from the SD scheduler of Con Kolivas:
  126. */
  127. static int get_update_sysctl_factor(void)
  128. {
  129. unsigned int cpus = min_t(int, num_online_cpus(), 8);
  130. unsigned int factor;
  131. switch (sysctl_sched_tunable_scaling) {
  132. case SCHED_TUNABLESCALING_NONE:
  133. factor = 1;
  134. break;
  135. case SCHED_TUNABLESCALING_LINEAR:
  136. factor = cpus;
  137. break;
  138. case SCHED_TUNABLESCALING_LOG:
  139. default:
  140. factor = 1 + ilog2(cpus);
  141. break;
  142. }
  143. return factor;
  144. }
  145. static void update_sysctl(void)
  146. {
  147. unsigned int factor = get_update_sysctl_factor();
  148. #define SET_SYSCTL(name) \
  149. (sysctl_##name = (factor) * normalized_sysctl_##name)
  150. SET_SYSCTL(sched_min_granularity);
  151. SET_SYSCTL(sched_latency);
  152. SET_SYSCTL(sched_wakeup_granularity);
  153. #undef SET_SYSCTL
  154. }
  155. void sched_init_granularity(void)
  156. {
  157. update_sysctl();
  158. }
  159. #if BITS_PER_LONG == 32
  160. # define WMULT_CONST (~0UL)
  161. #else
  162. # define WMULT_CONST (1UL << 32)
  163. #endif
  164. #define WMULT_SHIFT 32
  165. /*
  166. * Shift right and round:
  167. */
  168. #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
  169. /*
  170. * delta *= weight / lw
  171. */
  172. static unsigned long
  173. calc_delta_mine(unsigned long delta_exec, unsigned long weight,
  174. struct load_weight *lw)
  175. {
  176. u64 tmp;
  177. /*
  178. * weight can be less than 2^SCHED_LOAD_RESOLUTION for task group sched
  179. * entities since MIN_SHARES = 2. Treat weight as 1 if less than
  180. * 2^SCHED_LOAD_RESOLUTION.
  181. */
  182. if (likely(weight > (1UL << SCHED_LOAD_RESOLUTION)))
  183. tmp = (u64)delta_exec * scale_load_down(weight);
  184. else
  185. tmp = (u64)delta_exec;
  186. if (!lw->inv_weight) {
  187. unsigned long w = scale_load_down(lw->weight);
  188. if (BITS_PER_LONG > 32 && unlikely(w >= WMULT_CONST))
  189. lw->inv_weight = 1;
  190. else if (unlikely(!w))
  191. lw->inv_weight = WMULT_CONST;
  192. else
  193. lw->inv_weight = WMULT_CONST / w;
  194. }
  195. /*
  196. * Check whether we'd overflow the 64-bit multiplication:
  197. */
  198. if (unlikely(tmp > WMULT_CONST))
  199. tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
  200. WMULT_SHIFT/2);
  201. else
  202. tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);
  203. return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);
  204. }
  205. const struct sched_class fair_sched_class;
  206. /**************************************************************
  207. * CFS operations on generic schedulable entities:
  208. */
  209. #ifdef CONFIG_FAIR_GROUP_SCHED
  210. /* cpu runqueue to which this cfs_rq is attached */
  211. static inline struct rq *rq_of(struct cfs_rq *cfs_rq)
  212. {
  213. return cfs_rq->rq;
  214. }
  215. /* An entity is a task if it doesn't "own" a runqueue */
  216. #define entity_is_task(se) (!se->my_q)
  217. static inline struct task_struct *task_of(struct sched_entity *se)
  218. {
  219. #ifdef CONFIG_SCHED_DEBUG
  220. WARN_ON_ONCE(!entity_is_task(se));
  221. #endif
  222. return container_of(se, struct task_struct, se);
  223. }
  224. /* Walk up scheduling entities hierarchy */
  225. #define for_each_sched_entity(se) \
  226. for (; se; se = se->parent)
  227. static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
  228. {
  229. return p->se.cfs_rq;
  230. }
  231. /* runqueue on which this entity is (to be) queued */
  232. static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se)
  233. {
  234. return se->cfs_rq;
  235. }
  236. /* runqueue "owned" by this group */
  237. static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
  238. {
  239. return grp->my_q;
  240. }
  241. static void update_cfs_rq_blocked_load(struct cfs_rq *cfs_rq,
  242. int force_update);
  243. static inline void list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
  244. {
  245. if (!cfs_rq->on_list) {
  246. /*
  247. * Ensure we either appear before our parent (if already
  248. * enqueued) or force our parent to appear after us when it is
  249. * enqueued. The fact that we always enqueue bottom-up
  250. * reduces this to two cases.
  251. */
  252. if (cfs_rq->tg->parent &&
  253. cfs_rq->tg->parent->cfs_rq[cpu_of(rq_of(cfs_rq))]->on_list) {
  254. list_add_rcu(&cfs_rq->leaf_cfs_rq_list,
  255. &rq_of(cfs_rq)->leaf_cfs_rq_list);
  256. } else {
  257. list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
  258. &rq_of(cfs_rq)->leaf_cfs_rq_list);
  259. }
  260. cfs_rq->on_list = 1;
  261. /* We should have no load, but we need to update last_decay. */
  262. update_cfs_rq_blocked_load(cfs_rq, 0);
  263. }
  264. }
  265. static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
  266. {
  267. if (cfs_rq->on_list) {
  268. list_del_rcu(&cfs_rq->leaf_cfs_rq_list);
  269. cfs_rq->on_list = 0;
  270. }
  271. }
  272. /* Iterate thr' all leaf cfs_rq's on a runqueue */
  273. #define for_each_leaf_cfs_rq(rq, cfs_rq) \
  274. list_for_each_entry_rcu(cfs_rq, &rq->leaf_cfs_rq_list, leaf_cfs_rq_list)
  275. /* Do the two (enqueued) entities belong to the same group ? */
  276. static inline int
  277. is_same_group(struct sched_entity *se, struct sched_entity *pse)
  278. {
  279. if (se->cfs_rq == pse->cfs_rq)
  280. return 1;
  281. return 0;
  282. }
  283. static inline struct sched_entity *parent_entity(struct sched_entity *se)
  284. {
  285. return se->parent;
  286. }
  287. /* return depth at which a sched entity is present in the hierarchy */
  288. static inline int depth_se(struct sched_entity *se)
  289. {
  290. int depth = 0;
  291. for_each_sched_entity(se)
  292. depth++;
  293. return depth;
  294. }
  295. static void
  296. find_matching_se(struct sched_entity **se, struct sched_entity **pse)
  297. {
  298. int se_depth, pse_depth;
  299. /*
  300. * preemption test can be made between sibling entities who are in the
  301. * same cfs_rq i.e who have a common parent. Walk up the hierarchy of
  302. * both tasks until we find their ancestors who are siblings of common
  303. * parent.
  304. */
  305. /* First walk up until both entities are at same depth */
  306. se_depth = depth_se(*se);
  307. pse_depth = depth_se(*pse);
  308. while (se_depth > pse_depth) {
  309. se_depth--;
  310. *se = parent_entity(*se);
  311. }
  312. while (pse_depth > se_depth) {
  313. pse_depth--;
  314. *pse = parent_entity(*pse);
  315. }
  316. while (!is_same_group(*se, *pse)) {
  317. *se = parent_entity(*se);
  318. *pse = parent_entity(*pse);
  319. }
  320. }
  321. #else /* !CONFIG_FAIR_GROUP_SCHED */
  322. static inline struct task_struct *task_of(struct sched_entity *se)
  323. {
  324. return container_of(se, struct task_struct, se);
  325. }
  326. static inline struct rq *rq_of(struct cfs_rq *cfs_rq)
  327. {
  328. return container_of(cfs_rq, struct rq, cfs);
  329. }
  330. #define entity_is_task(se) 1
  331. #define for_each_sched_entity(se) \
  332. for (; se; se = NULL)
  333. static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
  334. {
  335. return &task_rq(p)->cfs;
  336. }
  337. static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se)
  338. {
  339. struct task_struct *p = task_of(se);
  340. struct rq *rq = task_rq(p);
  341. return &rq->cfs;
  342. }
  343. /* runqueue "owned" by this group */
  344. static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
  345. {
  346. return NULL;
  347. }
  348. static inline void list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
  349. {
  350. }
  351. static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
  352. {
  353. }
  354. #define for_each_leaf_cfs_rq(rq, cfs_rq) \
  355. for (cfs_rq = &rq->cfs; cfs_rq; cfs_rq = NULL)
  356. static inline int
  357. is_same_group(struct sched_entity *se, struct sched_entity *pse)
  358. {
  359. return 1;
  360. }
  361. static inline struct sched_entity *parent_entity(struct sched_entity *se)
  362. {
  363. return NULL;
  364. }
  365. static inline void
  366. find_matching_se(struct sched_entity **se, struct sched_entity **pse)
  367. {
  368. }
  369. #endif /* CONFIG_FAIR_GROUP_SCHED */
  370. static __always_inline
  371. void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, unsigned long delta_exec);
  372. /**************************************************************
  373. * Scheduling class tree data structure manipulation methods:
  374. */
  375. static inline u64 max_vruntime(u64 max_vruntime, u64 vruntime)
  376. {
  377. s64 delta = (s64)(vruntime - max_vruntime);
  378. if (delta > 0)
  379. max_vruntime = vruntime;
  380. return max_vruntime;
  381. }
  382. static inline u64 min_vruntime(u64 min_vruntime, u64 vruntime)
  383. {
  384. s64 delta = (s64)(vruntime - min_vruntime);
  385. if (delta < 0)
  386. min_vruntime = vruntime;
  387. return min_vruntime;
  388. }
  389. static inline int entity_before(struct sched_entity *a,
  390. struct sched_entity *b)
  391. {
  392. return (s64)(a->vruntime - b->vruntime) < 0;
  393. }
  394. static void update_min_vruntime(struct cfs_rq *cfs_rq)
  395. {
  396. u64 vruntime = cfs_rq->min_vruntime;
  397. if (cfs_rq->curr)
  398. vruntime = cfs_rq->curr->vruntime;
  399. if (cfs_rq->rb_leftmost) {
  400. struct sched_entity *se = rb_entry(cfs_rq->rb_leftmost,
  401. struct sched_entity,
  402. run_node);
  403. if (!cfs_rq->curr)
  404. vruntime = se->vruntime;
  405. else
  406. vruntime = min_vruntime(vruntime, se->vruntime);
  407. }
  408. /* ensure we never gain time by being placed backwards. */
  409. cfs_rq->min_vruntime = max_vruntime(cfs_rq->min_vruntime, vruntime);
  410. #ifndef CONFIG_64BIT
  411. smp_wmb();
  412. cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
  413. #endif
  414. }
  415. /*
  416. * Enqueue an entity into the rb-tree:
  417. */
  418. static void __enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
  419. {
  420. struct rb_node **link = &cfs_rq->tasks_timeline.rb_node;
  421. struct rb_node *parent = NULL;
  422. struct sched_entity *entry;
  423. int leftmost = 1;
  424. /*
  425. * Find the right place in the rbtree:
  426. */
  427. while (*link) {
  428. parent = *link;
  429. entry = rb_entry(parent, struct sched_entity, run_node);
  430. /*
  431. * We dont care about collisions. Nodes with
  432. * the same key stay together.
  433. */
  434. if (entity_before(se, entry)) {
  435. link = &parent->rb_left;
  436. } else {
  437. link = &parent->rb_right;
  438. leftmost = 0;
  439. }
  440. }
  441. /*
  442. * Maintain a cache of leftmost tree entries (it is frequently
  443. * used):
  444. */
  445. if (leftmost)
  446. cfs_rq->rb_leftmost = &se->run_node;
  447. rb_link_node(&se->run_node, parent, link);
  448. rb_insert_color(&se->run_node, &cfs_rq->tasks_timeline);
  449. }
  450. static void __dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
  451. {
  452. if (cfs_rq->rb_leftmost == &se->run_node) {
  453. struct rb_node *next_node;
  454. next_node = rb_next(&se->run_node);
  455. cfs_rq->rb_leftmost = next_node;
  456. }
  457. rb_erase(&se->run_node, &cfs_rq->tasks_timeline);
  458. }
  459. struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq)
  460. {
  461. struct rb_node *left = cfs_rq->rb_leftmost;
  462. if (!left)
  463. return NULL;
  464. return rb_entry(left, struct sched_entity, run_node);
  465. }
  466. static struct sched_entity *__pick_next_entity(struct sched_entity *se)
  467. {
  468. struct rb_node *next = rb_next(&se->run_node);
  469. if (!next)
  470. return NULL;
  471. return rb_entry(next, struct sched_entity, run_node);
  472. }
  473. #ifdef CONFIG_SCHED_DEBUG
  474. struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq)
  475. {
  476. struct rb_node *last = rb_last(&cfs_rq->tasks_timeline);
  477. if (!last)
  478. return NULL;
  479. return rb_entry(last, struct sched_entity, run_node);
  480. }
  481. /**************************************************************
  482. * Scheduling class statistics methods:
  483. */
  484. int sched_proc_update_handler(struct ctl_table *table, int write,
  485. void __user *buffer, size_t *lenp,
  486. loff_t *ppos)
  487. {
  488. int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
  489. int factor = get_update_sysctl_factor();
  490. if (ret || !write)
  491. return ret;
  492. sched_nr_latency = DIV_ROUND_UP(sysctl_sched_latency,
  493. sysctl_sched_min_granularity);
  494. #define WRT_SYSCTL(name) \
  495. (normalized_sysctl_##name = sysctl_##name / (factor))
  496. WRT_SYSCTL(sched_min_granularity);
  497. WRT_SYSCTL(sched_latency);
  498. WRT_SYSCTL(sched_wakeup_granularity);
  499. #undef WRT_SYSCTL
  500. return 0;
  501. }
  502. #endif
  503. /*
  504. * delta /= w
  505. */
  506. static inline unsigned long
  507. calc_delta_fair(unsigned long delta, struct sched_entity *se)
  508. {
  509. if (unlikely(se->load.weight != NICE_0_LOAD))
  510. delta = calc_delta_mine(delta, NICE_0_LOAD, &se->load);
  511. return delta;
  512. }
  513. /*
  514. * The idea is to set a period in which each task runs once.
  515. *
  516. * When there are too many tasks (sched_nr_latency) we have to stretch
  517. * this period because otherwise the slices get too small.
  518. *
  519. * p = (nr <= nl) ? l : l*nr/nl
  520. */
  521. static u64 __sched_period(unsigned long nr_running)
  522. {
  523. u64 period = sysctl_sched_latency;
  524. unsigned long nr_latency = sched_nr_latency;
  525. if (unlikely(nr_running > nr_latency)) {
  526. period = sysctl_sched_min_granularity;
  527. period *= nr_running;
  528. }
  529. return period;
  530. }
  531. /*
  532. * We calculate the wall-time slice from the period by taking a part
  533. * proportional to the weight.
  534. *
  535. * s = p*P[w/rw]
  536. */
  537. static u64 sched_slice(struct cfs_rq *cfs_rq, struct sched_entity *se)
  538. {
  539. u64 slice = __sched_period(cfs_rq->nr_running + !se->on_rq);
  540. for_each_sched_entity(se) {
  541. struct load_weight *load;
  542. struct load_weight lw;
  543. cfs_rq = cfs_rq_of(se);
  544. load = &cfs_rq->load;
  545. if (unlikely(!se->on_rq)) {
  546. lw = cfs_rq->load;
  547. update_load_add(&lw, se->load.weight);
  548. load = &lw;
  549. }
  550. slice = calc_delta_mine(slice, se->load.weight, load);
  551. }
  552. return slice;
  553. }
  554. /*
  555. * We calculate the vruntime slice of a to-be-inserted task.
  556. *
  557. * vs = s/w
  558. */
  559. static u64 sched_vslice(struct cfs_rq *cfs_rq, struct sched_entity *se)
  560. {
  561. return calc_delta_fair(sched_slice(cfs_rq, se), se);
  562. }
  563. #ifdef CONFIG_SMP
  564. static unsigned long task_h_load(struct task_struct *p);
  565. static inline void __update_task_entity_contrib(struct sched_entity *se);
  566. /* Give new task start runnable values to heavy its load in infant time */
  567. void init_task_runnable_average(struct task_struct *p)
  568. {
  569. u32 slice;
  570. p->se.avg.decay_count = 0;
  571. slice = sched_slice(task_cfs_rq(p), &p->se) >> 10;
  572. p->se.avg.runnable_avg_sum = slice;
  573. p->se.avg.runnable_avg_period = slice;
  574. __update_task_entity_contrib(&p->se);
  575. }
  576. #else
  577. void init_task_runnable_average(struct task_struct *p)
  578. {
  579. }
  580. #endif
  581. /*
  582. * Update the current task's runtime statistics. Skip current tasks that
  583. * are not in our scheduling class.
  584. */
  585. static inline void
  586. __update_curr(struct cfs_rq *cfs_rq, struct sched_entity *curr,
  587. unsigned long delta_exec)
  588. {
  589. unsigned long delta_exec_weighted;
  590. schedstat_set(curr->statistics.exec_max,
  591. max((u64)delta_exec, curr->statistics.exec_max));
  592. curr->sum_exec_runtime += delta_exec;
  593. schedstat_add(cfs_rq, exec_clock, delta_exec);
  594. delta_exec_weighted = calc_delta_fair(delta_exec, curr);
  595. curr->vruntime += delta_exec_weighted;
  596. update_min_vruntime(cfs_rq);
  597. }
  598. static void update_curr(struct cfs_rq *cfs_rq)
  599. {
  600. struct sched_entity *curr = cfs_rq->curr;
  601. u64 now = rq_clock_task(rq_of(cfs_rq));
  602. unsigned long delta_exec;
  603. if (unlikely(!curr))
  604. return;
  605. /*
  606. * Get the amount of time the current task was running
  607. * since the last time we changed load (this cannot
  608. * overflow on 32 bits):
  609. */
  610. delta_exec = (unsigned long)(now - curr->exec_start);
  611. if (!delta_exec)
  612. return;
  613. __update_curr(cfs_rq, curr, delta_exec);
  614. curr->exec_start = now;
  615. if (entity_is_task(curr)) {
  616. struct task_struct *curtask = task_of(curr);
  617. trace_sched_stat_runtime(curtask, delta_exec, curr->vruntime);
  618. cpuacct_charge(curtask, delta_exec);
  619. account_group_exec_runtime(curtask, delta_exec);
  620. }
  621. account_cfs_rq_runtime(cfs_rq, delta_exec);
  622. }
  623. static inline void
  624. update_stats_wait_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
  625. {
  626. schedstat_set(se->statistics.wait_start, rq_clock(rq_of(cfs_rq)));
  627. }
  628. /*
  629. * Task is being enqueued - update stats:
  630. */
  631. static void update_stats_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
  632. {
  633. /*
  634. * Are we enqueueing a waiting task? (for current tasks
  635. * a dequeue/enqueue event is a NOP)
  636. */
  637. if (se != cfs_rq->curr)
  638. update_stats_wait_start(cfs_rq, se);
  639. }
  640. static void
  641. update_stats_wait_end(struct cfs_rq *cfs_rq, struct sched_entity *se)
  642. {
  643. schedstat_set(se->statistics.wait_max, max(se->statistics.wait_max,
  644. rq_clock(rq_of(cfs_rq)) - se->statistics.wait_start));
  645. schedstat_set(se->statistics.wait_count, se->statistics.wait_count + 1);
  646. schedstat_set(se->statistics.wait_sum, se->statistics.wait_sum +
  647. rq_clock(rq_of(cfs_rq)) - se->statistics.wait_start);
  648. #ifdef CONFIG_SCHEDSTATS
  649. if (entity_is_task(se)) {
  650. trace_sched_stat_wait(task_of(se),
  651. rq_clock(rq_of(cfs_rq)) - se->statistics.wait_start);
  652. }
  653. #endif
  654. schedstat_set(se->statistics.wait_start, 0);
  655. }
  656. static inline void
  657. update_stats_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
  658. {
  659. /*
  660. * Mark the end of the wait period if dequeueing a
  661. * waiting task:
  662. */
  663. if (se != cfs_rq->curr)
  664. update_stats_wait_end(cfs_rq, se);
  665. }
  666. /*
  667. * We are picking a new current task - update its stats:
  668. */
  669. static inline void
  670. update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
  671. {
  672. /*
  673. * We are starting a new run period:
  674. */
  675. se->exec_start = rq_clock_task(rq_of(cfs_rq));
  676. }
  677. /**************************************************
  678. * Scheduling class queueing methods:
  679. */
  680. #ifdef CONFIG_NUMA_BALANCING
  681. /*
  682. * Approximate time to scan a full NUMA task in ms. The task scan period is
  683. * calculated based on the tasks virtual memory size and
  684. * numa_balancing_scan_size.
  685. */
  686. unsigned int sysctl_numa_balancing_scan_period_min = 1000;
  687. unsigned int sysctl_numa_balancing_scan_period_max = 60000;
  688. unsigned int sysctl_numa_balancing_scan_period_reset = 60000;
  689. /* Portion of address space to scan in MB */
  690. unsigned int sysctl_numa_balancing_scan_size = 256;
  691. /* Scan @scan_size MB every @scan_period after an initial @scan_delay in ms */
  692. unsigned int sysctl_numa_balancing_scan_delay = 1000;
  693. static unsigned int task_nr_scan_windows(struct task_struct *p)
  694. {
  695. unsigned long rss = 0;
  696. unsigned long nr_scan_pages;
  697. /*
  698. * Calculations based on RSS as non-present and empty pages are skipped
  699. * by the PTE scanner and NUMA hinting faults should be trapped based
  700. * on resident pages
  701. */
  702. nr_scan_pages = sysctl_numa_balancing_scan_size << (20 - PAGE_SHIFT);
  703. rss = get_mm_rss(p->mm);
  704. if (!rss)
  705. rss = nr_scan_pages;
  706. rss = round_up(rss, nr_scan_pages);
  707. return rss / nr_scan_pages;
  708. }
  709. /* For sanitys sake, never scan more PTEs than MAX_SCAN_WINDOW MB/sec. */
  710. #define MAX_SCAN_WINDOW 2560
  711. static unsigned int task_scan_min(struct task_struct *p)
  712. {
  713. unsigned int scan, floor;
  714. unsigned int windows = 1;
  715. if (sysctl_numa_balancing_scan_size < MAX_SCAN_WINDOW)
  716. windows = MAX_SCAN_WINDOW / sysctl_numa_balancing_scan_size;
  717. floor = 1000 / windows;
  718. scan = sysctl_numa_balancing_scan_period_min / task_nr_scan_windows(p);
  719. return max_t(unsigned int, floor, scan);
  720. }
  721. static unsigned int task_scan_max(struct task_struct *p)
  722. {
  723. unsigned int smin = task_scan_min(p);
  724. unsigned int smax;
  725. /* Watch for min being lower than max due to floor calculations */
  726. smax = sysctl_numa_balancing_scan_period_max / task_nr_scan_windows(p);
  727. return max(smin, smax);
  728. }
  729. /*
  730. * Once a preferred node is selected the scheduler balancer will prefer moving
  731. * a task to that node for sysctl_numa_balancing_settle_count number of PTE
  732. * scans. This will give the process the chance to accumulate more faults on
  733. * the preferred node but still allow the scheduler to move the task again if
  734. * the nodes CPUs are overloaded.
  735. */
  736. unsigned int sysctl_numa_balancing_settle_count __read_mostly = 4;
  737. static inline int task_faults_idx(int nid, int priv)
  738. {
  739. return 2 * nid + priv;
  740. }
  741. static inline unsigned long task_faults(struct task_struct *p, int nid)
  742. {
  743. if (!p->numa_faults)
  744. return 0;
  745. return p->numa_faults[task_faults_idx(nid, 0)] +
  746. p->numa_faults[task_faults_idx(nid, 1)];
  747. }
  748. static unsigned long weighted_cpuload(const int cpu);
  749. static unsigned long source_load(int cpu, int type);
  750. static unsigned long target_load(int cpu, int type);
  751. static unsigned long power_of(int cpu);
  752. static long effective_load(struct task_group *tg, int cpu, long wl, long wg);
  753. /* Cached statistics for all CPUs within a node */
  754. struct numa_stats {
  755. unsigned long nr_running;
  756. unsigned long load;
  757. /* Total compute capacity of CPUs on a node */
  758. unsigned long power;
  759. /* Approximate capacity in terms of runnable tasks on a node */
  760. unsigned long capacity;
  761. int has_capacity;
  762. };
  763. /*
  764. * XXX borrowed from update_sg_lb_stats
  765. */
  766. static void update_numa_stats(struct numa_stats *ns, int nid)
  767. {
  768. int cpu;
  769. memset(ns, 0, sizeof(*ns));
  770. for_each_cpu(cpu, cpumask_of_node(nid)) {
  771. struct rq *rq = cpu_rq(cpu);
  772. ns->nr_running += rq->nr_running;
  773. ns->load += weighted_cpuload(cpu);
  774. ns->power += power_of(cpu);
  775. }
  776. ns->load = (ns->load * SCHED_POWER_SCALE) / ns->power;
  777. ns->capacity = DIV_ROUND_CLOSEST(ns->power, SCHED_POWER_SCALE);
  778. ns->has_capacity = (ns->nr_running < ns->capacity);
  779. }
  780. struct task_numa_env {
  781. struct task_struct *p;
  782. int src_cpu, src_nid;
  783. int dst_cpu, dst_nid;
  784. struct numa_stats src_stats, dst_stats;
  785. int imbalance_pct, idx;
  786. struct task_struct *best_task;
  787. long best_imp;
  788. int best_cpu;
  789. };
  790. static void task_numa_assign(struct task_numa_env *env,
  791. struct task_struct *p, long imp)
  792. {
  793. if (env->best_task)
  794. put_task_struct(env->best_task);
  795. if (p)
  796. get_task_struct(p);
  797. env->best_task = p;
  798. env->best_imp = imp;
  799. env->best_cpu = env->dst_cpu;
  800. }
  801. /*
  802. * This checks if the overall compute and NUMA accesses of the system would
  803. * be improved if the source tasks was migrated to the target dst_cpu taking
  804. * into account that it might be best if task running on the dst_cpu should
  805. * be exchanged with the source task
  806. */
  807. static void task_numa_compare(struct task_numa_env *env, long imp)
  808. {
  809. struct rq *src_rq = cpu_rq(env->src_cpu);
  810. struct rq *dst_rq = cpu_rq(env->dst_cpu);
  811. struct task_struct *cur;
  812. long dst_load, src_load;
  813. long load;
  814. rcu_read_lock();
  815. cur = ACCESS_ONCE(dst_rq->curr);
  816. if (cur->pid == 0) /* idle */
  817. cur = NULL;
  818. /*
  819. * "imp" is the fault differential for the source task between the
  820. * source and destination node. Calculate the total differential for
  821. * the source task and potential destination task. The more negative
  822. * the value is, the more rmeote accesses that would be expected to
  823. * be incurred if the tasks were swapped.
  824. */
  825. if (cur) {
  826. /* Skip this swap candidate if cannot move to the source cpu */
  827. if (!cpumask_test_cpu(env->src_cpu, tsk_cpus_allowed(cur)))
  828. goto unlock;
  829. imp += task_faults(cur, env->src_nid) -
  830. task_faults(cur, env->dst_nid);
  831. }
  832. if (imp < env->best_imp)
  833. goto unlock;
  834. if (!cur) {
  835. /* Is there capacity at our destination? */
  836. if (env->src_stats.has_capacity &&
  837. !env->dst_stats.has_capacity)
  838. goto unlock;
  839. goto balance;
  840. }
  841. /* Balance doesn't matter much if we're running a task per cpu */
  842. if (src_rq->nr_running == 1 && dst_rq->nr_running == 1)
  843. goto assign;
  844. /*
  845. * In the overloaded case, try and keep the load balanced.
  846. */
  847. balance:
  848. dst_load = env->dst_stats.load;
  849. src_load = env->src_stats.load;
  850. /* XXX missing power terms */
  851. load = task_h_load(env->p);
  852. dst_load += load;
  853. src_load -= load;
  854. if (cur) {
  855. load = task_h_load(cur);
  856. dst_load -= load;
  857. src_load += load;
  858. }
  859. /* make src_load the smaller */
  860. if (dst_load < src_load)
  861. swap(dst_load, src_load);
  862. if (src_load * env->imbalance_pct < dst_load * 100)
  863. goto unlock;
  864. assign:
  865. task_numa_assign(env, cur, imp);
  866. unlock:
  867. rcu_read_unlock();
  868. }
  869. static void task_numa_find_cpu(struct task_numa_env *env, long imp)
  870. {
  871. int cpu;
  872. for_each_cpu(cpu, cpumask_of_node(env->dst_nid)) {
  873. /* Skip this CPU if the source task cannot migrate */
  874. if (!cpumask_test_cpu(cpu, tsk_cpus_allowed(env->p)))
  875. continue;
  876. env->dst_cpu = cpu;
  877. task_numa_compare(env, imp);
  878. }
  879. }
  880. static int task_numa_migrate(struct task_struct *p)
  881. {
  882. struct task_numa_env env = {
  883. .p = p,
  884. .src_cpu = task_cpu(p),
  885. .src_nid = cpu_to_node(task_cpu(p)),
  886. .imbalance_pct = 112,
  887. .best_task = NULL,
  888. .best_imp = 0,
  889. .best_cpu = -1
  890. };
  891. struct sched_domain *sd;
  892. unsigned long faults;
  893. int nid, ret;
  894. long imp;
  895. /*
  896. * Pick the lowest SD_NUMA domain, as that would have the smallest
  897. * imbalance and would be the first to start moving tasks about.
  898. *
  899. * And we want to avoid any moving of tasks about, as that would create
  900. * random movement of tasks -- counter the numa conditions we're trying
  901. * to satisfy here.
  902. */
  903. rcu_read_lock();
  904. sd = rcu_dereference(per_cpu(sd_numa, env.src_cpu));
  905. env.imbalance_pct = 100 + (sd->imbalance_pct - 100) / 2;
  906. rcu_read_unlock();
  907. faults = task_faults(p, env.src_nid);
  908. update_numa_stats(&env.src_stats, env.src_nid);
  909. env.dst_nid = p->numa_preferred_nid;
  910. imp = task_faults(env.p, env.dst_nid) - faults;
  911. update_numa_stats(&env.dst_stats, env.dst_nid);
  912. /* If the preferred nid has capacity, try to use it. */
  913. if (env.dst_stats.has_capacity)
  914. task_numa_find_cpu(&env, imp);
  915. /* No space available on the preferred nid. Look elsewhere. */
  916. if (env.best_cpu == -1) {
  917. for_each_online_node(nid) {
  918. if (nid == env.src_nid || nid == p->numa_preferred_nid)
  919. continue;
  920. /* Only consider nodes that recorded more faults */
  921. imp = task_faults(env.p, nid) - faults;
  922. if (imp < 0)
  923. continue;
  924. env.dst_nid = nid;
  925. update_numa_stats(&env.dst_stats, env.dst_nid);
  926. task_numa_find_cpu(&env, imp);
  927. }
  928. }
  929. /* No better CPU than the current one was found. */
  930. if (env.best_cpu == -1)
  931. return -EAGAIN;
  932. if (env.best_task == NULL) {
  933. int ret = migrate_task_to(p, env.best_cpu);
  934. return ret;
  935. }
  936. ret = migrate_swap(p, env.best_task);
  937. put_task_struct(env.best_task);
  938. return ret;
  939. }
  940. /* Attempt to migrate a task to a CPU on the preferred node. */
  941. static void numa_migrate_preferred(struct task_struct *p)
  942. {
  943. /* Success if task is already running on preferred CPU */
  944. p->numa_migrate_retry = 0;
  945. if (cpu_to_node(task_cpu(p)) == p->numa_preferred_nid) {
  946. /*
  947. * If migration is temporarily disabled due to a task migration
  948. * then re-enable it now as the task is running on its
  949. * preferred node and memory should migrate locally
  950. */
  951. if (!p->numa_migrate_seq)
  952. p->numa_migrate_seq++;
  953. return;
  954. }
  955. /* This task has no NUMA fault statistics yet */
  956. if (unlikely(p->numa_preferred_nid == -1))
  957. return;
  958. /* Otherwise, try migrate to a CPU on the preferred node */
  959. if (task_numa_migrate(p) != 0)
  960. p->numa_migrate_retry = jiffies + HZ*5;
  961. }
  962. static void task_numa_placement(struct task_struct *p)
  963. {
  964. int seq, nid, max_nid = -1;
  965. unsigned long max_faults = 0;
  966. seq = ACCESS_ONCE(p->mm->numa_scan_seq);
  967. if (p->numa_scan_seq == seq)
  968. return;
  969. p->numa_scan_seq = seq;
  970. p->numa_migrate_seq++;
  971. p->numa_scan_period_max = task_scan_max(p);
  972. /* Find the node with the highest number of faults */
  973. for_each_online_node(nid) {
  974. unsigned long faults = 0;
  975. int priv, i;
  976. for (priv = 0; priv < 2; priv++) {
  977. i = task_faults_idx(nid, priv);
  978. /* Decay existing window, copy faults since last scan */
  979. p->numa_faults[i] >>= 1;
  980. p->numa_faults[i] += p->numa_faults_buffer[i];
  981. p->numa_faults_buffer[i] = 0;
  982. faults += p->numa_faults[i];
  983. }
  984. if (faults > max_faults) {
  985. max_faults = faults;
  986. max_nid = nid;
  987. }
  988. }
  989. /* Preferred node as the node with the most faults */
  990. if (max_faults && max_nid != p->numa_preferred_nid) {
  991. /* Update the preferred nid and migrate task if possible */
  992. p->numa_preferred_nid = max_nid;
  993. p->numa_migrate_seq = 1;
  994. numa_migrate_preferred(p);
  995. }
  996. }
  997. /*
  998. * Got a PROT_NONE fault for a page on @node.
  999. */
  1000. void task_numa_fault(int last_nidpid, int node, int pages, bool migrated)
  1001. {
  1002. struct task_struct *p = current;
  1003. int priv;
  1004. if (!numabalancing_enabled)
  1005. return;
  1006. /* for example, ksmd faulting in a user's mm */
  1007. if (!p->mm)
  1008. return;
  1009. /*
  1010. * First accesses are treated as private, otherwise consider accesses
  1011. * to be private if the accessing pid has not changed
  1012. */
  1013. if (!nidpid_pid_unset(last_nidpid))
  1014. priv = ((p->pid & LAST__PID_MASK) == nidpid_to_pid(last_nidpid));
  1015. else
  1016. priv = 1;
  1017. /* Allocate buffer to track faults on a per-node basis */
  1018. if (unlikely(!p->numa_faults)) {
  1019. int size = sizeof(*p->numa_faults) * 2 * nr_node_ids;
  1020. /* numa_faults and numa_faults_buffer share the allocation */
  1021. p->numa_faults = kzalloc(size * 2, GFP_KERNEL|__GFP_NOWARN);
  1022. if (!p->numa_faults)
  1023. return;
  1024. BUG_ON(p->numa_faults_buffer);
  1025. p->numa_faults_buffer = p->numa_faults + (2 * nr_node_ids);
  1026. }
  1027. /*
  1028. * If pages are properly placed (did not migrate) then scan slower.
  1029. * This is reset periodically in case of phase changes
  1030. */
  1031. if (!migrated) {
  1032. /* Initialise if necessary */
  1033. if (!p->numa_scan_period_max)
  1034. p->numa_scan_period_max = task_scan_max(p);
  1035. p->numa_scan_period = min(p->numa_scan_period_max,
  1036. p->numa_scan_period + 10);
  1037. }
  1038. task_numa_placement(p);
  1039. /* Retry task to preferred node migration if it previously failed */
  1040. if (p->numa_migrate_retry && time_after(jiffies, p->numa_migrate_retry))
  1041. numa_migrate_preferred(p);
  1042. p->numa_faults_buffer[task_faults_idx(node, priv)] += pages;
  1043. }
  1044. static void reset_ptenuma_scan(struct task_struct *p)
  1045. {
  1046. ACCESS_ONCE(p->mm->numa_scan_seq)++;
  1047. p->mm->numa_scan_offset = 0;
  1048. }
  1049. /*
  1050. * The expensive part of numa migration is done from task_work context.
  1051. * Triggered from task_tick_numa().
  1052. */
  1053. void task_numa_work(struct callback_head *work)
  1054. {
  1055. unsigned long migrate, next_scan, now = jiffies;
  1056. struct task_struct *p = current;
  1057. struct mm_struct *mm = p->mm;
  1058. struct vm_area_struct *vma;
  1059. unsigned long start, end;
  1060. unsigned long nr_pte_updates = 0;
  1061. long pages;
  1062. WARN_ON_ONCE(p != container_of(work, struct task_struct, numa_work));
  1063. work->next = work; /* protect against double add */
  1064. /*
  1065. * Who cares about NUMA placement when they're dying.
  1066. *
  1067. * NOTE: make sure not to dereference p->mm before this check,
  1068. * exit_task_work() happens _after_ exit_mm() so we could be called
  1069. * without p->mm even though we still had it when we enqueued this
  1070. * work.
  1071. */
  1072. if (p->flags & PF_EXITING)
  1073. return;
  1074. if (!mm->numa_next_reset || !mm->numa_next_scan) {
  1075. mm->numa_next_scan = now +
  1076. msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
  1077. mm->numa_next_reset = now +
  1078. msecs_to_jiffies(sysctl_numa_balancing_scan_period_reset);
  1079. }
  1080. /*
  1081. * Reset the scan period if enough time has gone by. Objective is that
  1082. * scanning will be reduced if pages are properly placed. As tasks
  1083. * can enter different phases this needs to be re-examined. Lacking
  1084. * proper tracking of reference behaviour, this blunt hammer is used.
  1085. */
  1086. migrate = mm->numa_next_reset;
  1087. if (time_after(now, migrate)) {
  1088. p->numa_scan_period = task_scan_min(p);
  1089. next_scan = now + msecs_to_jiffies(sysctl_numa_balancing_scan_period_reset);
  1090. xchg(&mm->numa_next_reset, next_scan);
  1091. }
  1092. /*
  1093. * Enforce maximal scan/migration frequency..
  1094. */
  1095. migrate = mm->numa_next_scan;
  1096. if (time_before(now, migrate))
  1097. return;
  1098. if (p->numa_scan_period == 0) {
  1099. p->numa_scan_period_max = task_scan_max(p);
  1100. p->numa_scan_period = task_scan_min(p);
  1101. }
  1102. next_scan = now + msecs_to_jiffies(p->numa_scan_period);
  1103. if (cmpxchg(&mm->numa_next_scan, migrate, next_scan) != migrate)
  1104. return;
  1105. /*
  1106. * Delay this task enough that another task of this mm will likely win
  1107. * the next time around.
  1108. */
  1109. p->node_stamp += 2 * TICK_NSEC;
  1110. start = mm->numa_scan_offset;
  1111. pages = sysctl_numa_balancing_scan_size;
  1112. pages <<= 20 - PAGE_SHIFT; /* MB in pages */
  1113. if (!pages)
  1114. return;
  1115. down_read(&mm->mmap_sem);
  1116. vma = find_vma(mm, start);
  1117. if (!vma) {
  1118. reset_ptenuma_scan(p);
  1119. start = 0;
  1120. vma = mm->mmap;
  1121. }
  1122. for (; vma; vma = vma->vm_next) {
  1123. if (!vma_migratable(vma) || !vma_policy_mof(p, vma))
  1124. continue;
  1125. /*
  1126. * Shared library pages mapped by multiple processes are not
  1127. * migrated as it is expected they are cache replicated. Avoid
  1128. * hinting faults in read-only file-backed mappings or the vdso
  1129. * as migrating the pages will be of marginal benefit.
  1130. */
  1131. if (!vma->vm_mm ||
  1132. (vma->vm_file && (vma->vm_flags & (VM_READ|VM_WRITE)) == (VM_READ)))
  1133. continue;
  1134. do {
  1135. start = max(start, vma->vm_start);
  1136. end = ALIGN(start + (pages << PAGE_SHIFT), HPAGE_SIZE);
  1137. end = min(end, vma->vm_end);
  1138. nr_pte_updates += change_prot_numa(vma, start, end);
  1139. /*
  1140. * Scan sysctl_numa_balancing_scan_size but ensure that
  1141. * at least one PTE is updated so that unused virtual
  1142. * address space is quickly skipped.
  1143. */
  1144. if (nr_pte_updates)
  1145. pages -= (end - start) >> PAGE_SHIFT;
  1146. start = end;
  1147. if (pages <= 0)
  1148. goto out;
  1149. } while (end != vma->vm_end);
  1150. }
  1151. out:
  1152. /*
  1153. * If the whole process was scanned without updates then no NUMA
  1154. * hinting faults are being recorded and scan rate should be lower.
  1155. */
  1156. if (mm->numa_scan_offset == 0 && !nr_pte_updates) {
  1157. p->numa_scan_period = min(p->numa_scan_period_max,
  1158. p->numa_scan_period << 1);
  1159. next_scan = now + msecs_to_jiffies(p->numa_scan_period);
  1160. mm->numa_next_scan = next_scan;
  1161. }
  1162. /*
  1163. * It is possible to reach the end of the VMA list but the last few
  1164. * VMAs are not guaranteed to the vma_migratable. If they are not, we
  1165. * would find the !migratable VMA on the next scan but not reset the
  1166. * scanner to the start so check it now.
  1167. */
  1168. if (vma)
  1169. mm->numa_scan_offset = start;
  1170. else
  1171. reset_ptenuma_scan(p);
  1172. up_read(&mm->mmap_sem);
  1173. }
  1174. /*
  1175. * Drive the periodic memory faults..
  1176. */
  1177. void task_tick_numa(struct rq *rq, struct task_struct *curr)
  1178. {
  1179. struct callback_head *work = &curr->numa_work;
  1180. u64 period, now;
  1181. /*
  1182. * We don't care about NUMA placement if we don't have memory.
  1183. */
  1184. if (!curr->mm || (curr->flags & PF_EXITING) || work->next != work)
  1185. return;
  1186. /*
  1187. * Using runtime rather than walltime has the dual advantage that
  1188. * we (mostly) drive the selection from busy threads and that the
  1189. * task needs to have done some actual work before we bother with
  1190. * NUMA placement.
  1191. */
  1192. now = curr->se.sum_exec_runtime;
  1193. period = (u64)curr->numa_scan_period * NSEC_PER_MSEC;
  1194. if (now - curr->node_stamp > period) {
  1195. if (!curr->node_stamp)
  1196. curr->numa_scan_period = task_scan_min(curr);
  1197. curr->node_stamp += period;
  1198. if (!time_before(jiffies, curr->mm->numa_next_scan)) {
  1199. init_task_work(work, task_numa_work); /* TODO: move this into sched_fork() */
  1200. task_work_add(curr, work, true);
  1201. }
  1202. }
  1203. }
  1204. #else
  1205. static void task_tick_numa(struct rq *rq, struct task_struct *curr)
  1206. {
  1207. }
  1208. #endif /* CONFIG_NUMA_BALANCING */
  1209. static void
  1210. account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
  1211. {
  1212. update_load_add(&cfs_rq->load, se->load.weight);
  1213. if (!parent_entity(se))
  1214. update_load_add(&rq_of(cfs_rq)->load, se->load.weight);
  1215. #ifdef CONFIG_SMP
  1216. if (entity_is_task(se))
  1217. list_add(&se->group_node, &rq_of(cfs_rq)->cfs_tasks);
  1218. #endif
  1219. cfs_rq->nr_running++;
  1220. }
  1221. static void
  1222. account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
  1223. {
  1224. update_load_sub(&cfs_rq->load, se->load.weight);
  1225. if (!parent_entity(se))
  1226. update_load_sub(&rq_of(cfs_rq)->load, se->load.weight);
  1227. if (entity_is_task(se))
  1228. list_del_init(&se->group_node);
  1229. cfs_rq->nr_running--;
  1230. }
  1231. #ifdef CONFIG_FAIR_GROUP_SCHED
  1232. # ifdef CONFIG_SMP
  1233. static inline long calc_tg_weight(struct task_group *tg, struct cfs_rq *cfs_rq)
  1234. {
  1235. long tg_weight;
  1236. /*
  1237. * Use this CPU's actual weight instead of the last load_contribution
  1238. * to gain a more accurate current total weight. See
  1239. * update_cfs_rq_load_contribution().
  1240. */
  1241. tg_weight = atomic_long_read(&tg->load_avg);
  1242. tg_weight -= cfs_rq->tg_load_contrib;
  1243. tg_weight += cfs_rq->load.weight;
  1244. return tg_weight;
  1245. }
  1246. static long calc_cfs_shares(struct cfs_rq *cfs_rq, struct task_group *tg)
  1247. {
  1248. long tg_weight, load, shares;
  1249. tg_weight = calc_tg_weight(tg, cfs_rq);
  1250. load = cfs_rq->load.weight;
  1251. shares = (tg->shares * load);
  1252. if (tg_weight)
  1253. shares /= tg_weight;
  1254. if (shares < MIN_SHARES)
  1255. shares = MIN_SHARES;
  1256. if (shares > tg->shares)
  1257. shares = tg->shares;
  1258. return shares;
  1259. }
  1260. # else /* CONFIG_SMP */
  1261. static inline long calc_cfs_shares(struct cfs_rq *cfs_rq, struct task_group *tg)
  1262. {
  1263. return tg->shares;
  1264. }
  1265. # endif /* CONFIG_SMP */
  1266. static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se,
  1267. unsigned long weight)
  1268. {
  1269. if (se->on_rq) {
  1270. /* commit outstanding execution time */
  1271. if (cfs_rq->curr == se)
  1272. update_curr(cfs_rq);
  1273. account_entity_dequeue(cfs_rq, se);
  1274. }
  1275. update_load_set(&se->load, weight);
  1276. if (se->on_rq)
  1277. account_entity_enqueue(cfs_rq, se);
  1278. }
  1279. static inline int throttled_hierarchy(struct cfs_rq *cfs_rq);
  1280. static void update_cfs_shares(struct cfs_rq *cfs_rq)
  1281. {
  1282. struct task_group *tg;
  1283. struct sched_entity *se;
  1284. long shares;
  1285. tg = cfs_rq->tg;
  1286. se = tg->se[cpu_of(rq_of(cfs_rq))];
  1287. if (!se || throttled_hierarchy(cfs_rq))
  1288. return;
  1289. #ifndef CONFIG_SMP
  1290. if (likely(se->load.weight == tg->shares))
  1291. return;
  1292. #endif
  1293. shares = calc_cfs_shares(cfs_rq, tg);
  1294. reweight_entity(cfs_rq_of(se), se, shares);
  1295. }
  1296. #else /* CONFIG_FAIR_GROUP_SCHED */
  1297. static inline void update_cfs_shares(struct cfs_rq *cfs_rq)
  1298. {
  1299. }
  1300. #endif /* CONFIG_FAIR_GROUP_SCHED */
  1301. #ifdef CONFIG_SMP
  1302. /*
  1303. * We choose a half-life close to 1 scheduling period.
  1304. * Note: The tables below are dependent on this value.
  1305. */
  1306. #define LOAD_AVG_PERIOD 32
  1307. #define LOAD_AVG_MAX 47742 /* maximum possible load avg */
  1308. #define LOAD_AVG_MAX_N 345 /* number of full periods to produce LOAD_MAX_AVG */
  1309. /* Precomputed fixed inverse multiplies for multiplication by y^n */
  1310. static const u32 runnable_avg_yN_inv[] = {
  1311. 0xffffffff, 0xfa83b2da, 0xf5257d14, 0xefe4b99a, 0xeac0c6e6, 0xe5b906e6,
  1312. 0xe0ccdeeb, 0xdbfbb796, 0xd744fcc9, 0xd2a81d91, 0xce248c14, 0xc9b9bd85,
  1313. 0xc5672a10, 0xc12c4cc9, 0xbd08a39e, 0xb8fbaf46, 0xb504f333, 0xb123f581,
  1314. 0xad583ee9, 0xa9a15ab4, 0xa5fed6a9, 0xa2704302, 0x9ef5325f, 0x9b8d39b9,
  1315. 0x9837f050, 0x94f4efa8, 0x91c3d373, 0x8ea4398a, 0x8b95c1e3, 0x88980e80,
  1316. 0x85aac367, 0x82cd8698,
  1317. };
  1318. /*
  1319. * Precomputed \Sum y^k { 1<=k<=n }. These are floor(true_value) to prevent
  1320. * over-estimates when re-combining.
  1321. */
  1322. static const u32 runnable_avg_yN_sum[] = {
  1323. 0, 1002, 1982, 2941, 3880, 4798, 5697, 6576, 7437, 8279, 9103,
  1324. 9909,10698,11470,12226,12966,13690,14398,15091,15769,16433,17082,
  1325. 17718,18340,18949,19545,20128,20698,21256,21802,22336,22859,23371,
  1326. };
  1327. /*
  1328. * Approximate:
  1329. * val * y^n, where y^32 ~= 0.5 (~1 scheduling period)
  1330. */
  1331. static __always_inline u64 decay_load(u64 val, u64 n)
  1332. {
  1333. unsigned int local_n;
  1334. if (!n)
  1335. return val;
  1336. else if (unlikely(n > LOAD_AVG_PERIOD * 63))
  1337. return 0;
  1338. /* after bounds checking we can collapse to 32-bit */
  1339. local_n = n;
  1340. /*
  1341. * As y^PERIOD = 1/2, we can combine
  1342. * y^n = 1/2^(n/PERIOD) * k^(n%PERIOD)
  1343. * With a look-up table which covers k^n (n<PERIOD)
  1344. *
  1345. * To achieve constant time decay_load.
  1346. */
  1347. if (unlikely(local_n >= LOAD_AVG_PERIOD)) {
  1348. val >>= local_n / LOAD_AVG_PERIOD;
  1349. local_n %= LOAD_AVG_PERIOD;
  1350. }
  1351. val *= runnable_avg_yN_inv[local_n];
  1352. /* We don't use SRR here since we always want to round down. */
  1353. return val >> 32;
  1354. }
  1355. /*
  1356. * For updates fully spanning n periods, the contribution to runnable
  1357. * average will be: \Sum 1024*y^n
  1358. *
  1359. * We can compute this reasonably efficiently by combining:
  1360. * y^PERIOD = 1/2 with precomputed \Sum 1024*y^n {for n <PERIOD}
  1361. */
  1362. static u32 __compute_runnable_contrib(u64 n)
  1363. {
  1364. u32 contrib = 0;
  1365. if (likely(n <= LOAD_AVG_PERIOD))
  1366. return runnable_avg_yN_sum[n];
  1367. else if (unlikely(n >= LOAD_AVG_MAX_N))
  1368. return LOAD_AVG_MAX;
  1369. /* Compute \Sum k^n combining precomputed values for k^i, \Sum k^j */
  1370. do {
  1371. contrib /= 2; /* y^LOAD_AVG_PERIOD = 1/2 */
  1372. contrib += runnable_avg_yN_sum[LOAD_AVG_PERIOD];
  1373. n -= LOAD_AVG_PERIOD;
  1374. } while (n > LOAD_AVG_PERIOD);
  1375. contrib = decay_load(contrib, n);
  1376. return contrib + runnable_avg_yN_sum[n];
  1377. }
  1378. /*
  1379. * We can represent the historical contribution to runnable average as the
  1380. * coefficients of a geometric series. To do this we sub-divide our runnable
  1381. * history into segments of approximately 1ms (1024us); label the segment that
  1382. * occurred N-ms ago p_N, with p_0 corresponding to the current period, e.g.
  1383. *
  1384. * [<- 1024us ->|<- 1024us ->|<- 1024us ->| ...
  1385. * p0 p1 p2
  1386. * (now) (~1ms ago) (~2ms ago)
  1387. *
  1388. * Let u_i denote the fraction of p_i that the entity was runnable.
  1389. *
  1390. * We then designate the fractions u_i as our co-efficients, yielding the
  1391. * following representation of historical load:
  1392. * u_0 + u_1*y + u_2*y^2 + u_3*y^3 + ...
  1393. *
  1394. * We choose y based on the with of a reasonably scheduling period, fixing:
  1395. * y^32 = 0.5
  1396. *
  1397. * This means that the contribution to load ~32ms ago (u_32) will be weighted
  1398. * approximately half as much as the contribution to load within the last ms
  1399. * (u_0).
  1400. *
  1401. * When a period "rolls over" and we have new u_0`, multiplying the previous
  1402. * sum again by y is sufficient to update:
  1403. * load_avg = u_0` + y*(u_0 + u_1*y + u_2*y^2 + ... )
  1404. * = u_0 + u_1*y + u_2*y^2 + ... [re-labeling u_i --> u_{i+1}]
  1405. */
  1406. static __always_inline int __update_entity_runnable_avg(u64 now,
  1407. struct sched_avg *sa,
  1408. int runnable)
  1409. {
  1410. u64 delta, periods;
  1411. u32 runnable_contrib;
  1412. int delta_w, decayed = 0;
  1413. delta = now - sa->last_runnable_update;
  1414. /*
  1415. * This should only happen when time goes backwards, which it
  1416. * unfortunately does during sched clock init when we swap over to TSC.
  1417. */
  1418. if ((s64)delta < 0) {
  1419. sa->last_runnable_update = now;
  1420. return 0;
  1421. }
  1422. /*
  1423. * Use 1024ns as the unit of measurement since it's a reasonable
  1424. * approximation of 1us and fast to compute.
  1425. */
  1426. delta >>= 10;
  1427. if (!delta)
  1428. return 0;
  1429. sa->last_runnable_update = now;
  1430. /* delta_w is the amount already accumulated against our next period */
  1431. delta_w = sa->runnable_avg_period % 1024;
  1432. if (delta + delta_w >= 1024) {
  1433. /* period roll-over */
  1434. decayed = 1;
  1435. /*
  1436. * Now that we know we're crossing a period boundary, figure
  1437. * out how much from delta we need to complete the current
  1438. * period and accrue it.
  1439. */
  1440. delta_w = 1024 - delta_w;
  1441. if (runnable)
  1442. sa->runnable_avg_sum += delta_w;
  1443. sa->runnable_avg_period += delta_w;
  1444. delta -= delta_w;
  1445. /* Figure out how many additional periods this update spans */
  1446. periods = delta / 1024;
  1447. delta %= 1024;
  1448. sa->runnable_avg_sum = decay_load(sa->runnable_avg_sum,
  1449. periods + 1);
  1450. sa->runnable_avg_period = decay_load(sa->runnable_avg_period,
  1451. periods + 1);
  1452. /* Efficiently calculate \sum (1..n_period) 1024*y^i */
  1453. runnable_contrib = __compute_runnable_contrib(periods);
  1454. if (runnable)
  1455. sa->runnable_avg_sum += runnable_contrib;
  1456. sa->runnable_avg_period += runnable_contrib;
  1457. }
  1458. /* Remainder of delta accrued against u_0` */
  1459. if (runnable)
  1460. sa->runnable_avg_sum += delta;
  1461. sa->runnable_avg_period += delta;
  1462. return decayed;
  1463. }
  1464. /* Synchronize an entity's decay with its parenting cfs_rq.*/
  1465. static inline u64 __synchronize_entity_decay(struct sched_entity *se)
  1466. {
  1467. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  1468. u64 decays = atomic64_read(&cfs_rq->decay_counter);
  1469. decays -= se->avg.decay_count;
  1470. if (!decays)
  1471. return 0;
  1472. se->avg.load_avg_contrib = decay_load(se->avg.load_avg_contrib, decays);
  1473. se->avg.decay_count = 0;
  1474. return decays;
  1475. }
  1476. #ifdef CONFIG_FAIR_GROUP_SCHED
  1477. static inline void __update_cfs_rq_tg_load_contrib(struct cfs_rq *cfs_rq,
  1478. int force_update)
  1479. {
  1480. struct task_group *tg = cfs_rq->tg;
  1481. long tg_contrib;
  1482. tg_contrib = cfs_rq->runnable_load_avg + cfs_rq->blocked_load_avg;
  1483. tg_contrib -= cfs_rq->tg_load_contrib;
  1484. if (force_update || abs(tg_contrib) > cfs_rq->tg_load_contrib / 8) {
  1485. atomic_long_add(tg_contrib, &tg->load_avg);
  1486. cfs_rq->tg_load_contrib += tg_contrib;
  1487. }
  1488. }
  1489. /*
  1490. * Aggregate cfs_rq runnable averages into an equivalent task_group
  1491. * representation for computing load contributions.
  1492. */
  1493. static inline void __update_tg_runnable_avg(struct sched_avg *sa,
  1494. struct cfs_rq *cfs_rq)
  1495. {
  1496. struct task_group *tg = cfs_rq->tg;
  1497. long contrib;
  1498. /* The fraction of a cpu used by this cfs_rq */
  1499. contrib = div_u64(sa->runnable_avg_sum << NICE_0_SHIFT,
  1500. sa->runnable_avg_period + 1);
  1501. contrib -= cfs_rq->tg_runnable_contrib;
  1502. if (abs(contrib) > cfs_rq->tg_runnable_contrib / 64) {
  1503. atomic_add(contrib, &tg->runnable_avg);
  1504. cfs_rq->tg_runnable_contrib += contrib;
  1505. }
  1506. }
  1507. static inline void __update_group_entity_contrib(struct sched_entity *se)
  1508. {
  1509. struct cfs_rq *cfs_rq = group_cfs_rq(se);
  1510. struct task_group *tg = cfs_rq->tg;
  1511. int runnable_avg;
  1512. u64 contrib;
  1513. contrib = cfs_rq->tg_load_contrib * tg->shares;
  1514. se->avg.load_avg_contrib = div_u64(contrib,
  1515. atomic_long_read(&tg->load_avg) + 1);
  1516. /*
  1517. * For group entities we need to compute a correction term in the case
  1518. * that they are consuming <1 cpu so that we would contribute the same
  1519. * load as a task of equal weight.
  1520. *
  1521. * Explicitly co-ordinating this measurement would be expensive, but
  1522. * fortunately the sum of each cpus contribution forms a usable
  1523. * lower-bound on the true value.
  1524. *
  1525. * Consider the aggregate of 2 contributions. Either they are disjoint
  1526. * (and the sum represents true value) or they are disjoint and we are
  1527. * understating by the aggregate of their overlap.
  1528. *
  1529. * Extending this to N cpus, for a given overlap, the maximum amount we
  1530. * understand is then n_i(n_i+1)/2 * w_i where n_i is the number of
  1531. * cpus that overlap for this interval and w_i is the interval width.
  1532. *
  1533. * On a small machine; the first term is well-bounded which bounds the
  1534. * total error since w_i is a subset of the period. Whereas on a
  1535. * larger machine, while this first term can be larger, if w_i is the
  1536. * of consequential size guaranteed to see n_i*w_i quickly converge to
  1537. * our upper bound of 1-cpu.
  1538. */
  1539. runnable_avg = atomic_read(&tg->runnable_avg);
  1540. if (runnable_avg < NICE_0_LOAD) {
  1541. se->avg.load_avg_contrib *= runnable_avg;
  1542. se->avg.load_avg_contrib >>= NICE_0_SHIFT;
  1543. }
  1544. }
  1545. #else
  1546. static inline void __update_cfs_rq_tg_load_contrib(struct cfs_rq *cfs_rq,
  1547. int force_update) {}
  1548. static inline void __update_tg_runnable_avg(struct sched_avg *sa,
  1549. struct cfs_rq *cfs_rq) {}
  1550. static inline void __update_group_entity_contrib(struct sched_entity *se) {}
  1551. #endif
  1552. static inline void __update_task_entity_contrib(struct sched_entity *se)
  1553. {
  1554. u32 contrib;
  1555. /* avoid overflowing a 32-bit type w/ SCHED_LOAD_SCALE */
  1556. contrib = se->avg.runnable_avg_sum * scale_load_down(se->load.weight);
  1557. contrib /= (se->avg.runnable_avg_period + 1);
  1558. se->avg.load_avg_contrib = scale_load(contrib);
  1559. }
  1560. /* Compute the current contribution to load_avg by se, return any delta */
  1561. static long __update_entity_load_avg_contrib(struct sched_entity *se)
  1562. {
  1563. long old_contrib = se->avg.load_avg_contrib;
  1564. if (entity_is_task(se)) {
  1565. __update_task_entity_contrib(se);
  1566. } else {
  1567. __update_tg_runnable_avg(&se->avg, group_cfs_rq(se));
  1568. __update_group_entity_contrib(se);
  1569. }
  1570. return se->avg.load_avg_contrib - old_contrib;
  1571. }
  1572. static inline void subtract_blocked_load_contrib(struct cfs_rq *cfs_rq,
  1573. long load_contrib)
  1574. {
  1575. if (likely(load_contrib < cfs_rq->blocked_load_avg))
  1576. cfs_rq->blocked_load_avg -= load_contrib;
  1577. else
  1578. cfs_rq->blocked_load_avg = 0;
  1579. }
  1580. static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq);
  1581. /* Update a sched_entity's runnable average */
  1582. static inline void update_entity_load_avg(struct sched_entity *se,
  1583. int update_cfs_rq)
  1584. {
  1585. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  1586. long contrib_delta;
  1587. u64 now;
  1588. /*
  1589. * For a group entity we need to use their owned cfs_rq_clock_task() in
  1590. * case they are the parent of a throttled hierarchy.
  1591. */
  1592. if (entity_is_task(se))
  1593. now = cfs_rq_clock_task(cfs_rq);
  1594. else
  1595. now = cfs_rq_clock_task(group_cfs_rq(se));
  1596. if (!__update_entity_runnable_avg(now, &se->avg, se->on_rq))
  1597. return;
  1598. contrib_delta = __update_entity_load_avg_contrib(se);
  1599. if (!update_cfs_rq)
  1600. return;
  1601. if (se->on_rq)
  1602. cfs_rq->runnable_load_avg += contrib_delta;
  1603. else
  1604. subtract_blocked_load_contrib(cfs_rq, -contrib_delta);
  1605. }
  1606. /*
  1607. * Decay the load contributed by all blocked children and account this so that
  1608. * their contribution may appropriately discounted when they wake up.
  1609. */
  1610. static void update_cfs_rq_blocked_load(struct cfs_rq *cfs_rq, int force_update)
  1611. {
  1612. u64 now = cfs_rq_clock_task(cfs_rq) >> 20;
  1613. u64 decays;
  1614. decays = now - cfs_rq->last_decay;
  1615. if (!decays && !force_update)
  1616. return;
  1617. if (atomic_long_read(&cfs_rq->removed_load)) {
  1618. unsigned long removed_load;
  1619. removed_load = atomic_long_xchg(&cfs_rq->removed_load, 0);
  1620. subtract_blocked_load_contrib(cfs_rq, removed_load);
  1621. }
  1622. if (decays) {
  1623. cfs_rq->blocked_load_avg = decay_load(cfs_rq->blocked_load_avg,
  1624. decays);
  1625. atomic64_add(decays, &cfs_rq->decay_counter);
  1626. cfs_rq->last_decay = now;
  1627. }
  1628. __update_cfs_rq_tg_load_contrib(cfs_rq, force_update);
  1629. }
  1630. static inline void update_rq_runnable_avg(struct rq *rq, int runnable)
  1631. {
  1632. __update_entity_runnable_avg(rq_clock_task(rq), &rq->avg, runnable);
  1633. __update_tg_runnable_avg(&rq->avg, &rq->cfs);
  1634. }
  1635. /* Add the load generated by se into cfs_rq's child load-average */
  1636. static inline void enqueue_entity_load_avg(struct cfs_rq *cfs_rq,
  1637. struct sched_entity *se,
  1638. int wakeup)
  1639. {
  1640. /*
  1641. * We track migrations using entity decay_count <= 0, on a wake-up
  1642. * migration we use a negative decay count to track the remote decays
  1643. * accumulated while sleeping.
  1644. *
  1645. * Newly forked tasks are enqueued with se->avg.decay_count == 0, they
  1646. * are seen by enqueue_entity_load_avg() as a migration with an already
  1647. * constructed load_avg_contrib.
  1648. */
  1649. if (unlikely(se->avg.decay_count <= 0)) {
  1650. se->avg.last_runnable_update = rq_clock_task(rq_of(cfs_rq));
  1651. if (se->avg.decay_count) {
  1652. /*
  1653. * In a wake-up migration we have to approximate the
  1654. * time sleeping. This is because we can't synchronize
  1655. * clock_task between the two cpus, and it is not
  1656. * guaranteed to be read-safe. Instead, we can
  1657. * approximate this using our carried decays, which are
  1658. * explicitly atomically readable.
  1659. */
  1660. se->avg.last_runnable_update -= (-se->avg.decay_count)
  1661. << 20;
  1662. update_entity_load_avg(se, 0);
  1663. /* Indicate that we're now synchronized and on-rq */
  1664. se->avg.decay_count = 0;
  1665. }
  1666. wakeup = 0;
  1667. } else {
  1668. /*
  1669. * Task re-woke on same cpu (or else migrate_task_rq_fair()
  1670. * would have made count negative); we must be careful to avoid
  1671. * double-accounting blocked time after synchronizing decays.
  1672. */
  1673. se->avg.last_runnable_update += __synchronize_entity_decay(se)
  1674. << 20;
  1675. }
  1676. /* migrated tasks did not contribute to our blocked load */
  1677. if (wakeup) {
  1678. subtract_blocked_load_contrib(cfs_rq, se->avg.load_avg_contrib);
  1679. update_entity_load_avg(se, 0);
  1680. }
  1681. cfs_rq->runnable_load_avg += se->avg.load_avg_contrib;
  1682. /* we force update consideration on load-balancer moves */
  1683. update_cfs_rq_blocked_load(cfs_rq, !wakeup);
  1684. }
  1685. /*
  1686. * Remove se's load from this cfs_rq child load-average, if the entity is
  1687. * transitioning to a blocked state we track its projected decay using
  1688. * blocked_load_avg.
  1689. */
  1690. static inline void dequeue_entity_load_avg(struct cfs_rq *cfs_rq,
  1691. struct sched_entity *se,
  1692. int sleep)
  1693. {
  1694. update_entity_load_avg(se, 1);
  1695. /* we force update consideration on load-balancer moves */
  1696. update_cfs_rq_blocked_load(cfs_rq, !sleep);
  1697. cfs_rq->runnable_load_avg -= se->avg.load_avg_contrib;
  1698. if (sleep) {
  1699. cfs_rq->blocked_load_avg += se->avg.load_avg_contrib;
  1700. se->avg.decay_count = atomic64_read(&cfs_rq->decay_counter);
  1701. } /* migrations, e.g. sleep=0 leave decay_count == 0 */
  1702. }
  1703. /*
  1704. * Update the rq's load with the elapsed running time before entering
  1705. * idle. if the last scheduled task is not a CFS task, idle_enter will
  1706. * be the only way to update the runnable statistic.
  1707. */
  1708. void idle_enter_fair(struct rq *this_rq)
  1709. {
  1710. update_rq_runnable_avg(this_rq, 1);
  1711. }
  1712. /*
  1713. * Update the rq's load with the elapsed idle time before a task is
  1714. * scheduled. if the newly scheduled task is not a CFS task, idle_exit will
  1715. * be the only way to update the runnable statistic.
  1716. */
  1717. void idle_exit_fair(struct rq *this_rq)
  1718. {
  1719. update_rq_runnable_avg(this_rq, 0);
  1720. }
  1721. #else
  1722. static inline void update_entity_load_avg(struct sched_entity *se,
  1723. int update_cfs_rq) {}
  1724. static inline void update_rq_runnable_avg(struct rq *rq, int runnable) {}
  1725. static inline void enqueue_entity_load_avg(struct cfs_rq *cfs_rq,
  1726. struct sched_entity *se,
  1727. int wakeup) {}
  1728. static inline void dequeue_entity_load_avg(struct cfs_rq *cfs_rq,
  1729. struct sched_entity *se,
  1730. int sleep) {}
  1731. static inline void update_cfs_rq_blocked_load(struct cfs_rq *cfs_rq,
  1732. int force_update) {}
  1733. #endif
  1734. static void enqueue_sleeper(struct cfs_rq *cfs_rq, struct sched_entity *se)
  1735. {
  1736. #ifdef CONFIG_SCHEDSTATS
  1737. struct task_struct *tsk = NULL;
  1738. if (entity_is_task(se))
  1739. tsk = task_of(se);
  1740. if (se->statistics.sleep_start) {
  1741. u64 delta = rq_clock(rq_of(cfs_rq)) - se->statistics.sleep_start;
  1742. if ((s64)delta < 0)
  1743. delta = 0;
  1744. if (unlikely(delta > se->statistics.sleep_max))
  1745. se->statistics.sleep_max = delta;
  1746. se->statistics.sleep_start = 0;
  1747. se->statistics.sum_sleep_runtime += delta;
  1748. if (tsk) {
  1749. account_scheduler_latency(tsk, delta >> 10, 1);
  1750. trace_sched_stat_sleep(tsk, delta);
  1751. }
  1752. }
  1753. if (se->statistics.block_start) {
  1754. u64 delta = rq_clock(rq_of(cfs_rq)) - se->statistics.block_start;
  1755. if ((s64)delta < 0)
  1756. delta = 0;
  1757. if (unlikely(delta > se->statistics.block_max))
  1758. se->statistics.block_max = delta;
  1759. se->statistics.block_start = 0;
  1760. se->statistics.sum_sleep_runtime += delta;
  1761. if (tsk) {
  1762. if (tsk->in_iowait) {
  1763. se->statistics.iowait_sum += delta;
  1764. se->statistics.iowait_count++;
  1765. trace_sched_stat_iowait(tsk, delta);
  1766. }
  1767. trace_sched_stat_blocked(tsk, delta);
  1768. /*
  1769. * Blocking time is in units of nanosecs, so shift by
  1770. * 20 to get a milliseconds-range estimation of the
  1771. * amount of time that the task spent sleeping:
  1772. */
  1773. if (unlikely(prof_on == SLEEP_PROFILING)) {
  1774. profile_hits(SLEEP_PROFILING,
  1775. (void *)get_wchan(tsk),
  1776. delta >> 20);
  1777. }
  1778. account_scheduler_latency(tsk, delta >> 10, 0);
  1779. }
  1780. }
  1781. #endif
  1782. }
  1783. static void check_spread(struct cfs_rq *cfs_rq, struct sched_entity *se)
  1784. {
  1785. #ifdef CONFIG_SCHED_DEBUG
  1786. s64 d = se->vruntime - cfs_rq->min_vruntime;
  1787. if (d < 0)
  1788. d = -d;
  1789. if (d > 3*sysctl_sched_latency)
  1790. schedstat_inc(cfs_rq, nr_spread_over);
  1791. #endif
  1792. }
  1793. static void
  1794. place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int initial)
  1795. {
  1796. u64 vruntime = cfs_rq->min_vruntime;
  1797. /*
  1798. * The 'current' period is already promised to the current tasks,
  1799. * however the extra weight of the new task will slow them down a
  1800. * little, place the new task so that it fits in the slot that
  1801. * stays open at the end.
  1802. */
  1803. if (initial && sched_feat(START_DEBIT))
  1804. vruntime += sched_vslice(cfs_rq, se);
  1805. /* sleeps up to a single latency don't count. */
  1806. if (!initial) {
  1807. unsigned long thresh = sysctl_sched_latency;
  1808. /*
  1809. * Halve their sleep time's effect, to allow
  1810. * for a gentler effect of sleepers:
  1811. */
  1812. if (sched_feat(GENTLE_FAIR_SLEEPERS))
  1813. thresh >>= 1;
  1814. vruntime -= thresh;
  1815. }
  1816. /* ensure we never gain time by being placed backwards. */
  1817. se->vruntime = max_vruntime(se->vruntime, vruntime);
  1818. }
  1819. static void check_enqueue_throttle(struct cfs_rq *cfs_rq);
  1820. static void
  1821. enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
  1822. {
  1823. /*
  1824. * Update the normalized vruntime before updating min_vruntime
  1825. * through calling update_curr().
  1826. */
  1827. if (!(flags & ENQUEUE_WAKEUP) || (flags & ENQUEUE_WAKING))
  1828. se->vruntime += cfs_rq->min_vruntime;
  1829. /*
  1830. * Update run-time statistics of the 'current'.
  1831. */
  1832. update_curr(cfs_rq);
  1833. enqueue_entity_load_avg(cfs_rq, se, flags & ENQUEUE_WAKEUP);
  1834. account_entity_enqueue(cfs_rq, se);
  1835. update_cfs_shares(cfs_rq);
  1836. if (flags & ENQUEUE_WAKEUP) {
  1837. place_entity(cfs_rq, se, 0);
  1838. enqueue_sleeper(cfs_rq, se);
  1839. }
  1840. update_stats_enqueue(cfs_rq, se);
  1841. check_spread(cfs_rq, se);
  1842. if (se != cfs_rq->curr)
  1843. __enqueue_entity(cfs_rq, se);
  1844. se->on_rq = 1;
  1845. if (cfs_rq->nr_running == 1) {
  1846. list_add_leaf_cfs_rq(cfs_rq);
  1847. check_enqueue_throttle(cfs_rq);
  1848. }
  1849. }
  1850. static void __clear_buddies_last(struct sched_entity *se)
  1851. {
  1852. for_each_sched_entity(se) {
  1853. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  1854. if (cfs_rq->last == se)
  1855. cfs_rq->last = NULL;
  1856. else
  1857. break;
  1858. }
  1859. }
  1860. static void __clear_buddies_next(struct sched_entity *se)
  1861. {
  1862. for_each_sched_entity(se) {
  1863. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  1864. if (cfs_rq->next == se)
  1865. cfs_rq->next = NULL;
  1866. else
  1867. break;
  1868. }
  1869. }
  1870. static void __clear_buddies_skip(struct sched_entity *se)
  1871. {
  1872. for_each_sched_entity(se) {
  1873. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  1874. if (cfs_rq->skip == se)
  1875. cfs_rq->skip = NULL;
  1876. else
  1877. break;
  1878. }
  1879. }
  1880. static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
  1881. {
  1882. if (cfs_rq->last == se)
  1883. __clear_buddies_last(se);
  1884. if (cfs_rq->next == se)
  1885. __clear_buddies_next(se);
  1886. if (cfs_rq->skip == se)
  1887. __clear_buddies_skip(se);
  1888. }
  1889. static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq);
  1890. static void
  1891. dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
  1892. {
  1893. /*
  1894. * Update run-time statistics of the 'current'.
  1895. */
  1896. update_curr(cfs_rq);
  1897. dequeue_entity_load_avg(cfs_rq, se, flags & DEQUEUE_SLEEP);
  1898. update_stats_dequeue(cfs_rq, se);
  1899. if (flags & DEQUEUE_SLEEP) {
  1900. #ifdef CONFIG_SCHEDSTATS
  1901. if (entity_is_task(se)) {
  1902. struct task_struct *tsk = task_of(se);
  1903. if (tsk->state & TASK_INTERRUPTIBLE)
  1904. se->statistics.sleep_start = rq_clock(rq_of(cfs_rq));
  1905. if (tsk->state & TASK_UNINTERRUPTIBLE)
  1906. se->statistics.block_start = rq_clock(rq_of(cfs_rq));
  1907. }
  1908. #endif
  1909. }
  1910. clear_buddies(cfs_rq, se);
  1911. if (se != cfs_rq->curr)
  1912. __dequeue_entity(cfs_rq, se);
  1913. se->on_rq = 0;
  1914. account_entity_dequeue(cfs_rq, se);
  1915. /*
  1916. * Normalize the entity after updating the min_vruntime because the
  1917. * update can refer to the ->curr item and we need to reflect this
  1918. * movement in our normalized position.
  1919. */
  1920. if (!(flags & DEQUEUE_SLEEP))
  1921. se->vruntime -= cfs_rq->min_vruntime;
  1922. /* return excess runtime on last dequeue */
  1923. return_cfs_rq_runtime(cfs_rq);
  1924. update_min_vruntime(cfs_rq);
  1925. update_cfs_shares(cfs_rq);
  1926. }
  1927. /*
  1928. * Preempt the current task with a newly woken task if needed:
  1929. */
  1930. static void
  1931. check_preempt_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr)
  1932. {
  1933. unsigned long ideal_runtime, delta_exec;
  1934. struct sched_entity *se;
  1935. s64 delta;
  1936. ideal_runtime = sched_slice(cfs_rq, curr);
  1937. delta_exec = curr->sum_exec_runtime - curr->prev_sum_exec_runtime;
  1938. if (delta_exec > ideal_runtime) {
  1939. resched_task(rq_of(cfs_rq)->curr);
  1940. /*
  1941. * The current task ran long enough, ensure it doesn't get
  1942. * re-elected due to buddy favours.
  1943. */
  1944. clear_buddies(cfs_rq, curr);
  1945. return;
  1946. }
  1947. /*
  1948. * Ensure that a task that missed wakeup preemption by a
  1949. * narrow margin doesn't have to wait for a full slice.
  1950. * This also mitigates buddy induced latencies under load.
  1951. */
  1952. if (delta_exec < sysctl_sched_min_granularity)
  1953. return;
  1954. se = __pick_first_entity(cfs_rq);
  1955. delta = curr->vruntime - se->vruntime;
  1956. if (delta < 0)
  1957. return;
  1958. if (delta > ideal_runtime)
  1959. resched_task(rq_of(cfs_rq)->curr);
  1960. }
  1961. static void
  1962. set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
  1963. {
  1964. /* 'current' is not kept within the tree. */
  1965. if (se->on_rq) {
  1966. /*
  1967. * Any task has to be enqueued before it get to execute on
  1968. * a CPU. So account for the time it spent waiting on the
  1969. * runqueue.
  1970. */
  1971. update_stats_wait_end(cfs_rq, se);
  1972. __dequeue_entity(cfs_rq, se);
  1973. }
  1974. update_stats_curr_start(cfs_rq, se);
  1975. cfs_rq->curr = se;
  1976. #ifdef CONFIG_SCHEDSTATS
  1977. /*
  1978. * Track our maximum slice length, if the CPU's load is at
  1979. * least twice that of our own weight (i.e. dont track it
  1980. * when there are only lesser-weight tasks around):
  1981. */
  1982. if (rq_of(cfs_rq)->load.weight >= 2*se->load.weight) {
  1983. se->statistics.slice_max = max(se->statistics.slice_max,
  1984. se->sum_exec_runtime - se->prev_sum_exec_runtime);
  1985. }
  1986. #endif
  1987. se->prev_sum_exec_runtime = se->sum_exec_runtime;
  1988. }
  1989. static int
  1990. wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se);
  1991. /*
  1992. * Pick the next process, keeping these things in mind, in this order:
  1993. * 1) keep things fair between processes/task groups
  1994. * 2) pick the "next" process, since someone really wants that to run
  1995. * 3) pick the "last" process, for cache locality
  1996. * 4) do not run the "skip" process, if something else is available
  1997. */
  1998. static struct sched_entity *pick_next_entity(struct cfs_rq *cfs_rq)
  1999. {
  2000. struct sched_entity *se = __pick_first_entity(cfs_rq);
  2001. struct sched_entity *left = se;
  2002. /*
  2003. * Avoid running the skip buddy, if running something else can
  2004. * be done without getting too unfair.
  2005. */
  2006. if (cfs_rq->skip == se) {
  2007. struct sched_entity *second = __pick_next_entity(se);
  2008. if (second && wakeup_preempt_entity(second, left) < 1)
  2009. se = second;
  2010. }
  2011. /*
  2012. * Prefer last buddy, try to return the CPU to a preempted task.
  2013. */
  2014. if (cfs_rq->last && wakeup_preempt_entity(cfs_rq->last, left) < 1)
  2015. se = cfs_rq->last;
  2016. /*
  2017. * Someone really wants this to run. If it's not unfair, run it.
  2018. */
  2019. if (cfs_rq->next && wakeup_preempt_entity(cfs_rq->next, left) < 1)
  2020. se = cfs_rq->next;
  2021. clear_buddies(cfs_rq, se);
  2022. return se;
  2023. }
  2024. static void check_cfs_rq_runtime(struct cfs_rq *cfs_rq);
  2025. static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
  2026. {
  2027. /*
  2028. * If still on the runqueue then deactivate_task()
  2029. * was not called and update_curr() has to be done:
  2030. */
  2031. if (prev->on_rq)
  2032. update_curr(cfs_rq);
  2033. /* throttle cfs_rqs exceeding runtime */
  2034. check_cfs_rq_runtime(cfs_rq);
  2035. check_spread(cfs_rq, prev);
  2036. if (prev->on_rq) {
  2037. update_stats_wait_start(cfs_rq, prev);
  2038. /* Put 'current' back into the tree. */
  2039. __enqueue_entity(cfs_rq, prev);
  2040. /* in !on_rq case, update occurred at dequeue */
  2041. update_entity_load_avg(prev, 1);
  2042. }
  2043. cfs_rq->curr = NULL;
  2044. }
  2045. static void
  2046. entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
  2047. {
  2048. /*
  2049. * Update run-time statistics of the 'current'.
  2050. */
  2051. update_curr(cfs_rq);
  2052. /*
  2053. * Ensure that runnable average is periodically updated.
  2054. */
  2055. update_entity_load_avg(curr, 1);
  2056. update_cfs_rq_blocked_load(cfs_rq, 1);
  2057. update_cfs_shares(cfs_rq);
  2058. #ifdef CONFIG_SCHED_HRTICK
  2059. /*
  2060. * queued ticks are scheduled to match the slice, so don't bother
  2061. * validating it and just reschedule.
  2062. */
  2063. if (queued) {
  2064. resched_task(rq_of(cfs_rq)->curr);
  2065. return;
  2066. }
  2067. /*
  2068. * don't let the period tick interfere with the hrtick preemption
  2069. */
  2070. if (!sched_feat(DOUBLE_TICK) &&
  2071. hrtimer_active(&rq_of(cfs_rq)->hrtick_timer))
  2072. return;
  2073. #endif
  2074. if (cfs_rq->nr_running > 1)
  2075. check_preempt_tick(cfs_rq, curr);
  2076. }
  2077. /**************************************************
  2078. * CFS bandwidth control machinery
  2079. */
  2080. #ifdef CONFIG_CFS_BANDWIDTH
  2081. #ifdef HAVE_JUMP_LABEL
  2082. static struct static_key __cfs_bandwidth_used;
  2083. static inline bool cfs_bandwidth_used(void)
  2084. {
  2085. return static_key_false(&__cfs_bandwidth_used);
  2086. }
  2087. void account_cfs_bandwidth_used(int enabled, int was_enabled)
  2088. {
  2089. /* only need to count groups transitioning between enabled/!enabled */
  2090. if (enabled && !was_enabled)
  2091. static_key_slow_inc(&__cfs_bandwidth_used);
  2092. else if (!enabled && was_enabled)
  2093. static_key_slow_dec(&__cfs_bandwidth_used);
  2094. }
  2095. #else /* HAVE_JUMP_LABEL */
  2096. static bool cfs_bandwidth_used(void)
  2097. {
  2098. return true;
  2099. }
  2100. void account_cfs_bandwidth_used(int enabled, int was_enabled) {}
  2101. #endif /* HAVE_JUMP_LABEL */
  2102. /*
  2103. * default period for cfs group bandwidth.
  2104. * default: 0.1s, units: nanoseconds
  2105. */
  2106. static inline u64 default_cfs_period(void)
  2107. {
  2108. return 100000000ULL;
  2109. }
  2110. static inline u64 sched_cfs_bandwidth_slice(void)
  2111. {
  2112. return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC;
  2113. }
  2114. /*
  2115. * Replenish runtime according to assigned quota and update expiration time.
  2116. * We use sched_clock_cpu directly instead of rq->clock to avoid adding
  2117. * additional synchronization around rq->lock.
  2118. *
  2119. * requires cfs_b->lock
  2120. */
  2121. void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
  2122. {
  2123. u64 now;
  2124. if (cfs_b->quota == RUNTIME_INF)
  2125. return;
  2126. now = sched_clock_cpu(smp_processor_id());
  2127. cfs_b->runtime = cfs_b->quota;
  2128. cfs_b->runtime_expires = now + ktime_to_ns(cfs_b->period);
  2129. }
  2130. static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
  2131. {
  2132. return &tg->cfs_bandwidth;
  2133. }
  2134. /* rq->task_clock normalized against any time this cfs_rq has spent throttled */
  2135. static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq)
  2136. {
  2137. if (unlikely(cfs_rq->throttle_count))
  2138. return cfs_rq->throttled_clock_task;
  2139. return rq_clock_task(rq_of(cfs_rq)) - cfs_rq->throttled_clock_task_time;
  2140. }
  2141. /* returns 0 on failure to allocate runtime */
  2142. static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  2143. {
  2144. struct task_group *tg = cfs_rq->tg;
  2145. struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(tg);
  2146. u64 amount = 0, min_amount, expires;
  2147. /* note: this is a positive sum as runtime_remaining <= 0 */
  2148. min_amount = sched_cfs_bandwidth_slice() - cfs_rq->runtime_remaining;
  2149. raw_spin_lock(&cfs_b->lock);
  2150. if (cfs_b->quota == RUNTIME_INF)
  2151. amount = min_amount;
  2152. else {
  2153. /*
  2154. * If the bandwidth pool has become inactive, then at least one
  2155. * period must have elapsed since the last consumption.
  2156. * Refresh the global state and ensure bandwidth timer becomes
  2157. * active.
  2158. */
  2159. if (!cfs_b->timer_active) {
  2160. __refill_cfs_bandwidth_runtime(cfs_b);
  2161. __start_cfs_bandwidth(cfs_b);
  2162. }
  2163. if (cfs_b->runtime > 0) {
  2164. amount = min(cfs_b->runtime, min_amount);
  2165. cfs_b->runtime -= amount;
  2166. cfs_b->idle = 0;
  2167. }
  2168. }
  2169. expires = cfs_b->runtime_expires;
  2170. raw_spin_unlock(&cfs_b->lock);
  2171. cfs_rq->runtime_remaining += amount;
  2172. /*
  2173. * we may have advanced our local expiration to account for allowed
  2174. * spread between our sched_clock and the one on which runtime was
  2175. * issued.
  2176. */
  2177. if ((s64)(expires - cfs_rq->runtime_expires) > 0)
  2178. cfs_rq->runtime_expires = expires;
  2179. return cfs_rq->runtime_remaining > 0;
  2180. }
  2181. /*
  2182. * Note: This depends on the synchronization provided by sched_clock and the
  2183. * fact that rq->clock snapshots this value.
  2184. */
  2185. static void expire_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  2186. {
  2187. struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
  2188. /* if the deadline is ahead of our clock, nothing to do */
  2189. if (likely((s64)(rq_clock(rq_of(cfs_rq)) - cfs_rq->runtime_expires) < 0))
  2190. return;
  2191. if (cfs_rq->runtime_remaining < 0)
  2192. return;
  2193. /*
  2194. * If the local deadline has passed we have to consider the
  2195. * possibility that our sched_clock is 'fast' and the global deadline
  2196. * has not truly expired.
  2197. *
  2198. * Fortunately we can check determine whether this the case by checking
  2199. * whether the global deadline has advanced.
  2200. */
  2201. if ((s64)(cfs_rq->runtime_expires - cfs_b->runtime_expires) >= 0) {
  2202. /* extend local deadline, drift is bounded above by 2 ticks */
  2203. cfs_rq->runtime_expires += TICK_NSEC;
  2204. } else {
  2205. /* global deadline is ahead, expiration has passed */
  2206. cfs_rq->runtime_remaining = 0;
  2207. }
  2208. }
  2209. static void __account_cfs_rq_runtime(struct cfs_rq *cfs_rq,
  2210. unsigned long delta_exec)
  2211. {
  2212. /* dock delta_exec before expiring quota (as it could span periods) */
  2213. cfs_rq->runtime_remaining -= delta_exec;
  2214. expire_cfs_rq_runtime(cfs_rq);
  2215. if (likely(cfs_rq->runtime_remaining > 0))
  2216. return;
  2217. /*
  2218. * if we're unable to extend our runtime we resched so that the active
  2219. * hierarchy can be throttled
  2220. */
  2221. if (!assign_cfs_rq_runtime(cfs_rq) && likely(cfs_rq->curr))
  2222. resched_task(rq_of(cfs_rq)->curr);
  2223. }
  2224. static __always_inline
  2225. void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, unsigned long delta_exec)
  2226. {
  2227. if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled)
  2228. return;
  2229. __account_cfs_rq_runtime(cfs_rq, delta_exec);
  2230. }
  2231. static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
  2232. {
  2233. return cfs_bandwidth_used() && cfs_rq->throttled;
  2234. }
  2235. /* check whether cfs_rq, or any parent, is throttled */
  2236. static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
  2237. {
  2238. return cfs_bandwidth_used() && cfs_rq->throttle_count;
  2239. }
  2240. /*
  2241. * Ensure that neither of the group entities corresponding to src_cpu or
  2242. * dest_cpu are members of a throttled hierarchy when performing group
  2243. * load-balance operations.
  2244. */
  2245. static inline int throttled_lb_pair(struct task_group *tg,
  2246. int src_cpu, int dest_cpu)
  2247. {
  2248. struct cfs_rq *src_cfs_rq, *dest_cfs_rq;
  2249. src_cfs_rq = tg->cfs_rq[src_cpu];
  2250. dest_cfs_rq = tg->cfs_rq[dest_cpu];
  2251. return throttled_hierarchy(src_cfs_rq) ||
  2252. throttled_hierarchy(dest_cfs_rq);
  2253. }
  2254. /* updated child weight may affect parent so we have to do this bottom up */
  2255. static int tg_unthrottle_up(struct task_group *tg, void *data)
  2256. {
  2257. struct rq *rq = data;
  2258. struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
  2259. cfs_rq->throttle_count--;
  2260. #ifdef CONFIG_SMP
  2261. if (!cfs_rq->throttle_count) {
  2262. /* adjust cfs_rq_clock_task() */
  2263. cfs_rq->throttled_clock_task_time += rq_clock_task(rq) -
  2264. cfs_rq->throttled_clock_task;
  2265. }
  2266. #endif
  2267. return 0;
  2268. }
  2269. static int tg_throttle_down(struct task_group *tg, void *data)
  2270. {
  2271. struct rq *rq = data;
  2272. struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
  2273. /* group is entering throttled state, stop time */
  2274. if (!cfs_rq->throttle_count)
  2275. cfs_rq->throttled_clock_task = rq_clock_task(rq);
  2276. cfs_rq->throttle_count++;
  2277. return 0;
  2278. }
  2279. static void throttle_cfs_rq(struct cfs_rq *cfs_rq)
  2280. {
  2281. struct rq *rq = rq_of(cfs_rq);
  2282. struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
  2283. struct sched_entity *se;
  2284. long task_delta, dequeue = 1;
  2285. se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))];
  2286. /* freeze hierarchy runnable averages while throttled */
  2287. rcu_read_lock();
  2288. walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq);
  2289. rcu_read_unlock();
  2290. task_delta = cfs_rq->h_nr_running;
  2291. for_each_sched_entity(se) {
  2292. struct cfs_rq *qcfs_rq = cfs_rq_of(se);
  2293. /* throttled entity or throttle-on-deactivate */
  2294. if (!se->on_rq)
  2295. break;
  2296. if (dequeue)
  2297. dequeue_entity(qcfs_rq, se, DEQUEUE_SLEEP);
  2298. qcfs_rq->h_nr_running -= task_delta;
  2299. if (qcfs_rq->load.weight)
  2300. dequeue = 0;
  2301. }
  2302. if (!se)
  2303. rq->nr_running -= task_delta;
  2304. cfs_rq->throttled = 1;
  2305. cfs_rq->throttled_clock = rq_clock(rq);
  2306. raw_spin_lock(&cfs_b->lock);
  2307. list_add_tail_rcu(&cfs_rq->throttled_list, &cfs_b->throttled_cfs_rq);
  2308. raw_spin_unlock(&cfs_b->lock);
  2309. }
  2310. void unthrottle_cfs_rq(struct cfs_rq *cfs_rq)
  2311. {
  2312. struct rq *rq = rq_of(cfs_rq);
  2313. struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
  2314. struct sched_entity *se;
  2315. int enqueue = 1;
  2316. long task_delta;
  2317. se = cfs_rq->tg->se[cpu_of(rq)];
  2318. cfs_rq->throttled = 0;
  2319. update_rq_clock(rq);
  2320. raw_spin_lock(&cfs_b->lock);
  2321. cfs_b->throttled_time += rq_clock(rq) - cfs_rq->throttled_clock;
  2322. list_del_rcu(&cfs_rq->throttled_list);
  2323. raw_spin_unlock(&cfs_b->lock);
  2324. /* update hierarchical throttle state */
  2325. walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq);
  2326. if (!cfs_rq->load.weight)
  2327. return;
  2328. task_delta = cfs_rq->h_nr_running;
  2329. for_each_sched_entity(se) {
  2330. if (se->on_rq)
  2331. enqueue = 0;
  2332. cfs_rq = cfs_rq_of(se);
  2333. if (enqueue)
  2334. enqueue_entity(cfs_rq, se, ENQUEUE_WAKEUP);
  2335. cfs_rq->h_nr_running += task_delta;
  2336. if (cfs_rq_throttled(cfs_rq))
  2337. break;
  2338. }
  2339. if (!se)
  2340. rq->nr_running += task_delta;
  2341. /* determine whether we need to wake up potentially idle cpu */
  2342. if (rq->curr == rq->idle && rq->cfs.nr_running)
  2343. resched_task(rq->curr);
  2344. }
  2345. static u64 distribute_cfs_runtime(struct cfs_bandwidth *cfs_b,
  2346. u64 remaining, u64 expires)
  2347. {
  2348. struct cfs_rq *cfs_rq;
  2349. u64 runtime = remaining;
  2350. rcu_read_lock();
  2351. list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
  2352. throttled_list) {
  2353. struct rq *rq = rq_of(cfs_rq);
  2354. raw_spin_lock(&rq->lock);
  2355. if (!cfs_rq_throttled(cfs_rq))
  2356. goto next;
  2357. runtime = -cfs_rq->runtime_remaining + 1;
  2358. if (runtime > remaining)
  2359. runtime = remaining;
  2360. remaining -= runtime;
  2361. cfs_rq->runtime_remaining += runtime;
  2362. cfs_rq->runtime_expires = expires;
  2363. /* we check whether we're throttled above */
  2364. if (cfs_rq->runtime_remaining > 0)
  2365. unthrottle_cfs_rq(cfs_rq);
  2366. next:
  2367. raw_spin_unlock(&rq->lock);
  2368. if (!remaining)
  2369. break;
  2370. }
  2371. rcu_read_unlock();
  2372. return remaining;
  2373. }
  2374. /*
  2375. * Responsible for refilling a task_group's bandwidth and unthrottling its
  2376. * cfs_rqs as appropriate. If there has been no activity within the last
  2377. * period the timer is deactivated until scheduling resumes; cfs_b->idle is
  2378. * used to track this state.
  2379. */
  2380. static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun)
  2381. {
  2382. u64 runtime, runtime_expires;
  2383. int idle = 1, throttled;
  2384. raw_spin_lock(&cfs_b->lock);
  2385. /* no need to continue the timer with no bandwidth constraint */
  2386. if (cfs_b->quota == RUNTIME_INF)
  2387. goto out_unlock;
  2388. throttled = !list_empty(&cfs_b->throttled_cfs_rq);
  2389. /* idle depends on !throttled (for the case of a large deficit) */
  2390. idle = cfs_b->idle && !throttled;
  2391. cfs_b->nr_periods += overrun;
  2392. /* if we're going inactive then everything else can be deferred */
  2393. if (idle)
  2394. goto out_unlock;
  2395. __refill_cfs_bandwidth_runtime(cfs_b);
  2396. if (!throttled) {
  2397. /* mark as potentially idle for the upcoming period */
  2398. cfs_b->idle = 1;
  2399. goto out_unlock;
  2400. }
  2401. /* account preceding periods in which throttling occurred */
  2402. cfs_b->nr_throttled += overrun;
  2403. /*
  2404. * There are throttled entities so we must first use the new bandwidth
  2405. * to unthrottle them before making it generally available. This
  2406. * ensures that all existing debts will be paid before a new cfs_rq is
  2407. * allowed to run.
  2408. */
  2409. runtime = cfs_b->runtime;
  2410. runtime_expires = cfs_b->runtime_expires;
  2411. cfs_b->runtime = 0;
  2412. /*
  2413. * This check is repeated as we are holding onto the new bandwidth
  2414. * while we unthrottle. This can potentially race with an unthrottled
  2415. * group trying to acquire new bandwidth from the global pool.
  2416. */
  2417. while (throttled && runtime > 0) {
  2418. raw_spin_unlock(&cfs_b->lock);
  2419. /* we can't nest cfs_b->lock while distributing bandwidth */
  2420. runtime = distribute_cfs_runtime(cfs_b, runtime,
  2421. runtime_expires);
  2422. raw_spin_lock(&cfs_b->lock);
  2423. throttled = !list_empty(&cfs_b->throttled_cfs_rq);
  2424. }
  2425. /* return (any) remaining runtime */
  2426. cfs_b->runtime = runtime;
  2427. /*
  2428. * While we are ensured activity in the period following an
  2429. * unthrottle, this also covers the case in which the new bandwidth is
  2430. * insufficient to cover the existing bandwidth deficit. (Forcing the
  2431. * timer to remain active while there are any throttled entities.)
  2432. */
  2433. cfs_b->idle = 0;
  2434. out_unlock:
  2435. if (idle)
  2436. cfs_b->timer_active = 0;
  2437. raw_spin_unlock(&cfs_b->lock);
  2438. return idle;
  2439. }
  2440. /* a cfs_rq won't donate quota below this amount */
  2441. static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC;
  2442. /* minimum remaining period time to redistribute slack quota */
  2443. static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC;
  2444. /* how long we wait to gather additional slack before distributing */
  2445. static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC;
  2446. /* are we near the end of the current quota period? */
  2447. static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire)
  2448. {
  2449. struct hrtimer *refresh_timer = &cfs_b->period_timer;
  2450. u64 remaining;
  2451. /* if the call-back is running a quota refresh is already occurring */
  2452. if (hrtimer_callback_running(refresh_timer))
  2453. return 1;
  2454. /* is a quota refresh about to occur? */
  2455. remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer));
  2456. if (remaining < min_expire)
  2457. return 1;
  2458. return 0;
  2459. }
  2460. static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b)
  2461. {
  2462. u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration;
  2463. /* if there's a quota refresh soon don't bother with slack */
  2464. if (runtime_refresh_within(cfs_b, min_left))
  2465. return;
  2466. start_bandwidth_timer(&cfs_b->slack_timer,
  2467. ns_to_ktime(cfs_bandwidth_slack_period));
  2468. }
  2469. /* we know any runtime found here is valid as update_curr() precedes return */
  2470. static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  2471. {
  2472. struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
  2473. s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;
  2474. if (slack_runtime <= 0)
  2475. return;
  2476. raw_spin_lock(&cfs_b->lock);
  2477. if (cfs_b->quota != RUNTIME_INF &&
  2478. cfs_rq->runtime_expires == cfs_b->runtime_expires) {
  2479. cfs_b->runtime += slack_runtime;
  2480. /* we are under rq->lock, defer unthrottling using a timer */
  2481. if (cfs_b->runtime > sched_cfs_bandwidth_slice() &&
  2482. !list_empty(&cfs_b->throttled_cfs_rq))
  2483. start_cfs_slack_bandwidth(cfs_b);
  2484. }
  2485. raw_spin_unlock(&cfs_b->lock);
  2486. /* even if it's not valid for return we don't want to try again */
  2487. cfs_rq->runtime_remaining -= slack_runtime;
  2488. }
  2489. static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  2490. {
  2491. if (!cfs_bandwidth_used())
  2492. return;
  2493. if (!cfs_rq->runtime_enabled || cfs_rq->nr_running)
  2494. return;
  2495. __return_cfs_rq_runtime(cfs_rq);
  2496. }
  2497. /*
  2498. * This is done with a timer (instead of inline with bandwidth return) since
  2499. * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
  2500. */
  2501. static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)
  2502. {
  2503. u64 runtime = 0, slice = sched_cfs_bandwidth_slice();
  2504. u64 expires;
  2505. /* confirm we're still not at a refresh boundary */
  2506. if (runtime_refresh_within(cfs_b, min_bandwidth_expiration))
  2507. return;
  2508. raw_spin_lock(&cfs_b->lock);
  2509. if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice) {
  2510. runtime = cfs_b->runtime;
  2511. cfs_b->runtime = 0;
  2512. }
  2513. expires = cfs_b->runtime_expires;
  2514. raw_spin_unlock(&cfs_b->lock);
  2515. if (!runtime)
  2516. return;
  2517. runtime = distribute_cfs_runtime(cfs_b, runtime, expires);
  2518. raw_spin_lock(&cfs_b->lock);
  2519. if (expires == cfs_b->runtime_expires)
  2520. cfs_b->runtime = runtime;
  2521. raw_spin_unlock(&cfs_b->lock);
  2522. }
  2523. /*
  2524. * When a group wakes up we want to make sure that its quota is not already
  2525. * expired/exceeded, otherwise it may be allowed to steal additional ticks of
  2526. * runtime as update_curr() throttling can not not trigger until it's on-rq.
  2527. */
  2528. static void check_enqueue_throttle(struct cfs_rq *cfs_rq)
  2529. {
  2530. if (!cfs_bandwidth_used())
  2531. return;
  2532. /* an active group must be handled by the update_curr()->put() path */
  2533. if (!cfs_rq->runtime_enabled || cfs_rq->curr)
  2534. return;
  2535. /* ensure the group is not already throttled */
  2536. if (cfs_rq_throttled(cfs_rq))
  2537. return;
  2538. /* update runtime allocation */
  2539. account_cfs_rq_runtime(cfs_rq, 0);
  2540. if (cfs_rq->runtime_remaining <= 0)
  2541. throttle_cfs_rq(cfs_rq);
  2542. }
  2543. /* conditionally throttle active cfs_rq's from put_prev_entity() */
  2544. static void check_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  2545. {
  2546. if (!cfs_bandwidth_used())
  2547. return;
  2548. if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0))
  2549. return;
  2550. /*
  2551. * it's possible for a throttled entity to be forced into a running
  2552. * state (e.g. set_curr_task), in this case we're finished.
  2553. */
  2554. if (cfs_rq_throttled(cfs_rq))
  2555. return;
  2556. throttle_cfs_rq(cfs_rq);
  2557. }
  2558. static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer)
  2559. {
  2560. struct cfs_bandwidth *cfs_b =
  2561. container_of(timer, struct cfs_bandwidth, slack_timer);
  2562. do_sched_cfs_slack_timer(cfs_b);
  2563. return HRTIMER_NORESTART;
  2564. }
  2565. static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)
  2566. {
  2567. struct cfs_bandwidth *cfs_b =
  2568. container_of(timer, struct cfs_bandwidth, period_timer);
  2569. ktime_t now;
  2570. int overrun;
  2571. int idle = 0;
  2572. for (;;) {
  2573. now = hrtimer_cb_get_time(timer);
  2574. overrun = hrtimer_forward(timer, now, cfs_b->period);
  2575. if (!overrun)
  2576. break;
  2577. idle = do_sched_cfs_period_timer(cfs_b, overrun);
  2578. }
  2579. return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
  2580. }
  2581. void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
  2582. {
  2583. raw_spin_lock_init(&cfs_b->lock);
  2584. cfs_b->runtime = 0;
  2585. cfs_b->quota = RUNTIME_INF;
  2586. cfs_b->period = ns_to_ktime(default_cfs_period());
  2587. INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq);
  2588. hrtimer_init(&cfs_b->period_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
  2589. cfs_b->period_timer.function = sched_cfs_period_timer;
  2590. hrtimer_init(&cfs_b->slack_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
  2591. cfs_b->slack_timer.function = sched_cfs_slack_timer;
  2592. }
  2593. static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  2594. {
  2595. cfs_rq->runtime_enabled = 0;
  2596. INIT_LIST_HEAD(&cfs_rq->throttled_list);
  2597. }
  2598. /* requires cfs_b->lock, may release to reprogram timer */
  2599. void __start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
  2600. {
  2601. /*
  2602. * The timer may be active because we're trying to set a new bandwidth
  2603. * period or because we're racing with the tear-down path
  2604. * (timer_active==0 becomes visible before the hrtimer call-back
  2605. * terminates). In either case we ensure that it's re-programmed
  2606. */
  2607. while (unlikely(hrtimer_active(&cfs_b->period_timer))) {
  2608. raw_spin_unlock(&cfs_b->lock);
  2609. /* ensure cfs_b->lock is available while we wait */
  2610. hrtimer_cancel(&cfs_b->period_timer);
  2611. raw_spin_lock(&cfs_b->lock);
  2612. /* if someone else restarted the timer then we're done */
  2613. if (cfs_b->timer_active)
  2614. return;
  2615. }
  2616. cfs_b->timer_active = 1;
  2617. start_bandwidth_timer(&cfs_b->period_timer, cfs_b->period);
  2618. }
  2619. static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
  2620. {
  2621. hrtimer_cancel(&cfs_b->period_timer);
  2622. hrtimer_cancel(&cfs_b->slack_timer);
  2623. }
  2624. static void __maybe_unused unthrottle_offline_cfs_rqs(struct rq *rq)
  2625. {
  2626. struct cfs_rq *cfs_rq;
  2627. for_each_leaf_cfs_rq(rq, cfs_rq) {
  2628. struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
  2629. if (!cfs_rq->runtime_enabled)
  2630. continue;
  2631. /*
  2632. * clock_task is not advancing so we just need to make sure
  2633. * there's some valid quota amount
  2634. */
  2635. cfs_rq->runtime_remaining = cfs_b->quota;
  2636. if (cfs_rq_throttled(cfs_rq))
  2637. unthrottle_cfs_rq(cfs_rq);
  2638. }
  2639. }
  2640. #else /* CONFIG_CFS_BANDWIDTH */
  2641. static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq)
  2642. {
  2643. return rq_clock_task(rq_of(cfs_rq));
  2644. }
  2645. static void account_cfs_rq_runtime(struct cfs_rq *cfs_rq,
  2646. unsigned long delta_exec) {}
  2647. static void check_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
  2648. static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {}
  2649. static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
  2650. static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
  2651. {
  2652. return 0;
  2653. }
  2654. static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
  2655. {
  2656. return 0;
  2657. }
  2658. static inline int throttled_lb_pair(struct task_group *tg,
  2659. int src_cpu, int dest_cpu)
  2660. {
  2661. return 0;
  2662. }
  2663. void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
  2664. #ifdef CONFIG_FAIR_GROUP_SCHED
  2665. static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
  2666. #endif
  2667. static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
  2668. {
  2669. return NULL;
  2670. }
  2671. static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
  2672. static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {}
  2673. #endif /* CONFIG_CFS_BANDWIDTH */
  2674. /**************************************************
  2675. * CFS operations on tasks:
  2676. */
  2677. #ifdef CONFIG_SCHED_HRTICK
  2678. static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
  2679. {
  2680. struct sched_entity *se = &p->se;
  2681. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  2682. WARN_ON(task_rq(p) != rq);
  2683. if (cfs_rq->nr_running > 1) {
  2684. u64 slice = sched_slice(cfs_rq, se);
  2685. u64 ran = se->sum_exec_runtime - se->prev_sum_exec_runtime;
  2686. s64 delta = slice - ran;
  2687. if (delta < 0) {
  2688. if (rq->curr == p)
  2689. resched_task(p);
  2690. return;
  2691. }
  2692. /*
  2693. * Don't schedule slices shorter than 10000ns, that just
  2694. * doesn't make sense. Rely on vruntime for fairness.
  2695. */
  2696. if (rq->curr != p)
  2697. delta = max_t(s64, 10000LL, delta);
  2698. hrtick_start(rq, delta);
  2699. }
  2700. }
  2701. /*
  2702. * called from enqueue/dequeue and updates the hrtick when the
  2703. * current task is from our class and nr_running is low enough
  2704. * to matter.
  2705. */
  2706. static void hrtick_update(struct rq *rq)
  2707. {
  2708. struct task_struct *curr = rq->curr;
  2709. if (!hrtick_enabled(rq) || curr->sched_class != &fair_sched_class)
  2710. return;
  2711. if (cfs_rq_of(&curr->se)->nr_running < sched_nr_latency)
  2712. hrtick_start_fair(rq, curr);
  2713. }
  2714. #else /* !CONFIG_SCHED_HRTICK */
  2715. static inline void
  2716. hrtick_start_fair(struct rq *rq, struct task_struct *p)
  2717. {
  2718. }
  2719. static inline void hrtick_update(struct rq *rq)
  2720. {
  2721. }
  2722. #endif
  2723. /*
  2724. * The enqueue_task method is called before nr_running is
  2725. * increased. Here we update the fair scheduling stats and
  2726. * then put the task into the rbtree:
  2727. */
  2728. static void
  2729. enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
  2730. {
  2731. struct cfs_rq *cfs_rq;
  2732. struct sched_entity *se = &p->se;
  2733. for_each_sched_entity(se) {
  2734. if (se->on_rq)
  2735. break;
  2736. cfs_rq = cfs_rq_of(se);
  2737. enqueue_entity(cfs_rq, se, flags);
  2738. /*
  2739. * end evaluation on encountering a throttled cfs_rq
  2740. *
  2741. * note: in the case of encountering a throttled cfs_rq we will
  2742. * post the final h_nr_running increment below.
  2743. */
  2744. if (cfs_rq_throttled(cfs_rq))
  2745. break;
  2746. cfs_rq->h_nr_running++;
  2747. flags = ENQUEUE_WAKEUP;
  2748. }
  2749. for_each_sched_entity(se) {
  2750. cfs_rq = cfs_rq_of(se);
  2751. cfs_rq->h_nr_running++;
  2752. if (cfs_rq_throttled(cfs_rq))
  2753. break;
  2754. update_cfs_shares(cfs_rq);
  2755. update_entity_load_avg(se, 1);
  2756. }
  2757. if (!se) {
  2758. update_rq_runnable_avg(rq, rq->nr_running);
  2759. inc_nr_running(rq);
  2760. }
  2761. hrtick_update(rq);
  2762. }
  2763. static void set_next_buddy(struct sched_entity *se);
  2764. /*
  2765. * The dequeue_task method is called before nr_running is
  2766. * decreased. We remove the task from the rbtree and
  2767. * update the fair scheduling stats:
  2768. */
  2769. static void dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
  2770. {
  2771. struct cfs_rq *cfs_rq;
  2772. struct sched_entity *se = &p->se;
  2773. int task_sleep = flags & DEQUEUE_SLEEP;
  2774. for_each_sched_entity(se) {
  2775. cfs_rq = cfs_rq_of(se);
  2776. dequeue_entity(cfs_rq, se, flags);
  2777. /*
  2778. * end evaluation on encountering a throttled cfs_rq
  2779. *
  2780. * note: in the case of encountering a throttled cfs_rq we will
  2781. * post the final h_nr_running decrement below.
  2782. */
  2783. if (cfs_rq_throttled(cfs_rq))
  2784. break;
  2785. cfs_rq->h_nr_running--;
  2786. /* Don't dequeue parent if it has other entities besides us */
  2787. if (cfs_rq->load.weight) {
  2788. /*
  2789. * Bias pick_next to pick a task from this cfs_rq, as
  2790. * p is sleeping when it is within its sched_slice.
  2791. */
  2792. if (task_sleep && parent_entity(se))
  2793. set_next_buddy(parent_entity(se));
  2794. /* avoid re-evaluating load for this entity */
  2795. se = parent_entity(se);
  2796. break;
  2797. }
  2798. flags |= DEQUEUE_SLEEP;
  2799. }
  2800. for_each_sched_entity(se) {
  2801. cfs_rq = cfs_rq_of(se);
  2802. cfs_rq->h_nr_running--;
  2803. if (cfs_rq_throttled(cfs_rq))
  2804. break;
  2805. update_cfs_shares(cfs_rq);
  2806. update_entity_load_avg(se, 1);
  2807. }
  2808. if (!se) {
  2809. dec_nr_running(rq);
  2810. update_rq_runnable_avg(rq, 1);
  2811. }
  2812. hrtick_update(rq);
  2813. }
  2814. #ifdef CONFIG_SMP
  2815. /* Used instead of source_load when we know the type == 0 */
  2816. static unsigned long weighted_cpuload(const int cpu)
  2817. {
  2818. return cpu_rq(cpu)->cfs.runnable_load_avg;
  2819. }
  2820. /*
  2821. * Return a low guess at the load of a migration-source cpu weighted
  2822. * according to the scheduling class and "nice" value.
  2823. *
  2824. * We want to under-estimate the load of migration sources, to
  2825. * balance conservatively.
  2826. */
  2827. static unsigned long source_load(int cpu, int type)
  2828. {
  2829. struct rq *rq = cpu_rq(cpu);
  2830. unsigned long total = weighted_cpuload(cpu);
  2831. if (type == 0 || !sched_feat(LB_BIAS))
  2832. return total;
  2833. return min(rq->cpu_load[type-1], total);
  2834. }
  2835. /*
  2836. * Return a high guess at the load of a migration-target cpu weighted
  2837. * according to the scheduling class and "nice" value.
  2838. */
  2839. static unsigned long target_load(int cpu, int type)
  2840. {
  2841. struct rq *rq = cpu_rq(cpu);
  2842. unsigned long total = weighted_cpuload(cpu);
  2843. if (type == 0 || !sched_feat(LB_BIAS))
  2844. return total;
  2845. return max(rq->cpu_load[type-1], total);
  2846. }
  2847. static unsigned long power_of(int cpu)
  2848. {
  2849. return cpu_rq(cpu)->cpu_power;
  2850. }
  2851. static unsigned long cpu_avg_load_per_task(int cpu)
  2852. {
  2853. struct rq *rq = cpu_rq(cpu);
  2854. unsigned long nr_running = ACCESS_ONCE(rq->nr_running);
  2855. unsigned long load_avg = rq->cfs.runnable_load_avg;
  2856. if (nr_running)
  2857. return load_avg / nr_running;
  2858. return 0;
  2859. }
  2860. static void record_wakee(struct task_struct *p)
  2861. {
  2862. /*
  2863. * Rough decay (wiping) for cost saving, don't worry
  2864. * about the boundary, really active task won't care
  2865. * about the loss.
  2866. */
  2867. if (jiffies > current->wakee_flip_decay_ts + HZ) {
  2868. current->wakee_flips = 0;
  2869. current->wakee_flip_decay_ts = jiffies;
  2870. }
  2871. if (current->last_wakee != p) {
  2872. current->last_wakee = p;
  2873. current->wakee_flips++;
  2874. }
  2875. }
  2876. static void task_waking_fair(struct task_struct *p)
  2877. {
  2878. struct sched_entity *se = &p->se;
  2879. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  2880. u64 min_vruntime;
  2881. #ifndef CONFIG_64BIT
  2882. u64 min_vruntime_copy;
  2883. do {
  2884. min_vruntime_copy = cfs_rq->min_vruntime_copy;
  2885. smp_rmb();
  2886. min_vruntime = cfs_rq->min_vruntime;
  2887. } while (min_vruntime != min_vruntime_copy);
  2888. #else
  2889. min_vruntime = cfs_rq->min_vruntime;
  2890. #endif
  2891. se->vruntime -= min_vruntime;
  2892. record_wakee(p);
  2893. }
  2894. #ifdef CONFIG_FAIR_GROUP_SCHED
  2895. /*
  2896. * effective_load() calculates the load change as seen from the root_task_group
  2897. *
  2898. * Adding load to a group doesn't make a group heavier, but can cause movement
  2899. * of group shares between cpus. Assuming the shares were perfectly aligned one
  2900. * can calculate the shift in shares.
  2901. *
  2902. * Calculate the effective load difference if @wl is added (subtracted) to @tg
  2903. * on this @cpu and results in a total addition (subtraction) of @wg to the
  2904. * total group weight.
  2905. *
  2906. * Given a runqueue weight distribution (rw_i) we can compute a shares
  2907. * distribution (s_i) using:
  2908. *
  2909. * s_i = rw_i / \Sum rw_j (1)
  2910. *
  2911. * Suppose we have 4 CPUs and our @tg is a direct child of the root group and
  2912. * has 7 equal weight tasks, distributed as below (rw_i), with the resulting
  2913. * shares distribution (s_i):
  2914. *
  2915. * rw_i = { 2, 4, 1, 0 }
  2916. * s_i = { 2/7, 4/7, 1/7, 0 }
  2917. *
  2918. * As per wake_affine() we're interested in the load of two CPUs (the CPU the
  2919. * task used to run on and the CPU the waker is running on), we need to
  2920. * compute the effect of waking a task on either CPU and, in case of a sync
  2921. * wakeup, compute the effect of the current task going to sleep.
  2922. *
  2923. * So for a change of @wl to the local @cpu with an overall group weight change
  2924. * of @wl we can compute the new shares distribution (s'_i) using:
  2925. *
  2926. * s'_i = (rw_i + @wl) / (@wg + \Sum rw_j) (2)
  2927. *
  2928. * Suppose we're interested in CPUs 0 and 1, and want to compute the load
  2929. * differences in waking a task to CPU 0. The additional task changes the
  2930. * weight and shares distributions like:
  2931. *
  2932. * rw'_i = { 3, 4, 1, 0 }
  2933. * s'_i = { 3/8, 4/8, 1/8, 0 }
  2934. *
  2935. * We can then compute the difference in effective weight by using:
  2936. *
  2937. * dw_i = S * (s'_i - s_i) (3)
  2938. *
  2939. * Where 'S' is the group weight as seen by its parent.
  2940. *
  2941. * Therefore the effective change in loads on CPU 0 would be 5/56 (3/8 - 2/7)
  2942. * times the weight of the group. The effect on CPU 1 would be -4/56 (4/8 -
  2943. * 4/7) times the weight of the group.
  2944. */
  2945. static long effective_load(struct task_group *tg, int cpu, long wl, long wg)
  2946. {
  2947. struct sched_entity *se = tg->se[cpu];
  2948. if (!tg->parent || !wl) /* the trivial, non-cgroup case */
  2949. return wl;
  2950. for_each_sched_entity(se) {
  2951. long w, W;
  2952. tg = se->my_q->tg;
  2953. /*
  2954. * W = @wg + \Sum rw_j
  2955. */
  2956. W = wg + calc_tg_weight(tg, se->my_q);
  2957. /*
  2958. * w = rw_i + @wl
  2959. */
  2960. w = se->my_q->load.weight + wl;
  2961. /*
  2962. * wl = S * s'_i; see (2)
  2963. */
  2964. if (W > 0 && w < W)
  2965. wl = (w * tg->shares) / W;
  2966. else
  2967. wl = tg->shares;
  2968. /*
  2969. * Per the above, wl is the new se->load.weight value; since
  2970. * those are clipped to [MIN_SHARES, ...) do so now. See
  2971. * calc_cfs_shares().
  2972. */
  2973. if (wl < MIN_SHARES)
  2974. wl = MIN_SHARES;
  2975. /*
  2976. * wl = dw_i = S * (s'_i - s_i); see (3)
  2977. */
  2978. wl -= se->load.weight;
  2979. /*
  2980. * Recursively apply this logic to all parent groups to compute
  2981. * the final effective load change on the root group. Since
  2982. * only the @tg group gets extra weight, all parent groups can
  2983. * only redistribute existing shares. @wl is the shift in shares
  2984. * resulting from this level per the above.
  2985. */
  2986. wg = 0;
  2987. }
  2988. return wl;
  2989. }
  2990. #else
  2991. static long effective_load(struct task_group *tg, int cpu, long wl, long wg)
  2992. {
  2993. return wl;
  2994. }
  2995. #endif
  2996. static int wake_wide(struct task_struct *p)
  2997. {
  2998. int factor = this_cpu_read(sd_llc_size);
  2999. /*
  3000. * Yeah, it's the switching-frequency, could means many wakee or
  3001. * rapidly switch, use factor here will just help to automatically
  3002. * adjust the loose-degree, so bigger node will lead to more pull.
  3003. */
  3004. if (p->wakee_flips > factor) {
  3005. /*
  3006. * wakee is somewhat hot, it needs certain amount of cpu
  3007. * resource, so if waker is far more hot, prefer to leave
  3008. * it alone.
  3009. */
  3010. if (current->wakee_flips > (factor * p->wakee_flips))
  3011. return 1;
  3012. }
  3013. return 0;
  3014. }
  3015. static int wake_affine(struct sched_domain *sd, struct task_struct *p, int sync)
  3016. {
  3017. s64 this_load, load;
  3018. int idx, this_cpu, prev_cpu;
  3019. unsigned long tl_per_task;
  3020. struct task_group *tg;
  3021. unsigned long weight;
  3022. int balanced;
  3023. /*
  3024. * If we wake multiple tasks be careful to not bounce
  3025. * ourselves around too much.
  3026. */
  3027. if (wake_wide(p))
  3028. return 0;
  3029. idx = sd->wake_idx;
  3030. this_cpu = smp_processor_id();
  3031. prev_cpu = task_cpu(p);
  3032. load = source_load(prev_cpu, idx);
  3033. this_load = target_load(this_cpu, idx);
  3034. /*
  3035. * If sync wakeup then subtract the (maximum possible)
  3036. * effect of the currently running task from the load
  3037. * of the current CPU:
  3038. */
  3039. if (sync) {
  3040. tg = task_group(current);
  3041. weight = current->se.load.weight;
  3042. this_load += effective_load(tg, this_cpu, -weight, -weight);
  3043. load += effective_load(tg, prev_cpu, 0, -weight);
  3044. }
  3045. tg = task_group(p);
  3046. weight = p->se.load.weight;
  3047. /*
  3048. * In low-load situations, where prev_cpu is idle and this_cpu is idle
  3049. * due to the sync cause above having dropped this_load to 0, we'll
  3050. * always have an imbalance, but there's really nothing you can do
  3051. * about that, so that's good too.
  3052. *
  3053. * Otherwise check if either cpus are near enough in load to allow this
  3054. * task to be woken on this_cpu.
  3055. */
  3056. if (this_load > 0) {
  3057. s64 this_eff_load, prev_eff_load;
  3058. this_eff_load = 100;
  3059. this_eff_load *= power_of(prev_cpu);
  3060. this_eff_load *= this_load +
  3061. effective_load(tg, this_cpu, weight, weight);
  3062. prev_eff_load = 100 + (sd->imbalance_pct - 100) / 2;
  3063. prev_eff_load *= power_of(this_cpu);
  3064. prev_eff_load *= load + effective_load(tg, prev_cpu, 0, weight);
  3065. balanced = this_eff_load <= prev_eff_load;
  3066. } else
  3067. balanced = true;
  3068. /*
  3069. * If the currently running task will sleep within
  3070. * a reasonable amount of time then attract this newly
  3071. * woken task:
  3072. */
  3073. if (sync && balanced)
  3074. return 1;
  3075. schedstat_inc(p, se.statistics.nr_wakeups_affine_attempts);
  3076. tl_per_task = cpu_avg_load_per_task(this_cpu);
  3077. if (balanced ||
  3078. (this_load <= load &&
  3079. this_load + target_load(prev_cpu, idx) <= tl_per_task)) {
  3080. /*
  3081. * This domain has SD_WAKE_AFFINE and
  3082. * p is cache cold in this domain, and
  3083. * there is no bad imbalance.
  3084. */
  3085. schedstat_inc(sd, ttwu_move_affine);
  3086. schedstat_inc(p, se.statistics.nr_wakeups_affine);
  3087. return 1;
  3088. }
  3089. return 0;
  3090. }
  3091. /*
  3092. * find_idlest_group finds and returns the least busy CPU group within the
  3093. * domain.
  3094. */
  3095. static struct sched_group *
  3096. find_idlest_group(struct sched_domain *sd, struct task_struct *p,
  3097. int this_cpu, int load_idx)
  3098. {
  3099. struct sched_group *idlest = NULL, *group = sd->groups;
  3100. unsigned long min_load = ULONG_MAX, this_load = 0;
  3101. int imbalance = 100 + (sd->imbalance_pct-100)/2;
  3102. do {
  3103. unsigned long load, avg_load;
  3104. int local_group;
  3105. int i;
  3106. /* Skip over this group if it has no CPUs allowed */
  3107. if (!cpumask_intersects(sched_group_cpus(group),
  3108. tsk_cpus_allowed(p)))
  3109. continue;
  3110. local_group = cpumask_test_cpu(this_cpu,
  3111. sched_group_cpus(group));
  3112. /* Tally up the load of all CPUs in the group */
  3113. avg_load = 0;
  3114. for_each_cpu(i, sched_group_cpus(group)) {
  3115. /* Bias balancing toward cpus of our domain */
  3116. if (local_group)
  3117. load = source_load(i, load_idx);
  3118. else
  3119. load = target_load(i, load_idx);
  3120. avg_load += load;
  3121. }
  3122. /* Adjust by relative CPU power of the group */
  3123. avg_load = (avg_load * SCHED_POWER_SCALE) / group->sgp->power;
  3124. if (local_group) {
  3125. this_load = avg_load;
  3126. } else if (avg_load < min_load) {
  3127. min_load = avg_load;
  3128. idlest = group;
  3129. }
  3130. } while (group = group->next, group != sd->groups);
  3131. if (!idlest || 100*this_load < imbalance*min_load)
  3132. return NULL;
  3133. return idlest;
  3134. }
  3135. /*
  3136. * find_idlest_cpu - find the idlest cpu among the cpus in group.
  3137. */
  3138. static int
  3139. find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
  3140. {
  3141. unsigned long load, min_load = ULONG_MAX;
  3142. int idlest = -1;
  3143. int i;
  3144. /* Traverse only the allowed CPUs */
  3145. for_each_cpu_and(i, sched_group_cpus(group), tsk_cpus_allowed(p)) {
  3146. load = weighted_cpuload(i);
  3147. if (load < min_load || (load == min_load && i == this_cpu)) {
  3148. min_load = load;
  3149. idlest = i;
  3150. }
  3151. }
  3152. return idlest;
  3153. }
  3154. /*
  3155. * Try and locate an idle CPU in the sched_domain.
  3156. */
  3157. static int select_idle_sibling(struct task_struct *p, int target)
  3158. {
  3159. struct sched_domain *sd;
  3160. struct sched_group *sg;
  3161. int i = task_cpu(p);
  3162. if (idle_cpu(target))
  3163. return target;
  3164. /*
  3165. * If the prevous cpu is cache affine and idle, don't be stupid.
  3166. */
  3167. if (i != target && cpus_share_cache(i, target) && idle_cpu(i))
  3168. return i;
  3169. /*
  3170. * Otherwise, iterate the domains and find an elegible idle cpu.
  3171. */
  3172. sd = rcu_dereference(per_cpu(sd_llc, target));
  3173. for_each_lower_domain(sd) {
  3174. sg = sd->groups;
  3175. do {
  3176. if (!cpumask_intersects(sched_group_cpus(sg),
  3177. tsk_cpus_allowed(p)))
  3178. goto next;
  3179. for_each_cpu(i, sched_group_cpus(sg)) {
  3180. if (i == target || !idle_cpu(i))
  3181. goto next;
  3182. }
  3183. target = cpumask_first_and(sched_group_cpus(sg),
  3184. tsk_cpus_allowed(p));
  3185. goto done;
  3186. next:
  3187. sg = sg->next;
  3188. } while (sg != sd->groups);
  3189. }
  3190. done:
  3191. return target;
  3192. }
  3193. /*
  3194. * sched_balance_self: balance the current task (running on cpu) in domains
  3195. * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
  3196. * SD_BALANCE_EXEC.
  3197. *
  3198. * Balance, ie. select the least loaded group.
  3199. *
  3200. * Returns the target CPU number, or the same CPU if no balancing is needed.
  3201. *
  3202. * preempt must be disabled.
  3203. */
  3204. static int
  3205. select_task_rq_fair(struct task_struct *p, int prev_cpu, int sd_flag, int wake_flags)
  3206. {
  3207. struct sched_domain *tmp, *affine_sd = NULL, *sd = NULL;
  3208. int cpu = smp_processor_id();
  3209. int new_cpu = cpu;
  3210. int want_affine = 0;
  3211. int sync = wake_flags & WF_SYNC;
  3212. if (p->nr_cpus_allowed == 1)
  3213. return prev_cpu;
  3214. if (sd_flag & SD_BALANCE_WAKE) {
  3215. if (cpumask_test_cpu(cpu, tsk_cpus_allowed(p)))
  3216. want_affine = 1;
  3217. new_cpu = prev_cpu;
  3218. }
  3219. rcu_read_lock();
  3220. for_each_domain(cpu, tmp) {
  3221. if (!(tmp->flags & SD_LOAD_BALANCE))
  3222. continue;
  3223. /*
  3224. * If both cpu and prev_cpu are part of this domain,
  3225. * cpu is a valid SD_WAKE_AFFINE target.
  3226. */
  3227. if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
  3228. cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
  3229. affine_sd = tmp;
  3230. break;
  3231. }
  3232. if (tmp->flags & sd_flag)
  3233. sd = tmp;
  3234. }
  3235. if (affine_sd) {
  3236. if (cpu != prev_cpu && wake_affine(affine_sd, p, sync))
  3237. prev_cpu = cpu;
  3238. new_cpu = select_idle_sibling(p, prev_cpu);
  3239. goto unlock;
  3240. }
  3241. while (sd) {
  3242. int load_idx = sd->forkexec_idx;
  3243. struct sched_group *group;
  3244. int weight;
  3245. if (!(sd->flags & sd_flag)) {
  3246. sd = sd->child;
  3247. continue;
  3248. }
  3249. if (sd_flag & SD_BALANCE_WAKE)
  3250. load_idx = sd->wake_idx;
  3251. group = find_idlest_group(sd, p, cpu, load_idx);
  3252. if (!group) {
  3253. sd = sd->child;
  3254. continue;
  3255. }
  3256. new_cpu = find_idlest_cpu(group, p, cpu);
  3257. if (new_cpu == -1 || new_cpu == cpu) {
  3258. /* Now try balancing at a lower domain level of cpu */
  3259. sd = sd->child;
  3260. continue;
  3261. }
  3262. /* Now try balancing at a lower domain level of new_cpu */
  3263. cpu = new_cpu;
  3264. weight = sd->span_weight;
  3265. sd = NULL;
  3266. for_each_domain(cpu, tmp) {
  3267. if (weight <= tmp->span_weight)
  3268. break;
  3269. if (tmp->flags & sd_flag)
  3270. sd = tmp;
  3271. }
  3272. /* while loop will break here if sd == NULL */
  3273. }
  3274. unlock:
  3275. rcu_read_unlock();
  3276. return new_cpu;
  3277. }
  3278. /*
  3279. * Called immediately before a task is migrated to a new cpu; task_cpu(p) and
  3280. * cfs_rq_of(p) references at time of call are still valid and identify the
  3281. * previous cpu. However, the caller only guarantees p->pi_lock is held; no
  3282. * other assumptions, including the state of rq->lock, should be made.
  3283. */
  3284. static void
  3285. migrate_task_rq_fair(struct task_struct *p, int next_cpu)
  3286. {
  3287. struct sched_entity *se = &p->se;
  3288. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  3289. /*
  3290. * Load tracking: accumulate removed load so that it can be processed
  3291. * when we next update owning cfs_rq under rq->lock. Tasks contribute
  3292. * to blocked load iff they have a positive decay-count. It can never
  3293. * be negative here since on-rq tasks have decay-count == 0.
  3294. */
  3295. if (se->avg.decay_count) {
  3296. se->avg.decay_count = -__synchronize_entity_decay(se);
  3297. atomic_long_add(se->avg.load_avg_contrib,
  3298. &cfs_rq->removed_load);
  3299. }
  3300. }
  3301. #endif /* CONFIG_SMP */
  3302. static unsigned long
  3303. wakeup_gran(struct sched_entity *curr, struct sched_entity *se)
  3304. {
  3305. unsigned long gran = sysctl_sched_wakeup_granularity;
  3306. /*
  3307. * Since its curr running now, convert the gran from real-time
  3308. * to virtual-time in his units.
  3309. *
  3310. * By using 'se' instead of 'curr' we penalize light tasks, so
  3311. * they get preempted easier. That is, if 'se' < 'curr' then
  3312. * the resulting gran will be larger, therefore penalizing the
  3313. * lighter, if otoh 'se' > 'curr' then the resulting gran will
  3314. * be smaller, again penalizing the lighter task.
  3315. *
  3316. * This is especially important for buddies when the leftmost
  3317. * task is higher priority than the buddy.
  3318. */
  3319. return calc_delta_fair(gran, se);
  3320. }
  3321. /*
  3322. * Should 'se' preempt 'curr'.
  3323. *
  3324. * |s1
  3325. * |s2
  3326. * |s3
  3327. * g
  3328. * |<--->|c
  3329. *
  3330. * w(c, s1) = -1
  3331. * w(c, s2) = 0
  3332. * w(c, s3) = 1
  3333. *
  3334. */
  3335. static int
  3336. wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se)
  3337. {
  3338. s64 gran, vdiff = curr->vruntime - se->vruntime;
  3339. if (vdiff <= 0)
  3340. return -1;
  3341. gran = wakeup_gran(curr, se);
  3342. if (vdiff > gran)
  3343. return 1;
  3344. return 0;
  3345. }
  3346. static void set_last_buddy(struct sched_entity *se)
  3347. {
  3348. if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE))
  3349. return;
  3350. for_each_sched_entity(se)
  3351. cfs_rq_of(se)->last = se;
  3352. }
  3353. static void set_next_buddy(struct sched_entity *se)
  3354. {
  3355. if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE))
  3356. return;
  3357. for_each_sched_entity(se)
  3358. cfs_rq_of(se)->next = se;
  3359. }
  3360. static void set_skip_buddy(struct sched_entity *se)
  3361. {
  3362. for_each_sched_entity(se)
  3363. cfs_rq_of(se)->skip = se;
  3364. }
  3365. /*
  3366. * Preempt the current task with a newly woken task if needed:
  3367. */
  3368. static void check_preempt_wakeup(struct rq *rq, struct task_struct *p, int wake_flags)
  3369. {
  3370. struct task_struct *curr = rq->curr;
  3371. struct sched_entity *se = &curr->se, *pse = &p->se;
  3372. struct cfs_rq *cfs_rq = task_cfs_rq(curr);
  3373. int scale = cfs_rq->nr_running >= sched_nr_latency;
  3374. int next_buddy_marked = 0;
  3375. if (unlikely(se == pse))
  3376. return;
  3377. /*
  3378. * This is possible from callers such as move_task(), in which we
  3379. * unconditionally check_prempt_curr() after an enqueue (which may have
  3380. * lead to a throttle). This both saves work and prevents false
  3381. * next-buddy nomination below.
  3382. */
  3383. if (unlikely(throttled_hierarchy(cfs_rq_of(pse))))
  3384. return;
  3385. if (sched_feat(NEXT_BUDDY) && scale && !(wake_flags & WF_FORK)) {
  3386. set_next_buddy(pse);
  3387. next_buddy_marked = 1;
  3388. }
  3389. /*
  3390. * We can come here with TIF_NEED_RESCHED already set from new task
  3391. * wake up path.
  3392. *
  3393. * Note: this also catches the edge-case of curr being in a throttled
  3394. * group (e.g. via set_curr_task), since update_curr() (in the
  3395. * enqueue of curr) will have resulted in resched being set. This
  3396. * prevents us from potentially nominating it as a false LAST_BUDDY
  3397. * below.
  3398. */
  3399. if (test_tsk_need_resched(curr))
  3400. return;
  3401. /* Idle tasks are by definition preempted by non-idle tasks. */
  3402. if (unlikely(curr->policy == SCHED_IDLE) &&
  3403. likely(p->policy != SCHED_IDLE))
  3404. goto preempt;
  3405. /*
  3406. * Batch and idle tasks do not preempt non-idle tasks (their preemption
  3407. * is driven by the tick):
  3408. */
  3409. if (unlikely(p->policy != SCHED_NORMAL) || !sched_feat(WAKEUP_PREEMPTION))
  3410. return;
  3411. find_matching_se(&se, &pse);
  3412. update_curr(cfs_rq_of(se));
  3413. BUG_ON(!pse);
  3414. if (wakeup_preempt_entity(se, pse) == 1) {
  3415. /*
  3416. * Bias pick_next to pick the sched entity that is
  3417. * triggering this preemption.
  3418. */
  3419. if (!next_buddy_marked)
  3420. set_next_buddy(pse);
  3421. goto preempt;
  3422. }
  3423. return;
  3424. preempt:
  3425. resched_task(curr);
  3426. /*
  3427. * Only set the backward buddy when the current task is still
  3428. * on the rq. This can happen when a wakeup gets interleaved
  3429. * with schedule on the ->pre_schedule() or idle_balance()
  3430. * point, either of which can * drop the rq lock.
  3431. *
  3432. * Also, during early boot the idle thread is in the fair class,
  3433. * for obvious reasons its a bad idea to schedule back to it.
  3434. */
  3435. if (unlikely(!se->on_rq || curr == rq->idle))
  3436. return;
  3437. if (sched_feat(LAST_BUDDY) && scale && entity_is_task(se))
  3438. set_last_buddy(se);
  3439. }
  3440. static struct task_struct *pick_next_task_fair(struct rq *rq)
  3441. {
  3442. struct task_struct *p;
  3443. struct cfs_rq *cfs_rq = &rq->cfs;
  3444. struct sched_entity *se;
  3445. if (!cfs_rq->nr_running)
  3446. return NULL;
  3447. do {
  3448. se = pick_next_entity(cfs_rq);
  3449. set_next_entity(cfs_rq, se);
  3450. cfs_rq = group_cfs_rq(se);
  3451. } while (cfs_rq);
  3452. p = task_of(se);
  3453. if (hrtick_enabled(rq))
  3454. hrtick_start_fair(rq, p);
  3455. return p;
  3456. }
  3457. /*
  3458. * Account for a descheduled task:
  3459. */
  3460. static void put_prev_task_fair(struct rq *rq, struct task_struct *prev)
  3461. {
  3462. struct sched_entity *se = &prev->se;
  3463. struct cfs_rq *cfs_rq;
  3464. for_each_sched_entity(se) {
  3465. cfs_rq = cfs_rq_of(se);
  3466. put_prev_entity(cfs_rq, se);
  3467. }
  3468. }
  3469. /*
  3470. * sched_yield() is very simple
  3471. *
  3472. * The magic of dealing with the ->skip buddy is in pick_next_entity.
  3473. */
  3474. static void yield_task_fair(struct rq *rq)
  3475. {
  3476. struct task_struct *curr = rq->curr;
  3477. struct cfs_rq *cfs_rq = task_cfs_rq(curr);
  3478. struct sched_entity *se = &curr->se;
  3479. /*
  3480. * Are we the only task in the tree?
  3481. */
  3482. if (unlikely(rq->nr_running == 1))
  3483. return;
  3484. clear_buddies(cfs_rq, se);
  3485. if (curr->policy != SCHED_BATCH) {
  3486. update_rq_clock(rq);
  3487. /*
  3488. * Update run-time statistics of the 'current'.
  3489. */
  3490. update_curr(cfs_rq);
  3491. /*
  3492. * Tell update_rq_clock() that we've just updated,
  3493. * so we don't do microscopic update in schedule()
  3494. * and double the fastpath cost.
  3495. */
  3496. rq->skip_clock_update = 1;
  3497. }
  3498. set_skip_buddy(se);
  3499. }
  3500. static bool yield_to_task_fair(struct rq *rq, struct task_struct *p, bool preempt)
  3501. {
  3502. struct sched_entity *se = &p->se;
  3503. /* throttled hierarchies are not runnable */
  3504. if (!se->on_rq || throttled_hierarchy(cfs_rq_of(se)))
  3505. return false;
  3506. /* Tell the scheduler that we'd really like pse to run next. */
  3507. set_next_buddy(se);
  3508. yield_task_fair(rq);
  3509. return true;
  3510. }
  3511. #ifdef CONFIG_SMP
  3512. /**************************************************
  3513. * Fair scheduling class load-balancing methods.
  3514. *
  3515. * BASICS
  3516. *
  3517. * The purpose of load-balancing is to achieve the same basic fairness the
  3518. * per-cpu scheduler provides, namely provide a proportional amount of compute
  3519. * time to each task. This is expressed in the following equation:
  3520. *
  3521. * W_i,n/P_i == W_j,n/P_j for all i,j (1)
  3522. *
  3523. * Where W_i,n is the n-th weight average for cpu i. The instantaneous weight
  3524. * W_i,0 is defined as:
  3525. *
  3526. * W_i,0 = \Sum_j w_i,j (2)
  3527. *
  3528. * Where w_i,j is the weight of the j-th runnable task on cpu i. This weight
  3529. * is derived from the nice value as per prio_to_weight[].
  3530. *
  3531. * The weight average is an exponential decay average of the instantaneous
  3532. * weight:
  3533. *
  3534. * W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0 (3)
  3535. *
  3536. * P_i is the cpu power (or compute capacity) of cpu i, typically it is the
  3537. * fraction of 'recent' time available for SCHED_OTHER task execution. But it
  3538. * can also include other factors [XXX].
  3539. *
  3540. * To achieve this balance we define a measure of imbalance which follows
  3541. * directly from (1):
  3542. *
  3543. * imb_i,j = max{ avg(W/P), W_i/P_i } - min{ avg(W/P), W_j/P_j } (4)
  3544. *
  3545. * We them move tasks around to minimize the imbalance. In the continuous
  3546. * function space it is obvious this converges, in the discrete case we get
  3547. * a few fun cases generally called infeasible weight scenarios.
  3548. *
  3549. * [XXX expand on:
  3550. * - infeasible weights;
  3551. * - local vs global optima in the discrete case. ]
  3552. *
  3553. *
  3554. * SCHED DOMAINS
  3555. *
  3556. * In order to solve the imbalance equation (4), and avoid the obvious O(n^2)
  3557. * for all i,j solution, we create a tree of cpus that follows the hardware
  3558. * topology where each level pairs two lower groups (or better). This results
  3559. * in O(log n) layers. Furthermore we reduce the number of cpus going up the
  3560. * tree to only the first of the previous level and we decrease the frequency
  3561. * of load-balance at each level inv. proportional to the number of cpus in
  3562. * the groups.
  3563. *
  3564. * This yields:
  3565. *
  3566. * log_2 n 1 n
  3567. * \Sum { --- * --- * 2^i } = O(n) (5)
  3568. * i = 0 2^i 2^i
  3569. * `- size of each group
  3570. * | | `- number of cpus doing load-balance
  3571. * | `- freq
  3572. * `- sum over all levels
  3573. *
  3574. * Coupled with a limit on how many tasks we can migrate every balance pass,
  3575. * this makes (5) the runtime complexity of the balancer.
  3576. *
  3577. * An important property here is that each CPU is still (indirectly) connected
  3578. * to every other cpu in at most O(log n) steps:
  3579. *
  3580. * The adjacency matrix of the resulting graph is given by:
  3581. *
  3582. * log_2 n
  3583. * A_i,j = \Union (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1) (6)
  3584. * k = 0
  3585. *
  3586. * And you'll find that:
  3587. *
  3588. * A^(log_2 n)_i,j != 0 for all i,j (7)
  3589. *
  3590. * Showing there's indeed a path between every cpu in at most O(log n) steps.
  3591. * The task movement gives a factor of O(m), giving a convergence complexity
  3592. * of:
  3593. *
  3594. * O(nm log n), n := nr_cpus, m := nr_tasks (8)
  3595. *
  3596. *
  3597. * WORK CONSERVING
  3598. *
  3599. * In order to avoid CPUs going idle while there's still work to do, new idle
  3600. * balancing is more aggressive and has the newly idle cpu iterate up the domain
  3601. * tree itself instead of relying on other CPUs to bring it work.
  3602. *
  3603. * This adds some complexity to both (5) and (8) but it reduces the total idle
  3604. * time.
  3605. *
  3606. * [XXX more?]
  3607. *
  3608. *
  3609. * CGROUPS
  3610. *
  3611. * Cgroups make a horror show out of (2), instead of a simple sum we get:
  3612. *
  3613. * s_k,i
  3614. * W_i,0 = \Sum_j \Prod_k w_k * ----- (9)
  3615. * S_k
  3616. *
  3617. * Where
  3618. *
  3619. * s_k,i = \Sum_j w_i,j,k and S_k = \Sum_i s_k,i (10)
  3620. *
  3621. * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on cpu i.
  3622. *
  3623. * The big problem is S_k, its a global sum needed to compute a local (W_i)
  3624. * property.
  3625. *
  3626. * [XXX write more on how we solve this.. _after_ merging pjt's patches that
  3627. * rewrite all of this once again.]
  3628. */
  3629. static unsigned long __read_mostly max_load_balance_interval = HZ/10;
  3630. #define LBF_ALL_PINNED 0x01
  3631. #define LBF_NEED_BREAK 0x02
  3632. #define LBF_DST_PINNED 0x04
  3633. #define LBF_SOME_PINNED 0x08
  3634. struct lb_env {
  3635. struct sched_domain *sd;
  3636. struct rq *src_rq;
  3637. int src_cpu;
  3638. int dst_cpu;
  3639. struct rq *dst_rq;
  3640. struct cpumask *dst_grpmask;
  3641. int new_dst_cpu;
  3642. enum cpu_idle_type idle;
  3643. long imbalance;
  3644. /* The set of CPUs under consideration for load-balancing */
  3645. struct cpumask *cpus;
  3646. unsigned int flags;
  3647. unsigned int loop;
  3648. unsigned int loop_break;
  3649. unsigned int loop_max;
  3650. };
  3651. /*
  3652. * move_task - move a task from one runqueue to another runqueue.
  3653. * Both runqueues must be locked.
  3654. */
  3655. static void move_task(struct task_struct *p, struct lb_env *env)
  3656. {
  3657. deactivate_task(env->src_rq, p, 0);
  3658. set_task_cpu(p, env->dst_cpu);
  3659. activate_task(env->dst_rq, p, 0);
  3660. check_preempt_curr(env->dst_rq, p, 0);
  3661. #ifdef CONFIG_NUMA_BALANCING
  3662. if (p->numa_preferred_nid != -1) {
  3663. int src_nid = cpu_to_node(env->src_cpu);
  3664. int dst_nid = cpu_to_node(env->dst_cpu);
  3665. /*
  3666. * If the load balancer has moved the task then limit
  3667. * migrations from taking place in the short term in
  3668. * case this is a short-lived migration.
  3669. */
  3670. if (src_nid != dst_nid && dst_nid != p->numa_preferred_nid)
  3671. p->numa_migrate_seq = 0;
  3672. }
  3673. #endif
  3674. }
  3675. /*
  3676. * Is this task likely cache-hot:
  3677. */
  3678. static int
  3679. task_hot(struct task_struct *p, u64 now, struct sched_domain *sd)
  3680. {
  3681. s64 delta;
  3682. if (p->sched_class != &fair_sched_class)
  3683. return 0;
  3684. if (unlikely(p->policy == SCHED_IDLE))
  3685. return 0;
  3686. /*
  3687. * Buddy candidates are cache hot:
  3688. */
  3689. if (sched_feat(CACHE_HOT_BUDDY) && this_rq()->nr_running &&
  3690. (&p->se == cfs_rq_of(&p->se)->next ||
  3691. &p->se == cfs_rq_of(&p->se)->last))
  3692. return 1;
  3693. if (sysctl_sched_migration_cost == -1)
  3694. return 1;
  3695. if (sysctl_sched_migration_cost == 0)
  3696. return 0;
  3697. delta = now - p->se.exec_start;
  3698. return delta < (s64)sysctl_sched_migration_cost;
  3699. }
  3700. #ifdef CONFIG_NUMA_BALANCING
  3701. /* Returns true if the destination node has incurred more faults */
  3702. static bool migrate_improves_locality(struct task_struct *p, struct lb_env *env)
  3703. {
  3704. int src_nid, dst_nid;
  3705. if (!sched_feat(NUMA_FAVOUR_HIGHER) || !p->numa_faults ||
  3706. !(env->sd->flags & SD_NUMA)) {
  3707. return false;
  3708. }
  3709. src_nid = cpu_to_node(env->src_cpu);
  3710. dst_nid = cpu_to_node(env->dst_cpu);
  3711. if (src_nid == dst_nid ||
  3712. p->numa_migrate_seq >= sysctl_numa_balancing_settle_count)
  3713. return false;
  3714. if (dst_nid == p->numa_preferred_nid ||
  3715. task_faults(p, dst_nid) > task_faults(p, src_nid))
  3716. return true;
  3717. return false;
  3718. }
  3719. static bool migrate_degrades_locality(struct task_struct *p, struct lb_env *env)
  3720. {
  3721. int src_nid, dst_nid;
  3722. if (!sched_feat(NUMA) || !sched_feat(NUMA_RESIST_LOWER))
  3723. return false;
  3724. if (!p->numa_faults || !(env->sd->flags & SD_NUMA))
  3725. return false;
  3726. src_nid = cpu_to_node(env->src_cpu);
  3727. dst_nid = cpu_to_node(env->dst_cpu);
  3728. if (src_nid == dst_nid ||
  3729. p->numa_migrate_seq >= sysctl_numa_balancing_settle_count)
  3730. return false;
  3731. if (task_faults(p, dst_nid) < task_faults(p, src_nid))
  3732. return true;
  3733. return false;
  3734. }
  3735. #else
  3736. static inline bool migrate_improves_locality(struct task_struct *p,
  3737. struct lb_env *env)
  3738. {
  3739. return false;
  3740. }
  3741. static inline bool migrate_degrades_locality(struct task_struct *p,
  3742. struct lb_env *env)
  3743. {
  3744. return false;
  3745. }
  3746. #endif
  3747. /*
  3748. * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
  3749. */
  3750. static
  3751. int can_migrate_task(struct task_struct *p, struct lb_env *env)
  3752. {
  3753. int tsk_cache_hot = 0;
  3754. /*
  3755. * We do not migrate tasks that are:
  3756. * 1) throttled_lb_pair, or
  3757. * 2) cannot be migrated to this CPU due to cpus_allowed, or
  3758. * 3) running (obviously), or
  3759. * 4) are cache-hot on their current CPU.
  3760. */
  3761. if (throttled_lb_pair(task_group(p), env->src_cpu, env->dst_cpu))
  3762. return 0;
  3763. if (!cpumask_test_cpu(env->dst_cpu, tsk_cpus_allowed(p))) {
  3764. int cpu;
  3765. schedstat_inc(p, se.statistics.nr_failed_migrations_affine);
  3766. env->flags |= LBF_SOME_PINNED;
  3767. /*
  3768. * Remember if this task can be migrated to any other cpu in
  3769. * our sched_group. We may want to revisit it if we couldn't
  3770. * meet load balance goals by pulling other tasks on src_cpu.
  3771. *
  3772. * Also avoid computing new_dst_cpu if we have already computed
  3773. * one in current iteration.
  3774. */
  3775. if (!env->dst_grpmask || (env->flags & LBF_DST_PINNED))
  3776. return 0;
  3777. /* Prevent to re-select dst_cpu via env's cpus */
  3778. for_each_cpu_and(cpu, env->dst_grpmask, env->cpus) {
  3779. if (cpumask_test_cpu(cpu, tsk_cpus_allowed(p))) {
  3780. env->flags |= LBF_DST_PINNED;
  3781. env->new_dst_cpu = cpu;
  3782. break;
  3783. }
  3784. }
  3785. return 0;
  3786. }
  3787. /* Record that we found atleast one task that could run on dst_cpu */
  3788. env->flags &= ~LBF_ALL_PINNED;
  3789. if (task_running(env->src_rq, p)) {
  3790. schedstat_inc(p, se.statistics.nr_failed_migrations_running);
  3791. return 0;
  3792. }
  3793. /*
  3794. * Aggressive migration if:
  3795. * 1) destination numa is preferred
  3796. * 2) task is cache cold, or
  3797. * 3) too many balance attempts have failed.
  3798. */
  3799. tsk_cache_hot = task_hot(p, rq_clock_task(env->src_rq), env->sd);
  3800. if (!tsk_cache_hot)
  3801. tsk_cache_hot = migrate_degrades_locality(p, env);
  3802. if (migrate_improves_locality(p, env)) {
  3803. #ifdef CONFIG_SCHEDSTATS
  3804. if (tsk_cache_hot) {
  3805. schedstat_inc(env->sd, lb_hot_gained[env->idle]);
  3806. schedstat_inc(p, se.statistics.nr_forced_migrations);
  3807. }
  3808. #endif
  3809. return 1;
  3810. }
  3811. if (!tsk_cache_hot ||
  3812. env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
  3813. if (tsk_cache_hot) {
  3814. schedstat_inc(env->sd, lb_hot_gained[env->idle]);
  3815. schedstat_inc(p, se.statistics.nr_forced_migrations);
  3816. }
  3817. return 1;
  3818. }
  3819. schedstat_inc(p, se.statistics.nr_failed_migrations_hot);
  3820. return 0;
  3821. }
  3822. /*
  3823. * move_one_task tries to move exactly one task from busiest to this_rq, as
  3824. * part of active balancing operations within "domain".
  3825. * Returns 1 if successful and 0 otherwise.
  3826. *
  3827. * Called with both runqueues locked.
  3828. */
  3829. static int move_one_task(struct lb_env *env)
  3830. {
  3831. struct task_struct *p, *n;
  3832. list_for_each_entry_safe(p, n, &env->src_rq->cfs_tasks, se.group_node) {
  3833. if (!can_migrate_task(p, env))
  3834. continue;
  3835. move_task(p, env);
  3836. /*
  3837. * Right now, this is only the second place move_task()
  3838. * is called, so we can safely collect move_task()
  3839. * stats here rather than inside move_task().
  3840. */
  3841. schedstat_inc(env->sd, lb_gained[env->idle]);
  3842. return 1;
  3843. }
  3844. return 0;
  3845. }
  3846. static const unsigned int sched_nr_migrate_break = 32;
  3847. /*
  3848. * move_tasks tries to move up to imbalance weighted load from busiest to
  3849. * this_rq, as part of a balancing operation within domain "sd".
  3850. * Returns 1 if successful and 0 otherwise.
  3851. *
  3852. * Called with both runqueues locked.
  3853. */
  3854. static int move_tasks(struct lb_env *env)
  3855. {
  3856. struct list_head *tasks = &env->src_rq->cfs_tasks;
  3857. struct task_struct *p;
  3858. unsigned long load;
  3859. int pulled = 0;
  3860. if (env->imbalance <= 0)
  3861. return 0;
  3862. while (!list_empty(tasks)) {
  3863. p = list_first_entry(tasks, struct task_struct, se.group_node);
  3864. env->loop++;
  3865. /* We've more or less seen every task there is, call it quits */
  3866. if (env->loop > env->loop_max)
  3867. break;
  3868. /* take a breather every nr_migrate tasks */
  3869. if (env->loop > env->loop_break) {
  3870. env->loop_break += sched_nr_migrate_break;
  3871. env->flags |= LBF_NEED_BREAK;
  3872. break;
  3873. }
  3874. if (!can_migrate_task(p, env))
  3875. goto next;
  3876. load = task_h_load(p);
  3877. if (sched_feat(LB_MIN) && load < 16 && !env->sd->nr_balance_failed)
  3878. goto next;
  3879. if ((load / 2) > env->imbalance)
  3880. goto next;
  3881. move_task(p, env);
  3882. pulled++;
  3883. env->imbalance -= load;
  3884. #ifdef CONFIG_PREEMPT
  3885. /*
  3886. * NEWIDLE balancing is a source of latency, so preemptible
  3887. * kernels will stop after the first task is pulled to minimize
  3888. * the critical section.
  3889. */
  3890. if (env->idle == CPU_NEWLY_IDLE)
  3891. break;
  3892. #endif
  3893. /*
  3894. * We only want to steal up to the prescribed amount of
  3895. * weighted load.
  3896. */
  3897. if (env->imbalance <= 0)
  3898. break;
  3899. continue;
  3900. next:
  3901. list_move_tail(&p->se.group_node, tasks);
  3902. }
  3903. /*
  3904. * Right now, this is one of only two places move_task() is called,
  3905. * so we can safely collect move_task() stats here rather than
  3906. * inside move_task().
  3907. */
  3908. schedstat_add(env->sd, lb_gained[env->idle], pulled);
  3909. return pulled;
  3910. }
  3911. #ifdef CONFIG_FAIR_GROUP_SCHED
  3912. /*
  3913. * update tg->load_weight by folding this cpu's load_avg
  3914. */
  3915. static void __update_blocked_averages_cpu(struct task_group *tg, int cpu)
  3916. {
  3917. struct sched_entity *se = tg->se[cpu];
  3918. struct cfs_rq *cfs_rq = tg->cfs_rq[cpu];
  3919. /* throttled entities do not contribute to load */
  3920. if (throttled_hierarchy(cfs_rq))
  3921. return;
  3922. update_cfs_rq_blocked_load(cfs_rq, 1);
  3923. if (se) {
  3924. update_entity_load_avg(se, 1);
  3925. /*
  3926. * We pivot on our runnable average having decayed to zero for
  3927. * list removal. This generally implies that all our children
  3928. * have also been removed (modulo rounding error or bandwidth
  3929. * control); however, such cases are rare and we can fix these
  3930. * at enqueue.
  3931. *
  3932. * TODO: fix up out-of-order children on enqueue.
  3933. */
  3934. if (!se->avg.runnable_avg_sum && !cfs_rq->nr_running)
  3935. list_del_leaf_cfs_rq(cfs_rq);
  3936. } else {
  3937. struct rq *rq = rq_of(cfs_rq);
  3938. update_rq_runnable_avg(rq, rq->nr_running);
  3939. }
  3940. }
  3941. static void update_blocked_averages(int cpu)
  3942. {
  3943. struct rq *rq = cpu_rq(cpu);
  3944. struct cfs_rq *cfs_rq;
  3945. unsigned long flags;
  3946. raw_spin_lock_irqsave(&rq->lock, flags);
  3947. update_rq_clock(rq);
  3948. /*
  3949. * Iterates the task_group tree in a bottom up fashion, see
  3950. * list_add_leaf_cfs_rq() for details.
  3951. */
  3952. for_each_leaf_cfs_rq(rq, cfs_rq) {
  3953. /*
  3954. * Note: We may want to consider periodically releasing
  3955. * rq->lock about these updates so that creating many task
  3956. * groups does not result in continually extending hold time.
  3957. */
  3958. __update_blocked_averages_cpu(cfs_rq->tg, rq->cpu);
  3959. }
  3960. raw_spin_unlock_irqrestore(&rq->lock, flags);
  3961. }
  3962. /*
  3963. * Compute the hierarchical load factor for cfs_rq and all its ascendants.
  3964. * This needs to be done in a top-down fashion because the load of a child
  3965. * group is a fraction of its parents load.
  3966. */
  3967. static void update_cfs_rq_h_load(struct cfs_rq *cfs_rq)
  3968. {
  3969. struct rq *rq = rq_of(cfs_rq);
  3970. struct sched_entity *se = cfs_rq->tg->se[cpu_of(rq)];
  3971. unsigned long now = jiffies;
  3972. unsigned long load;
  3973. if (cfs_rq->last_h_load_update == now)
  3974. return;
  3975. cfs_rq->h_load_next = NULL;
  3976. for_each_sched_entity(se) {
  3977. cfs_rq = cfs_rq_of(se);
  3978. cfs_rq->h_load_next = se;
  3979. if (cfs_rq->last_h_load_update == now)
  3980. break;
  3981. }
  3982. if (!se) {
  3983. cfs_rq->h_load = cfs_rq->runnable_load_avg;
  3984. cfs_rq->last_h_load_update = now;
  3985. }
  3986. while ((se = cfs_rq->h_load_next) != NULL) {
  3987. load = cfs_rq->h_load;
  3988. load = div64_ul(load * se->avg.load_avg_contrib,
  3989. cfs_rq->runnable_load_avg + 1);
  3990. cfs_rq = group_cfs_rq(se);
  3991. cfs_rq->h_load = load;
  3992. cfs_rq->last_h_load_update = now;
  3993. }
  3994. }
  3995. static unsigned long task_h_load(struct task_struct *p)
  3996. {
  3997. struct cfs_rq *cfs_rq = task_cfs_rq(p);
  3998. update_cfs_rq_h_load(cfs_rq);
  3999. return div64_ul(p->se.avg.load_avg_contrib * cfs_rq->h_load,
  4000. cfs_rq->runnable_load_avg + 1);
  4001. }
  4002. #else
  4003. static inline void update_blocked_averages(int cpu)
  4004. {
  4005. }
  4006. static unsigned long task_h_load(struct task_struct *p)
  4007. {
  4008. return p->se.avg.load_avg_contrib;
  4009. }
  4010. #endif
  4011. /********** Helpers for find_busiest_group ************************/
  4012. /*
  4013. * sg_lb_stats - stats of a sched_group required for load_balancing
  4014. */
  4015. struct sg_lb_stats {
  4016. unsigned long avg_load; /*Avg load across the CPUs of the group */
  4017. unsigned long group_load; /* Total load over the CPUs of the group */
  4018. unsigned long sum_weighted_load; /* Weighted load of group's tasks */
  4019. unsigned long load_per_task;
  4020. unsigned long group_power;
  4021. unsigned int sum_nr_running; /* Nr tasks running in the group */
  4022. unsigned int group_capacity;
  4023. unsigned int idle_cpus;
  4024. unsigned int group_weight;
  4025. int group_imb; /* Is there an imbalance in the group ? */
  4026. int group_has_capacity; /* Is there extra capacity in the group? */
  4027. };
  4028. /*
  4029. * sd_lb_stats - Structure to store the statistics of a sched_domain
  4030. * during load balancing.
  4031. */
  4032. struct sd_lb_stats {
  4033. struct sched_group *busiest; /* Busiest group in this sd */
  4034. struct sched_group *local; /* Local group in this sd */
  4035. unsigned long total_load; /* Total load of all groups in sd */
  4036. unsigned long total_pwr; /* Total power of all groups in sd */
  4037. unsigned long avg_load; /* Average load across all groups in sd */
  4038. struct sg_lb_stats busiest_stat;/* Statistics of the busiest group */
  4039. struct sg_lb_stats local_stat; /* Statistics of the local group */
  4040. };
  4041. static inline void init_sd_lb_stats(struct sd_lb_stats *sds)
  4042. {
  4043. /*
  4044. * Skimp on the clearing to avoid duplicate work. We can avoid clearing
  4045. * local_stat because update_sg_lb_stats() does a full clear/assignment.
  4046. * We must however clear busiest_stat::avg_load because
  4047. * update_sd_pick_busiest() reads this before assignment.
  4048. */
  4049. *sds = (struct sd_lb_stats){
  4050. .busiest = NULL,
  4051. .local = NULL,
  4052. .total_load = 0UL,
  4053. .total_pwr = 0UL,
  4054. .busiest_stat = {
  4055. .avg_load = 0UL,
  4056. },
  4057. };
  4058. }
  4059. /**
  4060. * get_sd_load_idx - Obtain the load index for a given sched domain.
  4061. * @sd: The sched_domain whose load_idx is to be obtained.
  4062. * @idle: The Idle status of the CPU for whose sd load_icx is obtained.
  4063. *
  4064. * Return: The load index.
  4065. */
  4066. static inline int get_sd_load_idx(struct sched_domain *sd,
  4067. enum cpu_idle_type idle)
  4068. {
  4069. int load_idx;
  4070. switch (idle) {
  4071. case CPU_NOT_IDLE:
  4072. load_idx = sd->busy_idx;
  4073. break;
  4074. case CPU_NEWLY_IDLE:
  4075. load_idx = sd->newidle_idx;
  4076. break;
  4077. default:
  4078. load_idx = sd->idle_idx;
  4079. break;
  4080. }
  4081. return load_idx;
  4082. }
  4083. static unsigned long default_scale_freq_power(struct sched_domain *sd, int cpu)
  4084. {
  4085. return SCHED_POWER_SCALE;
  4086. }
  4087. unsigned long __weak arch_scale_freq_power(struct sched_domain *sd, int cpu)
  4088. {
  4089. return default_scale_freq_power(sd, cpu);
  4090. }
  4091. static unsigned long default_scale_smt_power(struct sched_domain *sd, int cpu)
  4092. {
  4093. unsigned long weight = sd->span_weight;
  4094. unsigned long smt_gain = sd->smt_gain;
  4095. smt_gain /= weight;
  4096. return smt_gain;
  4097. }
  4098. unsigned long __weak arch_scale_smt_power(struct sched_domain *sd, int cpu)
  4099. {
  4100. return default_scale_smt_power(sd, cpu);
  4101. }
  4102. static unsigned long scale_rt_power(int cpu)
  4103. {
  4104. struct rq *rq = cpu_rq(cpu);
  4105. u64 total, available, age_stamp, avg;
  4106. /*
  4107. * Since we're reading these variables without serialization make sure
  4108. * we read them once before doing sanity checks on them.
  4109. */
  4110. age_stamp = ACCESS_ONCE(rq->age_stamp);
  4111. avg = ACCESS_ONCE(rq->rt_avg);
  4112. total = sched_avg_period() + (rq_clock(rq) - age_stamp);
  4113. if (unlikely(total < avg)) {
  4114. /* Ensures that power won't end up being negative */
  4115. available = 0;
  4116. } else {
  4117. available = total - avg;
  4118. }
  4119. if (unlikely((s64)total < SCHED_POWER_SCALE))
  4120. total = SCHED_POWER_SCALE;
  4121. total >>= SCHED_POWER_SHIFT;
  4122. return div_u64(available, total);
  4123. }
  4124. static void update_cpu_power(struct sched_domain *sd, int cpu)
  4125. {
  4126. unsigned long weight = sd->span_weight;
  4127. unsigned long power = SCHED_POWER_SCALE;
  4128. struct sched_group *sdg = sd->groups;
  4129. if ((sd->flags & SD_SHARE_CPUPOWER) && weight > 1) {
  4130. if (sched_feat(ARCH_POWER))
  4131. power *= arch_scale_smt_power(sd, cpu);
  4132. else
  4133. power *= default_scale_smt_power(sd, cpu);
  4134. power >>= SCHED_POWER_SHIFT;
  4135. }
  4136. sdg->sgp->power_orig = power;
  4137. if (sched_feat(ARCH_POWER))
  4138. power *= arch_scale_freq_power(sd, cpu);
  4139. else
  4140. power *= default_scale_freq_power(sd, cpu);
  4141. power >>= SCHED_POWER_SHIFT;
  4142. power *= scale_rt_power(cpu);
  4143. power >>= SCHED_POWER_SHIFT;
  4144. if (!power)
  4145. power = 1;
  4146. cpu_rq(cpu)->cpu_power = power;
  4147. sdg->sgp->power = power;
  4148. }
  4149. void update_group_power(struct sched_domain *sd, int cpu)
  4150. {
  4151. struct sched_domain *child = sd->child;
  4152. struct sched_group *group, *sdg = sd->groups;
  4153. unsigned long power, power_orig;
  4154. unsigned long interval;
  4155. interval = msecs_to_jiffies(sd->balance_interval);
  4156. interval = clamp(interval, 1UL, max_load_balance_interval);
  4157. sdg->sgp->next_update = jiffies + interval;
  4158. if (!child) {
  4159. update_cpu_power(sd, cpu);
  4160. return;
  4161. }
  4162. power_orig = power = 0;
  4163. if (child->flags & SD_OVERLAP) {
  4164. /*
  4165. * SD_OVERLAP domains cannot assume that child groups
  4166. * span the current group.
  4167. */
  4168. for_each_cpu(cpu, sched_group_cpus(sdg)) {
  4169. struct sched_group *sg = cpu_rq(cpu)->sd->groups;
  4170. power_orig += sg->sgp->power_orig;
  4171. power += sg->sgp->power;
  4172. }
  4173. } else {
  4174. /*
  4175. * !SD_OVERLAP domains can assume that child groups
  4176. * span the current group.
  4177. */
  4178. group = child->groups;
  4179. do {
  4180. power_orig += group->sgp->power_orig;
  4181. power += group->sgp->power;
  4182. group = group->next;
  4183. } while (group != child->groups);
  4184. }
  4185. sdg->sgp->power_orig = power_orig;
  4186. sdg->sgp->power = power;
  4187. }
  4188. /*
  4189. * Try and fix up capacity for tiny siblings, this is needed when
  4190. * things like SD_ASYM_PACKING need f_b_g to select another sibling
  4191. * which on its own isn't powerful enough.
  4192. *
  4193. * See update_sd_pick_busiest() and check_asym_packing().
  4194. */
  4195. static inline int
  4196. fix_small_capacity(struct sched_domain *sd, struct sched_group *group)
  4197. {
  4198. /*
  4199. * Only siblings can have significantly less than SCHED_POWER_SCALE
  4200. */
  4201. if (!(sd->flags & SD_SHARE_CPUPOWER))
  4202. return 0;
  4203. /*
  4204. * If ~90% of the cpu_power is still there, we're good.
  4205. */
  4206. if (group->sgp->power * 32 > group->sgp->power_orig * 29)
  4207. return 1;
  4208. return 0;
  4209. }
  4210. /*
  4211. * Group imbalance indicates (and tries to solve) the problem where balancing
  4212. * groups is inadequate due to tsk_cpus_allowed() constraints.
  4213. *
  4214. * Imagine a situation of two groups of 4 cpus each and 4 tasks each with a
  4215. * cpumask covering 1 cpu of the first group and 3 cpus of the second group.
  4216. * Something like:
  4217. *
  4218. * { 0 1 2 3 } { 4 5 6 7 }
  4219. * * * * *
  4220. *
  4221. * If we were to balance group-wise we'd place two tasks in the first group and
  4222. * two tasks in the second group. Clearly this is undesired as it will overload
  4223. * cpu 3 and leave one of the cpus in the second group unused.
  4224. *
  4225. * The current solution to this issue is detecting the skew in the first group
  4226. * by noticing the lower domain failed to reach balance and had difficulty
  4227. * moving tasks due to affinity constraints.
  4228. *
  4229. * When this is so detected; this group becomes a candidate for busiest; see
  4230. * update_sd_pick_busiest(). And calculcate_imbalance() and
  4231. * find_busiest_group() avoid some of the usual balance conditions to allow it
  4232. * to create an effective group imbalance.
  4233. *
  4234. * This is a somewhat tricky proposition since the next run might not find the
  4235. * group imbalance and decide the groups need to be balanced again. A most
  4236. * subtle and fragile situation.
  4237. */
  4238. static inline int sg_imbalanced(struct sched_group *group)
  4239. {
  4240. return group->sgp->imbalance;
  4241. }
  4242. /*
  4243. * Compute the group capacity.
  4244. *
  4245. * Avoid the issue where N*frac(smt_power) >= 1 creates 'phantom' cores by
  4246. * first dividing out the smt factor and computing the actual number of cores
  4247. * and limit power unit capacity with that.
  4248. */
  4249. static inline int sg_capacity(struct lb_env *env, struct sched_group *group)
  4250. {
  4251. unsigned int capacity, smt, cpus;
  4252. unsigned int power, power_orig;
  4253. power = group->sgp->power;
  4254. power_orig = group->sgp->power_orig;
  4255. cpus = group->group_weight;
  4256. /* smt := ceil(cpus / power), assumes: 1 < smt_power < 2 */
  4257. smt = DIV_ROUND_UP(SCHED_POWER_SCALE * cpus, power_orig);
  4258. capacity = cpus / smt; /* cores */
  4259. capacity = min_t(unsigned, capacity, DIV_ROUND_CLOSEST(power, SCHED_POWER_SCALE));
  4260. if (!capacity)
  4261. capacity = fix_small_capacity(env->sd, group);
  4262. return capacity;
  4263. }
  4264. /**
  4265. * update_sg_lb_stats - Update sched_group's statistics for load balancing.
  4266. * @env: The load balancing environment.
  4267. * @group: sched_group whose statistics are to be updated.
  4268. * @load_idx: Load index of sched_domain of this_cpu for load calc.
  4269. * @local_group: Does group contain this_cpu.
  4270. * @sgs: variable to hold the statistics for this group.
  4271. */
  4272. static inline void update_sg_lb_stats(struct lb_env *env,
  4273. struct sched_group *group, int load_idx,
  4274. int local_group, struct sg_lb_stats *sgs)
  4275. {
  4276. unsigned long nr_running;
  4277. unsigned long load;
  4278. int i;
  4279. memset(sgs, 0, sizeof(*sgs));
  4280. for_each_cpu_and(i, sched_group_cpus(group), env->cpus) {
  4281. struct rq *rq = cpu_rq(i);
  4282. nr_running = rq->nr_running;
  4283. /* Bias balancing toward cpus of our domain */
  4284. if (local_group)
  4285. load = target_load(i, load_idx);
  4286. else
  4287. load = source_load(i, load_idx);
  4288. sgs->group_load += load;
  4289. sgs->sum_nr_running += nr_running;
  4290. sgs->sum_weighted_load += weighted_cpuload(i);
  4291. if (idle_cpu(i))
  4292. sgs->idle_cpus++;
  4293. }
  4294. /* Adjust by relative CPU power of the group */
  4295. sgs->group_power = group->sgp->power;
  4296. sgs->avg_load = (sgs->group_load*SCHED_POWER_SCALE) / sgs->group_power;
  4297. if (sgs->sum_nr_running)
  4298. sgs->load_per_task = sgs->sum_weighted_load / sgs->sum_nr_running;
  4299. sgs->group_weight = group->group_weight;
  4300. sgs->group_imb = sg_imbalanced(group);
  4301. sgs->group_capacity = sg_capacity(env, group);
  4302. if (sgs->group_capacity > sgs->sum_nr_running)
  4303. sgs->group_has_capacity = 1;
  4304. }
  4305. /**
  4306. * update_sd_pick_busiest - return 1 on busiest group
  4307. * @env: The load balancing environment.
  4308. * @sds: sched_domain statistics
  4309. * @sg: sched_group candidate to be checked for being the busiest
  4310. * @sgs: sched_group statistics
  4311. *
  4312. * Determine if @sg is a busier group than the previously selected
  4313. * busiest group.
  4314. *
  4315. * Return: %true if @sg is a busier group than the previously selected
  4316. * busiest group. %false otherwise.
  4317. */
  4318. static bool update_sd_pick_busiest(struct lb_env *env,
  4319. struct sd_lb_stats *sds,
  4320. struct sched_group *sg,
  4321. struct sg_lb_stats *sgs)
  4322. {
  4323. if (sgs->avg_load <= sds->busiest_stat.avg_load)
  4324. return false;
  4325. if (sgs->sum_nr_running > sgs->group_capacity)
  4326. return true;
  4327. if (sgs->group_imb)
  4328. return true;
  4329. /*
  4330. * ASYM_PACKING needs to move all the work to the lowest
  4331. * numbered CPUs in the group, therefore mark all groups
  4332. * higher than ourself as busy.
  4333. */
  4334. if ((env->sd->flags & SD_ASYM_PACKING) && sgs->sum_nr_running &&
  4335. env->dst_cpu < group_first_cpu(sg)) {
  4336. if (!sds->busiest)
  4337. return true;
  4338. if (group_first_cpu(sds->busiest) > group_first_cpu(sg))
  4339. return true;
  4340. }
  4341. return false;
  4342. }
  4343. /**
  4344. * update_sd_lb_stats - Update sched_domain's statistics for load balancing.
  4345. * @env: The load balancing environment.
  4346. * @balance: Should we balance.
  4347. * @sds: variable to hold the statistics for this sched_domain.
  4348. */
  4349. static inline void update_sd_lb_stats(struct lb_env *env,
  4350. struct sd_lb_stats *sds)
  4351. {
  4352. struct sched_domain *child = env->sd->child;
  4353. struct sched_group *sg = env->sd->groups;
  4354. struct sg_lb_stats tmp_sgs;
  4355. int load_idx, prefer_sibling = 0;
  4356. if (child && child->flags & SD_PREFER_SIBLING)
  4357. prefer_sibling = 1;
  4358. load_idx = get_sd_load_idx(env->sd, env->idle);
  4359. do {
  4360. struct sg_lb_stats *sgs = &tmp_sgs;
  4361. int local_group;
  4362. local_group = cpumask_test_cpu(env->dst_cpu, sched_group_cpus(sg));
  4363. if (local_group) {
  4364. sds->local = sg;
  4365. sgs = &sds->local_stat;
  4366. if (env->idle != CPU_NEWLY_IDLE ||
  4367. time_after_eq(jiffies, sg->sgp->next_update))
  4368. update_group_power(env->sd, env->dst_cpu);
  4369. }
  4370. update_sg_lb_stats(env, sg, load_idx, local_group, sgs);
  4371. if (local_group)
  4372. goto next_group;
  4373. /*
  4374. * In case the child domain prefers tasks go to siblings
  4375. * first, lower the sg capacity to one so that we'll try
  4376. * and move all the excess tasks away. We lower the capacity
  4377. * of a group only if the local group has the capacity to fit
  4378. * these excess tasks, i.e. nr_running < group_capacity. The
  4379. * extra check prevents the case where you always pull from the
  4380. * heaviest group when it is already under-utilized (possible
  4381. * with a large weight task outweighs the tasks on the system).
  4382. */
  4383. if (prefer_sibling && sds->local &&
  4384. sds->local_stat.group_has_capacity)
  4385. sgs->group_capacity = min(sgs->group_capacity, 1U);
  4386. if (update_sd_pick_busiest(env, sds, sg, sgs)) {
  4387. sds->busiest = sg;
  4388. sds->busiest_stat = *sgs;
  4389. }
  4390. next_group:
  4391. /* Now, start updating sd_lb_stats */
  4392. sds->total_load += sgs->group_load;
  4393. sds->total_pwr += sgs->group_power;
  4394. sg = sg->next;
  4395. } while (sg != env->sd->groups);
  4396. }
  4397. /**
  4398. * check_asym_packing - Check to see if the group is packed into the
  4399. * sched doman.
  4400. *
  4401. * This is primarily intended to used at the sibling level. Some
  4402. * cores like POWER7 prefer to use lower numbered SMT threads. In the
  4403. * case of POWER7, it can move to lower SMT modes only when higher
  4404. * threads are idle. When in lower SMT modes, the threads will
  4405. * perform better since they share less core resources. Hence when we
  4406. * have idle threads, we want them to be the higher ones.
  4407. *
  4408. * This packing function is run on idle threads. It checks to see if
  4409. * the busiest CPU in this domain (core in the P7 case) has a higher
  4410. * CPU number than the packing function is being run on. Here we are
  4411. * assuming lower CPU number will be equivalent to lower a SMT thread
  4412. * number.
  4413. *
  4414. * Return: 1 when packing is required and a task should be moved to
  4415. * this CPU. The amount of the imbalance is returned in *imbalance.
  4416. *
  4417. * @env: The load balancing environment.
  4418. * @sds: Statistics of the sched_domain which is to be packed
  4419. */
  4420. static int check_asym_packing(struct lb_env *env, struct sd_lb_stats *sds)
  4421. {
  4422. int busiest_cpu;
  4423. if (!(env->sd->flags & SD_ASYM_PACKING))
  4424. return 0;
  4425. if (!sds->busiest)
  4426. return 0;
  4427. busiest_cpu = group_first_cpu(sds->busiest);
  4428. if (env->dst_cpu > busiest_cpu)
  4429. return 0;
  4430. env->imbalance = DIV_ROUND_CLOSEST(
  4431. sds->busiest_stat.avg_load * sds->busiest_stat.group_power,
  4432. SCHED_POWER_SCALE);
  4433. return 1;
  4434. }
  4435. /**
  4436. * fix_small_imbalance - Calculate the minor imbalance that exists
  4437. * amongst the groups of a sched_domain, during
  4438. * load balancing.
  4439. * @env: The load balancing environment.
  4440. * @sds: Statistics of the sched_domain whose imbalance is to be calculated.
  4441. */
  4442. static inline
  4443. void fix_small_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
  4444. {
  4445. unsigned long tmp, pwr_now = 0, pwr_move = 0;
  4446. unsigned int imbn = 2;
  4447. unsigned long scaled_busy_load_per_task;
  4448. struct sg_lb_stats *local, *busiest;
  4449. local = &sds->local_stat;
  4450. busiest = &sds->busiest_stat;
  4451. if (!local->sum_nr_running)
  4452. local->load_per_task = cpu_avg_load_per_task(env->dst_cpu);
  4453. else if (busiest->load_per_task > local->load_per_task)
  4454. imbn = 1;
  4455. scaled_busy_load_per_task =
  4456. (busiest->load_per_task * SCHED_POWER_SCALE) /
  4457. busiest->group_power;
  4458. if (busiest->avg_load + scaled_busy_load_per_task >=
  4459. local->avg_load + (scaled_busy_load_per_task * imbn)) {
  4460. env->imbalance = busiest->load_per_task;
  4461. return;
  4462. }
  4463. /*
  4464. * OK, we don't have enough imbalance to justify moving tasks,
  4465. * however we may be able to increase total CPU power used by
  4466. * moving them.
  4467. */
  4468. pwr_now += busiest->group_power *
  4469. min(busiest->load_per_task, busiest->avg_load);
  4470. pwr_now += local->group_power *
  4471. min(local->load_per_task, local->avg_load);
  4472. pwr_now /= SCHED_POWER_SCALE;
  4473. /* Amount of load we'd subtract */
  4474. tmp = (busiest->load_per_task * SCHED_POWER_SCALE) /
  4475. busiest->group_power;
  4476. if (busiest->avg_load > tmp) {
  4477. pwr_move += busiest->group_power *
  4478. min(busiest->load_per_task,
  4479. busiest->avg_load - tmp);
  4480. }
  4481. /* Amount of load we'd add */
  4482. if (busiest->avg_load * busiest->group_power <
  4483. busiest->load_per_task * SCHED_POWER_SCALE) {
  4484. tmp = (busiest->avg_load * busiest->group_power) /
  4485. local->group_power;
  4486. } else {
  4487. tmp = (busiest->load_per_task * SCHED_POWER_SCALE) /
  4488. local->group_power;
  4489. }
  4490. pwr_move += local->group_power *
  4491. min(local->load_per_task, local->avg_load + tmp);
  4492. pwr_move /= SCHED_POWER_SCALE;
  4493. /* Move if we gain throughput */
  4494. if (pwr_move > pwr_now)
  4495. env->imbalance = busiest->load_per_task;
  4496. }
  4497. /**
  4498. * calculate_imbalance - Calculate the amount of imbalance present within the
  4499. * groups of a given sched_domain during load balance.
  4500. * @env: load balance environment
  4501. * @sds: statistics of the sched_domain whose imbalance is to be calculated.
  4502. */
  4503. static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
  4504. {
  4505. unsigned long max_pull, load_above_capacity = ~0UL;
  4506. struct sg_lb_stats *local, *busiest;
  4507. local = &sds->local_stat;
  4508. busiest = &sds->busiest_stat;
  4509. if (busiest->group_imb) {
  4510. /*
  4511. * In the group_imb case we cannot rely on group-wide averages
  4512. * to ensure cpu-load equilibrium, look at wider averages. XXX
  4513. */
  4514. busiest->load_per_task =
  4515. min(busiest->load_per_task, sds->avg_load);
  4516. }
  4517. /*
  4518. * In the presence of smp nice balancing, certain scenarios can have
  4519. * max load less than avg load(as we skip the groups at or below
  4520. * its cpu_power, while calculating max_load..)
  4521. */
  4522. if (busiest->avg_load <= sds->avg_load ||
  4523. local->avg_load >= sds->avg_load) {
  4524. env->imbalance = 0;
  4525. return fix_small_imbalance(env, sds);
  4526. }
  4527. if (!busiest->group_imb) {
  4528. /*
  4529. * Don't want to pull so many tasks that a group would go idle.
  4530. * Except of course for the group_imb case, since then we might
  4531. * have to drop below capacity to reach cpu-load equilibrium.
  4532. */
  4533. load_above_capacity =
  4534. (busiest->sum_nr_running - busiest->group_capacity);
  4535. load_above_capacity *= (SCHED_LOAD_SCALE * SCHED_POWER_SCALE);
  4536. load_above_capacity /= busiest->group_power;
  4537. }
  4538. /*
  4539. * We're trying to get all the cpus to the average_load, so we don't
  4540. * want to push ourselves above the average load, nor do we wish to
  4541. * reduce the max loaded cpu below the average load. At the same time,
  4542. * we also don't want to reduce the group load below the group capacity
  4543. * (so that we can implement power-savings policies etc). Thus we look
  4544. * for the minimum possible imbalance.
  4545. */
  4546. max_pull = min(busiest->avg_load - sds->avg_load, load_above_capacity);
  4547. /* How much load to actually move to equalise the imbalance */
  4548. env->imbalance = min(
  4549. max_pull * busiest->group_power,
  4550. (sds->avg_load - local->avg_load) * local->group_power
  4551. ) / SCHED_POWER_SCALE;
  4552. /*
  4553. * if *imbalance is less than the average load per runnable task
  4554. * there is no guarantee that any tasks will be moved so we'll have
  4555. * a think about bumping its value to force at least one task to be
  4556. * moved
  4557. */
  4558. if (env->imbalance < busiest->load_per_task)
  4559. return fix_small_imbalance(env, sds);
  4560. }
  4561. /******* find_busiest_group() helpers end here *********************/
  4562. /**
  4563. * find_busiest_group - Returns the busiest group within the sched_domain
  4564. * if there is an imbalance. If there isn't an imbalance, and
  4565. * the user has opted for power-savings, it returns a group whose
  4566. * CPUs can be put to idle by rebalancing those tasks elsewhere, if
  4567. * such a group exists.
  4568. *
  4569. * Also calculates the amount of weighted load which should be moved
  4570. * to restore balance.
  4571. *
  4572. * @env: The load balancing environment.
  4573. *
  4574. * Return: - The busiest group if imbalance exists.
  4575. * - If no imbalance and user has opted for power-savings balance,
  4576. * return the least loaded group whose CPUs can be
  4577. * put to idle by rebalancing its tasks onto our group.
  4578. */
  4579. static struct sched_group *find_busiest_group(struct lb_env *env)
  4580. {
  4581. struct sg_lb_stats *local, *busiest;
  4582. struct sd_lb_stats sds;
  4583. init_sd_lb_stats(&sds);
  4584. /*
  4585. * Compute the various statistics relavent for load balancing at
  4586. * this level.
  4587. */
  4588. update_sd_lb_stats(env, &sds);
  4589. local = &sds.local_stat;
  4590. busiest = &sds.busiest_stat;
  4591. if ((env->idle == CPU_IDLE || env->idle == CPU_NEWLY_IDLE) &&
  4592. check_asym_packing(env, &sds))
  4593. return sds.busiest;
  4594. /* There is no busy sibling group to pull tasks from */
  4595. if (!sds.busiest || busiest->sum_nr_running == 0)
  4596. goto out_balanced;
  4597. sds.avg_load = (SCHED_POWER_SCALE * sds.total_load) / sds.total_pwr;
  4598. /*
  4599. * If the busiest group is imbalanced the below checks don't
  4600. * work because they assume all things are equal, which typically
  4601. * isn't true due to cpus_allowed constraints and the like.
  4602. */
  4603. if (busiest->group_imb)
  4604. goto force_balance;
  4605. /* SD_BALANCE_NEWIDLE trumps SMP nice when underutilized */
  4606. if (env->idle == CPU_NEWLY_IDLE && local->group_has_capacity &&
  4607. !busiest->group_has_capacity)
  4608. goto force_balance;
  4609. /*
  4610. * If the local group is more busy than the selected busiest group
  4611. * don't try and pull any tasks.
  4612. */
  4613. if (local->avg_load >= busiest->avg_load)
  4614. goto out_balanced;
  4615. /*
  4616. * Don't pull any tasks if this group is already above the domain
  4617. * average load.
  4618. */
  4619. if (local->avg_load >= sds.avg_load)
  4620. goto out_balanced;
  4621. if (env->idle == CPU_IDLE) {
  4622. /*
  4623. * This cpu is idle. If the busiest group load doesn't
  4624. * have more tasks than the number of available cpu's and
  4625. * there is no imbalance between this and busiest group
  4626. * wrt to idle cpu's, it is balanced.
  4627. */
  4628. if ((local->idle_cpus < busiest->idle_cpus) &&
  4629. busiest->sum_nr_running <= busiest->group_weight)
  4630. goto out_balanced;
  4631. } else {
  4632. /*
  4633. * In the CPU_NEWLY_IDLE, CPU_NOT_IDLE cases, use
  4634. * imbalance_pct to be conservative.
  4635. */
  4636. if (100 * busiest->avg_load <=
  4637. env->sd->imbalance_pct * local->avg_load)
  4638. goto out_balanced;
  4639. }
  4640. force_balance:
  4641. /* Looks like there is an imbalance. Compute it */
  4642. calculate_imbalance(env, &sds);
  4643. return sds.busiest;
  4644. out_balanced:
  4645. env->imbalance = 0;
  4646. return NULL;
  4647. }
  4648. /*
  4649. * find_busiest_queue - find the busiest runqueue among the cpus in group.
  4650. */
  4651. static struct rq *find_busiest_queue(struct lb_env *env,
  4652. struct sched_group *group)
  4653. {
  4654. struct rq *busiest = NULL, *rq;
  4655. unsigned long busiest_load = 0, busiest_power = 1;
  4656. int i;
  4657. for_each_cpu_and(i, sched_group_cpus(group), env->cpus) {
  4658. unsigned long power = power_of(i);
  4659. unsigned long capacity = DIV_ROUND_CLOSEST(power,
  4660. SCHED_POWER_SCALE);
  4661. unsigned long wl;
  4662. if (!capacity)
  4663. capacity = fix_small_capacity(env->sd, group);
  4664. rq = cpu_rq(i);
  4665. wl = weighted_cpuload(i);
  4666. /*
  4667. * When comparing with imbalance, use weighted_cpuload()
  4668. * which is not scaled with the cpu power.
  4669. */
  4670. if (capacity && rq->nr_running == 1 && wl > env->imbalance)
  4671. continue;
  4672. /*
  4673. * For the load comparisons with the other cpu's, consider
  4674. * the weighted_cpuload() scaled with the cpu power, so that
  4675. * the load can be moved away from the cpu that is potentially
  4676. * running at a lower capacity.
  4677. *
  4678. * Thus we're looking for max(wl_i / power_i), crosswise
  4679. * multiplication to rid ourselves of the division works out
  4680. * to: wl_i * power_j > wl_j * power_i; where j is our
  4681. * previous maximum.
  4682. */
  4683. if (wl * busiest_power > busiest_load * power) {
  4684. busiest_load = wl;
  4685. busiest_power = power;
  4686. busiest = rq;
  4687. }
  4688. }
  4689. return busiest;
  4690. }
  4691. /*
  4692. * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
  4693. * so long as it is large enough.
  4694. */
  4695. #define MAX_PINNED_INTERVAL 512
  4696. /* Working cpumask for load_balance and load_balance_newidle. */
  4697. DEFINE_PER_CPU(cpumask_var_t, load_balance_mask);
  4698. static int need_active_balance(struct lb_env *env)
  4699. {
  4700. struct sched_domain *sd = env->sd;
  4701. if (env->idle == CPU_NEWLY_IDLE) {
  4702. /*
  4703. * ASYM_PACKING needs to force migrate tasks from busy but
  4704. * higher numbered CPUs in order to pack all tasks in the
  4705. * lowest numbered CPUs.
  4706. */
  4707. if ((sd->flags & SD_ASYM_PACKING) && env->src_cpu > env->dst_cpu)
  4708. return 1;
  4709. }
  4710. return unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2);
  4711. }
  4712. static int active_load_balance_cpu_stop(void *data);
  4713. static int should_we_balance(struct lb_env *env)
  4714. {
  4715. struct sched_group *sg = env->sd->groups;
  4716. struct cpumask *sg_cpus, *sg_mask;
  4717. int cpu, balance_cpu = -1;
  4718. /*
  4719. * In the newly idle case, we will allow all the cpu's
  4720. * to do the newly idle load balance.
  4721. */
  4722. if (env->idle == CPU_NEWLY_IDLE)
  4723. return 1;
  4724. sg_cpus = sched_group_cpus(sg);
  4725. sg_mask = sched_group_mask(sg);
  4726. /* Try to find first idle cpu */
  4727. for_each_cpu_and(cpu, sg_cpus, env->cpus) {
  4728. if (!cpumask_test_cpu(cpu, sg_mask) || !idle_cpu(cpu))
  4729. continue;
  4730. balance_cpu = cpu;
  4731. break;
  4732. }
  4733. if (balance_cpu == -1)
  4734. balance_cpu = group_balance_cpu(sg);
  4735. /*
  4736. * First idle cpu or the first cpu(busiest) in this sched group
  4737. * is eligible for doing load balancing at this and above domains.
  4738. */
  4739. return balance_cpu == env->dst_cpu;
  4740. }
  4741. /*
  4742. * Check this_cpu to ensure it is balanced within domain. Attempt to move
  4743. * tasks if there is an imbalance.
  4744. */
  4745. static int load_balance(int this_cpu, struct rq *this_rq,
  4746. struct sched_domain *sd, enum cpu_idle_type idle,
  4747. int *continue_balancing)
  4748. {
  4749. int ld_moved, cur_ld_moved, active_balance = 0;
  4750. struct sched_domain *sd_parent = sd->parent;
  4751. struct sched_group *group;
  4752. struct rq *busiest;
  4753. unsigned long flags;
  4754. struct cpumask *cpus = __get_cpu_var(load_balance_mask);
  4755. struct lb_env env = {
  4756. .sd = sd,
  4757. .dst_cpu = this_cpu,
  4758. .dst_rq = this_rq,
  4759. .dst_grpmask = sched_group_cpus(sd->groups),
  4760. .idle = idle,
  4761. .loop_break = sched_nr_migrate_break,
  4762. .cpus = cpus,
  4763. };
  4764. /*
  4765. * For NEWLY_IDLE load_balancing, we don't need to consider
  4766. * other cpus in our group
  4767. */
  4768. if (idle == CPU_NEWLY_IDLE)
  4769. env.dst_grpmask = NULL;
  4770. cpumask_copy(cpus, cpu_active_mask);
  4771. schedstat_inc(sd, lb_count[idle]);
  4772. redo:
  4773. if (!should_we_balance(&env)) {
  4774. *continue_balancing = 0;
  4775. goto out_balanced;
  4776. }
  4777. group = find_busiest_group(&env);
  4778. if (!group) {
  4779. schedstat_inc(sd, lb_nobusyg[idle]);
  4780. goto out_balanced;
  4781. }
  4782. busiest = find_busiest_queue(&env, group);
  4783. if (!busiest) {
  4784. schedstat_inc(sd, lb_nobusyq[idle]);
  4785. goto out_balanced;
  4786. }
  4787. BUG_ON(busiest == env.dst_rq);
  4788. schedstat_add(sd, lb_imbalance[idle], env.imbalance);
  4789. ld_moved = 0;
  4790. if (busiest->nr_running > 1) {
  4791. /*
  4792. * Attempt to move tasks. If find_busiest_group has found
  4793. * an imbalance but busiest->nr_running <= 1, the group is
  4794. * still unbalanced. ld_moved simply stays zero, so it is
  4795. * correctly treated as an imbalance.
  4796. */
  4797. env.flags |= LBF_ALL_PINNED;
  4798. env.src_cpu = busiest->cpu;
  4799. env.src_rq = busiest;
  4800. env.loop_max = min(sysctl_sched_nr_migrate, busiest->nr_running);
  4801. more_balance:
  4802. local_irq_save(flags);
  4803. double_rq_lock(env.dst_rq, busiest);
  4804. /*
  4805. * cur_ld_moved - load moved in current iteration
  4806. * ld_moved - cumulative load moved across iterations
  4807. */
  4808. cur_ld_moved = move_tasks(&env);
  4809. ld_moved += cur_ld_moved;
  4810. double_rq_unlock(env.dst_rq, busiest);
  4811. local_irq_restore(flags);
  4812. /*
  4813. * some other cpu did the load balance for us.
  4814. */
  4815. if (cur_ld_moved && env.dst_cpu != smp_processor_id())
  4816. resched_cpu(env.dst_cpu);
  4817. if (env.flags & LBF_NEED_BREAK) {
  4818. env.flags &= ~LBF_NEED_BREAK;
  4819. goto more_balance;
  4820. }
  4821. /*
  4822. * Revisit (affine) tasks on src_cpu that couldn't be moved to
  4823. * us and move them to an alternate dst_cpu in our sched_group
  4824. * where they can run. The upper limit on how many times we
  4825. * iterate on same src_cpu is dependent on number of cpus in our
  4826. * sched_group.
  4827. *
  4828. * This changes load balance semantics a bit on who can move
  4829. * load to a given_cpu. In addition to the given_cpu itself
  4830. * (or a ilb_cpu acting on its behalf where given_cpu is
  4831. * nohz-idle), we now have balance_cpu in a position to move
  4832. * load to given_cpu. In rare situations, this may cause
  4833. * conflicts (balance_cpu and given_cpu/ilb_cpu deciding
  4834. * _independently_ and at _same_ time to move some load to
  4835. * given_cpu) causing exceess load to be moved to given_cpu.
  4836. * This however should not happen so much in practice and
  4837. * moreover subsequent load balance cycles should correct the
  4838. * excess load moved.
  4839. */
  4840. if ((env.flags & LBF_DST_PINNED) && env.imbalance > 0) {
  4841. /* Prevent to re-select dst_cpu via env's cpus */
  4842. cpumask_clear_cpu(env.dst_cpu, env.cpus);
  4843. env.dst_rq = cpu_rq(env.new_dst_cpu);
  4844. env.dst_cpu = env.new_dst_cpu;
  4845. env.flags &= ~LBF_DST_PINNED;
  4846. env.loop = 0;
  4847. env.loop_break = sched_nr_migrate_break;
  4848. /*
  4849. * Go back to "more_balance" rather than "redo" since we
  4850. * need to continue with same src_cpu.
  4851. */
  4852. goto more_balance;
  4853. }
  4854. /*
  4855. * We failed to reach balance because of affinity.
  4856. */
  4857. if (sd_parent) {
  4858. int *group_imbalance = &sd_parent->groups->sgp->imbalance;
  4859. if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0) {
  4860. *group_imbalance = 1;
  4861. } else if (*group_imbalance)
  4862. *group_imbalance = 0;
  4863. }
  4864. /* All tasks on this runqueue were pinned by CPU affinity */
  4865. if (unlikely(env.flags & LBF_ALL_PINNED)) {
  4866. cpumask_clear_cpu(cpu_of(busiest), cpus);
  4867. if (!cpumask_empty(cpus)) {
  4868. env.loop = 0;
  4869. env.loop_break = sched_nr_migrate_break;
  4870. goto redo;
  4871. }
  4872. goto out_balanced;
  4873. }
  4874. }
  4875. if (!ld_moved) {
  4876. schedstat_inc(sd, lb_failed[idle]);
  4877. /*
  4878. * Increment the failure counter only on periodic balance.
  4879. * We do not want newidle balance, which can be very
  4880. * frequent, pollute the failure counter causing
  4881. * excessive cache_hot migrations and active balances.
  4882. */
  4883. if (idle != CPU_NEWLY_IDLE)
  4884. sd->nr_balance_failed++;
  4885. if (need_active_balance(&env)) {
  4886. raw_spin_lock_irqsave(&busiest->lock, flags);
  4887. /* don't kick the active_load_balance_cpu_stop,
  4888. * if the curr task on busiest cpu can't be
  4889. * moved to this_cpu
  4890. */
  4891. if (!cpumask_test_cpu(this_cpu,
  4892. tsk_cpus_allowed(busiest->curr))) {
  4893. raw_spin_unlock_irqrestore(&busiest->lock,
  4894. flags);
  4895. env.flags |= LBF_ALL_PINNED;
  4896. goto out_one_pinned;
  4897. }
  4898. /*
  4899. * ->active_balance synchronizes accesses to
  4900. * ->active_balance_work. Once set, it's cleared
  4901. * only after active load balance is finished.
  4902. */
  4903. if (!busiest->active_balance) {
  4904. busiest->active_balance = 1;
  4905. busiest->push_cpu = this_cpu;
  4906. active_balance = 1;
  4907. }
  4908. raw_spin_unlock_irqrestore(&busiest->lock, flags);
  4909. if (active_balance) {
  4910. stop_one_cpu_nowait(cpu_of(busiest),
  4911. active_load_balance_cpu_stop, busiest,
  4912. &busiest->active_balance_work);
  4913. }
  4914. /*
  4915. * We've kicked active balancing, reset the failure
  4916. * counter.
  4917. */
  4918. sd->nr_balance_failed = sd->cache_nice_tries+1;
  4919. }
  4920. } else
  4921. sd->nr_balance_failed = 0;
  4922. if (likely(!active_balance)) {
  4923. /* We were unbalanced, so reset the balancing interval */
  4924. sd->balance_interval = sd->min_interval;
  4925. } else {
  4926. /*
  4927. * If we've begun active balancing, start to back off. This
  4928. * case may not be covered by the all_pinned logic if there
  4929. * is only 1 task on the busy runqueue (because we don't call
  4930. * move_tasks).
  4931. */
  4932. if (sd->balance_interval < sd->max_interval)
  4933. sd->balance_interval *= 2;
  4934. }
  4935. goto out;
  4936. out_balanced:
  4937. schedstat_inc(sd, lb_balanced[idle]);
  4938. sd->nr_balance_failed = 0;
  4939. out_one_pinned:
  4940. /* tune up the balancing interval */
  4941. if (((env.flags & LBF_ALL_PINNED) &&
  4942. sd->balance_interval < MAX_PINNED_INTERVAL) ||
  4943. (sd->balance_interval < sd->max_interval))
  4944. sd->balance_interval *= 2;
  4945. ld_moved = 0;
  4946. out:
  4947. return ld_moved;
  4948. }
  4949. /*
  4950. * idle_balance is called by schedule() if this_cpu is about to become
  4951. * idle. Attempts to pull tasks from other CPUs.
  4952. */
  4953. void idle_balance(int this_cpu, struct rq *this_rq)
  4954. {
  4955. struct sched_domain *sd;
  4956. int pulled_task = 0;
  4957. unsigned long next_balance = jiffies + HZ;
  4958. u64 curr_cost = 0;
  4959. this_rq->idle_stamp = rq_clock(this_rq);
  4960. if (this_rq->avg_idle < sysctl_sched_migration_cost)
  4961. return;
  4962. /*
  4963. * Drop the rq->lock, but keep IRQ/preempt disabled.
  4964. */
  4965. raw_spin_unlock(&this_rq->lock);
  4966. update_blocked_averages(this_cpu);
  4967. rcu_read_lock();
  4968. for_each_domain(this_cpu, sd) {
  4969. unsigned long interval;
  4970. int continue_balancing = 1;
  4971. u64 t0, domain_cost;
  4972. if (!(sd->flags & SD_LOAD_BALANCE))
  4973. continue;
  4974. if (this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost)
  4975. break;
  4976. if (sd->flags & SD_BALANCE_NEWIDLE) {
  4977. t0 = sched_clock_cpu(this_cpu);
  4978. /* If we've pulled tasks over stop searching: */
  4979. pulled_task = load_balance(this_cpu, this_rq,
  4980. sd, CPU_NEWLY_IDLE,
  4981. &continue_balancing);
  4982. domain_cost = sched_clock_cpu(this_cpu) - t0;
  4983. if (domain_cost > sd->max_newidle_lb_cost)
  4984. sd->max_newidle_lb_cost = domain_cost;
  4985. curr_cost += domain_cost;
  4986. }
  4987. interval = msecs_to_jiffies(sd->balance_interval);
  4988. if (time_after(next_balance, sd->last_balance + interval))
  4989. next_balance = sd->last_balance + interval;
  4990. if (pulled_task) {
  4991. this_rq->idle_stamp = 0;
  4992. break;
  4993. }
  4994. }
  4995. rcu_read_unlock();
  4996. raw_spin_lock(&this_rq->lock);
  4997. if (pulled_task || time_after(jiffies, this_rq->next_balance)) {
  4998. /*
  4999. * We are going idle. next_balance may be set based on
  5000. * a busy processor. So reset next_balance.
  5001. */
  5002. this_rq->next_balance = next_balance;
  5003. }
  5004. if (curr_cost > this_rq->max_idle_balance_cost)
  5005. this_rq->max_idle_balance_cost = curr_cost;
  5006. }
  5007. /*
  5008. * active_load_balance_cpu_stop is run by cpu stopper. It pushes
  5009. * running tasks off the busiest CPU onto idle CPUs. It requires at
  5010. * least 1 task to be running on each physical CPU where possible, and
  5011. * avoids physical / logical imbalances.
  5012. */
  5013. static int active_load_balance_cpu_stop(void *data)
  5014. {
  5015. struct rq *busiest_rq = data;
  5016. int busiest_cpu = cpu_of(busiest_rq);
  5017. int target_cpu = busiest_rq->push_cpu;
  5018. struct rq *target_rq = cpu_rq(target_cpu);
  5019. struct sched_domain *sd;
  5020. raw_spin_lock_irq(&busiest_rq->lock);
  5021. /* make sure the requested cpu hasn't gone down in the meantime */
  5022. if (unlikely(busiest_cpu != smp_processor_id() ||
  5023. !busiest_rq->active_balance))
  5024. goto out_unlock;
  5025. /* Is there any task to move? */
  5026. if (busiest_rq->nr_running <= 1)
  5027. goto out_unlock;
  5028. /*
  5029. * This condition is "impossible", if it occurs
  5030. * we need to fix it. Originally reported by
  5031. * Bjorn Helgaas on a 128-cpu setup.
  5032. */
  5033. BUG_ON(busiest_rq == target_rq);
  5034. /* move a task from busiest_rq to target_rq */
  5035. double_lock_balance(busiest_rq, target_rq);
  5036. /* Search for an sd spanning us and the target CPU. */
  5037. rcu_read_lock();
  5038. for_each_domain(target_cpu, sd) {
  5039. if ((sd->flags & SD_LOAD_BALANCE) &&
  5040. cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
  5041. break;
  5042. }
  5043. if (likely(sd)) {
  5044. struct lb_env env = {
  5045. .sd = sd,
  5046. .dst_cpu = target_cpu,
  5047. .dst_rq = target_rq,
  5048. .src_cpu = busiest_rq->cpu,
  5049. .src_rq = busiest_rq,
  5050. .idle = CPU_IDLE,
  5051. };
  5052. schedstat_inc(sd, alb_count);
  5053. if (move_one_task(&env))
  5054. schedstat_inc(sd, alb_pushed);
  5055. else
  5056. schedstat_inc(sd, alb_failed);
  5057. }
  5058. rcu_read_unlock();
  5059. double_unlock_balance(busiest_rq, target_rq);
  5060. out_unlock:
  5061. busiest_rq->active_balance = 0;
  5062. raw_spin_unlock_irq(&busiest_rq->lock);
  5063. return 0;
  5064. }
  5065. #ifdef CONFIG_NO_HZ_COMMON
  5066. /*
  5067. * idle load balancing details
  5068. * - When one of the busy CPUs notice that there may be an idle rebalancing
  5069. * needed, they will kick the idle load balancer, which then does idle
  5070. * load balancing for all the idle CPUs.
  5071. */
  5072. static struct {
  5073. cpumask_var_t idle_cpus_mask;
  5074. atomic_t nr_cpus;
  5075. unsigned long next_balance; /* in jiffy units */
  5076. } nohz ____cacheline_aligned;
  5077. static inline int find_new_ilb(int call_cpu)
  5078. {
  5079. int ilb = cpumask_first(nohz.idle_cpus_mask);
  5080. if (ilb < nr_cpu_ids && idle_cpu(ilb))
  5081. return ilb;
  5082. return nr_cpu_ids;
  5083. }
  5084. /*
  5085. * Kick a CPU to do the nohz balancing, if it is time for it. We pick the
  5086. * nohz_load_balancer CPU (if there is one) otherwise fallback to any idle
  5087. * CPU (if there is one).
  5088. */
  5089. static void nohz_balancer_kick(int cpu)
  5090. {
  5091. int ilb_cpu;
  5092. nohz.next_balance++;
  5093. ilb_cpu = find_new_ilb(cpu);
  5094. if (ilb_cpu >= nr_cpu_ids)
  5095. return;
  5096. if (test_and_set_bit(NOHZ_BALANCE_KICK, nohz_flags(ilb_cpu)))
  5097. return;
  5098. /*
  5099. * Use smp_send_reschedule() instead of resched_cpu().
  5100. * This way we generate a sched IPI on the target cpu which
  5101. * is idle. And the softirq performing nohz idle load balance
  5102. * will be run before returning from the IPI.
  5103. */
  5104. smp_send_reschedule(ilb_cpu);
  5105. return;
  5106. }
  5107. static inline void nohz_balance_exit_idle(int cpu)
  5108. {
  5109. if (unlikely(test_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu)))) {
  5110. cpumask_clear_cpu(cpu, nohz.idle_cpus_mask);
  5111. atomic_dec(&nohz.nr_cpus);
  5112. clear_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu));
  5113. }
  5114. }
  5115. static inline void set_cpu_sd_state_busy(void)
  5116. {
  5117. struct sched_domain *sd;
  5118. rcu_read_lock();
  5119. sd = rcu_dereference_check_sched_domain(this_rq()->sd);
  5120. if (!sd || !sd->nohz_idle)
  5121. goto unlock;
  5122. sd->nohz_idle = 0;
  5123. for (; sd; sd = sd->parent)
  5124. atomic_inc(&sd->groups->sgp->nr_busy_cpus);
  5125. unlock:
  5126. rcu_read_unlock();
  5127. }
  5128. void set_cpu_sd_state_idle(void)
  5129. {
  5130. struct sched_domain *sd;
  5131. rcu_read_lock();
  5132. sd = rcu_dereference_check_sched_domain(this_rq()->sd);
  5133. if (!sd || sd->nohz_idle)
  5134. goto unlock;
  5135. sd->nohz_idle = 1;
  5136. for (; sd; sd = sd->parent)
  5137. atomic_dec(&sd->groups->sgp->nr_busy_cpus);
  5138. unlock:
  5139. rcu_read_unlock();
  5140. }
  5141. /*
  5142. * This routine will record that the cpu is going idle with tick stopped.
  5143. * This info will be used in performing idle load balancing in the future.
  5144. */
  5145. void nohz_balance_enter_idle(int cpu)
  5146. {
  5147. /*
  5148. * If this cpu is going down, then nothing needs to be done.
  5149. */
  5150. if (!cpu_active(cpu))
  5151. return;
  5152. if (test_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu)))
  5153. return;
  5154. cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
  5155. atomic_inc(&nohz.nr_cpus);
  5156. set_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu));
  5157. }
  5158. static int sched_ilb_notifier(struct notifier_block *nfb,
  5159. unsigned long action, void *hcpu)
  5160. {
  5161. switch (action & ~CPU_TASKS_FROZEN) {
  5162. case CPU_DYING:
  5163. nohz_balance_exit_idle(smp_processor_id());
  5164. return NOTIFY_OK;
  5165. default:
  5166. return NOTIFY_DONE;
  5167. }
  5168. }
  5169. #endif
  5170. static DEFINE_SPINLOCK(balancing);
  5171. /*
  5172. * Scale the max load_balance interval with the number of CPUs in the system.
  5173. * This trades load-balance latency on larger machines for less cross talk.
  5174. */
  5175. void update_max_interval(void)
  5176. {
  5177. max_load_balance_interval = HZ*num_online_cpus()/10;
  5178. }
  5179. /*
  5180. * It checks each scheduling domain to see if it is due to be balanced,
  5181. * and initiates a balancing operation if so.
  5182. *
  5183. * Balancing parameters are set up in init_sched_domains.
  5184. */
  5185. static void rebalance_domains(int cpu, enum cpu_idle_type idle)
  5186. {
  5187. int continue_balancing = 1;
  5188. struct rq *rq = cpu_rq(cpu);
  5189. unsigned long interval;
  5190. struct sched_domain *sd;
  5191. /* Earliest time when we have to do rebalance again */
  5192. unsigned long next_balance = jiffies + 60*HZ;
  5193. int update_next_balance = 0;
  5194. int need_serialize, need_decay = 0;
  5195. u64 max_cost = 0;
  5196. update_blocked_averages(cpu);
  5197. rcu_read_lock();
  5198. for_each_domain(cpu, sd) {
  5199. /*
  5200. * Decay the newidle max times here because this is a regular
  5201. * visit to all the domains. Decay ~1% per second.
  5202. */
  5203. if (time_after(jiffies, sd->next_decay_max_lb_cost)) {
  5204. sd->max_newidle_lb_cost =
  5205. (sd->max_newidle_lb_cost * 253) / 256;
  5206. sd->next_decay_max_lb_cost = jiffies + HZ;
  5207. need_decay = 1;
  5208. }
  5209. max_cost += sd->max_newidle_lb_cost;
  5210. if (!(sd->flags & SD_LOAD_BALANCE))
  5211. continue;
  5212. /*
  5213. * Stop the load balance at this level. There is another
  5214. * CPU in our sched group which is doing load balancing more
  5215. * actively.
  5216. */
  5217. if (!continue_balancing) {
  5218. if (need_decay)
  5219. continue;
  5220. break;
  5221. }
  5222. interval = sd->balance_interval;
  5223. if (idle != CPU_IDLE)
  5224. interval *= sd->busy_factor;
  5225. /* scale ms to jiffies */
  5226. interval = msecs_to_jiffies(interval);
  5227. interval = clamp(interval, 1UL, max_load_balance_interval);
  5228. need_serialize = sd->flags & SD_SERIALIZE;
  5229. if (need_serialize) {
  5230. if (!spin_trylock(&balancing))
  5231. goto out;
  5232. }
  5233. if (time_after_eq(jiffies, sd->last_balance + interval)) {
  5234. if (load_balance(cpu, rq, sd, idle, &continue_balancing)) {
  5235. /*
  5236. * The LBF_DST_PINNED logic could have changed
  5237. * env->dst_cpu, so we can't know our idle
  5238. * state even if we migrated tasks. Update it.
  5239. */
  5240. idle = idle_cpu(cpu) ? CPU_IDLE : CPU_NOT_IDLE;
  5241. }
  5242. sd->last_balance = jiffies;
  5243. }
  5244. if (need_serialize)
  5245. spin_unlock(&balancing);
  5246. out:
  5247. if (time_after(next_balance, sd->last_balance + interval)) {
  5248. next_balance = sd->last_balance + interval;
  5249. update_next_balance = 1;
  5250. }
  5251. }
  5252. if (need_decay) {
  5253. /*
  5254. * Ensure the rq-wide value also decays but keep it at a
  5255. * reasonable floor to avoid funnies with rq->avg_idle.
  5256. */
  5257. rq->max_idle_balance_cost =
  5258. max((u64)sysctl_sched_migration_cost, max_cost);
  5259. }
  5260. rcu_read_unlock();
  5261. /*
  5262. * next_balance will be updated only when there is a need.
  5263. * When the cpu is attached to null domain for ex, it will not be
  5264. * updated.
  5265. */
  5266. if (likely(update_next_balance))
  5267. rq->next_balance = next_balance;
  5268. }
  5269. #ifdef CONFIG_NO_HZ_COMMON
  5270. /*
  5271. * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the
  5272. * rebalancing for all the cpus for whom scheduler ticks are stopped.
  5273. */
  5274. static void nohz_idle_balance(int this_cpu, enum cpu_idle_type idle)
  5275. {
  5276. struct rq *this_rq = cpu_rq(this_cpu);
  5277. struct rq *rq;
  5278. int balance_cpu;
  5279. if (idle != CPU_IDLE ||
  5280. !test_bit(NOHZ_BALANCE_KICK, nohz_flags(this_cpu)))
  5281. goto end;
  5282. for_each_cpu(balance_cpu, nohz.idle_cpus_mask) {
  5283. if (balance_cpu == this_cpu || !idle_cpu(balance_cpu))
  5284. continue;
  5285. /*
  5286. * If this cpu gets work to do, stop the load balancing
  5287. * work being done for other cpus. Next load
  5288. * balancing owner will pick it up.
  5289. */
  5290. if (need_resched())
  5291. break;
  5292. rq = cpu_rq(balance_cpu);
  5293. raw_spin_lock_irq(&rq->lock);
  5294. update_rq_clock(rq);
  5295. update_idle_cpu_load(rq);
  5296. raw_spin_unlock_irq(&rq->lock);
  5297. rebalance_domains(balance_cpu, CPU_IDLE);
  5298. if (time_after(this_rq->next_balance, rq->next_balance))
  5299. this_rq->next_balance = rq->next_balance;
  5300. }
  5301. nohz.next_balance = this_rq->next_balance;
  5302. end:
  5303. clear_bit(NOHZ_BALANCE_KICK, nohz_flags(this_cpu));
  5304. }
  5305. /*
  5306. * Current heuristic for kicking the idle load balancer in the presence
  5307. * of an idle cpu is the system.
  5308. * - This rq has more than one task.
  5309. * - At any scheduler domain level, this cpu's scheduler group has multiple
  5310. * busy cpu's exceeding the group's power.
  5311. * - For SD_ASYM_PACKING, if the lower numbered cpu's in the scheduler
  5312. * domain span are idle.
  5313. */
  5314. static inline int nohz_kick_needed(struct rq *rq, int cpu)
  5315. {
  5316. unsigned long now = jiffies;
  5317. struct sched_domain *sd;
  5318. if (unlikely(idle_cpu(cpu)))
  5319. return 0;
  5320. /*
  5321. * We may be recently in ticked or tickless idle mode. At the first
  5322. * busy tick after returning from idle, we will update the busy stats.
  5323. */
  5324. set_cpu_sd_state_busy();
  5325. nohz_balance_exit_idle(cpu);
  5326. /*
  5327. * None are in tickless mode and hence no need for NOHZ idle load
  5328. * balancing.
  5329. */
  5330. if (likely(!atomic_read(&nohz.nr_cpus)))
  5331. return 0;
  5332. if (time_before(now, nohz.next_balance))
  5333. return 0;
  5334. if (rq->nr_running >= 2)
  5335. goto need_kick;
  5336. rcu_read_lock();
  5337. for_each_domain(cpu, sd) {
  5338. struct sched_group *sg = sd->groups;
  5339. struct sched_group_power *sgp = sg->sgp;
  5340. int nr_busy = atomic_read(&sgp->nr_busy_cpus);
  5341. if (sd->flags & SD_SHARE_PKG_RESOURCES && nr_busy > 1)
  5342. goto need_kick_unlock;
  5343. if (sd->flags & SD_ASYM_PACKING && nr_busy != sg->group_weight
  5344. && (cpumask_first_and(nohz.idle_cpus_mask,
  5345. sched_domain_span(sd)) < cpu))
  5346. goto need_kick_unlock;
  5347. if (!(sd->flags & (SD_SHARE_PKG_RESOURCES | SD_ASYM_PACKING)))
  5348. break;
  5349. }
  5350. rcu_read_unlock();
  5351. return 0;
  5352. need_kick_unlock:
  5353. rcu_read_unlock();
  5354. need_kick:
  5355. return 1;
  5356. }
  5357. #else
  5358. static void nohz_idle_balance(int this_cpu, enum cpu_idle_type idle) { }
  5359. #endif
  5360. /*
  5361. * run_rebalance_domains is triggered when needed from the scheduler tick.
  5362. * Also triggered for nohz idle balancing (with nohz_balancing_kick set).
  5363. */
  5364. static void run_rebalance_domains(struct softirq_action *h)
  5365. {
  5366. int this_cpu = smp_processor_id();
  5367. struct rq *this_rq = cpu_rq(this_cpu);
  5368. enum cpu_idle_type idle = this_rq->idle_balance ?
  5369. CPU_IDLE : CPU_NOT_IDLE;
  5370. rebalance_domains(this_cpu, idle);
  5371. /*
  5372. * If this cpu has a pending nohz_balance_kick, then do the
  5373. * balancing on behalf of the other idle cpus whose ticks are
  5374. * stopped.
  5375. */
  5376. nohz_idle_balance(this_cpu, idle);
  5377. }
  5378. static inline int on_null_domain(int cpu)
  5379. {
  5380. return !rcu_dereference_sched(cpu_rq(cpu)->sd);
  5381. }
  5382. /*
  5383. * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
  5384. */
  5385. void trigger_load_balance(struct rq *rq, int cpu)
  5386. {
  5387. /* Don't need to rebalance while attached to NULL domain */
  5388. if (time_after_eq(jiffies, rq->next_balance) &&
  5389. likely(!on_null_domain(cpu)))
  5390. raise_softirq(SCHED_SOFTIRQ);
  5391. #ifdef CONFIG_NO_HZ_COMMON
  5392. if (nohz_kick_needed(rq, cpu) && likely(!on_null_domain(cpu)))
  5393. nohz_balancer_kick(cpu);
  5394. #endif
  5395. }
  5396. static void rq_online_fair(struct rq *rq)
  5397. {
  5398. update_sysctl();
  5399. }
  5400. static void rq_offline_fair(struct rq *rq)
  5401. {
  5402. update_sysctl();
  5403. /* Ensure any throttled groups are reachable by pick_next_task */
  5404. unthrottle_offline_cfs_rqs(rq);
  5405. }
  5406. #endif /* CONFIG_SMP */
  5407. /*
  5408. * scheduler tick hitting a task of our scheduling class:
  5409. */
  5410. static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)
  5411. {
  5412. struct cfs_rq *cfs_rq;
  5413. struct sched_entity *se = &curr->se;
  5414. for_each_sched_entity(se) {
  5415. cfs_rq = cfs_rq_of(se);
  5416. entity_tick(cfs_rq, se, queued);
  5417. }
  5418. if (numabalancing_enabled)
  5419. task_tick_numa(rq, curr);
  5420. update_rq_runnable_avg(rq, 1);
  5421. }
  5422. /*
  5423. * called on fork with the child task as argument from the parent's context
  5424. * - child not yet on the tasklist
  5425. * - preemption disabled
  5426. */
  5427. static void task_fork_fair(struct task_struct *p)
  5428. {
  5429. struct cfs_rq *cfs_rq;
  5430. struct sched_entity *se = &p->se, *curr;
  5431. int this_cpu = smp_processor_id();
  5432. struct rq *rq = this_rq();
  5433. unsigned long flags;
  5434. raw_spin_lock_irqsave(&rq->lock, flags);
  5435. update_rq_clock(rq);
  5436. cfs_rq = task_cfs_rq(current);
  5437. curr = cfs_rq->curr;
  5438. /*
  5439. * Not only the cpu but also the task_group of the parent might have
  5440. * been changed after parent->se.parent,cfs_rq were copied to
  5441. * child->se.parent,cfs_rq. So call __set_task_cpu() to make those
  5442. * of child point to valid ones.
  5443. */
  5444. rcu_read_lock();
  5445. __set_task_cpu(p, this_cpu);
  5446. rcu_read_unlock();
  5447. update_curr(cfs_rq);
  5448. if (curr)
  5449. se->vruntime = curr->vruntime;
  5450. place_entity(cfs_rq, se, 1);
  5451. if (sysctl_sched_child_runs_first && curr && entity_before(curr, se)) {
  5452. /*
  5453. * Upon rescheduling, sched_class::put_prev_task() will place
  5454. * 'current' within the tree based on its new key value.
  5455. */
  5456. swap(curr->vruntime, se->vruntime);
  5457. resched_task(rq->curr);
  5458. }
  5459. se->vruntime -= cfs_rq->min_vruntime;
  5460. raw_spin_unlock_irqrestore(&rq->lock, flags);
  5461. }
  5462. /*
  5463. * Priority of the task has changed. Check to see if we preempt
  5464. * the current task.
  5465. */
  5466. static void
  5467. prio_changed_fair(struct rq *rq, struct task_struct *p, int oldprio)
  5468. {
  5469. if (!p->se.on_rq)
  5470. return;
  5471. /*
  5472. * Reschedule if we are currently running on this runqueue and
  5473. * our priority decreased, or if we are not currently running on
  5474. * this runqueue and our priority is higher than the current's
  5475. */
  5476. if (rq->curr == p) {
  5477. if (p->prio > oldprio)
  5478. resched_task(rq->curr);
  5479. } else
  5480. check_preempt_curr(rq, p, 0);
  5481. }
  5482. static void switched_from_fair(struct rq *rq, struct task_struct *p)
  5483. {
  5484. struct sched_entity *se = &p->se;
  5485. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  5486. /*
  5487. * Ensure the task's vruntime is normalized, so that when its
  5488. * switched back to the fair class the enqueue_entity(.flags=0) will
  5489. * do the right thing.
  5490. *
  5491. * If it was on_rq, then the dequeue_entity(.flags=0) will already
  5492. * have normalized the vruntime, if it was !on_rq, then only when
  5493. * the task is sleeping will it still have non-normalized vruntime.
  5494. */
  5495. if (!se->on_rq && p->state != TASK_RUNNING) {
  5496. /*
  5497. * Fix up our vruntime so that the current sleep doesn't
  5498. * cause 'unlimited' sleep bonus.
  5499. */
  5500. place_entity(cfs_rq, se, 0);
  5501. se->vruntime -= cfs_rq->min_vruntime;
  5502. }
  5503. #ifdef CONFIG_SMP
  5504. /*
  5505. * Remove our load from contribution when we leave sched_fair
  5506. * and ensure we don't carry in an old decay_count if we
  5507. * switch back.
  5508. */
  5509. if (se->avg.decay_count) {
  5510. __synchronize_entity_decay(se);
  5511. subtract_blocked_load_contrib(cfs_rq, se->avg.load_avg_contrib);
  5512. }
  5513. #endif
  5514. }
  5515. /*
  5516. * We switched to the sched_fair class.
  5517. */
  5518. static void switched_to_fair(struct rq *rq, struct task_struct *p)
  5519. {
  5520. if (!p->se.on_rq)
  5521. return;
  5522. /*
  5523. * We were most likely switched from sched_rt, so
  5524. * kick off the schedule if running, otherwise just see
  5525. * if we can still preempt the current task.
  5526. */
  5527. if (rq->curr == p)
  5528. resched_task(rq->curr);
  5529. else
  5530. check_preempt_curr(rq, p, 0);
  5531. }
  5532. /* Account for a task changing its policy or group.
  5533. *
  5534. * This routine is mostly called to set cfs_rq->curr field when a task
  5535. * migrates between groups/classes.
  5536. */
  5537. static void set_curr_task_fair(struct rq *rq)
  5538. {
  5539. struct sched_entity *se = &rq->curr->se;
  5540. for_each_sched_entity(se) {
  5541. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  5542. set_next_entity(cfs_rq, se);
  5543. /* ensure bandwidth has been allocated on our new cfs_rq */
  5544. account_cfs_rq_runtime(cfs_rq, 0);
  5545. }
  5546. }
  5547. void init_cfs_rq(struct cfs_rq *cfs_rq)
  5548. {
  5549. cfs_rq->tasks_timeline = RB_ROOT;
  5550. cfs_rq->min_vruntime = (u64)(-(1LL << 20));
  5551. #ifndef CONFIG_64BIT
  5552. cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
  5553. #endif
  5554. #ifdef CONFIG_SMP
  5555. atomic64_set(&cfs_rq->decay_counter, 1);
  5556. atomic_long_set(&cfs_rq->removed_load, 0);
  5557. #endif
  5558. }
  5559. #ifdef CONFIG_FAIR_GROUP_SCHED
  5560. static void task_move_group_fair(struct task_struct *p, int on_rq)
  5561. {
  5562. struct cfs_rq *cfs_rq;
  5563. /*
  5564. * If the task was not on the rq at the time of this cgroup movement
  5565. * it must have been asleep, sleeping tasks keep their ->vruntime
  5566. * absolute on their old rq until wakeup (needed for the fair sleeper
  5567. * bonus in place_entity()).
  5568. *
  5569. * If it was on the rq, we've just 'preempted' it, which does convert
  5570. * ->vruntime to a relative base.
  5571. *
  5572. * Make sure both cases convert their relative position when migrating
  5573. * to another cgroup's rq. This does somewhat interfere with the
  5574. * fair sleeper stuff for the first placement, but who cares.
  5575. */
  5576. /*
  5577. * When !on_rq, vruntime of the task has usually NOT been normalized.
  5578. * But there are some cases where it has already been normalized:
  5579. *
  5580. * - Moving a forked child which is waiting for being woken up by
  5581. * wake_up_new_task().
  5582. * - Moving a task which has been woken up by try_to_wake_up() and
  5583. * waiting for actually being woken up by sched_ttwu_pending().
  5584. *
  5585. * To prevent boost or penalty in the new cfs_rq caused by delta
  5586. * min_vruntime between the two cfs_rqs, we skip vruntime adjustment.
  5587. */
  5588. if (!on_rq && (!p->se.sum_exec_runtime || p->state == TASK_WAKING))
  5589. on_rq = 1;
  5590. if (!on_rq)
  5591. p->se.vruntime -= cfs_rq_of(&p->se)->min_vruntime;
  5592. set_task_rq(p, task_cpu(p));
  5593. if (!on_rq) {
  5594. cfs_rq = cfs_rq_of(&p->se);
  5595. p->se.vruntime += cfs_rq->min_vruntime;
  5596. #ifdef CONFIG_SMP
  5597. /*
  5598. * migrate_task_rq_fair() will have removed our previous
  5599. * contribution, but we must synchronize for ongoing future
  5600. * decay.
  5601. */
  5602. p->se.avg.decay_count = atomic64_read(&cfs_rq->decay_counter);
  5603. cfs_rq->blocked_load_avg += p->se.avg.load_avg_contrib;
  5604. #endif
  5605. }
  5606. }
  5607. void free_fair_sched_group(struct task_group *tg)
  5608. {
  5609. int i;
  5610. destroy_cfs_bandwidth(tg_cfs_bandwidth(tg));
  5611. for_each_possible_cpu(i) {
  5612. if (tg->cfs_rq)
  5613. kfree(tg->cfs_rq[i]);
  5614. if (tg->se)
  5615. kfree(tg->se[i]);
  5616. }
  5617. kfree(tg->cfs_rq);
  5618. kfree(tg->se);
  5619. }
  5620. int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
  5621. {
  5622. struct cfs_rq *cfs_rq;
  5623. struct sched_entity *se;
  5624. int i;
  5625. tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL);
  5626. if (!tg->cfs_rq)
  5627. goto err;
  5628. tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL);
  5629. if (!tg->se)
  5630. goto err;
  5631. tg->shares = NICE_0_LOAD;
  5632. init_cfs_bandwidth(tg_cfs_bandwidth(tg));
  5633. for_each_possible_cpu(i) {
  5634. cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
  5635. GFP_KERNEL, cpu_to_node(i));
  5636. if (!cfs_rq)
  5637. goto err;
  5638. se = kzalloc_node(sizeof(struct sched_entity),
  5639. GFP_KERNEL, cpu_to_node(i));
  5640. if (!se)
  5641. goto err_free_rq;
  5642. init_cfs_rq(cfs_rq);
  5643. init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
  5644. }
  5645. return 1;
  5646. err_free_rq:
  5647. kfree(cfs_rq);
  5648. err:
  5649. return 0;
  5650. }
  5651. void unregister_fair_sched_group(struct task_group *tg, int cpu)
  5652. {
  5653. struct rq *rq = cpu_rq(cpu);
  5654. unsigned long flags;
  5655. /*
  5656. * Only empty task groups can be destroyed; so we can speculatively
  5657. * check on_list without danger of it being re-added.
  5658. */
  5659. if (!tg->cfs_rq[cpu]->on_list)
  5660. return;
  5661. raw_spin_lock_irqsave(&rq->lock, flags);
  5662. list_del_leaf_cfs_rq(tg->cfs_rq[cpu]);
  5663. raw_spin_unlock_irqrestore(&rq->lock, flags);
  5664. }
  5665. void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
  5666. struct sched_entity *se, int cpu,
  5667. struct sched_entity *parent)
  5668. {
  5669. struct rq *rq = cpu_rq(cpu);
  5670. cfs_rq->tg = tg;
  5671. cfs_rq->rq = rq;
  5672. init_cfs_rq_runtime(cfs_rq);
  5673. tg->cfs_rq[cpu] = cfs_rq;
  5674. tg->se[cpu] = se;
  5675. /* se could be NULL for root_task_group */
  5676. if (!se)
  5677. return;
  5678. if (!parent)
  5679. se->cfs_rq = &rq->cfs;
  5680. else
  5681. se->cfs_rq = parent->my_q;
  5682. se->my_q = cfs_rq;
  5683. update_load_set(&se->load, 0);
  5684. se->parent = parent;
  5685. }
  5686. static DEFINE_MUTEX(shares_mutex);
  5687. int sched_group_set_shares(struct task_group *tg, unsigned long shares)
  5688. {
  5689. int i;
  5690. unsigned long flags;
  5691. /*
  5692. * We can't change the weight of the root cgroup.
  5693. */
  5694. if (!tg->se[0])
  5695. return -EINVAL;
  5696. shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
  5697. mutex_lock(&shares_mutex);
  5698. if (tg->shares == shares)
  5699. goto done;
  5700. tg->shares = shares;
  5701. for_each_possible_cpu(i) {
  5702. struct rq *rq = cpu_rq(i);
  5703. struct sched_entity *se;
  5704. se = tg->se[i];
  5705. /* Propagate contribution to hierarchy */
  5706. raw_spin_lock_irqsave(&rq->lock, flags);
  5707. /* Possible calls to update_curr() need rq clock */
  5708. update_rq_clock(rq);
  5709. for_each_sched_entity(se)
  5710. update_cfs_shares(group_cfs_rq(se));
  5711. raw_spin_unlock_irqrestore(&rq->lock, flags);
  5712. }
  5713. done:
  5714. mutex_unlock(&shares_mutex);
  5715. return 0;
  5716. }
  5717. #else /* CONFIG_FAIR_GROUP_SCHED */
  5718. void free_fair_sched_group(struct task_group *tg) { }
  5719. int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
  5720. {
  5721. return 1;
  5722. }
  5723. void unregister_fair_sched_group(struct task_group *tg, int cpu) { }
  5724. #endif /* CONFIG_FAIR_GROUP_SCHED */
  5725. static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task)
  5726. {
  5727. struct sched_entity *se = &task->se;
  5728. unsigned int rr_interval = 0;
  5729. /*
  5730. * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
  5731. * idle runqueue:
  5732. */
  5733. if (rq->cfs.load.weight)
  5734. rr_interval = NS_TO_JIFFIES(sched_slice(cfs_rq_of(se), se));
  5735. return rr_interval;
  5736. }
  5737. /*
  5738. * All the scheduling class methods:
  5739. */
  5740. const struct sched_class fair_sched_class = {
  5741. .next = &idle_sched_class,
  5742. .enqueue_task = enqueue_task_fair,
  5743. .dequeue_task = dequeue_task_fair,
  5744. .yield_task = yield_task_fair,
  5745. .yield_to_task = yield_to_task_fair,
  5746. .check_preempt_curr = check_preempt_wakeup,
  5747. .pick_next_task = pick_next_task_fair,
  5748. .put_prev_task = put_prev_task_fair,
  5749. #ifdef CONFIG_SMP
  5750. .select_task_rq = select_task_rq_fair,
  5751. .migrate_task_rq = migrate_task_rq_fair,
  5752. .rq_online = rq_online_fair,
  5753. .rq_offline = rq_offline_fair,
  5754. .task_waking = task_waking_fair,
  5755. #endif
  5756. .set_curr_task = set_curr_task_fair,
  5757. .task_tick = task_tick_fair,
  5758. .task_fork = task_fork_fair,
  5759. .prio_changed = prio_changed_fair,
  5760. .switched_from = switched_from_fair,
  5761. .switched_to = switched_to_fair,
  5762. .get_rr_interval = get_rr_interval_fair,
  5763. #ifdef CONFIG_FAIR_GROUP_SCHED
  5764. .task_move_group = task_move_group_fair,
  5765. #endif
  5766. };
  5767. #ifdef CONFIG_SCHED_DEBUG
  5768. void print_cfs_stats(struct seq_file *m, int cpu)
  5769. {
  5770. struct cfs_rq *cfs_rq;
  5771. rcu_read_lock();
  5772. for_each_leaf_cfs_rq(cpu_rq(cpu), cfs_rq)
  5773. print_cfs_rq(m, cpu, cfs_rq);
  5774. rcu_read_unlock();
  5775. }
  5776. #endif
  5777. __init void init_sched_fair_class(void)
  5778. {
  5779. #ifdef CONFIG_SMP
  5780. open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
  5781. #ifdef CONFIG_NO_HZ_COMMON
  5782. nohz.next_balance = jiffies;
  5783. zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);
  5784. cpu_notifier(sched_ilb_notifier, 0);
  5785. #endif
  5786. #endif /* SMP */
  5787. }