core.c 220 KB

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