fair.c 166 KB

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