fair.c 222 KB

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