fair.c 158 KB

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