core.c 220 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796
  1. /*
  2. * kernel/sched/core.c
  3. *
  4. * Core kernel scheduler code and related syscalls
  5. *
  6. * Copyright (C) 1991-2002 Linus Torvalds
  7. */
  8. #include <linux/sched.h>
  9. #include <linux/sched/clock.h>
  10. #include <linux/sched/energy.h>
  11. #include <uapi/linux/sched/types.h>
  12. #include <linux/sched/loadavg.h>
  13. #include <linux/sched/hotplug.h>
  14. #include <linux/wait_bit.h>
  15. #include <linux/cpuset.h>
  16. #include <linux/delayacct.h>
  17. #include <linux/init_task.h>
  18. #include <linux/context_tracking.h>
  19. #include <linux/rcupdate_wait.h>
  20. #include <linux/blkdev.h>
  21. #include <linux/kcov.h>
  22. #include <linux/kprobes.h>
  23. #include <linux/mmu_context.h>
  24. #include <linux/module.h>
  25. #include <linux/nmi.h>
  26. #include <linux/prefetch.h>
  27. #include <linux/profile.h>
  28. #include <linux/scs.h>
  29. #include <linux/security.h>
  30. #include <linux/syscalls.h>
  31. #include <linux/hrtimer.h>
  32. #include <linux/smp.h>
  33. #include <linux/timer.h>
  34. #include <asm/switch_to.h>
  35. #include <asm/tlb.h>
  36. #ifdef CONFIG_PARAVIRT
  37. #include <asm/paravirt.h>
  38. #endif
  39. #include "sched.h"
  40. #include "../workqueue_internal.h"
  41. #include "../smpboot.h"
  42. #include <mt-plat/perf_tracker.h>
  43. #define CREATE_TRACE_POINTS
  44. #include <trace/events/sched.h>
  45. #include "walt.h"
  46. #include "mtk_mcdi_api.h"
  47. #if defined(CONFIG_MTK_GIC_V3_EXT)
  48. #include <linux/irqchip/mtk-gic-extend.h>
  49. #endif
  50. #include <mt-plat/l3cc_common.h>
  51. #ifdef CONFIG_MTK_TASK_TURBO
  52. #include <mt-plat/turbo_common.h>
  53. #endif
  54. #ifdef CONFIG_MEDIATEK_SOLUTION
  55. #include "mtk_secure_api.h"
  56. #include <linux/arm-smccc.h>
  57. #define GIC_ISO_CODE (1 << 0)
  58. #endif
  59. #ifdef CONFIG_MTK_QOS_FRAMEWORK
  60. #include <mt-plat/mtk_qos_prefetch_common.h>
  61. #endif /* CONFIG_MTK_QOS_FRAMEWORK */
  62. DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
  63. DEFINE_MUTEX(sched_isolation_mutex);
  64. struct cpumask cpu_all_masks;
  65. struct cpumask available_cpus;
  66. enum iso_prio_t iso_prio = ISO_UNSET;
  67. /*
  68. * Debugging: various feature bits
  69. */
  70. #define SCHED_FEAT(name, enabled) \
  71. (1UL << __SCHED_FEAT_##name) * enabled |
  72. const_debug unsigned int sysctl_sched_features =
  73. #include "features.h"
  74. 0;
  75. #undef SCHED_FEAT
  76. /*
  77. * Number of tasks to iterate in a single balance run.
  78. * Limited because this is done with IRQs disabled.
  79. */
  80. const_debug unsigned int sysctl_sched_nr_migrate = 32;
  81. /*
  82. * period over which we average the RT time consumption, measured
  83. * in ms.
  84. *
  85. * default: 1s
  86. */
  87. const_debug unsigned int sysctl_sched_time_avg = MSEC_PER_SEC;
  88. /*
  89. * period over which we measure -rt task CPU usage in us.
  90. * default: 1s
  91. */
  92. unsigned int sysctl_sched_rt_period = 1000000;
  93. __read_mostly int scheduler_running;
  94. /*
  95. * part of the period that we allow rt tasks to run in us.
  96. * default: 0.95s
  97. */
  98. int sysctl_sched_rt_runtime = 950000;
  99. /* CPUs with isolated domains */
  100. cpumask_var_t cpu_isolated_map;
  101. /*
  102. * __task_rq_lock - lock the rq @p resides on.
  103. */
  104. struct rq *__task_rq_lock(struct task_struct *p, struct rq_flags *rf)
  105. __acquires(rq->lock)
  106. {
  107. struct rq *rq;
  108. lockdep_assert_held(&p->pi_lock);
  109. for (;;) {
  110. rq = task_rq(p);
  111. raw_spin_lock(&rq->lock);
  112. if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
  113. rq_pin_lock(rq, rf);
  114. return rq;
  115. }
  116. raw_spin_unlock(&rq->lock);
  117. while (unlikely(task_on_rq_migrating(p)))
  118. cpu_relax();
  119. }
  120. }
  121. /*
  122. * task_rq_lock - lock p->pi_lock and lock the rq @p resides on.
  123. */
  124. struct rq *task_rq_lock(struct task_struct *p, struct rq_flags *rf)
  125. __acquires(p->pi_lock)
  126. __acquires(rq->lock)
  127. {
  128. struct rq *rq;
  129. for (;;) {
  130. raw_spin_lock_irqsave(&p->pi_lock, rf->flags);
  131. rq = task_rq(p);
  132. raw_spin_lock(&rq->lock);
  133. /*
  134. * move_queued_task() task_rq_lock()
  135. *
  136. * ACQUIRE (rq->lock)
  137. * [S] ->on_rq = MIGRATING [L] rq = task_rq()
  138. * WMB (__set_task_cpu()) ACQUIRE (rq->lock);
  139. * [S] ->cpu = new_cpu [L] task_rq()
  140. * [L] ->on_rq
  141. * RELEASE (rq->lock)
  142. *
  143. * If we observe the old cpu in task_rq_lock, the acquire of
  144. * the old rq->lock will fully serialize against the stores.
  145. *
  146. * If we observe the new CPU in task_rq_lock, the acquire will
  147. * pair with the WMB to ensure we must then also see migrating.
  148. */
  149. if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
  150. rq_pin_lock(rq, rf);
  151. return rq;
  152. }
  153. raw_spin_unlock(&rq->lock);
  154. raw_spin_unlock_irqrestore(&p->pi_lock, rf->flags);
  155. while (unlikely(task_on_rq_migrating(p)))
  156. cpu_relax();
  157. }
  158. }
  159. /*
  160. * RQ-clock updating methods:
  161. */
  162. static void update_rq_clock_task(struct rq *rq, s64 delta)
  163. {
  164. /*
  165. * In theory, the compile should just see 0 here, and optimize out the call
  166. * to sched_rt_avg_update. But I don't trust it...
  167. */
  168. #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
  169. s64 steal = 0, irq_delta = 0;
  170. #endif
  171. #ifdef CONFIG_IRQ_TIME_ACCOUNTING
  172. irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time;
  173. /*
  174. * Since irq_time is only updated on {soft,}irq_exit, we might run into
  175. * this case when a previous update_rq_clock() happened inside a
  176. * {soft,}irq region.
  177. *
  178. * When this happens, we stop ->clock_task and only update the
  179. * prev_irq_time stamp to account for the part that fit, so that a next
  180. * update will consume the rest. This ensures ->clock_task is
  181. * monotonic.
  182. *
  183. * It does however cause some slight miss-attribution of {soft,}irq
  184. * time, a more accurate solution would be to update the irq_time using
  185. * the current rq->clock timestamp, except that would require using
  186. * atomic ops.
  187. */
  188. if (irq_delta > delta)
  189. irq_delta = delta;
  190. rq->prev_irq_time += irq_delta;
  191. delta -= irq_delta;
  192. #endif
  193. #ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
  194. if (static_key_false((&paravirt_steal_rq_enabled))) {
  195. steal = paravirt_steal_clock(cpu_of(rq));
  196. steal -= rq->prev_steal_time_rq;
  197. if (unlikely(steal > delta))
  198. steal = delta;
  199. rq->prev_steal_time_rq += steal;
  200. delta -= steal;
  201. }
  202. #endif
  203. rq->clock_task += delta;
  204. #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
  205. if ((irq_delta + steal) && sched_feat(NONTASK_CAPACITY))
  206. sched_rt_avg_update(rq, irq_delta + steal);
  207. #endif
  208. }
  209. void update_rq_clock(struct rq *rq)
  210. {
  211. s64 delta;
  212. lockdep_assert_held(&rq->lock);
  213. if (rq->clock_update_flags & RQCF_ACT_SKIP)
  214. return;
  215. #ifdef CONFIG_SCHED_DEBUG
  216. if (sched_feat(WARN_DOUBLE_CLOCK))
  217. SCHED_WARN_ON(rq->clock_update_flags & RQCF_UPDATED);
  218. rq->clock_update_flags |= RQCF_UPDATED;
  219. #endif
  220. delta = sched_clock_cpu(cpu_of(rq)) - rq->clock;
  221. if (delta < 0)
  222. return;
  223. rq->clock += delta;
  224. update_rq_clock_task(rq, delta);
  225. }
  226. #ifdef CONFIG_SCHED_HRTICK
  227. /*
  228. * Use HR-timers to deliver accurate preemption points.
  229. */
  230. static void hrtick_clear(struct rq *rq)
  231. {
  232. if (hrtimer_active(&rq->hrtick_timer))
  233. hrtimer_cancel(&rq->hrtick_timer);
  234. }
  235. /*
  236. * High-resolution timer tick.
  237. * Runs from hardirq context with interrupts disabled.
  238. */
  239. static enum hrtimer_restart hrtick(struct hrtimer *timer)
  240. {
  241. struct rq *rq = container_of(timer, struct rq, hrtick_timer);
  242. struct rq_flags rf;
  243. WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
  244. rq_lock(rq, &rf);
  245. update_rq_clock(rq);
  246. rq->curr->sched_class->task_tick(rq, rq->curr, 1);
  247. rq_unlock(rq, &rf);
  248. return HRTIMER_NORESTART;
  249. }
  250. #ifdef CONFIG_SMP
  251. static void __hrtick_restart(struct rq *rq)
  252. {
  253. struct hrtimer *timer = &rq->hrtick_timer;
  254. hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
  255. }
  256. /*
  257. * called from hardirq (IPI) context
  258. */
  259. static void __hrtick_start(void *arg)
  260. {
  261. struct rq *rq = arg;
  262. struct rq_flags rf;
  263. rq_lock(rq, &rf);
  264. __hrtick_restart(rq);
  265. rq->hrtick_csd_pending = 0;
  266. rq_unlock(rq, &rf);
  267. }
  268. /*
  269. * Called to set the hrtick timer state.
  270. *
  271. * called with rq->lock held and irqs disabled
  272. */
  273. void hrtick_start(struct rq *rq, u64 delay)
  274. {
  275. struct hrtimer *timer = &rq->hrtick_timer;
  276. ktime_t time;
  277. s64 delta;
  278. /*
  279. * Don't schedule slices shorter than 10000ns, that just
  280. * doesn't make sense and can cause timer DoS.
  281. */
  282. delta = max_t(s64, delay, 10000LL);
  283. time = ktime_add_ns(timer->base->get_time(), delta);
  284. hrtimer_set_expires(timer, time);
  285. if (rq == this_rq()) {
  286. __hrtick_restart(rq);
  287. } else if (!rq->hrtick_csd_pending) {
  288. smp_call_function_single_async(cpu_of(rq), &rq->hrtick_csd);
  289. rq->hrtick_csd_pending = 1;
  290. }
  291. }
  292. #else
  293. /*
  294. * Called to set the hrtick timer state.
  295. *
  296. * called with rq->lock held and irqs disabled
  297. */
  298. void hrtick_start(struct rq *rq, u64 delay)
  299. {
  300. /*
  301. * Don't schedule slices shorter than 10000ns, that just
  302. * doesn't make sense. Rely on vruntime for fairness.
  303. */
  304. delay = max_t(u64, delay, 10000LL);
  305. hrtimer_start(&rq->hrtick_timer, ns_to_ktime(delay),
  306. HRTIMER_MODE_REL_PINNED);
  307. }
  308. #endif /* CONFIG_SMP */
  309. static void init_rq_hrtick(struct rq *rq)
  310. {
  311. #ifdef CONFIG_SMP
  312. rq->hrtick_csd_pending = 0;
  313. rq->hrtick_csd.flags = 0;
  314. rq->hrtick_csd.func = __hrtick_start;
  315. rq->hrtick_csd.info = rq;
  316. #endif
  317. hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
  318. rq->hrtick_timer.function = hrtick;
  319. }
  320. #else /* CONFIG_SCHED_HRTICK */
  321. static inline void hrtick_clear(struct rq *rq)
  322. {
  323. }
  324. static inline void init_rq_hrtick(struct rq *rq)
  325. {
  326. }
  327. #endif /* CONFIG_SCHED_HRTICK */
  328. /*
  329. * cmpxchg based fetch_or, macro so it works for different integer types
  330. */
  331. #define fetch_or(ptr, mask) \
  332. ({ \
  333. typeof(ptr) _ptr = (ptr); \
  334. typeof(mask) _mask = (mask); \
  335. typeof(*_ptr) _old, _val = *_ptr; \
  336. \
  337. for (;;) { \
  338. _old = cmpxchg(_ptr, _val, _val | _mask); \
  339. if (_old == _val) \
  340. break; \
  341. _val = _old; \
  342. } \
  343. _old; \
  344. })
  345. #if defined(CONFIG_SMP) && defined(TIF_POLLING_NRFLAG)
  346. /*
  347. * Atomically set TIF_NEED_RESCHED and test for TIF_POLLING_NRFLAG,
  348. * this avoids any races wrt polling state changes and thereby avoids
  349. * spurious IPIs.
  350. */
  351. static bool set_nr_and_not_polling(struct task_struct *p)
  352. {
  353. struct thread_info *ti = task_thread_info(p);
  354. return !(fetch_or(&ti->flags, _TIF_NEED_RESCHED) & _TIF_POLLING_NRFLAG);
  355. }
  356. /*
  357. * Atomically set TIF_NEED_RESCHED if TIF_POLLING_NRFLAG is set.
  358. *
  359. * If this returns true, then the idle task promises to call
  360. * sched_ttwu_pending() and reschedule soon.
  361. */
  362. static bool set_nr_if_polling(struct task_struct *p)
  363. {
  364. struct thread_info *ti = task_thread_info(p);
  365. typeof(ti->flags) old, val = READ_ONCE(ti->flags);
  366. for (;;) {
  367. if (!(val & _TIF_POLLING_NRFLAG))
  368. return false;
  369. if (val & _TIF_NEED_RESCHED)
  370. return true;
  371. old = cmpxchg(&ti->flags, val, val | _TIF_NEED_RESCHED);
  372. if (old == val)
  373. break;
  374. val = old;
  375. }
  376. return true;
  377. }
  378. #else
  379. static bool set_nr_and_not_polling(struct task_struct *p)
  380. {
  381. set_tsk_need_resched(p);
  382. return true;
  383. }
  384. #ifdef CONFIG_SMP
  385. static bool set_nr_if_polling(struct task_struct *p)
  386. {
  387. return false;
  388. }
  389. #endif
  390. #endif
  391. void wake_q_add(struct wake_q_head *head, struct task_struct *task)
  392. {
  393. struct wake_q_node *node = &task->wake_q;
  394. /*
  395. * Atomically grab the task, if ->wake_q is !nil already it means
  396. * its already queued (either by us or someone else) and will get the
  397. * wakeup due to that.
  398. *
  399. * In order to ensure that a pending wakeup will observe our pending
  400. * state, even in the failed case, an explicit smp_mb() must be used.
  401. */
  402. smp_mb__before_atomic();
  403. if (cmpxchg_relaxed(&node->next, NULL, WAKE_Q_TAIL))
  404. return;
  405. head->count++;
  406. get_task_struct(task);
  407. /*
  408. * The head is context local, there can be no concurrency.
  409. */
  410. *head->lastp = node;
  411. head->lastp = &node->next;
  412. }
  413. static int
  414. try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags,
  415. int sibling_count_hint);
  416. void wake_up_q(struct wake_q_head *head)
  417. {
  418. struct wake_q_node *node = head->first;
  419. while (node != WAKE_Q_TAIL) {
  420. struct task_struct *task;
  421. task = container_of(node, struct task_struct, wake_q);
  422. BUG_ON(!task);
  423. /* Task can safely be re-inserted now: */
  424. node = node->next;
  425. task->wake_q.next = NULL;
  426. /*
  427. * try_to_wake_up() implies a wmb() to pair with the queueing
  428. * in wake_q_add() so as not to miss wakeups.
  429. */
  430. try_to_wake_up(task, TASK_NORMAL, 0, head->count);
  431. put_task_struct(task);
  432. }
  433. }
  434. /*
  435. * resched_curr - mark rq's current task 'to be rescheduled now'.
  436. *
  437. * On UP this means the setting of the need_resched flag, on SMP it
  438. * might also involve a cross-CPU call to trigger the scheduler on
  439. * the target CPU.
  440. */
  441. void resched_curr(struct rq *rq)
  442. {
  443. struct task_struct *curr = rq->curr;
  444. int cpu;
  445. lockdep_assert_held(&rq->lock);
  446. if (test_tsk_need_resched(curr))
  447. return;
  448. cpu = cpu_of(rq);
  449. if (cpu == smp_processor_id()) {
  450. set_tsk_need_resched(curr);
  451. set_preempt_need_resched();
  452. return;
  453. }
  454. if (set_nr_and_not_polling(curr))
  455. smp_send_reschedule(cpu);
  456. else
  457. trace_sched_wake_idle_without_ipi(cpu);
  458. }
  459. void resched_cpu(int cpu)
  460. {
  461. struct rq *rq = cpu_rq(cpu);
  462. unsigned long flags;
  463. raw_spin_lock_irqsave(&rq->lock, flags);
  464. if (cpu_online(cpu) || cpu == smp_processor_id())
  465. resched_curr(rq);
  466. raw_spin_unlock_irqrestore(&rq->lock, flags);
  467. }
  468. #ifdef CONFIG_SMP
  469. #ifdef CONFIG_NO_HZ_COMMON
  470. /*
  471. * In the semi idle case, use the nearest busy CPU for migrating timers
  472. * from an idle CPU. This is good for power-savings.
  473. *
  474. * We don't do similar optimization for completely idle system, as
  475. * selecting an idle CPU will add more delays to the timers than intended
  476. * (as that CPU's timer base may not be uptodate wrt jiffies etc).
  477. */
  478. int get_nohz_timer_target(void)
  479. {
  480. int i, cpu = smp_processor_id();
  481. struct sched_domain *sd;
  482. if (!idle_cpu(cpu) && is_housekeeping_cpu(cpu))
  483. return cpu;
  484. rcu_read_lock();
  485. for_each_domain(cpu, sd) {
  486. for_each_cpu(i, sched_domain_span(sd)) {
  487. if (cpu == i)
  488. continue;
  489. if (!idle_cpu(i) && is_housekeeping_cpu(i)) {
  490. cpu = i;
  491. goto unlock;
  492. }
  493. }
  494. }
  495. if (!is_housekeeping_cpu(cpu))
  496. cpu = housekeeping_any_cpu();
  497. unlock:
  498. rcu_read_unlock();
  499. return cpu;
  500. }
  501. /*
  502. * When add_timer_on() enqueues a timer into the timer wheel of an
  503. * idle CPU then this timer might expire before the next timer event
  504. * which is scheduled to wake up that CPU. In case of a completely
  505. * idle system the next event might even be infinite time into the
  506. * future. wake_up_idle_cpu() ensures that the CPU is woken up and
  507. * leaves the inner idle loop so the newly added timer is taken into
  508. * account when the CPU goes back to idle and evaluates the timer
  509. * wheel for the next timer event.
  510. */
  511. static void wake_up_idle_cpu(int cpu)
  512. {
  513. struct rq *rq = cpu_rq(cpu);
  514. if (cpu == smp_processor_id())
  515. return;
  516. if (set_nr_and_not_polling(rq->idle))
  517. smp_send_reschedule(cpu);
  518. else
  519. trace_sched_wake_idle_without_ipi(cpu);
  520. }
  521. static bool wake_up_full_nohz_cpu(int cpu)
  522. {
  523. /*
  524. * We just need the target to call irq_exit() and re-evaluate
  525. * the next tick. The nohz full kick at least implies that.
  526. * If needed we can still optimize that later with an
  527. * empty IRQ.
  528. */
  529. if (cpu_is_offline(cpu))
  530. return true; /* Don't try to wake offline CPUs. */
  531. if (tick_nohz_full_cpu(cpu)) {
  532. if (cpu != smp_processor_id() ||
  533. tick_nohz_tick_stopped())
  534. tick_nohz_full_kick_cpu(cpu);
  535. return true;
  536. }
  537. return false;
  538. }
  539. /*
  540. * Wake up the specified CPU. If the CPU is going offline, it is the
  541. * caller's responsibility to deal with the lost wakeup, for example,
  542. * by hooking into the CPU_DEAD notifier like timers and hrtimers do.
  543. */
  544. void wake_up_nohz_cpu(int cpu)
  545. {
  546. if (!wake_up_full_nohz_cpu(cpu))
  547. wake_up_idle_cpu(cpu);
  548. }
  549. static inline bool got_nohz_idle_kick(void)
  550. {
  551. int cpu = smp_processor_id();
  552. if (!test_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu)))
  553. return false;
  554. if (idle_cpu(cpu) && !need_resched())
  555. return true;
  556. /*
  557. * We can't run Idle Load Balance on this CPU for this time so we
  558. * cancel it and clear NOHZ_BALANCE_KICK
  559. */
  560. clear_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu));
  561. return false;
  562. }
  563. #else /* CONFIG_NO_HZ_COMMON */
  564. static inline bool got_nohz_idle_kick(void)
  565. {
  566. return false;
  567. }
  568. #endif /* CONFIG_NO_HZ_COMMON */
  569. #ifdef CONFIG_NO_HZ_FULL
  570. bool sched_can_stop_tick(struct rq *rq)
  571. {
  572. int fifo_nr_running;
  573. /* Deadline tasks, even if single, need the tick */
  574. if (rq->dl.dl_nr_running)
  575. return false;
  576. /*
  577. * If there are more than one RR tasks, we need the tick to effect the
  578. * actual RR behaviour.
  579. */
  580. if (rq->rt.rr_nr_running) {
  581. if (rq->rt.rr_nr_running == 1)
  582. return true;
  583. else
  584. return false;
  585. }
  586. /*
  587. * If there's no RR tasks, but FIFO tasks, we can skip the tick, no
  588. * forced preemption between FIFO tasks.
  589. */
  590. fifo_nr_running = rq->rt.rt_nr_running - rq->rt.rr_nr_running;
  591. if (fifo_nr_running)
  592. return true;
  593. /*
  594. * If there are no DL,RR/FIFO tasks, there must only be CFS tasks left;
  595. * if there's more than one we need the tick for involuntary
  596. * preemption.
  597. */
  598. if (rq->nr_running > 1)
  599. return false;
  600. return true;
  601. }
  602. #endif /* CONFIG_NO_HZ_FULL */
  603. void sched_avg_update(struct rq *rq)
  604. {
  605. s64 period = sched_avg_period();
  606. while ((s64)(rq_clock(rq) - rq->age_stamp) > period) {
  607. /*
  608. * Inline assembly required to prevent the compiler
  609. * optimising this loop into a divmod call.
  610. * See __iter_div_u64_rem() for another example of this.
  611. */
  612. asm("" : "+rm" (rq->age_stamp));
  613. rq->age_stamp += period;
  614. rq->rt_avg /= 2;
  615. }
  616. }
  617. #endif /* CONFIG_SMP */
  618. #if defined(CONFIG_RT_GROUP_SCHED) || (defined(CONFIG_FAIR_GROUP_SCHED) && \
  619. (defined(CONFIG_SMP) || defined(CONFIG_CFS_BANDWIDTH)))
  620. /*
  621. * Iterate task_group tree rooted at *from, calling @down when first entering a
  622. * node and @up when leaving it for the final time.
  623. *
  624. * Caller must hold rcu_lock or sufficient equivalent.
  625. */
  626. int walk_tg_tree_from(struct task_group *from,
  627. tg_visitor down, tg_visitor up, void *data)
  628. {
  629. struct task_group *parent, *child;
  630. int ret;
  631. parent = from;
  632. down:
  633. ret = (*down)(parent, data);
  634. if (ret)
  635. goto out;
  636. list_for_each_entry_rcu(child, &parent->children, siblings) {
  637. parent = child;
  638. goto down;
  639. up:
  640. continue;
  641. }
  642. ret = (*up)(parent, data);
  643. if (ret || parent == from)
  644. goto out;
  645. child = parent;
  646. parent = parent->parent;
  647. if (parent)
  648. goto up;
  649. out:
  650. return ret;
  651. }
  652. int tg_nop(struct task_group *tg, void *data)
  653. {
  654. return 0;
  655. }
  656. #endif
  657. static void set_load_weight(struct task_struct *p)
  658. {
  659. int prio = p->static_prio - MAX_RT_PRIO;
  660. struct load_weight *load = &p->se.load;
  661. /*
  662. * SCHED_IDLE tasks get minimal weight:
  663. */
  664. if (idle_policy(p->policy)) {
  665. load->weight = scale_load(WEIGHT_IDLEPRIO);
  666. load->inv_weight = WMULT_IDLEPRIO;
  667. return;
  668. }
  669. load->weight = scale_load(sched_prio_to_weight[prio]);
  670. load->inv_weight = sched_prio_to_wmult[prio];
  671. }
  672. #ifdef CONFIG_UCLAMP_MAP_OPP
  673. #include <linux/sort.h>
  674. #include <linux/cpufreq.h>
  675. int total_opp_count;
  676. int opp_capacity_tbl_ready;
  677. unsigned int *opp_capacity_tbl;
  678. static int cap_compare(const void *lhs, const void *rhs)
  679. {
  680. unsigned int lhs_cap = *(const unsigned int *)(lhs);
  681. unsigned int rhs_cap = *(const unsigned int *)(rhs);
  682. if (lhs_cap < rhs_cap)
  683. return -1;
  684. if (lhs_cap > rhs_cap)
  685. return 1;
  686. return 0;
  687. }
  688. static int system_opp_count(void)
  689. {
  690. int cpu, cid, prev_cid = -1;
  691. int count = 0;
  692. struct sched_domain *sd;
  693. struct sched_group *sg;
  694. const struct sched_group_energy *sge;
  695. rcu_read_lock();
  696. for (cpu = 0; cpu < nr_cpu_ids; cpu++) {
  697. cid = arch_get_cluster_id(cpu);
  698. if (cid == prev_cid)
  699. continue;
  700. sd = rcu_dereference_check_sched_domain(cpu_rq(cpu)->sd);
  701. if (sd) {
  702. sg = sd->groups;
  703. sge = sg->sge;
  704. } else {
  705. rcu_read_unlock();
  706. pr_info("sched: %s no sd\n", __func__);
  707. return -1;
  708. }
  709. count += sge->nr_cap_states;
  710. prev_cid = cid;
  711. }
  712. rcu_read_unlock();
  713. return count;
  714. }
  715. #ifdef CONFIG_NONLINEAR_FREQ_CTL
  716. static inline unsigned int get_opp_capacity(struct cpufreq_policy *policy,
  717. int row)
  718. {
  719. struct upower_tbl *upower_tbl;
  720. upower_tbl = upower_get_core_tbl(policy->cpu);
  721. return upower_tbl->row[row].cap;
  722. }
  723. #else
  724. static inline unsigned int get_opp_capacity(struct cpufreq_policy *policy,
  725. int row)
  726. {
  727. unsigned int cap, orig_cap;
  728. unsigned long freq, max_freq;
  729. max_freq = policy->cpuinfo.max_freq;
  730. orig_cap = capacity_orig_of(policy->cpu);
  731. freq = policy->freq_table[row].frequency;
  732. cap = orig_cap * freq / max_freq;
  733. return cap;
  734. }
  735. #endif
  736. void init_opp_capacity_tbl(void)
  737. {
  738. int cpu, cid, prev_cid = -1;
  739. int count = 0;
  740. int i, idx = 0;
  741. unsigned int cap;
  742. struct sched_domain *sd;
  743. struct sched_group *sg;
  744. const struct sched_group_energy *sge;
  745. struct cpufreq_policy *policy;
  746. count = system_opp_count();
  747. if (count < 0)
  748. return;
  749. opp_capacity_tbl =
  750. kmalloc_array(count, sizeof(unsigned int), GFP_KERNEL);
  751. if (!opp_capacity_tbl)
  752. return;
  753. rcu_read_lock();
  754. for (cpu = 0; cpu < nr_cpu_ids; cpu++) {
  755. cid = arch_get_cluster_id(cpu);
  756. if (cid == prev_cid)
  757. continue;
  758. sd = rcu_dereference_check_sched_domain(cpu_rq(cpu)->sd);
  759. if (sd) {
  760. sg = sd->groups;
  761. sge = sg->sge;
  762. } else {
  763. pr_info("sched: %s no sd\n", __func__);
  764. goto free_unlock;
  765. }
  766. policy = cpufreq_cpu_get(cpu);
  767. if (!policy) {
  768. pr_info("policy not ready\n");
  769. goto free_unlock;
  770. }
  771. for (i = 0; i < sge->nr_cap_states; i++) {
  772. cap = get_opp_capacity(policy, i);
  773. opp_capacity_tbl[idx] = cap;
  774. idx++;
  775. }
  776. cpufreq_cpu_put(policy);
  777. prev_cid = cid;
  778. }
  779. rcu_read_unlock();
  780. sort(opp_capacity_tbl, count, sizeof(unsigned int),
  781. &cap_compare, NULL);
  782. opp_capacity_tbl[count - 1] = SCHED_CAPACITY_SCALE;
  783. total_opp_count = count;
  784. opp_capacity_tbl_ready = 1;
  785. return;
  786. free_unlock:
  787. rcu_read_unlock();
  788. kfree(opp_capacity_tbl);
  789. }
  790. unsigned int find_fit_capacity(unsigned int cap)
  791. {
  792. int i;
  793. if (unlikely(!opp_capacity_tbl_ready))
  794. return cap;
  795. if (cap == 0)
  796. return cap;
  797. for (i = 0; i < total_opp_count; i++) {
  798. if (opp_capacity_tbl[i] >= cap)
  799. return opp_capacity_tbl[i];
  800. }
  801. return SCHED_CAPACITY_SCALE;
  802. }
  803. #else
  804. int opp_capacity_tbl_ready = 1;
  805. void init_opp_capacity_tbl(void) {}
  806. unsigned int find_fit_capacity(unsigned int cap)
  807. {
  808. return cap;
  809. }
  810. #endif
  811. #ifdef CONFIG_UCLAMP_TASK
  812. /**
  813. * uclamp_mutex: serializes updates of utilization clamp values
  814. *
  815. * Utilization clamp value updates are triggered from user-space (slow-path)
  816. * but require refcounting updates on data structures used by scheduler's
  817. * enqueue/dequeue operations (fast-path).
  818. * While fast-path refcounting is enforced by atomic operations, this mutex
  819. * ensures that we serialize user-space requests thus avoiding the risk of
  820. * conflicting updates or API abuses.
  821. */
  822. DEFINE_MUTEX(uclamp_mutex);
  823. /*
  824. * Minimum utilization for all tasks
  825. * default: 0
  826. */
  827. unsigned int sysctl_sched_uclamp_util_min;
  828. /*
  829. * Maximum utilization for all tasks
  830. * default: 1024
  831. */
  832. unsigned int sysctl_sched_uclamp_util_max = SCHED_CAPACITY_SCALE;
  833. /*
  834. * Tasks's clamp values are required to be within this range
  835. */
  836. static struct uclamp_se uclamp_default[UCLAMP_CNT];
  837. static struct uclamp_se uclamp_default_perf[UCLAMP_CNT];
  838. /**
  839. * uclamp_map: reference count utilization clamp groups
  840. * @value: the utilization "clamp value" tracked by this clamp group
  841. * @se_count: the number of scheduling entities using this "clamp value"
  842. */
  843. union uclamp_map {
  844. struct {
  845. unsigned long value : SCHED_CAPACITY_SHIFT + 1;
  846. unsigned long se_count : BITS_PER_LONG -
  847. SCHED_CAPACITY_SHIFT - 1;
  848. };
  849. unsigned long data;
  850. atomic_long_t adata;
  851. };
  852. /**
  853. * uclamp_maps: map SEs "clamp value" into CPUs "clamp group"
  854. *
  855. * Since only a limited number of different "clamp values" are supported, we
  856. * map each value into a "clamp group" (group_id) used at tasks {en,de}queued
  857. * time to update a per-CPU refcounter tracking the number or RUNNABLE tasks
  858. * requesting that clamp value.
  859. * A "clamp index" (clamp_id) is used to define the kind of clamping, i.e. min
  860. * and max utilization.
  861. *
  862. * A matrix is thus required to map "clamp values" (value) to "clamp groups"
  863. * (group_id), for each "clamp index" (clamp_id), where:
  864. * - rows are indexed by clamp_id and they collect the clamp groups for a
  865. * given clamp index
  866. * - columns are indexed by group_id and they collect the clamp values which
  867. * maps to that clamp group
  868. *
  869. * Thus, the column index of a given (clamp_id, value) pair represents the
  870. * clamp group (group_id) used by the fast-path's per-CPU refcounter.
  871. *
  872. * uclamp_maps is a matrix of
  873. * +------- UCLAMP_CNT by UCLAMP_GROUPS entries
  874. * | |
  875. * | /---------------+---------------\
  876. * | +------------+ +------------+
  877. * | / UCLAMP_MIN | value | | value |
  878. * | | | se_count |...... | se_count |
  879. * | | +------------+ +------------+
  880. * +--+ +------------+ +------------+
  881. * | | value | | value |
  882. * \ UCLAMP_MAX | se_count |...... | se_count |
  883. * +-----^------+ +----^-------+
  884. * |
  885. * |
  886. * +
  887. * uclamp_maps[clamp_id][group_id].value
  888. */
  889. static union uclamp_map uclamp_maps[UCLAMP_CNT][UCLAMP_GROUPS];
  890. /*
  891. * uclamp_group_value: get the "group value" for a given "clamp value"
  892. * @value: the utiliation "clamp value" to translate
  893. *
  894. * The number of clamp group, which is defined at compile time, allows to
  895. * track a finite number of different clamp values. Thus clamp values are
  896. * grouped into bins each one representing a different "group value".
  897. * This method returns the "group value" corresponding to the specified
  898. * "clamp value".
  899. */
  900. static inline unsigned int uclamp_group_value(unsigned int clamp_value)
  901. {
  902. #define UCLAMP_GROUP_DELTA (SCHED_CAPACITY_SCALE / CONFIG_UCLAMP_GROUPS_COUNT)
  903. #define UCLAMP_GROUP_UPPER (UCLAMP_GROUP_DELTA * CONFIG_UCLAMP_GROUPS_COUNT)
  904. if (clamp_value >= UCLAMP_GROUP_UPPER)
  905. return SCHED_CAPACITY_SCALE;
  906. return UCLAMP_GROUP_DELTA * (clamp_value / UCLAMP_GROUP_DELTA);
  907. }
  908. /**
  909. * uclamp_cpu_update: updates the utilization clamp of a CPU
  910. * @rq: the CPU's rq which utilization clamp has to be updated
  911. * @clamp_id: the clamp index to update
  912. *
  913. * When tasks are enqueued/dequeued on/from a CPU, the set of currently active
  914. * clamp groups can change. Since each clamp group enforces a different
  915. * utilization clamp value, once the set of active groups changes it can be
  916. * required to re-compute what is the new clamp value to apply for that CPU.
  917. *
  918. * For the specified clamp index, this method computes the new CPU utilization
  919. * clamp to use until the next change on the set of active clamp groups.
  920. */
  921. static inline void uclamp_cpu_update(struct rq *rq, unsigned int clamp_id,
  922. unsigned int last_clamp_value)
  923. {
  924. unsigned int group_id;
  925. int max_value = -1;
  926. for (group_id = 0; group_id < UCLAMP_GROUPS; ++group_id) {
  927. if (!rq->uclamp.group[clamp_id][group_id].tasks)
  928. continue;
  929. /* Both min and max clamps are MAX aggregated */
  930. if (max_value < rq->uclamp.group[clamp_id][group_id].value)
  931. max_value = rq->uclamp.group[clamp_id][group_id].value;
  932. if (max_value >= SCHED_CAPACITY_SCALE)
  933. break;
  934. }
  935. /*
  936. * Just for the UCLAMP_MAX value, in case there are no RUNNABLE
  937. * task, we want to keep the CPU clamped to the last task's clamp
  938. * value. This is to avoid frequency spikes to MAX when one CPU, with
  939. * an high blocked utilization, sleeps and another CPU, in the same
  940. * frequency domain, do not see anymore the clamp on the first CPU.
  941. *
  942. * The UCLAMP_FLAG_IDLE is set whenever we detect, from the above
  943. * loop, that there are no more RUNNABLE taks on that CPU.
  944. * In this case we enforce the CPU util_max to that of the last
  945. * dequeued task.
  946. */
  947. if (max_value < 0) {
  948. if (clamp_id == UCLAMP_MAX) {
  949. rq->uclamp.flags |= UCLAMP_FLAG_IDLE;
  950. max_value = last_clamp_value;
  951. } else {
  952. max_value = uclamp_none(UCLAMP_MIN);
  953. }
  954. }
  955. rq->uclamp.value[clamp_id] = max_value;
  956. }
  957. #if defined(CONFIG_UCLAMP_TASK_GROUP) && defined(CONFIG_SCHED_TUNE)
  958. #define uclamp_apply_defaults(p) false
  959. #elif defined(CONFIG_UCLAMP_TASK_GROUP)
  960. /**
  961. * uclamp_apply_defaults: check if p is subject to system default clamps
  962. * @p: the task to check
  963. *
  964. * Tasks in the root group or autogroups are always and only limited by system
  965. * defaults. All others instead are limited by their TG's specific value.
  966. * This method checks the conditions under witch a task is subject to system
  967. * default clamps.
  968. */
  969. static inline bool uclamp_apply_defaults(struct task_struct *p)
  970. {
  971. if (task_group_is_autogroup(task_group(p)))
  972. return true;
  973. if (task_group(p) == &root_task_group)
  974. return true;
  975. return false;
  976. }
  977. #else
  978. #define uclamp_apply_defaults(p) true
  979. #endif
  980. /**
  981. * uclamp_effective_group_id: get the effective clamp group index of a task
  982. * @p: the task to get the effective clamp value for
  983. * @clamp_id: the clamp index to consider
  984. *
  985. * The effective clamp group index of a task depends on:
  986. * - the task specific clamp value, explicitly requested from userspace
  987. * - the task group effective clamp value, for tasks not in the root group or
  988. * in an autogroup
  989. * - the system default clamp value, defined by the sysadmin
  990. * and tasks specific's clamp values are always restricted, with increasing
  991. * priority, by their task group first and the system defaults after.
  992. *
  993. * This method returns the effective group index for a task, depending on its
  994. * status and a proper aggregation of the clamp values listed above.
  995. * Moreover, it ensures that the task's effective value:
  996. * task_struct::uclamp::effective::value
  997. * is updated to represent the clamp value corresponding to the taks effective
  998. * group index.
  999. */
  1000. static inline unsigned int uclamp_effective_group_id(struct task_struct *p,
  1001. unsigned int clamp_id)
  1002. {
  1003. struct uclamp_se *default_clamp;
  1004. unsigned int clamp_value;
  1005. unsigned int group_id;
  1006. /* Task currently refcounted into a CPU clamp group */
  1007. if (p->uclamp[clamp_id].active)
  1008. return p->uclamp[clamp_id].effective.group_id;
  1009. /* Task specific clamp value */
  1010. clamp_value = p->uclamp[clamp_id].value;
  1011. group_id = p->uclamp[clamp_id].group_id;
  1012. if (!uclamp_apply_defaults(p)) {
  1013. #if defined(CONFIG_UCLAMP_TASK_GROUP) && defined(CONFIG_SCHED_TUNE)
  1014. struct uclamp_se *uc_se;
  1015. unsigned int clamp_max;
  1016. unsigned int group_max;
  1017. /* Group specific clamp value */
  1018. uc_se = task_schedtune_uclamp(p, clamp_id);
  1019. clamp_max = uc_se->effective.value;
  1020. group_max = uc_se->effective.group_id;
  1021. /* Use group clamp value restrict task clamp value */
  1022. if (!p->uclamp[clamp_id].user_defined ||
  1023. (clamp_max != uclamp_none(clamp_id) &&
  1024. clamp_value != clamp_max)) {
  1025. clamp_value = clamp_max;
  1026. group_id = group_max;
  1027. }
  1028. #elif defined(CONFIG_UCLAMP_TASK_GROUP)
  1029. unsigned int clamp_max =
  1030. task_group(p)->uclamp[clamp_id].effective.value;
  1031. unsigned int group_max =
  1032. task_group(p)->uclamp[clamp_id].effective.group_id;
  1033. if (!p->uclamp[clamp_id].user_defined ||
  1034. clamp_value > clamp_max) {
  1035. clamp_value = clamp_max;
  1036. group_id = group_max;
  1037. }
  1038. #endif
  1039. goto done;
  1040. }
  1041. /* RT tasks have different default values */
  1042. default_clamp = task_has_rt_policy(p)
  1043. ? uclamp_default_perf
  1044. : uclamp_default;
  1045. /* System default restriction */
  1046. if (unlikely(clamp_value < default_clamp[UCLAMP_MIN].value ||
  1047. clamp_value > default_clamp[UCLAMP_MAX].value)) {
  1048. /*
  1049. * Unconditionally enforce system defaults, which is a simpler
  1050. * solution compared to a proper clamping.
  1051. */
  1052. clamp_value = default_clamp[clamp_id].value;
  1053. group_id = default_clamp[clamp_id].group_id;
  1054. }
  1055. done:
  1056. p->uclamp[clamp_id].effective.value = clamp_value;
  1057. p->uclamp[clamp_id].effective.group_id = group_id;
  1058. return group_id;
  1059. }
  1060. unsigned int uclamp_task_effective_util(struct task_struct *p,
  1061. unsigned int clamp_id)
  1062. {
  1063. uclamp_effective_group_id(p, clamp_id);
  1064. return p->uclamp[clamp_id].effective.value;
  1065. }
  1066. unsigned int uclamp_task_util(struct task_struct *p,
  1067. unsigned int clamp_id)
  1068. {
  1069. return p->uclamp[clamp_id].value;
  1070. }
  1071. /**
  1072. * uclamp_cpu_get_id(): increase reference count for a clamp group on a CPU
  1073. * @p: the task being enqueued on a CPU
  1074. * @rq: the CPU's rq where the clamp group has to be reference counted
  1075. * @clamp_id: the clamp index to update
  1076. *
  1077. * Once a task is enqueued on a CPU's rq, with increasing priority, we
  1078. * reference count the most restrictive clamp group between the task specific
  1079. * clamp value, the clamp value of its task group and the system default clamp
  1080. * value.
  1081. */
  1082. static inline void uclamp_cpu_get_id(struct task_struct *p, struct rq *rq,
  1083. unsigned int clamp_id)
  1084. {
  1085. unsigned int effective;
  1086. unsigned int group_id;
  1087. if (unlikely(!p->uclamp[clamp_id].mapped))
  1088. return;
  1089. group_id = uclamp_effective_group_id(p, clamp_id);
  1090. p->uclamp[clamp_id].active = true;
  1091. rq->uclamp.group[clamp_id][group_id].tasks += 1;
  1092. effective = p->uclamp[clamp_id].effective.value;
  1093. if (unlikely(rq->uclamp.flags & UCLAMP_FLAG_IDLE)) {
  1094. /*
  1095. * Reset clamp holds on idle exit.
  1096. * This function is called for both UCLAMP_MIN (before) and
  1097. * UCLAMP_MAX (after). Let's reset the flag only the second
  1098. * once we know that UCLAMP_MIN has been already updated.
  1099. */
  1100. if (clamp_id == UCLAMP_MAX)
  1101. rq->uclamp.flags &= ~UCLAMP_FLAG_IDLE;
  1102. rq->uclamp.value[clamp_id] = effective;
  1103. }
  1104. /* CPU's clamp groups track the max effective clamp value */
  1105. if (effective > rq->uclamp.group[clamp_id][group_id].value)
  1106. rq->uclamp.group[clamp_id][group_id].value = effective;
  1107. if (rq->uclamp.value[clamp_id] < effective)
  1108. rq->uclamp.value[clamp_id] = effective;
  1109. trace_uclamp_cpu_get_id(p, rq, clamp_id);
  1110. }
  1111. /**
  1112. * uclamp_cpu_put_id(): decrease reference count for a clamp group on a CPU
  1113. * @p: the task being dequeued from a CPU
  1114. * @rq: the CPU's rq from where the clamp group has to be released
  1115. * @clamp_id: the clamp index to update
  1116. *
  1117. * When a task is dequeued from a CPU's rq, the CPU's clamp group reference
  1118. * counted by the task is released.
  1119. * If this was the last task reference coutning the current max clamp group,
  1120. * then the CPU clamping is updated to find the new max for the specified
  1121. * clamp index.
  1122. */
  1123. static inline void uclamp_cpu_put_id(struct task_struct *p, struct rq *rq,
  1124. unsigned int clamp_id)
  1125. {
  1126. unsigned int clamp_value;
  1127. unsigned int group_id;
  1128. if (unlikely(!p->uclamp[clamp_id].mapped))
  1129. return;
  1130. group_id = uclamp_effective_group_id(p, clamp_id);
  1131. p->uclamp[clamp_id].active = false;
  1132. if (likely(rq->uclamp.group[clamp_id][group_id].tasks))
  1133. rq->uclamp.group[clamp_id][group_id].tasks -= 1;
  1134. #ifdef CONFIG_SCHED_DEBUG
  1135. else {
  1136. printk_deferred("[name:uclamp&] invalid CPU[%d] clamp group [%u:%u] refcount\n",
  1137. cpu_of(rq), clamp_id, group_id);
  1138. }
  1139. #endif
  1140. if (likely(rq->uclamp.group[clamp_id][group_id].tasks))
  1141. return;
  1142. clamp_value = rq->uclamp.group[clamp_id][group_id].value;
  1143. #ifdef CONFIG_SCHED_DEBUG
  1144. if (unlikely(clamp_value > rq->uclamp.value[clamp_id])) {
  1145. printk_deferred("[name:uclamp&] invalid CPU[%d] clamp group [%u:%u] value\n",
  1146. cpu_of(rq), clamp_id, group_id);
  1147. }
  1148. #endif
  1149. if (clamp_value >= rq->uclamp.value[clamp_id]) {
  1150. /*
  1151. * Each CPU's clamp group value is reset to its nominal group
  1152. * value whenever there are anymore RUNNABLE tasks refcounting
  1153. * that clamp group.
  1154. */
  1155. rq->uclamp.group[clamp_id][group_id].value =
  1156. uclamp_maps[clamp_id][group_id].value;
  1157. uclamp_cpu_update(rq, clamp_id, clamp_value);
  1158. }
  1159. trace_uclamp_cpu_put_id(p, rq, clamp_id, clamp_value);
  1160. }
  1161. /**
  1162. * uclamp_cpu_get(): increase CPU's clamp group refcount
  1163. * @rq: the CPU's rq where the task is enqueued
  1164. * @p: the task being enqueued
  1165. *
  1166. * When a task is enqueued on a CPU's rq, all the clamp groups currently
  1167. * enforced on a task are reference counted on that rq. Since not all
  1168. * scheduling classes have utilization clamping support, their tasks will
  1169. * be silently ignored.
  1170. *
  1171. * This method updates the utilization clamp constraints considering the
  1172. * requirements for the specified task. Thus, this update must be done before
  1173. * calling into the scheduling classes, which will eventually update schedutil
  1174. * considering the new task requirements.
  1175. */
  1176. static inline void uclamp_cpu_get(struct rq *rq, struct task_struct *p)
  1177. {
  1178. unsigned int clamp_id;
  1179. if (unlikely(!p->sched_class->uclamp_enabled))
  1180. return;
  1181. for (clamp_id = 0; clamp_id < UCLAMP_CNT; ++clamp_id)
  1182. uclamp_cpu_get_id(p, rq, clamp_id);
  1183. }
  1184. /**
  1185. * uclamp_cpu_put(): decrease CPU's clamp group refcount
  1186. * @rq: the CPU's rq from where the task is dequeued
  1187. * @p: the task being dequeued
  1188. *
  1189. * When a task is dequeued from a CPU's rq, all the clamp groups the task has
  1190. * reference counted at enqueue time are now released.
  1191. *
  1192. * This method updates the utilization clamp constraints considering the
  1193. * requirements for the specified task. Thus, this update must be done before
  1194. * calling into the scheduling classes, which will eventually update schedutil
  1195. * considering the new task requirements.
  1196. */
  1197. static inline void uclamp_cpu_put(struct rq *rq, struct task_struct *p)
  1198. {
  1199. unsigned int clamp_id;
  1200. if (unlikely(!p->sched_class->uclamp_enabled))
  1201. return;
  1202. for (clamp_id = 0; clamp_id < UCLAMP_CNT; ++clamp_id)
  1203. uclamp_cpu_put_id(p, rq, clamp_id);
  1204. }
  1205. /**
  1206. * uclamp_task_update_active: update the clamp group of a RUNNABLE task
  1207. * @p: the task which clamp groups must be updated
  1208. * @clamp_id: the clamp index to consider
  1209. *
  1210. * Each time the clamp value of a task group is changed, the old and new clamp
  1211. * groups must be updated for each CPU containing a RUNNABLE task belonging to
  1212. * that task group. Sleeping tasks are not updated since they will be enqueued
  1213. * with the proper clamp group index at their next activation.
  1214. */
  1215. static inline void
  1216. uclamp_task_update_active(struct task_struct *p, unsigned int clamp_id)
  1217. {
  1218. struct rq_flags rf;
  1219. struct rq *rq;
  1220. /*
  1221. * Lock the task and the CPU where the task is (or was) queued.
  1222. *
  1223. * We might lock the (previous) rq of a !RUNNABLE task, but that's the
  1224. * price to pay to safely serialize util_{min,max} updates with
  1225. * enqueues, dequeues and migration operations.
  1226. * This is the same locking schema used by __set_cpus_allowed_ptr().
  1227. */
  1228. rq = task_rq_lock(p, &rf);
  1229. /*
  1230. * The setting of the clamp group is serialized by task_rq_lock().
  1231. * Thus, if the task is not yet RUNNABLE and its task_struct is not
  1232. * affecting a valid clamp group, then the next time it's going to be
  1233. * enqueued it will already see the updated clamp group value.
  1234. */
  1235. if (!p->uclamp[clamp_id].active)
  1236. goto done;
  1237. uclamp_cpu_put_id(p, rq, clamp_id);
  1238. uclamp_cpu_get_id(p, rq, clamp_id);
  1239. done:
  1240. task_rq_unlock(rq, p, &rf);
  1241. }
  1242. /**
  1243. * uclamp_group_put: decrease the reference count for a clamp group
  1244. * @clamp_id: the clamp index which was affected by a task group
  1245. * @group_id: the clamp group to release
  1246. *
  1247. * When the clamp value for a task group is changed we decrease the reference
  1248. * count for the clamp group mapping its current clamp value.
  1249. */
  1250. void uclamp_group_put(unsigned int clamp_id, unsigned int group_id)
  1251. {
  1252. union uclamp_map *uc_maps = &uclamp_maps[clamp_id][0];
  1253. union uclamp_map uc_map_old, uc_map_new;
  1254. long res;
  1255. retry:
  1256. uc_map_old.data = atomic_long_read(&uc_maps[group_id].adata);
  1257. #ifdef CONFIG_SCHED_DEBUG
  1258. #define UCLAMP_GRPERR "invalid SE clamp group [%u:%u] refcount\n"
  1259. if (unlikely(!uc_map_old.se_count)) {
  1260. pr_err_ratelimited(UCLAMP_GRPERR, clamp_id, group_id);
  1261. return;
  1262. }
  1263. #endif
  1264. uc_map_new = uc_map_old;
  1265. uc_map_new.se_count -= 1;
  1266. res = atomic_long_cmpxchg(&uc_maps[group_id].adata,
  1267. uc_map_old.data, uc_map_new.data);
  1268. if (res != uc_map_old.data)
  1269. goto retry;
  1270. }
  1271. static inline void uclamp_group_get_tg(struct cgroup_subsys_state *css,
  1272. int clamp_id, unsigned int group_id)
  1273. {
  1274. struct css_task_iter it;
  1275. struct task_struct *p;
  1276. /*
  1277. * In lazy update mode, tasks will be accounted into the right clamp
  1278. * group the next time they will be requeued.
  1279. */
  1280. if (unlikely(sched_feat(UCLAMP_LAZY_UPDATE)))
  1281. return;
  1282. /* Update clamp groups for RUNNABLE tasks in this TG */
  1283. css_task_iter_start(css, 0, &it);
  1284. while ((p = css_task_iter_next(&it)))
  1285. uclamp_task_update_active(p, clamp_id);
  1286. css_task_iter_end(&it);
  1287. }
  1288. /**
  1289. * uclamp_group_get: increase the reference count for a clamp group
  1290. * @p: the task which clamp value must be tracked
  1291. * @css: the task group which clamp value must be tracked
  1292. * @uc_se: the utilization clamp data for the task
  1293. * @clamp_id: the clamp index affected by the task
  1294. * @clamp_value: the new clamp value for the task
  1295. *
  1296. * Each time a task changes its utilization clamp value, for a specified clamp
  1297. * index, we need to find an available clamp group which can be used to track
  1298. * this new clamp value. The corresponding clamp group index will be used to
  1299. * reference count the corresponding clamp value while the task is enqueued on
  1300. * a CPU.
  1301. */
  1302. void uclamp_group_get(struct task_struct *p,
  1303. struct cgroup_subsys_state *css,
  1304. struct uclamp_se *uc_se,
  1305. unsigned int clamp_id, unsigned int clamp_value)
  1306. {
  1307. union uclamp_map *uc_maps = &uclamp_maps[clamp_id][0];
  1308. unsigned int prev_group_id = uc_se->group_id;
  1309. union uclamp_map uc_map_old, uc_map_new;
  1310. unsigned int free_group_id;
  1311. unsigned int group_value;
  1312. unsigned int group_id;
  1313. unsigned long res;
  1314. int cpu;
  1315. #ifdef CONFIG_UCLAMP_MAP_OPP
  1316. group_value = clamp_value;
  1317. #else
  1318. group_value = uclamp_group_value(clamp_value);
  1319. #endif
  1320. retry:
  1321. free_group_id = UCLAMP_GROUPS;
  1322. for (group_id = 0; group_id < UCLAMP_GROUPS; ++group_id) {
  1323. uc_map_old.data = atomic_long_read(&uc_maps[group_id].adata);
  1324. if (free_group_id == UCLAMP_GROUPS && !uc_map_old.se_count)
  1325. free_group_id = group_id;
  1326. if (uc_map_old.value == group_value)
  1327. break;
  1328. }
  1329. if (group_id >= UCLAMP_GROUPS) {
  1330. #ifdef CONFIG_SCHED_DEBUG
  1331. #define UCLAMP_MAPERR "clamp value [%u] mapping to clamp group failed\n"
  1332. if (unlikely(free_group_id == UCLAMP_GROUPS)) {
  1333. pr_err_ratelimited(UCLAMP_MAPERR, clamp_value);
  1334. return;
  1335. }
  1336. #endif
  1337. group_id = free_group_id;
  1338. uc_map_old.data = atomic_long_read(&uc_maps[group_id].adata);
  1339. }
  1340. uc_map_new.se_count = uc_map_old.se_count + 1;
  1341. uc_map_new.value = group_value;
  1342. res = atomic_long_cmpxchg(&uc_maps[group_id].adata,
  1343. uc_map_old.data, uc_map_new.data);
  1344. if (res != uc_map_old.data)
  1345. goto retry;
  1346. /* Ensure each CPU tracks the correct value for this clamp group */
  1347. if (likely(uc_map_new.se_count > 1))
  1348. goto done;
  1349. for_each_possible_cpu(cpu) {
  1350. struct uclamp_cpu *uc_cpu = &cpu_rq(cpu)->uclamp;
  1351. /* Refcounting is expected to be always 0 for free groups */
  1352. if (unlikely(uc_cpu->group[clamp_id][group_id].tasks)) {
  1353. #ifdef CONFIG_SCHED_DEBUG
  1354. WARN(1, "invalid CPU[%d] clamp group [%u:%u] refcount: [%u]\n",
  1355. cpu, clamp_id, group_id,
  1356. uc_cpu->group[clamp_id][group_id].tasks);
  1357. #endif
  1358. uc_cpu->group[clamp_id][group_id].tasks = 0;
  1359. }
  1360. if (uc_cpu->group[clamp_id][group_id].value == group_value)
  1361. continue;
  1362. uc_cpu->group[clamp_id][group_id].value = group_value;
  1363. }
  1364. done:
  1365. /* Update SE's clamp values and attach it to new clamp group */
  1366. uc_se->value = clamp_value;
  1367. uc_se->group_id = group_id;
  1368. /* Newly created TG don't have tasks assigned */
  1369. if (css) {
  1370. uc_se->effective.value = clamp_value;
  1371. uc_se->effective.group_id = group_id;
  1372. uclamp_group_get_tg(css, clamp_id, group_id);
  1373. }
  1374. /* Update CPU's clamp group refcounts of RUNNABLE task */
  1375. if (p)
  1376. uclamp_task_update_active(p, clamp_id);
  1377. /* Release the previous clamp group */
  1378. if (uc_se->mapped)
  1379. uclamp_group_put(clamp_id, prev_group_id);
  1380. uc_se->mapped = true;
  1381. }
  1382. int sched_uclamp_handler(struct ctl_table *table, int write,
  1383. void __user *buffer, size_t *lenp,
  1384. loff_t *ppos)
  1385. {
  1386. int old_min, old_max;
  1387. int result = 0;
  1388. mutex_lock(&uclamp_mutex);
  1389. old_min = sysctl_sched_uclamp_util_min;
  1390. old_max = sysctl_sched_uclamp_util_max;
  1391. result = proc_dointvec(table, write, buffer, lenp, ppos);
  1392. if (result)
  1393. goto undo;
  1394. if (!write)
  1395. goto done;
  1396. if (sysctl_sched_uclamp_util_min > sysctl_sched_uclamp_util_max ||
  1397. sysctl_sched_uclamp_util_max > SCHED_CAPACITY_SCALE) {
  1398. result = -EINVAL;
  1399. goto undo;
  1400. }
  1401. sysctl_sched_uclamp_util_min =
  1402. find_fit_capacity(sysctl_sched_uclamp_util_min);
  1403. sysctl_sched_uclamp_util_max =
  1404. find_fit_capacity(sysctl_sched_uclamp_util_max);
  1405. if (old_min != sysctl_sched_uclamp_util_min) {
  1406. uclamp_group_get(NULL, NULL, &uclamp_default[UCLAMP_MIN],
  1407. UCLAMP_MIN, sysctl_sched_uclamp_util_min);
  1408. }
  1409. if (old_max != sysctl_sched_uclamp_util_max) {
  1410. uclamp_group_get(NULL, NULL, &uclamp_default[UCLAMP_MAX],
  1411. UCLAMP_MAX, sysctl_sched_uclamp_util_max);
  1412. }
  1413. goto done;
  1414. undo:
  1415. sysctl_sched_uclamp_util_min = old_min;
  1416. sysctl_sched_uclamp_util_max = old_max;
  1417. done:
  1418. mutex_unlock(&uclamp_mutex);
  1419. return result;
  1420. }
  1421. #if defined(CONFIG_UCLAMP_TASK_GROUP) && !defined(CONFIG_SCHED_TUNE)
  1422. /*
  1423. * free_uclamp_sched_group: release utilization clamp references of a TG
  1424. * @tg: the task group being removed
  1425. *
  1426. * An empty task group can be removed only when it has no more tasks or child
  1427. * groups. This means that we can also safely release all the reference
  1428. * counting to clamp groups.
  1429. */
  1430. static inline void free_uclamp_sched_group(struct task_group *tg)
  1431. {
  1432. int clamp_id;
  1433. for (clamp_id = 0; clamp_id < UCLAMP_CNT; ++clamp_id)
  1434. uclamp_group_put(clamp_id, tg->uclamp[clamp_id].group_id);
  1435. }
  1436. /**
  1437. * alloc_uclamp_sched_group: initialize a new TG's for utilization clamping
  1438. * @tg: the newly created task group
  1439. * @parent: its parent task group
  1440. *
  1441. * A newly created task group inherits its utilization clamp values, for all
  1442. * clamp indexes, from its parent task group.
  1443. * This ensures that its values are properly initialized and that the task
  1444. * group is accounted in the same parent's group index.
  1445. *
  1446. * Return: 0 on error
  1447. */
  1448. static inline int alloc_uclamp_sched_group(struct task_group *tg,
  1449. struct task_group *parent)
  1450. {
  1451. int clamp_id;
  1452. for (clamp_id = 0; clamp_id < UCLAMP_CNT; ++clamp_id) {
  1453. uclamp_group_get(NULL, NULL, &tg->uclamp[clamp_id],
  1454. clamp_id, parent->uclamp[clamp_id].value);
  1455. tg->uclamp[clamp_id].effective.value =
  1456. parent->uclamp[clamp_id].effective.value;
  1457. tg->uclamp[clamp_id].effective.group_id =
  1458. parent->uclamp[clamp_id].effective.group_id;
  1459. }
  1460. return 1;
  1461. }
  1462. #else /* CONFIG_UCLAMP_TASK_GROUP */
  1463. static inline void free_uclamp_sched_group(struct task_group *tg) { }
  1464. static inline int alloc_uclamp_sched_group(struct task_group *tg,
  1465. struct task_group *parent)
  1466. {
  1467. return 1;
  1468. }
  1469. #endif /* CONFIG_UCLAMP_TASK_GROUP */
  1470. /**
  1471. * uclamp_exit_task: release referenced clamp groups
  1472. * @p: the task exiting
  1473. *
  1474. * When a task terminates, release all its (eventually) refcounted
  1475. * task-specific clamp groups.
  1476. */
  1477. void uclamp_exit_task(struct task_struct *p)
  1478. {
  1479. unsigned int clamp_id;
  1480. if (unlikely(!p->sched_class->uclamp_enabled))
  1481. return;
  1482. for (clamp_id = 0; clamp_id < UCLAMP_CNT; ++clamp_id) {
  1483. if (!p->uclamp[clamp_id].mapped)
  1484. continue;
  1485. uclamp_group_put(clamp_id, p->uclamp[clamp_id].group_id);
  1486. }
  1487. }
  1488. /**
  1489. * uclamp_fork: refcount task-specific clamp values for a new task
  1490. */
  1491. static void uclamp_fork(struct task_struct *p, bool reset)
  1492. {
  1493. unsigned int clamp_id;
  1494. if (unlikely(!p->sched_class->uclamp_enabled))
  1495. return;
  1496. for (clamp_id = 0; clamp_id < UCLAMP_CNT; ++clamp_id) {
  1497. unsigned int clamp_value = uclamp_none(clamp_id);
  1498. memset(&p->uclamp[clamp_id], 0, sizeof(struct uclamp_se));
  1499. p->uclamp[clamp_id].user_defined = false;
  1500. p->uclamp[clamp_id].mapped = false;
  1501. p->uclamp[clamp_id].active = false;
  1502. uclamp_group_get(p, NULL, &p->uclamp[clamp_id],
  1503. clamp_id, clamp_value);
  1504. }
  1505. }
  1506. static struct task_struct *find_process_by_pid(pid_t pid);
  1507. int set_task_util_min(pid_t pid, unsigned int util_min)
  1508. {
  1509. unsigned int upper_bound;
  1510. struct task_struct *p;
  1511. int ret = 0;
  1512. if (!opp_capacity_tbl_ready)
  1513. init_opp_capacity_tbl();
  1514. util_min = find_fit_capacity(util_min);
  1515. mutex_lock(&uclamp_mutex);
  1516. rcu_read_lock();
  1517. p = find_process_by_pid(pid);
  1518. if (!p) {
  1519. ret = -ESRCH;
  1520. goto out;
  1521. }
  1522. upper_bound = p->uclamp[UCLAMP_MAX].value;
  1523. if (util_min > upper_bound || util_min < 0) {
  1524. ret = -EINVAL;
  1525. goto out;
  1526. }
  1527. p->uclamp[UCLAMP_MIN].user_defined = true;
  1528. uclamp_group_get(p, NULL, &p->uclamp[UCLAMP_MIN],
  1529. UCLAMP_MIN, util_min);
  1530. out:
  1531. rcu_read_unlock();
  1532. mutex_unlock(&uclamp_mutex);
  1533. return ret;
  1534. }
  1535. EXPORT_SYMBOL(set_task_util_min);
  1536. int set_task_util_min_pct(pid_t pid, unsigned int pct)
  1537. {
  1538. unsigned int util_min;
  1539. if (pid <= 0)
  1540. return -EINVAL;
  1541. if (pct < 0 || pct > 100)
  1542. return -ERANGE;
  1543. util_min = scale_from_percent(pct);
  1544. return set_task_util_min(pid, util_min);
  1545. }
  1546. EXPORT_SYMBOL(set_task_util_min_pct);
  1547. int set_task_util_max(pid_t pid, unsigned int util_max)
  1548. {
  1549. unsigned int lower_bound;
  1550. struct task_struct *p;
  1551. int ret = 0;
  1552. if (!opp_capacity_tbl_ready)
  1553. init_opp_capacity_tbl();
  1554. util_max = find_fit_capacity(util_max);
  1555. mutex_lock(&uclamp_mutex);
  1556. rcu_read_lock();
  1557. p = find_process_by_pid(pid);
  1558. if (!p) {
  1559. ret = -ESRCH;
  1560. goto out;
  1561. }
  1562. lower_bound = p->uclamp[UCLAMP_MIN].value;
  1563. if (util_max < lower_bound || util_max > 1024) {
  1564. ret = -EINVAL;
  1565. goto out;
  1566. }
  1567. p->uclamp[UCLAMP_MAX].user_defined = true;
  1568. uclamp_group_get(p, NULL, &p->uclamp[UCLAMP_MAX],
  1569. UCLAMP_MAX, util_max);
  1570. out:
  1571. rcu_read_unlock();
  1572. mutex_unlock(&uclamp_mutex);
  1573. return ret;
  1574. }
  1575. EXPORT_SYMBOL(set_task_util_max);
  1576. int set_task_util_max_pct(pid_t pid, unsigned int pct)
  1577. {
  1578. unsigned int util_max;
  1579. if (pid <= 0)
  1580. return -EINVAL;
  1581. if (pct < 0 || pct > 100)
  1582. return -ERANGE;
  1583. util_max = scale_from_percent(pct);
  1584. return set_task_util_max(pid, util_max);
  1585. }
  1586. EXPORT_SYMBOL(set_task_util_max_pct);
  1587. /**
  1588. * init_uclamp: initialize data structures required for utilization clamping
  1589. */
  1590. static void __init init_uclamp(void)
  1591. {
  1592. struct uclamp_se *uc_se;
  1593. unsigned int clamp_id;
  1594. int cpu;
  1595. mutex_init(&uclamp_mutex);
  1596. for_each_possible_cpu(cpu)
  1597. memset(&cpu_rq(cpu)->uclamp, 0, sizeof(struct uclamp_cpu));
  1598. memset(uclamp_maps, 0, sizeof(uclamp_maps));
  1599. for (clamp_id = 0; clamp_id < UCLAMP_CNT; ++clamp_id) {
  1600. uc_se = &init_task.uclamp[clamp_id];
  1601. uclamp_group_get(NULL, NULL, uc_se, clamp_id,
  1602. uclamp_none(clamp_id));
  1603. uc_se = &uclamp_default[clamp_id];
  1604. uclamp_group_get(NULL, NULL, uc_se, clamp_id,
  1605. uclamp_none(clamp_id));
  1606. /* RT tasks by default will go to max frequency */
  1607. uc_se = &uclamp_default_perf[clamp_id];
  1608. uclamp_group_get(NULL, NULL, uc_se, clamp_id,
  1609. uclamp_none(UCLAMP_MAX));
  1610. #if defined(CONFIG_UCLAMP_TASK_GROUP) && defined(CONFIG_SCHED_TUNE)
  1611. schedtune_init_uclamp();
  1612. #elif defined(CONFIG_UCLAMP_TASK_GROUP)
  1613. /* Init root TG's clamp group */
  1614. uc_se = &root_task_group.uclamp[clamp_id];
  1615. uclamp_group_get(NULL, NULL, uc_se, clamp_id,
  1616. uclamp_none(UCLAMP_MAX));
  1617. uc_se->effective.group_id = uc_se->group_id;
  1618. uc_se->effective.value = uc_se->value;
  1619. #endif
  1620. }
  1621. }
  1622. #else /* CONFIG_UCLAMP_TASK */
  1623. unsigned int uclamp_task_effective_util(struct task_struct *p,
  1624. unsigned int clamp_id)
  1625. {
  1626. return 0;
  1627. }
  1628. unsigned int uclamp_task_util(struct task_struct *p,
  1629. unsigned int clamp_id)
  1630. {
  1631. return 0;
  1632. }
  1633. static inline void uclamp_fork(struct task_struct *p, bool reset) { }
  1634. static inline void init_uclamp(void) { }
  1635. static inline void uclamp_cpu_get(struct rq *rq, struct task_struct *p) { }
  1636. static inline void uclamp_cpu_put(struct rq *rq, struct task_struct *p) { }
  1637. #endif /* CONFIG_UCLAMP_TASK */
  1638. void set_capacity_margin(unsigned int margin)
  1639. {
  1640. capacity_margin = margin;
  1641. }
  1642. EXPORT_SYMBOL(set_capacity_margin);
  1643. unsigned int get_capacity_margin(void)
  1644. {
  1645. return capacity_margin;
  1646. }
  1647. EXPORT_SYMBOL(get_capacity_margin);
  1648. static inline void enqueue_task(struct rq *rq, struct task_struct *p, int flags)
  1649. {
  1650. if (!(flags & ENQUEUE_NOCLOCK))
  1651. update_rq_clock(rq);
  1652. if (!(flags & ENQUEUE_RESTORE)) {
  1653. sched_info_queued(rq, p);
  1654. psi_enqueue(p, flags & ENQUEUE_WAKEUP);
  1655. }
  1656. uclamp_cpu_get(rq, p);
  1657. p->sched_class->enqueue_task(rq, p, flags);
  1658. /* update last_enqueued_ts for big task rotation */
  1659. p->last_enqueued_ts = ktime_get_ns();
  1660. }
  1661. static inline void dequeue_task(struct rq *rq, struct task_struct *p, int flags)
  1662. {
  1663. if (!(flags & DEQUEUE_NOCLOCK))
  1664. update_rq_clock(rq);
  1665. if (!(flags & DEQUEUE_SAVE)) {
  1666. sched_info_dequeued(rq, p);
  1667. psi_dequeue(p, flags & DEQUEUE_SLEEP);
  1668. }
  1669. uclamp_cpu_put(rq, p);
  1670. p->sched_class->dequeue_task(rq, p, flags);
  1671. }
  1672. void activate_task(struct rq *rq, struct task_struct *p, int flags)
  1673. {
  1674. if (task_contributes_to_load(p))
  1675. rq->nr_uninterruptible--;
  1676. enqueue_task(rq, p, flags);
  1677. }
  1678. void deactivate_task(struct rq *rq, struct task_struct *p, int flags)
  1679. {
  1680. if (task_contributes_to_load(p))
  1681. rq->nr_uninterruptible++;
  1682. dequeue_task(rq, p, flags);
  1683. }
  1684. /*
  1685. * __normal_prio - return the priority that is based on the static prio
  1686. */
  1687. static inline int __normal_prio(struct task_struct *p)
  1688. {
  1689. return p->static_prio;
  1690. }
  1691. /*
  1692. * Calculate the expected normal priority: i.e. priority
  1693. * without taking RT-inheritance into account. Might be
  1694. * boosted by interactivity modifiers. Changes upon fork,
  1695. * setprio syscalls, and whenever the interactivity
  1696. * estimator recalculates.
  1697. */
  1698. static inline int normal_prio(struct task_struct *p)
  1699. {
  1700. int prio;
  1701. if (task_has_dl_policy(p))
  1702. prio = MAX_DL_PRIO-1;
  1703. else if (task_has_rt_policy(p))
  1704. prio = MAX_RT_PRIO-1 - p->rt_priority;
  1705. else
  1706. prio = __normal_prio(p);
  1707. return prio;
  1708. }
  1709. /*
  1710. * Calculate the current priority, i.e. the priority
  1711. * taken into account by the scheduler. This value might
  1712. * be boosted by RT tasks, or might be boosted by
  1713. * interactivity modifiers. Will be RT if the task got
  1714. * RT-boosted. If not then it returns p->normal_prio.
  1715. */
  1716. static int effective_prio(struct task_struct *p)
  1717. {
  1718. p->normal_prio = normal_prio(p);
  1719. /*
  1720. * If we are RT tasks or we were boosted to RT priority,
  1721. * keep the priority unchanged. Otherwise, update priority
  1722. * to the normal priority:
  1723. */
  1724. if (!rt_prio(p->prio))
  1725. return p->normal_prio;
  1726. return p->prio;
  1727. }
  1728. /**
  1729. * task_curr - is this task currently executing on a CPU?
  1730. * @p: the task in question.
  1731. *
  1732. * Return: 1 if the task is currently executing. 0 otherwise.
  1733. */
  1734. inline int task_curr(const struct task_struct *p)
  1735. {
  1736. return cpu_curr(task_cpu(p)) == p;
  1737. }
  1738. /*
  1739. * switched_from, switched_to and prio_changed must _NOT_ drop rq->lock,
  1740. * use the balance_callback list if you want balancing.
  1741. *
  1742. * this means any call to check_class_changed() must be followed by a call to
  1743. * balance_callback().
  1744. */
  1745. static inline void check_class_changed(struct rq *rq, struct task_struct *p,
  1746. const struct sched_class *prev_class,
  1747. int oldprio)
  1748. {
  1749. if (prev_class != p->sched_class) {
  1750. if (prev_class->switched_from)
  1751. prev_class->switched_from(rq, p);
  1752. p->sched_class->switched_to(rq, p);
  1753. } else if (oldprio != p->prio || dl_task(p))
  1754. p->sched_class->prio_changed(rq, p, oldprio);
  1755. }
  1756. void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
  1757. {
  1758. const struct sched_class *class;
  1759. if (p->sched_class == rq->curr->sched_class) {
  1760. rq->curr->sched_class->check_preempt_curr(rq, p, flags);
  1761. } else {
  1762. for_each_class(class) {
  1763. if (class == rq->curr->sched_class)
  1764. break;
  1765. if (class == p->sched_class) {
  1766. resched_curr(rq);
  1767. break;
  1768. }
  1769. }
  1770. }
  1771. /*
  1772. * A queue event has occurred, and we're going to schedule. In
  1773. * this case, we can save a useless back to back clock update.
  1774. */
  1775. if (task_on_rq_queued(rq->curr) && test_tsk_need_resched(rq->curr))
  1776. rq_clock_skip_update(rq, true);
  1777. }
  1778. #ifdef CONFIG_SMP
  1779. static inline bool is_per_cpu_kthread(struct task_struct *p)
  1780. {
  1781. if (!(p->flags & PF_KTHREAD))
  1782. return false;
  1783. if (p->nr_cpus_allowed != 1)
  1784. return false;
  1785. return true;
  1786. }
  1787. /*
  1788. * Per-CPU kthreads are allowed to run on !actie && online CPUs, see
  1789. * __set_cpus_allowed_ptr() and select_fallback_rq().
  1790. */
  1791. static inline bool is_cpu_allowed(struct task_struct *p, int cpu)
  1792. {
  1793. if (!cpumask_test_cpu(cpu, &p->cpus_allowed))
  1794. return false;
  1795. if (is_per_cpu_kthread(p))
  1796. return cpu_online(cpu);
  1797. return cpu_active(cpu);
  1798. }
  1799. /*
  1800. * This is how migration works:
  1801. *
  1802. * 1) we invoke migration_cpu_stop() on the target CPU using
  1803. * stop_one_cpu().
  1804. * 2) stopper starts to run (implicitly forcing the migrated thread
  1805. * off the CPU)
  1806. * 3) it checks whether the migrated task is still in the wrong runqueue.
  1807. * 4) if it's in the wrong runqueue then the migration thread removes
  1808. * it and puts it into the right queue.
  1809. * 5) stopper completes and stop_one_cpu() returns and the migration
  1810. * is done.
  1811. */
  1812. /*
  1813. * move_queued_task - move a queued task to new rq.
  1814. *
  1815. * Returns (locked) new rq. Old rq's lock is released.
  1816. */
  1817. static struct rq *move_queued_task(struct rq *rq, struct rq_flags *rf,
  1818. struct task_struct *p, int new_cpu)
  1819. {
  1820. lockdep_assert_held(&rq->lock);
  1821. p->on_rq = TASK_ON_RQ_MIGRATING;
  1822. dequeue_task(rq, p, DEQUEUE_NOCLOCK);
  1823. rq_unpin_lock(rq, rf);
  1824. double_lock_balance(rq, cpu_rq(new_cpu));
  1825. set_task_cpu(p, new_cpu);
  1826. double_rq_unlock(cpu_rq(new_cpu), rq);
  1827. rq = cpu_rq(new_cpu);
  1828. rq_lock(rq, rf);
  1829. BUG_ON(task_cpu(p) != new_cpu);
  1830. enqueue_task(rq, p, 0);
  1831. p->on_rq = TASK_ON_RQ_QUEUED;
  1832. check_preempt_curr(rq, p, 0);
  1833. return rq;
  1834. }
  1835. struct migration_arg {
  1836. struct task_struct *task;
  1837. int dest_cpu;
  1838. };
  1839. /*
  1840. * Move (not current) task off this CPU, onto the destination CPU. We're doing
  1841. * this because either it can't run here any more (set_cpus_allowed()
  1842. * away from this CPU, or CPU going down), or because we're
  1843. * attempting to rebalance this task on exec (sched_exec).
  1844. *
  1845. * So we race with normal scheduler movements, but that's OK, as long
  1846. * as the task is no longer on this CPU.
  1847. */
  1848. struct rq *__migrate_task(struct rq *rq, struct rq_flags *rf,
  1849. struct task_struct *p, int dest_cpu)
  1850. {
  1851. /* Affinity changed (again). */
  1852. if (!is_cpu_allowed(p, dest_cpu))
  1853. return rq;
  1854. update_rq_clock(rq);
  1855. rq = move_queued_task(rq, rf, p, dest_cpu);
  1856. return rq;
  1857. }
  1858. /*
  1859. * migration_cpu_stop - this will be executed by a highprio stopper thread
  1860. * and performs thread migration by bumping thread off CPU then
  1861. * 'pushing' onto another runqueue.
  1862. */
  1863. static int migration_cpu_stop(void *data)
  1864. {
  1865. struct migration_arg *arg = data;
  1866. struct task_struct *p = arg->task;
  1867. struct rq *rq = this_rq();
  1868. struct rq_flags rf;
  1869. /*
  1870. * The original target CPU might have gone down and we might
  1871. * be on another CPU but it doesn't matter.
  1872. */
  1873. local_irq_disable();
  1874. /*
  1875. * We need to explicitly wake pending tasks before running
  1876. * __migrate_task() such that we will not miss enforcing cpus_allowed
  1877. * during wakeups, see set_cpus_allowed_ptr()'s TASK_WAKING test.
  1878. */
  1879. sched_ttwu_pending();
  1880. raw_spin_lock(&p->pi_lock);
  1881. rq_lock(rq, &rf);
  1882. /*
  1883. * If task_rq(p) != rq, it cannot be migrated here, because we're
  1884. * holding rq->lock, if p->on_rq == 0 it cannot get enqueued because
  1885. * we're holding p->pi_lock.
  1886. */
  1887. if (task_rq(p) == rq) {
  1888. if (task_on_rq_queued(p))
  1889. rq = __migrate_task(rq, &rf, p, arg->dest_cpu);
  1890. else
  1891. p->wake_cpu = arg->dest_cpu;
  1892. }
  1893. rq_unlock(rq, &rf);
  1894. raw_spin_unlock(&p->pi_lock);
  1895. local_irq_enable();
  1896. return 0;
  1897. }
  1898. /*
  1899. * sched_class::set_cpus_allowed must do the below, but is not required to
  1900. * actually call this function.
  1901. */
  1902. void set_cpus_allowed_common(struct task_struct *p, const struct cpumask *new_mask)
  1903. {
  1904. cpumask_copy(&p->cpus_allowed, new_mask);
  1905. p->nr_cpus_allowed = cpumask_weight(new_mask);
  1906. }
  1907. void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask)
  1908. {
  1909. struct rq *rq = task_rq(p);
  1910. bool queued, running;
  1911. lockdep_assert_held(&p->pi_lock);
  1912. queued = task_on_rq_queued(p);
  1913. running = task_current(rq, p);
  1914. if (queued) {
  1915. /*
  1916. * Because __kthread_bind() calls this on blocked tasks without
  1917. * holding rq->lock.
  1918. */
  1919. lockdep_assert_held(&rq->lock);
  1920. dequeue_task(rq, p, DEQUEUE_SAVE | DEQUEUE_NOCLOCK);
  1921. }
  1922. if (running)
  1923. put_prev_task(rq, p);
  1924. p->sched_class->set_cpus_allowed(p, new_mask);
  1925. if (queued)
  1926. enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
  1927. if (running)
  1928. set_curr_task(rq, p);
  1929. }
  1930. /*
  1931. * Change a given task's CPU affinity. Migrate the thread to a
  1932. * proper CPU and schedule it away if the CPU it's executing on
  1933. * is removed from the allowed bitmask.
  1934. *
  1935. * NOTE: the caller must have a valid reference to the task, the
  1936. * task must not exit() & deallocate itself prematurely. The
  1937. * call is not atomic; no spinlocks may be held.
  1938. */
  1939. static int __set_cpus_allowed_ptr(struct task_struct *p,
  1940. const struct cpumask *new_mask, bool check)
  1941. {
  1942. const struct cpumask *cpu_valid_mask = cpu_active_mask;
  1943. unsigned int dest_cpu;
  1944. struct rq_flags rf;
  1945. struct rq *rq;
  1946. int ret = 0;
  1947. cpumask_t allowed_mask;
  1948. rq = task_rq_lock(p, &rf);
  1949. update_rq_clock(rq);
  1950. if (p->flags & PF_KTHREAD) {
  1951. /*
  1952. * Kernel threads are allowed on online && !active CPUs
  1953. */
  1954. cpu_valid_mask = cpu_online_mask;
  1955. }
  1956. /*
  1957. * Must re-check here, to close a race against __kthread_bind(),
  1958. * sched_setaffinity() is not guaranteed to observe the flag.
  1959. */
  1960. if (check && (p->flags & PF_NO_SETAFFINITY)) {
  1961. ret = -EINVAL;
  1962. goto out;
  1963. }
  1964. if (cpumask_equal(&p->cpus_allowed, new_mask))
  1965. goto out;
  1966. cpumask_andnot(&allowed_mask, new_mask, cpu_isolated_mask);
  1967. cpumask_and(&allowed_mask, &allowed_mask, cpu_valid_mask);
  1968. dest_cpu = cpumask_any(&allowed_mask);
  1969. if (dest_cpu >= nr_cpu_ids) {
  1970. /* If p is a kthread, ignore isolated mask. */
  1971. if (p->flags & PF_KTHREAD)
  1972. cpumask_and(&allowed_mask, cpu_valid_mask, new_mask);
  1973. else
  1974. cpumask_andnot(&allowed_mask,
  1975. cpu_valid_mask, cpu_isolated_mask);
  1976. dest_cpu = cpumask_any(&allowed_mask);
  1977. if (dest_cpu >= nr_cpu_ids) {
  1978. ret = -EINVAL;
  1979. goto out;
  1980. }
  1981. }
  1982. do_set_cpus_allowed(p, new_mask);
  1983. if (p->flags & PF_KTHREAD) {
  1984. /*
  1985. * For kernel threads that do indeed end up on online &&
  1986. * !active we want to ensure they are strict per-CPU threads.
  1987. */
  1988. WARN_ON(cpumask_intersects(new_mask, cpu_online_mask) &&
  1989. !cpumask_intersects(new_mask, cpu_active_mask) &&
  1990. p->nr_cpus_allowed != 1);
  1991. }
  1992. /* Can the task run on the task's current CPU? If so, we're done */
  1993. if (cpumask_test_cpu(task_cpu(p), &allowed_mask))
  1994. goto out;
  1995. if (task_running(rq, p) || p->state == TASK_WAKING) {
  1996. struct migration_arg arg = { p, dest_cpu };
  1997. /* Need help from migration thread: drop lock and wait. */
  1998. task_rq_unlock(rq, p, &rf);
  1999. stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg);
  2000. tlb_migrate_finish(p->mm);
  2001. return 0;
  2002. } else if (task_on_rq_queued(p)) {
  2003. /*
  2004. * OK, since we're going to drop the lock immediately
  2005. * afterwards anyway.
  2006. */
  2007. if (cpu_online(dest_cpu))
  2008. rq = move_queued_task(rq, &rf, p, dest_cpu);
  2009. }
  2010. out:
  2011. task_rq_unlock(rq, p, &rf);
  2012. return ret;
  2013. }
  2014. int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
  2015. {
  2016. return __set_cpus_allowed_ptr(p, new_mask, false);
  2017. }
  2018. EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
  2019. void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
  2020. {
  2021. #ifdef CONFIG_SCHED_DEBUG
  2022. /*
  2023. * We should never call set_task_cpu() on a blocked task,
  2024. * ttwu() will sort out the placement.
  2025. */
  2026. WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING &&
  2027. !p->on_rq);
  2028. /*
  2029. * Migrating fair class task must have p->on_rq = TASK_ON_RQ_MIGRATING,
  2030. * because schedstat_wait_{start,end} rebase migrating task's wait_start
  2031. * time relying on p->on_rq.
  2032. */
  2033. WARN_ON_ONCE(p->state == TASK_RUNNING &&
  2034. p->sched_class == &fair_sched_class &&
  2035. (p->on_rq && !task_on_rq_migrating(p)));
  2036. #ifdef CONFIG_LOCKDEP
  2037. /*
  2038. * The caller should hold either p->pi_lock or rq->lock, when changing
  2039. * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks.
  2040. *
  2041. * sched_move_task() holds both and thus holding either pins the cgroup,
  2042. * see task_group().
  2043. *
  2044. * Furthermore, all task_rq users should acquire both locks, see
  2045. * task_rq_lock().
  2046. */
  2047. WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) ||
  2048. lockdep_is_held(&task_rq(p)->lock)));
  2049. #endif
  2050. /*
  2051. * Clearly, migrating tasks to offline CPUs is a fairly daft thing.
  2052. */
  2053. WARN_ON_ONCE(!cpu_online(new_cpu));
  2054. #endif
  2055. trace_sched_migrate_task(p, new_cpu);
  2056. if (task_cpu(p) != new_cpu) {
  2057. if (p->sched_class->migrate_task_rq)
  2058. p->sched_class->migrate_task_rq(p);
  2059. p->se.nr_migrations++;
  2060. perf_event_task_migrate(p);
  2061. walt_fixup_busy_time(p, new_cpu);
  2062. }
  2063. __set_task_cpu(p, new_cpu);
  2064. }
  2065. static void __migrate_swap_task(struct task_struct *p, int cpu)
  2066. {
  2067. if (task_on_rq_queued(p)) {
  2068. struct rq *src_rq, *dst_rq;
  2069. struct rq_flags srf, drf;
  2070. src_rq = task_rq(p);
  2071. dst_rq = cpu_rq(cpu);
  2072. rq_pin_lock(src_rq, &srf);
  2073. rq_pin_lock(dst_rq, &drf);
  2074. p->on_rq = TASK_ON_RQ_MIGRATING;
  2075. deactivate_task(src_rq, p, 0);
  2076. set_task_cpu(p, cpu);
  2077. activate_task(dst_rq, p, 0);
  2078. p->on_rq = TASK_ON_RQ_QUEUED;
  2079. check_preempt_curr(dst_rq, p, 0);
  2080. rq_unpin_lock(dst_rq, &drf);
  2081. rq_unpin_lock(src_rq, &srf);
  2082. } else {
  2083. /*
  2084. * Task isn't running anymore; make it appear like we migrated
  2085. * it before it went to sleep. This means on wakeup we make the
  2086. * previous CPU our target instead of where it really is.
  2087. */
  2088. p->wake_cpu = cpu;
  2089. }
  2090. }
  2091. struct migration_swap_arg {
  2092. struct task_struct *src_task, *dst_task;
  2093. int src_cpu, dst_cpu;
  2094. };
  2095. static int migrate_swap_stop(void *data)
  2096. {
  2097. struct migration_swap_arg *arg = data;
  2098. struct rq *src_rq, *dst_rq;
  2099. int ret = -EAGAIN;
  2100. if (!cpu_active(arg->src_cpu) || !cpu_active(arg->dst_cpu))
  2101. return -EAGAIN;
  2102. src_rq = cpu_rq(arg->src_cpu);
  2103. dst_rq = cpu_rq(arg->dst_cpu);
  2104. double_raw_lock(&arg->src_task->pi_lock,
  2105. &arg->dst_task->pi_lock);
  2106. double_rq_lock(src_rq, dst_rq);
  2107. if (task_cpu(arg->dst_task) != arg->dst_cpu)
  2108. goto unlock;
  2109. if (task_cpu(arg->src_task) != arg->src_cpu)
  2110. goto unlock;
  2111. if (!cpumask_test_cpu(arg->dst_cpu, &arg->src_task->cpus_allowed))
  2112. goto unlock;
  2113. if (!cpumask_test_cpu(arg->src_cpu, &arg->dst_task->cpus_allowed))
  2114. goto unlock;
  2115. __migrate_swap_task(arg->src_task, arg->dst_cpu);
  2116. __migrate_swap_task(arg->dst_task, arg->src_cpu);
  2117. ret = 0;
  2118. unlock:
  2119. double_rq_unlock(src_rq, dst_rq);
  2120. raw_spin_unlock(&arg->dst_task->pi_lock);
  2121. raw_spin_unlock(&arg->src_task->pi_lock);
  2122. return ret;
  2123. }
  2124. /*
  2125. * Cross migrate two tasks
  2126. */
  2127. int migrate_swap(struct task_struct *cur, struct task_struct *p)
  2128. {
  2129. struct migration_swap_arg arg;
  2130. int ret = -EINVAL;
  2131. arg = (struct migration_swap_arg){
  2132. .src_task = cur,
  2133. .src_cpu = task_cpu(cur),
  2134. .dst_task = p,
  2135. .dst_cpu = task_cpu(p),
  2136. };
  2137. if (arg.src_cpu == arg.dst_cpu)
  2138. goto out;
  2139. /*
  2140. * These three tests are all lockless; this is OK since all of them
  2141. * will be re-checked with proper locks held further down the line.
  2142. */
  2143. if (!cpu_active(arg.src_cpu) || !cpu_active(arg.dst_cpu))
  2144. goto out;
  2145. if (!cpumask_test_cpu(arg.dst_cpu, &arg.src_task->cpus_allowed))
  2146. goto out;
  2147. if (!cpumask_test_cpu(arg.src_cpu, &arg.dst_task->cpus_allowed))
  2148. goto out;
  2149. trace_sched_swap_numa(cur, arg.src_cpu, p, arg.dst_cpu);
  2150. ret = stop_two_cpus(arg.dst_cpu, arg.src_cpu, migrate_swap_stop, &arg);
  2151. out:
  2152. return ret;
  2153. }
  2154. /*
  2155. * wait_task_inactive - wait for a thread to unschedule.
  2156. *
  2157. * If @match_state is nonzero, it's the @p->state value just checked and
  2158. * not expected to change. If it changes, i.e. @p might have woken up,
  2159. * then return zero. When we succeed in waiting for @p to be off its CPU,
  2160. * we return a positive number (its total switch count). If a second call
  2161. * a short while later returns the same number, the caller can be sure that
  2162. * @p has remained unscheduled the whole time.
  2163. *
  2164. * The caller must ensure that the task *will* unschedule sometime soon,
  2165. * else this function might spin for a *long* time. This function can't
  2166. * be called with interrupts off, or it may introduce deadlock with
  2167. * smp_call_function() if an IPI is sent by the same process we are
  2168. * waiting to become inactive.
  2169. */
  2170. unsigned long wait_task_inactive(struct task_struct *p, long match_state)
  2171. {
  2172. int running, queued;
  2173. struct rq_flags rf;
  2174. unsigned long ncsw;
  2175. struct rq *rq;
  2176. for (;;) {
  2177. /*
  2178. * We do the initial early heuristics without holding
  2179. * any task-queue locks at all. We'll only try to get
  2180. * the runqueue lock when things look like they will
  2181. * work out!
  2182. */
  2183. rq = task_rq(p);
  2184. /*
  2185. * If the task is actively running on another CPU
  2186. * still, just relax and busy-wait without holding
  2187. * any locks.
  2188. *
  2189. * NOTE! Since we don't hold any locks, it's not
  2190. * even sure that "rq" stays as the right runqueue!
  2191. * But we don't care, since "task_running()" will
  2192. * return false if the runqueue has changed and p
  2193. * is actually now running somewhere else!
  2194. */
  2195. while (task_running(rq, p)) {
  2196. if (match_state && unlikely(p->state != match_state))
  2197. return 0;
  2198. cpu_relax();
  2199. }
  2200. /*
  2201. * Ok, time to look more closely! We need the rq
  2202. * lock now, to be *sure*. If we're wrong, we'll
  2203. * just go back and repeat.
  2204. */
  2205. rq = task_rq_lock(p, &rf);
  2206. trace_sched_wait_task(p);
  2207. running = task_running(rq, p);
  2208. queued = task_on_rq_queued(p);
  2209. ncsw = 0;
  2210. if (!match_state || p->state == match_state)
  2211. ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
  2212. task_rq_unlock(rq, p, &rf);
  2213. /*
  2214. * If it changed from the expected state, bail out now.
  2215. */
  2216. if (unlikely(!ncsw))
  2217. break;
  2218. /*
  2219. * Was it really running after all now that we
  2220. * checked with the proper locks actually held?
  2221. *
  2222. * Oops. Go back and try again..
  2223. */
  2224. if (unlikely(running)) {
  2225. cpu_relax();
  2226. continue;
  2227. }
  2228. /*
  2229. * It's not enough that it's not actively running,
  2230. * it must be off the runqueue _entirely_, and not
  2231. * preempted!
  2232. *
  2233. * So if it was still runnable (but just not actively
  2234. * running right now), it's preempted, and we should
  2235. * yield - it could be a while.
  2236. */
  2237. if (unlikely(queued)) {
  2238. ktime_t to = NSEC_PER_SEC / HZ;
  2239. set_current_state(TASK_UNINTERRUPTIBLE);
  2240. schedule_hrtimeout(&to, HRTIMER_MODE_REL);
  2241. continue;
  2242. }
  2243. /*
  2244. * Ahh, all good. It wasn't running, and it wasn't
  2245. * runnable, which means that it will never become
  2246. * running in the future either. We're all done!
  2247. */
  2248. break;
  2249. }
  2250. return ncsw;
  2251. }
  2252. /***
  2253. * kick_process - kick a running thread to enter/exit the kernel
  2254. * @p: the to-be-kicked thread
  2255. *
  2256. * Cause a process which is running on another CPU to enter
  2257. * kernel-mode, without any delay. (to get signals handled.)
  2258. *
  2259. * NOTE: this function doesn't have to take the runqueue lock,
  2260. * because all it wants to ensure is that the remote task enters
  2261. * the kernel. If the IPI races and the task has been migrated
  2262. * to another CPU then no harm is done and the purpose has been
  2263. * achieved as well.
  2264. */
  2265. void kick_process(struct task_struct *p)
  2266. {
  2267. int cpu;
  2268. preempt_disable();
  2269. cpu = task_cpu(p);
  2270. if ((cpu != smp_processor_id()) && task_curr(p))
  2271. smp_send_reschedule(cpu);
  2272. preempt_enable();
  2273. }
  2274. EXPORT_SYMBOL_GPL(kick_process);
  2275. /*
  2276. * ->cpus_allowed is protected by both rq->lock and p->pi_lock
  2277. *
  2278. * A few notes on cpu_active vs cpu_online:
  2279. *
  2280. * - cpu_active must be a subset of cpu_online
  2281. *
  2282. * - on cpu-up we allow per-cpu kthreads on the online && !active cpu,
  2283. * see __set_cpus_allowed_ptr(). At this point the newly online
  2284. * CPU isn't yet part of the sched domains, and balancing will not
  2285. * see it.
  2286. *
  2287. * - on CPU-down we clear cpu_active() to mask the sched domains and
  2288. * avoid the load balancer to place new tasks on the to be removed
  2289. * CPU. Existing tasks will remain running there and will be taken
  2290. * off.
  2291. *
  2292. * This means that fallback selection must not select !active CPUs.
  2293. * And can assume that any active CPU must be online. Conversely
  2294. * select_task_rq() below may allow selection of !active CPUs in order
  2295. * to satisfy the above rules.
  2296. */
  2297. static int select_fallback_rq(int cpu, struct task_struct *p, bool allow_iso)
  2298. {
  2299. int nid = cpu_to_node(cpu);
  2300. const struct cpumask *nodemask = NULL;
  2301. enum { cpuset, possible, fail, bug } state = cpuset;
  2302. int dest_cpu;
  2303. int isolated_candidate = -1;
  2304. /*
  2305. * If the node that the CPU is on has been offlined, cpu_to_node()
  2306. * will return -1. There is no CPU on the node, and we should
  2307. * select the CPU on the other node.
  2308. */
  2309. if (nid != -1) {
  2310. nodemask = cpumask_of_node(nid);
  2311. /* Look for allowed, online CPU in same node. */
  2312. for_each_cpu(dest_cpu, nodemask) {
  2313. if (!cpu_active(dest_cpu))
  2314. continue;
  2315. if (cpu_isolated(dest_cpu))
  2316. continue;
  2317. if (cpumask_test_cpu(dest_cpu, &p->cpus_allowed))
  2318. return dest_cpu;
  2319. }
  2320. }
  2321. for (;;) {
  2322. /* Any allowed, online CPU? */
  2323. for_each_cpu(dest_cpu, &p->cpus_allowed) {
  2324. if (!is_cpu_allowed(p, dest_cpu))
  2325. continue;
  2326. if (cpu_isolated(dest_cpu)) {
  2327. if (allow_iso)
  2328. isolated_candidate = dest_cpu;
  2329. continue;
  2330. }
  2331. goto out;
  2332. }
  2333. if (isolated_candidate != -1) {
  2334. dest_cpu = isolated_candidate;
  2335. goto out;
  2336. }
  2337. /* No more Mr. Nice Guy. */
  2338. switch (state) {
  2339. case cpuset:
  2340. if (IS_ENABLED(CONFIG_CPUSETS)) {
  2341. cpuset_cpus_allowed_fallback(p);
  2342. state = possible;
  2343. break;
  2344. }
  2345. /* Fall-through */
  2346. case possible:
  2347. do_set_cpus_allowed(p, cpu_possible_mask);
  2348. state = fail;
  2349. break;
  2350. case fail:
  2351. allow_iso = true;
  2352. state = bug;
  2353. break;
  2354. case bug:
  2355. BUG();
  2356. break;
  2357. }
  2358. }
  2359. out:
  2360. if (state != cpuset) {
  2361. /*
  2362. * Don't tell them about moving exiting tasks or
  2363. * kernel threads (both mm NULL), since they never
  2364. * leave kernel.
  2365. */
  2366. if (p->mm && printk_ratelimit()) {
  2367. printk_deferred("process %d (%s) no longer affine to cpu%d\n",
  2368. task_pid_nr(p), p->comm, cpu);
  2369. }
  2370. }
  2371. return dest_cpu;
  2372. }
  2373. /*
  2374. * The caller (fork, wakeup) owns p->pi_lock, ->cpus_allowed is stable.
  2375. */
  2376. static inline
  2377. int select_task_rq(struct task_struct *p, int cpu, int sd_flags, int wake_flags,
  2378. int sibling_count_hint)
  2379. {
  2380. bool allow_isolated = (p->flags & PF_KTHREAD);
  2381. bool select_fallback = false;
  2382. cpumask_t cpu_unisolated_mask;
  2383. lockdep_assert_held(&p->pi_lock);
  2384. if (p->nr_cpus_allowed > 1)
  2385. cpu = p->sched_class->select_task_rq(p, cpu, sd_flags, wake_flags,
  2386. sibling_count_hint);
  2387. else
  2388. cpu = cpumask_any(&p->cpus_allowed);
  2389. /*
  2390. * In order not to call set_task_cpu() on a blocking task we need
  2391. * to rely on ttwu() to place the task on a valid ->cpus_allowed
  2392. * CPU.
  2393. *
  2394. * Since this is common to all placement strategies, this lives here.
  2395. *
  2396. * [ this allows ->select_task() to simply return task_cpu(p) and
  2397. * not worry about this generic constraint ]
  2398. */
  2399. cpumask_andnot(&cpu_unisolated_mask, cpu_possible_mask,
  2400. cpu_isolated_mask);
  2401. /*
  2402. * If kernel thread select a isolated CPU but it has other allowed CPU,
  2403. * go to select_fallback_rq to choose allowed and un-isolated CPU.
  2404. */
  2405. if (allow_isolated && cpu_isolated(cpu) &&
  2406. cpumask_intersects(tsk_cpus_allowed(p), &cpu_unisolated_mask)) {
  2407. select_fallback = true;
  2408. }
  2409. if (unlikely(!is_cpu_allowed(p, cpu)) ||
  2410. (cpu_isolated(cpu) && !allow_isolated) ||
  2411. select_fallback)
  2412. cpu = select_fallback_rq(task_cpu(p), p, allow_isolated);
  2413. return cpu;
  2414. }
  2415. static void update_avg(u64 *avg, u64 sample)
  2416. {
  2417. s64 diff = sample - *avg;
  2418. *avg += diff >> 3;
  2419. }
  2420. void sched_set_stop_task(int cpu, struct task_struct *stop)
  2421. {
  2422. struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
  2423. struct task_struct *old_stop = cpu_rq(cpu)->stop;
  2424. if (stop) {
  2425. /*
  2426. * Make it appear like a SCHED_FIFO task, its something
  2427. * userspace knows about and won't get confused about.
  2428. *
  2429. * Also, it will make PI more or less work without too
  2430. * much confusion -- but then, stop work should not
  2431. * rely on PI working anyway.
  2432. */
  2433. sched_setscheduler_nocheck(stop, SCHED_FIFO, &param);
  2434. stop->sched_class = &stop_sched_class;
  2435. }
  2436. cpu_rq(cpu)->stop = stop;
  2437. if (old_stop) {
  2438. /*
  2439. * Reset it back to a normal scheduling class so that
  2440. * it can die in pieces.
  2441. */
  2442. old_stop->sched_class = &rt_sched_class;
  2443. }
  2444. }
  2445. #else
  2446. static inline int __set_cpus_allowed_ptr(struct task_struct *p,
  2447. const struct cpumask *new_mask, bool check)
  2448. {
  2449. return set_cpus_allowed_ptr(p, new_mask);
  2450. }
  2451. #endif /* CONFIG_SMP */
  2452. static void
  2453. ttwu_stat(struct task_struct *p, int cpu, int wake_flags)
  2454. {
  2455. struct rq *rq;
  2456. if (!schedstat_enabled())
  2457. return;
  2458. rq = this_rq();
  2459. #ifdef CONFIG_SMP
  2460. if (cpu == rq->cpu) {
  2461. schedstat_inc(rq->ttwu_local);
  2462. schedstat_inc(p->se.statistics.nr_wakeups_local);
  2463. } else {
  2464. struct sched_domain *sd;
  2465. schedstat_inc(p->se.statistics.nr_wakeups_remote);
  2466. rcu_read_lock();
  2467. for_each_domain(rq->cpu, sd) {
  2468. if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
  2469. schedstat_inc(sd->ttwu_wake_remote);
  2470. break;
  2471. }
  2472. }
  2473. rcu_read_unlock();
  2474. }
  2475. if (wake_flags & WF_MIGRATED)
  2476. schedstat_inc(p->se.statistics.nr_wakeups_migrate);
  2477. #endif /* CONFIG_SMP */
  2478. schedstat_inc(rq->ttwu_count);
  2479. schedstat_inc(p->se.statistics.nr_wakeups);
  2480. if (wake_flags & WF_SYNC)
  2481. schedstat_inc(p->se.statistics.nr_wakeups_sync);
  2482. }
  2483. static inline void ttwu_activate(struct rq *rq, struct task_struct *p, int en_flags)
  2484. {
  2485. activate_task(rq, p, en_flags);
  2486. p->on_rq = TASK_ON_RQ_QUEUED;
  2487. /* If a worker is waking up, notify the workqueue: */
  2488. if (p->flags & PF_WQ_WORKER)
  2489. wq_worker_waking_up(p, cpu_of(rq));
  2490. }
  2491. /*
  2492. * Mark the task runnable and perform wakeup-preemption.
  2493. */
  2494. static void ttwu_do_wakeup(struct rq *rq, struct task_struct *p, int wake_flags,
  2495. struct rq_flags *rf)
  2496. {
  2497. check_preempt_curr(rq, p, wake_flags);
  2498. p->state = TASK_RUNNING;
  2499. trace_sched_wakeup(p);
  2500. #ifdef CONFIG_SMP
  2501. if (p->sched_class->task_woken) {
  2502. /*
  2503. * Our task @p is fully woken up and running; so its safe to
  2504. * drop the rq->lock, hereafter rq is only used for statistics.
  2505. */
  2506. rq_unpin_lock(rq, rf);
  2507. p->sched_class->task_woken(rq, p);
  2508. rq_repin_lock(rq, rf);
  2509. }
  2510. if (rq->idle_stamp) {
  2511. u64 delta = rq_clock(rq) - rq->idle_stamp;
  2512. u64 max = 2*rq->max_idle_balance_cost;
  2513. update_avg(&rq->avg_idle, delta);
  2514. if (rq->avg_idle > max)
  2515. rq->avg_idle = max;
  2516. rq->idle_stamp = 0;
  2517. }
  2518. #endif
  2519. }
  2520. static void
  2521. ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags,
  2522. struct rq_flags *rf)
  2523. {
  2524. int en_flags = ENQUEUE_WAKEUP | ENQUEUE_NOCLOCK;
  2525. lockdep_assert_held(&rq->lock);
  2526. #ifdef CONFIG_SMP
  2527. if (p->sched_contributes_to_load)
  2528. rq->nr_uninterruptible--;
  2529. if (wake_flags & WF_MIGRATED)
  2530. en_flags |= ENQUEUE_MIGRATED;
  2531. #endif
  2532. ttwu_activate(rq, p, en_flags);
  2533. ttwu_do_wakeup(rq, p, wake_flags, rf);
  2534. }
  2535. /*
  2536. * Called in case the task @p isn't fully descheduled from its runqueue,
  2537. * in this case we must do a remote wakeup. Its a 'light' wakeup though,
  2538. * since all we need to do is flip p->state to TASK_RUNNING, since
  2539. * the task is still ->on_rq.
  2540. */
  2541. static int ttwu_remote(struct task_struct *p, int wake_flags)
  2542. {
  2543. struct rq_flags rf;
  2544. struct rq *rq;
  2545. int ret = 0;
  2546. rq = __task_rq_lock(p, &rf);
  2547. if (task_on_rq_queued(p)) {
  2548. /* check_preempt_curr() may use rq clock */
  2549. update_rq_clock(rq);
  2550. ttwu_do_wakeup(rq, p, wake_flags, &rf);
  2551. ret = 1;
  2552. }
  2553. __task_rq_unlock(rq, &rf);
  2554. return ret;
  2555. }
  2556. #ifdef CONFIG_SMP
  2557. void sched_ttwu_pending(void)
  2558. {
  2559. struct rq *rq = this_rq();
  2560. struct llist_node *llist = llist_del_all(&rq->wake_list);
  2561. struct task_struct *p, *t;
  2562. struct rq_flags rf;
  2563. if (!llist)
  2564. return;
  2565. rq_lock_irqsave(rq, &rf);
  2566. update_rq_clock(rq);
  2567. llist_for_each_entry_safe(p, t, llist, wake_entry)
  2568. ttwu_do_activate(rq, p, p->sched_remote_wakeup ? WF_MIGRATED : 0, &rf);
  2569. rq_unlock_irqrestore(rq, &rf);
  2570. }
  2571. void scheduler_ipi(void)
  2572. {
  2573. int cpu = smp_processor_id();
  2574. /*
  2575. * Fold TIF_NEED_RESCHED into the preempt_count; anybody setting
  2576. * TIF_NEED_RESCHED remotely (for the first time) will also send
  2577. * this IPI.
  2578. */
  2579. preempt_fold_need_resched();
  2580. if (llist_empty(&this_rq()->wake_list) && !got_nohz_idle_kick())
  2581. return;
  2582. /*
  2583. * Not all reschedule IPI handlers call irq_enter/irq_exit, since
  2584. * traditionally all their work was done from the interrupt return
  2585. * path. Now that we actually do some work, we need to make sure
  2586. * we do call them.
  2587. *
  2588. * Some archs already do call them, luckily irq_enter/exit nest
  2589. * properly.
  2590. *
  2591. * Arguably we should visit all archs and update all handlers,
  2592. * however a fair share of IPIs are still resched only so this would
  2593. * somewhat pessimize the simple resched case.
  2594. */
  2595. irq_enter();
  2596. sched_ttwu_pending();
  2597. /*
  2598. * Check if someone kicked us for doing the nohz idle load balance.
  2599. */
  2600. if (unlikely(got_nohz_idle_kick()) && !cpu_isolated(cpu)) {
  2601. this_rq()->idle_balance = 1;
  2602. raise_softirq_irqoff(SCHED_SOFTIRQ);
  2603. }
  2604. irq_exit();
  2605. }
  2606. static void ttwu_queue_remote(struct task_struct *p, int cpu, int wake_flags)
  2607. {
  2608. struct rq *rq = cpu_rq(cpu);
  2609. p->sched_remote_wakeup = !!(wake_flags & WF_MIGRATED);
  2610. if (llist_add(&p->wake_entry, &cpu_rq(cpu)->wake_list)) {
  2611. if (!set_nr_if_polling(rq->idle))
  2612. smp_send_reschedule(cpu);
  2613. else
  2614. trace_sched_wake_idle_without_ipi(cpu);
  2615. }
  2616. }
  2617. void wake_up_if_idle(int cpu)
  2618. {
  2619. struct rq *rq = cpu_rq(cpu);
  2620. struct rq_flags rf;
  2621. rcu_read_lock();
  2622. if (!is_idle_task(rcu_dereference(rq->curr)))
  2623. goto out;
  2624. if (set_nr_if_polling(rq->idle)) {
  2625. trace_sched_wake_idle_without_ipi(cpu);
  2626. } else {
  2627. rq_lock_irqsave(rq, &rf);
  2628. if (is_idle_task(rq->curr))
  2629. smp_send_reschedule(cpu);
  2630. /* Else CPU is not idle, do nothing here: */
  2631. rq_unlock_irqrestore(rq, &rf);
  2632. }
  2633. out:
  2634. rcu_read_unlock();
  2635. }
  2636. bool cpus_share_cache(int this_cpu, int that_cpu)
  2637. {
  2638. return per_cpu(sd_llc_id, this_cpu) == per_cpu(sd_llc_id, that_cpu);
  2639. }
  2640. #endif /* CONFIG_SMP */
  2641. static void ttwu_queue(struct task_struct *p, int cpu, int wake_flags)
  2642. {
  2643. struct rq *rq = cpu_rq(cpu);
  2644. struct rq_flags rf;
  2645. #if defined(CONFIG_SMP)
  2646. if (sched_feat(TTWU_QUEUE) && !cpus_share_cache(smp_processor_id(), cpu)) {
  2647. sched_clock_cpu(cpu); /* Sync clocks across CPUs */
  2648. ttwu_queue_remote(p, cpu, wake_flags);
  2649. return;
  2650. }
  2651. #endif
  2652. rq_lock(rq, &rf);
  2653. update_rq_clock(rq);
  2654. ttwu_do_activate(rq, p, wake_flags, &rf);
  2655. rq_unlock(rq, &rf);
  2656. }
  2657. /*
  2658. * Notes on Program-Order guarantees on SMP systems.
  2659. *
  2660. * MIGRATION
  2661. *
  2662. * The basic program-order guarantee on SMP systems is that when a task [t]
  2663. * migrates, all its activity on its old CPU [c0] happens-before any subsequent
  2664. * execution on its new CPU [c1].
  2665. *
  2666. * For migration (of runnable tasks) this is provided by the following means:
  2667. *
  2668. * A) UNLOCK of the rq(c0)->lock scheduling out task t
  2669. * B) migration for t is required to synchronize *both* rq(c0)->lock and
  2670. * rq(c1)->lock (if not at the same time, then in that order).
  2671. * C) LOCK of the rq(c1)->lock scheduling in task
  2672. *
  2673. * Transitivity guarantees that B happens after A and C after B.
  2674. * Note: we only require RCpc transitivity.
  2675. * Note: the CPU doing B need not be c0 or c1
  2676. *
  2677. * Example:
  2678. *
  2679. * CPU0 CPU1 CPU2
  2680. *
  2681. * LOCK rq(0)->lock
  2682. * sched-out X
  2683. * sched-in Y
  2684. * UNLOCK rq(0)->lock
  2685. *
  2686. * LOCK rq(0)->lock // orders against CPU0
  2687. * dequeue X
  2688. * UNLOCK rq(0)->lock
  2689. *
  2690. * LOCK rq(1)->lock
  2691. * enqueue X
  2692. * UNLOCK rq(1)->lock
  2693. *
  2694. * LOCK rq(1)->lock // orders against CPU2
  2695. * sched-out Z
  2696. * sched-in X
  2697. * UNLOCK rq(1)->lock
  2698. *
  2699. *
  2700. * BLOCKING -- aka. SLEEP + WAKEUP
  2701. *
  2702. * For blocking we (obviously) need to provide the same guarantee as for
  2703. * migration. However the means are completely different as there is no lock
  2704. * chain to provide order. Instead we do:
  2705. *
  2706. * 1) smp_store_release(X->on_cpu, 0)
  2707. * 2) smp_cond_load_acquire(!X->on_cpu)
  2708. *
  2709. * Example:
  2710. *
  2711. * CPU0 (schedule) CPU1 (try_to_wake_up) CPU2 (schedule)
  2712. *
  2713. * LOCK rq(0)->lock LOCK X->pi_lock
  2714. * dequeue X
  2715. * sched-out X
  2716. * smp_store_release(X->on_cpu, 0);
  2717. *
  2718. * smp_cond_load_acquire(&X->on_cpu, !VAL);
  2719. * X->state = WAKING
  2720. * set_task_cpu(X,2)
  2721. *
  2722. * LOCK rq(2)->lock
  2723. * enqueue X
  2724. * X->state = RUNNING
  2725. * UNLOCK rq(2)->lock
  2726. *
  2727. * LOCK rq(2)->lock // orders against CPU1
  2728. * sched-out Z
  2729. * sched-in X
  2730. * UNLOCK rq(2)->lock
  2731. *
  2732. * UNLOCK X->pi_lock
  2733. * UNLOCK rq(0)->lock
  2734. *
  2735. *
  2736. * However; for wakeups there is a second guarantee we must provide, namely we
  2737. * must observe the state that lead to our wakeup. That is, not only must our
  2738. * task observe its own prior state, it must also observe the stores prior to
  2739. * its wakeup.
  2740. *
  2741. * This means that any means of doing remote wakeups must order the CPU doing
  2742. * the wakeup against the CPU the task is going to end up running on. This,
  2743. * however, is already required for the regular Program-Order guarantee above,
  2744. * since the waking CPU is the one issueing the ACQUIRE (smp_cond_load_acquire).
  2745. *
  2746. */
  2747. #ifdef CONFIG_SMP
  2748. #ifdef CONFIG_SCHED_WALT
  2749. /* utility function to update walt signals at wakeup */
  2750. static inline void walt_try_to_wake_up(struct task_struct *p)
  2751. {
  2752. struct rq *rq = cpu_rq(task_cpu(p));
  2753. struct rq_flags rf;
  2754. u64 wallclock;
  2755. rq_lock_irqsave(rq, &rf);
  2756. wallclock = walt_ktime_clock();
  2757. walt_update_task_ravg(rq->curr, rq, TASK_UPDATE, wallclock, 0);
  2758. walt_update_task_ravg(p, rq, TASK_WAKE, wallclock, 0);
  2759. rq_unlock_irqrestore(rq, &rf);
  2760. }
  2761. #else
  2762. #define walt_try_to_wake_up(a) {}
  2763. #endif
  2764. #endif
  2765. /**
  2766. * try_to_wake_up - wake up a thread
  2767. * @p: the thread to be awakened
  2768. * @state: the mask of task states that can be woken
  2769. * @wake_flags: wake modifier flags (WF_*)
  2770. * @sibling_count_hint: A hint at the number of threads that are being woken up
  2771. * in this event.
  2772. *
  2773. * If (@state & @p->state) @p->state = TASK_RUNNING.
  2774. *
  2775. * If the task was not queued/runnable, also place it back on a runqueue.
  2776. *
  2777. * Atomic against schedule() which would dequeue a task, also see
  2778. * set_current_state().
  2779. *
  2780. * Return: %true if @p->state changes (an actual wakeup was done),
  2781. * %false otherwise.
  2782. */
  2783. static int
  2784. try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags,
  2785. int sibling_count_hint)
  2786. {
  2787. unsigned long flags;
  2788. int cpu, success = 0;
  2789. /*
  2790. * If we are going to wake up a thread waiting for CONDITION we
  2791. * need to ensure that CONDITION=1 done by the caller can not be
  2792. * reordered with p->state check below. This pairs with mb() in
  2793. * set_current_state() the waiting thread does.
  2794. */
  2795. raw_spin_lock_irqsave(&p->pi_lock, flags);
  2796. smp_mb__after_spinlock();
  2797. if (!(p->state & state))
  2798. goto out;
  2799. trace_sched_waking(p);
  2800. /* We're going to change ->state: */
  2801. success = 1;
  2802. cpu = task_cpu(p);
  2803. /*
  2804. * Ensure we load p->on_rq _after_ p->state, otherwise it would
  2805. * be possible to, falsely, observe p->on_rq == 0 and get stuck
  2806. * in smp_cond_load_acquire() below.
  2807. *
  2808. * sched_ttwu_pending() try_to_wake_up()
  2809. * [S] p->on_rq = 1; [L] P->state
  2810. * UNLOCK rq->lock -----.
  2811. * \
  2812. * +--- RMB
  2813. * schedule() /
  2814. * LOCK rq->lock -----'
  2815. * UNLOCK rq->lock
  2816. *
  2817. * [task p]
  2818. * [S] p->state = UNINTERRUPTIBLE [L] p->on_rq
  2819. *
  2820. * Pairs with the UNLOCK+LOCK on rq->lock from the
  2821. * last wakeup of our task and the schedule that got our task
  2822. * current.
  2823. */
  2824. smp_rmb();
  2825. if (p->on_rq && ttwu_remote(p, wake_flags))
  2826. goto stat;
  2827. #ifdef CONFIG_SMP
  2828. /*
  2829. * Ensure we load p->on_cpu _after_ p->on_rq, otherwise it would be
  2830. * possible to, falsely, observe p->on_cpu == 0.
  2831. *
  2832. * One must be running (->on_cpu == 1) in order to remove oneself
  2833. * from the runqueue.
  2834. *
  2835. * [S] ->on_cpu = 1; [L] ->on_rq
  2836. * UNLOCK rq->lock
  2837. * RMB
  2838. * LOCK rq->lock
  2839. * [S] ->on_rq = 0; [L] ->on_cpu
  2840. *
  2841. * Pairs with the full barrier implied in the UNLOCK+LOCK on rq->lock
  2842. * from the consecutive calls to schedule(); the first switching to our
  2843. * task, the second putting it to sleep.
  2844. */
  2845. smp_rmb();
  2846. /*
  2847. * If the owning (remote) CPU is still in the middle of schedule() with
  2848. * this task as prev, wait until its done referencing the task.
  2849. *
  2850. * Pairs with the smp_store_release() in finish_lock_switch().
  2851. *
  2852. * This ensures that tasks getting woken will be fully ordered against
  2853. * their previous state and preserve Program Order.
  2854. */
  2855. smp_cond_load_acquire(&p->on_cpu, !VAL);
  2856. walt_try_to_wake_up(p);
  2857. p->sched_contributes_to_load = !!task_contributes_to_load(p);
  2858. p->state = TASK_WAKING;
  2859. if (p->in_iowait) {
  2860. delayacct_blkio_end(p);
  2861. atomic_dec(&task_rq(p)->nr_iowait);
  2862. }
  2863. cpu = select_task_rq(p, p->wake_cpu, SD_BALANCE_WAKE, wake_flags,
  2864. sibling_count_hint);
  2865. if (task_cpu(p) != cpu) {
  2866. wake_flags |= WF_MIGRATED;
  2867. psi_ttwu_dequeue(p);
  2868. set_task_cpu(p, cpu);
  2869. }
  2870. #else /* CONFIG_SMP */
  2871. if (p->in_iowait) {
  2872. delayacct_blkio_end(p);
  2873. atomic_dec(&task_rq(p)->nr_iowait);
  2874. }
  2875. #endif /* CONFIG_SMP */
  2876. ttwu_queue(p, cpu, wake_flags);
  2877. stat:
  2878. ttwu_stat(p, cpu, wake_flags);
  2879. out:
  2880. raw_spin_unlock_irqrestore(&p->pi_lock, flags);
  2881. return success;
  2882. }
  2883. /**
  2884. * try_to_wake_up_local - try to wake up a local task with rq lock held
  2885. * @p: the thread to be awakened
  2886. * @rf: request-queue flags for pinning
  2887. *
  2888. * Put @p on the run-queue if it's not already there. The caller must
  2889. * ensure that this_rq() is locked, @p is bound to this_rq() and not
  2890. * the current task.
  2891. */
  2892. static void try_to_wake_up_local(struct task_struct *p, struct rq_flags *rf)
  2893. {
  2894. struct rq *rq = task_rq(p);
  2895. if (WARN_ON_ONCE(rq != this_rq()) ||
  2896. WARN_ON_ONCE(p == current))
  2897. return;
  2898. lockdep_assert_held(&rq->lock);
  2899. if (!raw_spin_trylock(&p->pi_lock)) {
  2900. /*
  2901. * This is OK, because current is on_cpu, which avoids it being
  2902. * picked for load-balance and preemption/IRQs are still
  2903. * disabled avoiding further scheduler activity on it and we've
  2904. * not yet picked a replacement task.
  2905. */
  2906. rq_unlock(rq, rf);
  2907. raw_spin_lock(&p->pi_lock);
  2908. rq_relock(rq, rf);
  2909. }
  2910. if (!(p->state & TASK_NORMAL))
  2911. goto out;
  2912. trace_sched_waking(p);
  2913. if (!task_on_rq_queued(p)) {
  2914. u64 wallclock = walt_ktime_clock();
  2915. walt_update_task_ravg(rq->curr, rq, TASK_UPDATE, wallclock, 0);
  2916. walt_update_task_ravg(p, rq, TASK_WAKE, wallclock, 0);
  2917. if (p->in_iowait) {
  2918. delayacct_blkio_end(p);
  2919. atomic_dec(&rq->nr_iowait);
  2920. }
  2921. ttwu_activate(rq, p, ENQUEUE_WAKEUP | ENQUEUE_NOCLOCK);
  2922. }
  2923. ttwu_do_wakeup(rq, p, 0, rf);
  2924. ttwu_stat(p, smp_processor_id(), 0);
  2925. out:
  2926. raw_spin_unlock(&p->pi_lock);
  2927. }
  2928. /**
  2929. * wake_up_process - Wake up a specific process
  2930. * @p: The process to be woken up.
  2931. *
  2932. * Attempt to wake up the nominated process and move it to the set of runnable
  2933. * processes.
  2934. *
  2935. * Return: 1 if the process was woken up, 0 if it was already running.
  2936. *
  2937. * It may be assumed that this function implies a write memory barrier before
  2938. * changing the task state if and only if any tasks are woken up.
  2939. */
  2940. int wake_up_process(struct task_struct *p)
  2941. {
  2942. return try_to_wake_up(p, TASK_NORMAL, 0, 1);
  2943. }
  2944. EXPORT_SYMBOL(wake_up_process);
  2945. int wake_up_state(struct task_struct *p, unsigned int state)
  2946. {
  2947. return try_to_wake_up(p, state, 0, 1);
  2948. }
  2949. /*
  2950. * Perform scheduler related setup for a newly forked process p.
  2951. * p is forked by current.
  2952. *
  2953. * __sched_fork() is basic setup used by init_idle() too:
  2954. */
  2955. static void __sched_fork(unsigned long clone_flags, struct task_struct *p)
  2956. {
  2957. p->on_rq = 0;
  2958. p->se.on_rq = 0;
  2959. p->se.exec_start = 0;
  2960. p->se.sum_exec_runtime = 0;
  2961. p->se.prev_sum_exec_runtime = 0;
  2962. p->se.nr_migrations = 0;
  2963. p->se.vruntime = 0;
  2964. #ifdef CONFIG_SCHED_WALT
  2965. p->last_sleep_ts = 0;
  2966. #endif
  2967. INIT_LIST_HEAD(&p->se.group_node);
  2968. walt_init_new_task_load(p);
  2969. #ifdef CONFIG_FAIR_GROUP_SCHED
  2970. p->se.cfs_rq = NULL;
  2971. #endif
  2972. #ifdef CONFIG_SCHEDSTATS
  2973. /* Even if schedstat is disabled, there should not be garbage */
  2974. memset(&p->se.statistics, 0, sizeof(p->se.statistics));
  2975. #endif
  2976. RB_CLEAR_NODE(&p->dl.rb_node);
  2977. init_dl_task_timer(&p->dl);
  2978. init_dl_inactive_task_timer(&p->dl);
  2979. __dl_clear_params(p);
  2980. INIT_LIST_HEAD(&p->rt.run_list);
  2981. p->rt.timeout = 0;
  2982. p->rt.time_slice = sched_rr_timeslice;
  2983. p->rt.on_rq = 0;
  2984. p->rt.on_list = 0;
  2985. #ifdef CONFIG_PREEMPT_NOTIFIERS
  2986. INIT_HLIST_HEAD(&p->preempt_notifiers);
  2987. #endif
  2988. #ifdef CONFIG_NUMA_BALANCING
  2989. if (p->mm && atomic_read(&p->mm->mm_users) == 1) {
  2990. p->mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
  2991. p->mm->numa_scan_seq = 0;
  2992. }
  2993. if (clone_flags & CLONE_VM)
  2994. p->numa_preferred_nid = current->numa_preferred_nid;
  2995. else
  2996. p->numa_preferred_nid = -1;
  2997. p->node_stamp = 0ULL;
  2998. p->numa_scan_seq = p->mm ? p->mm->numa_scan_seq : 0;
  2999. p->numa_scan_period = sysctl_numa_balancing_scan_delay;
  3000. p->numa_work.next = &p->numa_work;
  3001. p->numa_faults = NULL;
  3002. p->last_task_numa_placement = 0;
  3003. p->last_sum_exec_runtime = 0;
  3004. p->numa_group = NULL;
  3005. #endif /* CONFIG_NUMA_BALANCING */
  3006. }
  3007. DEFINE_STATIC_KEY_FALSE(sched_numa_balancing);
  3008. #ifdef CONFIG_NUMA_BALANCING
  3009. void set_numabalancing_state(bool enabled)
  3010. {
  3011. if (enabled)
  3012. static_branch_enable(&sched_numa_balancing);
  3013. else
  3014. static_branch_disable(&sched_numa_balancing);
  3015. }
  3016. #ifdef CONFIG_PROC_SYSCTL
  3017. int sysctl_numa_balancing(struct ctl_table *table, int write,
  3018. void __user *buffer, size_t *lenp, loff_t *ppos)
  3019. {
  3020. struct ctl_table t;
  3021. int err;
  3022. int state = static_branch_likely(&sched_numa_balancing);
  3023. if (write && !capable(CAP_SYS_ADMIN))
  3024. return -EPERM;
  3025. t = *table;
  3026. t.data = &state;
  3027. err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
  3028. if (err < 0)
  3029. return err;
  3030. if (write)
  3031. set_numabalancing_state(state);
  3032. return err;
  3033. }
  3034. #endif
  3035. #endif
  3036. #ifdef CONFIG_SCHEDSTATS
  3037. DEFINE_STATIC_KEY_FALSE(sched_schedstats);
  3038. static bool __initdata __sched_schedstats = false;
  3039. static void set_schedstats(bool enabled)
  3040. {
  3041. if (enabled)
  3042. static_branch_enable(&sched_schedstats);
  3043. else
  3044. static_branch_disable(&sched_schedstats);
  3045. }
  3046. void force_schedstat_enabled(void)
  3047. {
  3048. if (!schedstat_enabled()) {
  3049. pr_info("kernel profiling enabled schedstats, disable via kernel.sched_schedstats.\n");
  3050. static_branch_enable(&sched_schedstats);
  3051. }
  3052. }
  3053. static int __init setup_schedstats(char *str)
  3054. {
  3055. int ret = 0;
  3056. if (!str)
  3057. goto out;
  3058. /*
  3059. * This code is called before jump labels have been set up, so we can't
  3060. * change the static branch directly just yet. Instead set a temporary
  3061. * variable so init_schedstats() can do it later.
  3062. */
  3063. if (!strcmp(str, "enable")) {
  3064. __sched_schedstats = true;
  3065. ret = 1;
  3066. } else if (!strcmp(str, "disable")) {
  3067. __sched_schedstats = false;
  3068. ret = 1;
  3069. }
  3070. out:
  3071. if (!ret)
  3072. pr_warn("Unable to parse schedstats=\n");
  3073. return ret;
  3074. }
  3075. __setup("schedstats=", setup_schedstats);
  3076. static void __init init_schedstats(void)
  3077. {
  3078. set_schedstats(__sched_schedstats);
  3079. }
  3080. #ifdef CONFIG_PROC_SYSCTL
  3081. int sysctl_schedstats(struct ctl_table *table, int write,
  3082. void __user *buffer, size_t *lenp, loff_t *ppos)
  3083. {
  3084. struct ctl_table t;
  3085. int err;
  3086. int state = static_branch_likely(&sched_schedstats);
  3087. if (write && !capable(CAP_SYS_ADMIN))
  3088. return -EPERM;
  3089. t = *table;
  3090. t.data = &state;
  3091. err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
  3092. if (err < 0)
  3093. return err;
  3094. if (write)
  3095. set_schedstats(state);
  3096. return err;
  3097. }
  3098. #endif /* CONFIG_PROC_SYSCTL */
  3099. #else /* !CONFIG_SCHEDSTATS */
  3100. static inline void init_schedstats(void) {}
  3101. #endif /* CONFIG_SCHEDSTATS */
  3102. /*
  3103. * fork()/clone()-time setup:
  3104. */
  3105. int sched_fork(unsigned long clone_flags, struct task_struct *p)
  3106. {
  3107. unsigned long flags;
  3108. bool reset;
  3109. int cpu = get_cpu();
  3110. __sched_fork(clone_flags, p);
  3111. /*
  3112. * We mark the process as NEW here. This guarantees that
  3113. * nobody will actually run it, and a signal or other external
  3114. * event cannot wake it up and insert it on the runqueue either.
  3115. */
  3116. p->state = TASK_NEW;
  3117. /*
  3118. * Make sure we do not leak PI boosting priority to the child.
  3119. */
  3120. p->prio = current->normal_prio;
  3121. #ifdef CONFIG_MTK_TASK_TURBO
  3122. if (unlikely(is_turbo_task(current)))
  3123. set_user_nice(p, current->nice_backup);
  3124. #endif
  3125. /*
  3126. * Revert to default priority/policy on fork if requested.
  3127. */
  3128. reset = p->sched_reset_on_fork;
  3129. if (unlikely(reset)) {
  3130. if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
  3131. p->policy = SCHED_NORMAL;
  3132. p->static_prio = NICE_TO_PRIO(0);
  3133. p->rt_priority = 0;
  3134. } else if (PRIO_TO_NICE(p->static_prio) < 0)
  3135. p->static_prio = NICE_TO_PRIO(0);
  3136. p->prio = p->normal_prio = __normal_prio(p);
  3137. set_load_weight(p);
  3138. /*
  3139. * We don't need the reset flag anymore after the fork. It has
  3140. * fulfilled its duty:
  3141. */
  3142. p->sched_reset_on_fork = 0;
  3143. }
  3144. if (dl_prio(p->prio)) {
  3145. put_cpu();
  3146. return -EAGAIN;
  3147. } else if (rt_prio(p->prio)) {
  3148. p->sched_class = &rt_sched_class;
  3149. } else {
  3150. p->sched_class = &fair_sched_class;
  3151. #ifdef CONFIG_MTK_TASK_TURBO
  3152. /* prio and backup should be aligned */
  3153. p->nice_backup = PRIO_TO_NICE(p->prio);
  3154. #endif
  3155. }
  3156. init_entity_runnable_average(&p->se);
  3157. #ifdef CONFIG_MTK_SCHED_BOOST
  3158. p->cpu_prefer = current->cpu_prefer;
  3159. #ifdef CONFIG_MTK_TASK_TURBO
  3160. if (unlikely(is_turbo_task(current)))
  3161. p->cpu_prefer = 0; // SCHED_PREFER_NONE
  3162. #endif
  3163. #endif
  3164. uclamp_fork(p, reset);
  3165. /*
  3166. * The child is not yet in the pid-hash so no cgroup attach races,
  3167. * and the cgroup is pinned to this child due to cgroup_fork()
  3168. * is ran before sched_fork().
  3169. *
  3170. * Silence PROVE_RCU.
  3171. */
  3172. raw_spin_lock_irqsave(&p->pi_lock, flags);
  3173. /*
  3174. * We're setting the CPU for the first time, we don't migrate,
  3175. * so use __set_task_cpu().
  3176. */
  3177. __set_task_cpu(p, cpu);
  3178. if (p->sched_class->task_fork)
  3179. p->sched_class->task_fork(p);
  3180. raw_spin_unlock_irqrestore(&p->pi_lock, flags);
  3181. #ifdef CONFIG_SCHED_INFO
  3182. if (likely(sched_info_on()))
  3183. memset(&p->sched_info, 0, sizeof(p->sched_info));
  3184. #endif
  3185. #if defined(CONFIG_SMP)
  3186. p->on_cpu = 0;
  3187. #endif
  3188. init_task_preempt_count(p);
  3189. #ifdef CONFIG_SMP
  3190. plist_node_init(&p->pushable_tasks, MAX_PRIO);
  3191. RB_CLEAR_NODE(&p->pushable_dl_tasks);
  3192. #endif
  3193. put_cpu();
  3194. return 0;
  3195. }
  3196. unsigned long to_ratio(u64 period, u64 runtime)
  3197. {
  3198. if (runtime == RUNTIME_INF)
  3199. return BW_UNIT;
  3200. /*
  3201. * Doing this here saves a lot of checks in all
  3202. * the calling paths, and returning zero seems
  3203. * safe for them anyway.
  3204. */
  3205. if (period == 0)
  3206. return 0;
  3207. return div64_u64(runtime << BW_SHIFT, period);
  3208. }
  3209. /*
  3210. * wake_up_new_task - wake up a newly created task for the first time.
  3211. *
  3212. * This function will do some initial scheduler statistics housekeeping
  3213. * that must be done for every newly created context, then puts the task
  3214. * on the runqueue and wakes it.
  3215. */
  3216. void wake_up_new_task(struct task_struct *p)
  3217. {
  3218. struct rq_flags rf;
  3219. struct rq *rq;
  3220. raw_spin_lock_irqsave(&p->pi_lock, rf.flags);
  3221. walt_init_new_task_load(p);
  3222. p->state = TASK_RUNNING;
  3223. #ifdef CONFIG_SMP
  3224. /*
  3225. * Fork balancing, do it here and not earlier because:
  3226. * - cpus_allowed can change in the fork path
  3227. * - any previously selected CPU might disappear through hotplug
  3228. *
  3229. * Use __set_task_cpu() to avoid calling sched_class::migrate_task_rq,
  3230. * as we're not fully set-up yet.
  3231. */
  3232. __set_task_cpu(p, select_task_rq(p, task_cpu(p), SD_BALANCE_FORK, 0, 1));
  3233. #endif
  3234. rq = __task_rq_lock(p, &rf);
  3235. update_rq_clock(rq);
  3236. post_init_entity_util_avg(&p->se);
  3237. p->last_enqueued_ts = ktime_get_ns();
  3238. activate_task(rq, p, ENQUEUE_NOCLOCK);
  3239. walt_mark_task_starting(p);
  3240. p->on_rq = TASK_ON_RQ_QUEUED;
  3241. trace_sched_wakeup_new(p);
  3242. check_preempt_curr(rq, p, WF_FORK);
  3243. #ifdef CONFIG_SMP
  3244. if (p->sched_class->task_woken) {
  3245. /*
  3246. * Nothing relies on rq->lock after this, so its fine to
  3247. * drop it.
  3248. */
  3249. rq_unpin_lock(rq, &rf);
  3250. p->sched_class->task_woken(rq, p);
  3251. rq_repin_lock(rq, &rf);
  3252. }
  3253. #endif
  3254. task_rq_unlock(rq, p, &rf);
  3255. }
  3256. #ifdef CONFIG_PREEMPT_NOTIFIERS
  3257. static struct static_key preempt_notifier_key = STATIC_KEY_INIT_FALSE;
  3258. void preempt_notifier_inc(void)
  3259. {
  3260. static_key_slow_inc(&preempt_notifier_key);
  3261. }
  3262. EXPORT_SYMBOL_GPL(preempt_notifier_inc);
  3263. void preempt_notifier_dec(void)
  3264. {
  3265. static_key_slow_dec(&preempt_notifier_key);
  3266. }
  3267. EXPORT_SYMBOL_GPL(preempt_notifier_dec);
  3268. /**
  3269. * preempt_notifier_register - tell me when current is being preempted & rescheduled
  3270. * @notifier: notifier struct to register
  3271. */
  3272. void preempt_notifier_register(struct preempt_notifier *notifier)
  3273. {
  3274. if (!static_key_false(&preempt_notifier_key))
  3275. WARN(1, "registering preempt_notifier while notifiers disabled\n");
  3276. hlist_add_head(&notifier->link, &current->preempt_notifiers);
  3277. }
  3278. EXPORT_SYMBOL_GPL(preempt_notifier_register);
  3279. /**
  3280. * preempt_notifier_unregister - no longer interested in preemption notifications
  3281. * @notifier: notifier struct to unregister
  3282. *
  3283. * This is *not* safe to call from within a preemption notifier.
  3284. */
  3285. void preempt_notifier_unregister(struct preempt_notifier *notifier)
  3286. {
  3287. hlist_del(&notifier->link);
  3288. }
  3289. EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
  3290. static void __fire_sched_in_preempt_notifiers(struct task_struct *curr)
  3291. {
  3292. struct preempt_notifier *notifier;
  3293. hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
  3294. notifier->ops->sched_in(notifier, raw_smp_processor_id());
  3295. }
  3296. static __always_inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
  3297. {
  3298. if (static_key_false(&preempt_notifier_key))
  3299. __fire_sched_in_preempt_notifiers(curr);
  3300. }
  3301. static void
  3302. __fire_sched_out_preempt_notifiers(struct task_struct *curr,
  3303. struct task_struct *next)
  3304. {
  3305. struct preempt_notifier *notifier;
  3306. hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
  3307. notifier->ops->sched_out(notifier, next);
  3308. }
  3309. static __always_inline void
  3310. fire_sched_out_preempt_notifiers(struct task_struct *curr,
  3311. struct task_struct *next)
  3312. {
  3313. if (static_key_false(&preempt_notifier_key))
  3314. __fire_sched_out_preempt_notifiers(curr, next);
  3315. }
  3316. #else /* !CONFIG_PREEMPT_NOTIFIERS */
  3317. static inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
  3318. {
  3319. }
  3320. static inline void
  3321. fire_sched_out_preempt_notifiers(struct task_struct *curr,
  3322. struct task_struct *next)
  3323. {
  3324. }
  3325. #endif /* CONFIG_PREEMPT_NOTIFIERS */
  3326. /**
  3327. * prepare_task_switch - prepare to switch tasks
  3328. * @rq: the runqueue preparing to switch
  3329. * @prev: the current task that is being switched out
  3330. * @next: the task we are going to switch to.
  3331. *
  3332. * This is called with the rq lock held and interrupts off. It must
  3333. * be paired with a subsequent finish_task_switch after the context
  3334. * switch.
  3335. *
  3336. * prepare_task_switch sets up locking and calls architecture specific
  3337. * hooks.
  3338. */
  3339. static inline void
  3340. prepare_task_switch(struct rq *rq, struct task_struct *prev,
  3341. struct task_struct *next)
  3342. {
  3343. kcov_prepare_switch(prev);
  3344. sched_info_switch(rq, prev, next);
  3345. perf_event_task_sched_out(prev, next);
  3346. hook_ca_context_switch(rq, prev, next);
  3347. fire_sched_out_preempt_notifiers(prev, next);
  3348. prepare_lock_switch(rq, next);
  3349. prepare_arch_switch(next);
  3350. }
  3351. /**
  3352. * finish_task_switch - clean up after a task-switch
  3353. * @prev: the thread we just switched away from.
  3354. *
  3355. * finish_task_switch must be called after the context switch, paired
  3356. * with a prepare_task_switch call before the context switch.
  3357. * finish_task_switch will reconcile locking set up by prepare_task_switch,
  3358. * and do any other architecture-specific cleanup actions.
  3359. *
  3360. * Note that we may have delayed dropping an mm in context_switch(). If
  3361. * so, we finish that here outside of the runqueue lock. (Doing it
  3362. * with the lock held can cause deadlocks; see schedule() for
  3363. * details.)
  3364. *
  3365. * The context switch have flipped the stack from under us and restored the
  3366. * local variables which were saved when this task called schedule() in the
  3367. * past. prev == current is still correct but we need to recalculate this_rq
  3368. * because prev may have moved to another CPU.
  3369. */
  3370. static struct rq *finish_task_switch(struct task_struct *prev)
  3371. __releases(rq->lock)
  3372. {
  3373. struct rq *rq = this_rq();
  3374. struct mm_struct *mm = rq->prev_mm;
  3375. long prev_state;
  3376. /*
  3377. * The previous task will have left us with a preempt_count of 2
  3378. * because it left us after:
  3379. *
  3380. * schedule()
  3381. * preempt_disable(); // 1
  3382. * __schedule()
  3383. * raw_spin_lock_irq(&rq->lock) // 2
  3384. *
  3385. * Also, see FORK_PREEMPT_COUNT.
  3386. */
  3387. if (WARN_ONCE(preempt_count() != 2*PREEMPT_DISABLE_OFFSET,
  3388. "corrupted preempt_count: %s/%d/0x%x\n",
  3389. current->comm, current->pid, preempt_count()))
  3390. preempt_count_set(FORK_PREEMPT_COUNT);
  3391. rq->prev_mm = NULL;
  3392. /*
  3393. * A task struct has one reference for the use as "current".
  3394. * If a task dies, then it sets TASK_DEAD in tsk->state and calls
  3395. * schedule one last time. The schedule call will never return, and
  3396. * the scheduled task must drop that reference.
  3397. *
  3398. * We must observe prev->state before clearing prev->on_cpu (in
  3399. * finish_lock_switch), otherwise a concurrent wakeup can get prev
  3400. * running on another CPU and we could rave with its RUNNING -> DEAD
  3401. * transition, resulting in a double drop.
  3402. */
  3403. prev_state = prev->state;
  3404. vtime_task_switch(prev);
  3405. perf_event_task_sched_in(prev, current);
  3406. /*
  3407. * The membarrier system call requires a full memory barrier
  3408. * after storing to rq->curr, before going back to user-space.
  3409. *
  3410. * TODO: This smp_mb__after_unlock_lock can go away if PPC end
  3411. * up adding a full barrier to switch_mm(), or we should figure
  3412. * out if a smp_mb__after_unlock_lock is really the proper API
  3413. * to use.
  3414. */
  3415. smp_mb__after_unlock_lock();
  3416. finish_lock_switch(rq, prev);
  3417. finish_arch_post_lock_switch();
  3418. kcov_finish_switch(current);
  3419. fire_sched_in_preempt_notifiers(current);
  3420. if (mm)
  3421. mmdrop(mm);
  3422. if (unlikely(prev_state == TASK_DEAD)) {
  3423. if (prev->sched_class->task_dead)
  3424. prev->sched_class->task_dead(prev);
  3425. /*
  3426. * Remove function-return probe instances associated with this
  3427. * task and put them back on the free list.
  3428. */
  3429. kprobe_flush_task(prev);
  3430. /* Task is done with its stack. */
  3431. put_task_stack(prev);
  3432. put_task_struct(prev);
  3433. }
  3434. tick_nohz_task_switch();
  3435. return rq;
  3436. }
  3437. #ifdef CONFIG_SMP
  3438. /* rq->lock is NOT held, but preemption is disabled */
  3439. static void __balance_callback(struct rq *rq)
  3440. {
  3441. struct callback_head *head, *next;
  3442. void (*func)(struct rq *rq);
  3443. unsigned long flags;
  3444. raw_spin_lock_irqsave(&rq->lock, flags);
  3445. head = rq->balance_callback;
  3446. rq->balance_callback = NULL;
  3447. while (head) {
  3448. func = (void (*)(struct rq *))head->func;
  3449. next = head->next;
  3450. head->next = NULL;
  3451. head = next;
  3452. func(rq);
  3453. }
  3454. raw_spin_unlock_irqrestore(&rq->lock, flags);
  3455. }
  3456. static inline void balance_callback(struct rq *rq)
  3457. {
  3458. if (unlikely(rq->balance_callback))
  3459. __balance_callback(rq);
  3460. }
  3461. #else
  3462. static inline void balance_callback(struct rq *rq)
  3463. {
  3464. }
  3465. #endif
  3466. /**
  3467. * schedule_tail - first thing a freshly forked thread must call.
  3468. * @prev: the thread we just switched away from.
  3469. */
  3470. asmlinkage __visible void schedule_tail(struct task_struct *prev)
  3471. __releases(rq->lock)
  3472. {
  3473. struct rq *rq;
  3474. /*
  3475. * New tasks start with FORK_PREEMPT_COUNT, see there and
  3476. * finish_task_switch() for details.
  3477. *
  3478. * finish_task_switch() will drop rq->lock() and lower preempt_count
  3479. * and the preempt_enable() will end up enabling preemption (on
  3480. * PREEMPT_COUNT kernels).
  3481. */
  3482. rq = finish_task_switch(prev);
  3483. balance_callback(rq);
  3484. preempt_enable();
  3485. if (current->set_child_tid)
  3486. put_user(task_pid_vnr(current), current->set_child_tid);
  3487. }
  3488. /*
  3489. * context_switch - switch to the new MM and the new thread's register state.
  3490. */
  3491. static __always_inline struct rq *
  3492. context_switch(struct rq *rq, struct task_struct *prev,
  3493. struct task_struct *next, struct rq_flags *rf)
  3494. {
  3495. struct mm_struct *mm, *oldmm;
  3496. prepare_task_switch(rq, prev, next);
  3497. mm = next->mm;
  3498. oldmm = prev->active_mm;
  3499. /*
  3500. * For paravirt, this is coupled with an exit in switch_to to
  3501. * combine the page table reload and the switch backend into
  3502. * one hypercall.
  3503. */
  3504. arch_start_context_switch(prev);
  3505. if (!mm) {
  3506. next->active_mm = oldmm;
  3507. mmgrab(oldmm);
  3508. enter_lazy_tlb(oldmm, next);
  3509. } else
  3510. switch_mm_irqs_off(oldmm, mm, next);
  3511. if (!prev->mm) {
  3512. prev->active_mm = NULL;
  3513. rq->prev_mm = oldmm;
  3514. }
  3515. rq->clock_update_flags &= ~(RQCF_ACT_SKIP|RQCF_REQ_SKIP);
  3516. /*
  3517. * Since the runqueue lock will be released by the next
  3518. * task (which is an invalid locking op but in the case
  3519. * of the scheduler it's an obvious special-case), so we
  3520. * do an early lockdep release here:
  3521. */
  3522. rq_unpin_lock(rq, rf);
  3523. spin_release(&rq->lock.dep_map, 1, 0UL);
  3524. /* Here we just switch the register state and the stack. */
  3525. switch_to(prev, next, prev);
  3526. barrier();
  3527. return finish_task_switch(prev);
  3528. }
  3529. /*
  3530. * nr_running and nr_context_switches:
  3531. *
  3532. * externally visible scheduler statistics: current number of runnable
  3533. * threads, total number of context switches performed since bootup.
  3534. */
  3535. unsigned long nr_running(void)
  3536. {
  3537. unsigned long i, sum = 0;
  3538. for_each_online_cpu(i)
  3539. sum += cpu_rq(i)->nr_running;
  3540. return sum;
  3541. }
  3542. /*
  3543. * Check if only the current task is running on the CPU.
  3544. *
  3545. * Caution: this function does not check that the caller has disabled
  3546. * preemption, thus the result might have a time-of-check-to-time-of-use
  3547. * race. The caller is responsible to use it correctly, for example:
  3548. *
  3549. * - from a non-preemptable section (of course)
  3550. *
  3551. * - from a thread that is bound to a single CPU
  3552. *
  3553. * - in a loop with very short iterations (e.g. a polling loop)
  3554. */
  3555. bool single_task_running(void)
  3556. {
  3557. return raw_rq()->nr_running == 1;
  3558. }
  3559. EXPORT_SYMBOL(single_task_running);
  3560. unsigned long long nr_context_switches(void)
  3561. {
  3562. int i;
  3563. unsigned long long sum = 0;
  3564. for_each_possible_cpu(i)
  3565. sum += cpu_rq(i)->nr_switches;
  3566. return sum;
  3567. }
  3568. /*
  3569. * IO-wait accounting, and how its mostly bollocks (on SMP).
  3570. *
  3571. * The idea behind IO-wait account is to account the idle time that we could
  3572. * have spend running if it were not for IO. That is, if we were to improve the
  3573. * storage performance, we'd have a proportional reduction in IO-wait time.
  3574. *
  3575. * This all works nicely on UP, where, when a task blocks on IO, we account
  3576. * idle time as IO-wait, because if the storage were faster, it could've been
  3577. * running and we'd not be idle.
  3578. *
  3579. * This has been extended to SMP, by doing the same for each CPU. This however
  3580. * is broken.
  3581. *
  3582. * Imagine for instance the case where two tasks block on one CPU, only the one
  3583. * CPU will have IO-wait accounted, while the other has regular idle. Even
  3584. * though, if the storage were faster, both could've ran at the same time,
  3585. * utilising both CPUs.
  3586. *
  3587. * This means, that when looking globally, the current IO-wait accounting on
  3588. * SMP is a lower bound, by reason of under accounting.
  3589. *
  3590. * Worse, since the numbers are provided per CPU, they are sometimes
  3591. * interpreted per CPU, and that is nonsensical. A blocked task isn't strictly
  3592. * associated with any one particular CPU, it can wake to another CPU than it
  3593. * blocked on. This means the per CPU IO-wait number is meaningless.
  3594. *
  3595. * Task CPU affinities can make all that even more 'interesting'.
  3596. */
  3597. unsigned long nr_iowait(void)
  3598. {
  3599. unsigned long i, sum = 0;
  3600. for_each_possible_cpu(i)
  3601. sum += atomic_read(&cpu_rq(i)->nr_iowait);
  3602. return sum;
  3603. }
  3604. /*
  3605. * Consumers of these two interfaces, like for example the cpufreq menu
  3606. * governor are using nonsensical data. Boosting frequency for a CPU that has
  3607. * IO-wait which might not even end up running the task when it does become
  3608. * runnable.
  3609. */
  3610. unsigned long nr_iowait_cpu(int cpu)
  3611. {
  3612. struct rq *this = cpu_rq(cpu);
  3613. return atomic_read(&this->nr_iowait);
  3614. }
  3615. void get_iowait_load(unsigned long *nr_waiters, unsigned long *load)
  3616. {
  3617. struct rq *rq = this_rq();
  3618. *nr_waiters = atomic_read(&rq->nr_iowait);
  3619. *load = rq->load.weight;
  3620. }
  3621. #ifdef CONFIG_SMP
  3622. /*
  3623. * sched_exec - execve() is a valuable balancing opportunity, because at
  3624. * this point the task has the smallest effective memory and cache footprint.
  3625. */
  3626. void sched_exec(void)
  3627. {
  3628. struct task_struct *p = current;
  3629. unsigned long flags;
  3630. int dest_cpu;
  3631. raw_spin_lock_irqsave(&p->pi_lock, flags);
  3632. dest_cpu = p->sched_class->select_task_rq(p, task_cpu(p), SD_BALANCE_EXEC, 0, 1);
  3633. if (dest_cpu == smp_processor_id())
  3634. goto unlock;
  3635. if (likely(cpu_active(dest_cpu) && likely(!cpu_isolated(dest_cpu)))) {
  3636. struct migration_arg arg = { p, dest_cpu };
  3637. raw_spin_unlock_irqrestore(&p->pi_lock, flags);
  3638. stop_one_cpu(task_cpu(p), migration_cpu_stop, &arg);
  3639. return;
  3640. }
  3641. unlock:
  3642. raw_spin_unlock_irqrestore(&p->pi_lock, flags);
  3643. }
  3644. #endif
  3645. DEFINE_PER_CPU(struct kernel_stat, kstat);
  3646. DEFINE_PER_CPU(struct kernel_cpustat, kernel_cpustat);
  3647. EXPORT_PER_CPU_SYMBOL(kstat);
  3648. EXPORT_PER_CPU_SYMBOL(kernel_cpustat);
  3649. /*
  3650. * The function fair_sched_class.update_curr accesses the struct curr
  3651. * and its field curr->exec_start; when called from task_sched_runtime(),
  3652. * we observe a high rate of cache misses in practice.
  3653. * Prefetching this data results in improved performance.
  3654. */
  3655. static inline void prefetch_curr_exec_start(struct task_struct *p)
  3656. {
  3657. #ifdef CONFIG_FAIR_GROUP_SCHED
  3658. struct sched_entity *curr = (&p->se)->cfs_rq->curr;
  3659. #else
  3660. struct sched_entity *curr = (&task_rq(p)->cfs)->curr;
  3661. #endif
  3662. if (curr == NULL)
  3663. return;
  3664. prefetch(curr);
  3665. prefetch(&curr->exec_start);
  3666. }
  3667. /*
  3668. * Return accounted runtime for the task.
  3669. * In case the task is currently running, return the runtime plus current's
  3670. * pending runtime that have not been accounted yet.
  3671. */
  3672. unsigned long long task_sched_runtime(struct task_struct *p)
  3673. {
  3674. struct rq_flags rf;
  3675. struct rq *rq;
  3676. u64 ns;
  3677. #if defined(CONFIG_64BIT) && defined(CONFIG_SMP)
  3678. /*
  3679. * 64-bit doesn't need locks to atomically read a 64bit value.
  3680. * So we have a optimization chance when the task's delta_exec is 0.
  3681. * Reading ->on_cpu is racy, but this is ok.
  3682. *
  3683. * If we race with it leaving CPU, we'll take a lock. So we're correct.
  3684. * If we race with it entering CPU, unaccounted time is 0. This is
  3685. * indistinguishable from the read occurring a few cycles earlier.
  3686. * If we see ->on_cpu without ->on_rq, the task is leaving, and has
  3687. * been accounted, so we're correct here as well.
  3688. */
  3689. if (!p->on_cpu || !task_on_rq_queued(p))
  3690. return p->se.sum_exec_runtime;
  3691. #endif
  3692. rq = task_rq_lock(p, &rf);
  3693. /*
  3694. * Must be ->curr _and_ ->on_rq. If dequeued, we would
  3695. * project cycles that may never be accounted to this
  3696. * thread, breaking clock_gettime().
  3697. */
  3698. if (task_current(rq, p) && task_on_rq_queued(p)) {
  3699. prefetch_curr_exec_start(p);
  3700. update_rq_clock(rq);
  3701. p->sched_class->update_curr(rq);
  3702. }
  3703. ns = p->se.sum_exec_runtime;
  3704. task_rq_unlock(rq, p, &rf);
  3705. return ns;
  3706. }
  3707. /*
  3708. * This function gets called by the timer code, with HZ frequency.
  3709. * We call it with interrupts disabled.
  3710. */
  3711. void scheduler_tick(void)
  3712. {
  3713. int cpu = smp_processor_id();
  3714. struct rq *rq = cpu_rq(cpu);
  3715. struct task_struct *curr = rq->curr;
  3716. struct rq_flags rf;
  3717. sched_clock_tick();
  3718. rq_lock(rq, &rf);
  3719. walt_set_window_start(rq, &rf);
  3720. walt_update_task_ravg(rq->curr, rq, TASK_UPDATE,
  3721. walt_ktime_clock(), 0);
  3722. update_rq_clock(rq);
  3723. curr->sched_class->task_tick(rq, curr, 0);
  3724. cpu_load_update_active(rq);
  3725. calc_global_load_tick(rq);
  3726. psi_task_tick(rq);
  3727. rq_unlock(rq, &rf);
  3728. perf_event_task_tick();
  3729. #ifdef CONFIG_MTK_CACHE_CONTROL
  3730. hook_ca_scheduler_tick(cpu);
  3731. #endif
  3732. #ifdef CONFIG_MTK_PERF_TRACKER
  3733. perf_tracker(ktime_get_ns());
  3734. #endif
  3735. #ifdef CONFIG_SMP
  3736. rq->idle_balance = idle_cpu(cpu);
  3737. trigger_load_balance(rq);
  3738. #endif
  3739. rq_last_tick_reset(rq);
  3740. #ifdef CONFIG_MTK_SCHED_RQAVG_KS
  3741. sched_max_util_task_tracking();
  3742. #endif
  3743. #ifdef CONFIG_MTK_SCHED_CPULOAD
  3744. cal_cpu_load(cpu);
  3745. #endif
  3746. if (curr->sched_class == &fair_sched_class)
  3747. check_for_migration(rq, curr);
  3748. #ifdef CONFIG_MTK_QOS_FRAMEWORK
  3749. qos_prefetch_tick(cpu);
  3750. #endif /* CONFIG_MTK_QOS_FRAMEWORK */
  3751. }
  3752. #ifdef CONFIG_NO_HZ_FULL
  3753. /**
  3754. * scheduler_tick_max_deferment
  3755. *
  3756. * Keep at least one tick per second when a single
  3757. * active task is running because the scheduler doesn't
  3758. * yet completely support full dynticks environment.
  3759. *
  3760. * This makes sure that uptime, CFS vruntime, load
  3761. * balancing, etc... continue to move forward, even
  3762. * with a very low granularity.
  3763. *
  3764. * Return: Maximum deferment in nanoseconds.
  3765. */
  3766. u64 scheduler_tick_max_deferment(void)
  3767. {
  3768. struct rq *rq = this_rq();
  3769. unsigned long next, now = READ_ONCE(jiffies);
  3770. next = rq->last_sched_tick + HZ;
  3771. if (time_before_eq(next, now))
  3772. return 0;
  3773. return jiffies_to_nsecs(next - now);
  3774. }
  3775. #endif
  3776. #if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
  3777. defined(CONFIG_PREEMPT_TRACER))
  3778. /*
  3779. * If the value passed in is equal to the current preempt count
  3780. * then we just disabled preemption. Start timing the latency.
  3781. */
  3782. static inline void preempt_latency_start(int val)
  3783. {
  3784. if (preempt_count() == val) {
  3785. unsigned long ip = get_lock_parent_ip();
  3786. #ifdef CONFIG_DEBUG_PREEMPT
  3787. current->preempt_disable_ip = ip;
  3788. record_preempt_disable_ips(current);
  3789. #endif
  3790. trace_preempt_off(CALLER_ADDR0, ip);
  3791. }
  3792. }
  3793. void preempt_count_add(int val)
  3794. {
  3795. #ifdef CONFIG_DEBUG_PREEMPT
  3796. /*
  3797. * Underflow?
  3798. */
  3799. if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
  3800. return;
  3801. #endif
  3802. __preempt_count_add(val);
  3803. #ifdef CONFIG_DEBUG_PREEMPT
  3804. /*
  3805. * Spinlock count overflowing soon?
  3806. */
  3807. DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
  3808. PREEMPT_MASK - 10);
  3809. #endif
  3810. preempt_latency_start(val);
  3811. }
  3812. EXPORT_SYMBOL(preempt_count_add);
  3813. NOKPROBE_SYMBOL(preempt_count_add);
  3814. /*
  3815. * If the value passed in equals to the current preempt count
  3816. * then we just enabled preemption. Stop timing the latency.
  3817. */
  3818. static inline void preempt_latency_stop(int val)
  3819. {
  3820. if (preempt_count() == val)
  3821. trace_preempt_on(CALLER_ADDR0, get_lock_parent_ip());
  3822. }
  3823. void preempt_count_sub(int val)
  3824. {
  3825. #ifdef CONFIG_DEBUG_PREEMPT
  3826. /*
  3827. * Underflow?
  3828. */
  3829. if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
  3830. return;
  3831. /*
  3832. * Is the spinlock portion underflowing?
  3833. */
  3834. if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
  3835. !(preempt_count() & PREEMPT_MASK)))
  3836. return;
  3837. #endif
  3838. preempt_latency_stop(val);
  3839. __preempt_count_sub(val);
  3840. }
  3841. EXPORT_SYMBOL(preempt_count_sub);
  3842. NOKPROBE_SYMBOL(preempt_count_sub);
  3843. #else
  3844. static inline void preempt_latency_start(int val) { }
  3845. static inline void preempt_latency_stop(int val) { }
  3846. #endif
  3847. static inline unsigned long get_preempt_disable_ip(struct task_struct *p)
  3848. {
  3849. #ifdef CONFIG_DEBUG_PREEMPT
  3850. return p->preempt_disable_ip;
  3851. #else
  3852. return 0;
  3853. #endif
  3854. }
  3855. /*
  3856. * Print scheduling while atomic bug:
  3857. */
  3858. static noinline void __schedule_bug(struct task_struct *prev)
  3859. {
  3860. /* Save this before calling printk(), since that will clobber it */
  3861. unsigned long preempt_disable_ip = get_preempt_disable_ip(current);
  3862. int i = 0;
  3863. if (oops_in_progress)
  3864. return;
  3865. printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
  3866. prev->comm, prev->pid, preempt_count());
  3867. debug_show_held_locks(prev);
  3868. print_modules();
  3869. if (irqs_disabled())
  3870. print_irqtrace_events(prev);
  3871. if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)
  3872. && in_atomic_preempt_off()) {
  3873. pr_err("Preemption disabled at:");
  3874. print_ip_sym(preempt_disable_ip);
  3875. dump_preempt_disable_ips(current);
  3876. pr_cont("\n");
  3877. }
  3878. if (panic_on_warn)
  3879. panic("scheduling while atomic\n");
  3880. dump_stack();
  3881. add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
  3882. BUG_ON(1);
  3883. }
  3884. /*
  3885. * Various schedule()-time debugging checks and statistics:
  3886. */
  3887. static inline void schedule_debug(struct task_struct *prev)
  3888. {
  3889. #ifdef CONFIG_SCHED_STACK_END_CHECK
  3890. if (task_stack_end_corrupted(prev))
  3891. panic("corrupted stack end detected inside scheduler\n");
  3892. #endif
  3893. if (unlikely(in_atomic_preempt_off())) {
  3894. __schedule_bug(prev);
  3895. preempt_count_set(PREEMPT_DISABLED);
  3896. }
  3897. rcu_sleep_check();
  3898. profile_hit(SCHED_PROFILING, __builtin_return_address(0));
  3899. schedstat_inc(this_rq()->sched_count);
  3900. }
  3901. /*
  3902. * Pick up the highest-prio task:
  3903. */
  3904. static inline struct task_struct *
  3905. pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
  3906. {
  3907. const struct sched_class *class;
  3908. struct task_struct *p;
  3909. /*
  3910. * Optimization: we know that if all tasks are in the fair class we can
  3911. * call that function directly, but only if the @prev task wasn't of a
  3912. * higher scheduling class, because otherwise those loose the
  3913. * opportunity to pull in more work from other CPUs.
  3914. */
  3915. if (likely((prev->sched_class == &idle_sched_class ||
  3916. prev->sched_class == &fair_sched_class) &&
  3917. rq->nr_running == rq->cfs.h_nr_running)) {
  3918. p = fair_sched_class.pick_next_task(rq, prev, rf);
  3919. if (unlikely(p == RETRY_TASK))
  3920. goto again;
  3921. /* Assumes fair_sched_class->next == idle_sched_class */
  3922. if (unlikely(!p))
  3923. p = idle_sched_class.pick_next_task(rq, prev, rf);
  3924. return p;
  3925. }
  3926. again:
  3927. for_each_class(class) {
  3928. p = class->pick_next_task(rq, prev, rf);
  3929. if (p) {
  3930. if (unlikely(p == RETRY_TASK))
  3931. goto again;
  3932. return p;
  3933. }
  3934. }
  3935. /* The idle class should always have a runnable task: */
  3936. BUG();
  3937. }
  3938. /*
  3939. * __schedule() is the main scheduler function.
  3940. *
  3941. * The main means of driving the scheduler and thus entering this function are:
  3942. *
  3943. * 1. Explicit blocking: mutex, semaphore, waitqueue, etc.
  3944. *
  3945. * 2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return
  3946. * paths. For example, see arch/x86/entry_64.S.
  3947. *
  3948. * To drive preemption between tasks, the scheduler sets the flag in timer
  3949. * interrupt handler scheduler_tick().
  3950. *
  3951. * 3. Wakeups don't really cause entry into schedule(). They add a
  3952. * task to the run-queue and that's it.
  3953. *
  3954. * Now, if the new task added to the run-queue preempts the current
  3955. * task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets
  3956. * called on the nearest possible occasion:
  3957. *
  3958. * - If the kernel is preemptible (CONFIG_PREEMPT=y):
  3959. *
  3960. * - in syscall or exception context, at the next outmost
  3961. * preempt_enable(). (this might be as soon as the wake_up()'s
  3962. * spin_unlock()!)
  3963. *
  3964. * - in IRQ context, return from interrupt-handler to
  3965. * preemptible context
  3966. *
  3967. * - If the kernel is not preemptible (CONFIG_PREEMPT is not set)
  3968. * then at the next:
  3969. *
  3970. * - cond_resched() call
  3971. * - explicit schedule() call
  3972. * - return from syscall or exception to user-space
  3973. * - return from interrupt-handler to user-space
  3974. *
  3975. * WARNING: must be called with preemption disabled!
  3976. */
  3977. static void __sched notrace __schedule(bool preempt)
  3978. {
  3979. struct task_struct *prev, *next;
  3980. unsigned long *switch_count;
  3981. struct rq_flags rf;
  3982. struct rq *rq;
  3983. int cpu;
  3984. u64 wallclock;
  3985. cpu = smp_processor_id();
  3986. rq = cpu_rq(cpu);
  3987. prev = rq->curr;
  3988. schedule_debug(prev);
  3989. if (sched_feat(HRTICK))
  3990. hrtick_clear(rq);
  3991. local_irq_disable();
  3992. rcu_note_context_switch(preempt);
  3993. /*
  3994. * Make sure that signal_pending_state()->signal_pending() below
  3995. * can't be reordered with __set_current_state(TASK_INTERRUPTIBLE)
  3996. * done by the caller to avoid the race with signal_wake_up().
  3997. */
  3998. rq_lock(rq, &rf);
  3999. smp_mb__after_spinlock();
  4000. /* Promote REQ to ACT */
  4001. rq->clock_update_flags <<= 1;
  4002. update_rq_clock(rq);
  4003. switch_count = &prev->nivcsw;
  4004. if (!preempt && prev->state) {
  4005. if (unlikely(signal_pending_state(prev->state, prev))) {
  4006. prev->state = TASK_RUNNING;
  4007. } else {
  4008. deactivate_task(rq, prev, DEQUEUE_SLEEP | DEQUEUE_NOCLOCK);
  4009. prev->on_rq = 0;
  4010. if (prev->in_iowait) {
  4011. atomic_inc(&rq->nr_iowait);
  4012. delayacct_blkio_start();
  4013. }
  4014. /*
  4015. * If a worker went to sleep, notify and ask workqueue
  4016. * whether it wants to wake up a task to maintain
  4017. * concurrency.
  4018. */
  4019. if (prev->flags & PF_WQ_WORKER) {
  4020. struct task_struct *to_wakeup;
  4021. to_wakeup = wq_worker_sleeping(prev);
  4022. if (to_wakeup)
  4023. try_to_wake_up_local(to_wakeup, &rf);
  4024. }
  4025. }
  4026. switch_count = &prev->nvcsw;
  4027. }
  4028. next = pick_next_task(rq, prev, &rf);
  4029. wallclock = walt_ktime_clock();
  4030. walt_update_task_ravg(prev, rq, PUT_PREV_TASK, wallclock, 0);
  4031. walt_update_task_ravg(next, rq, PICK_NEXT_TASK, wallclock, 0);
  4032. clear_tsk_need_resched(prev);
  4033. clear_preempt_need_resched();
  4034. if (likely(prev != next)) {
  4035. #ifdef CONFIG_SCHED_WALT
  4036. if (!prev->on_rq)
  4037. prev->last_sleep_ts = wallclock;
  4038. #endif
  4039. rq->nr_switches++;
  4040. rq->curr = next;
  4041. /*
  4042. * The membarrier system call requires each architecture
  4043. * to have a full memory barrier after updating
  4044. * rq->curr, before returning to user-space. For TSO
  4045. * (e.g. x86), the architecture must provide its own
  4046. * barrier in switch_mm(). For weakly ordered machines
  4047. * for which spin_unlock() acts as a full memory
  4048. * barrier, finish_lock_switch() in common code takes
  4049. * care of this barrier. For weakly ordered machines for
  4050. * which spin_unlock() acts as a RELEASE barrier (only
  4051. * arm64 and PowerPC), arm64 has a full barrier in
  4052. * switch_to(), and PowerPC has
  4053. * smp_mb__after_unlock_lock() before
  4054. * finish_lock_switch().
  4055. */
  4056. ++*switch_count;
  4057. trace_sched_switch(preempt, prev, next);
  4058. /* Also unlocks the rq: */
  4059. rq = context_switch(rq, prev, next, &rf);
  4060. } else {
  4061. rq->clock_update_flags &= ~(RQCF_ACT_SKIP|RQCF_REQ_SKIP);
  4062. rq_unlock_irq(rq, &rf);
  4063. }
  4064. balance_callback(rq);
  4065. }
  4066. void __noreturn do_task_dead(void)
  4067. {
  4068. /* Causes final put_task_struct in finish_task_switch(): */
  4069. set_special_state(TASK_DEAD);
  4070. /* Tell freezer to ignore us: */
  4071. current->flags |= PF_NOFREEZE;
  4072. __schedule(false);
  4073. BUG();
  4074. /* Avoid "noreturn function does return" - but don't continue if BUG() is a NOP: */
  4075. for (;;)
  4076. cpu_relax();
  4077. }
  4078. static inline void sched_submit_work(struct task_struct *tsk)
  4079. {
  4080. if (!tsk->state || tsk_is_pi_blocked(tsk))
  4081. return;
  4082. /*
  4083. * If we are going to sleep and we have plugged IO queued,
  4084. * make sure to submit it to avoid deadlocks.
  4085. */
  4086. if (blk_needs_flush_plug(tsk))
  4087. blk_schedule_flush_plug(tsk);
  4088. }
  4089. asmlinkage __visible void __sched schedule(void)
  4090. {
  4091. struct task_struct *tsk = current;
  4092. sched_submit_work(tsk);
  4093. do {
  4094. preempt_disable();
  4095. __schedule(false);
  4096. sched_preempt_enable_no_resched();
  4097. } while (need_resched());
  4098. }
  4099. EXPORT_SYMBOL(schedule);
  4100. /*
  4101. * synchronize_rcu_tasks() makes sure that no task is stuck in preempted
  4102. * state (have scheduled out non-voluntarily) by making sure that all
  4103. * tasks have either left the run queue or have gone into user space.
  4104. * As idle tasks do not do either, they must not ever be preempted
  4105. * (schedule out non-voluntarily).
  4106. *
  4107. * schedule_idle() is similar to schedule_preempt_disable() except that it
  4108. * never enables preemption because it does not call sched_submit_work().
  4109. */
  4110. void __sched schedule_idle(void)
  4111. {
  4112. /*
  4113. * As this skips calling sched_submit_work(), which the idle task does
  4114. * regardless because that function is a nop when the task is in a
  4115. * TASK_RUNNING state, make sure this isn't used someplace that the
  4116. * current task can be in any other state. Note, idle is always in the
  4117. * TASK_RUNNING state.
  4118. */
  4119. WARN_ON_ONCE(current->state);
  4120. do {
  4121. __schedule(false);
  4122. } while (need_resched());
  4123. }
  4124. #ifdef CONFIG_CONTEXT_TRACKING
  4125. asmlinkage __visible void __sched schedule_user(void)
  4126. {
  4127. /*
  4128. * If we come here after a random call to set_need_resched(),
  4129. * or we have been woken up remotely but the IPI has not yet arrived,
  4130. * we haven't yet exited the RCU idle mode. Do it here manually until
  4131. * we find a better solution.
  4132. *
  4133. * NB: There are buggy callers of this function. Ideally we
  4134. * should warn if prev_state != CONTEXT_USER, but that will trigger
  4135. * too frequently to make sense yet.
  4136. */
  4137. enum ctx_state prev_state = exception_enter();
  4138. schedule();
  4139. exception_exit(prev_state);
  4140. }
  4141. #endif
  4142. /**
  4143. * schedule_preempt_disabled - called with preemption disabled
  4144. *
  4145. * Returns with preemption disabled. Note: preempt_count must be 1
  4146. */
  4147. void __sched schedule_preempt_disabled(void)
  4148. {
  4149. sched_preempt_enable_no_resched();
  4150. schedule();
  4151. preempt_disable();
  4152. }
  4153. static void __sched notrace preempt_schedule_common(void)
  4154. {
  4155. do {
  4156. /*
  4157. * Because the function tracer can trace preempt_count_sub()
  4158. * and it also uses preempt_enable/disable_notrace(), if
  4159. * NEED_RESCHED is set, the preempt_enable_notrace() called
  4160. * by the function tracer will call this function again and
  4161. * cause infinite recursion.
  4162. *
  4163. * Preemption must be disabled here before the function
  4164. * tracer can trace. Break up preempt_disable() into two
  4165. * calls. One to disable preemption without fear of being
  4166. * traced. The other to still record the preemption latency,
  4167. * which can also be traced by the function tracer.
  4168. */
  4169. preempt_disable_notrace();
  4170. preempt_latency_start(1);
  4171. __schedule(true);
  4172. preempt_latency_stop(1);
  4173. preempt_enable_no_resched_notrace();
  4174. /*
  4175. * Check again in case we missed a preemption opportunity
  4176. * between schedule and now.
  4177. */
  4178. } while (need_resched());
  4179. }
  4180. #ifdef CONFIG_PREEMPT
  4181. /*
  4182. * this is the entry point to schedule() from in-kernel preemption
  4183. * off of preempt_enable. Kernel preemptions off return from interrupt
  4184. * occur there and call schedule directly.
  4185. */
  4186. asmlinkage __visible void __sched notrace preempt_schedule(void)
  4187. {
  4188. /*
  4189. * If there is a non-zero preempt_count or interrupts are disabled,
  4190. * we do not want to preempt the current task. Just return..
  4191. */
  4192. if (likely(!preemptible()))
  4193. return;
  4194. preempt_schedule_common();
  4195. }
  4196. NOKPROBE_SYMBOL(preempt_schedule);
  4197. EXPORT_SYMBOL(preempt_schedule);
  4198. /**
  4199. * preempt_schedule_notrace - preempt_schedule called by tracing
  4200. *
  4201. * The tracing infrastructure uses preempt_enable_notrace to prevent
  4202. * recursion and tracing preempt enabling caused by the tracing
  4203. * infrastructure itself. But as tracing can happen in areas coming
  4204. * from userspace or just about to enter userspace, a preempt enable
  4205. * can occur before user_exit() is called. This will cause the scheduler
  4206. * to be called when the system is still in usermode.
  4207. *
  4208. * To prevent this, the preempt_enable_notrace will use this function
  4209. * instead of preempt_schedule() to exit user context if needed before
  4210. * calling the scheduler.
  4211. */
  4212. asmlinkage __visible void __sched notrace preempt_schedule_notrace(void)
  4213. {
  4214. enum ctx_state prev_ctx;
  4215. if (likely(!preemptible()))
  4216. return;
  4217. do {
  4218. /*
  4219. * Because the function tracer can trace preempt_count_sub()
  4220. * and it also uses preempt_enable/disable_notrace(), if
  4221. * NEED_RESCHED is set, the preempt_enable_notrace() called
  4222. * by the function tracer will call this function again and
  4223. * cause infinite recursion.
  4224. *
  4225. * Preemption must be disabled here before the function
  4226. * tracer can trace. Break up preempt_disable() into two
  4227. * calls. One to disable preemption without fear of being
  4228. * traced. The other to still record the preemption latency,
  4229. * which can also be traced by the function tracer.
  4230. */
  4231. preempt_disable_notrace();
  4232. preempt_latency_start(1);
  4233. /*
  4234. * Needs preempt disabled in case user_exit() is traced
  4235. * and the tracer calls preempt_enable_notrace() causing
  4236. * an infinite recursion.
  4237. */
  4238. prev_ctx = exception_enter();
  4239. __schedule(true);
  4240. exception_exit(prev_ctx);
  4241. preempt_latency_stop(1);
  4242. preempt_enable_no_resched_notrace();
  4243. } while (need_resched());
  4244. }
  4245. EXPORT_SYMBOL_GPL(preempt_schedule_notrace);
  4246. #endif /* CONFIG_PREEMPT */
  4247. /*
  4248. * this is the entry point to schedule() from kernel preemption
  4249. * off of irq context.
  4250. * Note, that this is called and return with irqs disabled. This will
  4251. * protect us against recursive calling from irq.
  4252. */
  4253. asmlinkage __visible void __sched preempt_schedule_irq(void)
  4254. {
  4255. enum ctx_state prev_state;
  4256. /* Catch callers which need to be fixed */
  4257. BUG_ON(preempt_count() || !irqs_disabled());
  4258. prev_state = exception_enter();
  4259. do {
  4260. preempt_disable();
  4261. local_irq_enable();
  4262. __schedule(true);
  4263. local_irq_disable();
  4264. sched_preempt_enable_no_resched();
  4265. } while (need_resched());
  4266. exception_exit(prev_state);
  4267. }
  4268. int default_wake_function(wait_queue_entry_t *curr, unsigned mode, int wake_flags,
  4269. void *key)
  4270. {
  4271. return try_to_wake_up(curr->private, mode, wake_flags, 1);
  4272. }
  4273. EXPORT_SYMBOL(default_wake_function);
  4274. #ifdef CONFIG_RT_MUTEXES
  4275. static inline int __rt_effective_prio(struct task_struct *pi_task, int prio)
  4276. {
  4277. if (pi_task)
  4278. prio = min(prio, pi_task->prio);
  4279. return prio;
  4280. }
  4281. static inline int rt_effective_prio(struct task_struct *p, int prio)
  4282. {
  4283. struct task_struct *pi_task = rt_mutex_get_top_task(p);
  4284. return __rt_effective_prio(pi_task, prio);
  4285. }
  4286. /*
  4287. * rt_mutex_setprio - set the current priority of a task
  4288. * @p: task to boost
  4289. * @pi_task: donor task
  4290. *
  4291. * This function changes the 'effective' priority of a task. It does
  4292. * not touch ->normal_prio like __setscheduler().
  4293. *
  4294. * Used by the rt_mutex code to implement priority inheritance
  4295. * logic. Call site only calls if the priority of the task changed.
  4296. */
  4297. void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task)
  4298. {
  4299. int prio, oldprio, queued, running, queue_flag =
  4300. DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
  4301. const struct sched_class *prev_class;
  4302. struct rq_flags rf;
  4303. struct rq *rq;
  4304. #ifdef CONFIG_MTK_TASK_TURBO
  4305. /* if rt boost, recover prio with backup */
  4306. if (unlikely(is_turbo_task(p))) {
  4307. if (!dl_prio(p->prio) && !rt_prio(p->prio)) {
  4308. int backup = p->nice_backup;
  4309. if (backup >= MIN_NICE && backup <= MAX_NICE) {
  4310. p->static_prio = NICE_TO_PRIO(backup);
  4311. p->prio = p->normal_prio = __normal_prio(p);
  4312. set_load_weight(p);
  4313. }
  4314. }
  4315. }
  4316. #endif
  4317. /* XXX used to be waiter->prio, not waiter->task->prio */
  4318. prio = __rt_effective_prio(pi_task, p->normal_prio);
  4319. /*
  4320. * If nothing changed; bail early.
  4321. */
  4322. if (p->pi_top_task == pi_task && prio == p->prio && !dl_prio(prio))
  4323. return;
  4324. rq = __task_rq_lock(p, &rf);
  4325. update_rq_clock(rq);
  4326. /*
  4327. * Set under pi_lock && rq->lock, such that the value can be used under
  4328. * either lock.
  4329. *
  4330. * Note that there is loads of tricky to make this pointer cache work
  4331. * right. rt_mutex_slowunlock()+rt_mutex_postunlock() work together to
  4332. * ensure a task is de-boosted (pi_task is set to NULL) before the
  4333. * task is allowed to run again (and can exit). This ensures the pointer
  4334. * points to a blocked task -- which guaratees the task is present.
  4335. */
  4336. p->pi_top_task = pi_task;
  4337. /*
  4338. * For FIFO/RR we only need to set prio, if that matches we're done.
  4339. */
  4340. if (prio == p->prio && !dl_prio(prio))
  4341. goto out_unlock;
  4342. /*
  4343. * Idle task boosting is a nono in general. There is one
  4344. * exception, when PREEMPT_RT and NOHZ is active:
  4345. *
  4346. * The idle task calls get_next_timer_interrupt() and holds
  4347. * the timer wheel base->lock on the CPU and another CPU wants
  4348. * to access the timer (probably to cancel it). We can safely
  4349. * ignore the boosting request, as the idle CPU runs this code
  4350. * with interrupts disabled and will complete the lock
  4351. * protected section without being interrupted. So there is no
  4352. * real need to boost.
  4353. */
  4354. if (unlikely(p == rq->idle)) {
  4355. WARN_ON(p != rq->curr);
  4356. WARN_ON(p->pi_blocked_on);
  4357. goto out_unlock;
  4358. }
  4359. trace_sched_pi_setprio(p, pi_task);
  4360. oldprio = p->prio;
  4361. if (oldprio == prio)
  4362. queue_flag &= ~DEQUEUE_MOVE;
  4363. prev_class = p->sched_class;
  4364. queued = task_on_rq_queued(p);
  4365. running = task_current(rq, p);
  4366. if (queued)
  4367. dequeue_task(rq, p, queue_flag);
  4368. if (running)
  4369. put_prev_task(rq, p);
  4370. /*
  4371. * Boosting condition are:
  4372. * 1. -rt task is running and holds mutex A
  4373. * --> -dl task blocks on mutex A
  4374. *
  4375. * 2. -dl task is running and holds mutex A
  4376. * --> -dl task blocks on mutex A and could preempt the
  4377. * running task
  4378. */
  4379. if (dl_prio(prio)) {
  4380. if (!dl_prio(p->normal_prio) ||
  4381. (pi_task && dl_prio(pi_task->prio) &&
  4382. dl_entity_preempt(&pi_task->dl, &p->dl))) {
  4383. p->dl.dl_boosted = 1;
  4384. queue_flag |= ENQUEUE_REPLENISH;
  4385. } else
  4386. p->dl.dl_boosted = 0;
  4387. p->sched_class = &dl_sched_class;
  4388. } else if (rt_prio(prio)) {
  4389. if (dl_prio(oldprio))
  4390. p->dl.dl_boosted = 0;
  4391. if (oldprio < prio)
  4392. queue_flag |= ENQUEUE_HEAD;
  4393. p->sched_class = &rt_sched_class;
  4394. } else {
  4395. if (dl_prio(oldprio))
  4396. p->dl.dl_boosted = 0;
  4397. if (rt_prio(oldprio))
  4398. p->rt.timeout = 0;
  4399. p->sched_class = &fair_sched_class;
  4400. }
  4401. p->prio = prio;
  4402. if (queued)
  4403. enqueue_task(rq, p, queue_flag);
  4404. if (running)
  4405. set_curr_task(rq, p);
  4406. check_class_changed(rq, p, prev_class, oldprio);
  4407. out_unlock:
  4408. /* Avoid rq from going away on us: */
  4409. preempt_disable();
  4410. __task_rq_unlock(rq, &rf);
  4411. balance_callback(rq);
  4412. preempt_enable();
  4413. }
  4414. #else
  4415. static inline int rt_effective_prio(struct task_struct *p, int prio)
  4416. {
  4417. return prio;
  4418. }
  4419. #endif
  4420. #ifdef CONFIG_MTK_TASK_TURBO
  4421. #define task_turbo_nice(nice) (nice == 0xbeef || nice == 0xbeee)
  4422. #endif
  4423. void set_user_nice(struct task_struct *p, long nice)
  4424. {
  4425. bool queued, running;
  4426. int old_prio, delta;
  4427. struct rq_flags rf;
  4428. struct rq *rq;
  4429. #ifdef CONFIG_MTK_TASK_TURBO
  4430. if ((nice < MIN_NICE || nice > MAX_NICE) && !task_turbo_nice(nice))
  4431. return;
  4432. #else
  4433. if (task_nice(p) == nice || nice < MIN_NICE || nice > MAX_NICE)
  4434. return;
  4435. #endif
  4436. /*
  4437. * We have to be careful, if called from sys_setpriority(),
  4438. * the task might be in the middle of scheduling on another CPU.
  4439. */
  4440. rq = task_rq_lock(p, &rf);
  4441. update_rq_clock(rq);
  4442. #ifdef CONFIG_MTK_TASK_TURBO
  4443. /* for general use, backup it */
  4444. if (!task_turbo_nice(nice))
  4445. p->nice_backup = nice;
  4446. if (is_turbo_task(p)) {
  4447. nice = rlimit_to_nice(task_rlimit(p, RLIMIT_NICE));
  4448. if (unlikely(nice > MAX_NICE)) {
  4449. printk_deferred("[name:task-turbo&]pid=%d RLIMIT_NICE=%ld is not set\n",
  4450. p->pid, nice);
  4451. nice = p->nice_backup;
  4452. }
  4453. }
  4454. else
  4455. nice = p->nice_backup;
  4456. trace_sched_set_user_nice(p, nice, is_turbo_task(p));
  4457. #endif
  4458. /*
  4459. * The RT priorities are set via sched_setscheduler(), but we still
  4460. * allow the 'normal' nice value to be set - but as expected
  4461. * it wont have any effect on scheduling until the task is
  4462. * SCHED_DEADLINE, SCHED_FIFO or SCHED_RR:
  4463. */
  4464. if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
  4465. p->static_prio = NICE_TO_PRIO(nice);
  4466. goto out_unlock;
  4467. }
  4468. queued = task_on_rq_queued(p);
  4469. running = task_current(rq, p);
  4470. if (queued)
  4471. dequeue_task(rq, p, DEQUEUE_SAVE | DEQUEUE_NOCLOCK);
  4472. if (running)
  4473. put_prev_task(rq, p);
  4474. p->static_prio = NICE_TO_PRIO(nice);
  4475. set_load_weight(p);
  4476. old_prio = p->prio;
  4477. p->prio = effective_prio(p);
  4478. delta = p->prio - old_prio;
  4479. if (queued) {
  4480. enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
  4481. /*
  4482. * If the task increased its priority or is running and
  4483. * lowered its priority, then reschedule its CPU:
  4484. */
  4485. if (delta < 0 || (delta > 0 && task_running(rq, p)))
  4486. resched_curr(rq);
  4487. }
  4488. if (running)
  4489. set_curr_task(rq, p);
  4490. out_unlock:
  4491. task_rq_unlock(rq, p, &rf);
  4492. }
  4493. EXPORT_SYMBOL(set_user_nice);
  4494. /*
  4495. * can_nice - check if a task can reduce its nice value
  4496. * @p: task
  4497. * @nice: nice value
  4498. */
  4499. int can_nice(const struct task_struct *p, const int nice)
  4500. {
  4501. /* Convert nice value [19,-20] to rlimit style value [1,40]: */
  4502. int nice_rlim = nice_to_rlimit(nice);
  4503. return (nice_rlim <= task_rlimit(p, RLIMIT_NICE) ||
  4504. capable(CAP_SYS_NICE));
  4505. }
  4506. #ifdef __ARCH_WANT_SYS_NICE
  4507. /*
  4508. * sys_nice - change the priority of the current process.
  4509. * @increment: priority increment
  4510. *
  4511. * sys_setpriority is a more generic, but much slower function that
  4512. * does similar things.
  4513. */
  4514. SYSCALL_DEFINE1(nice, int, increment)
  4515. {
  4516. long nice, retval;
  4517. /*
  4518. * Setpriority might change our priority at the same moment.
  4519. * We don't have to worry. Conceptually one call occurs first
  4520. * and we have a single winner.
  4521. */
  4522. increment = clamp(increment, -NICE_WIDTH, NICE_WIDTH);
  4523. nice = task_nice(current) + increment;
  4524. nice = clamp_val(nice, MIN_NICE, MAX_NICE);
  4525. if (increment < 0 && !can_nice(current, nice))
  4526. return -EPERM;
  4527. retval = security_task_setnice(current, nice);
  4528. if (retval)
  4529. return retval;
  4530. set_user_nice(current, nice);
  4531. return 0;
  4532. }
  4533. #endif
  4534. /**
  4535. * task_prio - return the priority value of a given task.
  4536. * @p: the task in question.
  4537. *
  4538. * Return: The priority value as seen by users in /proc.
  4539. * RT tasks are offset by -200. Normal tasks are centered
  4540. * around 0, value goes from -16 to +15.
  4541. */
  4542. int task_prio(const struct task_struct *p)
  4543. {
  4544. return p->prio - MAX_RT_PRIO;
  4545. }
  4546. /**
  4547. * idle_cpu - is a given CPU idle currently?
  4548. * @cpu: the processor in question.
  4549. *
  4550. * Return: 1 if the CPU is currently idle. 0 otherwise.
  4551. */
  4552. int idle_cpu(int cpu)
  4553. {
  4554. struct rq *rq = cpu_rq(cpu);
  4555. if (rq->curr != rq->idle)
  4556. return 0;
  4557. if (rq->nr_running)
  4558. return 0;
  4559. #ifdef CONFIG_SMP
  4560. if (!llist_empty(&rq->wake_list))
  4561. return 0;
  4562. #endif
  4563. return 1;
  4564. }
  4565. /**
  4566. * idle_task - return the idle task for a given CPU.
  4567. * @cpu: the processor in question.
  4568. *
  4569. * Return: The idle task for the CPU @cpu.
  4570. */
  4571. struct task_struct *idle_task(int cpu)
  4572. {
  4573. return cpu_rq(cpu)->idle;
  4574. }
  4575. /**
  4576. * find_process_by_pid - find a process with a matching PID value.
  4577. * @pid: the pid in question.
  4578. *
  4579. * The task of @pid, if found. %NULL otherwise.
  4580. */
  4581. static struct task_struct *find_process_by_pid(pid_t pid)
  4582. {
  4583. return pid ? find_task_by_vpid(pid) : current;
  4584. }
  4585. /*
  4586. * sched_setparam() passes in -1 for its policy, to let the functions
  4587. * it calls know not to change it.
  4588. */
  4589. #define SETPARAM_POLICY -1
  4590. static void __setscheduler_params(struct task_struct *p,
  4591. const struct sched_attr *attr)
  4592. {
  4593. int policy = attr->sched_policy;
  4594. if (policy == SETPARAM_POLICY)
  4595. policy = p->policy;
  4596. /* Replace SCHED_FIFO with SCHED_RR to reduce latency */
  4597. p->policy = policy == SCHED_FIFO ? SCHED_RR : policy;
  4598. if (dl_policy(policy))
  4599. __setparam_dl(p, attr);
  4600. else if (fair_policy(policy))
  4601. p->static_prio = NICE_TO_PRIO(attr->sched_nice);
  4602. /*
  4603. * __sched_setscheduler() ensures attr->sched_priority == 0 when
  4604. * !rt_policy. Always setting this ensures that things like
  4605. * getparam()/getattr() don't report silly values for !rt tasks.
  4606. */
  4607. p->rt_priority = attr->sched_priority;
  4608. p->normal_prio = normal_prio(p);
  4609. set_load_weight(p);
  4610. }
  4611. /* Actually do priority change: must hold pi & rq lock. */
  4612. static void __setscheduler(struct rq *rq, struct task_struct *p,
  4613. const struct sched_attr *attr, bool keep_boost)
  4614. {
  4615. __setscheduler_params(p, attr);
  4616. /*
  4617. * Keep a potential priority boosting if called from
  4618. * sched_setscheduler().
  4619. */
  4620. p->prio = normal_prio(p);
  4621. if (keep_boost)
  4622. p->prio = rt_effective_prio(p, p->prio);
  4623. if (dl_prio(p->prio))
  4624. p->sched_class = &dl_sched_class;
  4625. else if (rt_prio(p->prio))
  4626. p->sched_class = &rt_sched_class;
  4627. #ifdef CONFIG_MTK_TASK_TURBO
  4628. else {
  4629. p->sched_class = &fair_sched_class;
  4630. p->nice_backup = PRIO_TO_NICE(p->prio);
  4631. }
  4632. #else
  4633. else
  4634. p->sched_class = &fair_sched_class;
  4635. #endif
  4636. }
  4637. /*
  4638. * Check the target process has a UID that matches the current process's:
  4639. */
  4640. static bool check_same_owner(struct task_struct *p)
  4641. {
  4642. const struct cred *cred = current_cred(), *pcred;
  4643. bool match;
  4644. rcu_read_lock();
  4645. pcred = __task_cred(p);
  4646. match = (uid_eq(cred->euid, pcred->euid) ||
  4647. uid_eq(cred->euid, pcred->uid));
  4648. rcu_read_unlock();
  4649. return match;
  4650. }
  4651. static int __sched_setscheduler(struct task_struct *p,
  4652. const struct sched_attr *attr,
  4653. bool user, bool pi)
  4654. {
  4655. int newprio = dl_policy(attr->sched_policy) ? MAX_DL_PRIO - 1 :
  4656. MAX_RT_PRIO - 1 - attr->sched_priority;
  4657. int retval, oldprio, oldpolicy = -1, queued, running;
  4658. int new_effective_prio, policy = attr->sched_policy;
  4659. const struct sched_class *prev_class;
  4660. struct rq_flags rf;
  4661. int reset_on_fork;
  4662. int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
  4663. struct rq *rq;
  4664. /* The pi code expects interrupts enabled */
  4665. BUG_ON(pi && in_interrupt());
  4666. recheck:
  4667. /* Double check policy once rq lock held: */
  4668. if (policy < 0) {
  4669. reset_on_fork = p->sched_reset_on_fork;
  4670. policy = oldpolicy = p->policy;
  4671. } else {
  4672. reset_on_fork = !!(attr->sched_flags & SCHED_FLAG_RESET_ON_FORK);
  4673. if (!valid_policy(policy))
  4674. return -EINVAL;
  4675. }
  4676. if (attr->sched_flags &
  4677. ~(SCHED_FLAG_RESET_ON_FORK | SCHED_FLAG_RECLAIM))
  4678. return -EINVAL;
  4679. /*
  4680. * Valid priorities for SCHED_FIFO and SCHED_RR are
  4681. * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
  4682. * SCHED_BATCH and SCHED_IDLE is 0.
  4683. */
  4684. if ((p->mm && attr->sched_priority > MAX_USER_RT_PRIO-1) ||
  4685. (!p->mm && attr->sched_priority > MAX_RT_PRIO-1))
  4686. return -EINVAL;
  4687. if ((dl_policy(policy) && !__checkparam_dl(attr)) ||
  4688. (rt_policy(policy) != (attr->sched_priority != 0)))
  4689. return -EINVAL;
  4690. /*
  4691. * Allow unprivileged RT tasks to decrease priority:
  4692. */
  4693. if (user && !capable(CAP_SYS_NICE)) {
  4694. if (fair_policy(policy)) {
  4695. if (attr->sched_nice < task_nice(p) &&
  4696. !can_nice(p, attr->sched_nice))
  4697. return -EPERM;
  4698. }
  4699. if (rt_policy(policy)) {
  4700. unsigned long rlim_rtprio =
  4701. task_rlimit(p, RLIMIT_RTPRIO);
  4702. /* Can't set/change the rt policy: */
  4703. if (policy != p->policy && !rlim_rtprio)
  4704. return -EPERM;
  4705. /* Can't increase priority: */
  4706. if (attr->sched_priority > p->rt_priority &&
  4707. attr->sched_priority > rlim_rtprio)
  4708. return -EPERM;
  4709. }
  4710. /*
  4711. * Can't set/change SCHED_DEADLINE policy at all for now
  4712. * (safest behavior); in the future we would like to allow
  4713. * unprivileged DL tasks to increase their relative deadline
  4714. * or reduce their runtime (both ways reducing utilization)
  4715. */
  4716. if (dl_policy(policy))
  4717. return -EPERM;
  4718. /*
  4719. * Treat SCHED_IDLE as nice 20. Only allow a switch to
  4720. * SCHED_NORMAL if the RLIMIT_NICE would normally permit it.
  4721. */
  4722. if (idle_policy(p->policy) && !idle_policy(policy)) {
  4723. if (!can_nice(p, task_nice(p)))
  4724. return -EPERM;
  4725. }
  4726. /* Can't change other user's priorities: */
  4727. if (!check_same_owner(p))
  4728. return -EPERM;
  4729. /* Normal users shall not reset the sched_reset_on_fork flag: */
  4730. if (p->sched_reset_on_fork && !reset_on_fork)
  4731. return -EPERM;
  4732. }
  4733. if (user) {
  4734. retval = security_task_setscheduler(p);
  4735. if (retval)
  4736. return retval;
  4737. }
  4738. /*
  4739. * Make sure no PI-waiters arrive (or leave) while we are
  4740. * changing the priority of the task:
  4741. *
  4742. * To be able to change p->policy safely, the appropriate
  4743. * runqueue lock must be held.
  4744. */
  4745. rq = task_rq_lock(p, &rf);
  4746. update_rq_clock(rq);
  4747. /*
  4748. * Changing the policy of the stop threads its a very bad idea:
  4749. */
  4750. if (p == rq->stop) {
  4751. task_rq_unlock(rq, p, &rf);
  4752. return -EINVAL;
  4753. }
  4754. /*
  4755. * If not changing anything there's no need to proceed further,
  4756. * but store a possible modification of reset_on_fork.
  4757. */
  4758. if (unlikely(policy == p->policy)) {
  4759. if (fair_policy(policy) && attr->sched_nice != task_nice(p))
  4760. goto change;
  4761. if (rt_policy(policy) && attr->sched_priority != p->rt_priority)
  4762. goto change;
  4763. if (dl_policy(policy) && dl_param_changed(p, attr))
  4764. goto change;
  4765. p->sched_reset_on_fork = reset_on_fork;
  4766. task_rq_unlock(rq, p, &rf);
  4767. return 0;
  4768. }
  4769. change:
  4770. if (user) {
  4771. #ifdef CONFIG_RT_GROUP_SCHED
  4772. /*
  4773. * Do not allow realtime tasks into groups that have no runtime
  4774. * assigned.
  4775. */
  4776. if (rt_bandwidth_enabled() && rt_policy(policy) &&
  4777. task_group(p)->rt_bandwidth.rt_runtime == 0 &&
  4778. !task_group_is_autogroup(task_group(p))) {
  4779. task_rq_unlock(rq, p, &rf);
  4780. return -EPERM;
  4781. }
  4782. #endif
  4783. #ifdef CONFIG_SMP
  4784. if (dl_bandwidth_enabled() && dl_policy(policy)) {
  4785. cpumask_t *span = rq->rd->span;
  4786. /*
  4787. * Don't allow tasks with an affinity mask smaller than
  4788. * the entire root_domain to become SCHED_DEADLINE. We
  4789. * will also fail if there's no bandwidth available.
  4790. */
  4791. if (!cpumask_subset(span, &p->cpus_allowed) ||
  4792. rq->rd->dl_bw.bw == 0) {
  4793. task_rq_unlock(rq, p, &rf);
  4794. return -EPERM;
  4795. }
  4796. }
  4797. #endif
  4798. }
  4799. /* Re-check policy now with rq lock held: */
  4800. if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
  4801. policy = oldpolicy = -1;
  4802. task_rq_unlock(rq, p, &rf);
  4803. goto recheck;
  4804. }
  4805. /*
  4806. * If setscheduling to SCHED_DEADLINE (or changing the parameters
  4807. * of a SCHED_DEADLINE task) we need to check if enough bandwidth
  4808. * is available.
  4809. */
  4810. if ((dl_policy(policy) || dl_task(p)) && sched_dl_overflow(p, policy, attr)) {
  4811. task_rq_unlock(rq, p, &rf);
  4812. return -EBUSY;
  4813. }
  4814. p->sched_reset_on_fork = reset_on_fork;
  4815. oldprio = p->prio;
  4816. if (pi) {
  4817. /*
  4818. * Take priority boosted tasks into account. If the new
  4819. * effective priority is unchanged, we just store the new
  4820. * normal parameters and do not touch the scheduler class and
  4821. * the runqueue. This will be done when the task deboost
  4822. * itself.
  4823. */
  4824. new_effective_prio = rt_effective_prio(p, newprio);
  4825. if (new_effective_prio == oldprio)
  4826. queue_flags &= ~DEQUEUE_MOVE;
  4827. }
  4828. queued = task_on_rq_queued(p);
  4829. running = task_current(rq, p);
  4830. if (queued)
  4831. dequeue_task(rq, p, queue_flags);
  4832. if (running)
  4833. put_prev_task(rq, p);
  4834. prev_class = p->sched_class;
  4835. __setscheduler(rq, p, attr, pi);
  4836. if (queued) {
  4837. /*
  4838. * We enqueue to tail when the priority of a task is
  4839. * increased (user space view).
  4840. */
  4841. if (oldprio < p->prio)
  4842. queue_flags |= ENQUEUE_HEAD;
  4843. enqueue_task(rq, p, queue_flags);
  4844. }
  4845. if (running)
  4846. set_curr_task(rq, p);
  4847. check_class_changed(rq, p, prev_class, oldprio);
  4848. /* Avoid rq from going away on us: */
  4849. preempt_disable();
  4850. task_rq_unlock(rq, p, &rf);
  4851. if (pi)
  4852. rt_mutex_adjust_pi(p);
  4853. /* Run balance callbacks after we've adjusted the PI chain: */
  4854. balance_callback(rq);
  4855. preempt_enable();
  4856. return 0;
  4857. }
  4858. static int _sched_setscheduler(struct task_struct *p, int policy,
  4859. const struct sched_param *param, bool check)
  4860. {
  4861. struct sched_attr attr = {
  4862. .sched_policy = policy,
  4863. .sched_priority = param->sched_priority,
  4864. .sched_nice = PRIO_TO_NICE(p->static_prio),
  4865. };
  4866. /* Fixup the legacy SCHED_RESET_ON_FORK hack. */
  4867. if ((policy != SETPARAM_POLICY) && (policy & SCHED_RESET_ON_FORK)) {
  4868. attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
  4869. policy &= ~SCHED_RESET_ON_FORK;
  4870. attr.sched_policy = policy;
  4871. }
  4872. return __sched_setscheduler(p, &attr, check, true);
  4873. }
  4874. /**
  4875. * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
  4876. * @p: the task in question.
  4877. * @policy: new policy.
  4878. * @param: structure containing the new RT priority.
  4879. *
  4880. * Return: 0 on success. An error code otherwise.
  4881. *
  4882. * NOTE that the task may be already dead.
  4883. */
  4884. int sched_setscheduler(struct task_struct *p, int policy,
  4885. const struct sched_param *param)
  4886. {
  4887. return _sched_setscheduler(p, policy, param, true);
  4888. }
  4889. EXPORT_SYMBOL_GPL(sched_setscheduler);
  4890. int sched_setattr(struct task_struct *p, const struct sched_attr *attr)
  4891. {
  4892. return __sched_setscheduler(p, attr, true, true);
  4893. }
  4894. EXPORT_SYMBOL_GPL(sched_setattr);
  4895. /**
  4896. * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
  4897. * @p: the task in question.
  4898. * @policy: new policy.
  4899. * @param: structure containing the new RT priority.
  4900. *
  4901. * Just like sched_setscheduler, only don't bother checking if the
  4902. * current context has permission. For example, this is needed in
  4903. * stop_machine(): we create temporary high priority worker threads,
  4904. * but our caller might not have that capability.
  4905. *
  4906. * Return: 0 on success. An error code otherwise.
  4907. */
  4908. int sched_setscheduler_nocheck(struct task_struct *p, int policy,
  4909. const struct sched_param *param)
  4910. {
  4911. return _sched_setscheduler(p, policy, param, false);
  4912. }
  4913. EXPORT_SYMBOL_GPL(sched_setscheduler_nocheck);
  4914. static int
  4915. do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
  4916. {
  4917. struct sched_param lparam;
  4918. struct task_struct *p;
  4919. int retval;
  4920. if (!param || pid < 0)
  4921. return -EINVAL;
  4922. if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
  4923. return -EFAULT;
  4924. rcu_read_lock();
  4925. retval = -ESRCH;
  4926. p = find_process_by_pid(pid);
  4927. if (p != NULL)
  4928. retval = sched_setscheduler(p, policy, &lparam);
  4929. rcu_read_unlock();
  4930. return retval;
  4931. }
  4932. /*
  4933. * Mimics kernel/events/core.c perf_copy_attr().
  4934. */
  4935. static int sched_copy_attr(struct sched_attr __user *uattr, struct sched_attr *attr)
  4936. {
  4937. u32 size;
  4938. int ret;
  4939. if (!access_ok(VERIFY_WRITE, uattr, SCHED_ATTR_SIZE_VER0))
  4940. return -EFAULT;
  4941. /* Zero the full structure, so that a short copy will be nice: */
  4942. memset(attr, 0, sizeof(*attr));
  4943. ret = get_user(size, &uattr->size);
  4944. if (ret)
  4945. return ret;
  4946. /* Bail out on silly large: */
  4947. if (size > PAGE_SIZE)
  4948. goto err_size;
  4949. /* ABI compatibility quirk: */
  4950. if (!size)
  4951. size = SCHED_ATTR_SIZE_VER0;
  4952. if (size < SCHED_ATTR_SIZE_VER0)
  4953. goto err_size;
  4954. /*
  4955. * If we're handed a bigger struct than we know of,
  4956. * ensure all the unknown bits are 0 - i.e. new
  4957. * user-space does not rely on any kernel feature
  4958. * extensions we dont know about yet.
  4959. */
  4960. if (size > sizeof(*attr)) {
  4961. unsigned char __user *addr;
  4962. unsigned char __user *end;
  4963. unsigned char val;
  4964. addr = (void __user *)uattr + sizeof(*attr);
  4965. end = (void __user *)uattr + size;
  4966. for (; addr < end; addr++) {
  4967. ret = get_user(val, addr);
  4968. if (ret)
  4969. return ret;
  4970. if (val)
  4971. goto err_size;
  4972. }
  4973. size = sizeof(*attr);
  4974. }
  4975. ret = copy_from_user(attr, uattr, size);
  4976. if (ret)
  4977. return -EFAULT;
  4978. /*
  4979. * XXX: Do we want to be lenient like existing syscalls; or do we want
  4980. * to be strict and return an error on out-of-bounds values?
  4981. */
  4982. attr->sched_nice = clamp(attr->sched_nice, MIN_NICE, MAX_NICE);
  4983. return 0;
  4984. err_size:
  4985. put_user(sizeof(*attr), &uattr->size);
  4986. return -E2BIG;
  4987. }
  4988. /**
  4989. * sys_sched_setscheduler - set/change the scheduler policy and RT priority
  4990. * @pid: the pid in question.
  4991. * @policy: new policy.
  4992. * @param: structure containing the new RT priority.
  4993. *
  4994. * Return: 0 on success. An error code otherwise.
  4995. */
  4996. SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy, struct sched_param __user *, param)
  4997. {
  4998. if (policy < 0)
  4999. return -EINVAL;
  5000. return do_sched_setscheduler(pid, policy, param);
  5001. }
  5002. /**
  5003. * sys_sched_setparam - set/change the RT priority of a thread
  5004. * @pid: the pid in question.
  5005. * @param: structure containing the new RT priority.
  5006. *
  5007. * Return: 0 on success. An error code otherwise.
  5008. */
  5009. SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
  5010. {
  5011. return do_sched_setscheduler(pid, SETPARAM_POLICY, param);
  5012. }
  5013. /**
  5014. * sys_sched_setattr - same as above, but with extended sched_attr
  5015. * @pid: the pid in question.
  5016. * @uattr: structure containing the extended parameters.
  5017. * @flags: for future extension.
  5018. */
  5019. SYSCALL_DEFINE3(sched_setattr, pid_t, pid, struct sched_attr __user *, uattr,
  5020. unsigned int, flags)
  5021. {
  5022. struct sched_attr attr;
  5023. struct task_struct *p;
  5024. int retval;
  5025. if (!uattr || pid < 0 || flags)
  5026. return -EINVAL;
  5027. retval = sched_copy_attr(uattr, &attr);
  5028. if (retval)
  5029. return retval;
  5030. if ((int)attr.sched_policy < 0)
  5031. return -EINVAL;
  5032. rcu_read_lock();
  5033. retval = -ESRCH;
  5034. p = find_process_by_pid(pid);
  5035. if (p != NULL)
  5036. retval = sched_setattr(p, &attr);
  5037. rcu_read_unlock();
  5038. return retval;
  5039. }
  5040. /**
  5041. * sys_sched_getscheduler - get the policy (scheduling class) of a thread
  5042. * @pid: the pid in question.
  5043. *
  5044. * Return: On success, the policy of the thread. Otherwise, a negative error
  5045. * code.
  5046. */
  5047. SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
  5048. {
  5049. struct task_struct *p;
  5050. int retval;
  5051. if (pid < 0)
  5052. return -EINVAL;
  5053. retval = -ESRCH;
  5054. rcu_read_lock();
  5055. p = find_process_by_pid(pid);
  5056. if (p) {
  5057. retval = security_task_getscheduler(p);
  5058. if (!retval)
  5059. retval = p->policy
  5060. | (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0);
  5061. }
  5062. rcu_read_unlock();
  5063. return retval;
  5064. }
  5065. /**
  5066. * sys_sched_getparam - get the RT priority of a thread
  5067. * @pid: the pid in question.
  5068. * @param: structure containing the RT priority.
  5069. *
  5070. * Return: On success, 0 and the RT priority is in @param. Otherwise, an error
  5071. * code.
  5072. */
  5073. SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
  5074. {
  5075. struct sched_param lp = { .sched_priority = 0 };
  5076. struct task_struct *p;
  5077. int retval;
  5078. if (!param || pid < 0)
  5079. return -EINVAL;
  5080. rcu_read_lock();
  5081. p = find_process_by_pid(pid);
  5082. retval = -ESRCH;
  5083. if (!p)
  5084. goto out_unlock;
  5085. retval = security_task_getscheduler(p);
  5086. if (retval)
  5087. goto out_unlock;
  5088. if (task_has_rt_policy(p))
  5089. lp.sched_priority = p->rt_priority;
  5090. rcu_read_unlock();
  5091. /*
  5092. * This one might sleep, we cannot do it with a spinlock held ...
  5093. */
  5094. retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
  5095. return retval;
  5096. out_unlock:
  5097. rcu_read_unlock();
  5098. return retval;
  5099. }
  5100. static int sched_read_attr(struct sched_attr __user *uattr,
  5101. struct sched_attr *attr,
  5102. unsigned int usize)
  5103. {
  5104. int ret;
  5105. if (!access_ok(VERIFY_WRITE, uattr, usize))
  5106. return -EFAULT;
  5107. /*
  5108. * If we're handed a smaller struct than we know of,
  5109. * ensure all the unknown bits are 0 - i.e. old
  5110. * user-space does not get uncomplete information.
  5111. */
  5112. if (usize < sizeof(*attr)) {
  5113. unsigned char *addr;
  5114. unsigned char *end;
  5115. addr = (void *)attr + usize;
  5116. end = (void *)attr + sizeof(*attr);
  5117. for (; addr < end; addr++) {
  5118. if (*addr)
  5119. return -EFBIG;
  5120. }
  5121. attr->size = usize;
  5122. }
  5123. ret = copy_to_user(uattr, attr, attr->size);
  5124. if (ret)
  5125. return -EFAULT;
  5126. return 0;
  5127. }
  5128. /**
  5129. * sys_sched_getattr - similar to sched_getparam, but with sched_attr
  5130. * @pid: the pid in question.
  5131. * @uattr: structure containing the extended parameters.
  5132. * @size: sizeof(attr) for fwd/bwd comp.
  5133. * @flags: for future extension.
  5134. */
  5135. SYSCALL_DEFINE4(sched_getattr, pid_t, pid, struct sched_attr __user *, uattr,
  5136. unsigned int, size, unsigned int, flags)
  5137. {
  5138. struct sched_attr attr = {
  5139. .size = sizeof(struct sched_attr),
  5140. };
  5141. struct task_struct *p;
  5142. int retval;
  5143. if (!uattr || pid < 0 || size > PAGE_SIZE ||
  5144. size < SCHED_ATTR_SIZE_VER0 || flags)
  5145. return -EINVAL;
  5146. rcu_read_lock();
  5147. p = find_process_by_pid(pid);
  5148. retval = -ESRCH;
  5149. if (!p)
  5150. goto out_unlock;
  5151. retval = security_task_getscheduler(p);
  5152. if (retval)
  5153. goto out_unlock;
  5154. attr.sched_policy = p->policy;
  5155. if (p->sched_reset_on_fork)
  5156. attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
  5157. if (task_has_dl_policy(p))
  5158. __getparam_dl(p, &attr);
  5159. else if (task_has_rt_policy(p))
  5160. attr.sched_priority = p->rt_priority;
  5161. else
  5162. attr.sched_nice = task_nice(p);
  5163. rcu_read_unlock();
  5164. retval = sched_read_attr(uattr, &attr, size);
  5165. return retval;
  5166. out_unlock:
  5167. rcu_read_unlock();
  5168. return retval;
  5169. }
  5170. long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
  5171. {
  5172. cpumask_var_t cpus_allowed, new_mask;
  5173. struct task_struct *p;
  5174. int retval;
  5175. int dest_cpu;
  5176. cpumask_t allowed_mask;
  5177. rcu_read_lock();
  5178. p = find_process_by_pid(pid);
  5179. if (!p) {
  5180. rcu_read_unlock();
  5181. return -ESRCH;
  5182. }
  5183. /* Prevent p going away */
  5184. get_task_struct(p);
  5185. rcu_read_unlock();
  5186. if (p->flags & PF_NO_SETAFFINITY) {
  5187. retval = -EINVAL;
  5188. goto out_put_task;
  5189. }
  5190. if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
  5191. retval = -ENOMEM;
  5192. goto out_put_task;
  5193. }
  5194. if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
  5195. retval = -ENOMEM;
  5196. goto out_free_cpus_allowed;
  5197. }
  5198. retval = -EPERM;
  5199. if (!check_same_owner(p)) {
  5200. rcu_read_lock();
  5201. if (!ns_capable(__task_cred(p)->user_ns, CAP_SYS_NICE)) {
  5202. rcu_read_unlock();
  5203. goto out_free_new_mask;
  5204. }
  5205. rcu_read_unlock();
  5206. }
  5207. retval = security_task_setscheduler(p);
  5208. if (retval)
  5209. goto out_free_new_mask;
  5210. cpuset_cpus_allowed(p, cpus_allowed);
  5211. cpumask_and(new_mask, in_mask, cpus_allowed);
  5212. /*
  5213. * Since bandwidth control happens on root_domain basis,
  5214. * if admission test is enabled, we only admit -deadline
  5215. * tasks allowed to run on all the CPUs in the task's
  5216. * root_domain.
  5217. */
  5218. #ifdef CONFIG_SMP
  5219. if (task_has_dl_policy(p) && dl_bandwidth_enabled()) {
  5220. rcu_read_lock();
  5221. if (!cpumask_subset(task_rq(p)->rd->span, new_mask)) {
  5222. retval = -EBUSY;
  5223. rcu_read_unlock();
  5224. goto out_free_new_mask;
  5225. }
  5226. rcu_read_unlock();
  5227. }
  5228. #endif
  5229. again:
  5230. cpumask_andnot(&allowed_mask, new_mask, cpu_isolated_mask);
  5231. dest_cpu = cpumask_any_and(cpu_active_mask, &allowed_mask);
  5232. if (dest_cpu < nr_cpu_ids) {
  5233. retval = __set_cpus_allowed_ptr(p, new_mask, true);
  5234. if (!retval) {
  5235. cpuset_cpus_allowed(p, cpus_allowed);
  5236. if (!cpumask_subset(new_mask, cpus_allowed)) {
  5237. /*
  5238. * We must have raced with a concurrent cpuset
  5239. * update. Just reset the cpus_allowed to the
  5240. * cpuset's cpus_allowed
  5241. */
  5242. cpumask_copy(new_mask, cpus_allowed);
  5243. goto again;
  5244. }
  5245. }
  5246. } else {
  5247. retval = -EINVAL;
  5248. }
  5249. out_free_new_mask:
  5250. free_cpumask_var(new_mask);
  5251. out_free_cpus_allowed:
  5252. free_cpumask_var(cpus_allowed);
  5253. out_put_task:
  5254. put_task_struct(p);
  5255. return retval;
  5256. }
  5257. static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
  5258. struct cpumask *new_mask)
  5259. {
  5260. if (len < cpumask_size())
  5261. cpumask_clear(new_mask);
  5262. else if (len > cpumask_size())
  5263. len = cpumask_size();
  5264. return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
  5265. }
  5266. /**
  5267. * sys_sched_setaffinity - set the CPU affinity of a process
  5268. * @pid: pid of the process
  5269. * @len: length in bytes of the bitmask pointed to by user_mask_ptr
  5270. * @user_mask_ptr: user-space pointer to the new CPU mask
  5271. *
  5272. * Return: 0 on success. An error code otherwise.
  5273. */
  5274. SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
  5275. unsigned long __user *, user_mask_ptr)
  5276. {
  5277. cpumask_var_t new_mask;
  5278. int retval;
  5279. if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
  5280. return -ENOMEM;
  5281. retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
  5282. if (retval == 0)
  5283. retval = sched_setaffinity(pid, new_mask);
  5284. free_cpumask_var(new_mask);
  5285. return retval;
  5286. }
  5287. long sched_getaffinity(pid_t pid, struct cpumask *mask)
  5288. {
  5289. struct task_struct *p;
  5290. unsigned long flags;
  5291. int retval;
  5292. rcu_read_lock();
  5293. retval = -ESRCH;
  5294. p = find_process_by_pid(pid);
  5295. if (!p)
  5296. goto out_unlock;
  5297. retval = security_task_getscheduler(p);
  5298. if (retval)
  5299. goto out_unlock;
  5300. raw_spin_lock_irqsave(&p->pi_lock, flags);
  5301. cpumask_and(mask, &p->cpus_allowed, cpu_active_mask);
  5302. raw_spin_unlock_irqrestore(&p->pi_lock, flags);
  5303. out_unlock:
  5304. rcu_read_unlock();
  5305. return retval;
  5306. }
  5307. /**
  5308. * sys_sched_getaffinity - get the CPU affinity of a process
  5309. * @pid: pid of the process
  5310. * @len: length in bytes of the bitmask pointed to by user_mask_ptr
  5311. * @user_mask_ptr: user-space pointer to hold the current CPU mask
  5312. *
  5313. * Return: size of CPU mask copied to user_mask_ptr on success. An
  5314. * error code otherwise.
  5315. */
  5316. SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
  5317. unsigned long __user *, user_mask_ptr)
  5318. {
  5319. int ret;
  5320. cpumask_var_t mask;
  5321. if ((len * BITS_PER_BYTE) < nr_cpu_ids)
  5322. return -EINVAL;
  5323. if (len & (sizeof(unsigned long)-1))
  5324. return -EINVAL;
  5325. if (!alloc_cpumask_var(&mask, GFP_KERNEL))
  5326. return -ENOMEM;
  5327. ret = sched_getaffinity(pid, mask);
  5328. if (ret == 0) {
  5329. size_t retlen = min_t(size_t, len, cpumask_size());
  5330. if (copy_to_user(user_mask_ptr, mask, retlen))
  5331. ret = -EFAULT;
  5332. else
  5333. ret = retlen;
  5334. }
  5335. free_cpumask_var(mask);
  5336. return ret;
  5337. }
  5338. /**
  5339. * sys_sched_yield - yield the current processor to other threads.
  5340. *
  5341. * This function yields the current CPU to other tasks. If there are no
  5342. * other threads running on this CPU then this function will return.
  5343. *
  5344. * Return: 0.
  5345. */
  5346. SYSCALL_DEFINE0(sched_yield)
  5347. {
  5348. struct rq_flags rf;
  5349. struct rq *rq;
  5350. rq = this_rq_lock_irq(&rf);
  5351. schedstat_inc(rq->yld_count);
  5352. current->sched_class->yield_task(rq);
  5353. preempt_disable();
  5354. rq_unlock_irq(rq, &rf);
  5355. sched_preempt_enable_no_resched();
  5356. schedule();
  5357. return 0;
  5358. }
  5359. #ifndef CONFIG_PREEMPT
  5360. int __sched _cond_resched(void)
  5361. {
  5362. if (should_resched(0)) {
  5363. preempt_schedule_common();
  5364. return 1;
  5365. }
  5366. return 0;
  5367. }
  5368. EXPORT_SYMBOL(_cond_resched);
  5369. #endif
  5370. /*
  5371. * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
  5372. * call schedule, and on return reacquire the lock.
  5373. *
  5374. * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
  5375. * operations here to prevent schedule() from being called twice (once via
  5376. * spin_unlock(), once by hand).
  5377. */
  5378. int __cond_resched_lock(spinlock_t *lock)
  5379. {
  5380. int resched = should_resched(PREEMPT_LOCK_OFFSET);
  5381. int ret = 0;
  5382. lockdep_assert_held(lock);
  5383. if (spin_needbreak(lock) || resched) {
  5384. spin_unlock(lock);
  5385. if (resched)
  5386. preempt_schedule_common();
  5387. else
  5388. cpu_relax();
  5389. ret = 1;
  5390. spin_lock(lock);
  5391. }
  5392. return ret;
  5393. }
  5394. EXPORT_SYMBOL(__cond_resched_lock);
  5395. int __sched __cond_resched_softirq(void)
  5396. {
  5397. BUG_ON(!in_softirq());
  5398. if (should_resched(SOFTIRQ_DISABLE_OFFSET)) {
  5399. local_bh_enable();
  5400. preempt_schedule_common();
  5401. local_bh_disable();
  5402. return 1;
  5403. }
  5404. return 0;
  5405. }
  5406. EXPORT_SYMBOL(__cond_resched_softirq);
  5407. /**
  5408. * yield - yield the current processor to other threads.
  5409. *
  5410. * Do not ever use this function, there's a 99% chance you're doing it wrong.
  5411. *
  5412. * The scheduler is at all times free to pick the calling task as the most
  5413. * eligible task to run, if removing the yield() call from your code breaks
  5414. * it, its already broken.
  5415. *
  5416. * Typical broken usage is:
  5417. *
  5418. * while (!event)
  5419. * yield();
  5420. *
  5421. * where one assumes that yield() will let 'the other' process run that will
  5422. * make event true. If the current task is a SCHED_FIFO task that will never
  5423. * happen. Never use yield() as a progress guarantee!!
  5424. *
  5425. * If you want to use yield() to wait for something, use wait_event().
  5426. * If you want to use yield() to be 'nice' for others, use cond_resched().
  5427. * If you still want to use yield(), do not!
  5428. */
  5429. void __sched yield(void)
  5430. {
  5431. set_current_state(TASK_RUNNING);
  5432. sys_sched_yield();
  5433. }
  5434. EXPORT_SYMBOL(yield);
  5435. /**
  5436. * yield_to - yield the current processor to another thread in
  5437. * your thread group, or accelerate that thread toward the
  5438. * processor it's on.
  5439. * @p: target task
  5440. * @preempt: whether task preemption is allowed or not
  5441. *
  5442. * It's the caller's job to ensure that the target task struct
  5443. * can't go away on us before we can do any checks.
  5444. *
  5445. * Return:
  5446. * true (>0) if we indeed boosted the target task.
  5447. * false (0) if we failed to boost the target.
  5448. * -ESRCH if there's no task to yield to.
  5449. */
  5450. int __sched yield_to(struct task_struct *p, bool preempt)
  5451. {
  5452. struct task_struct *curr = current;
  5453. struct rq *rq, *p_rq;
  5454. unsigned long flags;
  5455. int yielded = 0;
  5456. local_irq_save(flags);
  5457. rq = this_rq();
  5458. again:
  5459. p_rq = task_rq(p);
  5460. /*
  5461. * If we're the only runnable task on the rq and target rq also
  5462. * has only one task, there's absolutely no point in yielding.
  5463. */
  5464. if (rq->nr_running == 1 && p_rq->nr_running == 1) {
  5465. yielded = -ESRCH;
  5466. goto out_irq;
  5467. }
  5468. double_rq_lock(rq, p_rq);
  5469. if (task_rq(p) != p_rq) {
  5470. double_rq_unlock(rq, p_rq);
  5471. goto again;
  5472. }
  5473. if (!curr->sched_class->yield_to_task)
  5474. goto out_unlock;
  5475. if (curr->sched_class != p->sched_class)
  5476. goto out_unlock;
  5477. if (task_running(p_rq, p) || p->state)
  5478. goto out_unlock;
  5479. yielded = curr->sched_class->yield_to_task(rq, p, preempt);
  5480. if (yielded) {
  5481. schedstat_inc(rq->yld_count);
  5482. /*
  5483. * Make p's CPU reschedule; pick_next_entity takes care of
  5484. * fairness.
  5485. */
  5486. if (preempt && rq != p_rq)
  5487. resched_curr(p_rq);
  5488. }
  5489. out_unlock:
  5490. double_rq_unlock(rq, p_rq);
  5491. out_irq:
  5492. local_irq_restore(flags);
  5493. if (yielded > 0)
  5494. schedule();
  5495. return yielded;
  5496. }
  5497. EXPORT_SYMBOL_GPL(yield_to);
  5498. int io_schedule_prepare(void)
  5499. {
  5500. int old_iowait = current->in_iowait;
  5501. current->in_iowait = 1;
  5502. blk_schedule_flush_plug(current);
  5503. return old_iowait;
  5504. }
  5505. void io_schedule_finish(int token)
  5506. {
  5507. current->in_iowait = token;
  5508. }
  5509. /*
  5510. * This task is about to go to sleep on IO. Increment rq->nr_iowait so
  5511. * that process accounting knows that this is a task in IO wait state.
  5512. */
  5513. long __sched io_schedule_timeout(long timeout)
  5514. {
  5515. int token;
  5516. long ret;
  5517. token = io_schedule_prepare();
  5518. ret = schedule_timeout(timeout);
  5519. io_schedule_finish(token);
  5520. return ret;
  5521. }
  5522. EXPORT_SYMBOL(io_schedule_timeout);
  5523. void __sched io_schedule(void)
  5524. {
  5525. int token;
  5526. token = io_schedule_prepare();
  5527. schedule();
  5528. io_schedule_finish(token);
  5529. }
  5530. EXPORT_SYMBOL(io_schedule);
  5531. /**
  5532. * sys_sched_get_priority_max - return maximum RT priority.
  5533. * @policy: scheduling class.
  5534. *
  5535. * Return: On success, this syscall returns the maximum
  5536. * rt_priority that can be used by a given scheduling class.
  5537. * On failure, a negative error code is returned.
  5538. */
  5539. SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
  5540. {
  5541. int ret = -EINVAL;
  5542. switch (policy) {
  5543. case SCHED_FIFO:
  5544. case SCHED_RR:
  5545. ret = MAX_USER_RT_PRIO-1;
  5546. break;
  5547. case SCHED_DEADLINE:
  5548. case SCHED_NORMAL:
  5549. case SCHED_BATCH:
  5550. case SCHED_IDLE:
  5551. ret = 0;
  5552. break;
  5553. }
  5554. return ret;
  5555. }
  5556. /**
  5557. * sys_sched_get_priority_min - return minimum RT priority.
  5558. * @policy: scheduling class.
  5559. *
  5560. * Return: On success, this syscall returns the minimum
  5561. * rt_priority that can be used by a given scheduling class.
  5562. * On failure, a negative error code is returned.
  5563. */
  5564. SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
  5565. {
  5566. int ret = -EINVAL;
  5567. switch (policy) {
  5568. case SCHED_FIFO:
  5569. case SCHED_RR:
  5570. ret = 1;
  5571. break;
  5572. case SCHED_DEADLINE:
  5573. case SCHED_NORMAL:
  5574. case SCHED_BATCH:
  5575. case SCHED_IDLE:
  5576. ret = 0;
  5577. }
  5578. return ret;
  5579. }
  5580. /**
  5581. * sys_sched_rr_get_interval - return the default timeslice of a process.
  5582. * @pid: pid of the process.
  5583. * @interval: userspace pointer to the timeslice value.
  5584. *
  5585. * this syscall writes the default timeslice value of a given process
  5586. * into the user-space timespec buffer. A value of '0' means infinity.
  5587. *
  5588. * Return: On success, 0 and the timeslice is in @interval. Otherwise,
  5589. * an error code.
  5590. */
  5591. SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
  5592. struct timespec __user *, interval)
  5593. {
  5594. struct task_struct *p;
  5595. unsigned int time_slice;
  5596. struct rq_flags rf;
  5597. struct timespec t;
  5598. struct rq *rq;
  5599. int retval;
  5600. if (pid < 0)
  5601. return -EINVAL;
  5602. retval = -ESRCH;
  5603. rcu_read_lock();
  5604. p = find_process_by_pid(pid);
  5605. if (!p)
  5606. goto out_unlock;
  5607. retval = security_task_getscheduler(p);
  5608. if (retval)
  5609. goto out_unlock;
  5610. rq = task_rq_lock(p, &rf);
  5611. time_slice = 0;
  5612. if (p->sched_class->get_rr_interval)
  5613. time_slice = p->sched_class->get_rr_interval(rq, p);
  5614. task_rq_unlock(rq, p, &rf);
  5615. rcu_read_unlock();
  5616. jiffies_to_timespec(time_slice, &t);
  5617. retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
  5618. return retval;
  5619. out_unlock:
  5620. rcu_read_unlock();
  5621. return retval;
  5622. }
  5623. void sched_show_task(struct task_struct *p)
  5624. {
  5625. unsigned long free = 0;
  5626. int ppid;
  5627. if (!try_get_task_stack(p))
  5628. return;
  5629. printk(KERN_INFO "%-15.15s %c", p->comm, task_state_to_char(p));
  5630. if (p->state == TASK_RUNNING)
  5631. printk(KERN_CONT " running task ");
  5632. #ifdef CONFIG_DEBUG_STACK_USAGE
  5633. free = stack_not_used(p);
  5634. #endif
  5635. ppid = 0;
  5636. rcu_read_lock();
  5637. if (pid_alive(p))
  5638. ppid = task_pid_nr(rcu_dereference(p->real_parent));
  5639. rcu_read_unlock();
  5640. printk(KERN_CONT "%5lu %5d %6d 0x%08lx\n", free,
  5641. task_pid_nr(p), ppid,
  5642. (unsigned long)task_thread_info(p)->flags);
  5643. print_worker_info(KERN_INFO, p);
  5644. show_stack(p, NULL);
  5645. put_task_stack(p);
  5646. }
  5647. static inline bool
  5648. state_filter_match(unsigned long state_filter, struct task_struct *p)
  5649. {
  5650. /* no filter, everything matches */
  5651. if (!state_filter)
  5652. return true;
  5653. /* filter, but doesn't match */
  5654. if (!(p->state & state_filter))
  5655. return false;
  5656. /*
  5657. * When looking for TASK_UNINTERRUPTIBLE skip TASK_IDLE (allows
  5658. * TASK_KILLABLE).
  5659. */
  5660. if (state_filter == TASK_UNINTERRUPTIBLE && p->state == TASK_IDLE)
  5661. return false;
  5662. return true;
  5663. }
  5664. void show_state_filter(unsigned long state_filter)
  5665. {
  5666. struct task_struct *g, *p;
  5667. #if BITS_PER_LONG == 32
  5668. printk(KERN_INFO
  5669. " task PC stack pid father\n");
  5670. #else
  5671. printk(KERN_INFO
  5672. " task PC stack pid father\n");
  5673. #endif
  5674. rcu_read_lock();
  5675. for_each_process_thread(g, p) {
  5676. /*
  5677. * reset the NMI-timeout, listing all files on a slow
  5678. * console might take a lot of time:
  5679. * Also, reset softlockup watchdogs on all CPUs, because
  5680. * another CPU might be blocked waiting for us to process
  5681. * an IPI.
  5682. */
  5683. touch_nmi_watchdog();
  5684. touch_all_softlockup_watchdogs();
  5685. if (state_filter_match(state_filter, p))
  5686. sched_show_task(p);
  5687. }
  5688. #ifdef CONFIG_SCHED_DEBUG
  5689. if (!state_filter)
  5690. sysrq_sched_debug_show();
  5691. #endif
  5692. rcu_read_unlock();
  5693. /*
  5694. * Only show locks if all tasks are dumped:
  5695. */
  5696. if (!state_filter)
  5697. debug_show_all_locks();
  5698. }
  5699. /**
  5700. * init_idle - set up an idle thread for a given CPU
  5701. * @idle: task in question
  5702. * @cpu: CPU the idle task belongs to
  5703. *
  5704. * NOTE: this function does not set the idle thread's NEED_RESCHED
  5705. * flag, to make booting more robust.
  5706. */
  5707. void init_idle(struct task_struct *idle, int cpu)
  5708. {
  5709. struct rq *rq = cpu_rq(cpu);
  5710. unsigned long flags;
  5711. __sched_fork(0, idle);
  5712. raw_spin_lock_irqsave(&idle->pi_lock, flags);
  5713. raw_spin_lock(&rq->lock);
  5714. idle->state = TASK_RUNNING;
  5715. idle->se.exec_start = sched_clock();
  5716. idle->flags |= PF_IDLE;
  5717. kasan_unpoison_task_stack(idle);
  5718. #ifdef CONFIG_SMP
  5719. /*
  5720. * Its possible that init_idle() gets called multiple times on a task,
  5721. * in that case do_set_cpus_allowed() will not do the right thing.
  5722. *
  5723. * And since this is boot we can forgo the serialization.
  5724. */
  5725. set_cpus_allowed_common(idle, cpumask_of(cpu));
  5726. #endif
  5727. /*
  5728. * We're having a chicken and egg problem, even though we are
  5729. * holding rq->lock, the CPU isn't yet set to this CPU so the
  5730. * lockdep check in task_group() will fail.
  5731. *
  5732. * Similar case to sched_fork(). / Alternatively we could
  5733. * use task_rq_lock() here and obtain the other rq->lock.
  5734. *
  5735. * Silence PROVE_RCU
  5736. */
  5737. rcu_read_lock();
  5738. __set_task_cpu(idle, cpu);
  5739. rcu_read_unlock();
  5740. rq->curr = rq->idle = idle;
  5741. idle->on_rq = TASK_ON_RQ_QUEUED;
  5742. #ifdef CONFIG_SMP
  5743. idle->on_cpu = 1;
  5744. #endif
  5745. raw_spin_unlock(&rq->lock);
  5746. raw_spin_unlock_irqrestore(&idle->pi_lock, flags);
  5747. /* Set the preempt count _outside_ the spinlocks! */
  5748. init_idle_preempt_count(idle, cpu);
  5749. /*
  5750. * The idle tasks have their own, simple scheduling class:
  5751. */
  5752. idle->sched_class = &idle_sched_class;
  5753. ftrace_graph_init_idle_task(idle, cpu);
  5754. vtime_init_idle(idle, cpu);
  5755. #ifdef CONFIG_SMP
  5756. sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu);
  5757. #endif
  5758. }
  5759. #ifdef CONFIG_SMP
  5760. int cpuset_cpumask_can_shrink(const struct cpumask *cur,
  5761. const struct cpumask *trial)
  5762. {
  5763. int ret = 1;
  5764. if (!cpumask_weight(cur))
  5765. return ret;
  5766. ret = dl_cpuset_cpumask_can_shrink(cur, trial);
  5767. return ret;
  5768. }
  5769. int task_can_attach(struct task_struct *p,
  5770. const struct cpumask *cs_cpus_allowed)
  5771. {
  5772. int ret = 0;
  5773. /*
  5774. * Kthreads which disallow setaffinity shouldn't be moved
  5775. * to a new cpuset; we don't want to change their CPU
  5776. * affinity and isolating such threads by their set of
  5777. * allowed nodes is unnecessary. Thus, cpusets are not
  5778. * applicable for such threads. This prevents checking for
  5779. * success of set_cpus_allowed_ptr() on all attached tasks
  5780. * before cpus_allowed may be changed.
  5781. */
  5782. if (p->flags & PF_NO_SETAFFINITY) {
  5783. ret = -EINVAL;
  5784. goto out;
  5785. }
  5786. if (dl_task(p) && !cpumask_intersects(task_rq(p)->rd->span,
  5787. cs_cpus_allowed))
  5788. ret = dl_task_can_attach(p, cs_cpus_allowed);
  5789. out:
  5790. return ret;
  5791. }
  5792. bool sched_smp_initialized __read_mostly;
  5793. #ifdef CONFIG_NUMA_BALANCING
  5794. /* Migrate current task p to target_cpu */
  5795. int migrate_task_to(struct task_struct *p, int target_cpu)
  5796. {
  5797. struct migration_arg arg = { p, target_cpu };
  5798. int curr_cpu = task_cpu(p);
  5799. if (curr_cpu == target_cpu)
  5800. return 0;
  5801. if (!cpumask_test_cpu(target_cpu, &p->cpus_allowed))
  5802. return -EINVAL;
  5803. /* TODO: This is not properly updating schedstats */
  5804. trace_sched_move_numa(p, curr_cpu, target_cpu);
  5805. return stop_one_cpu(curr_cpu, migration_cpu_stop, &arg);
  5806. }
  5807. /*
  5808. * Requeue a task on a given node and accurately track the number of NUMA
  5809. * tasks on the runqueues
  5810. */
  5811. void sched_setnuma(struct task_struct *p, int nid)
  5812. {
  5813. bool queued, running;
  5814. struct rq_flags rf;
  5815. struct rq *rq;
  5816. rq = task_rq_lock(p, &rf);
  5817. queued = task_on_rq_queued(p);
  5818. running = task_current(rq, p);
  5819. if (queued)
  5820. dequeue_task(rq, p, DEQUEUE_SAVE);
  5821. if (running)
  5822. put_prev_task(rq, p);
  5823. p->numa_preferred_nid = nid;
  5824. if (queued)
  5825. enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
  5826. if (running)
  5827. set_curr_task(rq, p);
  5828. task_rq_unlock(rq, p, &rf);
  5829. }
  5830. #endif /* CONFIG_NUMA_BALANCING */
  5831. #ifdef CONFIG_HOTPLUG_CPU
  5832. /*
  5833. * Ensure that the idle task is using init_mm right before its CPU goes
  5834. * offline.
  5835. */
  5836. void idle_task_exit(void)
  5837. {
  5838. struct mm_struct *mm = current->active_mm;
  5839. BUG_ON(cpu_online(smp_processor_id()));
  5840. if (mm != &init_mm) {
  5841. switch_mm(mm, &init_mm, current);
  5842. finish_arch_post_lock_switch();
  5843. }
  5844. mmdrop(mm);
  5845. }
  5846. /*
  5847. * Since this CPU is going 'away' for a while, fold any nr_active delta
  5848. * we might have. Assumes we're called after migrate_tasks() so that the
  5849. * nr_active count is stable. We need to take the teardown thread which
  5850. * is calling this into account, so we hand in adjust = 1 to the load
  5851. * calculation.
  5852. *
  5853. * Also see the comment "Global load-average calculations".
  5854. */
  5855. static void calc_load_migrate(struct rq *rq)
  5856. {
  5857. long delta = calc_load_fold_active(rq, 1);
  5858. if (delta)
  5859. atomic_long_add(delta, &calc_load_tasks);
  5860. }
  5861. static void put_prev_task_fake(struct rq *rq, struct task_struct *prev)
  5862. {
  5863. }
  5864. static const struct sched_class fake_sched_class = {
  5865. .put_prev_task = put_prev_task_fake,
  5866. };
  5867. static struct task_struct fake_task = {
  5868. /*
  5869. * Avoid pull_{rt,dl}_task()
  5870. */
  5871. .prio = MAX_PRIO + 1,
  5872. .sched_class = &fake_sched_class,
  5873. };
  5874. /*
  5875. * Remove a task from the runqueue and pretend that it's migrating. This
  5876. * should prevent migrations for the detached task and disallow further
  5877. * changes to tsk_cpus_allowed.
  5878. */
  5879. static void
  5880. detach_one_task(struct task_struct *p, struct rq *rq, struct list_head *tasks)
  5881. {
  5882. lockdep_assert_held(&rq->lock);
  5883. p->on_rq = TASK_ON_RQ_MIGRATING;
  5884. deactivate_task(rq, p, 0);
  5885. list_add(&p->se.group_node, tasks);
  5886. }
  5887. static void attach_tasks(struct list_head *tasks, struct rq *rq)
  5888. {
  5889. struct task_struct *p;
  5890. lockdep_assert_held(&rq->lock);
  5891. while (!list_empty(tasks)) {
  5892. p = list_first_entry(tasks, struct task_struct, se.group_node);
  5893. list_del_init(&p->se.group_node);
  5894. WARN_ON(task_rq(p) != rq);
  5895. activate_task(rq, p, 0);
  5896. p->on_rq = TASK_ON_RQ_QUEUED;
  5897. }
  5898. }
  5899. /*
  5900. *Migrate all tasks (not pinned if pinned argument say so) from the rq,
  5901. *sleeping tasks will be migrated by try_to_wake_up()->select_task_rq().
  5902. * Called with rq->lock held even though we'er in stop_machine() and
  5903. * there's no concurrency possible, we hold the required locks anyway
  5904. * because of lock validation efforts.
  5905. */
  5906. static void migrate_tasks(struct rq *dead_rq, struct rq_flags *rf,
  5907. bool migrate_pinned_tasks)
  5908. {
  5909. struct rq *rq = dead_rq;
  5910. struct task_struct *next, *stop = rq->stop;
  5911. struct rq_flags orf = *rf;
  5912. int dest_cpu;
  5913. LIST_HEAD(tasks);
  5914. unsigned int num_pinned_kthreads = 1; /* this thread */
  5915. cpumask_t avail_cpus;
  5916. cpumask_andnot(&avail_cpus, cpu_online_mask, cpu_isolated_mask);
  5917. /*
  5918. * Fudge the rq selection such that the below task selection loop
  5919. * doesn't get stuck on the currently eligible stop task.
  5920. *
  5921. * We're currently inside stop_machine() and the rq is either stuck
  5922. * in the stop_machine_cpu_stop() loop, or we're executing this code,
  5923. * either way we should never end up calling schedule() until we're
  5924. * done here.
  5925. */
  5926. rq->stop = NULL;
  5927. /*
  5928. * put_prev_task() and pick_next_task() sched
  5929. * class method both need to have an up-to-date
  5930. * value of rq->clock[_task]
  5931. */
  5932. update_rq_clock(rq);
  5933. unthrottle_offline_rt_rqs(rq);
  5934. for (;;) {
  5935. /*
  5936. * There's this thread running, bail when that's the only
  5937. * remaining thread:
  5938. */
  5939. if (rq->nr_running == 1)
  5940. break;
  5941. /*
  5942. * pick_next_task() assumes pinned rq->lock:
  5943. */
  5944. next = pick_next_task(rq, &fake_task, rf);
  5945. BUG_ON(!next);
  5946. put_prev_task(rq, next);
  5947. if (!migrate_pinned_tasks && next->flags & PF_KTHREAD &&
  5948. !cpumask_intersects(&avail_cpus, &next->cpus_allowed)) {
  5949. detach_one_task(next, rq, &tasks);
  5950. num_pinned_kthreads += 1;
  5951. continue;
  5952. }
  5953. /*
  5954. * Rules for changing task_struct::cpus_allowed are holding
  5955. * both pi_lock and rq->lock, such that holding either
  5956. * stabilizes the mask.
  5957. *
  5958. * Drop rq->lock is not quite as disastrous as it usually is
  5959. * because !cpu_active at this point, which means load-balance
  5960. * will not interfere. Also, stop-machine.
  5961. */
  5962. rq_unlock(rq, rf);
  5963. raw_spin_lock(&next->pi_lock);
  5964. rq_relock(rq, rf);
  5965. /*
  5966. * Since we're inside stop-machine, _nothing_ should have
  5967. * changed the task, WARN if weird stuff happened, because in
  5968. * that case the above rq->lock drop is a fail too.
  5969. * However, during cpu isolation the load balancer might have
  5970. * interferred since we don't stop all CPUs. Ignore warning for
  5971. * this case.
  5972. */
  5973. if (task_rq(next) != rq || !task_on_rq_queued(next)) {
  5974. WARN_ON(migrate_pinned_tasks);
  5975. raw_spin_unlock(&next->pi_lock);
  5976. continue;
  5977. }
  5978. /* Find suitable destination for @next, with force if needed. */
  5979. dest_cpu = select_fallback_rq(dead_rq->cpu, next, false);
  5980. rq = __migrate_task(rq, rf, next, dest_cpu);
  5981. if (rq != dead_rq) {
  5982. rq_unlock(rq, rf);
  5983. rq = dead_rq;
  5984. *rf = orf;
  5985. rq_relock(rq, rf);
  5986. }
  5987. raw_spin_unlock(&next->pi_lock);
  5988. }
  5989. rq->stop = stop;
  5990. if (num_pinned_kthreads > 1)
  5991. attach_tasks(&tasks, rq);
  5992. }
  5993. int do_isolation_work_cpu_stop(void *data)
  5994. {
  5995. unsigned int cpu = smp_processor_id();
  5996. struct rq *rq = cpu_rq(cpu);
  5997. struct rq_flags rf;
  5998. local_irq_disable();
  5999. sched_ttwu_pending();
  6000. rq_lock_irqsave(rq, &rf);
  6001. /*
  6002. * Temporarily mark the rq as offline. This will allow us to
  6003. * move tasks off the CPU.
  6004. */
  6005. if (rq->rd) {
  6006. WARN_ON(!cpumask_test_cpu(cpu, rq->rd->span));
  6007. set_rq_offline(rq);
  6008. }
  6009. migrate_tasks(rq, &rf, false);
  6010. if (rq->rd)
  6011. set_rq_online(rq);
  6012. rq_unlock_irqrestore(rq, &rf);
  6013. /*
  6014. * We might have been in tickless state. Clear NOHZ flags to avoid
  6015. * us being kicked for helping out with balancing
  6016. */
  6017. nohz_balance_clear_nohz_mask(cpu);
  6018. local_irq_enable();
  6019. return 0;
  6020. }
  6021. static void sched_update_group_capacities(int cpu)
  6022. {
  6023. struct sched_domain *sd;
  6024. mutex_lock(&sched_domains_mutex);
  6025. rcu_read_lock();
  6026. for_each_domain(cpu, sd) {
  6027. int balance_cpu = group_balance_cpu(sd->groups);
  6028. init_sched_groups_capacity(cpu, sd);
  6029. /*
  6030. * Need to ensure this is also called with balancing
  6031. * cpu.
  6032. */
  6033. if (cpu != balance_cpu)
  6034. init_sched_groups_capacity(balance_cpu, sd);
  6035. }
  6036. rcu_read_unlock();
  6037. mutex_unlock(&sched_domains_mutex);
  6038. }
  6039. static unsigned int cpu_isolation_vote[NR_CPUS];
  6040. int sched_isolate_count(const cpumask_t *mask, bool include_offline)
  6041. {
  6042. cpumask_t count_mask = CPU_MASK_NONE;
  6043. if (include_offline) {
  6044. cpumask_complement(&count_mask, cpu_online_mask);
  6045. cpumask_or(&count_mask, &count_mask, cpu_isolated_mask);
  6046. cpumask_and(&count_mask, &count_mask, mask);
  6047. } else {
  6048. cpumask_and(&count_mask, mask, cpu_isolated_mask);
  6049. }
  6050. return cpumask_weight(&count_mask);
  6051. }
  6052. void notify_atf_cpu_isolated_status(int cpu)
  6053. {
  6054. #ifdef CONFIG_MEDIATEK_SOLUTION
  6055. unsigned long cur_mask = cpu_isolated_mask->bits[0];
  6056. struct arm_smccc_res res;
  6057. arm_smccc_smc(MTK_SIP_GIC_CONTROL, GIC_ISO_CODE, cur_mask,
  6058. 0, 0, 0, 0, 0, &res);
  6059. #endif
  6060. }
  6061. /*
  6062. * 1) CPU is isolated and cpu is offlined:
  6063. * Unisolate the core.
  6064. * 2) CPU is not isolated and CPU is offlined:
  6065. * No action taken.
  6066. * 3) CPU is offline and request to isolate
  6067. * Request ignored.
  6068. * 4) CPU is offline and isolated:
  6069. * Not a possible state.
  6070. * 5) CPU is online and request to isolate
  6071. * Normal case: Isolate the CPU
  6072. * 6) CPU is not isolated and comes back online
  6073. * Nothing to do
  6074. *
  6075. * Note: The client calling sched_isolate_cpu() is repsonsible for ONLY
  6076. * calling sched_deisolate_cpu() on a CPU that the client previously isolated.
  6077. * Client is also responsible for deisolating when a core goes offline
  6078. * (after CPU is marked offline).
  6079. */
  6080. int _sched_isolate_cpu(int cpu)
  6081. {
  6082. struct rq *rq = cpu_rq(cpu);
  6083. cpumask_t avail_cpus;
  6084. int ret_code = 0;
  6085. u64 start_time = 0;
  6086. if (trace_sched_isolate_enabled())
  6087. start_time = sched_clock();
  6088. cpu_maps_update_begin();
  6089. cpumask_andnot(&avail_cpus, cpu_online_mask, cpu_isolated_mask);
  6090. /* We cannot isolate ALL cpus in the system */
  6091. if (cpumask_weight(&avail_cpus) == 1) {
  6092. ret_code = -EINVAL;
  6093. goto out;
  6094. }
  6095. if (!cpu_online(cpu)) {
  6096. ret_code = -EINVAL;
  6097. goto out;
  6098. }
  6099. if (++cpu_isolation_vote[cpu] > 1)
  6100. goto out;
  6101. set_cpu_isolated(cpu, true);
  6102. mcdi_cpu_iso_mask(cpu_isolated_mask->bits[0]);
  6103. cpumask_clear_cpu(cpu, &avail_cpus);
  6104. notify_atf_cpu_isolated_status(cpu);
  6105. /* Migrate timers */
  6106. smp_call_function_any(&avail_cpus, hrtimer_quiesce_cpu, &cpu, 1);
  6107. smp_call_function_any(&avail_cpus, timer_quiesce_cpu, &cpu, 1);
  6108. stop_cpus(cpumask_of(cpu), do_isolation_work_cpu_stop, 0);
  6109. calc_load_migrate(rq);
  6110. update_max_interval();
  6111. sched_update_group_capacities(cpu);
  6112. out:
  6113. cpu_maps_update_done();
  6114. trace_sched_isolate(cpu, cpumask_bits(cpu_isolated_mask)[0],
  6115. start_time, 1);
  6116. printk_deferred("%s: prio=%d, cpu=%d, isolation_cpus=0x%lx\n",
  6117. __func__, iso_prio, cpu, cpu_isolated_mask->bits[0]);
  6118. return ret_code;
  6119. }
  6120. /*
  6121. * Note: The client calling sched_isolate_cpu() is repsonsible for ONLY
  6122. * calling sched_deisolate_cpu() on a CPU that the client previously isolated.
  6123. * Client is also responsible for deisolating when a core goes offline
  6124. * (after CPU is marked offline).
  6125. */
  6126. int __sched_deisolate_cpu_unlocked(int cpu)
  6127. {
  6128. int ret_code = 0;
  6129. struct rq *rq = cpu_rq(cpu);
  6130. u64 start_time = 0;
  6131. if (trace_sched_isolate_enabled())
  6132. start_time = sched_clock();
  6133. if (!cpu_isolation_vote[cpu]) {
  6134. ret_code = -EINVAL;
  6135. goto out;
  6136. }
  6137. if (--cpu_isolation_vote[cpu])
  6138. goto out;
  6139. if (cpu_online(cpu)) {
  6140. unsigned long flags;
  6141. raw_spin_lock_irqsave(&rq->lock, flags);
  6142. rq->age_stamp = sched_clock_cpu(cpu);
  6143. raw_spin_unlock_irqrestore(&rq->lock, flags);
  6144. }
  6145. set_cpu_isolated(cpu, false);
  6146. mcdi_cpu_iso_mask(cpu_isolated_mask->bits[0]);
  6147. notify_atf_cpu_isolated_status(cpu);
  6148. update_max_interval();
  6149. sched_update_group_capacities(cpu);
  6150. if (cpu_online(cpu)) {
  6151. /* Kick CPU to immediately do load balancing */
  6152. if (!test_and_set_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu)))
  6153. smp_send_reschedule(cpu);
  6154. }
  6155. out:
  6156. trace_sched_isolate(cpu, cpumask_bits(cpu_isolated_mask)[0],
  6157. start_time, 0);
  6158. printk_deferred("%s: prio=%d, cpu=%d, isolation_cpus=0x%lx\n",
  6159. __func__, iso_prio, cpu, cpu_isolated_mask->bits[0]);
  6160. return ret_code;
  6161. }
  6162. int _sched_deisolate_cpu(int cpu)
  6163. {
  6164. int ret_code;
  6165. cpu_maps_update_begin();
  6166. ret_code = __sched_deisolate_cpu_unlocked(cpu);
  6167. cpu_maps_update_done();
  6168. return ret_code;
  6169. }
  6170. void iso_cpumask_init(void)
  6171. {
  6172. cpumask_copy(&cpu_all_masks, cpu_possible_mask);
  6173. cpumask_setall(&available_cpus);
  6174. }
  6175. /* Use available_cpus to determine cpu isolated or deisolated */
  6176. int set_cpu_isolation(enum iso_prio_t prio, struct cpumask *cpumask_ptr)
  6177. {
  6178. struct cpumask iso_mask;
  6179. struct cpumask deiso_mask;
  6180. int i = 0;
  6181. if (prio > iso_prio)
  6182. return -1;
  6183. if (!cpumask_ptr)
  6184. return -1;
  6185. might_sleep();
  6186. mutex_lock(&sched_isolation_mutex);
  6187. iso_prio = prio;
  6188. /* cpumask of isolated */
  6189. cpumask_or(&iso_mask, cpumask_ptr, cpu_isolated_mask);
  6190. cpumask_complement(&iso_mask, &iso_mask);
  6191. /* cpumask of de-isolated */
  6192. cpumask_and(&deiso_mask, cpumask_ptr, cpu_isolated_mask);
  6193. /* set cpu isolated */
  6194. if (!cpumask_empty(&iso_mask)) {
  6195. for_each_cpu(i, &iso_mask)
  6196. _sched_isolate_cpu(i);
  6197. }
  6198. /* set cpu de-isolated */
  6199. if (!cpumask_empty(&deiso_mask)) {
  6200. for_each_cpu(i, &deiso_mask)
  6201. _sched_deisolate_cpu(i);
  6202. }
  6203. /* all possible cpu de-isolated*/
  6204. if (cpumask_empty(cpu_isolated_mask)) {
  6205. iso_prio = ISO_UNSET;
  6206. cpumask_setall(&available_cpus);
  6207. }
  6208. mutex_unlock(&sched_isolation_mutex);
  6209. return 0;
  6210. }
  6211. /* de-isolated all cpu */
  6212. int unset_cpu_isolation(enum iso_prio_t prio)
  6213. {
  6214. int err;
  6215. err = set_cpu_isolation(prio, &cpu_all_masks);
  6216. return err;
  6217. }
  6218. /*
  6219. * Set cpu to be isolated
  6220. * Success: return 0
  6221. */
  6222. int sched_isolate_cpu(int cpu)
  6223. {
  6224. int err = -1;
  6225. if (cpu >= nr_cpu_ids)
  6226. return err;
  6227. #if defined(CONFIG_MTK_GIC_V3_EXT)
  6228. remove_cpu_from_prefer_schedule_domain(cpu);
  6229. #endif
  6230. cpumask_clear_cpu(cpu, &available_cpus);
  6231. err = set_cpu_isolation(ISO_CUSTOMIZE, &available_cpus);
  6232. return err;
  6233. }
  6234. EXPORT_SYMBOL(sched_isolate_cpu);
  6235. /*
  6236. * Set cpu to be deisolated
  6237. * Success: return 0
  6238. */
  6239. int sched_deisolate_cpu(int cpu)
  6240. {
  6241. int err = -1;
  6242. if (cpu >= nr_cpu_ids)
  6243. return err;
  6244. cpumask_set_cpu(cpu, &available_cpus);
  6245. err = set_cpu_isolation(ISO_CUSTOMIZE, &available_cpus);
  6246. #if defined(CONFIG_MTK_GIC_V3_EXT)
  6247. add_cpu_to_prefer_schedule_domain(cpu);
  6248. #endif
  6249. return err;
  6250. }
  6251. EXPORT_SYMBOL(sched_deisolate_cpu);
  6252. #endif /* CONFIG_HOTPLUG_CPU */
  6253. void set_rq_online(struct rq *rq)
  6254. {
  6255. if (!rq->online) {
  6256. const struct sched_class *class;
  6257. cpumask_set_cpu(rq->cpu, rq->rd->online);
  6258. rq->online = 1;
  6259. for_each_class(class) {
  6260. if (class->rq_online)
  6261. class->rq_online(rq);
  6262. }
  6263. }
  6264. }
  6265. void set_rq_offline(struct rq *rq)
  6266. {
  6267. if (rq->online) {
  6268. const struct sched_class *class;
  6269. for_each_class(class) {
  6270. if (class->rq_offline)
  6271. class->rq_offline(rq);
  6272. }
  6273. cpumask_clear_cpu(rq->cpu, rq->rd->online);
  6274. rq->online = 0;
  6275. }
  6276. }
  6277. static void set_cpu_rq_start_time(unsigned int cpu)
  6278. {
  6279. struct rq *rq = cpu_rq(cpu);
  6280. rq->age_stamp = sched_clock_cpu(cpu);
  6281. }
  6282. /*
  6283. * used to mark begin/end of suspend/resume:
  6284. */
  6285. static int num_cpus_frozen;
  6286. /*
  6287. * Update cpusets according to cpu_active mask. If cpusets are
  6288. * disabled, cpuset_update_active_cpus() becomes a simple wrapper
  6289. * around partition_sched_domains().
  6290. *
  6291. * If we come here as part of a suspend/resume, don't touch cpusets because we
  6292. * want to restore it back to its original state upon resume anyway.
  6293. */
  6294. static void cpuset_cpu_active(void)
  6295. {
  6296. if (cpuhp_tasks_frozen) {
  6297. /*
  6298. * num_cpus_frozen tracks how many CPUs are involved in suspend
  6299. * resume sequence. As long as this is not the last online
  6300. * operation in the resume sequence, just build a single sched
  6301. * domain, ignoring cpusets.
  6302. */
  6303. partition_sched_domains(1, NULL, NULL);
  6304. if (--num_cpus_frozen)
  6305. return;
  6306. /*
  6307. * This is the last CPU online operation. So fall through and
  6308. * restore the original sched domains by considering the
  6309. * cpuset configurations.
  6310. */
  6311. cpuset_force_rebuild();
  6312. }
  6313. cpuset_update_active_cpus();
  6314. }
  6315. static int cpuset_cpu_inactive(unsigned int cpu)
  6316. {
  6317. if (!cpuhp_tasks_frozen) {
  6318. if (dl_cpu_busy(cpu))
  6319. return -EBUSY;
  6320. cpuset_update_active_cpus();
  6321. } else {
  6322. num_cpus_frozen++;
  6323. partition_sched_domains(1, NULL, NULL);
  6324. }
  6325. return 0;
  6326. }
  6327. int sched_cpu_activate(unsigned int cpu)
  6328. {
  6329. struct rq *rq = cpu_rq(cpu);
  6330. struct rq_flags rf;
  6331. #ifdef CONFIG_SCHED_SMT
  6332. /*
  6333. * When going up, increment the number of cores with SMT present.
  6334. */
  6335. if (cpumask_weight(cpu_smt_mask(cpu)) == 2)
  6336. static_branch_inc_cpuslocked(&sched_smt_present);
  6337. #endif
  6338. set_cpu_active(cpu, true);
  6339. if (sched_smp_initialized) {
  6340. sched_domains_numa_masks_set(cpu);
  6341. cpuset_cpu_active();
  6342. }
  6343. /*
  6344. * Put the rq online, if not already. This happens:
  6345. *
  6346. * 1) In the early boot process, because we build the real domains
  6347. * after all CPUs have been brought up.
  6348. *
  6349. * 2) At runtime, if cpuset_cpu_active() fails to rebuild the
  6350. * domains.
  6351. */
  6352. rq_lock_irqsave(rq, &rf);
  6353. if (rq->rd) {
  6354. BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
  6355. set_rq_online(rq);
  6356. }
  6357. rq_unlock_irqrestore(rq, &rf);
  6358. update_max_interval();
  6359. return 0;
  6360. }
  6361. int sched_cpu_deactivate(unsigned int cpu)
  6362. {
  6363. int ret;
  6364. set_cpu_active(cpu, false);
  6365. /*
  6366. * We've cleared cpu_active_mask, wait for all preempt-disabled and RCU
  6367. * users of this state to go away such that all new such users will
  6368. * observe it.
  6369. *
  6370. * Do sync before park smpboot threads to take care the rcu boost case.
  6371. */
  6372. synchronize_rcu_mult(call_rcu, call_rcu_sched);
  6373. #ifdef CONFIG_SCHED_SMT
  6374. /*
  6375. * When going down, decrement the number of cores with SMT present.
  6376. */
  6377. if (cpumask_weight(cpu_smt_mask(cpu)) == 2)
  6378. static_branch_dec_cpuslocked(&sched_smt_present);
  6379. #endif
  6380. if (!sched_smp_initialized)
  6381. return 0;
  6382. ret = cpuset_cpu_inactive(cpu);
  6383. if (ret) {
  6384. set_cpu_active(cpu, true);
  6385. return ret;
  6386. }
  6387. sched_domains_numa_masks_clear(cpu);
  6388. return 0;
  6389. }
  6390. static void sched_rq_cpu_starting(unsigned int cpu)
  6391. {
  6392. struct rq *rq = cpu_rq(cpu);
  6393. rq->calc_load_update = calc_load_update;
  6394. update_max_interval();
  6395. }
  6396. int sched_cpu_starting(unsigned int cpu)
  6397. {
  6398. set_cpu_rq_start_time(cpu);
  6399. sched_rq_cpu_starting(cpu);
  6400. return 0;
  6401. }
  6402. #ifdef CONFIG_HOTPLUG_CPU
  6403. int sched_cpu_dying(unsigned int cpu)
  6404. {
  6405. struct rq *rq = cpu_rq(cpu);
  6406. struct rq_flags rf;
  6407. /* Handle pending wakeups and then migrate everything off */
  6408. sched_ttwu_pending();
  6409. rq_lock_irqsave(rq, &rf);
  6410. walt_migrate_sync_cpu(cpu);
  6411. if (rq->rd) {
  6412. BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
  6413. set_rq_offline(rq);
  6414. }
  6415. migrate_tasks(rq, &rf, true);
  6416. BUG_ON(rq->nr_running != 1);
  6417. rq_unlock_irqrestore(rq, &rf);
  6418. calc_load_migrate(rq);
  6419. update_max_interval();
  6420. nohz_balance_exit_idle(cpu);
  6421. hrtick_clear(rq);
  6422. return 0;
  6423. }
  6424. #endif
  6425. void __init sched_init_smp(void)
  6426. {
  6427. cpumask_var_t non_isolated_cpus;
  6428. init_hmp_domains();
  6429. #ifdef CONFIG_MACH_MT6873
  6430. init_efuse_info();
  6431. #endif
  6432. alloc_cpumask_var(&non_isolated_cpus, GFP_KERNEL);
  6433. sched_init_numa();
  6434. /*
  6435. * There's no userspace yet to cause hotplug operations; hence all the
  6436. * CPU masks are stable and all blatant races in the below code cannot
  6437. * happen. The hotplug lock is nevertheless taken to satisfy lockdep,
  6438. * but there won't be any contention on it.
  6439. */
  6440. cpus_read_lock();
  6441. mutex_lock(&sched_domains_mutex);
  6442. sched_init_domains(cpu_active_mask);
  6443. cpumask_andnot(non_isolated_cpus, cpu_possible_mask, cpu_isolated_map);
  6444. if (cpumask_empty(non_isolated_cpus))
  6445. cpumask_set_cpu(smp_processor_id(), non_isolated_cpus);
  6446. mutex_unlock(&sched_domains_mutex);
  6447. cpus_read_unlock();
  6448. /* Move init over to a non-isolated CPU */
  6449. if (set_cpus_allowed_ptr(current, non_isolated_cpus) < 0)
  6450. BUG();
  6451. sched_init_granularity();
  6452. free_cpumask_var(non_isolated_cpus);
  6453. init_sched_rt_class();
  6454. init_sched_dl_class();
  6455. sched_smp_initialized = true;
  6456. }
  6457. static int __init migration_init(void)
  6458. {
  6459. sched_rq_cpu_starting(smp_processor_id());
  6460. return 0;
  6461. }
  6462. early_initcall(migration_init);
  6463. #else
  6464. void __init sched_init_smp(void)
  6465. {
  6466. sched_init_granularity();
  6467. }
  6468. #endif /* CONFIG_SMP */
  6469. int in_sched_functions(unsigned long addr)
  6470. {
  6471. return in_lock_functions(addr) ||
  6472. (addr >= (unsigned long)__sched_text_start
  6473. && addr < (unsigned long)__sched_text_end);
  6474. }
  6475. #ifdef CONFIG_CGROUP_SCHED
  6476. /*
  6477. * Default task group.
  6478. * Every task in system belongs to this group at bootup.
  6479. */
  6480. struct task_group root_task_group;
  6481. LIST_HEAD(task_groups);
  6482. /* Cacheline aligned slab cache for task_group */
  6483. static struct kmem_cache *task_group_cache __read_mostly;
  6484. #endif
  6485. DECLARE_PER_CPU(cpumask_var_t, load_balance_mask);
  6486. DECLARE_PER_CPU(cpumask_var_t, select_idle_mask);
  6487. void __init sched_init(void)
  6488. {
  6489. int i, j;
  6490. unsigned long alloc_size = 0, ptr;
  6491. sched_clock_init();
  6492. wait_bit_init();
  6493. #ifdef CONFIG_FAIR_GROUP_SCHED
  6494. alloc_size += 2 * nr_cpu_ids * sizeof(void **);
  6495. #endif
  6496. #ifdef CONFIG_RT_GROUP_SCHED
  6497. alloc_size += 2 * nr_cpu_ids * sizeof(void **);
  6498. #endif
  6499. if (alloc_size) {
  6500. ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT);
  6501. iso_cpumask_init();
  6502. #ifdef CONFIG_FAIR_GROUP_SCHED
  6503. root_task_group.se = (struct sched_entity **)ptr;
  6504. ptr += nr_cpu_ids * sizeof(void **);
  6505. root_task_group.cfs_rq = (struct cfs_rq **)ptr;
  6506. ptr += nr_cpu_ids * sizeof(void **);
  6507. #endif /* CONFIG_FAIR_GROUP_SCHED */
  6508. #ifdef CONFIG_RT_GROUP_SCHED
  6509. root_task_group.rt_se = (struct sched_rt_entity **)ptr;
  6510. ptr += nr_cpu_ids * sizeof(void **);
  6511. root_task_group.rt_rq = (struct rt_rq **)ptr;
  6512. ptr += nr_cpu_ids * sizeof(void **);
  6513. #endif /* CONFIG_RT_GROUP_SCHED */
  6514. }
  6515. #ifdef CONFIG_CPUMASK_OFFSTACK
  6516. for_each_possible_cpu(i) {
  6517. per_cpu(load_balance_mask, i) = (cpumask_var_t)kzalloc_node(
  6518. cpumask_size(), GFP_KERNEL, cpu_to_node(i));
  6519. per_cpu(select_idle_mask, i) = (cpumask_var_t)kzalloc_node(
  6520. cpumask_size(), GFP_KERNEL, cpu_to_node(i));
  6521. }
  6522. #endif /* CONFIG_CPUMASK_OFFSTACK */
  6523. init_rt_bandwidth(&def_rt_bandwidth, global_rt_period(), global_rt_runtime());
  6524. init_dl_bandwidth(&def_dl_bandwidth, global_rt_period(), global_rt_runtime());
  6525. #ifdef CONFIG_SMP
  6526. init_defrootdomain();
  6527. #endif
  6528. #ifdef CONFIG_RT_GROUP_SCHED
  6529. init_rt_bandwidth(&root_task_group.rt_bandwidth,
  6530. global_rt_period(), global_rt_runtime());
  6531. #endif /* CONFIG_RT_GROUP_SCHED */
  6532. #ifdef CONFIG_CGROUP_SCHED
  6533. task_group_cache = KMEM_CACHE(task_group, 0);
  6534. list_add(&root_task_group.list, &task_groups);
  6535. INIT_LIST_HEAD(&root_task_group.children);
  6536. INIT_LIST_HEAD(&root_task_group.siblings);
  6537. autogroup_init(&init_task);
  6538. #endif /* CONFIG_CGROUP_SCHED */
  6539. for_each_possible_cpu(i) {
  6540. struct rq *rq;
  6541. rq = cpu_rq(i);
  6542. raw_spin_lock_init(&rq->lock);
  6543. rq->nr_running = 0;
  6544. rq->calc_load_active = 0;
  6545. rq->calc_load_update = jiffies + LOAD_FREQ;
  6546. init_cfs_rq(&rq->cfs);
  6547. init_rt_rq(&rq->rt);
  6548. init_dl_rq(&rq->dl);
  6549. #ifdef CONFIG_FAIR_GROUP_SCHED
  6550. root_task_group.shares = ROOT_TASK_GROUP_LOAD;
  6551. INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
  6552. rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
  6553. /*
  6554. * How much CPU bandwidth does root_task_group get?
  6555. *
  6556. * In case of task-groups formed thr' the cgroup filesystem, it
  6557. * gets 100% of the CPU resources in the system. This overall
  6558. * system CPU resource is divided among the tasks of
  6559. * root_task_group and its child task-groups in a fair manner,
  6560. * based on each entity's (task or task-group's) weight
  6561. * (se->load.weight).
  6562. *
  6563. * In other words, if root_task_group has 10 tasks of weight
  6564. * 1024) and two child groups A0 and A1 (of weight 1024 each),
  6565. * then A0's share of the CPU resource is:
  6566. *
  6567. * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
  6568. *
  6569. * We achieve this by letting root_task_group's tasks sit
  6570. * directly in rq->cfs (i.e root_task_group->se[] = NULL).
  6571. */
  6572. init_cfs_bandwidth(&root_task_group.cfs_bandwidth);
  6573. init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL);
  6574. #endif /* CONFIG_FAIR_GROUP_SCHED */
  6575. rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
  6576. #ifdef CONFIG_RT_GROUP_SCHED
  6577. init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL);
  6578. #endif
  6579. for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
  6580. rq->cpu_load[j] = 0;
  6581. #ifdef CONFIG_SMP
  6582. rq->sd = NULL;
  6583. rq->rd = NULL;
  6584. rq->cpu_capacity = rq->cpu_capacity_orig = SCHED_CAPACITY_SCALE;
  6585. rq->balance_callback = NULL;
  6586. rq->active_balance = 0;
  6587. rq->next_balance = jiffies;
  6588. rq->push_cpu = 0;
  6589. rq->cpu = i;
  6590. rq->online = 0;
  6591. rq->idle_stamp = 0;
  6592. rq->avg_idle = 2*sysctl_sched_migration_cost;
  6593. rq->max_idle_balance_cost = sysctl_sched_migration_cost;
  6594. #ifdef CONFIG_SCHED_WALT
  6595. rq->cur_irqload = 0;
  6596. rq->avg_irqload = 0;
  6597. rq->irqload_ts = 0;
  6598. #endif
  6599. INIT_LIST_HEAD(&rq->cfs_tasks);
  6600. rq_attach_root(rq, &def_root_domain);
  6601. #ifdef CONFIG_NO_HZ_COMMON
  6602. rq->last_load_update_tick = jiffies;
  6603. rq->last_blocked_load_update_tick = jiffies;
  6604. rq->nohz_flags = 0;
  6605. #endif
  6606. #ifdef CONFIG_NO_HZ_FULL
  6607. rq->last_sched_tick = 0;
  6608. #endif
  6609. #endif /* CONFIG_SMP */
  6610. init_rq_hrtick(rq);
  6611. atomic_set(&rq->nr_iowait, 0);
  6612. }
  6613. set_load_weight(&init_task);
  6614. /*
  6615. * The boot idle thread does lazy MMU switching as well:
  6616. */
  6617. mmgrab(&init_mm);
  6618. enter_lazy_tlb(&init_mm, current);
  6619. /*
  6620. * Make us the idle thread. Technically, schedule() should not be
  6621. * called from this thread, however somewhere below it might be,
  6622. * but because we are the idle thread, we just pick up running again
  6623. * when this runqueue becomes "idle".
  6624. */
  6625. init_idle(current, smp_processor_id());
  6626. calc_load_update = jiffies + LOAD_FREQ;
  6627. #ifdef CONFIG_SMP
  6628. /* May be allocated at isolcpus cmdline parse time */
  6629. if (cpu_isolated_map == NULL)
  6630. zalloc_cpumask_var(&cpu_isolated_map, GFP_NOWAIT);
  6631. idle_thread_set_boot_cpu();
  6632. set_cpu_rq_start_time(smp_processor_id());
  6633. #endif
  6634. init_sched_fair_class();
  6635. init_schedstats();
  6636. init_uclamp();
  6637. init_sched_energy_costs();
  6638. psi_init();
  6639. scheduler_running = 1;
  6640. task_rotate_work_init();
  6641. }
  6642. #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
  6643. static inline int preempt_count_equals(int preempt_offset)
  6644. {
  6645. int nested = preempt_count() + rcu_preempt_depth();
  6646. return (nested == preempt_offset);
  6647. }
  6648. void __might_sleep(const char *file, int line, int preempt_offset)
  6649. {
  6650. /*
  6651. * Blocking primitives will set (and therefore destroy) current->state,
  6652. * since we will exit with TASK_RUNNING make sure we enter with it,
  6653. * otherwise we will destroy state.
  6654. */
  6655. WARN_ONCE(current->state != TASK_RUNNING && current->task_state_change,
  6656. "do not call blocking ops when !TASK_RUNNING; "
  6657. "state=%lx set at [<%p>] %pS\n",
  6658. current->state,
  6659. (void *)current->task_state_change,
  6660. (void *)current->task_state_change);
  6661. ___might_sleep(file, line, preempt_offset);
  6662. }
  6663. EXPORT_SYMBOL(__might_sleep);
  6664. void ___might_sleep(const char *file, int line, int preempt_offset)
  6665. {
  6666. /* Ratelimiting timestamp: */
  6667. static unsigned long prev_jiffy;
  6668. unsigned long preempt_disable_ip;
  6669. /* WARN_ON_ONCE() by default, no rate limit required: */
  6670. rcu_sleep_check();
  6671. if ((preempt_count_equals(preempt_offset) && !irqs_disabled() &&
  6672. !is_idle_task(current)) ||
  6673. system_state == SYSTEM_BOOTING || system_state > SYSTEM_RUNNING ||
  6674. oops_in_progress)
  6675. return;
  6676. if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
  6677. return;
  6678. prev_jiffy = jiffies;
  6679. /* Save this before calling printk(), since that will clobber it: */
  6680. preempt_disable_ip = get_preempt_disable_ip(current);
  6681. printk(KERN_ERR
  6682. "BUG: sleeping function called from invalid context at %s:%d\n",
  6683. file, line);
  6684. printk(KERN_ERR
  6685. "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
  6686. in_atomic(), irqs_disabled(),
  6687. current->pid, current->comm);
  6688. if (task_stack_end_corrupted(current))
  6689. printk(KERN_EMERG "Thread overran stack, or stack corrupted\n");
  6690. debug_show_held_locks(current);
  6691. if (irqs_disabled())
  6692. print_irqtrace_events(current);
  6693. if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)
  6694. && !preempt_count_equals(preempt_offset)) {
  6695. pr_err("Preemption disabled at:");
  6696. print_ip_sym(preempt_disable_ip);
  6697. dump_preempt_disable_ips(current);
  6698. pr_cont("\n");
  6699. }
  6700. dump_stack();
  6701. add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
  6702. }
  6703. EXPORT_SYMBOL(___might_sleep);
  6704. #endif
  6705. #ifdef CONFIG_MAGIC_SYSRQ
  6706. void normalize_rt_tasks(void)
  6707. {
  6708. struct task_struct *g, *p;
  6709. struct sched_attr attr = {
  6710. .sched_policy = SCHED_NORMAL,
  6711. };
  6712. read_lock(&tasklist_lock);
  6713. for_each_process_thread(g, p) {
  6714. /*
  6715. * Only normalize user tasks:
  6716. */
  6717. if (p->flags & PF_KTHREAD)
  6718. continue;
  6719. p->se.exec_start = 0;
  6720. schedstat_set(p->se.statistics.wait_start, 0);
  6721. schedstat_set(p->se.statistics.sleep_start, 0);
  6722. schedstat_set(p->se.statistics.block_start, 0);
  6723. if (!dl_task(p) && !rt_task(p)) {
  6724. /*
  6725. * Renice negative nice level userspace
  6726. * tasks back to 0:
  6727. */
  6728. if (task_nice(p) < 0)
  6729. set_user_nice(p, 0);
  6730. continue;
  6731. }
  6732. __sched_setscheduler(p, &attr, false, false);
  6733. }
  6734. read_unlock(&tasklist_lock);
  6735. }
  6736. #endif /* CONFIG_MAGIC_SYSRQ */
  6737. #if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
  6738. /*
  6739. * These functions are only useful for the IA64 MCA handling, or kdb.
  6740. *
  6741. * They can only be called when the whole system has been
  6742. * stopped - every CPU needs to be quiescent, and no scheduling
  6743. * activity can take place. Using them for anything else would
  6744. * be a serious bug, and as a result, they aren't even visible
  6745. * under any other configuration.
  6746. */
  6747. /**
  6748. * curr_task - return the current task for a given CPU.
  6749. * @cpu: the processor in question.
  6750. *
  6751. * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
  6752. *
  6753. * Return: The current task for @cpu.
  6754. */
  6755. struct task_struct *curr_task(int cpu)
  6756. {
  6757. return cpu_curr(cpu);
  6758. }
  6759. #endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
  6760. #ifdef CONFIG_IA64
  6761. /**
  6762. * set_curr_task - set the current task for a given CPU.
  6763. * @cpu: the processor in question.
  6764. * @p: the task pointer to set.
  6765. *
  6766. * Description: This function must only be used when non-maskable interrupts
  6767. * are serviced on a separate stack. It allows the architecture to switch the
  6768. * notion of the current task on a CPU in a non-blocking manner. This function
  6769. * must be called with all CPU's synchronized, and interrupts disabled, the
  6770. * and caller must save the original value of the current task (see
  6771. * curr_task() above) and restore that value before reenabling interrupts and
  6772. * re-starting the system.
  6773. *
  6774. * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
  6775. */
  6776. void ia64_set_curr_task(int cpu, struct task_struct *p)
  6777. {
  6778. cpu_curr(cpu) = p;
  6779. }
  6780. #endif
  6781. #ifdef CONFIG_CGROUP_SCHED
  6782. /* task_group_lock serializes the addition/removal of task groups */
  6783. static DEFINE_SPINLOCK(task_group_lock);
  6784. static void sched_free_group(struct task_group *tg)
  6785. {
  6786. #if defined(CONFIG_UCLAMP_TASK_GROUP) && !defined(CONFIG_SCHED_TUNE)
  6787. free_uclamp_sched_group(tg);
  6788. #endif
  6789. free_fair_sched_group(tg);
  6790. free_rt_sched_group(tg);
  6791. autogroup_free(tg);
  6792. kmem_cache_free(task_group_cache, tg);
  6793. }
  6794. /* allocate runqueue etc for a new task group */
  6795. struct task_group *sched_create_group(struct task_group *parent)
  6796. {
  6797. struct task_group *tg;
  6798. tg = kmem_cache_alloc(task_group_cache, GFP_KERNEL | __GFP_ZERO);
  6799. if (!tg)
  6800. return ERR_PTR(-ENOMEM);
  6801. if (!alloc_fair_sched_group(tg, parent))
  6802. goto err;
  6803. if (!alloc_rt_sched_group(tg, parent))
  6804. goto err;
  6805. #if defined(CONFIG_UCLAMP_TASK_GROUP) && !defined(CONFIG_SCHED_TUNE)
  6806. if (!alloc_uclamp_sched_group(tg, parent))
  6807. goto err;
  6808. #endif
  6809. return tg;
  6810. err:
  6811. sched_free_group(tg);
  6812. return ERR_PTR(-ENOMEM);
  6813. }
  6814. void sched_online_group(struct task_group *tg, struct task_group *parent)
  6815. {
  6816. unsigned long flags;
  6817. spin_lock_irqsave(&task_group_lock, flags);
  6818. list_add_rcu(&tg->list, &task_groups);
  6819. /* Root should already exist: */
  6820. WARN_ON(!parent);
  6821. tg->parent = parent;
  6822. INIT_LIST_HEAD(&tg->children);
  6823. list_add_rcu(&tg->siblings, &parent->children);
  6824. spin_unlock_irqrestore(&task_group_lock, flags);
  6825. online_fair_sched_group(tg);
  6826. }
  6827. /* rcu callback to free various structures associated with a task group */
  6828. static void sched_free_group_rcu(struct rcu_head *rhp)
  6829. {
  6830. /* Now it should be safe to free those cfs_rqs: */
  6831. sched_free_group(container_of(rhp, struct task_group, rcu));
  6832. }
  6833. void sched_destroy_group(struct task_group *tg)
  6834. {
  6835. /* Wait for possible concurrent references to cfs_rqs complete: */
  6836. call_rcu(&tg->rcu, sched_free_group_rcu);
  6837. }
  6838. void sched_offline_group(struct task_group *tg)
  6839. {
  6840. unsigned long flags;
  6841. /* End participation in shares distribution: */
  6842. unregister_fair_sched_group(tg);
  6843. spin_lock_irqsave(&task_group_lock, flags);
  6844. list_del_rcu(&tg->list);
  6845. list_del_rcu(&tg->siblings);
  6846. spin_unlock_irqrestore(&task_group_lock, flags);
  6847. }
  6848. static void sched_change_group(struct task_struct *tsk, int type)
  6849. {
  6850. struct task_group *tg;
  6851. /*
  6852. * All callers are synchronized by task_rq_lock(); we do not use RCU
  6853. * which is pointless here. Thus, we pass "true" to task_css_check()
  6854. * to prevent lockdep warnings.
  6855. */
  6856. tg = container_of(task_css_check(tsk, cpu_cgrp_id, true),
  6857. struct task_group, css);
  6858. tg = autogroup_task_group(tsk, tg);
  6859. tsk->sched_task_group = tg;
  6860. #ifdef CONFIG_FAIR_GROUP_SCHED
  6861. if (tsk->sched_class->task_change_group)
  6862. tsk->sched_class->task_change_group(tsk, type);
  6863. else
  6864. #endif
  6865. set_task_rq(tsk, task_cpu(tsk));
  6866. }
  6867. /*
  6868. * Change task's runqueue when it moves between groups.
  6869. *
  6870. * The caller of this function should have put the task in its new group by
  6871. * now. This function just updates tsk->se.cfs_rq and tsk->se.parent to reflect
  6872. * its new group.
  6873. */
  6874. void sched_move_task(struct task_struct *tsk)
  6875. {
  6876. int queued, running, queue_flags =
  6877. DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
  6878. struct rq_flags rf;
  6879. struct rq *rq;
  6880. rq = task_rq_lock(tsk, &rf);
  6881. update_rq_clock(rq);
  6882. running = task_current(rq, tsk);
  6883. queued = task_on_rq_queued(tsk);
  6884. if (queued)
  6885. dequeue_task(rq, tsk, queue_flags);
  6886. if (running)
  6887. put_prev_task(rq, tsk);
  6888. sched_change_group(tsk, TASK_MOVE_GROUP);
  6889. if (queued)
  6890. enqueue_task(rq, tsk, queue_flags);
  6891. if (running)
  6892. set_curr_task(rq, tsk);
  6893. task_rq_unlock(rq, tsk, &rf);
  6894. }
  6895. static inline struct task_group *css_tg(struct cgroup_subsys_state *css)
  6896. {
  6897. return css ? container_of(css, struct task_group, css) : NULL;
  6898. }
  6899. static struct cgroup_subsys_state *
  6900. cpu_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
  6901. {
  6902. struct task_group *parent = css_tg(parent_css);
  6903. struct task_group *tg;
  6904. if (!parent) {
  6905. /* This is early initialization for the top cgroup */
  6906. return &root_task_group.css;
  6907. }
  6908. tg = sched_create_group(parent);
  6909. if (IS_ERR(tg))
  6910. return ERR_PTR(-ENOMEM);
  6911. return &tg->css;
  6912. }
  6913. /* Expose task group only after completing cgroup initialization */
  6914. static int cpu_cgroup_css_online(struct cgroup_subsys_state *css)
  6915. {
  6916. struct task_group *tg = css_tg(css);
  6917. struct task_group *parent = css_tg(css->parent);
  6918. if (parent)
  6919. sched_online_group(tg, parent);
  6920. return 0;
  6921. }
  6922. static void cpu_cgroup_css_released(struct cgroup_subsys_state *css)
  6923. {
  6924. struct task_group *tg = css_tg(css);
  6925. sched_offline_group(tg);
  6926. }
  6927. static void cpu_cgroup_css_free(struct cgroup_subsys_state *css)
  6928. {
  6929. struct task_group *tg = css_tg(css);
  6930. /*
  6931. * Relies on the RCU grace period between css_released() and this.
  6932. */
  6933. sched_free_group(tg);
  6934. }
  6935. /*
  6936. * This is called before wake_up_new_task(), therefore we really only
  6937. * have to set its group bits, all the other stuff does not apply.
  6938. */
  6939. static void cpu_cgroup_fork(struct task_struct *task)
  6940. {
  6941. struct rq_flags rf;
  6942. struct rq *rq;
  6943. rq = task_rq_lock(task, &rf);
  6944. update_rq_clock(rq);
  6945. sched_change_group(task, TASK_SET_GROUP);
  6946. task_rq_unlock(rq, task, &rf);
  6947. }
  6948. static int cpu_cgroup_can_attach(struct cgroup_taskset *tset)
  6949. {
  6950. struct task_struct *task;
  6951. struct cgroup_subsys_state *css;
  6952. int ret = 0;
  6953. cgroup_taskset_for_each(task, css, tset) {
  6954. #ifdef CONFIG_RT_GROUP_SCHED
  6955. if (!sched_rt_can_attach(css_tg(css), task))
  6956. return -EINVAL;
  6957. #endif
  6958. /*
  6959. * Serialize against wake_up_new_task() such that if its
  6960. * running, we're sure to observe its full state.
  6961. */
  6962. raw_spin_lock_irq(&task->pi_lock);
  6963. /*
  6964. * Avoid calling sched_move_task() before wake_up_new_task()
  6965. * has happened. This would lead to problems with PELT, due to
  6966. * move wanting to detach+attach while we're not attached yet.
  6967. */
  6968. if (task->state == TASK_NEW)
  6969. ret = -EINVAL;
  6970. raw_spin_unlock_irq(&task->pi_lock);
  6971. if (ret)
  6972. break;
  6973. }
  6974. return ret;
  6975. }
  6976. static void cpu_cgroup_attach(struct cgroup_taskset *tset)
  6977. {
  6978. struct task_struct *task;
  6979. struct cgroup_subsys_state *css;
  6980. cgroup_taskset_for_each(task, css, tset)
  6981. sched_move_task(task);
  6982. }
  6983. #if defined(CONFIG_UCLAMP_TASK_GROUP) && !defined(CONFIG_SCHED_TUNE)
  6984. /**
  6985. * cpu_util_update_hier: propagate effective clamp down the hierarchy
  6986. * @css: the task group to update
  6987. * @clamp_id: the clamp index to update
  6988. * @group_id: the group index mapping the new task clamp value
  6989. * @value: the new task group clamp value
  6990. *
  6991. * The effective clamp for a TG is expected to track the most restrictive
  6992. * value between the TG's clamp value and it's parent effective clamp value.
  6993. * This method achieve that:
  6994. * 1. updating the current TG effective value
  6995. * 2. walking all the descendant task group that needs an update
  6996. *
  6997. * A TG's effective clamp needs to be updated when its current value is not
  6998. * matching the TG's clamp value. In this case indeed either:
  6999. * a) the parent has got a more relaxed clamp value
  7000. * thus potentially we can relax the effective value for this group
  7001. * b) the parent has got a more strict clamp value
  7002. * thus potentially we have to restrict the effective value of this group
  7003. *
  7004. * Restriction and relaxation of current TG's effective clamp values needs to
  7005. * be propagated down to all the descendants. When a subgroup is found which
  7006. * has already its effective clamp value matching its clamp value, then we can
  7007. * safely skip all its descendants which are granted to be already in sync.
  7008. *
  7009. * The TG's group_id is also updated to ensure it tracks the effective clamp
  7010. * value.
  7011. */
  7012. static void cpu_util_update_hier(struct cgroup_subsys_state *css,
  7013. unsigned int clamp_id, unsigned int group_id,
  7014. unsigned int value)
  7015. {
  7016. struct cgroup_subsys_state *top_css = css;
  7017. struct uclamp_se *uc_se, *uc_parent;
  7018. css_for_each_descendant_pre(css, top_css) {
  7019. /*
  7020. * The first visited task group is top_css, which clamp value
  7021. * is the one passed as parameter. For descendent task
  7022. * groups we consider their current value.
  7023. */
  7024. uc_se = &css_tg(css)->uclamp[clamp_id];
  7025. if (css != top_css) {
  7026. value = uc_se->value;
  7027. group_id = uc_se->effective.group_id;
  7028. }
  7029. /*
  7030. * Skip the whole subtrees if the current effective clamp is
  7031. * already matching the TG's clamp value.
  7032. * In this case, all the subtrees already have top_value, or a
  7033. * more restrictive, as effective clamp.
  7034. */
  7035. uc_parent = &css_tg(css)->parent->uclamp[clamp_id];
  7036. if (uc_se->effective.value == value &&
  7037. uc_parent->effective.value >= value) {
  7038. css = css_rightmost_descendant(css);
  7039. continue;
  7040. }
  7041. /* Propagate the most restrictive effective value */
  7042. if (uc_parent->effective.value < value) {
  7043. value = uc_parent->effective.value;
  7044. group_id = uc_parent->effective.group_id;
  7045. }
  7046. if (uc_se->effective.value == value)
  7047. continue;
  7048. uc_se->effective.value = value;
  7049. uc_se->effective.group_id = group_id;
  7050. /* Immediately updated descendants active tasks */
  7051. if (css != top_css)
  7052. uclamp_group_get_tg(css, clamp_id, group_id);
  7053. }
  7054. }
  7055. static int cpu_util_min_write_u64(struct cgroup_subsys_state *css,
  7056. struct cftype *cftype, u64 min_value)
  7057. {
  7058. struct task_group *tg;
  7059. int ret = 0;
  7060. if (min_value > SCHED_CAPACITY_SCALE)
  7061. return -ERANGE;
  7062. if (!opp_capacity_tbl_ready)
  7063. init_opp_capacity_tbl();
  7064. min_value = find_fit_capacity(min_value);
  7065. mutex_lock(&uclamp_mutex);
  7066. rcu_read_lock();
  7067. tg = css_tg(css);
  7068. if (tg->uclamp[UCLAMP_MIN].value == min_value)
  7069. goto out;
  7070. if (tg->uclamp[UCLAMP_MAX].value < min_value) {
  7071. ret = -EINVAL;
  7072. goto out;
  7073. }
  7074. /* Update TG's reference count */
  7075. uclamp_group_get(NULL, css, &tg->uclamp[UCLAMP_MIN],
  7076. UCLAMP_MIN, min_value);
  7077. /* Update effective clamps to track the most restrictive value */
  7078. cpu_util_update_hier(css, UCLAMP_MIN, tg->uclamp[UCLAMP_MIN].group_id,
  7079. min_value);
  7080. out:
  7081. rcu_read_unlock();
  7082. mutex_unlock(&uclamp_mutex);
  7083. return ret;
  7084. }
  7085. static int cpu_util_max_write_u64(struct cgroup_subsys_state *css,
  7086. struct cftype *cftype, u64 max_value)
  7087. {
  7088. struct task_group *tg;
  7089. int ret = 0;
  7090. if (max_value > SCHED_CAPACITY_SCALE)
  7091. return -ERANGE;
  7092. if (!opp_capacity_tbl_ready)
  7093. init_opp_capacity_tbl();
  7094. max_value = find_fit_capacity(max_value);
  7095. mutex_lock(&uclamp_mutex);
  7096. rcu_read_lock();
  7097. tg = css_tg(css);
  7098. if (tg->uclamp[UCLAMP_MAX].value == max_value)
  7099. goto out;
  7100. if (tg->uclamp[UCLAMP_MIN].value > max_value) {
  7101. ret = -EINVAL;
  7102. goto out;
  7103. }
  7104. /* Update TG's reference count */
  7105. uclamp_group_get(NULL, css, &tg->uclamp[UCLAMP_MAX],
  7106. UCLAMP_MAX, max_value);
  7107. /* Update effective clamps to track the most restrictive value */
  7108. cpu_util_update_hier(css, UCLAMP_MAX, tg->uclamp[UCLAMP_MAX].group_id,
  7109. max_value);
  7110. out:
  7111. rcu_read_unlock();
  7112. mutex_unlock(&uclamp_mutex);
  7113. return ret;
  7114. }
  7115. static inline u64 cpu_uclamp_read(struct cgroup_subsys_state *css,
  7116. enum uclamp_id clamp_id,
  7117. bool effective)
  7118. {
  7119. struct task_group *tg;
  7120. u64 util_clamp;
  7121. rcu_read_lock();
  7122. tg = css_tg(css);
  7123. util_clamp = effective
  7124. ? tg->uclamp[clamp_id].effective.value
  7125. : tg->uclamp[clamp_id].value;
  7126. rcu_read_unlock();
  7127. return util_clamp;
  7128. }
  7129. static u64 cpu_util_min_read_u64(struct cgroup_subsys_state *css,
  7130. struct cftype *cft)
  7131. {
  7132. return cpu_uclamp_read(css, UCLAMP_MIN, false);
  7133. }
  7134. static u64 cpu_util_max_read_u64(struct cgroup_subsys_state *css,
  7135. struct cftype *cft)
  7136. {
  7137. return cpu_uclamp_read(css, UCLAMP_MAX, false);
  7138. }
  7139. static u64 cpu_util_min_effective_read_u64(struct cgroup_subsys_state *css,
  7140. struct cftype *cft)
  7141. {
  7142. return cpu_uclamp_read(css, UCLAMP_MIN, true);
  7143. }
  7144. static u64 cpu_util_max_effective_read_u64(struct cgroup_subsys_state *css,
  7145. struct cftype *cft)
  7146. {
  7147. return cpu_uclamp_read(css, UCLAMP_MAX, true);
  7148. }
  7149. #endif /* CONFIG_UCLAMP_TASK_GROUP */
  7150. #ifdef CONFIG_FAIR_GROUP_SCHED
  7151. static int cpu_shares_write_u64(struct cgroup_subsys_state *css,
  7152. struct cftype *cftype, u64 shareval)
  7153. {
  7154. if (shareval > scale_load_down(ULONG_MAX))
  7155. shareval = MAX_SHARES;
  7156. return sched_group_set_shares(css_tg(css), scale_load(shareval));
  7157. }
  7158. static u64 cpu_shares_read_u64(struct cgroup_subsys_state *css,
  7159. struct cftype *cft)
  7160. {
  7161. struct task_group *tg = css_tg(css);
  7162. return (u64) scale_load_down(tg->shares);
  7163. }
  7164. #ifdef CONFIG_CFS_BANDWIDTH
  7165. static DEFINE_MUTEX(cfs_constraints_mutex);
  7166. const u64 max_cfs_quota_period = 1 * NSEC_PER_SEC; /* 1s */
  7167. const u64 min_cfs_quota_period = 1 * NSEC_PER_MSEC; /* 1ms */
  7168. static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime);
  7169. static int tg_set_cfs_bandwidth(struct task_group *tg, u64 period, u64 quota)
  7170. {
  7171. int i, ret = 0, runtime_enabled, runtime_was_enabled;
  7172. struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
  7173. if (tg == &root_task_group)
  7174. return -EINVAL;
  7175. /*
  7176. * Ensure we have at some amount of bandwidth every period. This is
  7177. * to prevent reaching a state of large arrears when throttled via
  7178. * entity_tick() resulting in prolonged exit starvation.
  7179. */
  7180. if (quota < min_cfs_quota_period || period < min_cfs_quota_period)
  7181. return -EINVAL;
  7182. /*
  7183. * Likewise, bound things on the otherside by preventing insane quota
  7184. * periods. This also allows us to normalize in computing quota
  7185. * feasibility.
  7186. */
  7187. if (period > max_cfs_quota_period)
  7188. return -EINVAL;
  7189. /*
  7190. * Prevent race between setting of cfs_rq->runtime_enabled and
  7191. * unthrottle_offline_cfs_rqs().
  7192. */
  7193. get_online_cpus();
  7194. mutex_lock(&cfs_constraints_mutex);
  7195. ret = __cfs_schedulable(tg, period, quota);
  7196. if (ret)
  7197. goto out_unlock;
  7198. runtime_enabled = quota != RUNTIME_INF;
  7199. runtime_was_enabled = cfs_b->quota != RUNTIME_INF;
  7200. /*
  7201. * If we need to toggle cfs_bandwidth_used, off->on must occur
  7202. * before making related changes, and on->off must occur afterwards
  7203. */
  7204. if (runtime_enabled && !runtime_was_enabled)
  7205. cfs_bandwidth_usage_inc();
  7206. raw_spin_lock_irq(&cfs_b->lock);
  7207. cfs_b->period = ns_to_ktime(period);
  7208. cfs_b->quota = quota;
  7209. __refill_cfs_bandwidth_runtime(cfs_b);
  7210. /* Restart the period timer (if active) to handle new period expiry: */
  7211. if (runtime_enabled)
  7212. start_cfs_bandwidth(cfs_b);
  7213. raw_spin_unlock_irq(&cfs_b->lock);
  7214. for_each_online_cpu(i) {
  7215. struct cfs_rq *cfs_rq = tg->cfs_rq[i];
  7216. struct rq *rq = cfs_rq->rq;
  7217. struct rq_flags rf;
  7218. rq_lock_irq(rq, &rf);
  7219. cfs_rq->runtime_enabled = runtime_enabled;
  7220. cfs_rq->runtime_remaining = 0;
  7221. if (cfs_rq->throttled)
  7222. unthrottle_cfs_rq(cfs_rq);
  7223. rq_unlock_irq(rq, &rf);
  7224. }
  7225. if (runtime_was_enabled && !runtime_enabled)
  7226. cfs_bandwidth_usage_dec();
  7227. out_unlock:
  7228. mutex_unlock(&cfs_constraints_mutex);
  7229. put_online_cpus();
  7230. return ret;
  7231. }
  7232. int tg_set_cfs_quota(struct task_group *tg, long cfs_quota_us)
  7233. {
  7234. u64 quota, period;
  7235. period = ktime_to_ns(tg->cfs_bandwidth.period);
  7236. if (cfs_quota_us < 0)
  7237. quota = RUNTIME_INF;
  7238. else if ((u64)cfs_quota_us <= U64_MAX / NSEC_PER_USEC)
  7239. quota = (u64)cfs_quota_us * NSEC_PER_USEC;
  7240. else
  7241. return -EINVAL;
  7242. return tg_set_cfs_bandwidth(tg, period, quota);
  7243. }
  7244. long tg_get_cfs_quota(struct task_group *tg)
  7245. {
  7246. u64 quota_us;
  7247. if (tg->cfs_bandwidth.quota == RUNTIME_INF)
  7248. return -1;
  7249. quota_us = tg->cfs_bandwidth.quota;
  7250. do_div(quota_us, NSEC_PER_USEC);
  7251. return quota_us;
  7252. }
  7253. int tg_set_cfs_period(struct task_group *tg, long cfs_period_us)
  7254. {
  7255. u64 quota, period;
  7256. if ((u64)cfs_period_us > U64_MAX / NSEC_PER_USEC)
  7257. return -EINVAL;
  7258. period = (u64)cfs_period_us * NSEC_PER_USEC;
  7259. quota = tg->cfs_bandwidth.quota;
  7260. return tg_set_cfs_bandwidth(tg, period, quota);
  7261. }
  7262. long tg_get_cfs_period(struct task_group *tg)
  7263. {
  7264. u64 cfs_period_us;
  7265. cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period);
  7266. do_div(cfs_period_us, NSEC_PER_USEC);
  7267. return cfs_period_us;
  7268. }
  7269. static s64 cpu_cfs_quota_read_s64(struct cgroup_subsys_state *css,
  7270. struct cftype *cft)
  7271. {
  7272. return tg_get_cfs_quota(css_tg(css));
  7273. }
  7274. static int cpu_cfs_quota_write_s64(struct cgroup_subsys_state *css,
  7275. struct cftype *cftype, s64 cfs_quota_us)
  7276. {
  7277. return tg_set_cfs_quota(css_tg(css), cfs_quota_us);
  7278. }
  7279. static u64 cpu_cfs_period_read_u64(struct cgroup_subsys_state *css,
  7280. struct cftype *cft)
  7281. {
  7282. return tg_get_cfs_period(css_tg(css));
  7283. }
  7284. static int cpu_cfs_period_write_u64(struct cgroup_subsys_state *css,
  7285. struct cftype *cftype, u64 cfs_period_us)
  7286. {
  7287. return tg_set_cfs_period(css_tg(css), cfs_period_us);
  7288. }
  7289. struct cfs_schedulable_data {
  7290. struct task_group *tg;
  7291. u64 period, quota;
  7292. };
  7293. /*
  7294. * normalize group quota/period to be quota/max_period
  7295. * note: units are usecs
  7296. */
  7297. static u64 normalize_cfs_quota(struct task_group *tg,
  7298. struct cfs_schedulable_data *d)
  7299. {
  7300. u64 quota, period;
  7301. if (tg == d->tg) {
  7302. period = d->period;
  7303. quota = d->quota;
  7304. } else {
  7305. period = tg_get_cfs_period(tg);
  7306. quota = tg_get_cfs_quota(tg);
  7307. }
  7308. /* note: these should typically be equivalent */
  7309. if (quota == RUNTIME_INF || quota == -1)
  7310. return RUNTIME_INF;
  7311. return to_ratio(period, quota);
  7312. }
  7313. static int tg_cfs_schedulable_down(struct task_group *tg, void *data)
  7314. {
  7315. struct cfs_schedulable_data *d = data;
  7316. struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
  7317. s64 quota = 0, parent_quota = -1;
  7318. if (!tg->parent) {
  7319. quota = RUNTIME_INF;
  7320. } else {
  7321. struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth;
  7322. quota = normalize_cfs_quota(tg, d);
  7323. parent_quota = parent_b->hierarchical_quota;
  7324. /*
  7325. * Ensure max(child_quota) <= parent_quota, inherit when no
  7326. * limit is set:
  7327. */
  7328. if (quota == RUNTIME_INF)
  7329. quota = parent_quota;
  7330. else if (parent_quota != RUNTIME_INF && quota > parent_quota)
  7331. return -EINVAL;
  7332. }
  7333. cfs_b->hierarchical_quota = quota;
  7334. return 0;
  7335. }
  7336. static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota)
  7337. {
  7338. int ret;
  7339. struct cfs_schedulable_data data = {
  7340. .tg = tg,
  7341. .period = period,
  7342. .quota = quota,
  7343. };
  7344. if (quota != RUNTIME_INF) {
  7345. do_div(data.period, NSEC_PER_USEC);
  7346. do_div(data.quota, NSEC_PER_USEC);
  7347. }
  7348. rcu_read_lock();
  7349. ret = walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data);
  7350. rcu_read_unlock();
  7351. return ret;
  7352. }
  7353. static int cpu_stats_show(struct seq_file *sf, void *v)
  7354. {
  7355. struct task_group *tg = css_tg(seq_css(sf));
  7356. struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
  7357. seq_printf(sf, "nr_periods %d\n", cfs_b->nr_periods);
  7358. seq_printf(sf, "nr_throttled %d\n", cfs_b->nr_throttled);
  7359. seq_printf(sf, "throttled_time %llu\n", cfs_b->throttled_time);
  7360. return 0;
  7361. }
  7362. #endif /* CONFIG_CFS_BANDWIDTH */
  7363. #endif /* CONFIG_FAIR_GROUP_SCHED */
  7364. #ifdef CONFIG_RT_GROUP_SCHED
  7365. static int cpu_rt_runtime_write(struct cgroup_subsys_state *css,
  7366. struct cftype *cft, s64 val)
  7367. {
  7368. return sched_group_set_rt_runtime(css_tg(css), val);
  7369. }
  7370. static s64 cpu_rt_runtime_read(struct cgroup_subsys_state *css,
  7371. struct cftype *cft)
  7372. {
  7373. return sched_group_rt_runtime(css_tg(css));
  7374. }
  7375. static int cpu_rt_period_write_uint(struct cgroup_subsys_state *css,
  7376. struct cftype *cftype, u64 rt_period_us)
  7377. {
  7378. return sched_group_set_rt_period(css_tg(css), rt_period_us);
  7379. }
  7380. static u64 cpu_rt_period_read_uint(struct cgroup_subsys_state *css,
  7381. struct cftype *cft)
  7382. {
  7383. return sched_group_rt_period(css_tg(css));
  7384. }
  7385. #endif /* CONFIG_RT_GROUP_SCHED */
  7386. static struct cftype cpu_files[] = {
  7387. #ifdef CONFIG_FAIR_GROUP_SCHED
  7388. {
  7389. .name = "shares",
  7390. .read_u64 = cpu_shares_read_u64,
  7391. .write_u64 = cpu_shares_write_u64,
  7392. },
  7393. #endif
  7394. #ifdef CONFIG_CFS_BANDWIDTH
  7395. {
  7396. .name = "cfs_quota_us",
  7397. .read_s64 = cpu_cfs_quota_read_s64,
  7398. .write_s64 = cpu_cfs_quota_write_s64,
  7399. },
  7400. {
  7401. .name = "cfs_period_us",
  7402. .read_u64 = cpu_cfs_period_read_u64,
  7403. .write_u64 = cpu_cfs_period_write_u64,
  7404. },
  7405. {
  7406. .name = "stat",
  7407. .seq_show = cpu_stats_show,
  7408. },
  7409. #endif
  7410. #ifdef CONFIG_RT_GROUP_SCHED
  7411. {
  7412. .name = "rt_runtime_us",
  7413. .read_s64 = cpu_rt_runtime_read,
  7414. .write_s64 = cpu_rt_runtime_write,
  7415. },
  7416. {
  7417. .name = "rt_period_us",
  7418. .read_u64 = cpu_rt_period_read_uint,
  7419. .write_u64 = cpu_rt_period_write_uint,
  7420. },
  7421. #endif
  7422. #if defined(CONFIG_UCLAMP_TASK_GROUP) && !defined(CONFIG_SCHED_TUNE)
  7423. {
  7424. .name = "util.min",
  7425. .read_u64 = cpu_util_min_read_u64,
  7426. .write_u64 = cpu_util_min_write_u64,
  7427. },
  7428. {
  7429. .name = "util.min.effective",
  7430. .read_u64 = cpu_util_min_effective_read_u64,
  7431. },
  7432. {
  7433. .name = "util.max",
  7434. .read_u64 = cpu_util_max_read_u64,
  7435. .write_u64 = cpu_util_max_write_u64,
  7436. },
  7437. {
  7438. .name = "util.max.effective",
  7439. .read_u64 = cpu_util_max_effective_read_u64,
  7440. },
  7441. #endif
  7442. { } /* Terminate */
  7443. };
  7444. struct cgroup_subsys cpu_cgrp_subsys = {
  7445. .css_alloc = cpu_cgroup_css_alloc,
  7446. .css_online = cpu_cgroup_css_online,
  7447. .css_released = cpu_cgroup_css_released,
  7448. .css_free = cpu_cgroup_css_free,
  7449. .fork = cpu_cgroup_fork,
  7450. .can_attach = cpu_cgroup_can_attach,
  7451. .attach = cpu_cgroup_attach,
  7452. .legacy_cftypes = cpu_files,
  7453. .early_init = true,
  7454. };
  7455. #endif /* CONFIG_CGROUP_SCHED */
  7456. void dump_cpu_task(int cpu)
  7457. {
  7458. pr_info("Task dump for CPU %d:\n", cpu);
  7459. sched_show_task(cpu_curr(cpu));
  7460. }
  7461. /*
  7462. * Nice levels are multiplicative, with a gentle 10% change for every
  7463. * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
  7464. * nice 1, it will get ~10% less CPU time than another CPU-bound task
  7465. * that remained on nice 0.
  7466. *
  7467. * The "10% effect" is relative and cumulative: from _any_ nice level,
  7468. * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
  7469. * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
  7470. * If a task goes up by ~10% and another task goes down by ~10% then
  7471. * the relative distance between them is ~25%.)
  7472. */
  7473. const int sched_prio_to_weight[40] = {
  7474. /* -20 */ 88761, 71755, 56483, 46273, 36291,
  7475. /* -15 */ 29154, 23254, 18705, 14949, 11916,
  7476. /* -10 */ 9548, 7620, 6100, 4904, 3906,
  7477. /* -5 */ 3121, 2501, 1991, 1586, 1277,
  7478. /* 0 */ 1024, 820, 655, 526, 423,
  7479. /* 5 */ 335, 272, 215, 172, 137,
  7480. /* 10 */ 110, 87, 70, 56, 45,
  7481. /* 15 */ 36, 29, 23, 18, 15,
  7482. };
  7483. /*
  7484. * Inverse (2^32/x) values of the sched_prio_to_weight[] array, precalculated.
  7485. *
  7486. * In cases where the weight does not change often, we can use the
  7487. * precalculated inverse to speed up arithmetics by turning divisions
  7488. * into multiplications:
  7489. */
  7490. const u32 sched_prio_to_wmult[40] = {
  7491. /* -20 */ 48388, 59856, 76040, 92818, 118348,
  7492. /* -15 */ 147320, 184698, 229616, 287308, 360437,
  7493. /* -10 */ 449829, 563644, 704093, 875809, 1099582,
  7494. /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
  7495. /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
  7496. /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
  7497. /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
  7498. /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
  7499. };