fair.c 187 KB

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