fair.c 207 KB

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