fair.c 221 KB

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