fair.c 202 KB

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