core.c 272 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * kernel/sched/core.c
  4. *
  5. * Core kernel CPU scheduler code
  6. *
  7. * Copyright (C) 1991-2002 Linus Torvalds
  8. * Copyright (C) 1998-2024 Ingo Molnar, Red Hat
  9. */
  10. #include <linux/highmem.h>
  11. #include <linux/hrtimer_api.h>
  12. #include <linux/ktime_api.h>
  13. #include <linux/sched/signal.h>
  14. #include <linux/syscalls_api.h>
  15. #include <linux/debug_locks.h>
  16. #include <linux/prefetch.h>
  17. #include <linux/capability.h>
  18. #include <linux/pgtable_api.h>
  19. #include <linux/wait_bit.h>
  20. #include <linux/jiffies.h>
  21. #include <linux/spinlock_api.h>
  22. #include <linux/cpumask_api.h>
  23. #include <linux/lockdep_api.h>
  24. #include <linux/hardirq.h>
  25. #include <linux/softirq.h>
  26. #include <linux/refcount_api.h>
  27. #include <linux/topology.h>
  28. #include <linux/sched/clock.h>
  29. #include <linux/sched/cond_resched.h>
  30. #include <linux/sched/cputime.h>
  31. #include <linux/sched/debug.h>
  32. #include <linux/sched/hotplug.h>
  33. #include <linux/sched/init.h>
  34. #include <linux/sched/isolation.h>
  35. #include <linux/sched/loadavg.h>
  36. #include <linux/sched/mm.h>
  37. #include <linux/sched/nohz.h>
  38. #include <linux/sched/rseq_api.h>
  39. #include <linux/sched/rt.h>
  40. #include <linux/blkdev.h>
  41. #include <linux/context_tracking.h>
  42. #include <linux/cpuset.h>
  43. #include <linux/delayacct.h>
  44. #include <linux/init_task.h>
  45. #include <linux/interrupt.h>
  46. #include <linux/ioprio.h>
  47. #include <linux/kallsyms.h>
  48. #include <linux/kcov.h>
  49. #include <linux/kprobes.h>
  50. #include <linux/llist_api.h>
  51. #include <linux/mmu_context.h>
  52. #include <linux/mmzone.h>
  53. #include <linux/mutex_api.h>
  54. #include <linux/nmi.h>
  55. #include <linux/nospec.h>
  56. #include <linux/perf_event_api.h>
  57. #include <linux/profile.h>
  58. #include <linux/psi.h>
  59. #include <linux/rcuwait_api.h>
  60. #include <linux/rseq.h>
  61. #include <linux/sched/wake_q.h>
  62. #include <linux/scs.h>
  63. #include <linux/slab.h>
  64. #include <linux/syscalls.h>
  65. #include <linux/vtime.h>
  66. #include <linux/wait_api.h>
  67. #include <linux/workqueue_api.h>
  68. #ifdef CONFIG_PREEMPT_DYNAMIC
  69. # ifdef CONFIG_GENERIC_ENTRY
  70. # include <linux/entry-common.h>
  71. # endif
  72. #endif
  73. #include <uapi/linux/sched/types.h>
  74. #include <asm/irq_regs.h>
  75. #include <asm/switch_to.h>
  76. #include <asm/tlb.h>
  77. #define CREATE_TRACE_POINTS
  78. #include <linux/sched/rseq_api.h>
  79. #include <trace/events/sched.h>
  80. #include <trace/events/ipi.h>
  81. #undef CREATE_TRACE_POINTS
  82. #include "sched.h"
  83. #include "stats.h"
  84. #include "autogroup.h"
  85. #include "pelt.h"
  86. #include "smp.h"
  87. #include "stats.h"
  88. #include "../workqueue_internal.h"
  89. #include "../../io_uring/io-wq.h"
  90. #include "../smpboot.h"
  91. EXPORT_TRACEPOINT_SYMBOL_GPL(ipi_send_cpu);
  92. EXPORT_TRACEPOINT_SYMBOL_GPL(ipi_send_cpumask);
  93. /*
  94. * Export tracepoints that act as a bare tracehook (ie: have no trace event
  95. * associated with them) to allow external modules to probe them.
  96. */
  97. EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_cfs_tp);
  98. EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_rt_tp);
  99. EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_dl_tp);
  100. EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_irq_tp);
  101. EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_se_tp);
  102. EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_hw_tp);
  103. EXPORT_TRACEPOINT_SYMBOL_GPL(sched_cpu_capacity_tp);
  104. EXPORT_TRACEPOINT_SYMBOL_GPL(sched_overutilized_tp);
  105. EXPORT_TRACEPOINT_SYMBOL_GPL(sched_util_est_cfs_tp);
  106. EXPORT_TRACEPOINT_SYMBOL_GPL(sched_util_est_se_tp);
  107. EXPORT_TRACEPOINT_SYMBOL_GPL(sched_update_nr_running_tp);
  108. EXPORT_TRACEPOINT_SYMBOL_GPL(sched_compute_energy_tp);
  109. DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
  110. #ifdef CONFIG_SCHED_DEBUG
  111. /*
  112. * Debugging: various feature bits
  113. *
  114. * If SCHED_DEBUG is disabled, each compilation unit has its own copy of
  115. * sysctl_sched_features, defined in sched.h, to allow constants propagation
  116. * at compile time and compiler optimization based on features default.
  117. */
  118. #define SCHED_FEAT(name, enabled) \
  119. (1UL << __SCHED_FEAT_##name) * enabled |
  120. const_debug unsigned int sysctl_sched_features =
  121. #include "features.h"
  122. 0;
  123. #undef SCHED_FEAT
  124. /*
  125. * Print a warning if need_resched is set for the given duration (if
  126. * LATENCY_WARN is enabled).
  127. *
  128. * If sysctl_resched_latency_warn_once is set, only one warning will be shown
  129. * per boot.
  130. */
  131. __read_mostly int sysctl_resched_latency_warn_ms = 100;
  132. __read_mostly int sysctl_resched_latency_warn_once = 1;
  133. #endif /* CONFIG_SCHED_DEBUG */
  134. /*
  135. * Number of tasks to iterate in a single balance run.
  136. * Limited because this is done with IRQs disabled.
  137. */
  138. const_debug unsigned int sysctl_sched_nr_migrate = SCHED_NR_MIGRATE_BREAK;
  139. __read_mostly int scheduler_running;
  140. #ifdef CONFIG_SCHED_CORE
  141. DEFINE_STATIC_KEY_FALSE(__sched_core_enabled);
  142. /* kernel prio, less is more */
  143. static inline int __task_prio(const struct task_struct *p)
  144. {
  145. if (p->sched_class == &stop_sched_class) /* trumps deadline */
  146. return -2;
  147. if (p->dl_server)
  148. return -1; /* deadline */
  149. if (rt_or_dl_prio(p->prio))
  150. return p->prio; /* [-1, 99] */
  151. if (p->sched_class == &idle_sched_class)
  152. return MAX_RT_PRIO + NICE_WIDTH; /* 140 */
  153. if (task_on_scx(p))
  154. return MAX_RT_PRIO + MAX_NICE + 1; /* 120, squash ext */
  155. return MAX_RT_PRIO + MAX_NICE; /* 119, squash fair */
  156. }
  157. /*
  158. * l(a,b)
  159. * le(a,b) := !l(b,a)
  160. * g(a,b) := l(b,a)
  161. * ge(a,b) := !l(a,b)
  162. */
  163. /* real prio, less is less */
  164. static inline bool prio_less(const struct task_struct *a,
  165. const struct task_struct *b, bool in_fi)
  166. {
  167. int pa = __task_prio(a), pb = __task_prio(b);
  168. if (-pa < -pb)
  169. return true;
  170. if (-pb < -pa)
  171. return false;
  172. if (pa == -1) { /* dl_prio() doesn't work because of stop_class above */
  173. const struct sched_dl_entity *a_dl, *b_dl;
  174. a_dl = &a->dl;
  175. /*
  176. * Since,'a' and 'b' can be CFS tasks served by DL server,
  177. * __task_prio() can return -1 (for DL) even for those. In that
  178. * case, get to the dl_server's DL entity.
  179. */
  180. if (a->dl_server)
  181. a_dl = a->dl_server;
  182. b_dl = &b->dl;
  183. if (b->dl_server)
  184. b_dl = b->dl_server;
  185. return !dl_time_before(a_dl->deadline, b_dl->deadline);
  186. }
  187. if (pa == MAX_RT_PRIO + MAX_NICE) /* fair */
  188. return cfs_prio_less(a, b, in_fi);
  189. #ifdef CONFIG_SCHED_CLASS_EXT
  190. if (pa == MAX_RT_PRIO + MAX_NICE + 1) /* ext */
  191. return scx_prio_less(a, b, in_fi);
  192. #endif
  193. return false;
  194. }
  195. static inline bool __sched_core_less(const struct task_struct *a,
  196. const struct task_struct *b)
  197. {
  198. if (a->core_cookie < b->core_cookie)
  199. return true;
  200. if (a->core_cookie > b->core_cookie)
  201. return false;
  202. /* flip prio, so high prio is leftmost */
  203. if (prio_less(b, a, !!task_rq(a)->core->core_forceidle_count))
  204. return true;
  205. return false;
  206. }
  207. #define __node_2_sc(node) rb_entry((node), struct task_struct, core_node)
  208. static inline bool rb_sched_core_less(struct rb_node *a, const struct rb_node *b)
  209. {
  210. return __sched_core_less(__node_2_sc(a), __node_2_sc(b));
  211. }
  212. static inline int rb_sched_core_cmp(const void *key, const struct rb_node *node)
  213. {
  214. const struct task_struct *p = __node_2_sc(node);
  215. unsigned long cookie = (unsigned long)key;
  216. if (cookie < p->core_cookie)
  217. return -1;
  218. if (cookie > p->core_cookie)
  219. return 1;
  220. return 0;
  221. }
  222. void sched_core_enqueue(struct rq *rq, struct task_struct *p)
  223. {
  224. if (p->se.sched_delayed)
  225. return;
  226. rq->core->core_task_seq++;
  227. if (!p->core_cookie)
  228. return;
  229. rb_add(&p->core_node, &rq->core_tree, rb_sched_core_less);
  230. }
  231. void sched_core_dequeue(struct rq *rq, struct task_struct *p, int flags)
  232. {
  233. if (p->se.sched_delayed)
  234. return;
  235. rq->core->core_task_seq++;
  236. if (sched_core_enqueued(p)) {
  237. rb_erase(&p->core_node, &rq->core_tree);
  238. RB_CLEAR_NODE(&p->core_node);
  239. }
  240. /*
  241. * Migrating the last task off the cpu, with the cpu in forced idle
  242. * state. Reschedule to create an accounting edge for forced idle,
  243. * and re-examine whether the core is still in forced idle state.
  244. */
  245. if (!(flags & DEQUEUE_SAVE) && rq->nr_running == 1 &&
  246. rq->core->core_forceidle_count && rq->curr == rq->idle)
  247. resched_curr(rq);
  248. }
  249. static int sched_task_is_throttled(struct task_struct *p, int cpu)
  250. {
  251. if (p->sched_class->task_is_throttled)
  252. return p->sched_class->task_is_throttled(p, cpu);
  253. return 0;
  254. }
  255. static struct task_struct *sched_core_next(struct task_struct *p, unsigned long cookie)
  256. {
  257. struct rb_node *node = &p->core_node;
  258. int cpu = task_cpu(p);
  259. do {
  260. node = rb_next(node);
  261. if (!node)
  262. return NULL;
  263. p = __node_2_sc(node);
  264. if (p->core_cookie != cookie)
  265. return NULL;
  266. } while (sched_task_is_throttled(p, cpu));
  267. return p;
  268. }
  269. /*
  270. * Find left-most (aka, highest priority) and unthrottled task matching @cookie.
  271. * If no suitable task is found, NULL will be returned.
  272. */
  273. static struct task_struct *sched_core_find(struct rq *rq, unsigned long cookie)
  274. {
  275. struct task_struct *p;
  276. struct rb_node *node;
  277. node = rb_find_first((void *)cookie, &rq->core_tree, rb_sched_core_cmp);
  278. if (!node)
  279. return NULL;
  280. p = __node_2_sc(node);
  281. if (!sched_task_is_throttled(p, rq->cpu))
  282. return p;
  283. return sched_core_next(p, cookie);
  284. }
  285. /*
  286. * Magic required such that:
  287. *
  288. * raw_spin_rq_lock(rq);
  289. * ...
  290. * raw_spin_rq_unlock(rq);
  291. *
  292. * ends up locking and unlocking the _same_ lock, and all CPUs
  293. * always agree on what rq has what lock.
  294. *
  295. * XXX entirely possible to selectively enable cores, don't bother for now.
  296. */
  297. static DEFINE_MUTEX(sched_core_mutex);
  298. static atomic_t sched_core_count;
  299. static struct cpumask sched_core_mask;
  300. static void sched_core_lock(int cpu, unsigned long *flags)
  301. {
  302. const struct cpumask *smt_mask = cpu_smt_mask(cpu);
  303. int t, i = 0;
  304. local_irq_save(*flags);
  305. for_each_cpu(t, smt_mask)
  306. raw_spin_lock_nested(&cpu_rq(t)->__lock, i++);
  307. }
  308. static void sched_core_unlock(int cpu, unsigned long *flags)
  309. {
  310. const struct cpumask *smt_mask = cpu_smt_mask(cpu);
  311. int t;
  312. for_each_cpu(t, smt_mask)
  313. raw_spin_unlock(&cpu_rq(t)->__lock);
  314. local_irq_restore(*flags);
  315. }
  316. static void __sched_core_flip(bool enabled)
  317. {
  318. unsigned long flags;
  319. int cpu, t;
  320. cpus_read_lock();
  321. /*
  322. * Toggle the online cores, one by one.
  323. */
  324. cpumask_copy(&sched_core_mask, cpu_online_mask);
  325. for_each_cpu(cpu, &sched_core_mask) {
  326. const struct cpumask *smt_mask = cpu_smt_mask(cpu);
  327. sched_core_lock(cpu, &flags);
  328. for_each_cpu(t, smt_mask)
  329. cpu_rq(t)->core_enabled = enabled;
  330. cpu_rq(cpu)->core->core_forceidle_start = 0;
  331. sched_core_unlock(cpu, &flags);
  332. cpumask_andnot(&sched_core_mask, &sched_core_mask, smt_mask);
  333. }
  334. /*
  335. * Toggle the offline CPUs.
  336. */
  337. for_each_cpu_andnot(cpu, cpu_possible_mask, cpu_online_mask)
  338. cpu_rq(cpu)->core_enabled = enabled;
  339. cpus_read_unlock();
  340. }
  341. static void sched_core_assert_empty(void)
  342. {
  343. int cpu;
  344. for_each_possible_cpu(cpu)
  345. WARN_ON_ONCE(!RB_EMPTY_ROOT(&cpu_rq(cpu)->core_tree));
  346. }
  347. static void __sched_core_enable(void)
  348. {
  349. static_branch_enable(&__sched_core_enabled);
  350. /*
  351. * Ensure all previous instances of raw_spin_rq_*lock() have finished
  352. * and future ones will observe !sched_core_disabled().
  353. */
  354. synchronize_rcu();
  355. __sched_core_flip(true);
  356. sched_core_assert_empty();
  357. }
  358. static void __sched_core_disable(void)
  359. {
  360. sched_core_assert_empty();
  361. __sched_core_flip(false);
  362. static_branch_disable(&__sched_core_enabled);
  363. }
  364. void sched_core_get(void)
  365. {
  366. if (atomic_inc_not_zero(&sched_core_count))
  367. return;
  368. mutex_lock(&sched_core_mutex);
  369. if (!atomic_read(&sched_core_count))
  370. __sched_core_enable();
  371. smp_mb__before_atomic();
  372. atomic_inc(&sched_core_count);
  373. mutex_unlock(&sched_core_mutex);
  374. }
  375. static void __sched_core_put(struct work_struct *work)
  376. {
  377. if (atomic_dec_and_mutex_lock(&sched_core_count, &sched_core_mutex)) {
  378. __sched_core_disable();
  379. mutex_unlock(&sched_core_mutex);
  380. }
  381. }
  382. void sched_core_put(void)
  383. {
  384. static DECLARE_WORK(_work, __sched_core_put);
  385. /*
  386. * "There can be only one"
  387. *
  388. * Either this is the last one, or we don't actually need to do any
  389. * 'work'. If it is the last *again*, we rely on
  390. * WORK_STRUCT_PENDING_BIT.
  391. */
  392. if (!atomic_add_unless(&sched_core_count, -1, 1))
  393. schedule_work(&_work);
  394. }
  395. #else /* !CONFIG_SCHED_CORE */
  396. static inline void sched_core_enqueue(struct rq *rq, struct task_struct *p) { }
  397. static inline void
  398. sched_core_dequeue(struct rq *rq, struct task_struct *p, int flags) { }
  399. #endif /* CONFIG_SCHED_CORE */
  400. /*
  401. * Serialization rules:
  402. *
  403. * Lock order:
  404. *
  405. * p->pi_lock
  406. * rq->lock
  407. * hrtimer_cpu_base->lock (hrtimer_start() for bandwidth controls)
  408. *
  409. * rq1->lock
  410. * rq2->lock where: rq1 < rq2
  411. *
  412. * Regular state:
  413. *
  414. * Normal scheduling state is serialized by rq->lock. __schedule() takes the
  415. * local CPU's rq->lock, it optionally removes the task from the runqueue and
  416. * always looks at the local rq data structures to find the most eligible task
  417. * to run next.
  418. *
  419. * Task enqueue is also under rq->lock, possibly taken from another CPU.
  420. * Wakeups from another LLC domain might use an IPI to transfer the enqueue to
  421. * the local CPU to avoid bouncing the runqueue state around [ see
  422. * ttwu_queue_wakelist() ]
  423. *
  424. * Task wakeup, specifically wakeups that involve migration, are horribly
  425. * complicated to avoid having to take two rq->locks.
  426. *
  427. * Special state:
  428. *
  429. * System-calls and anything external will use task_rq_lock() which acquires
  430. * both p->pi_lock and rq->lock. As a consequence the state they change is
  431. * stable while holding either lock:
  432. *
  433. * - sched_setaffinity()/
  434. * set_cpus_allowed_ptr(): p->cpus_ptr, p->nr_cpus_allowed
  435. * - set_user_nice(): p->se.load, p->*prio
  436. * - __sched_setscheduler(): p->sched_class, p->policy, p->*prio,
  437. * p->se.load, p->rt_priority,
  438. * p->dl.dl_{runtime, deadline, period, flags, bw, density}
  439. * - sched_setnuma(): p->numa_preferred_nid
  440. * - sched_move_task(): p->sched_task_group
  441. * - uclamp_update_active() p->uclamp*
  442. *
  443. * p->state <- TASK_*:
  444. *
  445. * is changed locklessly using set_current_state(), __set_current_state() or
  446. * set_special_state(), see their respective comments, or by
  447. * try_to_wake_up(). This latter uses p->pi_lock to serialize against
  448. * concurrent self.
  449. *
  450. * p->on_rq <- { 0, 1 = TASK_ON_RQ_QUEUED, 2 = TASK_ON_RQ_MIGRATING }:
  451. *
  452. * is set by activate_task() and cleared by deactivate_task(), under
  453. * rq->lock. Non-zero indicates the task is runnable, the special
  454. * ON_RQ_MIGRATING state is used for migration without holding both
  455. * rq->locks. It indicates task_cpu() is not stable, see task_rq_lock().
  456. *
  457. * Additionally it is possible to be ->on_rq but still be considered not
  458. * runnable when p->se.sched_delayed is true. These tasks are on the runqueue
  459. * but will be dequeued as soon as they get picked again. See the
  460. * task_is_runnable() helper.
  461. *
  462. * p->on_cpu <- { 0, 1 }:
  463. *
  464. * is set by prepare_task() and cleared by finish_task() such that it will be
  465. * set before p is scheduled-in and cleared after p is scheduled-out, both
  466. * under rq->lock. Non-zero indicates the task is running on its CPU.
  467. *
  468. * [ The astute reader will observe that it is possible for two tasks on one
  469. * CPU to have ->on_cpu = 1 at the same time. ]
  470. *
  471. * task_cpu(p): is changed by set_task_cpu(), the rules are:
  472. *
  473. * - Don't call set_task_cpu() on a blocked task:
  474. *
  475. * We don't care what CPU we're not running on, this simplifies hotplug,
  476. * the CPU assignment of blocked tasks isn't required to be valid.
  477. *
  478. * - for try_to_wake_up(), called under p->pi_lock:
  479. *
  480. * This allows try_to_wake_up() to only take one rq->lock, see its comment.
  481. *
  482. * - for migration called under rq->lock:
  483. * [ see task_on_rq_migrating() in task_rq_lock() ]
  484. *
  485. * o move_queued_task()
  486. * o detach_task()
  487. *
  488. * - for migration called under double_rq_lock():
  489. *
  490. * o __migrate_swap_task()
  491. * o push_rt_task() / pull_rt_task()
  492. * o push_dl_task() / pull_dl_task()
  493. * o dl_task_offline_migration()
  494. *
  495. */
  496. void raw_spin_rq_lock_nested(struct rq *rq, int subclass)
  497. {
  498. raw_spinlock_t *lock;
  499. /* Matches synchronize_rcu() in __sched_core_enable() */
  500. preempt_disable();
  501. if (sched_core_disabled()) {
  502. raw_spin_lock_nested(&rq->__lock, subclass);
  503. /* preempt_count *MUST* be > 1 */
  504. preempt_enable_no_resched();
  505. return;
  506. }
  507. for (;;) {
  508. lock = __rq_lockp(rq);
  509. raw_spin_lock_nested(lock, subclass);
  510. if (likely(lock == __rq_lockp(rq))) {
  511. /* preempt_count *MUST* be > 1 */
  512. preempt_enable_no_resched();
  513. return;
  514. }
  515. raw_spin_unlock(lock);
  516. }
  517. }
  518. bool raw_spin_rq_trylock(struct rq *rq)
  519. {
  520. raw_spinlock_t *lock;
  521. bool ret;
  522. /* Matches synchronize_rcu() in __sched_core_enable() */
  523. preempt_disable();
  524. if (sched_core_disabled()) {
  525. ret = raw_spin_trylock(&rq->__lock);
  526. preempt_enable();
  527. return ret;
  528. }
  529. for (;;) {
  530. lock = __rq_lockp(rq);
  531. ret = raw_spin_trylock(lock);
  532. if (!ret || (likely(lock == __rq_lockp(rq)))) {
  533. preempt_enable();
  534. return ret;
  535. }
  536. raw_spin_unlock(lock);
  537. }
  538. }
  539. void raw_spin_rq_unlock(struct rq *rq)
  540. {
  541. raw_spin_unlock(rq_lockp(rq));
  542. }
  543. #ifdef CONFIG_SMP
  544. /*
  545. * double_rq_lock - safely lock two runqueues
  546. */
  547. void double_rq_lock(struct rq *rq1, struct rq *rq2)
  548. {
  549. lockdep_assert_irqs_disabled();
  550. if (rq_order_less(rq2, rq1))
  551. swap(rq1, rq2);
  552. raw_spin_rq_lock(rq1);
  553. if (__rq_lockp(rq1) != __rq_lockp(rq2))
  554. raw_spin_rq_lock_nested(rq2, SINGLE_DEPTH_NESTING);
  555. double_rq_clock_clear_update(rq1, rq2);
  556. }
  557. #endif
  558. /*
  559. * __task_rq_lock - lock the rq @p resides on.
  560. */
  561. struct rq *__task_rq_lock(struct task_struct *p, struct rq_flags *rf)
  562. __acquires(rq->lock)
  563. {
  564. struct rq *rq;
  565. lockdep_assert_held(&p->pi_lock);
  566. for (;;) {
  567. rq = task_rq(p);
  568. raw_spin_rq_lock(rq);
  569. if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
  570. rq_pin_lock(rq, rf);
  571. return rq;
  572. }
  573. raw_spin_rq_unlock(rq);
  574. while (unlikely(task_on_rq_migrating(p)))
  575. cpu_relax();
  576. }
  577. }
  578. /*
  579. * task_rq_lock - lock p->pi_lock and lock the rq @p resides on.
  580. */
  581. struct rq *task_rq_lock(struct task_struct *p, struct rq_flags *rf)
  582. __acquires(p->pi_lock)
  583. __acquires(rq->lock)
  584. {
  585. struct rq *rq;
  586. for (;;) {
  587. raw_spin_lock_irqsave(&p->pi_lock, rf->flags);
  588. rq = task_rq(p);
  589. raw_spin_rq_lock(rq);
  590. /*
  591. * move_queued_task() task_rq_lock()
  592. *
  593. * ACQUIRE (rq->lock)
  594. * [S] ->on_rq = MIGRATING [L] rq = task_rq()
  595. * WMB (__set_task_cpu()) ACQUIRE (rq->lock);
  596. * [S] ->cpu = new_cpu [L] task_rq()
  597. * [L] ->on_rq
  598. * RELEASE (rq->lock)
  599. *
  600. * If we observe the old CPU in task_rq_lock(), the acquire of
  601. * the old rq->lock will fully serialize against the stores.
  602. *
  603. * If we observe the new CPU in task_rq_lock(), the address
  604. * dependency headed by '[L] rq = task_rq()' and the acquire
  605. * will pair with the WMB to ensure we then also see migrating.
  606. */
  607. if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
  608. rq_pin_lock(rq, rf);
  609. return rq;
  610. }
  611. raw_spin_rq_unlock(rq);
  612. raw_spin_unlock_irqrestore(&p->pi_lock, rf->flags);
  613. while (unlikely(task_on_rq_migrating(p)))
  614. cpu_relax();
  615. }
  616. }
  617. /*
  618. * RQ-clock updating methods:
  619. */
  620. static void update_rq_clock_task(struct rq *rq, s64 delta)
  621. {
  622. /*
  623. * In theory, the compile should just see 0 here, and optimize out the call
  624. * to sched_rt_avg_update. But I don't trust it...
  625. */
  626. s64 __maybe_unused steal = 0, irq_delta = 0;
  627. #ifdef CONFIG_IRQ_TIME_ACCOUNTING
  628. irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time;
  629. /*
  630. * Since irq_time is only updated on {soft,}irq_exit, we might run into
  631. * this case when a previous update_rq_clock() happened inside a
  632. * {soft,}IRQ region.
  633. *
  634. * When this happens, we stop ->clock_task and only update the
  635. * prev_irq_time stamp to account for the part that fit, so that a next
  636. * update will consume the rest. This ensures ->clock_task is
  637. * monotonic.
  638. *
  639. * It does however cause some slight miss-attribution of {soft,}IRQ
  640. * time, a more accurate solution would be to update the irq_time using
  641. * the current rq->clock timestamp, except that would require using
  642. * atomic ops.
  643. */
  644. if (irq_delta > delta)
  645. irq_delta = delta;
  646. rq->prev_irq_time += irq_delta;
  647. delta -= irq_delta;
  648. delayacct_irq(rq->curr, irq_delta);
  649. #endif
  650. #ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
  651. if (static_key_false((&paravirt_steal_rq_enabled))) {
  652. u64 prev_steal;
  653. steal = prev_steal = paravirt_steal_clock(cpu_of(rq));
  654. steal -= rq->prev_steal_time_rq;
  655. if (unlikely(steal > delta))
  656. steal = delta;
  657. rq->prev_steal_time_rq = prev_steal;
  658. delta -= steal;
  659. }
  660. #endif
  661. rq->clock_task += delta;
  662. #ifdef CONFIG_HAVE_SCHED_AVG_IRQ
  663. if ((irq_delta + steal) && sched_feat(NONTASK_CAPACITY))
  664. update_irq_load_avg(rq, irq_delta + steal);
  665. #endif
  666. update_rq_clock_pelt(rq, delta);
  667. }
  668. void update_rq_clock(struct rq *rq)
  669. {
  670. s64 delta;
  671. lockdep_assert_rq_held(rq);
  672. if (rq->clock_update_flags & RQCF_ACT_SKIP)
  673. return;
  674. #ifdef CONFIG_SCHED_DEBUG
  675. if (sched_feat(WARN_DOUBLE_CLOCK))
  676. SCHED_WARN_ON(rq->clock_update_flags & RQCF_UPDATED);
  677. rq->clock_update_flags |= RQCF_UPDATED;
  678. #endif
  679. delta = sched_clock_cpu(cpu_of(rq)) - rq->clock;
  680. if (delta < 0)
  681. return;
  682. rq->clock += delta;
  683. update_rq_clock_task(rq, delta);
  684. }
  685. #ifdef CONFIG_SCHED_HRTICK
  686. /*
  687. * Use HR-timers to deliver accurate preemption points.
  688. */
  689. static void hrtick_clear(struct rq *rq)
  690. {
  691. if (hrtimer_active(&rq->hrtick_timer))
  692. hrtimer_cancel(&rq->hrtick_timer);
  693. }
  694. /*
  695. * High-resolution timer tick.
  696. * Runs from hardirq context with interrupts disabled.
  697. */
  698. static enum hrtimer_restart hrtick(struct hrtimer *timer)
  699. {
  700. struct rq *rq = container_of(timer, struct rq, hrtick_timer);
  701. struct rq_flags rf;
  702. WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
  703. rq_lock(rq, &rf);
  704. update_rq_clock(rq);
  705. rq->curr->sched_class->task_tick(rq, rq->curr, 1);
  706. rq_unlock(rq, &rf);
  707. return HRTIMER_NORESTART;
  708. }
  709. #ifdef CONFIG_SMP
  710. static void __hrtick_restart(struct rq *rq)
  711. {
  712. struct hrtimer *timer = &rq->hrtick_timer;
  713. ktime_t time = rq->hrtick_time;
  714. hrtimer_start(timer, time, HRTIMER_MODE_ABS_PINNED_HARD);
  715. }
  716. /*
  717. * called from hardirq (IPI) context
  718. */
  719. static void __hrtick_start(void *arg)
  720. {
  721. struct rq *rq = arg;
  722. struct rq_flags rf;
  723. rq_lock(rq, &rf);
  724. __hrtick_restart(rq);
  725. rq_unlock(rq, &rf);
  726. }
  727. /*
  728. * Called to set the hrtick timer state.
  729. *
  730. * called with rq->lock held and IRQs disabled
  731. */
  732. void hrtick_start(struct rq *rq, u64 delay)
  733. {
  734. struct hrtimer *timer = &rq->hrtick_timer;
  735. s64 delta;
  736. /*
  737. * Don't schedule slices shorter than 10000ns, that just
  738. * doesn't make sense and can cause timer DoS.
  739. */
  740. delta = max_t(s64, delay, 10000LL);
  741. rq->hrtick_time = ktime_add_ns(timer->base->get_time(), delta);
  742. if (rq == this_rq())
  743. __hrtick_restart(rq);
  744. else
  745. smp_call_function_single_async(cpu_of(rq), &rq->hrtick_csd);
  746. }
  747. #else
  748. /*
  749. * Called to set the hrtick timer state.
  750. *
  751. * called with rq->lock held and IRQs disabled
  752. */
  753. void hrtick_start(struct rq *rq, u64 delay)
  754. {
  755. /*
  756. * Don't schedule slices shorter than 10000ns, that just
  757. * doesn't make sense. Rely on vruntime for fairness.
  758. */
  759. delay = max_t(u64, delay, 10000LL);
  760. hrtimer_start(&rq->hrtick_timer, ns_to_ktime(delay),
  761. HRTIMER_MODE_REL_PINNED_HARD);
  762. }
  763. #endif /* CONFIG_SMP */
  764. static void hrtick_rq_init(struct rq *rq)
  765. {
  766. #ifdef CONFIG_SMP
  767. INIT_CSD(&rq->hrtick_csd, __hrtick_start, rq);
  768. #endif
  769. hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD);
  770. rq->hrtick_timer.function = hrtick;
  771. }
  772. #else /* CONFIG_SCHED_HRTICK */
  773. static inline void hrtick_clear(struct rq *rq)
  774. {
  775. }
  776. static inline void hrtick_rq_init(struct rq *rq)
  777. {
  778. }
  779. #endif /* CONFIG_SCHED_HRTICK */
  780. /*
  781. * try_cmpxchg based fetch_or() macro so it works for different integer types:
  782. */
  783. #define fetch_or(ptr, mask) \
  784. ({ \
  785. typeof(ptr) _ptr = (ptr); \
  786. typeof(mask) _mask = (mask); \
  787. typeof(*_ptr) _val = *_ptr; \
  788. \
  789. do { \
  790. } while (!try_cmpxchg(_ptr, &_val, _val | _mask)); \
  791. _val; \
  792. })
  793. #if defined(CONFIG_SMP) && defined(TIF_POLLING_NRFLAG)
  794. /*
  795. * Atomically set TIF_NEED_RESCHED and test for TIF_POLLING_NRFLAG,
  796. * this avoids any races wrt polling state changes and thereby avoids
  797. * spurious IPIs.
  798. */
  799. static inline bool set_nr_and_not_polling(struct task_struct *p)
  800. {
  801. struct thread_info *ti = task_thread_info(p);
  802. return !(fetch_or(&ti->flags, _TIF_NEED_RESCHED) & _TIF_POLLING_NRFLAG);
  803. }
  804. /*
  805. * Atomically set TIF_NEED_RESCHED if TIF_POLLING_NRFLAG is set.
  806. *
  807. * If this returns true, then the idle task promises to call
  808. * sched_ttwu_pending() and reschedule soon.
  809. */
  810. static bool set_nr_if_polling(struct task_struct *p)
  811. {
  812. struct thread_info *ti = task_thread_info(p);
  813. typeof(ti->flags) val = READ_ONCE(ti->flags);
  814. do {
  815. if (!(val & _TIF_POLLING_NRFLAG))
  816. return false;
  817. if (val & _TIF_NEED_RESCHED)
  818. return true;
  819. } while (!try_cmpxchg(&ti->flags, &val, val | _TIF_NEED_RESCHED));
  820. return true;
  821. }
  822. #else
  823. static inline bool set_nr_and_not_polling(struct task_struct *p)
  824. {
  825. set_tsk_need_resched(p);
  826. return true;
  827. }
  828. #ifdef CONFIG_SMP
  829. static inline bool set_nr_if_polling(struct task_struct *p)
  830. {
  831. return false;
  832. }
  833. #endif
  834. #endif
  835. static bool __wake_q_add(struct wake_q_head *head, struct task_struct *task)
  836. {
  837. struct wake_q_node *node = &task->wake_q;
  838. /*
  839. * Atomically grab the task, if ->wake_q is !nil already it means
  840. * it's already queued (either by us or someone else) and will get the
  841. * wakeup due to that.
  842. *
  843. * In order to ensure that a pending wakeup will observe our pending
  844. * state, even in the failed case, an explicit smp_mb() must be used.
  845. */
  846. smp_mb__before_atomic();
  847. if (unlikely(cmpxchg_relaxed(&node->next, NULL, WAKE_Q_TAIL)))
  848. return false;
  849. /*
  850. * The head is context local, there can be no concurrency.
  851. */
  852. *head->lastp = node;
  853. head->lastp = &node->next;
  854. return true;
  855. }
  856. /**
  857. * wake_q_add() - queue a wakeup for 'later' waking.
  858. * @head: the wake_q_head to add @task to
  859. * @task: the task to queue for 'later' wakeup
  860. *
  861. * Queue a task for later wakeup, most likely by the wake_up_q() call in the
  862. * same context, _HOWEVER_ this is not guaranteed, the wakeup can come
  863. * instantly.
  864. *
  865. * This function must be used as-if it were wake_up_process(); IOW the task
  866. * must be ready to be woken at this location.
  867. */
  868. void wake_q_add(struct wake_q_head *head, struct task_struct *task)
  869. {
  870. if (__wake_q_add(head, task))
  871. get_task_struct(task);
  872. }
  873. /**
  874. * wake_q_add_safe() - safely queue a wakeup for 'later' waking.
  875. * @head: the wake_q_head to add @task to
  876. * @task: the task to queue for 'later' wakeup
  877. *
  878. * Queue a task for later wakeup, most likely by the wake_up_q() call in the
  879. * same context, _HOWEVER_ this is not guaranteed, the wakeup can come
  880. * instantly.
  881. *
  882. * This function must be used as-if it were wake_up_process(); IOW the task
  883. * must be ready to be woken at this location.
  884. *
  885. * This function is essentially a task-safe equivalent to wake_q_add(). Callers
  886. * that already hold reference to @task can call the 'safe' version and trust
  887. * wake_q to do the right thing depending whether or not the @task is already
  888. * queued for wakeup.
  889. */
  890. void wake_q_add_safe(struct wake_q_head *head, struct task_struct *task)
  891. {
  892. if (!__wake_q_add(head, task))
  893. put_task_struct(task);
  894. }
  895. void wake_up_q(struct wake_q_head *head)
  896. {
  897. struct wake_q_node *node = head->first;
  898. while (node != WAKE_Q_TAIL) {
  899. struct task_struct *task;
  900. task = container_of(node, struct task_struct, wake_q);
  901. node = node->next;
  902. /* pairs with cmpxchg_relaxed() in __wake_q_add() */
  903. WRITE_ONCE(task->wake_q.next, NULL);
  904. /* Task can safely be re-inserted now. */
  905. /*
  906. * wake_up_process() executes a full barrier, which pairs with
  907. * the queueing in wake_q_add() so as not to miss wakeups.
  908. */
  909. wake_up_process(task);
  910. put_task_struct(task);
  911. }
  912. }
  913. /*
  914. * resched_curr - mark rq's current task 'to be rescheduled now'.
  915. *
  916. * On UP this means the setting of the need_resched flag, on SMP it
  917. * might also involve a cross-CPU call to trigger the scheduler on
  918. * the target CPU.
  919. */
  920. void resched_curr(struct rq *rq)
  921. {
  922. struct task_struct *curr = rq->curr;
  923. int cpu;
  924. lockdep_assert_rq_held(rq);
  925. if (test_tsk_need_resched(curr))
  926. return;
  927. cpu = cpu_of(rq);
  928. if (cpu == smp_processor_id()) {
  929. set_tsk_need_resched(curr);
  930. set_preempt_need_resched();
  931. return;
  932. }
  933. if (set_nr_and_not_polling(curr))
  934. smp_send_reschedule(cpu);
  935. else
  936. trace_sched_wake_idle_without_ipi(cpu);
  937. }
  938. void resched_cpu(int cpu)
  939. {
  940. struct rq *rq = cpu_rq(cpu);
  941. unsigned long flags;
  942. raw_spin_rq_lock_irqsave(rq, flags);
  943. if (cpu_online(cpu) || cpu == smp_processor_id())
  944. resched_curr(rq);
  945. raw_spin_rq_unlock_irqrestore(rq, flags);
  946. }
  947. #ifdef CONFIG_SMP
  948. #ifdef CONFIG_NO_HZ_COMMON
  949. /*
  950. * In the semi idle case, use the nearest busy CPU for migrating timers
  951. * from an idle CPU. This is good for power-savings.
  952. *
  953. * We don't do similar optimization for completely idle system, as
  954. * selecting an idle CPU will add more delays to the timers than intended
  955. * (as that CPU's timer base may not be up to date wrt jiffies etc).
  956. */
  957. int get_nohz_timer_target(void)
  958. {
  959. int i, cpu = smp_processor_id(), default_cpu = -1;
  960. struct sched_domain *sd;
  961. const struct cpumask *hk_mask;
  962. if (housekeeping_cpu(cpu, HK_TYPE_TIMER)) {
  963. if (!idle_cpu(cpu))
  964. return cpu;
  965. default_cpu = cpu;
  966. }
  967. hk_mask = housekeeping_cpumask(HK_TYPE_TIMER);
  968. guard(rcu)();
  969. for_each_domain(cpu, sd) {
  970. for_each_cpu_and(i, sched_domain_span(sd), hk_mask) {
  971. if (cpu == i)
  972. continue;
  973. if (!idle_cpu(i))
  974. return i;
  975. }
  976. }
  977. if (default_cpu == -1)
  978. default_cpu = housekeeping_any_cpu(HK_TYPE_TIMER);
  979. return default_cpu;
  980. }
  981. /*
  982. * When add_timer_on() enqueues a timer into the timer wheel of an
  983. * idle CPU then this timer might expire before the next timer event
  984. * which is scheduled to wake up that CPU. In case of a completely
  985. * idle system the next event might even be infinite time into the
  986. * future. wake_up_idle_cpu() ensures that the CPU is woken up and
  987. * leaves the inner idle loop so the newly added timer is taken into
  988. * account when the CPU goes back to idle and evaluates the timer
  989. * wheel for the next timer event.
  990. */
  991. static void wake_up_idle_cpu(int cpu)
  992. {
  993. struct rq *rq = cpu_rq(cpu);
  994. if (cpu == smp_processor_id())
  995. return;
  996. /*
  997. * Set TIF_NEED_RESCHED and send an IPI if in the non-polling
  998. * part of the idle loop. This forces an exit from the idle loop
  999. * and a round trip to schedule(). Now this could be optimized
  1000. * because a simple new idle loop iteration is enough to
  1001. * re-evaluate the next tick. Provided some re-ordering of tick
  1002. * nohz functions that would need to follow TIF_NR_POLLING
  1003. * clearing:
  1004. *
  1005. * - On most architectures, a simple fetch_or on ti::flags with a
  1006. * "0" value would be enough to know if an IPI needs to be sent.
  1007. *
  1008. * - x86 needs to perform a last need_resched() check between
  1009. * monitor and mwait which doesn't take timers into account.
  1010. * There a dedicated TIF_TIMER flag would be required to
  1011. * fetch_or here and be checked along with TIF_NEED_RESCHED
  1012. * before mwait().
  1013. *
  1014. * However, remote timer enqueue is not such a frequent event
  1015. * and testing of the above solutions didn't appear to report
  1016. * much benefits.
  1017. */
  1018. if (set_nr_and_not_polling(rq->idle))
  1019. smp_send_reschedule(cpu);
  1020. else
  1021. trace_sched_wake_idle_without_ipi(cpu);
  1022. }
  1023. static bool wake_up_full_nohz_cpu(int cpu)
  1024. {
  1025. /*
  1026. * We just need the target to call irq_exit() and re-evaluate
  1027. * the next tick. The nohz full kick at least implies that.
  1028. * If needed we can still optimize that later with an
  1029. * empty IRQ.
  1030. */
  1031. if (cpu_is_offline(cpu))
  1032. return true; /* Don't try to wake offline CPUs. */
  1033. if (tick_nohz_full_cpu(cpu)) {
  1034. if (cpu != smp_processor_id() ||
  1035. tick_nohz_tick_stopped())
  1036. tick_nohz_full_kick_cpu(cpu);
  1037. return true;
  1038. }
  1039. return false;
  1040. }
  1041. /*
  1042. * Wake up the specified CPU. If the CPU is going offline, it is the
  1043. * caller's responsibility to deal with the lost wakeup, for example,
  1044. * by hooking into the CPU_DEAD notifier like timers and hrtimers do.
  1045. */
  1046. void wake_up_nohz_cpu(int cpu)
  1047. {
  1048. if (!wake_up_full_nohz_cpu(cpu))
  1049. wake_up_idle_cpu(cpu);
  1050. }
  1051. static void nohz_csd_func(void *info)
  1052. {
  1053. struct rq *rq = info;
  1054. int cpu = cpu_of(rq);
  1055. unsigned int flags;
  1056. /*
  1057. * Release the rq::nohz_csd.
  1058. */
  1059. flags = atomic_fetch_andnot(NOHZ_KICK_MASK | NOHZ_NEWILB_KICK, nohz_flags(cpu));
  1060. WARN_ON(!(flags & NOHZ_KICK_MASK));
  1061. rq->idle_balance = idle_cpu(cpu);
  1062. if (rq->idle_balance) {
  1063. rq->nohz_idle_balance = flags;
  1064. __raise_softirq_irqoff(SCHED_SOFTIRQ);
  1065. }
  1066. }
  1067. #endif /* CONFIG_NO_HZ_COMMON */
  1068. #ifdef CONFIG_NO_HZ_FULL
  1069. static inline bool __need_bw_check(struct rq *rq, struct task_struct *p)
  1070. {
  1071. if (rq->nr_running != 1)
  1072. return false;
  1073. if (p->sched_class != &fair_sched_class)
  1074. return false;
  1075. if (!task_on_rq_queued(p))
  1076. return false;
  1077. return true;
  1078. }
  1079. bool sched_can_stop_tick(struct rq *rq)
  1080. {
  1081. int fifo_nr_running;
  1082. /* Deadline tasks, even if single, need the tick */
  1083. if (rq->dl.dl_nr_running)
  1084. return false;
  1085. /*
  1086. * If there are more than one RR tasks, we need the tick to affect the
  1087. * actual RR behaviour.
  1088. */
  1089. if (rq->rt.rr_nr_running) {
  1090. if (rq->rt.rr_nr_running == 1)
  1091. return true;
  1092. else
  1093. return false;
  1094. }
  1095. /*
  1096. * If there's no RR tasks, but FIFO tasks, we can skip the tick, no
  1097. * forced preemption between FIFO tasks.
  1098. */
  1099. fifo_nr_running = rq->rt.rt_nr_running - rq->rt.rr_nr_running;
  1100. if (fifo_nr_running)
  1101. return true;
  1102. /*
  1103. * If there are no DL,RR/FIFO tasks, there must only be CFS or SCX tasks
  1104. * left. For CFS, if there's more than one we need the tick for
  1105. * involuntary preemption. For SCX, ask.
  1106. */
  1107. if (scx_enabled() && !scx_can_stop_tick(rq))
  1108. return false;
  1109. if (rq->cfs.h_nr_queued > 1)
  1110. return false;
  1111. /*
  1112. * If there is one task and it has CFS runtime bandwidth constraints
  1113. * and it's on the cpu now we don't want to stop the tick.
  1114. * This check prevents clearing the bit if a newly enqueued task here is
  1115. * dequeued by migrating while the constrained task continues to run.
  1116. * E.g. going from 2->1 without going through pick_next_task().
  1117. */
  1118. if (__need_bw_check(rq, rq->curr)) {
  1119. if (cfs_task_bw_constrained(rq->curr))
  1120. return false;
  1121. }
  1122. return true;
  1123. }
  1124. #endif /* CONFIG_NO_HZ_FULL */
  1125. #endif /* CONFIG_SMP */
  1126. #if defined(CONFIG_RT_GROUP_SCHED) || (defined(CONFIG_FAIR_GROUP_SCHED) && \
  1127. (defined(CONFIG_SMP) || defined(CONFIG_CFS_BANDWIDTH)))
  1128. /*
  1129. * Iterate task_group tree rooted at *from, calling @down when first entering a
  1130. * node and @up when leaving it for the final time.
  1131. *
  1132. * Caller must hold rcu_lock or sufficient equivalent.
  1133. */
  1134. int walk_tg_tree_from(struct task_group *from,
  1135. tg_visitor down, tg_visitor up, void *data)
  1136. {
  1137. struct task_group *parent, *child;
  1138. int ret;
  1139. parent = from;
  1140. down:
  1141. ret = (*down)(parent, data);
  1142. if (ret)
  1143. goto out;
  1144. list_for_each_entry_rcu(child, &parent->children, siblings) {
  1145. parent = child;
  1146. goto down;
  1147. up:
  1148. continue;
  1149. }
  1150. ret = (*up)(parent, data);
  1151. if (ret || parent == from)
  1152. goto out;
  1153. child = parent;
  1154. parent = parent->parent;
  1155. if (parent)
  1156. goto up;
  1157. out:
  1158. return ret;
  1159. }
  1160. int tg_nop(struct task_group *tg, void *data)
  1161. {
  1162. return 0;
  1163. }
  1164. #endif
  1165. void set_load_weight(struct task_struct *p, bool update_load)
  1166. {
  1167. int prio = p->static_prio - MAX_RT_PRIO;
  1168. struct load_weight lw;
  1169. if (task_has_idle_policy(p)) {
  1170. lw.weight = scale_load(WEIGHT_IDLEPRIO);
  1171. lw.inv_weight = WMULT_IDLEPRIO;
  1172. } else {
  1173. lw.weight = scale_load(sched_prio_to_weight[prio]);
  1174. lw.inv_weight = sched_prio_to_wmult[prio];
  1175. }
  1176. /*
  1177. * SCHED_OTHER tasks have to update their load when changing their
  1178. * weight
  1179. */
  1180. if (update_load && p->sched_class->reweight_task)
  1181. p->sched_class->reweight_task(task_rq(p), p, &lw);
  1182. else
  1183. p->se.load = lw;
  1184. }
  1185. #ifdef CONFIG_UCLAMP_TASK
  1186. /*
  1187. * Serializes updates of utilization clamp values
  1188. *
  1189. * The (slow-path) user-space triggers utilization clamp value updates which
  1190. * can require updates on (fast-path) scheduler's data structures used to
  1191. * support enqueue/dequeue operations.
  1192. * While the per-CPU rq lock protects fast-path update operations, user-space
  1193. * requests are serialized using a mutex to reduce the risk of conflicting
  1194. * updates or API abuses.
  1195. */
  1196. static DEFINE_MUTEX(uclamp_mutex);
  1197. /* Max allowed minimum utilization */
  1198. static unsigned int __maybe_unused sysctl_sched_uclamp_util_min = SCHED_CAPACITY_SCALE;
  1199. /* Max allowed maximum utilization */
  1200. static unsigned int __maybe_unused sysctl_sched_uclamp_util_max = SCHED_CAPACITY_SCALE;
  1201. /*
  1202. * By default RT tasks run at the maximum performance point/capacity of the
  1203. * system. Uclamp enforces this by always setting UCLAMP_MIN of RT tasks to
  1204. * SCHED_CAPACITY_SCALE.
  1205. *
  1206. * This knob allows admins to change the default behavior when uclamp is being
  1207. * used. In battery powered devices, particularly, running at the maximum
  1208. * capacity and frequency will increase energy consumption and shorten the
  1209. * battery life.
  1210. *
  1211. * This knob only affects RT tasks that their uclamp_se->user_defined == false.
  1212. *
  1213. * This knob will not override the system default sched_util_clamp_min defined
  1214. * above.
  1215. */
  1216. unsigned int sysctl_sched_uclamp_util_min_rt_default = SCHED_CAPACITY_SCALE;
  1217. /* All clamps are required to be less or equal than these values */
  1218. static struct uclamp_se uclamp_default[UCLAMP_CNT];
  1219. /*
  1220. * This static key is used to reduce the uclamp overhead in the fast path. It
  1221. * primarily disables the call to uclamp_rq_{inc, dec}() in
  1222. * enqueue/dequeue_task().
  1223. *
  1224. * This allows users to continue to enable uclamp in their kernel config with
  1225. * minimum uclamp overhead in the fast path.
  1226. *
  1227. * As soon as userspace modifies any of the uclamp knobs, the static key is
  1228. * enabled, since we have an actual users that make use of uclamp
  1229. * functionality.
  1230. *
  1231. * The knobs that would enable this static key are:
  1232. *
  1233. * * A task modifying its uclamp value with sched_setattr().
  1234. * * An admin modifying the sysctl_sched_uclamp_{min, max} via procfs.
  1235. * * An admin modifying the cgroup cpu.uclamp.{min, max}
  1236. */
  1237. DEFINE_STATIC_KEY_FALSE(sched_uclamp_used);
  1238. static inline unsigned int
  1239. uclamp_idle_value(struct rq *rq, enum uclamp_id clamp_id,
  1240. unsigned int clamp_value)
  1241. {
  1242. /*
  1243. * Avoid blocked utilization pushing up the frequency when we go
  1244. * idle (which drops the max-clamp) by retaining the last known
  1245. * max-clamp.
  1246. */
  1247. if (clamp_id == UCLAMP_MAX) {
  1248. rq->uclamp_flags |= UCLAMP_FLAG_IDLE;
  1249. return clamp_value;
  1250. }
  1251. return uclamp_none(UCLAMP_MIN);
  1252. }
  1253. static inline void uclamp_idle_reset(struct rq *rq, enum uclamp_id clamp_id,
  1254. unsigned int clamp_value)
  1255. {
  1256. /* Reset max-clamp retention only on idle exit */
  1257. if (!(rq->uclamp_flags & UCLAMP_FLAG_IDLE))
  1258. return;
  1259. uclamp_rq_set(rq, clamp_id, clamp_value);
  1260. }
  1261. static inline
  1262. unsigned int uclamp_rq_max_value(struct rq *rq, enum uclamp_id clamp_id,
  1263. unsigned int clamp_value)
  1264. {
  1265. struct uclamp_bucket *bucket = rq->uclamp[clamp_id].bucket;
  1266. int bucket_id = UCLAMP_BUCKETS - 1;
  1267. /*
  1268. * Since both min and max clamps are max aggregated, find the
  1269. * top most bucket with tasks in.
  1270. */
  1271. for ( ; bucket_id >= 0; bucket_id--) {
  1272. if (!bucket[bucket_id].tasks)
  1273. continue;
  1274. return bucket[bucket_id].value;
  1275. }
  1276. /* No tasks -- default clamp values */
  1277. return uclamp_idle_value(rq, clamp_id, clamp_value);
  1278. }
  1279. static void __uclamp_update_util_min_rt_default(struct task_struct *p)
  1280. {
  1281. unsigned int default_util_min;
  1282. struct uclamp_se *uc_se;
  1283. lockdep_assert_held(&p->pi_lock);
  1284. uc_se = &p->uclamp_req[UCLAMP_MIN];
  1285. /* Only sync if user didn't override the default */
  1286. if (uc_se->user_defined)
  1287. return;
  1288. default_util_min = sysctl_sched_uclamp_util_min_rt_default;
  1289. uclamp_se_set(uc_se, default_util_min, false);
  1290. }
  1291. static void uclamp_update_util_min_rt_default(struct task_struct *p)
  1292. {
  1293. if (!rt_task(p))
  1294. return;
  1295. /* Protect updates to p->uclamp_* */
  1296. guard(task_rq_lock)(p);
  1297. __uclamp_update_util_min_rt_default(p);
  1298. }
  1299. static inline struct uclamp_se
  1300. uclamp_tg_restrict(struct task_struct *p, enum uclamp_id clamp_id)
  1301. {
  1302. /* Copy by value as we could modify it */
  1303. struct uclamp_se uc_req = p->uclamp_req[clamp_id];
  1304. #ifdef CONFIG_UCLAMP_TASK_GROUP
  1305. unsigned int tg_min, tg_max, value;
  1306. /*
  1307. * Tasks in autogroups or root task group will be
  1308. * restricted by system defaults.
  1309. */
  1310. if (task_group_is_autogroup(task_group(p)))
  1311. return uc_req;
  1312. if (task_group(p) == &root_task_group)
  1313. return uc_req;
  1314. tg_min = task_group(p)->uclamp[UCLAMP_MIN].value;
  1315. tg_max = task_group(p)->uclamp[UCLAMP_MAX].value;
  1316. value = uc_req.value;
  1317. value = clamp(value, tg_min, tg_max);
  1318. uclamp_se_set(&uc_req, value, false);
  1319. #endif
  1320. return uc_req;
  1321. }
  1322. /*
  1323. * The effective clamp bucket index of a task depends on, by increasing
  1324. * priority:
  1325. * - the task specific clamp value, when explicitly requested from userspace
  1326. * - the task group effective clamp value, for tasks not either in the root
  1327. * group or in an autogroup
  1328. * - the system default clamp value, defined by the sysadmin
  1329. */
  1330. static inline struct uclamp_se
  1331. uclamp_eff_get(struct task_struct *p, enum uclamp_id clamp_id)
  1332. {
  1333. struct uclamp_se uc_req = uclamp_tg_restrict(p, clamp_id);
  1334. struct uclamp_se uc_max = uclamp_default[clamp_id];
  1335. /* System default restrictions always apply */
  1336. if (unlikely(uc_req.value > uc_max.value))
  1337. return uc_max;
  1338. return uc_req;
  1339. }
  1340. unsigned long uclamp_eff_value(struct task_struct *p, enum uclamp_id clamp_id)
  1341. {
  1342. struct uclamp_se uc_eff;
  1343. /* Task currently refcounted: use back-annotated (effective) value */
  1344. if (p->uclamp[clamp_id].active)
  1345. return (unsigned long)p->uclamp[clamp_id].value;
  1346. uc_eff = uclamp_eff_get(p, clamp_id);
  1347. return (unsigned long)uc_eff.value;
  1348. }
  1349. /*
  1350. * When a task is enqueued on a rq, the clamp bucket currently defined by the
  1351. * task's uclamp::bucket_id is refcounted on that rq. This also immediately
  1352. * updates the rq's clamp value if required.
  1353. *
  1354. * Tasks can have a task-specific value requested from user-space, track
  1355. * within each bucket the maximum value for tasks refcounted in it.
  1356. * This "local max aggregation" allows to track the exact "requested" value
  1357. * for each bucket when all its RUNNABLE tasks require the same clamp.
  1358. */
  1359. static inline void uclamp_rq_inc_id(struct rq *rq, struct task_struct *p,
  1360. enum uclamp_id clamp_id)
  1361. {
  1362. struct uclamp_rq *uc_rq = &rq->uclamp[clamp_id];
  1363. struct uclamp_se *uc_se = &p->uclamp[clamp_id];
  1364. struct uclamp_bucket *bucket;
  1365. lockdep_assert_rq_held(rq);
  1366. /* Update task effective clamp */
  1367. p->uclamp[clamp_id] = uclamp_eff_get(p, clamp_id);
  1368. bucket = &uc_rq->bucket[uc_se->bucket_id];
  1369. bucket->tasks++;
  1370. uc_se->active = true;
  1371. uclamp_idle_reset(rq, clamp_id, uc_se->value);
  1372. /*
  1373. * Local max aggregation: rq buckets always track the max
  1374. * "requested" clamp value of its RUNNABLE tasks.
  1375. */
  1376. if (bucket->tasks == 1 || uc_se->value > bucket->value)
  1377. bucket->value = uc_se->value;
  1378. if (uc_se->value > uclamp_rq_get(rq, clamp_id))
  1379. uclamp_rq_set(rq, clamp_id, uc_se->value);
  1380. }
  1381. /*
  1382. * When a task is dequeued from a rq, the clamp bucket refcounted by the task
  1383. * is released. If this is the last task reference counting the rq's max
  1384. * active clamp value, then the rq's clamp value is updated.
  1385. *
  1386. * Both refcounted tasks and rq's cached clamp values are expected to be
  1387. * always valid. If it's detected they are not, as defensive programming,
  1388. * enforce the expected state and warn.
  1389. */
  1390. static inline void uclamp_rq_dec_id(struct rq *rq, struct task_struct *p,
  1391. enum uclamp_id clamp_id)
  1392. {
  1393. struct uclamp_rq *uc_rq = &rq->uclamp[clamp_id];
  1394. struct uclamp_se *uc_se = &p->uclamp[clamp_id];
  1395. struct uclamp_bucket *bucket;
  1396. unsigned int bkt_clamp;
  1397. unsigned int rq_clamp;
  1398. lockdep_assert_rq_held(rq);
  1399. /*
  1400. * If sched_uclamp_used was enabled after task @p was enqueued,
  1401. * we could end up with unbalanced call to uclamp_rq_dec_id().
  1402. *
  1403. * In this case the uc_se->active flag should be false since no uclamp
  1404. * accounting was performed at enqueue time and we can just return
  1405. * here.
  1406. *
  1407. * Need to be careful of the following enqueue/dequeue ordering
  1408. * problem too
  1409. *
  1410. * enqueue(taskA)
  1411. * // sched_uclamp_used gets enabled
  1412. * enqueue(taskB)
  1413. * dequeue(taskA)
  1414. * // Must not decrement bucket->tasks here
  1415. * dequeue(taskB)
  1416. *
  1417. * where we could end up with stale data in uc_se and
  1418. * bucket[uc_se->bucket_id].
  1419. *
  1420. * The following check here eliminates the possibility of such race.
  1421. */
  1422. if (unlikely(!uc_se->active))
  1423. return;
  1424. bucket = &uc_rq->bucket[uc_se->bucket_id];
  1425. SCHED_WARN_ON(!bucket->tasks);
  1426. if (likely(bucket->tasks))
  1427. bucket->tasks--;
  1428. uc_se->active = false;
  1429. /*
  1430. * Keep "local max aggregation" simple and accept to (possibly)
  1431. * overboost some RUNNABLE tasks in the same bucket.
  1432. * The rq clamp bucket value is reset to its base value whenever
  1433. * there are no more RUNNABLE tasks refcounting it.
  1434. */
  1435. if (likely(bucket->tasks))
  1436. return;
  1437. rq_clamp = uclamp_rq_get(rq, clamp_id);
  1438. /*
  1439. * Defensive programming: this should never happen. If it happens,
  1440. * e.g. due to future modification, warn and fix up the expected value.
  1441. */
  1442. SCHED_WARN_ON(bucket->value > rq_clamp);
  1443. if (bucket->value >= rq_clamp) {
  1444. bkt_clamp = uclamp_rq_max_value(rq, clamp_id, uc_se->value);
  1445. uclamp_rq_set(rq, clamp_id, bkt_clamp);
  1446. }
  1447. }
  1448. static inline void uclamp_rq_inc(struct rq *rq, struct task_struct *p)
  1449. {
  1450. enum uclamp_id clamp_id;
  1451. /*
  1452. * Avoid any overhead until uclamp is actually used by the userspace.
  1453. *
  1454. * The condition is constructed such that a NOP is generated when
  1455. * sched_uclamp_used is disabled.
  1456. */
  1457. if (!static_branch_unlikely(&sched_uclamp_used))
  1458. return;
  1459. if (unlikely(!p->sched_class->uclamp_enabled))
  1460. return;
  1461. if (p->se.sched_delayed)
  1462. return;
  1463. for_each_clamp_id(clamp_id)
  1464. uclamp_rq_inc_id(rq, p, clamp_id);
  1465. /* Reset clamp idle holding when there is one RUNNABLE task */
  1466. if (rq->uclamp_flags & UCLAMP_FLAG_IDLE)
  1467. rq->uclamp_flags &= ~UCLAMP_FLAG_IDLE;
  1468. }
  1469. static inline void uclamp_rq_dec(struct rq *rq, struct task_struct *p)
  1470. {
  1471. enum uclamp_id clamp_id;
  1472. /*
  1473. * Avoid any overhead until uclamp is actually used by the userspace.
  1474. *
  1475. * The condition is constructed such that a NOP is generated when
  1476. * sched_uclamp_used is disabled.
  1477. */
  1478. if (!static_branch_unlikely(&sched_uclamp_used))
  1479. return;
  1480. if (unlikely(!p->sched_class->uclamp_enabled))
  1481. return;
  1482. if (p->se.sched_delayed)
  1483. return;
  1484. for_each_clamp_id(clamp_id)
  1485. uclamp_rq_dec_id(rq, p, clamp_id);
  1486. }
  1487. static inline void uclamp_rq_reinc_id(struct rq *rq, struct task_struct *p,
  1488. enum uclamp_id clamp_id)
  1489. {
  1490. if (!p->uclamp[clamp_id].active)
  1491. return;
  1492. uclamp_rq_dec_id(rq, p, clamp_id);
  1493. uclamp_rq_inc_id(rq, p, clamp_id);
  1494. /*
  1495. * Make sure to clear the idle flag if we've transiently reached 0
  1496. * active tasks on rq.
  1497. */
  1498. if (clamp_id == UCLAMP_MAX && (rq->uclamp_flags & UCLAMP_FLAG_IDLE))
  1499. rq->uclamp_flags &= ~UCLAMP_FLAG_IDLE;
  1500. }
  1501. static inline void
  1502. uclamp_update_active(struct task_struct *p)
  1503. {
  1504. enum uclamp_id clamp_id;
  1505. struct rq_flags rf;
  1506. struct rq *rq;
  1507. /*
  1508. * Lock the task and the rq where the task is (or was) queued.
  1509. *
  1510. * We might lock the (previous) rq of a !RUNNABLE task, but that's the
  1511. * price to pay to safely serialize util_{min,max} updates with
  1512. * enqueues, dequeues and migration operations.
  1513. * This is the same locking schema used by __set_cpus_allowed_ptr().
  1514. */
  1515. rq = task_rq_lock(p, &rf);
  1516. /*
  1517. * Setting the clamp bucket is serialized by task_rq_lock().
  1518. * If the task is not yet RUNNABLE and its task_struct is not
  1519. * affecting a valid clamp bucket, the next time it's enqueued,
  1520. * it will already see the updated clamp bucket value.
  1521. */
  1522. for_each_clamp_id(clamp_id)
  1523. uclamp_rq_reinc_id(rq, p, clamp_id);
  1524. task_rq_unlock(rq, p, &rf);
  1525. }
  1526. #ifdef CONFIG_UCLAMP_TASK_GROUP
  1527. static inline void
  1528. uclamp_update_active_tasks(struct cgroup_subsys_state *css)
  1529. {
  1530. struct css_task_iter it;
  1531. struct task_struct *p;
  1532. css_task_iter_start(css, 0, &it);
  1533. while ((p = css_task_iter_next(&it)))
  1534. uclamp_update_active(p);
  1535. css_task_iter_end(&it);
  1536. }
  1537. static void cpu_util_update_eff(struct cgroup_subsys_state *css);
  1538. #endif
  1539. #ifdef CONFIG_SYSCTL
  1540. #ifdef CONFIG_UCLAMP_TASK_GROUP
  1541. static void uclamp_update_root_tg(void)
  1542. {
  1543. struct task_group *tg = &root_task_group;
  1544. uclamp_se_set(&tg->uclamp_req[UCLAMP_MIN],
  1545. sysctl_sched_uclamp_util_min, false);
  1546. uclamp_se_set(&tg->uclamp_req[UCLAMP_MAX],
  1547. sysctl_sched_uclamp_util_max, false);
  1548. guard(rcu)();
  1549. cpu_util_update_eff(&root_task_group.css);
  1550. }
  1551. #else
  1552. static void uclamp_update_root_tg(void) { }
  1553. #endif
  1554. static void uclamp_sync_util_min_rt_default(void)
  1555. {
  1556. struct task_struct *g, *p;
  1557. /*
  1558. * copy_process() sysctl_uclamp
  1559. * uclamp_min_rt = X;
  1560. * write_lock(&tasklist_lock) read_lock(&tasklist_lock)
  1561. * // link thread smp_mb__after_spinlock()
  1562. * write_unlock(&tasklist_lock) read_unlock(&tasklist_lock);
  1563. * sched_post_fork() for_each_process_thread()
  1564. * __uclamp_sync_rt() __uclamp_sync_rt()
  1565. *
  1566. * Ensures that either sched_post_fork() will observe the new
  1567. * uclamp_min_rt or for_each_process_thread() will observe the new
  1568. * task.
  1569. */
  1570. read_lock(&tasklist_lock);
  1571. smp_mb__after_spinlock();
  1572. read_unlock(&tasklist_lock);
  1573. guard(rcu)();
  1574. for_each_process_thread(g, p)
  1575. uclamp_update_util_min_rt_default(p);
  1576. }
  1577. static int sysctl_sched_uclamp_handler(const struct ctl_table *table, int write,
  1578. void *buffer, size_t *lenp, loff_t *ppos)
  1579. {
  1580. bool update_root_tg = false;
  1581. int old_min, old_max, old_min_rt;
  1582. int result;
  1583. guard(mutex)(&uclamp_mutex);
  1584. old_min = sysctl_sched_uclamp_util_min;
  1585. old_max = sysctl_sched_uclamp_util_max;
  1586. old_min_rt = sysctl_sched_uclamp_util_min_rt_default;
  1587. result = proc_dointvec(table, write, buffer, lenp, ppos);
  1588. if (result)
  1589. goto undo;
  1590. if (!write)
  1591. return 0;
  1592. if (sysctl_sched_uclamp_util_min > sysctl_sched_uclamp_util_max ||
  1593. sysctl_sched_uclamp_util_max > SCHED_CAPACITY_SCALE ||
  1594. sysctl_sched_uclamp_util_min_rt_default > SCHED_CAPACITY_SCALE) {
  1595. result = -EINVAL;
  1596. goto undo;
  1597. }
  1598. if (old_min != sysctl_sched_uclamp_util_min) {
  1599. uclamp_se_set(&uclamp_default[UCLAMP_MIN],
  1600. sysctl_sched_uclamp_util_min, false);
  1601. update_root_tg = true;
  1602. }
  1603. if (old_max != sysctl_sched_uclamp_util_max) {
  1604. uclamp_se_set(&uclamp_default[UCLAMP_MAX],
  1605. sysctl_sched_uclamp_util_max, false);
  1606. update_root_tg = true;
  1607. }
  1608. if (update_root_tg) {
  1609. static_branch_enable(&sched_uclamp_used);
  1610. uclamp_update_root_tg();
  1611. }
  1612. if (old_min_rt != sysctl_sched_uclamp_util_min_rt_default) {
  1613. static_branch_enable(&sched_uclamp_used);
  1614. uclamp_sync_util_min_rt_default();
  1615. }
  1616. /*
  1617. * We update all RUNNABLE tasks only when task groups are in use.
  1618. * Otherwise, keep it simple and do just a lazy update at each next
  1619. * task enqueue time.
  1620. */
  1621. return 0;
  1622. undo:
  1623. sysctl_sched_uclamp_util_min = old_min;
  1624. sysctl_sched_uclamp_util_max = old_max;
  1625. sysctl_sched_uclamp_util_min_rt_default = old_min_rt;
  1626. return result;
  1627. }
  1628. #endif
  1629. static void uclamp_fork(struct task_struct *p)
  1630. {
  1631. enum uclamp_id clamp_id;
  1632. /*
  1633. * We don't need to hold task_rq_lock() when updating p->uclamp_* here
  1634. * as the task is still at its early fork stages.
  1635. */
  1636. for_each_clamp_id(clamp_id)
  1637. p->uclamp[clamp_id].active = false;
  1638. if (likely(!p->sched_reset_on_fork))
  1639. return;
  1640. for_each_clamp_id(clamp_id) {
  1641. uclamp_se_set(&p->uclamp_req[clamp_id],
  1642. uclamp_none(clamp_id), false);
  1643. }
  1644. }
  1645. static void uclamp_post_fork(struct task_struct *p)
  1646. {
  1647. uclamp_update_util_min_rt_default(p);
  1648. }
  1649. static void __init init_uclamp_rq(struct rq *rq)
  1650. {
  1651. enum uclamp_id clamp_id;
  1652. struct uclamp_rq *uc_rq = rq->uclamp;
  1653. for_each_clamp_id(clamp_id) {
  1654. uc_rq[clamp_id] = (struct uclamp_rq) {
  1655. .value = uclamp_none(clamp_id)
  1656. };
  1657. }
  1658. rq->uclamp_flags = UCLAMP_FLAG_IDLE;
  1659. }
  1660. static void __init init_uclamp(void)
  1661. {
  1662. struct uclamp_se uc_max = {};
  1663. enum uclamp_id clamp_id;
  1664. int cpu;
  1665. for_each_possible_cpu(cpu)
  1666. init_uclamp_rq(cpu_rq(cpu));
  1667. for_each_clamp_id(clamp_id) {
  1668. uclamp_se_set(&init_task.uclamp_req[clamp_id],
  1669. uclamp_none(clamp_id), false);
  1670. }
  1671. /* System defaults allow max clamp values for both indexes */
  1672. uclamp_se_set(&uc_max, uclamp_none(UCLAMP_MAX), false);
  1673. for_each_clamp_id(clamp_id) {
  1674. uclamp_default[clamp_id] = uc_max;
  1675. #ifdef CONFIG_UCLAMP_TASK_GROUP
  1676. root_task_group.uclamp_req[clamp_id] = uc_max;
  1677. root_task_group.uclamp[clamp_id] = uc_max;
  1678. #endif
  1679. }
  1680. }
  1681. #else /* !CONFIG_UCLAMP_TASK */
  1682. static inline void uclamp_rq_inc(struct rq *rq, struct task_struct *p) { }
  1683. static inline void uclamp_rq_dec(struct rq *rq, struct task_struct *p) { }
  1684. static inline void uclamp_fork(struct task_struct *p) { }
  1685. static inline void uclamp_post_fork(struct task_struct *p) { }
  1686. static inline void init_uclamp(void) { }
  1687. #endif /* CONFIG_UCLAMP_TASK */
  1688. bool sched_task_on_rq(struct task_struct *p)
  1689. {
  1690. return task_on_rq_queued(p);
  1691. }
  1692. unsigned long get_wchan(struct task_struct *p)
  1693. {
  1694. unsigned long ip = 0;
  1695. unsigned int state;
  1696. if (!p || p == current)
  1697. return 0;
  1698. /* Only get wchan if task is blocked and we can keep it that way. */
  1699. raw_spin_lock_irq(&p->pi_lock);
  1700. state = READ_ONCE(p->__state);
  1701. smp_rmb(); /* see try_to_wake_up() */
  1702. if (state != TASK_RUNNING && state != TASK_WAKING && !p->on_rq)
  1703. ip = __get_wchan(p);
  1704. raw_spin_unlock_irq(&p->pi_lock);
  1705. return ip;
  1706. }
  1707. void enqueue_task(struct rq *rq, struct task_struct *p, int flags)
  1708. {
  1709. if (!(flags & ENQUEUE_NOCLOCK))
  1710. update_rq_clock(rq);
  1711. p->sched_class->enqueue_task(rq, p, flags);
  1712. /*
  1713. * Must be after ->enqueue_task() because ENQUEUE_DELAYED can clear
  1714. * ->sched_delayed.
  1715. */
  1716. uclamp_rq_inc(rq, p);
  1717. psi_enqueue(p, flags);
  1718. if (!(flags & ENQUEUE_RESTORE))
  1719. sched_info_enqueue(rq, p);
  1720. if (sched_core_enabled(rq))
  1721. sched_core_enqueue(rq, p);
  1722. }
  1723. /*
  1724. * Must only return false when DEQUEUE_SLEEP.
  1725. */
  1726. inline bool dequeue_task(struct rq *rq, struct task_struct *p, int flags)
  1727. {
  1728. if (sched_core_enabled(rq))
  1729. sched_core_dequeue(rq, p, flags);
  1730. if (!(flags & DEQUEUE_NOCLOCK))
  1731. update_rq_clock(rq);
  1732. if (!(flags & DEQUEUE_SAVE))
  1733. sched_info_dequeue(rq, p);
  1734. psi_dequeue(p, flags);
  1735. /*
  1736. * Must be before ->dequeue_task() because ->dequeue_task() can 'fail'
  1737. * and mark the task ->sched_delayed.
  1738. */
  1739. uclamp_rq_dec(rq, p);
  1740. return p->sched_class->dequeue_task(rq, p, flags);
  1741. }
  1742. void activate_task(struct rq *rq, struct task_struct *p, int flags)
  1743. {
  1744. if (task_on_rq_migrating(p))
  1745. flags |= ENQUEUE_MIGRATED;
  1746. if (flags & ENQUEUE_MIGRATED)
  1747. sched_mm_cid_migrate_to(rq, p);
  1748. enqueue_task(rq, p, flags);
  1749. WRITE_ONCE(p->on_rq, TASK_ON_RQ_QUEUED);
  1750. ASSERT_EXCLUSIVE_WRITER(p->on_rq);
  1751. }
  1752. void deactivate_task(struct rq *rq, struct task_struct *p, int flags)
  1753. {
  1754. SCHED_WARN_ON(flags & DEQUEUE_SLEEP);
  1755. WRITE_ONCE(p->on_rq, TASK_ON_RQ_MIGRATING);
  1756. ASSERT_EXCLUSIVE_WRITER(p->on_rq);
  1757. /*
  1758. * Code explicitly relies on TASK_ON_RQ_MIGRATING begin set *before*
  1759. * dequeue_task() and cleared *after* enqueue_task().
  1760. */
  1761. dequeue_task(rq, p, flags);
  1762. }
  1763. static void block_task(struct rq *rq, struct task_struct *p, int flags)
  1764. {
  1765. if (dequeue_task(rq, p, DEQUEUE_SLEEP | flags))
  1766. __block_task(rq, p);
  1767. }
  1768. /**
  1769. * task_curr - is this task currently executing on a CPU?
  1770. * @p: the task in question.
  1771. *
  1772. * Return: 1 if the task is currently executing. 0 otherwise.
  1773. */
  1774. inline int task_curr(const struct task_struct *p)
  1775. {
  1776. return cpu_curr(task_cpu(p)) == p;
  1777. }
  1778. /*
  1779. * ->switching_to() is called with the pi_lock and rq_lock held and must not
  1780. * mess with locking.
  1781. */
  1782. void check_class_changing(struct rq *rq, struct task_struct *p,
  1783. const struct sched_class *prev_class)
  1784. {
  1785. if (prev_class != p->sched_class && p->sched_class->switching_to)
  1786. p->sched_class->switching_to(rq, p);
  1787. }
  1788. /*
  1789. * switched_from, switched_to and prio_changed must _NOT_ drop rq->lock,
  1790. * use the balance_callback list if you want balancing.
  1791. *
  1792. * this means any call to check_class_changed() must be followed by a call to
  1793. * balance_callback().
  1794. */
  1795. void check_class_changed(struct rq *rq, struct task_struct *p,
  1796. const struct sched_class *prev_class,
  1797. int oldprio)
  1798. {
  1799. if (prev_class != p->sched_class) {
  1800. if (prev_class->switched_from)
  1801. prev_class->switched_from(rq, p);
  1802. p->sched_class->switched_to(rq, p);
  1803. } else if (oldprio != p->prio || dl_task(p))
  1804. p->sched_class->prio_changed(rq, p, oldprio);
  1805. }
  1806. void wakeup_preempt(struct rq *rq, struct task_struct *p, int flags)
  1807. {
  1808. if (p->sched_class == rq->curr->sched_class)
  1809. rq->curr->sched_class->wakeup_preempt(rq, p, flags);
  1810. else if (sched_class_above(p->sched_class, rq->curr->sched_class))
  1811. resched_curr(rq);
  1812. /*
  1813. * A queue event has occurred, and we're going to schedule. In
  1814. * this case, we can save a useless back to back clock update.
  1815. */
  1816. if (task_on_rq_queued(rq->curr) && test_tsk_need_resched(rq->curr))
  1817. rq_clock_skip_update(rq);
  1818. }
  1819. static __always_inline
  1820. int __task_state_match(struct task_struct *p, unsigned int state)
  1821. {
  1822. if (READ_ONCE(p->__state) & state)
  1823. return 1;
  1824. if (READ_ONCE(p->saved_state) & state)
  1825. return -1;
  1826. return 0;
  1827. }
  1828. static __always_inline
  1829. int task_state_match(struct task_struct *p, unsigned int state)
  1830. {
  1831. /*
  1832. * Serialize against current_save_and_set_rtlock_wait_state(),
  1833. * current_restore_rtlock_saved_state(), and __refrigerator().
  1834. */
  1835. guard(raw_spinlock_irq)(&p->pi_lock);
  1836. return __task_state_match(p, state);
  1837. }
  1838. /*
  1839. * wait_task_inactive - wait for a thread to unschedule.
  1840. *
  1841. * Wait for the thread to block in any of the states set in @match_state.
  1842. * If it changes, i.e. @p might have woken up, then return zero. When we
  1843. * succeed in waiting for @p to be off its CPU, we return a positive number
  1844. * (its total switch count). If a second call a short while later returns the
  1845. * same number, the caller can be sure that @p has remained unscheduled the
  1846. * whole time.
  1847. *
  1848. * The caller must ensure that the task *will* unschedule sometime soon,
  1849. * else this function might spin for a *long* time. This function can't
  1850. * be called with interrupts off, or it may introduce deadlock with
  1851. * smp_call_function() if an IPI is sent by the same process we are
  1852. * waiting to become inactive.
  1853. */
  1854. unsigned long wait_task_inactive(struct task_struct *p, unsigned int match_state)
  1855. {
  1856. int running, queued, match;
  1857. struct rq_flags rf;
  1858. unsigned long ncsw;
  1859. struct rq *rq;
  1860. for (;;) {
  1861. /*
  1862. * We do the initial early heuristics without holding
  1863. * any task-queue locks at all. We'll only try to get
  1864. * the runqueue lock when things look like they will
  1865. * work out!
  1866. */
  1867. rq = task_rq(p);
  1868. /*
  1869. * If the task is actively running on another CPU
  1870. * still, just relax and busy-wait without holding
  1871. * any locks.
  1872. *
  1873. * NOTE! Since we don't hold any locks, it's not
  1874. * even sure that "rq" stays as the right runqueue!
  1875. * But we don't care, since "task_on_cpu()" will
  1876. * return false if the runqueue has changed and p
  1877. * is actually now running somewhere else!
  1878. */
  1879. while (task_on_cpu(rq, p)) {
  1880. if (!task_state_match(p, match_state))
  1881. return 0;
  1882. cpu_relax();
  1883. }
  1884. /*
  1885. * Ok, time to look more closely! We need the rq
  1886. * lock now, to be *sure*. If we're wrong, we'll
  1887. * just go back and repeat.
  1888. */
  1889. rq = task_rq_lock(p, &rf);
  1890. /*
  1891. * If task is sched_delayed, force dequeue it, to avoid always
  1892. * hitting the tick timeout in the queued case
  1893. */
  1894. if (p->se.sched_delayed)
  1895. dequeue_task(rq, p, DEQUEUE_SLEEP | DEQUEUE_DELAYED);
  1896. trace_sched_wait_task(p);
  1897. running = task_on_cpu(rq, p);
  1898. queued = task_on_rq_queued(p);
  1899. ncsw = 0;
  1900. if ((match = __task_state_match(p, match_state))) {
  1901. /*
  1902. * When matching on p->saved_state, consider this task
  1903. * still queued so it will wait.
  1904. */
  1905. if (match < 0)
  1906. queued = 1;
  1907. ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
  1908. }
  1909. task_rq_unlock(rq, p, &rf);
  1910. /*
  1911. * If it changed from the expected state, bail out now.
  1912. */
  1913. if (unlikely(!ncsw))
  1914. break;
  1915. /*
  1916. * Was it really running after all now that we
  1917. * checked with the proper locks actually held?
  1918. *
  1919. * Oops. Go back and try again..
  1920. */
  1921. if (unlikely(running)) {
  1922. cpu_relax();
  1923. continue;
  1924. }
  1925. /*
  1926. * It's not enough that it's not actively running,
  1927. * it must be off the runqueue _entirely_, and not
  1928. * preempted!
  1929. *
  1930. * So if it was still runnable (but just not actively
  1931. * running right now), it's preempted, and we should
  1932. * yield - it could be a while.
  1933. */
  1934. if (unlikely(queued)) {
  1935. ktime_t to = NSEC_PER_SEC / HZ;
  1936. set_current_state(TASK_UNINTERRUPTIBLE);
  1937. schedule_hrtimeout(&to, HRTIMER_MODE_REL_HARD);
  1938. continue;
  1939. }
  1940. /*
  1941. * Ahh, all good. It wasn't running, and it wasn't
  1942. * runnable, which means that it will never become
  1943. * running in the future either. We're all done!
  1944. */
  1945. break;
  1946. }
  1947. return ncsw;
  1948. }
  1949. #ifdef CONFIG_SMP
  1950. static void
  1951. __do_set_cpus_allowed(struct task_struct *p, struct affinity_context *ctx);
  1952. static void migrate_disable_switch(struct rq *rq, struct task_struct *p)
  1953. {
  1954. struct affinity_context ac = {
  1955. .new_mask = cpumask_of(rq->cpu),
  1956. .flags = SCA_MIGRATE_DISABLE,
  1957. };
  1958. if (likely(!p->migration_disabled))
  1959. return;
  1960. if (p->cpus_ptr != &p->cpus_mask)
  1961. return;
  1962. /*
  1963. * Violates locking rules! See comment in __do_set_cpus_allowed().
  1964. */
  1965. __do_set_cpus_allowed(p, &ac);
  1966. }
  1967. void migrate_disable(void)
  1968. {
  1969. struct task_struct *p = current;
  1970. if (p->migration_disabled) {
  1971. #ifdef CONFIG_DEBUG_PREEMPT
  1972. /*
  1973. *Warn about overflow half-way through the range.
  1974. */
  1975. WARN_ON_ONCE((s16)p->migration_disabled < 0);
  1976. #endif
  1977. p->migration_disabled++;
  1978. return;
  1979. }
  1980. guard(preempt)();
  1981. this_rq()->nr_pinned++;
  1982. p->migration_disabled = 1;
  1983. }
  1984. EXPORT_SYMBOL_GPL(migrate_disable);
  1985. void migrate_enable(void)
  1986. {
  1987. struct task_struct *p = current;
  1988. struct affinity_context ac = {
  1989. .new_mask = &p->cpus_mask,
  1990. .flags = SCA_MIGRATE_ENABLE,
  1991. };
  1992. #ifdef CONFIG_DEBUG_PREEMPT
  1993. /*
  1994. * Check both overflow from migrate_disable() and superfluous
  1995. * migrate_enable().
  1996. */
  1997. if (WARN_ON_ONCE((s16)p->migration_disabled <= 0))
  1998. return;
  1999. #endif
  2000. if (p->migration_disabled > 1) {
  2001. p->migration_disabled--;
  2002. return;
  2003. }
  2004. /*
  2005. * Ensure stop_task runs either before or after this, and that
  2006. * __set_cpus_allowed_ptr(SCA_MIGRATE_ENABLE) doesn't schedule().
  2007. */
  2008. guard(preempt)();
  2009. if (p->cpus_ptr != &p->cpus_mask)
  2010. __set_cpus_allowed_ptr(p, &ac);
  2011. /*
  2012. * Mustn't clear migration_disabled() until cpus_ptr points back at the
  2013. * regular cpus_mask, otherwise things that race (eg.
  2014. * select_fallback_rq) get confused.
  2015. */
  2016. barrier();
  2017. p->migration_disabled = 0;
  2018. this_rq()->nr_pinned--;
  2019. }
  2020. EXPORT_SYMBOL_GPL(migrate_enable);
  2021. static inline bool rq_has_pinned_tasks(struct rq *rq)
  2022. {
  2023. return rq->nr_pinned;
  2024. }
  2025. /*
  2026. * Per-CPU kthreads are allowed to run on !active && online CPUs, see
  2027. * __set_cpus_allowed_ptr() and select_fallback_rq().
  2028. */
  2029. static inline bool is_cpu_allowed(struct task_struct *p, int cpu)
  2030. {
  2031. /* When not in the task's cpumask, no point in looking further. */
  2032. if (!task_allowed_on_cpu(p, cpu))
  2033. return false;
  2034. /* migrate_disabled() must be allowed to finish. */
  2035. if (is_migration_disabled(p))
  2036. return cpu_online(cpu);
  2037. /* Non kernel threads are not allowed during either online or offline. */
  2038. if (!(p->flags & PF_KTHREAD))
  2039. return cpu_active(cpu);
  2040. /* KTHREAD_IS_PER_CPU is always allowed. */
  2041. if (kthread_is_per_cpu(p))
  2042. return cpu_online(cpu);
  2043. /* Regular kernel threads don't get to stay during offline. */
  2044. if (cpu_dying(cpu))
  2045. return false;
  2046. /* But are allowed during online. */
  2047. return cpu_online(cpu);
  2048. }
  2049. /*
  2050. * This is how migration works:
  2051. *
  2052. * 1) we invoke migration_cpu_stop() on the target CPU using
  2053. * stop_one_cpu().
  2054. * 2) stopper starts to run (implicitly forcing the migrated thread
  2055. * off the CPU)
  2056. * 3) it checks whether the migrated task is still in the wrong runqueue.
  2057. * 4) if it's in the wrong runqueue then the migration thread removes
  2058. * it and puts it into the right queue.
  2059. * 5) stopper completes and stop_one_cpu() returns and the migration
  2060. * is done.
  2061. */
  2062. /*
  2063. * move_queued_task - move a queued task to new rq.
  2064. *
  2065. * Returns (locked) new rq. Old rq's lock is released.
  2066. */
  2067. static struct rq *move_queued_task(struct rq *rq, struct rq_flags *rf,
  2068. struct task_struct *p, int new_cpu)
  2069. {
  2070. lockdep_assert_rq_held(rq);
  2071. deactivate_task(rq, p, DEQUEUE_NOCLOCK);
  2072. set_task_cpu(p, new_cpu);
  2073. rq_unlock(rq, rf);
  2074. rq = cpu_rq(new_cpu);
  2075. rq_lock(rq, rf);
  2076. WARN_ON_ONCE(task_cpu(p) != new_cpu);
  2077. activate_task(rq, p, 0);
  2078. wakeup_preempt(rq, p, 0);
  2079. return rq;
  2080. }
  2081. struct migration_arg {
  2082. struct task_struct *task;
  2083. int dest_cpu;
  2084. struct set_affinity_pending *pending;
  2085. };
  2086. /*
  2087. * @refs: number of wait_for_completion()
  2088. * @stop_pending: is @stop_work in use
  2089. */
  2090. struct set_affinity_pending {
  2091. refcount_t refs;
  2092. unsigned int stop_pending;
  2093. struct completion done;
  2094. struct cpu_stop_work stop_work;
  2095. struct migration_arg arg;
  2096. };
  2097. /*
  2098. * Move (not current) task off this CPU, onto the destination CPU. We're doing
  2099. * this because either it can't run here any more (set_cpus_allowed()
  2100. * away from this CPU, or CPU going down), or because we're
  2101. * attempting to rebalance this task on exec (sched_exec).
  2102. *
  2103. * So we race with normal scheduler movements, but that's OK, as long
  2104. * as the task is no longer on this CPU.
  2105. */
  2106. static struct rq *__migrate_task(struct rq *rq, struct rq_flags *rf,
  2107. struct task_struct *p, int dest_cpu)
  2108. {
  2109. /* Affinity changed (again). */
  2110. if (!is_cpu_allowed(p, dest_cpu))
  2111. return rq;
  2112. rq = move_queued_task(rq, rf, p, dest_cpu);
  2113. return rq;
  2114. }
  2115. /*
  2116. * migration_cpu_stop - this will be executed by a high-prio stopper thread
  2117. * and performs thread migration by bumping thread off CPU then
  2118. * 'pushing' onto another runqueue.
  2119. */
  2120. static int migration_cpu_stop(void *data)
  2121. {
  2122. struct migration_arg *arg = data;
  2123. struct set_affinity_pending *pending = arg->pending;
  2124. struct task_struct *p = arg->task;
  2125. struct rq *rq = this_rq();
  2126. bool complete = false;
  2127. struct rq_flags rf;
  2128. /*
  2129. * The original target CPU might have gone down and we might
  2130. * be on another CPU but it doesn't matter.
  2131. */
  2132. local_irq_save(rf.flags);
  2133. /*
  2134. * We need to explicitly wake pending tasks before running
  2135. * __migrate_task() such that we will not miss enforcing cpus_ptr
  2136. * during wakeups, see set_cpus_allowed_ptr()'s TASK_WAKING test.
  2137. */
  2138. flush_smp_call_function_queue();
  2139. raw_spin_lock(&p->pi_lock);
  2140. rq_lock(rq, &rf);
  2141. /*
  2142. * If we were passed a pending, then ->stop_pending was set, thus
  2143. * p->migration_pending must have remained stable.
  2144. */
  2145. WARN_ON_ONCE(pending && pending != p->migration_pending);
  2146. /*
  2147. * If task_rq(p) != rq, it cannot be migrated here, because we're
  2148. * holding rq->lock, if p->on_rq == 0 it cannot get enqueued because
  2149. * we're holding p->pi_lock.
  2150. */
  2151. if (task_rq(p) == rq) {
  2152. if (is_migration_disabled(p))
  2153. goto out;
  2154. if (pending) {
  2155. p->migration_pending = NULL;
  2156. complete = true;
  2157. if (cpumask_test_cpu(task_cpu(p), &p->cpus_mask))
  2158. goto out;
  2159. }
  2160. if (task_on_rq_queued(p)) {
  2161. update_rq_clock(rq);
  2162. rq = __migrate_task(rq, &rf, p, arg->dest_cpu);
  2163. } else {
  2164. p->wake_cpu = arg->dest_cpu;
  2165. }
  2166. /*
  2167. * XXX __migrate_task() can fail, at which point we might end
  2168. * up running on a dodgy CPU, AFAICT this can only happen
  2169. * during CPU hotplug, at which point we'll get pushed out
  2170. * anyway, so it's probably not a big deal.
  2171. */
  2172. } else if (pending) {
  2173. /*
  2174. * This happens when we get migrated between migrate_enable()'s
  2175. * preempt_enable() and scheduling the stopper task. At that
  2176. * point we're a regular task again and not current anymore.
  2177. *
  2178. * A !PREEMPT kernel has a giant hole here, which makes it far
  2179. * more likely.
  2180. */
  2181. /*
  2182. * The task moved before the stopper got to run. We're holding
  2183. * ->pi_lock, so the allowed mask is stable - if it got
  2184. * somewhere allowed, we're done.
  2185. */
  2186. if (cpumask_test_cpu(task_cpu(p), p->cpus_ptr)) {
  2187. p->migration_pending = NULL;
  2188. complete = true;
  2189. goto out;
  2190. }
  2191. /*
  2192. * When migrate_enable() hits a rq mis-match we can't reliably
  2193. * determine is_migration_disabled() and so have to chase after
  2194. * it.
  2195. */
  2196. WARN_ON_ONCE(!pending->stop_pending);
  2197. preempt_disable();
  2198. task_rq_unlock(rq, p, &rf);
  2199. stop_one_cpu_nowait(task_cpu(p), migration_cpu_stop,
  2200. &pending->arg, &pending->stop_work);
  2201. preempt_enable();
  2202. return 0;
  2203. }
  2204. out:
  2205. if (pending)
  2206. pending->stop_pending = false;
  2207. task_rq_unlock(rq, p, &rf);
  2208. if (complete)
  2209. complete_all(&pending->done);
  2210. return 0;
  2211. }
  2212. int push_cpu_stop(void *arg)
  2213. {
  2214. struct rq *lowest_rq = NULL, *rq = this_rq();
  2215. struct task_struct *p = arg;
  2216. raw_spin_lock_irq(&p->pi_lock);
  2217. raw_spin_rq_lock(rq);
  2218. if (task_rq(p) != rq)
  2219. goto out_unlock;
  2220. if (is_migration_disabled(p)) {
  2221. p->migration_flags |= MDF_PUSH;
  2222. goto out_unlock;
  2223. }
  2224. p->migration_flags &= ~MDF_PUSH;
  2225. if (p->sched_class->find_lock_rq)
  2226. lowest_rq = p->sched_class->find_lock_rq(p, rq);
  2227. if (!lowest_rq)
  2228. goto out_unlock;
  2229. // XXX validate p is still the highest prio task
  2230. if (task_rq(p) == rq) {
  2231. deactivate_task(rq, p, 0);
  2232. set_task_cpu(p, lowest_rq->cpu);
  2233. activate_task(lowest_rq, p, 0);
  2234. resched_curr(lowest_rq);
  2235. }
  2236. double_unlock_balance(rq, lowest_rq);
  2237. out_unlock:
  2238. rq->push_busy = false;
  2239. raw_spin_rq_unlock(rq);
  2240. raw_spin_unlock_irq(&p->pi_lock);
  2241. put_task_struct(p);
  2242. return 0;
  2243. }
  2244. /*
  2245. * sched_class::set_cpus_allowed must do the below, but is not required to
  2246. * actually call this function.
  2247. */
  2248. void set_cpus_allowed_common(struct task_struct *p, struct affinity_context *ctx)
  2249. {
  2250. if (ctx->flags & (SCA_MIGRATE_ENABLE | SCA_MIGRATE_DISABLE)) {
  2251. p->cpus_ptr = ctx->new_mask;
  2252. return;
  2253. }
  2254. cpumask_copy(&p->cpus_mask, ctx->new_mask);
  2255. p->nr_cpus_allowed = cpumask_weight(ctx->new_mask);
  2256. /*
  2257. * Swap in a new user_cpus_ptr if SCA_USER flag set
  2258. */
  2259. if (ctx->flags & SCA_USER)
  2260. swap(p->user_cpus_ptr, ctx->user_mask);
  2261. }
  2262. static void
  2263. __do_set_cpus_allowed(struct task_struct *p, struct affinity_context *ctx)
  2264. {
  2265. struct rq *rq = task_rq(p);
  2266. bool queued, running;
  2267. /*
  2268. * This here violates the locking rules for affinity, since we're only
  2269. * supposed to change these variables while holding both rq->lock and
  2270. * p->pi_lock.
  2271. *
  2272. * HOWEVER, it magically works, because ttwu() is the only code that
  2273. * accesses these variables under p->pi_lock and only does so after
  2274. * smp_cond_load_acquire(&p->on_cpu, !VAL), and we're in __schedule()
  2275. * before finish_task().
  2276. *
  2277. * XXX do further audits, this smells like something putrid.
  2278. */
  2279. if (ctx->flags & SCA_MIGRATE_DISABLE)
  2280. SCHED_WARN_ON(!p->on_cpu);
  2281. else
  2282. lockdep_assert_held(&p->pi_lock);
  2283. queued = task_on_rq_queued(p);
  2284. running = task_current(rq, p);
  2285. if (queued) {
  2286. /*
  2287. * Because __kthread_bind() calls this on blocked tasks without
  2288. * holding rq->lock.
  2289. */
  2290. lockdep_assert_rq_held(rq);
  2291. dequeue_task(rq, p, DEQUEUE_SAVE | DEQUEUE_NOCLOCK);
  2292. }
  2293. if (running)
  2294. put_prev_task(rq, p);
  2295. p->sched_class->set_cpus_allowed(p, ctx);
  2296. if (queued)
  2297. enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
  2298. if (running)
  2299. set_next_task(rq, p);
  2300. }
  2301. /*
  2302. * Used for kthread_bind() and select_fallback_rq(), in both cases the user
  2303. * affinity (if any) should be destroyed too.
  2304. */
  2305. void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask)
  2306. {
  2307. struct affinity_context ac = {
  2308. .new_mask = new_mask,
  2309. .user_mask = NULL,
  2310. .flags = SCA_USER, /* clear the user requested mask */
  2311. };
  2312. union cpumask_rcuhead {
  2313. cpumask_t cpumask;
  2314. struct rcu_head rcu;
  2315. };
  2316. __do_set_cpus_allowed(p, &ac);
  2317. /*
  2318. * Because this is called with p->pi_lock held, it is not possible
  2319. * to use kfree() here (when PREEMPT_RT=y), therefore punt to using
  2320. * kfree_rcu().
  2321. */
  2322. kfree_rcu((union cpumask_rcuhead *)ac.user_mask, rcu);
  2323. }
  2324. int dup_user_cpus_ptr(struct task_struct *dst, struct task_struct *src,
  2325. int node)
  2326. {
  2327. cpumask_t *user_mask;
  2328. unsigned long flags;
  2329. /*
  2330. * Always clear dst->user_cpus_ptr first as their user_cpus_ptr's
  2331. * may differ by now due to racing.
  2332. */
  2333. dst->user_cpus_ptr = NULL;
  2334. /*
  2335. * This check is racy and losing the race is a valid situation.
  2336. * It is not worth the extra overhead of taking the pi_lock on
  2337. * every fork/clone.
  2338. */
  2339. if (data_race(!src->user_cpus_ptr))
  2340. return 0;
  2341. user_mask = alloc_user_cpus_ptr(node);
  2342. if (!user_mask)
  2343. return -ENOMEM;
  2344. /*
  2345. * Use pi_lock to protect content of user_cpus_ptr
  2346. *
  2347. * Though unlikely, user_cpus_ptr can be reset to NULL by a concurrent
  2348. * do_set_cpus_allowed().
  2349. */
  2350. raw_spin_lock_irqsave(&src->pi_lock, flags);
  2351. if (src->user_cpus_ptr) {
  2352. swap(dst->user_cpus_ptr, user_mask);
  2353. cpumask_copy(dst->user_cpus_ptr, src->user_cpus_ptr);
  2354. }
  2355. raw_spin_unlock_irqrestore(&src->pi_lock, flags);
  2356. if (unlikely(user_mask))
  2357. kfree(user_mask);
  2358. return 0;
  2359. }
  2360. static inline struct cpumask *clear_user_cpus_ptr(struct task_struct *p)
  2361. {
  2362. struct cpumask *user_mask = NULL;
  2363. swap(p->user_cpus_ptr, user_mask);
  2364. return user_mask;
  2365. }
  2366. void release_user_cpus_ptr(struct task_struct *p)
  2367. {
  2368. kfree(clear_user_cpus_ptr(p));
  2369. }
  2370. /*
  2371. * This function is wildly self concurrent; here be dragons.
  2372. *
  2373. *
  2374. * When given a valid mask, __set_cpus_allowed_ptr() must block until the
  2375. * designated task is enqueued on an allowed CPU. If that task is currently
  2376. * running, we have to kick it out using the CPU stopper.
  2377. *
  2378. * Migrate-Disable comes along and tramples all over our nice sandcastle.
  2379. * Consider:
  2380. *
  2381. * Initial conditions: P0->cpus_mask = [0, 1]
  2382. *
  2383. * P0@CPU0 P1
  2384. *
  2385. * migrate_disable();
  2386. * <preempted>
  2387. * set_cpus_allowed_ptr(P0, [1]);
  2388. *
  2389. * P1 *cannot* return from this set_cpus_allowed_ptr() call until P0 executes
  2390. * its outermost migrate_enable() (i.e. it exits its Migrate-Disable region).
  2391. * This means we need the following scheme:
  2392. *
  2393. * P0@CPU0 P1
  2394. *
  2395. * migrate_disable();
  2396. * <preempted>
  2397. * set_cpus_allowed_ptr(P0, [1]);
  2398. * <blocks>
  2399. * <resumes>
  2400. * migrate_enable();
  2401. * __set_cpus_allowed_ptr();
  2402. * <wakes local stopper>
  2403. * `--> <woken on migration completion>
  2404. *
  2405. * Now the fun stuff: there may be several P1-like tasks, i.e. multiple
  2406. * concurrent set_cpus_allowed_ptr(P0, [*]) calls. CPU affinity changes of any
  2407. * task p are serialized by p->pi_lock, which we can leverage: the one that
  2408. * should come into effect at the end of the Migrate-Disable region is the last
  2409. * one. This means we only need to track a single cpumask (i.e. p->cpus_mask),
  2410. * but we still need to properly signal those waiting tasks at the appropriate
  2411. * moment.
  2412. *
  2413. * This is implemented using struct set_affinity_pending. The first
  2414. * __set_cpus_allowed_ptr() caller within a given Migrate-Disable region will
  2415. * setup an instance of that struct and install it on the targeted task_struct.
  2416. * Any and all further callers will reuse that instance. Those then wait for
  2417. * a completion signaled at the tail of the CPU stopper callback (1), triggered
  2418. * on the end of the Migrate-Disable region (i.e. outermost migrate_enable()).
  2419. *
  2420. *
  2421. * (1) In the cases covered above. There is one more where the completion is
  2422. * signaled within affine_move_task() itself: when a subsequent affinity request
  2423. * occurs after the stopper bailed out due to the targeted task still being
  2424. * Migrate-Disable. Consider:
  2425. *
  2426. * Initial conditions: P0->cpus_mask = [0, 1]
  2427. *
  2428. * CPU0 P1 P2
  2429. * <P0>
  2430. * migrate_disable();
  2431. * <preempted>
  2432. * set_cpus_allowed_ptr(P0, [1]);
  2433. * <blocks>
  2434. * <migration/0>
  2435. * migration_cpu_stop()
  2436. * is_migration_disabled()
  2437. * <bails>
  2438. * set_cpus_allowed_ptr(P0, [0, 1]);
  2439. * <signal completion>
  2440. * <awakes>
  2441. *
  2442. * Note that the above is safe vs a concurrent migrate_enable(), as any
  2443. * pending affinity completion is preceded by an uninstallation of
  2444. * p->migration_pending done with p->pi_lock held.
  2445. */
  2446. static int affine_move_task(struct rq *rq, struct task_struct *p, struct rq_flags *rf,
  2447. int dest_cpu, unsigned int flags)
  2448. __releases(rq->lock)
  2449. __releases(p->pi_lock)
  2450. {
  2451. struct set_affinity_pending my_pending = { }, *pending = NULL;
  2452. bool stop_pending, complete = false;
  2453. /* Can the task run on the task's current CPU? If so, we're done */
  2454. if (cpumask_test_cpu(task_cpu(p), &p->cpus_mask)) {
  2455. struct task_struct *push_task = NULL;
  2456. if ((flags & SCA_MIGRATE_ENABLE) &&
  2457. (p->migration_flags & MDF_PUSH) && !rq->push_busy) {
  2458. rq->push_busy = true;
  2459. push_task = get_task_struct(p);
  2460. }
  2461. /*
  2462. * If there are pending waiters, but no pending stop_work,
  2463. * then complete now.
  2464. */
  2465. pending = p->migration_pending;
  2466. if (pending && !pending->stop_pending) {
  2467. p->migration_pending = NULL;
  2468. complete = true;
  2469. }
  2470. preempt_disable();
  2471. task_rq_unlock(rq, p, rf);
  2472. if (push_task) {
  2473. stop_one_cpu_nowait(rq->cpu, push_cpu_stop,
  2474. p, &rq->push_work);
  2475. }
  2476. preempt_enable();
  2477. if (complete)
  2478. complete_all(&pending->done);
  2479. return 0;
  2480. }
  2481. if (!(flags & SCA_MIGRATE_ENABLE)) {
  2482. /* serialized by p->pi_lock */
  2483. if (!p->migration_pending) {
  2484. /* Install the request */
  2485. refcount_set(&my_pending.refs, 1);
  2486. init_completion(&my_pending.done);
  2487. my_pending.arg = (struct migration_arg) {
  2488. .task = p,
  2489. .dest_cpu = dest_cpu,
  2490. .pending = &my_pending,
  2491. };
  2492. p->migration_pending = &my_pending;
  2493. } else {
  2494. pending = p->migration_pending;
  2495. refcount_inc(&pending->refs);
  2496. /*
  2497. * Affinity has changed, but we've already installed a
  2498. * pending. migration_cpu_stop() *must* see this, else
  2499. * we risk a completion of the pending despite having a
  2500. * task on a disallowed CPU.
  2501. *
  2502. * Serialized by p->pi_lock, so this is safe.
  2503. */
  2504. pending->arg.dest_cpu = dest_cpu;
  2505. }
  2506. }
  2507. pending = p->migration_pending;
  2508. /*
  2509. * - !MIGRATE_ENABLE:
  2510. * we'll have installed a pending if there wasn't one already.
  2511. *
  2512. * - MIGRATE_ENABLE:
  2513. * we're here because the current CPU isn't matching anymore,
  2514. * the only way that can happen is because of a concurrent
  2515. * set_cpus_allowed_ptr() call, which should then still be
  2516. * pending completion.
  2517. *
  2518. * Either way, we really should have a @pending here.
  2519. */
  2520. if (WARN_ON_ONCE(!pending)) {
  2521. task_rq_unlock(rq, p, rf);
  2522. return -EINVAL;
  2523. }
  2524. if (task_on_cpu(rq, p) || READ_ONCE(p->__state) == TASK_WAKING) {
  2525. /*
  2526. * MIGRATE_ENABLE gets here because 'p == current', but for
  2527. * anything else we cannot do is_migration_disabled(), punt
  2528. * and have the stopper function handle it all race-free.
  2529. */
  2530. stop_pending = pending->stop_pending;
  2531. if (!stop_pending)
  2532. pending->stop_pending = true;
  2533. if (flags & SCA_MIGRATE_ENABLE)
  2534. p->migration_flags &= ~MDF_PUSH;
  2535. preempt_disable();
  2536. task_rq_unlock(rq, p, rf);
  2537. if (!stop_pending) {
  2538. stop_one_cpu_nowait(cpu_of(rq), migration_cpu_stop,
  2539. &pending->arg, &pending->stop_work);
  2540. }
  2541. preempt_enable();
  2542. if (flags & SCA_MIGRATE_ENABLE)
  2543. return 0;
  2544. } else {
  2545. if (!is_migration_disabled(p)) {
  2546. if (task_on_rq_queued(p))
  2547. rq = move_queued_task(rq, rf, p, dest_cpu);
  2548. if (!pending->stop_pending) {
  2549. p->migration_pending = NULL;
  2550. complete = true;
  2551. }
  2552. }
  2553. task_rq_unlock(rq, p, rf);
  2554. if (complete)
  2555. complete_all(&pending->done);
  2556. }
  2557. wait_for_completion(&pending->done);
  2558. if (refcount_dec_and_test(&pending->refs))
  2559. wake_up_var(&pending->refs); /* No UaF, just an address */
  2560. /*
  2561. * Block the original owner of &pending until all subsequent callers
  2562. * have seen the completion and decremented the refcount
  2563. */
  2564. wait_var_event(&my_pending.refs, !refcount_read(&my_pending.refs));
  2565. /* ARGH */
  2566. WARN_ON_ONCE(my_pending.stop_pending);
  2567. return 0;
  2568. }
  2569. /*
  2570. * Called with both p->pi_lock and rq->lock held; drops both before returning.
  2571. */
  2572. static int __set_cpus_allowed_ptr_locked(struct task_struct *p,
  2573. struct affinity_context *ctx,
  2574. struct rq *rq,
  2575. struct rq_flags *rf)
  2576. __releases(rq->lock)
  2577. __releases(p->pi_lock)
  2578. {
  2579. const struct cpumask *cpu_allowed_mask = task_cpu_possible_mask(p);
  2580. const struct cpumask *cpu_valid_mask = cpu_active_mask;
  2581. bool kthread = p->flags & PF_KTHREAD;
  2582. unsigned int dest_cpu;
  2583. int ret = 0;
  2584. update_rq_clock(rq);
  2585. if (kthread || is_migration_disabled(p)) {
  2586. /*
  2587. * Kernel threads are allowed on online && !active CPUs,
  2588. * however, during cpu-hot-unplug, even these might get pushed
  2589. * away if not KTHREAD_IS_PER_CPU.
  2590. *
  2591. * Specifically, migration_disabled() tasks must not fail the
  2592. * cpumask_any_and_distribute() pick below, esp. so on
  2593. * SCA_MIGRATE_ENABLE, otherwise we'll not call
  2594. * set_cpus_allowed_common() and actually reset p->cpus_ptr.
  2595. */
  2596. cpu_valid_mask = cpu_online_mask;
  2597. }
  2598. if (!kthread && !cpumask_subset(ctx->new_mask, cpu_allowed_mask)) {
  2599. ret = -EINVAL;
  2600. goto out;
  2601. }
  2602. /*
  2603. * Must re-check here, to close a race against __kthread_bind(),
  2604. * sched_setaffinity() is not guaranteed to observe the flag.
  2605. */
  2606. if ((ctx->flags & SCA_CHECK) && (p->flags & PF_NO_SETAFFINITY)) {
  2607. ret = -EINVAL;
  2608. goto out;
  2609. }
  2610. if (!(ctx->flags & SCA_MIGRATE_ENABLE)) {
  2611. if (cpumask_equal(&p->cpus_mask, ctx->new_mask)) {
  2612. if (ctx->flags & SCA_USER)
  2613. swap(p->user_cpus_ptr, ctx->user_mask);
  2614. goto out;
  2615. }
  2616. if (WARN_ON_ONCE(p == current &&
  2617. is_migration_disabled(p) &&
  2618. !cpumask_test_cpu(task_cpu(p), ctx->new_mask))) {
  2619. ret = -EBUSY;
  2620. goto out;
  2621. }
  2622. }
  2623. /*
  2624. * Picking a ~random cpu helps in cases where we are changing affinity
  2625. * for groups of tasks (ie. cpuset), so that load balancing is not
  2626. * immediately required to distribute the tasks within their new mask.
  2627. */
  2628. dest_cpu = cpumask_any_and_distribute(cpu_valid_mask, ctx->new_mask);
  2629. if (dest_cpu >= nr_cpu_ids) {
  2630. ret = -EINVAL;
  2631. goto out;
  2632. }
  2633. __do_set_cpus_allowed(p, ctx);
  2634. return affine_move_task(rq, p, rf, dest_cpu, ctx->flags);
  2635. out:
  2636. task_rq_unlock(rq, p, rf);
  2637. return ret;
  2638. }
  2639. /*
  2640. * Change a given task's CPU affinity. Migrate the thread to a
  2641. * proper CPU and schedule it away if the CPU it's executing on
  2642. * is removed from the allowed bitmask.
  2643. *
  2644. * NOTE: the caller must have a valid reference to the task, the
  2645. * task must not exit() & deallocate itself prematurely. The
  2646. * call is not atomic; no spinlocks may be held.
  2647. */
  2648. int __set_cpus_allowed_ptr(struct task_struct *p, struct affinity_context *ctx)
  2649. {
  2650. struct rq_flags rf;
  2651. struct rq *rq;
  2652. rq = task_rq_lock(p, &rf);
  2653. /*
  2654. * Masking should be skipped if SCA_USER or any of the SCA_MIGRATE_*
  2655. * flags are set.
  2656. */
  2657. if (p->user_cpus_ptr &&
  2658. !(ctx->flags & (SCA_USER | SCA_MIGRATE_ENABLE | SCA_MIGRATE_DISABLE)) &&
  2659. cpumask_and(rq->scratch_mask, ctx->new_mask, p->user_cpus_ptr))
  2660. ctx->new_mask = rq->scratch_mask;
  2661. return __set_cpus_allowed_ptr_locked(p, ctx, rq, &rf);
  2662. }
  2663. int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
  2664. {
  2665. struct affinity_context ac = {
  2666. .new_mask = new_mask,
  2667. .flags = 0,
  2668. };
  2669. return __set_cpus_allowed_ptr(p, &ac);
  2670. }
  2671. EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
  2672. /*
  2673. * Change a given task's CPU affinity to the intersection of its current
  2674. * affinity mask and @subset_mask, writing the resulting mask to @new_mask.
  2675. * If user_cpus_ptr is defined, use it as the basis for restricting CPU
  2676. * affinity or use cpu_online_mask instead.
  2677. *
  2678. * If the resulting mask is empty, leave the affinity unchanged and return
  2679. * -EINVAL.
  2680. */
  2681. static int restrict_cpus_allowed_ptr(struct task_struct *p,
  2682. struct cpumask *new_mask,
  2683. const struct cpumask *subset_mask)
  2684. {
  2685. struct affinity_context ac = {
  2686. .new_mask = new_mask,
  2687. .flags = 0,
  2688. };
  2689. struct rq_flags rf;
  2690. struct rq *rq;
  2691. int err;
  2692. rq = task_rq_lock(p, &rf);
  2693. /*
  2694. * Forcefully restricting the affinity of a deadline task is
  2695. * likely to cause problems, so fail and noisily override the
  2696. * mask entirely.
  2697. */
  2698. if (task_has_dl_policy(p) && dl_bandwidth_enabled()) {
  2699. err = -EPERM;
  2700. goto err_unlock;
  2701. }
  2702. if (!cpumask_and(new_mask, task_user_cpus(p), subset_mask)) {
  2703. err = -EINVAL;
  2704. goto err_unlock;
  2705. }
  2706. return __set_cpus_allowed_ptr_locked(p, &ac, rq, &rf);
  2707. err_unlock:
  2708. task_rq_unlock(rq, p, &rf);
  2709. return err;
  2710. }
  2711. /*
  2712. * Restrict the CPU affinity of task @p so that it is a subset of
  2713. * task_cpu_possible_mask() and point @p->user_cpus_ptr to a copy of the
  2714. * old affinity mask. If the resulting mask is empty, we warn and walk
  2715. * up the cpuset hierarchy until we find a suitable mask.
  2716. */
  2717. void force_compatible_cpus_allowed_ptr(struct task_struct *p)
  2718. {
  2719. cpumask_var_t new_mask;
  2720. const struct cpumask *override_mask = task_cpu_possible_mask(p);
  2721. alloc_cpumask_var(&new_mask, GFP_KERNEL);
  2722. /*
  2723. * __migrate_task() can fail silently in the face of concurrent
  2724. * offlining of the chosen destination CPU, so take the hotplug
  2725. * lock to ensure that the migration succeeds.
  2726. */
  2727. cpus_read_lock();
  2728. if (!cpumask_available(new_mask))
  2729. goto out_set_mask;
  2730. if (!restrict_cpus_allowed_ptr(p, new_mask, override_mask))
  2731. goto out_free_mask;
  2732. /*
  2733. * We failed to find a valid subset of the affinity mask for the
  2734. * task, so override it based on its cpuset hierarchy.
  2735. */
  2736. cpuset_cpus_allowed(p, new_mask);
  2737. override_mask = new_mask;
  2738. out_set_mask:
  2739. if (printk_ratelimit()) {
  2740. printk_deferred("Overriding affinity for process %d (%s) to CPUs %*pbl\n",
  2741. task_pid_nr(p), p->comm,
  2742. cpumask_pr_args(override_mask));
  2743. }
  2744. WARN_ON(set_cpus_allowed_ptr(p, override_mask));
  2745. out_free_mask:
  2746. cpus_read_unlock();
  2747. free_cpumask_var(new_mask);
  2748. }
  2749. /*
  2750. * Restore the affinity of a task @p which was previously restricted by a
  2751. * call to force_compatible_cpus_allowed_ptr().
  2752. *
  2753. * It is the caller's responsibility to serialise this with any calls to
  2754. * force_compatible_cpus_allowed_ptr(@p).
  2755. */
  2756. void relax_compatible_cpus_allowed_ptr(struct task_struct *p)
  2757. {
  2758. struct affinity_context ac = {
  2759. .new_mask = task_user_cpus(p),
  2760. .flags = 0,
  2761. };
  2762. int ret;
  2763. /*
  2764. * Try to restore the old affinity mask with __sched_setaffinity().
  2765. * Cpuset masking will be done there too.
  2766. */
  2767. ret = __sched_setaffinity(p, &ac);
  2768. WARN_ON_ONCE(ret);
  2769. }
  2770. void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
  2771. {
  2772. #ifdef CONFIG_SCHED_DEBUG
  2773. unsigned int state = READ_ONCE(p->__state);
  2774. /*
  2775. * We should never call set_task_cpu() on a blocked task,
  2776. * ttwu() will sort out the placement.
  2777. */
  2778. WARN_ON_ONCE(state != TASK_RUNNING && state != TASK_WAKING && !p->on_rq);
  2779. /*
  2780. * Migrating fair class task must have p->on_rq = TASK_ON_RQ_MIGRATING,
  2781. * because schedstat_wait_{start,end} rebase migrating task's wait_start
  2782. * time relying on p->on_rq.
  2783. */
  2784. WARN_ON_ONCE(state == TASK_RUNNING &&
  2785. p->sched_class == &fair_sched_class &&
  2786. (p->on_rq && !task_on_rq_migrating(p)));
  2787. #ifdef CONFIG_LOCKDEP
  2788. /*
  2789. * The caller should hold either p->pi_lock or rq->lock, when changing
  2790. * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks.
  2791. *
  2792. * sched_move_task() holds both and thus holding either pins the cgroup,
  2793. * see task_group().
  2794. *
  2795. * Furthermore, all task_rq users should acquire both locks, see
  2796. * task_rq_lock().
  2797. */
  2798. WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) ||
  2799. lockdep_is_held(__rq_lockp(task_rq(p)))));
  2800. #endif
  2801. /*
  2802. * Clearly, migrating tasks to offline CPUs is a fairly daft thing.
  2803. */
  2804. WARN_ON_ONCE(!cpu_online(new_cpu));
  2805. WARN_ON_ONCE(is_migration_disabled(p));
  2806. #endif
  2807. trace_sched_migrate_task(p, new_cpu);
  2808. if (task_cpu(p) != new_cpu) {
  2809. if (p->sched_class->migrate_task_rq)
  2810. p->sched_class->migrate_task_rq(p, new_cpu);
  2811. p->se.nr_migrations++;
  2812. rseq_migrate(p);
  2813. sched_mm_cid_migrate_from(p);
  2814. perf_event_task_migrate(p);
  2815. }
  2816. __set_task_cpu(p, new_cpu);
  2817. }
  2818. #ifdef CONFIG_NUMA_BALANCING
  2819. static void __migrate_swap_task(struct task_struct *p, int cpu)
  2820. {
  2821. if (task_on_rq_queued(p)) {
  2822. struct rq *src_rq, *dst_rq;
  2823. struct rq_flags srf, drf;
  2824. src_rq = task_rq(p);
  2825. dst_rq = cpu_rq(cpu);
  2826. rq_pin_lock(src_rq, &srf);
  2827. rq_pin_lock(dst_rq, &drf);
  2828. deactivate_task(src_rq, p, 0);
  2829. set_task_cpu(p, cpu);
  2830. activate_task(dst_rq, p, 0);
  2831. wakeup_preempt(dst_rq, p, 0);
  2832. rq_unpin_lock(dst_rq, &drf);
  2833. rq_unpin_lock(src_rq, &srf);
  2834. } else {
  2835. /*
  2836. * Task isn't running anymore; make it appear like we migrated
  2837. * it before it went to sleep. This means on wakeup we make the
  2838. * previous CPU our target instead of where it really is.
  2839. */
  2840. p->wake_cpu = cpu;
  2841. }
  2842. }
  2843. struct migration_swap_arg {
  2844. struct task_struct *src_task, *dst_task;
  2845. int src_cpu, dst_cpu;
  2846. };
  2847. static int migrate_swap_stop(void *data)
  2848. {
  2849. struct migration_swap_arg *arg = data;
  2850. struct rq *src_rq, *dst_rq;
  2851. if (!cpu_active(arg->src_cpu) || !cpu_active(arg->dst_cpu))
  2852. return -EAGAIN;
  2853. src_rq = cpu_rq(arg->src_cpu);
  2854. dst_rq = cpu_rq(arg->dst_cpu);
  2855. guard(double_raw_spinlock)(&arg->src_task->pi_lock, &arg->dst_task->pi_lock);
  2856. guard(double_rq_lock)(src_rq, dst_rq);
  2857. if (task_cpu(arg->dst_task) != arg->dst_cpu)
  2858. return -EAGAIN;
  2859. if (task_cpu(arg->src_task) != arg->src_cpu)
  2860. return -EAGAIN;
  2861. if (!cpumask_test_cpu(arg->dst_cpu, arg->src_task->cpus_ptr))
  2862. return -EAGAIN;
  2863. if (!cpumask_test_cpu(arg->src_cpu, arg->dst_task->cpus_ptr))
  2864. return -EAGAIN;
  2865. __migrate_swap_task(arg->src_task, arg->dst_cpu);
  2866. __migrate_swap_task(arg->dst_task, arg->src_cpu);
  2867. return 0;
  2868. }
  2869. /*
  2870. * Cross migrate two tasks
  2871. */
  2872. int migrate_swap(struct task_struct *cur, struct task_struct *p,
  2873. int target_cpu, int curr_cpu)
  2874. {
  2875. struct migration_swap_arg arg;
  2876. int ret = -EINVAL;
  2877. arg = (struct migration_swap_arg){
  2878. .src_task = cur,
  2879. .src_cpu = curr_cpu,
  2880. .dst_task = p,
  2881. .dst_cpu = target_cpu,
  2882. };
  2883. if (arg.src_cpu == arg.dst_cpu)
  2884. goto out;
  2885. /*
  2886. * These three tests are all lockless; this is OK since all of them
  2887. * will be re-checked with proper locks held further down the line.
  2888. */
  2889. if (!cpu_active(arg.src_cpu) || !cpu_active(arg.dst_cpu))
  2890. goto out;
  2891. if (!cpumask_test_cpu(arg.dst_cpu, arg.src_task->cpus_ptr))
  2892. goto out;
  2893. if (!cpumask_test_cpu(arg.src_cpu, arg.dst_task->cpus_ptr))
  2894. goto out;
  2895. trace_sched_swap_numa(cur, arg.src_cpu, p, arg.dst_cpu);
  2896. ret = stop_two_cpus(arg.dst_cpu, arg.src_cpu, migrate_swap_stop, &arg);
  2897. out:
  2898. return ret;
  2899. }
  2900. #endif /* CONFIG_NUMA_BALANCING */
  2901. /***
  2902. * kick_process - kick a running thread to enter/exit the kernel
  2903. * @p: the to-be-kicked thread
  2904. *
  2905. * Cause a process which is running on another CPU to enter
  2906. * kernel-mode, without any delay. (to get signals handled.)
  2907. *
  2908. * NOTE: this function doesn't have to take the runqueue lock,
  2909. * because all it wants to ensure is that the remote task enters
  2910. * the kernel. If the IPI races and the task has been migrated
  2911. * to another CPU then no harm is done and the purpose has been
  2912. * achieved as well.
  2913. */
  2914. void kick_process(struct task_struct *p)
  2915. {
  2916. guard(preempt)();
  2917. int cpu = task_cpu(p);
  2918. if ((cpu != smp_processor_id()) && task_curr(p))
  2919. smp_send_reschedule(cpu);
  2920. }
  2921. EXPORT_SYMBOL_GPL(kick_process);
  2922. /*
  2923. * ->cpus_ptr is protected by both rq->lock and p->pi_lock
  2924. *
  2925. * A few notes on cpu_active vs cpu_online:
  2926. *
  2927. * - cpu_active must be a subset of cpu_online
  2928. *
  2929. * - on CPU-up we allow per-CPU kthreads on the online && !active CPU,
  2930. * see __set_cpus_allowed_ptr(). At this point the newly online
  2931. * CPU isn't yet part of the sched domains, and balancing will not
  2932. * see it.
  2933. *
  2934. * - on CPU-down we clear cpu_active() to mask the sched domains and
  2935. * avoid the load balancer to place new tasks on the to be removed
  2936. * CPU. Existing tasks will remain running there and will be taken
  2937. * off.
  2938. *
  2939. * This means that fallback selection must not select !active CPUs.
  2940. * And can assume that any active CPU must be online. Conversely
  2941. * select_task_rq() below may allow selection of !active CPUs in order
  2942. * to satisfy the above rules.
  2943. */
  2944. static int select_fallback_rq(int cpu, struct task_struct *p)
  2945. {
  2946. int nid = cpu_to_node(cpu);
  2947. const struct cpumask *nodemask = NULL;
  2948. enum { cpuset, possible, fail } state = cpuset;
  2949. int dest_cpu;
  2950. /*
  2951. * If the node that the CPU is on has been offlined, cpu_to_node()
  2952. * will return -1. There is no CPU on the node, and we should
  2953. * select the CPU on the other node.
  2954. */
  2955. if (nid != -1) {
  2956. nodemask = cpumask_of_node(nid);
  2957. /* Look for allowed, online CPU in same node. */
  2958. for_each_cpu(dest_cpu, nodemask) {
  2959. if (is_cpu_allowed(p, dest_cpu))
  2960. return dest_cpu;
  2961. }
  2962. }
  2963. for (;;) {
  2964. /* Any allowed, online CPU? */
  2965. for_each_cpu(dest_cpu, p->cpus_ptr) {
  2966. if (!is_cpu_allowed(p, dest_cpu))
  2967. continue;
  2968. goto out;
  2969. }
  2970. /* No more Mr. Nice Guy. */
  2971. switch (state) {
  2972. case cpuset:
  2973. if (cpuset_cpus_allowed_fallback(p)) {
  2974. state = possible;
  2975. break;
  2976. }
  2977. fallthrough;
  2978. case possible:
  2979. /*
  2980. * XXX When called from select_task_rq() we only
  2981. * hold p->pi_lock and again violate locking order.
  2982. *
  2983. * More yuck to audit.
  2984. */
  2985. do_set_cpus_allowed(p, task_cpu_possible_mask(p));
  2986. state = fail;
  2987. break;
  2988. case fail:
  2989. BUG();
  2990. break;
  2991. }
  2992. }
  2993. out:
  2994. if (state != cpuset) {
  2995. /*
  2996. * Don't tell them about moving exiting tasks or
  2997. * kernel threads (both mm NULL), since they never
  2998. * leave kernel.
  2999. */
  3000. if (p->mm && printk_ratelimit()) {
  3001. printk_deferred("process %d (%s) no longer affine to cpu%d\n",
  3002. task_pid_nr(p), p->comm, cpu);
  3003. }
  3004. }
  3005. return dest_cpu;
  3006. }
  3007. /*
  3008. * The caller (fork, wakeup) owns p->pi_lock, ->cpus_ptr is stable.
  3009. */
  3010. static inline
  3011. int select_task_rq(struct task_struct *p, int cpu, int *wake_flags)
  3012. {
  3013. lockdep_assert_held(&p->pi_lock);
  3014. if (p->nr_cpus_allowed > 1 && !is_migration_disabled(p)) {
  3015. cpu = p->sched_class->select_task_rq(p, cpu, *wake_flags);
  3016. *wake_flags |= WF_RQ_SELECTED;
  3017. } else {
  3018. cpu = cpumask_any(p->cpus_ptr);
  3019. }
  3020. /*
  3021. * In order not to call set_task_cpu() on a blocking task we need
  3022. * to rely on ttwu() to place the task on a valid ->cpus_ptr
  3023. * CPU.
  3024. *
  3025. * Since this is common to all placement strategies, this lives here.
  3026. *
  3027. * [ this allows ->select_task() to simply return task_cpu(p) and
  3028. * not worry about this generic constraint ]
  3029. */
  3030. if (unlikely(!is_cpu_allowed(p, cpu)))
  3031. cpu = select_fallback_rq(task_cpu(p), p);
  3032. return cpu;
  3033. }
  3034. void sched_set_stop_task(int cpu, struct task_struct *stop)
  3035. {
  3036. static struct lock_class_key stop_pi_lock;
  3037. struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
  3038. struct task_struct *old_stop = cpu_rq(cpu)->stop;
  3039. if (stop) {
  3040. /*
  3041. * Make it appear like a SCHED_FIFO task, its something
  3042. * userspace knows about and won't get confused about.
  3043. *
  3044. * Also, it will make PI more or less work without too
  3045. * much confusion -- but then, stop work should not
  3046. * rely on PI working anyway.
  3047. */
  3048. sched_setscheduler_nocheck(stop, SCHED_FIFO, &param);
  3049. stop->sched_class = &stop_sched_class;
  3050. /*
  3051. * The PI code calls rt_mutex_setprio() with ->pi_lock held to
  3052. * adjust the effective priority of a task. As a result,
  3053. * rt_mutex_setprio() can trigger (RT) balancing operations,
  3054. * which can then trigger wakeups of the stop thread to push
  3055. * around the current task.
  3056. *
  3057. * The stop task itself will never be part of the PI-chain, it
  3058. * never blocks, therefore that ->pi_lock recursion is safe.
  3059. * Tell lockdep about this by placing the stop->pi_lock in its
  3060. * own class.
  3061. */
  3062. lockdep_set_class(&stop->pi_lock, &stop_pi_lock);
  3063. }
  3064. cpu_rq(cpu)->stop = stop;
  3065. if (old_stop) {
  3066. /*
  3067. * Reset it back to a normal scheduling class so that
  3068. * it can die in pieces.
  3069. */
  3070. old_stop->sched_class = &rt_sched_class;
  3071. }
  3072. }
  3073. #else /* CONFIG_SMP */
  3074. static inline void migrate_disable_switch(struct rq *rq, struct task_struct *p) { }
  3075. static inline bool rq_has_pinned_tasks(struct rq *rq)
  3076. {
  3077. return false;
  3078. }
  3079. #endif /* !CONFIG_SMP */
  3080. static void
  3081. ttwu_stat(struct task_struct *p, int cpu, int wake_flags)
  3082. {
  3083. struct rq *rq;
  3084. if (!schedstat_enabled())
  3085. return;
  3086. rq = this_rq();
  3087. #ifdef CONFIG_SMP
  3088. if (cpu == rq->cpu) {
  3089. __schedstat_inc(rq->ttwu_local);
  3090. __schedstat_inc(p->stats.nr_wakeups_local);
  3091. } else {
  3092. struct sched_domain *sd;
  3093. __schedstat_inc(p->stats.nr_wakeups_remote);
  3094. guard(rcu)();
  3095. for_each_domain(rq->cpu, sd) {
  3096. if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
  3097. __schedstat_inc(sd->ttwu_wake_remote);
  3098. break;
  3099. }
  3100. }
  3101. }
  3102. if (wake_flags & WF_MIGRATED)
  3103. __schedstat_inc(p->stats.nr_wakeups_migrate);
  3104. #endif /* CONFIG_SMP */
  3105. __schedstat_inc(rq->ttwu_count);
  3106. __schedstat_inc(p->stats.nr_wakeups);
  3107. if (wake_flags & WF_SYNC)
  3108. __schedstat_inc(p->stats.nr_wakeups_sync);
  3109. }
  3110. /*
  3111. * Mark the task runnable.
  3112. */
  3113. static inline void ttwu_do_wakeup(struct task_struct *p)
  3114. {
  3115. WRITE_ONCE(p->__state, TASK_RUNNING);
  3116. trace_sched_wakeup(p);
  3117. }
  3118. static void
  3119. ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags,
  3120. struct rq_flags *rf)
  3121. {
  3122. int en_flags = ENQUEUE_WAKEUP | ENQUEUE_NOCLOCK;
  3123. lockdep_assert_rq_held(rq);
  3124. if (p->sched_contributes_to_load)
  3125. rq->nr_uninterruptible--;
  3126. #ifdef CONFIG_SMP
  3127. if (wake_flags & WF_RQ_SELECTED)
  3128. en_flags |= ENQUEUE_RQ_SELECTED;
  3129. if (wake_flags & WF_MIGRATED)
  3130. en_flags |= ENQUEUE_MIGRATED;
  3131. else
  3132. #endif
  3133. if (p->in_iowait) {
  3134. delayacct_blkio_end(p);
  3135. atomic_dec(&task_rq(p)->nr_iowait);
  3136. }
  3137. activate_task(rq, p, en_flags);
  3138. wakeup_preempt(rq, p, wake_flags);
  3139. ttwu_do_wakeup(p);
  3140. #ifdef CONFIG_SMP
  3141. if (p->sched_class->task_woken) {
  3142. /*
  3143. * Our task @p is fully woken up and running; so it's safe to
  3144. * drop the rq->lock, hereafter rq is only used for statistics.
  3145. */
  3146. rq_unpin_lock(rq, rf);
  3147. p->sched_class->task_woken(rq, p);
  3148. rq_repin_lock(rq, rf);
  3149. }
  3150. if (rq->idle_stamp) {
  3151. u64 delta = rq_clock(rq) - rq->idle_stamp;
  3152. u64 max = 2*rq->max_idle_balance_cost;
  3153. update_avg(&rq->avg_idle, delta);
  3154. if (rq->avg_idle > max)
  3155. rq->avg_idle = max;
  3156. rq->idle_stamp = 0;
  3157. }
  3158. #endif
  3159. }
  3160. /*
  3161. * Consider @p being inside a wait loop:
  3162. *
  3163. * for (;;) {
  3164. * set_current_state(TASK_UNINTERRUPTIBLE);
  3165. *
  3166. * if (CONDITION)
  3167. * break;
  3168. *
  3169. * schedule();
  3170. * }
  3171. * __set_current_state(TASK_RUNNING);
  3172. *
  3173. * between set_current_state() and schedule(). In this case @p is still
  3174. * runnable, so all that needs doing is change p->state back to TASK_RUNNING in
  3175. * an atomic manner.
  3176. *
  3177. * By taking task_rq(p)->lock we serialize against schedule(), if @p->on_rq
  3178. * then schedule() must still happen and p->state can be changed to
  3179. * TASK_RUNNING. Otherwise we lost the race, schedule() has happened, and we
  3180. * need to do a full wakeup with enqueue.
  3181. *
  3182. * Returns: %true when the wakeup is done,
  3183. * %false otherwise.
  3184. */
  3185. static int ttwu_runnable(struct task_struct *p, int wake_flags)
  3186. {
  3187. struct rq_flags rf;
  3188. struct rq *rq;
  3189. int ret = 0;
  3190. rq = __task_rq_lock(p, &rf);
  3191. if (task_on_rq_queued(p)) {
  3192. update_rq_clock(rq);
  3193. if (p->se.sched_delayed)
  3194. enqueue_task(rq, p, ENQUEUE_NOCLOCK | ENQUEUE_DELAYED);
  3195. if (!task_on_cpu(rq, p)) {
  3196. /*
  3197. * When on_rq && !on_cpu the task is preempted, see if
  3198. * it should preempt the task that is current now.
  3199. */
  3200. wakeup_preempt(rq, p, wake_flags);
  3201. }
  3202. ttwu_do_wakeup(p);
  3203. ret = 1;
  3204. }
  3205. __task_rq_unlock(rq, &rf);
  3206. return ret;
  3207. }
  3208. #ifdef CONFIG_SMP
  3209. void sched_ttwu_pending(void *arg)
  3210. {
  3211. struct llist_node *llist = arg;
  3212. struct rq *rq = this_rq();
  3213. struct task_struct *p, *t;
  3214. struct rq_flags rf;
  3215. if (!llist)
  3216. return;
  3217. rq_lock_irqsave(rq, &rf);
  3218. update_rq_clock(rq);
  3219. llist_for_each_entry_safe(p, t, llist, wake_entry.llist) {
  3220. if (WARN_ON_ONCE(p->on_cpu))
  3221. smp_cond_load_acquire(&p->on_cpu, !VAL);
  3222. if (WARN_ON_ONCE(task_cpu(p) != cpu_of(rq)))
  3223. set_task_cpu(p, cpu_of(rq));
  3224. ttwu_do_activate(rq, p, p->sched_remote_wakeup ? WF_MIGRATED : 0, &rf);
  3225. }
  3226. /*
  3227. * Must be after enqueueing at least once task such that
  3228. * idle_cpu() does not observe a false-negative -- if it does,
  3229. * it is possible for select_idle_siblings() to stack a number
  3230. * of tasks on this CPU during that window.
  3231. *
  3232. * It is OK to clear ttwu_pending when another task pending.
  3233. * We will receive IPI after local IRQ enabled and then enqueue it.
  3234. * Since now nr_running > 0, idle_cpu() will always get correct result.
  3235. */
  3236. WRITE_ONCE(rq->ttwu_pending, 0);
  3237. rq_unlock_irqrestore(rq, &rf);
  3238. }
  3239. /*
  3240. * Prepare the scene for sending an IPI for a remote smp_call
  3241. *
  3242. * Returns true if the caller can proceed with sending the IPI.
  3243. * Returns false otherwise.
  3244. */
  3245. bool call_function_single_prep_ipi(int cpu)
  3246. {
  3247. if (set_nr_if_polling(cpu_rq(cpu)->idle)) {
  3248. trace_sched_wake_idle_without_ipi(cpu);
  3249. return false;
  3250. }
  3251. return true;
  3252. }
  3253. /*
  3254. * Queue a task on the target CPUs wake_list and wake the CPU via IPI if
  3255. * necessary. The wakee CPU on receipt of the IPI will queue the task
  3256. * via sched_ttwu_wakeup() for activation so the wakee incurs the cost
  3257. * of the wakeup instead of the waker.
  3258. */
  3259. static void __ttwu_queue_wakelist(struct task_struct *p, int cpu, int wake_flags)
  3260. {
  3261. struct rq *rq = cpu_rq(cpu);
  3262. p->sched_remote_wakeup = !!(wake_flags & WF_MIGRATED);
  3263. WRITE_ONCE(rq->ttwu_pending, 1);
  3264. __smp_call_single_queue(cpu, &p->wake_entry.llist);
  3265. }
  3266. void wake_up_if_idle(int cpu)
  3267. {
  3268. struct rq *rq = cpu_rq(cpu);
  3269. guard(rcu)();
  3270. if (is_idle_task(rcu_dereference(rq->curr))) {
  3271. guard(rq_lock_irqsave)(rq);
  3272. if (is_idle_task(rq->curr))
  3273. resched_curr(rq);
  3274. }
  3275. }
  3276. bool cpus_equal_capacity(int this_cpu, int that_cpu)
  3277. {
  3278. if (!sched_asym_cpucap_active())
  3279. return true;
  3280. if (this_cpu == that_cpu)
  3281. return true;
  3282. return arch_scale_cpu_capacity(this_cpu) == arch_scale_cpu_capacity(that_cpu);
  3283. }
  3284. bool cpus_share_cache(int this_cpu, int that_cpu)
  3285. {
  3286. if (this_cpu == that_cpu)
  3287. return true;
  3288. return per_cpu(sd_llc_id, this_cpu) == per_cpu(sd_llc_id, that_cpu);
  3289. }
  3290. /*
  3291. * Whether CPUs are share cache resources, which means LLC on non-cluster
  3292. * machines and LLC tag or L2 on machines with clusters.
  3293. */
  3294. bool cpus_share_resources(int this_cpu, int that_cpu)
  3295. {
  3296. if (this_cpu == that_cpu)
  3297. return true;
  3298. return per_cpu(sd_share_id, this_cpu) == per_cpu(sd_share_id, that_cpu);
  3299. }
  3300. static inline bool ttwu_queue_cond(struct task_struct *p, int cpu)
  3301. {
  3302. /*
  3303. * The BPF scheduler may depend on select_task_rq() being invoked during
  3304. * wakeups. In addition, @p may end up executing on a different CPU
  3305. * regardless of what happens in the wakeup path making the ttwu_queue
  3306. * optimization less meaningful. Skip if on SCX.
  3307. */
  3308. if (task_on_scx(p))
  3309. return false;
  3310. #ifdef CONFIG_SMP
  3311. if (p->sched_class == &stop_sched_class)
  3312. return false;
  3313. #endif
  3314. /*
  3315. * Do not complicate things with the async wake_list while the CPU is
  3316. * in hotplug state.
  3317. */
  3318. if (!cpu_active(cpu))
  3319. return false;
  3320. /* Ensure the task will still be allowed to run on the CPU. */
  3321. if (!cpumask_test_cpu(cpu, p->cpus_ptr))
  3322. return false;
  3323. /*
  3324. * If the CPU does not share cache, then queue the task on the
  3325. * remote rqs wakelist to avoid accessing remote data.
  3326. */
  3327. if (!cpus_share_cache(smp_processor_id(), cpu))
  3328. return true;
  3329. if (cpu == smp_processor_id())
  3330. return false;
  3331. /*
  3332. * If the wakee cpu is idle, or the task is descheduling and the
  3333. * only running task on the CPU, then use the wakelist to offload
  3334. * the task activation to the idle (or soon-to-be-idle) CPU as
  3335. * the current CPU is likely busy. nr_running is checked to
  3336. * avoid unnecessary task stacking.
  3337. *
  3338. * Note that we can only get here with (wakee) p->on_rq=0,
  3339. * p->on_cpu can be whatever, we've done the dequeue, so
  3340. * the wakee has been accounted out of ->nr_running.
  3341. */
  3342. if (!cpu_rq(cpu)->nr_running)
  3343. return true;
  3344. return false;
  3345. }
  3346. static bool ttwu_queue_wakelist(struct task_struct *p, int cpu, int wake_flags)
  3347. {
  3348. if (sched_feat(TTWU_QUEUE) && ttwu_queue_cond(p, cpu)) {
  3349. sched_clock_cpu(cpu); /* Sync clocks across CPUs */
  3350. __ttwu_queue_wakelist(p, cpu, wake_flags);
  3351. return true;
  3352. }
  3353. return false;
  3354. }
  3355. #else /* !CONFIG_SMP */
  3356. static inline bool ttwu_queue_wakelist(struct task_struct *p, int cpu, int wake_flags)
  3357. {
  3358. return false;
  3359. }
  3360. #endif /* CONFIG_SMP */
  3361. static void ttwu_queue(struct task_struct *p, int cpu, int wake_flags)
  3362. {
  3363. struct rq *rq = cpu_rq(cpu);
  3364. struct rq_flags rf;
  3365. if (ttwu_queue_wakelist(p, cpu, wake_flags))
  3366. return;
  3367. rq_lock(rq, &rf);
  3368. update_rq_clock(rq);
  3369. ttwu_do_activate(rq, p, wake_flags, &rf);
  3370. rq_unlock(rq, &rf);
  3371. }
  3372. /*
  3373. * Invoked from try_to_wake_up() to check whether the task can be woken up.
  3374. *
  3375. * The caller holds p::pi_lock if p != current or has preemption
  3376. * disabled when p == current.
  3377. *
  3378. * The rules of saved_state:
  3379. *
  3380. * The related locking code always holds p::pi_lock when updating
  3381. * p::saved_state, which means the code is fully serialized in both cases.
  3382. *
  3383. * For PREEMPT_RT, the lock wait and lock wakeups happen via TASK_RTLOCK_WAIT.
  3384. * No other bits set. This allows to distinguish all wakeup scenarios.
  3385. *
  3386. * For FREEZER, the wakeup happens via TASK_FROZEN. No other bits set. This
  3387. * allows us to prevent early wakeup of tasks before they can be run on
  3388. * asymmetric ISA architectures (eg ARMv9).
  3389. */
  3390. static __always_inline
  3391. bool ttwu_state_match(struct task_struct *p, unsigned int state, int *success)
  3392. {
  3393. int match;
  3394. if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)) {
  3395. WARN_ON_ONCE((state & TASK_RTLOCK_WAIT) &&
  3396. state != TASK_RTLOCK_WAIT);
  3397. }
  3398. *success = !!(match = __task_state_match(p, state));
  3399. /*
  3400. * Saved state preserves the task state across blocking on
  3401. * an RT lock or TASK_FREEZABLE tasks. If the state matches,
  3402. * set p::saved_state to TASK_RUNNING, but do not wake the task
  3403. * because it waits for a lock wakeup or __thaw_task(). Also
  3404. * indicate success because from the regular waker's point of
  3405. * view this has succeeded.
  3406. *
  3407. * After acquiring the lock the task will restore p::__state
  3408. * from p::saved_state which ensures that the regular
  3409. * wakeup is not lost. The restore will also set
  3410. * p::saved_state to TASK_RUNNING so any further tests will
  3411. * not result in false positives vs. @success
  3412. */
  3413. if (match < 0)
  3414. p->saved_state = TASK_RUNNING;
  3415. return match > 0;
  3416. }
  3417. /*
  3418. * Notes on Program-Order guarantees on SMP systems.
  3419. *
  3420. * MIGRATION
  3421. *
  3422. * The basic program-order guarantee on SMP systems is that when a task [t]
  3423. * migrates, all its activity on its old CPU [c0] happens-before any subsequent
  3424. * execution on its new CPU [c1].
  3425. *
  3426. * For migration (of runnable tasks) this is provided by the following means:
  3427. *
  3428. * A) UNLOCK of the rq(c0)->lock scheduling out task t
  3429. * B) migration for t is required to synchronize *both* rq(c0)->lock and
  3430. * rq(c1)->lock (if not at the same time, then in that order).
  3431. * C) LOCK of the rq(c1)->lock scheduling in task
  3432. *
  3433. * Release/acquire chaining guarantees that B happens after A and C after B.
  3434. * Note: the CPU doing B need not be c0 or c1
  3435. *
  3436. * Example:
  3437. *
  3438. * CPU0 CPU1 CPU2
  3439. *
  3440. * LOCK rq(0)->lock
  3441. * sched-out X
  3442. * sched-in Y
  3443. * UNLOCK rq(0)->lock
  3444. *
  3445. * LOCK rq(0)->lock // orders against CPU0
  3446. * dequeue X
  3447. * UNLOCK rq(0)->lock
  3448. *
  3449. * LOCK rq(1)->lock
  3450. * enqueue X
  3451. * UNLOCK rq(1)->lock
  3452. *
  3453. * LOCK rq(1)->lock // orders against CPU2
  3454. * sched-out Z
  3455. * sched-in X
  3456. * UNLOCK rq(1)->lock
  3457. *
  3458. *
  3459. * BLOCKING -- aka. SLEEP + WAKEUP
  3460. *
  3461. * For blocking we (obviously) need to provide the same guarantee as for
  3462. * migration. However the means are completely different as there is no lock
  3463. * chain to provide order. Instead we do:
  3464. *
  3465. * 1) smp_store_release(X->on_cpu, 0) -- finish_task()
  3466. * 2) smp_cond_load_acquire(!X->on_cpu) -- try_to_wake_up()
  3467. *
  3468. * Example:
  3469. *
  3470. * CPU0 (schedule) CPU1 (try_to_wake_up) CPU2 (schedule)
  3471. *
  3472. * LOCK rq(0)->lock LOCK X->pi_lock
  3473. * dequeue X
  3474. * sched-out X
  3475. * smp_store_release(X->on_cpu, 0);
  3476. *
  3477. * smp_cond_load_acquire(&X->on_cpu, !VAL);
  3478. * X->state = WAKING
  3479. * set_task_cpu(X,2)
  3480. *
  3481. * LOCK rq(2)->lock
  3482. * enqueue X
  3483. * X->state = RUNNING
  3484. * UNLOCK rq(2)->lock
  3485. *
  3486. * LOCK rq(2)->lock // orders against CPU1
  3487. * sched-out Z
  3488. * sched-in X
  3489. * UNLOCK rq(2)->lock
  3490. *
  3491. * UNLOCK X->pi_lock
  3492. * UNLOCK rq(0)->lock
  3493. *
  3494. *
  3495. * However, for wakeups there is a second guarantee we must provide, namely we
  3496. * must ensure that CONDITION=1 done by the caller can not be reordered with
  3497. * accesses to the task state; see try_to_wake_up() and set_current_state().
  3498. */
  3499. /**
  3500. * try_to_wake_up - wake up a thread
  3501. * @p: the thread to be awakened
  3502. * @state: the mask of task states that can be woken
  3503. * @wake_flags: wake modifier flags (WF_*)
  3504. *
  3505. * Conceptually does:
  3506. *
  3507. * If (@state & @p->state) @p->state = TASK_RUNNING.
  3508. *
  3509. * If the task was not queued/runnable, also place it back on a runqueue.
  3510. *
  3511. * This function is atomic against schedule() which would dequeue the task.
  3512. *
  3513. * It issues a full memory barrier before accessing @p->state, see the comment
  3514. * with set_current_state().
  3515. *
  3516. * Uses p->pi_lock to serialize against concurrent wake-ups.
  3517. *
  3518. * Relies on p->pi_lock stabilizing:
  3519. * - p->sched_class
  3520. * - p->cpus_ptr
  3521. * - p->sched_task_group
  3522. * in order to do migration, see its use of select_task_rq()/set_task_cpu().
  3523. *
  3524. * Tries really hard to only take one task_rq(p)->lock for performance.
  3525. * Takes rq->lock in:
  3526. * - ttwu_runnable() -- old rq, unavoidable, see comment there;
  3527. * - ttwu_queue() -- new rq, for enqueue of the task;
  3528. * - psi_ttwu_dequeue() -- much sadness :-( accounting will kill us.
  3529. *
  3530. * As a consequence we race really badly with just about everything. See the
  3531. * many memory barriers and their comments for details.
  3532. *
  3533. * Return: %true if @p->state changes (an actual wakeup was done),
  3534. * %false otherwise.
  3535. */
  3536. int try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)
  3537. {
  3538. guard(preempt)();
  3539. int cpu, success = 0;
  3540. wake_flags |= WF_TTWU;
  3541. if (p == current) {
  3542. /*
  3543. * We're waking current, this means 'p->on_rq' and 'task_cpu(p)
  3544. * == smp_processor_id()'. Together this means we can special
  3545. * case the whole 'p->on_rq && ttwu_runnable()' case below
  3546. * without taking any locks.
  3547. *
  3548. * Specifically, given current runs ttwu() we must be before
  3549. * schedule()'s block_task(), as such this must not observe
  3550. * sched_delayed.
  3551. *
  3552. * In particular:
  3553. * - we rely on Program-Order guarantees for all the ordering,
  3554. * - we're serialized against set_special_state() by virtue of
  3555. * it disabling IRQs (this allows not taking ->pi_lock).
  3556. */
  3557. SCHED_WARN_ON(p->se.sched_delayed);
  3558. if (!ttwu_state_match(p, state, &success))
  3559. goto out;
  3560. trace_sched_waking(p);
  3561. ttwu_do_wakeup(p);
  3562. goto out;
  3563. }
  3564. /*
  3565. * If we are going to wake up a thread waiting for CONDITION we
  3566. * need to ensure that CONDITION=1 done by the caller can not be
  3567. * reordered with p->state check below. This pairs with smp_store_mb()
  3568. * in set_current_state() that the waiting thread does.
  3569. */
  3570. scoped_guard (raw_spinlock_irqsave, &p->pi_lock) {
  3571. smp_mb__after_spinlock();
  3572. if (!ttwu_state_match(p, state, &success))
  3573. break;
  3574. trace_sched_waking(p);
  3575. /*
  3576. * Ensure we load p->on_rq _after_ p->state, otherwise it would
  3577. * be possible to, falsely, observe p->on_rq == 0 and get stuck
  3578. * in smp_cond_load_acquire() below.
  3579. *
  3580. * sched_ttwu_pending() try_to_wake_up()
  3581. * STORE p->on_rq = 1 LOAD p->state
  3582. * UNLOCK rq->lock
  3583. *
  3584. * __schedule() (switch to task 'p')
  3585. * LOCK rq->lock smp_rmb();
  3586. * smp_mb__after_spinlock();
  3587. * UNLOCK rq->lock
  3588. *
  3589. * [task p]
  3590. * STORE p->state = UNINTERRUPTIBLE LOAD p->on_rq
  3591. *
  3592. * Pairs with the LOCK+smp_mb__after_spinlock() on rq->lock in
  3593. * __schedule(). See the comment for smp_mb__after_spinlock().
  3594. *
  3595. * A similar smp_rmb() lives in __task_needs_rq_lock().
  3596. */
  3597. smp_rmb();
  3598. if (READ_ONCE(p->on_rq) && ttwu_runnable(p, wake_flags))
  3599. break;
  3600. #ifdef CONFIG_SMP
  3601. /*
  3602. * Ensure we load p->on_cpu _after_ p->on_rq, otherwise it would be
  3603. * possible to, falsely, observe p->on_cpu == 0.
  3604. *
  3605. * One must be running (->on_cpu == 1) in order to remove oneself
  3606. * from the runqueue.
  3607. *
  3608. * __schedule() (switch to task 'p') try_to_wake_up()
  3609. * STORE p->on_cpu = 1 LOAD p->on_rq
  3610. * UNLOCK rq->lock
  3611. *
  3612. * __schedule() (put 'p' to sleep)
  3613. * LOCK rq->lock smp_rmb();
  3614. * smp_mb__after_spinlock();
  3615. * STORE p->on_rq = 0 LOAD p->on_cpu
  3616. *
  3617. * Pairs with the LOCK+smp_mb__after_spinlock() on rq->lock in
  3618. * __schedule(). See the comment for smp_mb__after_spinlock().
  3619. *
  3620. * Form a control-dep-acquire with p->on_rq == 0 above, to ensure
  3621. * schedule()'s deactivate_task() has 'happened' and p will no longer
  3622. * care about it's own p->state. See the comment in __schedule().
  3623. */
  3624. smp_acquire__after_ctrl_dep();
  3625. /*
  3626. * We're doing the wakeup (@success == 1), they did a dequeue (p->on_rq
  3627. * == 0), which means we need to do an enqueue, change p->state to
  3628. * TASK_WAKING such that we can unlock p->pi_lock before doing the
  3629. * enqueue, such as ttwu_queue_wakelist().
  3630. */
  3631. WRITE_ONCE(p->__state, TASK_WAKING);
  3632. /*
  3633. * If the owning (remote) CPU is still in the middle of schedule() with
  3634. * this task as prev, considering queueing p on the remote CPUs wake_list
  3635. * which potentially sends an IPI instead of spinning on p->on_cpu to
  3636. * let the waker make forward progress. This is safe because IRQs are
  3637. * disabled and the IPI will deliver after on_cpu is cleared.
  3638. *
  3639. * Ensure we load task_cpu(p) after p->on_cpu:
  3640. *
  3641. * set_task_cpu(p, cpu);
  3642. * STORE p->cpu = @cpu
  3643. * __schedule() (switch to task 'p')
  3644. * LOCK rq->lock
  3645. * smp_mb__after_spin_lock() smp_cond_load_acquire(&p->on_cpu)
  3646. * STORE p->on_cpu = 1 LOAD p->cpu
  3647. *
  3648. * to ensure we observe the correct CPU on which the task is currently
  3649. * scheduling.
  3650. */
  3651. if (smp_load_acquire(&p->on_cpu) &&
  3652. ttwu_queue_wakelist(p, task_cpu(p), wake_flags))
  3653. break;
  3654. /*
  3655. * If the owning (remote) CPU is still in the middle of schedule() with
  3656. * this task as prev, wait until it's done referencing the task.
  3657. *
  3658. * Pairs with the smp_store_release() in finish_task().
  3659. *
  3660. * This ensures that tasks getting woken will be fully ordered against
  3661. * their previous state and preserve Program Order.
  3662. */
  3663. smp_cond_load_acquire(&p->on_cpu, !VAL);
  3664. cpu = select_task_rq(p, p->wake_cpu, &wake_flags);
  3665. if (task_cpu(p) != cpu) {
  3666. if (p->in_iowait) {
  3667. delayacct_blkio_end(p);
  3668. atomic_dec(&task_rq(p)->nr_iowait);
  3669. }
  3670. wake_flags |= WF_MIGRATED;
  3671. psi_ttwu_dequeue(p);
  3672. set_task_cpu(p, cpu);
  3673. }
  3674. #else
  3675. cpu = task_cpu(p);
  3676. #endif /* CONFIG_SMP */
  3677. ttwu_queue(p, cpu, wake_flags);
  3678. }
  3679. out:
  3680. if (success)
  3681. ttwu_stat(p, task_cpu(p), wake_flags);
  3682. return success;
  3683. }
  3684. static bool __task_needs_rq_lock(struct task_struct *p)
  3685. {
  3686. unsigned int state = READ_ONCE(p->__state);
  3687. /*
  3688. * Since pi->lock blocks try_to_wake_up(), we don't need rq->lock when
  3689. * the task is blocked. Make sure to check @state since ttwu() can drop
  3690. * locks at the end, see ttwu_queue_wakelist().
  3691. */
  3692. if (state == TASK_RUNNING || state == TASK_WAKING)
  3693. return true;
  3694. /*
  3695. * Ensure we load p->on_rq after p->__state, otherwise it would be
  3696. * possible to, falsely, observe p->on_rq == 0.
  3697. *
  3698. * See try_to_wake_up() for a longer comment.
  3699. */
  3700. smp_rmb();
  3701. if (p->on_rq)
  3702. return true;
  3703. #ifdef CONFIG_SMP
  3704. /*
  3705. * Ensure the task has finished __schedule() and will not be referenced
  3706. * anymore. Again, see try_to_wake_up() for a longer comment.
  3707. */
  3708. smp_rmb();
  3709. smp_cond_load_acquire(&p->on_cpu, !VAL);
  3710. #endif
  3711. return false;
  3712. }
  3713. /**
  3714. * task_call_func - Invoke a function on task in fixed state
  3715. * @p: Process for which the function is to be invoked, can be @current.
  3716. * @func: Function to invoke.
  3717. * @arg: Argument to function.
  3718. *
  3719. * Fix the task in it's current state by avoiding wakeups and or rq operations
  3720. * and call @func(@arg) on it. This function can use task_is_runnable() and
  3721. * task_curr() to work out what the state is, if required. Given that @func
  3722. * can be invoked with a runqueue lock held, it had better be quite
  3723. * lightweight.
  3724. *
  3725. * Returns:
  3726. * Whatever @func returns
  3727. */
  3728. int task_call_func(struct task_struct *p, task_call_f func, void *arg)
  3729. {
  3730. struct rq *rq = NULL;
  3731. struct rq_flags rf;
  3732. int ret;
  3733. raw_spin_lock_irqsave(&p->pi_lock, rf.flags);
  3734. if (__task_needs_rq_lock(p))
  3735. rq = __task_rq_lock(p, &rf);
  3736. /*
  3737. * At this point the task is pinned; either:
  3738. * - blocked and we're holding off wakeups (pi->lock)
  3739. * - woken, and we're holding off enqueue (rq->lock)
  3740. * - queued, and we're holding off schedule (rq->lock)
  3741. * - running, and we're holding off de-schedule (rq->lock)
  3742. *
  3743. * The called function (@func) can use: task_curr(), p->on_rq and
  3744. * p->__state to differentiate between these states.
  3745. */
  3746. ret = func(p, arg);
  3747. if (rq)
  3748. rq_unlock(rq, &rf);
  3749. raw_spin_unlock_irqrestore(&p->pi_lock, rf.flags);
  3750. return ret;
  3751. }
  3752. /**
  3753. * cpu_curr_snapshot - Return a snapshot of the currently running task
  3754. * @cpu: The CPU on which to snapshot the task.
  3755. *
  3756. * Returns the task_struct pointer of the task "currently" running on
  3757. * the specified CPU.
  3758. *
  3759. * If the specified CPU was offline, the return value is whatever it
  3760. * is, perhaps a pointer to the task_struct structure of that CPU's idle
  3761. * task, but there is no guarantee. Callers wishing a useful return
  3762. * value must take some action to ensure that the specified CPU remains
  3763. * online throughout.
  3764. *
  3765. * This function executes full memory barriers before and after fetching
  3766. * the pointer, which permits the caller to confine this function's fetch
  3767. * with respect to the caller's accesses to other shared variables.
  3768. */
  3769. struct task_struct *cpu_curr_snapshot(int cpu)
  3770. {
  3771. struct rq *rq = cpu_rq(cpu);
  3772. struct task_struct *t;
  3773. struct rq_flags rf;
  3774. rq_lock_irqsave(rq, &rf);
  3775. smp_mb__after_spinlock(); /* Pairing determined by caller's synchronization design. */
  3776. t = rcu_dereference(cpu_curr(cpu));
  3777. rq_unlock_irqrestore(rq, &rf);
  3778. smp_mb(); /* Pairing determined by caller's synchronization design. */
  3779. return t;
  3780. }
  3781. /**
  3782. * wake_up_process - Wake up a specific process
  3783. * @p: The process to be woken up.
  3784. *
  3785. * Attempt to wake up the nominated process and move it to the set of runnable
  3786. * processes.
  3787. *
  3788. * Return: 1 if the process was woken up, 0 if it was already running.
  3789. *
  3790. * This function executes a full memory barrier before accessing the task state.
  3791. */
  3792. int wake_up_process(struct task_struct *p)
  3793. {
  3794. return try_to_wake_up(p, TASK_NORMAL, 0);
  3795. }
  3796. EXPORT_SYMBOL(wake_up_process);
  3797. int wake_up_state(struct task_struct *p, unsigned int state)
  3798. {
  3799. return try_to_wake_up(p, state, 0);
  3800. }
  3801. /*
  3802. * Perform scheduler related setup for a newly forked process p.
  3803. * p is forked by current.
  3804. *
  3805. * __sched_fork() is basic setup which is also used by sched_init() to
  3806. * initialize the boot CPU's idle task.
  3807. */
  3808. static void __sched_fork(unsigned long clone_flags, struct task_struct *p)
  3809. {
  3810. p->on_rq = 0;
  3811. p->se.on_rq = 0;
  3812. p->se.exec_start = 0;
  3813. p->se.sum_exec_runtime = 0;
  3814. p->se.prev_sum_exec_runtime = 0;
  3815. p->se.nr_migrations = 0;
  3816. p->se.vruntime = 0;
  3817. p->se.vlag = 0;
  3818. INIT_LIST_HEAD(&p->se.group_node);
  3819. /* A delayed task cannot be in clone(). */
  3820. SCHED_WARN_ON(p->se.sched_delayed);
  3821. #ifdef CONFIG_FAIR_GROUP_SCHED
  3822. p->se.cfs_rq = NULL;
  3823. #endif
  3824. #ifdef CONFIG_SCHEDSTATS
  3825. /* Even if schedstat is disabled, there should not be garbage */
  3826. memset(&p->stats, 0, sizeof(p->stats));
  3827. #endif
  3828. init_dl_entity(&p->dl);
  3829. INIT_LIST_HEAD(&p->rt.run_list);
  3830. p->rt.timeout = 0;
  3831. p->rt.time_slice = sched_rr_timeslice;
  3832. p->rt.on_rq = 0;
  3833. p->rt.on_list = 0;
  3834. #ifdef CONFIG_SCHED_CLASS_EXT
  3835. init_scx_entity(&p->scx);
  3836. #endif
  3837. #ifdef CONFIG_PREEMPT_NOTIFIERS
  3838. INIT_HLIST_HEAD(&p->preempt_notifiers);
  3839. #endif
  3840. #ifdef CONFIG_COMPACTION
  3841. p->capture_control = NULL;
  3842. #endif
  3843. init_numa_balancing(clone_flags, p);
  3844. #ifdef CONFIG_SMP
  3845. p->wake_entry.u_flags = CSD_TYPE_TTWU;
  3846. p->migration_pending = NULL;
  3847. #endif
  3848. init_sched_mm_cid(p);
  3849. }
  3850. DEFINE_STATIC_KEY_FALSE(sched_numa_balancing);
  3851. #ifdef CONFIG_NUMA_BALANCING
  3852. int sysctl_numa_balancing_mode;
  3853. static void __set_numabalancing_state(bool enabled)
  3854. {
  3855. if (enabled)
  3856. static_branch_enable(&sched_numa_balancing);
  3857. else
  3858. static_branch_disable(&sched_numa_balancing);
  3859. }
  3860. void set_numabalancing_state(bool enabled)
  3861. {
  3862. if (enabled)
  3863. sysctl_numa_balancing_mode = NUMA_BALANCING_NORMAL;
  3864. else
  3865. sysctl_numa_balancing_mode = NUMA_BALANCING_DISABLED;
  3866. __set_numabalancing_state(enabled);
  3867. }
  3868. #ifdef CONFIG_PROC_SYSCTL
  3869. static void reset_memory_tiering(void)
  3870. {
  3871. struct pglist_data *pgdat;
  3872. for_each_online_pgdat(pgdat) {
  3873. pgdat->nbp_threshold = 0;
  3874. pgdat->nbp_th_nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE);
  3875. pgdat->nbp_th_start = jiffies_to_msecs(jiffies);
  3876. }
  3877. }
  3878. static int sysctl_numa_balancing(const struct ctl_table *table, int write,
  3879. void *buffer, size_t *lenp, loff_t *ppos)
  3880. {
  3881. struct ctl_table t;
  3882. int err;
  3883. int state = sysctl_numa_balancing_mode;
  3884. if (write && !capable(CAP_SYS_ADMIN))
  3885. return -EPERM;
  3886. t = *table;
  3887. t.data = &state;
  3888. err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
  3889. if (err < 0)
  3890. return err;
  3891. if (write) {
  3892. if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) &&
  3893. (state & NUMA_BALANCING_MEMORY_TIERING))
  3894. reset_memory_tiering();
  3895. sysctl_numa_balancing_mode = state;
  3896. __set_numabalancing_state(state);
  3897. }
  3898. return err;
  3899. }
  3900. #endif
  3901. #endif
  3902. #ifdef CONFIG_SCHEDSTATS
  3903. DEFINE_STATIC_KEY_FALSE(sched_schedstats);
  3904. static void set_schedstats(bool enabled)
  3905. {
  3906. if (enabled)
  3907. static_branch_enable(&sched_schedstats);
  3908. else
  3909. static_branch_disable(&sched_schedstats);
  3910. }
  3911. void force_schedstat_enabled(void)
  3912. {
  3913. if (!schedstat_enabled()) {
  3914. pr_info("kernel profiling enabled schedstats, disable via kernel.sched_schedstats.\n");
  3915. static_branch_enable(&sched_schedstats);
  3916. }
  3917. }
  3918. static int __init setup_schedstats(char *str)
  3919. {
  3920. int ret = 0;
  3921. if (!str)
  3922. goto out;
  3923. if (!strcmp(str, "enable")) {
  3924. set_schedstats(true);
  3925. ret = 1;
  3926. } else if (!strcmp(str, "disable")) {
  3927. set_schedstats(false);
  3928. ret = 1;
  3929. }
  3930. out:
  3931. if (!ret)
  3932. pr_warn("Unable to parse schedstats=\n");
  3933. return ret;
  3934. }
  3935. __setup("schedstats=", setup_schedstats);
  3936. #ifdef CONFIG_PROC_SYSCTL
  3937. static int sysctl_schedstats(const struct ctl_table *table, int write, void *buffer,
  3938. size_t *lenp, loff_t *ppos)
  3939. {
  3940. struct ctl_table t;
  3941. int err;
  3942. int state = static_branch_likely(&sched_schedstats);
  3943. if (write && !capable(CAP_SYS_ADMIN))
  3944. return -EPERM;
  3945. t = *table;
  3946. t.data = &state;
  3947. err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
  3948. if (err < 0)
  3949. return err;
  3950. if (write)
  3951. set_schedstats(state);
  3952. return err;
  3953. }
  3954. #endif /* CONFIG_PROC_SYSCTL */
  3955. #endif /* CONFIG_SCHEDSTATS */
  3956. #ifdef CONFIG_SYSCTL
  3957. static struct ctl_table sched_core_sysctls[] = {
  3958. #ifdef CONFIG_SCHEDSTATS
  3959. {
  3960. .procname = "sched_schedstats",
  3961. .data = NULL,
  3962. .maxlen = sizeof(unsigned int),
  3963. .mode = 0644,
  3964. .proc_handler = sysctl_schedstats,
  3965. .extra1 = SYSCTL_ZERO,
  3966. .extra2 = SYSCTL_ONE,
  3967. },
  3968. #endif /* CONFIG_SCHEDSTATS */
  3969. #ifdef CONFIG_UCLAMP_TASK
  3970. {
  3971. .procname = "sched_util_clamp_min",
  3972. .data = &sysctl_sched_uclamp_util_min,
  3973. .maxlen = sizeof(unsigned int),
  3974. .mode = 0644,
  3975. .proc_handler = sysctl_sched_uclamp_handler,
  3976. },
  3977. {
  3978. .procname = "sched_util_clamp_max",
  3979. .data = &sysctl_sched_uclamp_util_max,
  3980. .maxlen = sizeof(unsigned int),
  3981. .mode = 0644,
  3982. .proc_handler = sysctl_sched_uclamp_handler,
  3983. },
  3984. {
  3985. .procname = "sched_util_clamp_min_rt_default",
  3986. .data = &sysctl_sched_uclamp_util_min_rt_default,
  3987. .maxlen = sizeof(unsigned int),
  3988. .mode = 0644,
  3989. .proc_handler = sysctl_sched_uclamp_handler,
  3990. },
  3991. #endif /* CONFIG_UCLAMP_TASK */
  3992. #ifdef CONFIG_NUMA_BALANCING
  3993. {
  3994. .procname = "numa_balancing",
  3995. .data = NULL, /* filled in by handler */
  3996. .maxlen = sizeof(unsigned int),
  3997. .mode = 0644,
  3998. .proc_handler = sysctl_numa_balancing,
  3999. .extra1 = SYSCTL_ZERO,
  4000. .extra2 = SYSCTL_FOUR,
  4001. },
  4002. #endif /* CONFIG_NUMA_BALANCING */
  4003. };
  4004. static int __init sched_core_sysctl_init(void)
  4005. {
  4006. register_sysctl_init("kernel", sched_core_sysctls);
  4007. return 0;
  4008. }
  4009. late_initcall(sched_core_sysctl_init);
  4010. #endif /* CONFIG_SYSCTL */
  4011. /*
  4012. * fork()/clone()-time setup:
  4013. */
  4014. int sched_fork(unsigned long clone_flags, struct task_struct *p)
  4015. {
  4016. __sched_fork(clone_flags, p);
  4017. /*
  4018. * We mark the process as NEW here. This guarantees that
  4019. * nobody will actually run it, and a signal or other external
  4020. * event cannot wake it up and insert it on the runqueue either.
  4021. */
  4022. p->__state = TASK_NEW;
  4023. /*
  4024. * Make sure we do not leak PI boosting priority to the child.
  4025. */
  4026. p->prio = current->normal_prio;
  4027. uclamp_fork(p);
  4028. /*
  4029. * Revert to default priority/policy on fork if requested.
  4030. */
  4031. if (unlikely(p->sched_reset_on_fork)) {
  4032. if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
  4033. p->policy = SCHED_NORMAL;
  4034. p->static_prio = NICE_TO_PRIO(0);
  4035. p->rt_priority = 0;
  4036. } else if (PRIO_TO_NICE(p->static_prio) < 0)
  4037. p->static_prio = NICE_TO_PRIO(0);
  4038. p->prio = p->normal_prio = p->static_prio;
  4039. set_load_weight(p, false);
  4040. p->se.custom_slice = 0;
  4041. p->se.slice = sysctl_sched_base_slice;
  4042. /*
  4043. * We don't need the reset flag anymore after the fork. It has
  4044. * fulfilled its duty:
  4045. */
  4046. p->sched_reset_on_fork = 0;
  4047. }
  4048. if (dl_prio(p->prio))
  4049. return -EAGAIN;
  4050. scx_pre_fork(p);
  4051. if (rt_prio(p->prio)) {
  4052. p->sched_class = &rt_sched_class;
  4053. #ifdef CONFIG_SCHED_CLASS_EXT
  4054. } else if (task_should_scx(p->policy)) {
  4055. p->sched_class = &ext_sched_class;
  4056. #endif
  4057. } else {
  4058. p->sched_class = &fair_sched_class;
  4059. }
  4060. init_entity_runnable_average(&p->se);
  4061. #ifdef CONFIG_SCHED_INFO
  4062. if (likely(sched_info_on()))
  4063. memset(&p->sched_info, 0, sizeof(p->sched_info));
  4064. #endif
  4065. #if defined(CONFIG_SMP)
  4066. p->on_cpu = 0;
  4067. #endif
  4068. init_task_preempt_count(p);
  4069. #ifdef CONFIG_SMP
  4070. plist_node_init(&p->pushable_tasks, MAX_PRIO);
  4071. RB_CLEAR_NODE(&p->pushable_dl_tasks);
  4072. #endif
  4073. return 0;
  4074. }
  4075. int sched_cgroup_fork(struct task_struct *p, struct kernel_clone_args *kargs)
  4076. {
  4077. unsigned long flags;
  4078. /*
  4079. * Because we're not yet on the pid-hash, p->pi_lock isn't strictly
  4080. * required yet, but lockdep gets upset if rules are violated.
  4081. */
  4082. raw_spin_lock_irqsave(&p->pi_lock, flags);
  4083. #ifdef CONFIG_CGROUP_SCHED
  4084. if (1) {
  4085. struct task_group *tg;
  4086. tg = container_of(kargs->cset->subsys[cpu_cgrp_id],
  4087. struct task_group, css);
  4088. tg = autogroup_task_group(p, tg);
  4089. p->sched_task_group = tg;
  4090. }
  4091. #endif
  4092. rseq_migrate(p);
  4093. /*
  4094. * We're setting the CPU for the first time, we don't migrate,
  4095. * so use __set_task_cpu().
  4096. */
  4097. __set_task_cpu(p, smp_processor_id());
  4098. if (p->sched_class->task_fork)
  4099. p->sched_class->task_fork(p);
  4100. raw_spin_unlock_irqrestore(&p->pi_lock, flags);
  4101. return scx_fork(p);
  4102. }
  4103. void sched_cancel_fork(struct task_struct *p)
  4104. {
  4105. scx_cancel_fork(p);
  4106. }
  4107. void sched_post_fork(struct task_struct *p)
  4108. {
  4109. uclamp_post_fork(p);
  4110. scx_post_fork(p);
  4111. }
  4112. unsigned long to_ratio(u64 period, u64 runtime)
  4113. {
  4114. if (runtime == RUNTIME_INF)
  4115. return BW_UNIT;
  4116. /*
  4117. * Doing this here saves a lot of checks in all
  4118. * the calling paths, and returning zero seems
  4119. * safe for them anyway.
  4120. */
  4121. if (period == 0)
  4122. return 0;
  4123. return div64_u64(runtime << BW_SHIFT, period);
  4124. }
  4125. /*
  4126. * wake_up_new_task - wake up a newly created task for the first time.
  4127. *
  4128. * This function will do some initial scheduler statistics housekeeping
  4129. * that must be done for every newly created context, then puts the task
  4130. * on the runqueue and wakes it.
  4131. */
  4132. void wake_up_new_task(struct task_struct *p)
  4133. {
  4134. struct rq_flags rf;
  4135. struct rq *rq;
  4136. int wake_flags = WF_FORK;
  4137. raw_spin_lock_irqsave(&p->pi_lock, rf.flags);
  4138. WRITE_ONCE(p->__state, TASK_RUNNING);
  4139. #ifdef CONFIG_SMP
  4140. /*
  4141. * Fork balancing, do it here and not earlier because:
  4142. * - cpus_ptr can change in the fork path
  4143. * - any previously selected CPU might disappear through hotplug
  4144. *
  4145. * Use __set_task_cpu() to avoid calling sched_class::migrate_task_rq,
  4146. * as we're not fully set-up yet.
  4147. */
  4148. p->recent_used_cpu = task_cpu(p);
  4149. rseq_migrate(p);
  4150. __set_task_cpu(p, select_task_rq(p, task_cpu(p), &wake_flags));
  4151. #endif
  4152. rq = __task_rq_lock(p, &rf);
  4153. update_rq_clock(rq);
  4154. post_init_entity_util_avg(p);
  4155. activate_task(rq, p, ENQUEUE_NOCLOCK | ENQUEUE_INITIAL);
  4156. trace_sched_wakeup_new(p);
  4157. wakeup_preempt(rq, p, wake_flags);
  4158. #ifdef CONFIG_SMP
  4159. if (p->sched_class->task_woken) {
  4160. /*
  4161. * Nothing relies on rq->lock after this, so it's fine to
  4162. * drop it.
  4163. */
  4164. rq_unpin_lock(rq, &rf);
  4165. p->sched_class->task_woken(rq, p);
  4166. rq_repin_lock(rq, &rf);
  4167. }
  4168. #endif
  4169. task_rq_unlock(rq, p, &rf);
  4170. }
  4171. #ifdef CONFIG_PREEMPT_NOTIFIERS
  4172. static DEFINE_STATIC_KEY_FALSE(preempt_notifier_key);
  4173. void preempt_notifier_inc(void)
  4174. {
  4175. static_branch_inc(&preempt_notifier_key);
  4176. }
  4177. EXPORT_SYMBOL_GPL(preempt_notifier_inc);
  4178. void preempt_notifier_dec(void)
  4179. {
  4180. static_branch_dec(&preempt_notifier_key);
  4181. }
  4182. EXPORT_SYMBOL_GPL(preempt_notifier_dec);
  4183. /**
  4184. * preempt_notifier_register - tell me when current is being preempted & rescheduled
  4185. * @notifier: notifier struct to register
  4186. */
  4187. void preempt_notifier_register(struct preempt_notifier *notifier)
  4188. {
  4189. if (!static_branch_unlikely(&preempt_notifier_key))
  4190. WARN(1, "registering preempt_notifier while notifiers disabled\n");
  4191. hlist_add_head(&notifier->link, &current->preempt_notifiers);
  4192. }
  4193. EXPORT_SYMBOL_GPL(preempt_notifier_register);
  4194. /**
  4195. * preempt_notifier_unregister - no longer interested in preemption notifications
  4196. * @notifier: notifier struct to unregister
  4197. *
  4198. * This is *not* safe to call from within a preemption notifier.
  4199. */
  4200. void preempt_notifier_unregister(struct preempt_notifier *notifier)
  4201. {
  4202. hlist_del(&notifier->link);
  4203. }
  4204. EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
  4205. static void __fire_sched_in_preempt_notifiers(struct task_struct *curr)
  4206. {
  4207. struct preempt_notifier *notifier;
  4208. hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
  4209. notifier->ops->sched_in(notifier, raw_smp_processor_id());
  4210. }
  4211. static __always_inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
  4212. {
  4213. if (static_branch_unlikely(&preempt_notifier_key))
  4214. __fire_sched_in_preempt_notifiers(curr);
  4215. }
  4216. static void
  4217. __fire_sched_out_preempt_notifiers(struct task_struct *curr,
  4218. struct task_struct *next)
  4219. {
  4220. struct preempt_notifier *notifier;
  4221. hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
  4222. notifier->ops->sched_out(notifier, next);
  4223. }
  4224. static __always_inline void
  4225. fire_sched_out_preempt_notifiers(struct task_struct *curr,
  4226. struct task_struct *next)
  4227. {
  4228. if (static_branch_unlikely(&preempt_notifier_key))
  4229. __fire_sched_out_preempt_notifiers(curr, next);
  4230. }
  4231. #else /* !CONFIG_PREEMPT_NOTIFIERS */
  4232. static inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
  4233. {
  4234. }
  4235. static inline void
  4236. fire_sched_out_preempt_notifiers(struct task_struct *curr,
  4237. struct task_struct *next)
  4238. {
  4239. }
  4240. #endif /* CONFIG_PREEMPT_NOTIFIERS */
  4241. static inline void prepare_task(struct task_struct *next)
  4242. {
  4243. #ifdef CONFIG_SMP
  4244. /*
  4245. * Claim the task as running, we do this before switching to it
  4246. * such that any running task will have this set.
  4247. *
  4248. * See the smp_load_acquire(&p->on_cpu) case in ttwu() and
  4249. * its ordering comment.
  4250. */
  4251. WRITE_ONCE(next->on_cpu, 1);
  4252. #endif
  4253. }
  4254. static inline void finish_task(struct task_struct *prev)
  4255. {
  4256. #ifdef CONFIG_SMP
  4257. /*
  4258. * This must be the very last reference to @prev from this CPU. After
  4259. * p->on_cpu is cleared, the task can be moved to a different CPU. We
  4260. * must ensure this doesn't happen until the switch is completely
  4261. * finished.
  4262. *
  4263. * In particular, the load of prev->state in finish_task_switch() must
  4264. * happen before this.
  4265. *
  4266. * Pairs with the smp_cond_load_acquire() in try_to_wake_up().
  4267. */
  4268. smp_store_release(&prev->on_cpu, 0);
  4269. #endif
  4270. }
  4271. #ifdef CONFIG_SMP
  4272. static void do_balance_callbacks(struct rq *rq, struct balance_callback *head)
  4273. {
  4274. void (*func)(struct rq *rq);
  4275. struct balance_callback *next;
  4276. lockdep_assert_rq_held(rq);
  4277. while (head) {
  4278. func = (void (*)(struct rq *))head->func;
  4279. next = head->next;
  4280. head->next = NULL;
  4281. head = next;
  4282. func(rq);
  4283. }
  4284. }
  4285. static void balance_push(struct rq *rq);
  4286. /*
  4287. * balance_push_callback is a right abuse of the callback interface and plays
  4288. * by significantly different rules.
  4289. *
  4290. * Where the normal balance_callback's purpose is to be ran in the same context
  4291. * that queued it (only later, when it's safe to drop rq->lock again),
  4292. * balance_push_callback is specifically targeted at __schedule().
  4293. *
  4294. * This abuse is tolerated because it places all the unlikely/odd cases behind
  4295. * a single test, namely: rq->balance_callback == NULL.
  4296. */
  4297. struct balance_callback balance_push_callback = {
  4298. .next = NULL,
  4299. .func = balance_push,
  4300. };
  4301. static inline struct balance_callback *
  4302. __splice_balance_callbacks(struct rq *rq, bool split)
  4303. {
  4304. struct balance_callback *head = rq->balance_callback;
  4305. if (likely(!head))
  4306. return NULL;
  4307. lockdep_assert_rq_held(rq);
  4308. /*
  4309. * Must not take balance_push_callback off the list when
  4310. * splice_balance_callbacks() and balance_callbacks() are not
  4311. * in the same rq->lock section.
  4312. *
  4313. * In that case it would be possible for __schedule() to interleave
  4314. * and observe the list empty.
  4315. */
  4316. if (split && head == &balance_push_callback)
  4317. head = NULL;
  4318. else
  4319. rq->balance_callback = NULL;
  4320. return head;
  4321. }
  4322. struct balance_callback *splice_balance_callbacks(struct rq *rq)
  4323. {
  4324. return __splice_balance_callbacks(rq, true);
  4325. }
  4326. static void __balance_callbacks(struct rq *rq)
  4327. {
  4328. do_balance_callbacks(rq, __splice_balance_callbacks(rq, false));
  4329. }
  4330. void balance_callbacks(struct rq *rq, struct balance_callback *head)
  4331. {
  4332. unsigned long flags;
  4333. if (unlikely(head)) {
  4334. raw_spin_rq_lock_irqsave(rq, flags);
  4335. do_balance_callbacks(rq, head);
  4336. raw_spin_rq_unlock_irqrestore(rq, flags);
  4337. }
  4338. }
  4339. #else
  4340. static inline void __balance_callbacks(struct rq *rq)
  4341. {
  4342. }
  4343. #endif
  4344. static inline void
  4345. prepare_lock_switch(struct rq *rq, struct task_struct *next, struct rq_flags *rf)
  4346. {
  4347. /*
  4348. * Since the runqueue lock will be released by the next
  4349. * task (which is an invalid locking op but in the case
  4350. * of the scheduler it's an obvious special-case), so we
  4351. * do an early lockdep release here:
  4352. */
  4353. rq_unpin_lock(rq, rf);
  4354. spin_release(&__rq_lockp(rq)->dep_map, _THIS_IP_);
  4355. #ifdef CONFIG_DEBUG_SPINLOCK
  4356. /* this is a valid case when another task releases the spinlock */
  4357. rq_lockp(rq)->owner = next;
  4358. #endif
  4359. }
  4360. static inline void finish_lock_switch(struct rq *rq)
  4361. {
  4362. /*
  4363. * If we are tracking spinlock dependencies then we have to
  4364. * fix up the runqueue lock - which gets 'carried over' from
  4365. * prev into current:
  4366. */
  4367. spin_acquire(&__rq_lockp(rq)->dep_map, 0, 0, _THIS_IP_);
  4368. __balance_callbacks(rq);
  4369. raw_spin_rq_unlock_irq(rq);
  4370. }
  4371. /*
  4372. * NOP if the arch has not defined these:
  4373. */
  4374. #ifndef prepare_arch_switch
  4375. # define prepare_arch_switch(next) do { } while (0)
  4376. #endif
  4377. #ifndef finish_arch_post_lock_switch
  4378. # define finish_arch_post_lock_switch() do { } while (0)
  4379. #endif
  4380. static inline void kmap_local_sched_out(void)
  4381. {
  4382. #ifdef CONFIG_KMAP_LOCAL
  4383. if (unlikely(current->kmap_ctrl.idx))
  4384. __kmap_local_sched_out();
  4385. #endif
  4386. }
  4387. static inline void kmap_local_sched_in(void)
  4388. {
  4389. #ifdef CONFIG_KMAP_LOCAL
  4390. if (unlikely(current->kmap_ctrl.idx))
  4391. __kmap_local_sched_in();
  4392. #endif
  4393. }
  4394. /**
  4395. * prepare_task_switch - prepare to switch tasks
  4396. * @rq: the runqueue preparing to switch
  4397. * @prev: the current task that is being switched out
  4398. * @next: the task we are going to switch to.
  4399. *
  4400. * This is called with the rq lock held and interrupts off. It must
  4401. * be paired with a subsequent finish_task_switch after the context
  4402. * switch.
  4403. *
  4404. * prepare_task_switch sets up locking and calls architecture specific
  4405. * hooks.
  4406. */
  4407. static inline void
  4408. prepare_task_switch(struct rq *rq, struct task_struct *prev,
  4409. struct task_struct *next)
  4410. {
  4411. kcov_prepare_switch(prev);
  4412. sched_info_switch(rq, prev, next);
  4413. perf_event_task_sched_out(prev, next);
  4414. rseq_preempt(prev);
  4415. fire_sched_out_preempt_notifiers(prev, next);
  4416. kmap_local_sched_out();
  4417. prepare_task(next);
  4418. prepare_arch_switch(next);
  4419. }
  4420. /**
  4421. * finish_task_switch - clean up after a task-switch
  4422. * @prev: the thread we just switched away from.
  4423. *
  4424. * finish_task_switch must be called after the context switch, paired
  4425. * with a prepare_task_switch call before the context switch.
  4426. * finish_task_switch will reconcile locking set up by prepare_task_switch,
  4427. * and do any other architecture-specific cleanup actions.
  4428. *
  4429. * Note that we may have delayed dropping an mm in context_switch(). If
  4430. * so, we finish that here outside of the runqueue lock. (Doing it
  4431. * with the lock held can cause deadlocks; see schedule() for
  4432. * details.)
  4433. *
  4434. * The context switch have flipped the stack from under us and restored the
  4435. * local variables which were saved when this task called schedule() in the
  4436. * past. 'prev == current' is still correct but we need to recalculate this_rq
  4437. * because prev may have moved to another CPU.
  4438. */
  4439. static struct rq *finish_task_switch(struct task_struct *prev)
  4440. __releases(rq->lock)
  4441. {
  4442. struct rq *rq = this_rq();
  4443. struct mm_struct *mm = rq->prev_mm;
  4444. unsigned int prev_state;
  4445. /*
  4446. * The previous task will have left us with a preempt_count of 2
  4447. * because it left us after:
  4448. *
  4449. * schedule()
  4450. * preempt_disable(); // 1
  4451. * __schedule()
  4452. * raw_spin_lock_irq(&rq->lock) // 2
  4453. *
  4454. * Also, see FORK_PREEMPT_COUNT.
  4455. */
  4456. if (WARN_ONCE(preempt_count() != 2*PREEMPT_DISABLE_OFFSET,
  4457. "corrupted preempt_count: %s/%d/0x%x\n",
  4458. current->comm, current->pid, preempt_count()))
  4459. preempt_count_set(FORK_PREEMPT_COUNT);
  4460. rq->prev_mm = NULL;
  4461. /*
  4462. * A task struct has one reference for the use as "current".
  4463. * If a task dies, then it sets TASK_DEAD in tsk->state and calls
  4464. * schedule one last time. The schedule call will never return, and
  4465. * the scheduled task must drop that reference.
  4466. *
  4467. * We must observe prev->state before clearing prev->on_cpu (in
  4468. * finish_task), otherwise a concurrent wakeup can get prev
  4469. * running on another CPU and we could rave with its RUNNING -> DEAD
  4470. * transition, resulting in a double drop.
  4471. */
  4472. prev_state = READ_ONCE(prev->__state);
  4473. vtime_task_switch(prev);
  4474. perf_event_task_sched_in(prev, current);
  4475. finish_task(prev);
  4476. tick_nohz_task_switch();
  4477. finish_lock_switch(rq);
  4478. finish_arch_post_lock_switch();
  4479. kcov_finish_switch(current);
  4480. /*
  4481. * kmap_local_sched_out() is invoked with rq::lock held and
  4482. * interrupts disabled. There is no requirement for that, but the
  4483. * sched out code does not have an interrupt enabled section.
  4484. * Restoring the maps on sched in does not require interrupts being
  4485. * disabled either.
  4486. */
  4487. kmap_local_sched_in();
  4488. fire_sched_in_preempt_notifiers(current);
  4489. /*
  4490. * When switching through a kernel thread, the loop in
  4491. * membarrier_{private,global}_expedited() may have observed that
  4492. * kernel thread and not issued an IPI. It is therefore possible to
  4493. * schedule between user->kernel->user threads without passing though
  4494. * switch_mm(). Membarrier requires a barrier after storing to
  4495. * rq->curr, before returning to userspace, so provide them here:
  4496. *
  4497. * - a full memory barrier for {PRIVATE,GLOBAL}_EXPEDITED, implicitly
  4498. * provided by mmdrop_lazy_tlb(),
  4499. * - a sync_core for SYNC_CORE.
  4500. */
  4501. if (mm) {
  4502. membarrier_mm_sync_core_before_usermode(mm);
  4503. mmdrop_lazy_tlb_sched(mm);
  4504. }
  4505. if (unlikely(prev_state == TASK_DEAD)) {
  4506. if (prev->sched_class->task_dead)
  4507. prev->sched_class->task_dead(prev);
  4508. /* Task is done with its stack. */
  4509. put_task_stack(prev);
  4510. put_task_struct_rcu_user(prev);
  4511. }
  4512. return rq;
  4513. }
  4514. /**
  4515. * schedule_tail - first thing a freshly forked thread must call.
  4516. * @prev: the thread we just switched away from.
  4517. */
  4518. asmlinkage __visible void schedule_tail(struct task_struct *prev)
  4519. __releases(rq->lock)
  4520. {
  4521. /*
  4522. * New tasks start with FORK_PREEMPT_COUNT, see there and
  4523. * finish_task_switch() for details.
  4524. *
  4525. * finish_task_switch() will drop rq->lock() and lower preempt_count
  4526. * and the preempt_enable() will end up enabling preemption (on
  4527. * PREEMPT_COUNT kernels).
  4528. */
  4529. finish_task_switch(prev);
  4530. preempt_enable();
  4531. if (current->set_child_tid)
  4532. put_user(task_pid_vnr(current), current->set_child_tid);
  4533. calculate_sigpending();
  4534. }
  4535. /*
  4536. * context_switch - switch to the new MM and the new thread's register state.
  4537. */
  4538. static __always_inline struct rq *
  4539. context_switch(struct rq *rq, struct task_struct *prev,
  4540. struct task_struct *next, struct rq_flags *rf)
  4541. {
  4542. prepare_task_switch(rq, prev, next);
  4543. /*
  4544. * For paravirt, this is coupled with an exit in switch_to to
  4545. * combine the page table reload and the switch backend into
  4546. * one hypercall.
  4547. */
  4548. arch_start_context_switch(prev);
  4549. /*
  4550. * kernel -> kernel lazy + transfer active
  4551. * user -> kernel lazy + mmgrab_lazy_tlb() active
  4552. *
  4553. * kernel -> user switch + mmdrop_lazy_tlb() active
  4554. * user -> user switch
  4555. *
  4556. * switch_mm_cid() needs to be updated if the barriers provided
  4557. * by context_switch() are modified.
  4558. */
  4559. if (!next->mm) { // to kernel
  4560. enter_lazy_tlb(prev->active_mm, next);
  4561. next->active_mm = prev->active_mm;
  4562. if (prev->mm) // from user
  4563. mmgrab_lazy_tlb(prev->active_mm);
  4564. else
  4565. prev->active_mm = NULL;
  4566. } else { // to user
  4567. membarrier_switch_mm(rq, prev->active_mm, next->mm);
  4568. /*
  4569. * sys_membarrier() requires an smp_mb() between setting
  4570. * rq->curr / membarrier_switch_mm() and returning to userspace.
  4571. *
  4572. * The below provides this either through switch_mm(), or in
  4573. * case 'prev->active_mm == next->mm' through
  4574. * finish_task_switch()'s mmdrop().
  4575. */
  4576. switch_mm_irqs_off(prev->active_mm, next->mm, next);
  4577. lru_gen_use_mm(next->mm);
  4578. if (!prev->mm) { // from kernel
  4579. /* will mmdrop_lazy_tlb() in finish_task_switch(). */
  4580. rq->prev_mm = prev->active_mm;
  4581. prev->active_mm = NULL;
  4582. }
  4583. }
  4584. /* switch_mm_cid() requires the memory barriers above. */
  4585. switch_mm_cid(rq, prev, next);
  4586. prepare_lock_switch(rq, next, rf);
  4587. /* Here we just switch the register state and the stack. */
  4588. switch_to(prev, next, prev);
  4589. barrier();
  4590. return finish_task_switch(prev);
  4591. }
  4592. /*
  4593. * nr_running and nr_context_switches:
  4594. *
  4595. * externally visible scheduler statistics: current number of runnable
  4596. * threads, total number of context switches performed since bootup.
  4597. */
  4598. unsigned int nr_running(void)
  4599. {
  4600. unsigned int i, sum = 0;
  4601. for_each_online_cpu(i)
  4602. sum += cpu_rq(i)->nr_running;
  4603. return sum;
  4604. }
  4605. /*
  4606. * Check if only the current task is running on the CPU.
  4607. *
  4608. * Caution: this function does not check that the caller has disabled
  4609. * preemption, thus the result might have a time-of-check-to-time-of-use
  4610. * race. The caller is responsible to use it correctly, for example:
  4611. *
  4612. * - from a non-preemptible section (of course)
  4613. *
  4614. * - from a thread that is bound to a single CPU
  4615. *
  4616. * - in a loop with very short iterations (e.g. a polling loop)
  4617. */
  4618. bool single_task_running(void)
  4619. {
  4620. return raw_rq()->nr_running == 1;
  4621. }
  4622. EXPORT_SYMBOL(single_task_running);
  4623. unsigned long long nr_context_switches_cpu(int cpu)
  4624. {
  4625. return cpu_rq(cpu)->nr_switches;
  4626. }
  4627. unsigned long long nr_context_switches(void)
  4628. {
  4629. int i;
  4630. unsigned long long sum = 0;
  4631. for_each_possible_cpu(i)
  4632. sum += cpu_rq(i)->nr_switches;
  4633. return sum;
  4634. }
  4635. /*
  4636. * Consumers of these two interfaces, like for example the cpuidle menu
  4637. * governor, are using nonsensical data. Preferring shallow idle state selection
  4638. * for a CPU that has IO-wait which might not even end up running the task when
  4639. * it does become runnable.
  4640. */
  4641. unsigned int nr_iowait_cpu(int cpu)
  4642. {
  4643. return atomic_read(&cpu_rq(cpu)->nr_iowait);
  4644. }
  4645. /*
  4646. * IO-wait accounting, and how it's mostly bollocks (on SMP).
  4647. *
  4648. * The idea behind IO-wait account is to account the idle time that we could
  4649. * have spend running if it were not for IO. That is, if we were to improve the
  4650. * storage performance, we'd have a proportional reduction in IO-wait time.
  4651. *
  4652. * This all works nicely on UP, where, when a task blocks on IO, we account
  4653. * idle time as IO-wait, because if the storage were faster, it could've been
  4654. * running and we'd not be idle.
  4655. *
  4656. * This has been extended to SMP, by doing the same for each CPU. This however
  4657. * is broken.
  4658. *
  4659. * Imagine for instance the case where two tasks block on one CPU, only the one
  4660. * CPU will have IO-wait accounted, while the other has regular idle. Even
  4661. * though, if the storage were faster, both could've ran at the same time,
  4662. * utilising both CPUs.
  4663. *
  4664. * This means, that when looking globally, the current IO-wait accounting on
  4665. * SMP is a lower bound, by reason of under accounting.
  4666. *
  4667. * Worse, since the numbers are provided per CPU, they are sometimes
  4668. * interpreted per CPU, and that is nonsensical. A blocked task isn't strictly
  4669. * associated with any one particular CPU, it can wake to another CPU than it
  4670. * blocked on. This means the per CPU IO-wait number is meaningless.
  4671. *
  4672. * Task CPU affinities can make all that even more 'interesting'.
  4673. */
  4674. unsigned int nr_iowait(void)
  4675. {
  4676. unsigned int i, sum = 0;
  4677. for_each_possible_cpu(i)
  4678. sum += nr_iowait_cpu(i);
  4679. return sum;
  4680. }
  4681. #ifdef CONFIG_SMP
  4682. /*
  4683. * sched_exec - execve() is a valuable balancing opportunity, because at
  4684. * this point the task has the smallest effective memory and cache footprint.
  4685. */
  4686. void sched_exec(void)
  4687. {
  4688. struct task_struct *p = current;
  4689. struct migration_arg arg;
  4690. int dest_cpu;
  4691. scoped_guard (raw_spinlock_irqsave, &p->pi_lock) {
  4692. dest_cpu = p->sched_class->select_task_rq(p, task_cpu(p), WF_EXEC);
  4693. if (dest_cpu == smp_processor_id())
  4694. return;
  4695. if (unlikely(!cpu_active(dest_cpu)))
  4696. return;
  4697. arg = (struct migration_arg){ p, dest_cpu };
  4698. }
  4699. stop_one_cpu(task_cpu(p), migration_cpu_stop, &arg);
  4700. }
  4701. #endif
  4702. DEFINE_PER_CPU(struct kernel_stat, kstat);
  4703. DEFINE_PER_CPU(struct kernel_cpustat, kernel_cpustat);
  4704. EXPORT_PER_CPU_SYMBOL(kstat);
  4705. EXPORT_PER_CPU_SYMBOL(kernel_cpustat);
  4706. /*
  4707. * The function fair_sched_class.update_curr accesses the struct curr
  4708. * and its field curr->exec_start; when called from task_sched_runtime(),
  4709. * we observe a high rate of cache misses in practice.
  4710. * Prefetching this data results in improved performance.
  4711. */
  4712. static inline void prefetch_curr_exec_start(struct task_struct *p)
  4713. {
  4714. #ifdef CONFIG_FAIR_GROUP_SCHED
  4715. struct sched_entity *curr = p->se.cfs_rq->curr;
  4716. #else
  4717. struct sched_entity *curr = task_rq(p)->cfs.curr;
  4718. #endif
  4719. prefetch(curr);
  4720. prefetch(&curr->exec_start);
  4721. }
  4722. /*
  4723. * Return accounted runtime for the task.
  4724. * In case the task is currently running, return the runtime plus current's
  4725. * pending runtime that have not been accounted yet.
  4726. */
  4727. unsigned long long task_sched_runtime(struct task_struct *p)
  4728. {
  4729. struct rq_flags rf;
  4730. struct rq *rq;
  4731. u64 ns;
  4732. #if defined(CONFIG_64BIT) && defined(CONFIG_SMP)
  4733. /*
  4734. * 64-bit doesn't need locks to atomically read a 64-bit value.
  4735. * So we have a optimization chance when the task's delta_exec is 0.
  4736. * Reading ->on_cpu is racy, but this is OK.
  4737. *
  4738. * If we race with it leaving CPU, we'll take a lock. So we're correct.
  4739. * If we race with it entering CPU, unaccounted time is 0. This is
  4740. * indistinguishable from the read occurring a few cycles earlier.
  4741. * If we see ->on_cpu without ->on_rq, the task is leaving, and has
  4742. * been accounted, so we're correct here as well.
  4743. */
  4744. if (!p->on_cpu || !task_on_rq_queued(p))
  4745. return p->se.sum_exec_runtime;
  4746. #endif
  4747. rq = task_rq_lock(p, &rf);
  4748. /*
  4749. * Must be ->curr _and_ ->on_rq. If dequeued, we would
  4750. * project cycles that may never be accounted to this
  4751. * thread, breaking clock_gettime().
  4752. */
  4753. if (task_current(rq, p) && task_on_rq_queued(p)) {
  4754. prefetch_curr_exec_start(p);
  4755. update_rq_clock(rq);
  4756. p->sched_class->update_curr(rq);
  4757. }
  4758. ns = p->se.sum_exec_runtime;
  4759. task_rq_unlock(rq, p, &rf);
  4760. return ns;
  4761. }
  4762. #ifdef CONFIG_SCHED_DEBUG
  4763. static u64 cpu_resched_latency(struct rq *rq)
  4764. {
  4765. int latency_warn_ms = READ_ONCE(sysctl_resched_latency_warn_ms);
  4766. u64 resched_latency, now = rq_clock(rq);
  4767. static bool warned_once;
  4768. if (sysctl_resched_latency_warn_once && warned_once)
  4769. return 0;
  4770. if (!need_resched() || !latency_warn_ms)
  4771. return 0;
  4772. if (system_state == SYSTEM_BOOTING)
  4773. return 0;
  4774. if (!rq->last_seen_need_resched_ns) {
  4775. rq->last_seen_need_resched_ns = now;
  4776. rq->ticks_without_resched = 0;
  4777. return 0;
  4778. }
  4779. rq->ticks_without_resched++;
  4780. resched_latency = now - rq->last_seen_need_resched_ns;
  4781. if (resched_latency <= latency_warn_ms * NSEC_PER_MSEC)
  4782. return 0;
  4783. warned_once = true;
  4784. return resched_latency;
  4785. }
  4786. static int __init setup_resched_latency_warn_ms(char *str)
  4787. {
  4788. long val;
  4789. if ((kstrtol(str, 0, &val))) {
  4790. pr_warn("Unable to set resched_latency_warn_ms\n");
  4791. return 1;
  4792. }
  4793. sysctl_resched_latency_warn_ms = val;
  4794. return 1;
  4795. }
  4796. __setup("resched_latency_warn_ms=", setup_resched_latency_warn_ms);
  4797. #else
  4798. static inline u64 cpu_resched_latency(struct rq *rq) { return 0; }
  4799. #endif /* CONFIG_SCHED_DEBUG */
  4800. /*
  4801. * This function gets called by the timer code, with HZ frequency.
  4802. * We call it with interrupts disabled.
  4803. */
  4804. void sched_tick(void)
  4805. {
  4806. int cpu = smp_processor_id();
  4807. struct rq *rq = cpu_rq(cpu);
  4808. struct task_struct *curr;
  4809. struct rq_flags rf;
  4810. unsigned long hw_pressure;
  4811. u64 resched_latency;
  4812. if (housekeeping_cpu(cpu, HK_TYPE_TICK))
  4813. arch_scale_freq_tick();
  4814. sched_clock_tick();
  4815. rq_lock(rq, &rf);
  4816. curr = rq->curr;
  4817. psi_account_irqtime(rq, curr, NULL);
  4818. update_rq_clock(rq);
  4819. hw_pressure = arch_scale_hw_pressure(cpu_of(rq));
  4820. update_hw_load_avg(rq_clock_task(rq), rq, hw_pressure);
  4821. curr->sched_class->task_tick(rq, curr, 0);
  4822. if (sched_feat(LATENCY_WARN))
  4823. resched_latency = cpu_resched_latency(rq);
  4824. calc_global_load_tick(rq);
  4825. sched_core_tick(rq);
  4826. task_tick_mm_cid(rq, curr);
  4827. scx_tick(rq);
  4828. rq_unlock(rq, &rf);
  4829. if (sched_feat(LATENCY_WARN) && resched_latency)
  4830. resched_latency_warn(cpu, resched_latency);
  4831. perf_event_task_tick();
  4832. if (curr->flags & PF_WQ_WORKER)
  4833. wq_worker_tick(curr);
  4834. #ifdef CONFIG_SMP
  4835. if (!scx_switched_all()) {
  4836. rq->idle_balance = idle_cpu(cpu);
  4837. sched_balance_trigger(rq);
  4838. }
  4839. #endif
  4840. }
  4841. #ifdef CONFIG_NO_HZ_FULL
  4842. struct tick_work {
  4843. int cpu;
  4844. atomic_t state;
  4845. struct delayed_work work;
  4846. };
  4847. /* Values for ->state, see diagram below. */
  4848. #define TICK_SCHED_REMOTE_OFFLINE 0
  4849. #define TICK_SCHED_REMOTE_OFFLINING 1
  4850. #define TICK_SCHED_REMOTE_RUNNING 2
  4851. /*
  4852. * State diagram for ->state:
  4853. *
  4854. *
  4855. * TICK_SCHED_REMOTE_OFFLINE
  4856. * | ^
  4857. * | |
  4858. * | | sched_tick_remote()
  4859. * | |
  4860. * | |
  4861. * +--TICK_SCHED_REMOTE_OFFLINING
  4862. * | ^
  4863. * | |
  4864. * sched_tick_start() | | sched_tick_stop()
  4865. * | |
  4866. * V |
  4867. * TICK_SCHED_REMOTE_RUNNING
  4868. *
  4869. *
  4870. * Other transitions get WARN_ON_ONCE(), except that sched_tick_remote()
  4871. * and sched_tick_start() are happy to leave the state in RUNNING.
  4872. */
  4873. static struct tick_work __percpu *tick_work_cpu;
  4874. static void sched_tick_remote(struct work_struct *work)
  4875. {
  4876. struct delayed_work *dwork = to_delayed_work(work);
  4877. struct tick_work *twork = container_of(dwork, struct tick_work, work);
  4878. int cpu = twork->cpu;
  4879. struct rq *rq = cpu_rq(cpu);
  4880. int os;
  4881. /*
  4882. * Handle the tick only if it appears the remote CPU is running in full
  4883. * dynticks mode. The check is racy by nature, but missing a tick or
  4884. * having one too much is no big deal because the scheduler tick updates
  4885. * statistics and checks timeslices in a time-independent way, regardless
  4886. * of when exactly it is running.
  4887. */
  4888. if (tick_nohz_tick_stopped_cpu(cpu)) {
  4889. guard(rq_lock_irq)(rq);
  4890. struct task_struct *curr = rq->curr;
  4891. if (cpu_online(cpu)) {
  4892. update_rq_clock(rq);
  4893. if (!is_idle_task(curr)) {
  4894. /*
  4895. * Make sure the next tick runs within a
  4896. * reasonable amount of time.
  4897. */
  4898. u64 delta = rq_clock_task(rq) - curr->se.exec_start;
  4899. WARN_ON_ONCE(delta > (u64)NSEC_PER_SEC * 3);
  4900. }
  4901. curr->sched_class->task_tick(rq, curr, 0);
  4902. calc_load_nohz_remote(rq);
  4903. }
  4904. }
  4905. /*
  4906. * Run the remote tick once per second (1Hz). This arbitrary
  4907. * frequency is large enough to avoid overload but short enough
  4908. * to keep scheduler internal stats reasonably up to date. But
  4909. * first update state to reflect hotplug activity if required.
  4910. */
  4911. os = atomic_fetch_add_unless(&twork->state, -1, TICK_SCHED_REMOTE_RUNNING);
  4912. WARN_ON_ONCE(os == TICK_SCHED_REMOTE_OFFLINE);
  4913. if (os == TICK_SCHED_REMOTE_RUNNING)
  4914. queue_delayed_work(system_unbound_wq, dwork, HZ);
  4915. }
  4916. static void sched_tick_start(int cpu)
  4917. {
  4918. int os;
  4919. struct tick_work *twork;
  4920. if (housekeeping_cpu(cpu, HK_TYPE_TICK))
  4921. return;
  4922. WARN_ON_ONCE(!tick_work_cpu);
  4923. twork = per_cpu_ptr(tick_work_cpu, cpu);
  4924. os = atomic_xchg(&twork->state, TICK_SCHED_REMOTE_RUNNING);
  4925. WARN_ON_ONCE(os == TICK_SCHED_REMOTE_RUNNING);
  4926. if (os == TICK_SCHED_REMOTE_OFFLINE) {
  4927. twork->cpu = cpu;
  4928. INIT_DELAYED_WORK(&twork->work, sched_tick_remote);
  4929. queue_delayed_work(system_unbound_wq, &twork->work, HZ);
  4930. }
  4931. }
  4932. #ifdef CONFIG_HOTPLUG_CPU
  4933. static void sched_tick_stop(int cpu)
  4934. {
  4935. struct tick_work *twork;
  4936. int os;
  4937. if (housekeeping_cpu(cpu, HK_TYPE_TICK))
  4938. return;
  4939. WARN_ON_ONCE(!tick_work_cpu);
  4940. twork = per_cpu_ptr(tick_work_cpu, cpu);
  4941. /* There cannot be competing actions, but don't rely on stop-machine. */
  4942. os = atomic_xchg(&twork->state, TICK_SCHED_REMOTE_OFFLINING);
  4943. WARN_ON_ONCE(os != TICK_SCHED_REMOTE_RUNNING);
  4944. /* Don't cancel, as this would mess up the state machine. */
  4945. }
  4946. #endif /* CONFIG_HOTPLUG_CPU */
  4947. int __init sched_tick_offload_init(void)
  4948. {
  4949. tick_work_cpu = alloc_percpu(struct tick_work);
  4950. BUG_ON(!tick_work_cpu);
  4951. return 0;
  4952. }
  4953. #else /* !CONFIG_NO_HZ_FULL */
  4954. static inline void sched_tick_start(int cpu) { }
  4955. static inline void sched_tick_stop(int cpu) { }
  4956. #endif
  4957. #if defined(CONFIG_PREEMPTION) && (defined(CONFIG_DEBUG_PREEMPT) || \
  4958. defined(CONFIG_TRACE_PREEMPT_TOGGLE))
  4959. /*
  4960. * If the value passed in is equal to the current preempt count
  4961. * then we just disabled preemption. Start timing the latency.
  4962. */
  4963. static inline void preempt_latency_start(int val)
  4964. {
  4965. if (preempt_count() == val) {
  4966. unsigned long ip = get_lock_parent_ip();
  4967. #ifdef CONFIG_DEBUG_PREEMPT
  4968. current->preempt_disable_ip = ip;
  4969. #endif
  4970. trace_preempt_off(CALLER_ADDR0, ip);
  4971. }
  4972. }
  4973. void preempt_count_add(int val)
  4974. {
  4975. #ifdef CONFIG_DEBUG_PREEMPT
  4976. /*
  4977. * Underflow?
  4978. */
  4979. if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
  4980. return;
  4981. #endif
  4982. __preempt_count_add(val);
  4983. #ifdef CONFIG_DEBUG_PREEMPT
  4984. /*
  4985. * Spinlock count overflowing soon?
  4986. */
  4987. DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
  4988. PREEMPT_MASK - 10);
  4989. #endif
  4990. preempt_latency_start(val);
  4991. }
  4992. EXPORT_SYMBOL(preempt_count_add);
  4993. NOKPROBE_SYMBOL(preempt_count_add);
  4994. /*
  4995. * If the value passed in equals to the current preempt count
  4996. * then we just enabled preemption. Stop timing the latency.
  4997. */
  4998. static inline void preempt_latency_stop(int val)
  4999. {
  5000. if (preempt_count() == val)
  5001. trace_preempt_on(CALLER_ADDR0, get_lock_parent_ip());
  5002. }
  5003. void preempt_count_sub(int val)
  5004. {
  5005. #ifdef CONFIG_DEBUG_PREEMPT
  5006. /*
  5007. * Underflow?
  5008. */
  5009. if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
  5010. return;
  5011. /*
  5012. * Is the spinlock portion underflowing?
  5013. */
  5014. if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
  5015. !(preempt_count() & PREEMPT_MASK)))
  5016. return;
  5017. #endif
  5018. preempt_latency_stop(val);
  5019. __preempt_count_sub(val);
  5020. }
  5021. EXPORT_SYMBOL(preempt_count_sub);
  5022. NOKPROBE_SYMBOL(preempt_count_sub);
  5023. #else
  5024. static inline void preempt_latency_start(int val) { }
  5025. static inline void preempt_latency_stop(int val) { }
  5026. #endif
  5027. static inline unsigned long get_preempt_disable_ip(struct task_struct *p)
  5028. {
  5029. #ifdef CONFIG_DEBUG_PREEMPT
  5030. return p->preempt_disable_ip;
  5031. #else
  5032. return 0;
  5033. #endif
  5034. }
  5035. /*
  5036. * Print scheduling while atomic bug:
  5037. */
  5038. static noinline void __schedule_bug(struct task_struct *prev)
  5039. {
  5040. /* Save this before calling printk(), since that will clobber it */
  5041. unsigned long preempt_disable_ip = get_preempt_disable_ip(current);
  5042. if (oops_in_progress)
  5043. return;
  5044. printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
  5045. prev->comm, prev->pid, preempt_count());
  5046. debug_show_held_locks(prev);
  5047. print_modules();
  5048. if (irqs_disabled())
  5049. print_irqtrace_events(prev);
  5050. if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)) {
  5051. pr_err("Preemption disabled at:");
  5052. print_ip_sym(KERN_ERR, preempt_disable_ip);
  5053. }
  5054. check_panic_on_warn("scheduling while atomic");
  5055. dump_stack();
  5056. add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
  5057. }
  5058. /*
  5059. * Various schedule()-time debugging checks and statistics:
  5060. */
  5061. static inline void schedule_debug(struct task_struct *prev, bool preempt)
  5062. {
  5063. #ifdef CONFIG_SCHED_STACK_END_CHECK
  5064. if (task_stack_end_corrupted(prev))
  5065. panic("corrupted stack end detected inside scheduler\n");
  5066. if (task_scs_end_corrupted(prev))
  5067. panic("corrupted shadow stack detected inside scheduler\n");
  5068. #endif
  5069. #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
  5070. if (!preempt && READ_ONCE(prev->__state) && prev->non_block_count) {
  5071. printk(KERN_ERR "BUG: scheduling in a non-blocking section: %s/%d/%i\n",
  5072. prev->comm, prev->pid, prev->non_block_count);
  5073. dump_stack();
  5074. add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
  5075. }
  5076. #endif
  5077. if (unlikely(in_atomic_preempt_off())) {
  5078. __schedule_bug(prev);
  5079. preempt_count_set(PREEMPT_DISABLED);
  5080. }
  5081. rcu_sleep_check();
  5082. SCHED_WARN_ON(ct_state() == CT_STATE_USER);
  5083. profile_hit(SCHED_PROFILING, __builtin_return_address(0));
  5084. schedstat_inc(this_rq()->sched_count);
  5085. }
  5086. static void prev_balance(struct rq *rq, struct task_struct *prev,
  5087. struct rq_flags *rf)
  5088. {
  5089. const struct sched_class *start_class = prev->sched_class;
  5090. const struct sched_class *class;
  5091. #ifdef CONFIG_SCHED_CLASS_EXT
  5092. /*
  5093. * SCX requires a balance() call before every pick_task() including when
  5094. * waking up from SCHED_IDLE. If @start_class is below SCX, start from
  5095. * SCX instead. Also, set a flag to detect missing balance() call.
  5096. */
  5097. if (scx_enabled()) {
  5098. rq->scx.flags |= SCX_RQ_BAL_PENDING;
  5099. if (sched_class_above(&ext_sched_class, start_class))
  5100. start_class = &ext_sched_class;
  5101. }
  5102. #endif
  5103. /*
  5104. * We must do the balancing pass before put_prev_task(), such
  5105. * that when we release the rq->lock the task is in the same
  5106. * state as before we took rq->lock.
  5107. *
  5108. * We can terminate the balance pass as soon as we know there is
  5109. * a runnable task of @class priority or higher.
  5110. */
  5111. for_active_class_range(class, start_class, &idle_sched_class) {
  5112. if (class->balance && class->balance(rq, prev, rf))
  5113. break;
  5114. }
  5115. }
  5116. /*
  5117. * Pick up the highest-prio task:
  5118. */
  5119. static inline struct task_struct *
  5120. __pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
  5121. {
  5122. const struct sched_class *class;
  5123. struct task_struct *p;
  5124. rq->dl_server = NULL;
  5125. if (scx_enabled())
  5126. goto restart;
  5127. /*
  5128. * Optimization: we know that if all tasks are in the fair class we can
  5129. * call that function directly, but only if the @prev task wasn't of a
  5130. * higher scheduling class, because otherwise those lose the
  5131. * opportunity to pull in more work from other CPUs.
  5132. */
  5133. if (likely(!sched_class_above(prev->sched_class, &fair_sched_class) &&
  5134. rq->nr_running == rq->cfs.h_nr_queued)) {
  5135. p = pick_next_task_fair(rq, prev, rf);
  5136. if (unlikely(p == RETRY_TASK))
  5137. goto restart;
  5138. /* Assume the next prioritized class is idle_sched_class */
  5139. if (!p) {
  5140. p = pick_task_idle(rq);
  5141. put_prev_set_next_task(rq, prev, p);
  5142. }
  5143. return p;
  5144. }
  5145. restart:
  5146. prev_balance(rq, prev, rf);
  5147. for_each_active_class(class) {
  5148. if (class->pick_next_task) {
  5149. p = class->pick_next_task(rq, prev);
  5150. if (p)
  5151. return p;
  5152. } else {
  5153. p = class->pick_task(rq);
  5154. if (p) {
  5155. put_prev_set_next_task(rq, prev, p);
  5156. return p;
  5157. }
  5158. }
  5159. }
  5160. BUG(); /* The idle class should always have a runnable task. */
  5161. }
  5162. #ifdef CONFIG_SCHED_CORE
  5163. static inline bool is_task_rq_idle(struct task_struct *t)
  5164. {
  5165. return (task_rq(t)->idle == t);
  5166. }
  5167. static inline bool cookie_equals(struct task_struct *a, unsigned long cookie)
  5168. {
  5169. return is_task_rq_idle(a) || (a->core_cookie == cookie);
  5170. }
  5171. static inline bool cookie_match(struct task_struct *a, struct task_struct *b)
  5172. {
  5173. if (is_task_rq_idle(a) || is_task_rq_idle(b))
  5174. return true;
  5175. return a->core_cookie == b->core_cookie;
  5176. }
  5177. static inline struct task_struct *pick_task(struct rq *rq)
  5178. {
  5179. const struct sched_class *class;
  5180. struct task_struct *p;
  5181. rq->dl_server = NULL;
  5182. for_each_active_class(class) {
  5183. p = class->pick_task(rq);
  5184. if (p)
  5185. return p;
  5186. }
  5187. BUG(); /* The idle class should always have a runnable task. */
  5188. }
  5189. extern void task_vruntime_update(struct rq *rq, struct task_struct *p, bool in_fi);
  5190. static void queue_core_balance(struct rq *rq);
  5191. static struct task_struct *
  5192. pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
  5193. {
  5194. struct task_struct *next, *p, *max = NULL;
  5195. const struct cpumask *smt_mask;
  5196. bool fi_before = false;
  5197. bool core_clock_updated = (rq == rq->core);
  5198. unsigned long cookie;
  5199. int i, cpu, occ = 0;
  5200. struct rq *rq_i;
  5201. bool need_sync;
  5202. if (!sched_core_enabled(rq))
  5203. return __pick_next_task(rq, prev, rf);
  5204. cpu = cpu_of(rq);
  5205. /* Stopper task is switching into idle, no need core-wide selection. */
  5206. if (cpu_is_offline(cpu)) {
  5207. /*
  5208. * Reset core_pick so that we don't enter the fastpath when
  5209. * coming online. core_pick would already be migrated to
  5210. * another cpu during offline.
  5211. */
  5212. rq->core_pick = NULL;
  5213. rq->core_dl_server = NULL;
  5214. return __pick_next_task(rq, prev, rf);
  5215. }
  5216. /*
  5217. * If there were no {en,de}queues since we picked (IOW, the task
  5218. * pointers are all still valid), and we haven't scheduled the last
  5219. * pick yet, do so now.
  5220. *
  5221. * rq->core_pick can be NULL if no selection was made for a CPU because
  5222. * it was either offline or went offline during a sibling's core-wide
  5223. * selection. In this case, do a core-wide selection.
  5224. */
  5225. if (rq->core->core_pick_seq == rq->core->core_task_seq &&
  5226. rq->core->core_pick_seq != rq->core_sched_seq &&
  5227. rq->core_pick) {
  5228. WRITE_ONCE(rq->core_sched_seq, rq->core->core_pick_seq);
  5229. next = rq->core_pick;
  5230. rq->dl_server = rq->core_dl_server;
  5231. rq->core_pick = NULL;
  5232. rq->core_dl_server = NULL;
  5233. goto out_set_next;
  5234. }
  5235. prev_balance(rq, prev, rf);
  5236. smt_mask = cpu_smt_mask(cpu);
  5237. need_sync = !!rq->core->core_cookie;
  5238. /* reset state */
  5239. rq->core->core_cookie = 0UL;
  5240. if (rq->core->core_forceidle_count) {
  5241. if (!core_clock_updated) {
  5242. update_rq_clock(rq->core);
  5243. core_clock_updated = true;
  5244. }
  5245. sched_core_account_forceidle(rq);
  5246. /* reset after accounting force idle */
  5247. rq->core->core_forceidle_start = 0;
  5248. rq->core->core_forceidle_count = 0;
  5249. rq->core->core_forceidle_occupation = 0;
  5250. need_sync = true;
  5251. fi_before = true;
  5252. }
  5253. /*
  5254. * core->core_task_seq, core->core_pick_seq, rq->core_sched_seq
  5255. *
  5256. * @task_seq guards the task state ({en,de}queues)
  5257. * @pick_seq is the @task_seq we did a selection on
  5258. * @sched_seq is the @pick_seq we scheduled
  5259. *
  5260. * However, preemptions can cause multiple picks on the same task set.
  5261. * 'Fix' this by also increasing @task_seq for every pick.
  5262. */
  5263. rq->core->core_task_seq++;
  5264. /*
  5265. * Optimize for common case where this CPU has no cookies
  5266. * and there are no cookied tasks running on siblings.
  5267. */
  5268. if (!need_sync) {
  5269. next = pick_task(rq);
  5270. if (!next->core_cookie) {
  5271. rq->core_pick = NULL;
  5272. rq->core_dl_server = NULL;
  5273. /*
  5274. * For robustness, update the min_vruntime_fi for
  5275. * unconstrained picks as well.
  5276. */
  5277. WARN_ON_ONCE(fi_before);
  5278. task_vruntime_update(rq, next, false);
  5279. goto out_set_next;
  5280. }
  5281. }
  5282. /*
  5283. * For each thread: do the regular task pick and find the max prio task
  5284. * amongst them.
  5285. *
  5286. * Tie-break prio towards the current CPU
  5287. */
  5288. for_each_cpu_wrap(i, smt_mask, cpu) {
  5289. rq_i = cpu_rq(i);
  5290. /*
  5291. * Current cpu always has its clock updated on entrance to
  5292. * pick_next_task(). If the current cpu is not the core,
  5293. * the core may also have been updated above.
  5294. */
  5295. if (i != cpu && (rq_i != rq->core || !core_clock_updated))
  5296. update_rq_clock(rq_i);
  5297. rq_i->core_pick = p = pick_task(rq_i);
  5298. rq_i->core_dl_server = rq_i->dl_server;
  5299. if (!max || prio_less(max, p, fi_before))
  5300. max = p;
  5301. }
  5302. cookie = rq->core->core_cookie = max->core_cookie;
  5303. /*
  5304. * For each thread: try and find a runnable task that matches @max or
  5305. * force idle.
  5306. */
  5307. for_each_cpu(i, smt_mask) {
  5308. rq_i = cpu_rq(i);
  5309. p = rq_i->core_pick;
  5310. if (!cookie_equals(p, cookie)) {
  5311. p = NULL;
  5312. if (cookie)
  5313. p = sched_core_find(rq_i, cookie);
  5314. if (!p)
  5315. p = idle_sched_class.pick_task(rq_i);
  5316. }
  5317. rq_i->core_pick = p;
  5318. rq_i->core_dl_server = NULL;
  5319. if (p == rq_i->idle) {
  5320. if (rq_i->nr_running) {
  5321. rq->core->core_forceidle_count++;
  5322. if (!fi_before)
  5323. rq->core->core_forceidle_seq++;
  5324. }
  5325. } else {
  5326. occ++;
  5327. }
  5328. }
  5329. if (schedstat_enabled() && rq->core->core_forceidle_count) {
  5330. rq->core->core_forceidle_start = rq_clock(rq->core);
  5331. rq->core->core_forceidle_occupation = occ;
  5332. }
  5333. rq->core->core_pick_seq = rq->core->core_task_seq;
  5334. next = rq->core_pick;
  5335. rq->core_sched_seq = rq->core->core_pick_seq;
  5336. /* Something should have been selected for current CPU */
  5337. WARN_ON_ONCE(!next);
  5338. /*
  5339. * Reschedule siblings
  5340. *
  5341. * NOTE: L1TF -- at this point we're no longer running the old task and
  5342. * sending an IPI (below) ensures the sibling will no longer be running
  5343. * their task. This ensures there is no inter-sibling overlap between
  5344. * non-matching user state.
  5345. */
  5346. for_each_cpu(i, smt_mask) {
  5347. rq_i = cpu_rq(i);
  5348. /*
  5349. * An online sibling might have gone offline before a task
  5350. * could be picked for it, or it might be offline but later
  5351. * happen to come online, but its too late and nothing was
  5352. * picked for it. That's Ok - it will pick tasks for itself,
  5353. * so ignore it.
  5354. */
  5355. if (!rq_i->core_pick)
  5356. continue;
  5357. /*
  5358. * Update for new !FI->FI transitions, or if continuing to be in !FI:
  5359. * fi_before fi update?
  5360. * 0 0 1
  5361. * 0 1 1
  5362. * 1 0 1
  5363. * 1 1 0
  5364. */
  5365. if (!(fi_before && rq->core->core_forceidle_count))
  5366. task_vruntime_update(rq_i, rq_i->core_pick, !!rq->core->core_forceidle_count);
  5367. rq_i->core_pick->core_occupation = occ;
  5368. if (i == cpu) {
  5369. rq_i->core_pick = NULL;
  5370. rq_i->core_dl_server = NULL;
  5371. continue;
  5372. }
  5373. /* Did we break L1TF mitigation requirements? */
  5374. WARN_ON_ONCE(!cookie_match(next, rq_i->core_pick));
  5375. if (rq_i->curr == rq_i->core_pick) {
  5376. rq_i->core_pick = NULL;
  5377. rq_i->core_dl_server = NULL;
  5378. continue;
  5379. }
  5380. resched_curr(rq_i);
  5381. }
  5382. out_set_next:
  5383. put_prev_set_next_task(rq, prev, next);
  5384. if (rq->core->core_forceidle_count && next == rq->idle)
  5385. queue_core_balance(rq);
  5386. return next;
  5387. }
  5388. static bool try_steal_cookie(int this, int that)
  5389. {
  5390. struct rq *dst = cpu_rq(this), *src = cpu_rq(that);
  5391. struct task_struct *p;
  5392. unsigned long cookie;
  5393. bool success = false;
  5394. guard(irq)();
  5395. guard(double_rq_lock)(dst, src);
  5396. cookie = dst->core->core_cookie;
  5397. if (!cookie)
  5398. return false;
  5399. if (dst->curr != dst->idle)
  5400. return false;
  5401. p = sched_core_find(src, cookie);
  5402. if (!p)
  5403. return false;
  5404. do {
  5405. if (p == src->core_pick || p == src->curr)
  5406. goto next;
  5407. if (!is_cpu_allowed(p, this))
  5408. goto next;
  5409. if (p->core_occupation > dst->idle->core_occupation)
  5410. goto next;
  5411. /*
  5412. * sched_core_find() and sched_core_next() will ensure
  5413. * that task @p is not throttled now, we also need to
  5414. * check whether the runqueue of the destination CPU is
  5415. * being throttled.
  5416. */
  5417. if (sched_task_is_throttled(p, this))
  5418. goto next;
  5419. deactivate_task(src, p, 0);
  5420. set_task_cpu(p, this);
  5421. activate_task(dst, p, 0);
  5422. resched_curr(dst);
  5423. success = true;
  5424. break;
  5425. next:
  5426. p = sched_core_next(p, cookie);
  5427. } while (p);
  5428. return success;
  5429. }
  5430. static bool steal_cookie_task(int cpu, struct sched_domain *sd)
  5431. {
  5432. int i;
  5433. for_each_cpu_wrap(i, sched_domain_span(sd), cpu + 1) {
  5434. if (i == cpu)
  5435. continue;
  5436. if (need_resched())
  5437. break;
  5438. if (try_steal_cookie(cpu, i))
  5439. return true;
  5440. }
  5441. return false;
  5442. }
  5443. static void sched_core_balance(struct rq *rq)
  5444. {
  5445. struct sched_domain *sd;
  5446. int cpu = cpu_of(rq);
  5447. guard(preempt)();
  5448. guard(rcu)();
  5449. raw_spin_rq_unlock_irq(rq);
  5450. for_each_domain(cpu, sd) {
  5451. if (need_resched())
  5452. break;
  5453. if (steal_cookie_task(cpu, sd))
  5454. break;
  5455. }
  5456. raw_spin_rq_lock_irq(rq);
  5457. }
  5458. static DEFINE_PER_CPU(struct balance_callback, core_balance_head);
  5459. static void queue_core_balance(struct rq *rq)
  5460. {
  5461. if (!sched_core_enabled(rq))
  5462. return;
  5463. if (!rq->core->core_cookie)
  5464. return;
  5465. if (!rq->nr_running) /* not forced idle */
  5466. return;
  5467. queue_balance_callback(rq, &per_cpu(core_balance_head, rq->cpu), sched_core_balance);
  5468. }
  5469. DEFINE_LOCK_GUARD_1(core_lock, int,
  5470. sched_core_lock(*_T->lock, &_T->flags),
  5471. sched_core_unlock(*_T->lock, &_T->flags),
  5472. unsigned long flags)
  5473. static void sched_core_cpu_starting(unsigned int cpu)
  5474. {
  5475. const struct cpumask *smt_mask = cpu_smt_mask(cpu);
  5476. struct rq *rq = cpu_rq(cpu), *core_rq = NULL;
  5477. int t;
  5478. guard(core_lock)(&cpu);
  5479. WARN_ON_ONCE(rq->core != rq);
  5480. /* if we're the first, we'll be our own leader */
  5481. if (cpumask_weight(smt_mask) == 1)
  5482. return;
  5483. /* find the leader */
  5484. for_each_cpu(t, smt_mask) {
  5485. if (t == cpu)
  5486. continue;
  5487. rq = cpu_rq(t);
  5488. if (rq->core == rq) {
  5489. core_rq = rq;
  5490. break;
  5491. }
  5492. }
  5493. if (WARN_ON_ONCE(!core_rq)) /* whoopsie */
  5494. return;
  5495. /* install and validate core_rq */
  5496. for_each_cpu(t, smt_mask) {
  5497. rq = cpu_rq(t);
  5498. if (t == cpu)
  5499. rq->core = core_rq;
  5500. WARN_ON_ONCE(rq->core != core_rq);
  5501. }
  5502. }
  5503. static void sched_core_cpu_deactivate(unsigned int cpu)
  5504. {
  5505. const struct cpumask *smt_mask = cpu_smt_mask(cpu);
  5506. struct rq *rq = cpu_rq(cpu), *core_rq = NULL;
  5507. int t;
  5508. guard(core_lock)(&cpu);
  5509. /* if we're the last man standing, nothing to do */
  5510. if (cpumask_weight(smt_mask) == 1) {
  5511. WARN_ON_ONCE(rq->core != rq);
  5512. return;
  5513. }
  5514. /* if we're not the leader, nothing to do */
  5515. if (rq->core != rq)
  5516. return;
  5517. /* find a new leader */
  5518. for_each_cpu(t, smt_mask) {
  5519. if (t == cpu)
  5520. continue;
  5521. core_rq = cpu_rq(t);
  5522. break;
  5523. }
  5524. if (WARN_ON_ONCE(!core_rq)) /* impossible */
  5525. return;
  5526. /* copy the shared state to the new leader */
  5527. core_rq->core_task_seq = rq->core_task_seq;
  5528. core_rq->core_pick_seq = rq->core_pick_seq;
  5529. core_rq->core_cookie = rq->core_cookie;
  5530. core_rq->core_forceidle_count = rq->core_forceidle_count;
  5531. core_rq->core_forceidle_seq = rq->core_forceidle_seq;
  5532. core_rq->core_forceidle_occupation = rq->core_forceidle_occupation;
  5533. /*
  5534. * Accounting edge for forced idle is handled in pick_next_task().
  5535. * Don't need another one here, since the hotplug thread shouldn't
  5536. * have a cookie.
  5537. */
  5538. core_rq->core_forceidle_start = 0;
  5539. /* install new leader */
  5540. for_each_cpu(t, smt_mask) {
  5541. rq = cpu_rq(t);
  5542. rq->core = core_rq;
  5543. }
  5544. }
  5545. static inline void sched_core_cpu_dying(unsigned int cpu)
  5546. {
  5547. struct rq *rq = cpu_rq(cpu);
  5548. if (rq->core != rq)
  5549. rq->core = rq;
  5550. }
  5551. #else /* !CONFIG_SCHED_CORE */
  5552. static inline void sched_core_cpu_starting(unsigned int cpu) {}
  5553. static inline void sched_core_cpu_deactivate(unsigned int cpu) {}
  5554. static inline void sched_core_cpu_dying(unsigned int cpu) {}
  5555. static struct task_struct *
  5556. pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
  5557. {
  5558. return __pick_next_task(rq, prev, rf);
  5559. }
  5560. #endif /* CONFIG_SCHED_CORE */
  5561. /*
  5562. * Constants for the sched_mode argument of __schedule().
  5563. *
  5564. * The mode argument allows RT enabled kernels to differentiate a
  5565. * preemption from blocking on an 'sleeping' spin/rwlock.
  5566. */
  5567. #define SM_IDLE (-1)
  5568. #define SM_NONE 0
  5569. #define SM_PREEMPT 1
  5570. #define SM_RTLOCK_WAIT 2
  5571. /*
  5572. * Helper function for __schedule()
  5573. *
  5574. * If a task does not have signals pending, deactivate it
  5575. * Otherwise marks the task's __state as RUNNING
  5576. */
  5577. static bool try_to_block_task(struct rq *rq, struct task_struct *p,
  5578. unsigned long *task_state_p)
  5579. {
  5580. unsigned long task_state = *task_state_p;
  5581. int flags = DEQUEUE_NOCLOCK;
  5582. if (signal_pending_state(task_state, p)) {
  5583. WRITE_ONCE(p->__state, TASK_RUNNING);
  5584. *task_state_p = TASK_RUNNING;
  5585. return false;
  5586. }
  5587. p->sched_contributes_to_load =
  5588. (task_state & TASK_UNINTERRUPTIBLE) &&
  5589. !(task_state & TASK_NOLOAD) &&
  5590. !(task_state & TASK_FROZEN);
  5591. if (unlikely(is_special_task_state(task_state)))
  5592. flags |= DEQUEUE_SPECIAL;
  5593. /*
  5594. * __schedule() ttwu()
  5595. * prev_state = prev->state; if (p->on_rq && ...)
  5596. * if (prev_state) goto out;
  5597. * p->on_rq = 0; smp_acquire__after_ctrl_dep();
  5598. * p->state = TASK_WAKING
  5599. *
  5600. * Where __schedule() and ttwu() have matching control dependencies.
  5601. *
  5602. * After this, schedule() must not care about p->state any more.
  5603. */
  5604. block_task(rq, p, flags);
  5605. return true;
  5606. }
  5607. /*
  5608. * __schedule() is the main scheduler function.
  5609. *
  5610. * The main means of driving the scheduler and thus entering this function are:
  5611. *
  5612. * 1. Explicit blocking: mutex, semaphore, waitqueue, etc.
  5613. *
  5614. * 2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return
  5615. * paths. For example, see arch/x86/entry_64.S.
  5616. *
  5617. * To drive preemption between tasks, the scheduler sets the flag in timer
  5618. * interrupt handler sched_tick().
  5619. *
  5620. * 3. Wakeups don't really cause entry into schedule(). They add a
  5621. * task to the run-queue and that's it.
  5622. *
  5623. * Now, if the new task added to the run-queue preempts the current
  5624. * task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets
  5625. * called on the nearest possible occasion:
  5626. *
  5627. * - If the kernel is preemptible (CONFIG_PREEMPTION=y):
  5628. *
  5629. * - in syscall or exception context, at the next outmost
  5630. * preempt_enable(). (this might be as soon as the wake_up()'s
  5631. * spin_unlock()!)
  5632. *
  5633. * - in IRQ context, return from interrupt-handler to
  5634. * preemptible context
  5635. *
  5636. * - If the kernel is not preemptible (CONFIG_PREEMPTION is not set)
  5637. * then at the next:
  5638. *
  5639. * - cond_resched() call
  5640. * - explicit schedule() call
  5641. * - return from syscall or exception to user-space
  5642. * - return from interrupt-handler to user-space
  5643. *
  5644. * WARNING: must be called with preemption disabled!
  5645. */
  5646. static void __sched notrace __schedule(int sched_mode)
  5647. {
  5648. struct task_struct *prev, *next;
  5649. /*
  5650. * On PREEMPT_RT kernel, SM_RTLOCK_WAIT is noted
  5651. * as a preemption by schedule_debug() and RCU.
  5652. */
  5653. bool preempt = sched_mode > SM_NONE;
  5654. unsigned long *switch_count;
  5655. unsigned long prev_state;
  5656. struct rq_flags rf;
  5657. struct rq *rq;
  5658. int cpu;
  5659. cpu = smp_processor_id();
  5660. rq = cpu_rq(cpu);
  5661. prev = rq->curr;
  5662. schedule_debug(prev, preempt);
  5663. if (sched_feat(HRTICK) || sched_feat(HRTICK_DL))
  5664. hrtick_clear(rq);
  5665. local_irq_disable();
  5666. rcu_note_context_switch(preempt);
  5667. /*
  5668. * Make sure that signal_pending_state()->signal_pending() below
  5669. * can't be reordered with __set_current_state(TASK_INTERRUPTIBLE)
  5670. * done by the caller to avoid the race with signal_wake_up():
  5671. *
  5672. * __set_current_state(@state) signal_wake_up()
  5673. * schedule() set_tsk_thread_flag(p, TIF_SIGPENDING)
  5674. * wake_up_state(p, state)
  5675. * LOCK rq->lock LOCK p->pi_state
  5676. * smp_mb__after_spinlock() smp_mb__after_spinlock()
  5677. * if (signal_pending_state()) if (p->state & @state)
  5678. *
  5679. * Also, the membarrier system call requires a full memory barrier
  5680. * after coming from user-space, before storing to rq->curr; this
  5681. * barrier matches a full barrier in the proximity of the membarrier
  5682. * system call exit.
  5683. */
  5684. rq_lock(rq, &rf);
  5685. smp_mb__after_spinlock();
  5686. /* Promote REQ to ACT */
  5687. rq->clock_update_flags <<= 1;
  5688. update_rq_clock(rq);
  5689. rq->clock_update_flags = RQCF_UPDATED;
  5690. switch_count = &prev->nivcsw;
  5691. /* Task state changes only considers SM_PREEMPT as preemption */
  5692. preempt = sched_mode == SM_PREEMPT;
  5693. /*
  5694. * We must load prev->state once (task_struct::state is volatile), such
  5695. * that we form a control dependency vs deactivate_task() below.
  5696. */
  5697. prev_state = READ_ONCE(prev->__state);
  5698. if (sched_mode == SM_IDLE) {
  5699. /* SCX must consult the BPF scheduler to tell if rq is empty */
  5700. if (!rq->nr_running && !scx_enabled()) {
  5701. next = prev;
  5702. goto picked;
  5703. }
  5704. } else if (!preempt && prev_state) {
  5705. try_to_block_task(rq, prev, &prev_state);
  5706. switch_count = &prev->nvcsw;
  5707. }
  5708. next = pick_next_task(rq, prev, &rf);
  5709. picked:
  5710. clear_tsk_need_resched(prev);
  5711. clear_preempt_need_resched();
  5712. #ifdef CONFIG_SCHED_DEBUG
  5713. rq->last_seen_need_resched_ns = 0;
  5714. #endif
  5715. if (likely(prev != next)) {
  5716. rq->nr_switches++;
  5717. /*
  5718. * RCU users of rcu_dereference(rq->curr) may not see
  5719. * changes to task_struct made by pick_next_task().
  5720. */
  5721. RCU_INIT_POINTER(rq->curr, next);
  5722. /*
  5723. * The membarrier system call requires each architecture
  5724. * to have a full memory barrier after updating
  5725. * rq->curr, before returning to user-space.
  5726. *
  5727. * Here are the schemes providing that barrier on the
  5728. * various architectures:
  5729. * - mm ? switch_mm() : mmdrop() for x86, s390, sparc, PowerPC,
  5730. * RISC-V. switch_mm() relies on membarrier_arch_switch_mm()
  5731. * on PowerPC and on RISC-V.
  5732. * - finish_lock_switch() for weakly-ordered
  5733. * architectures where spin_unlock is a full barrier,
  5734. * - switch_to() for arm64 (weakly-ordered, spin_unlock
  5735. * is a RELEASE barrier),
  5736. *
  5737. * The barrier matches a full barrier in the proximity of
  5738. * the membarrier system call entry.
  5739. *
  5740. * On RISC-V, this barrier pairing is also needed for the
  5741. * SYNC_CORE command when switching between processes, cf.
  5742. * the inline comments in membarrier_arch_switch_mm().
  5743. */
  5744. ++*switch_count;
  5745. migrate_disable_switch(rq, prev);
  5746. psi_account_irqtime(rq, prev, next);
  5747. psi_sched_switch(prev, next, !task_on_rq_queued(prev) ||
  5748. prev->se.sched_delayed);
  5749. trace_sched_switch(preempt, prev, next, prev_state);
  5750. /* Also unlocks the rq: */
  5751. rq = context_switch(rq, prev, next, &rf);
  5752. } else {
  5753. rq_unpin_lock(rq, &rf);
  5754. __balance_callbacks(rq);
  5755. raw_spin_rq_unlock_irq(rq);
  5756. }
  5757. }
  5758. void __noreturn do_task_dead(void)
  5759. {
  5760. /* Causes final put_task_struct in finish_task_switch(): */
  5761. set_special_state(TASK_DEAD);
  5762. /* Tell freezer to ignore us: */
  5763. current->flags |= PF_NOFREEZE;
  5764. __schedule(SM_NONE);
  5765. BUG();
  5766. /* Avoid "noreturn function does return" - but don't continue if BUG() is a NOP: */
  5767. for (;;)
  5768. cpu_relax();
  5769. }
  5770. static inline void sched_submit_work(struct task_struct *tsk)
  5771. {
  5772. static DEFINE_WAIT_OVERRIDE_MAP(sched_map, LD_WAIT_CONFIG);
  5773. unsigned int task_flags;
  5774. /*
  5775. * Establish LD_WAIT_CONFIG context to ensure none of the code called
  5776. * will use a blocking primitive -- which would lead to recursion.
  5777. */
  5778. lock_map_acquire_try(&sched_map);
  5779. task_flags = tsk->flags;
  5780. /*
  5781. * If a worker goes to sleep, notify and ask workqueue whether it
  5782. * wants to wake up a task to maintain concurrency.
  5783. */
  5784. if (task_flags & PF_WQ_WORKER)
  5785. wq_worker_sleeping(tsk);
  5786. else if (task_flags & PF_IO_WORKER)
  5787. io_wq_worker_sleeping(tsk);
  5788. /*
  5789. * spinlock and rwlock must not flush block requests. This will
  5790. * deadlock if the callback attempts to acquire a lock which is
  5791. * already acquired.
  5792. */
  5793. SCHED_WARN_ON(current->__state & TASK_RTLOCK_WAIT);
  5794. /*
  5795. * If we are going to sleep and we have plugged IO queued,
  5796. * make sure to submit it to avoid deadlocks.
  5797. */
  5798. blk_flush_plug(tsk->plug, true);
  5799. lock_map_release(&sched_map);
  5800. }
  5801. static void sched_update_worker(struct task_struct *tsk)
  5802. {
  5803. if (tsk->flags & (PF_WQ_WORKER | PF_IO_WORKER | PF_BLOCK_TS)) {
  5804. if (tsk->flags & PF_BLOCK_TS)
  5805. blk_plug_invalidate_ts(tsk);
  5806. if (tsk->flags & PF_WQ_WORKER)
  5807. wq_worker_running(tsk);
  5808. else if (tsk->flags & PF_IO_WORKER)
  5809. io_wq_worker_running(tsk);
  5810. }
  5811. }
  5812. static __always_inline void __schedule_loop(int sched_mode)
  5813. {
  5814. do {
  5815. preempt_disable();
  5816. __schedule(sched_mode);
  5817. sched_preempt_enable_no_resched();
  5818. } while (need_resched());
  5819. }
  5820. asmlinkage __visible void __sched schedule(void)
  5821. {
  5822. struct task_struct *tsk = current;
  5823. #ifdef CONFIG_RT_MUTEXES
  5824. lockdep_assert(!tsk->sched_rt_mutex);
  5825. #endif
  5826. if (!task_is_running(tsk))
  5827. sched_submit_work(tsk);
  5828. __schedule_loop(SM_NONE);
  5829. sched_update_worker(tsk);
  5830. }
  5831. EXPORT_SYMBOL(schedule);
  5832. /*
  5833. * synchronize_rcu_tasks() makes sure that no task is stuck in preempted
  5834. * state (have scheduled out non-voluntarily) by making sure that all
  5835. * tasks have either left the run queue or have gone into user space.
  5836. * As idle tasks do not do either, they must not ever be preempted
  5837. * (schedule out non-voluntarily).
  5838. *
  5839. * schedule_idle() is similar to schedule_preempt_disable() except that it
  5840. * never enables preemption because it does not call sched_submit_work().
  5841. */
  5842. void __sched schedule_idle(void)
  5843. {
  5844. /*
  5845. * As this skips calling sched_submit_work(), which the idle task does
  5846. * regardless because that function is a NOP when the task is in a
  5847. * TASK_RUNNING state, make sure this isn't used someplace that the
  5848. * current task can be in any other state. Note, idle is always in the
  5849. * TASK_RUNNING state.
  5850. */
  5851. WARN_ON_ONCE(current->__state);
  5852. do {
  5853. __schedule(SM_IDLE);
  5854. } while (need_resched());
  5855. }
  5856. #if defined(CONFIG_CONTEXT_TRACKING_USER) && !defined(CONFIG_HAVE_CONTEXT_TRACKING_USER_OFFSTACK)
  5857. asmlinkage __visible void __sched schedule_user(void)
  5858. {
  5859. /*
  5860. * If we come here after a random call to set_need_resched(),
  5861. * or we have been woken up remotely but the IPI has not yet arrived,
  5862. * we haven't yet exited the RCU idle mode. Do it here manually until
  5863. * we find a better solution.
  5864. *
  5865. * NB: There are buggy callers of this function. Ideally we
  5866. * should warn if prev_state != CT_STATE_USER, but that will trigger
  5867. * too frequently to make sense yet.
  5868. */
  5869. enum ctx_state prev_state = exception_enter();
  5870. schedule();
  5871. exception_exit(prev_state);
  5872. }
  5873. #endif
  5874. /**
  5875. * schedule_preempt_disabled - called with preemption disabled
  5876. *
  5877. * Returns with preemption disabled. Note: preempt_count must be 1
  5878. */
  5879. void __sched schedule_preempt_disabled(void)
  5880. {
  5881. sched_preempt_enable_no_resched();
  5882. schedule();
  5883. preempt_disable();
  5884. }
  5885. #ifdef CONFIG_PREEMPT_RT
  5886. void __sched notrace schedule_rtlock(void)
  5887. {
  5888. __schedule_loop(SM_RTLOCK_WAIT);
  5889. }
  5890. NOKPROBE_SYMBOL(schedule_rtlock);
  5891. #endif
  5892. static void __sched notrace preempt_schedule_common(void)
  5893. {
  5894. do {
  5895. /*
  5896. * Because the function tracer can trace preempt_count_sub()
  5897. * and it also uses preempt_enable/disable_notrace(), if
  5898. * NEED_RESCHED is set, the preempt_enable_notrace() called
  5899. * by the function tracer will call this function again and
  5900. * cause infinite recursion.
  5901. *
  5902. * Preemption must be disabled here before the function
  5903. * tracer can trace. Break up preempt_disable() into two
  5904. * calls. One to disable preemption without fear of being
  5905. * traced. The other to still record the preemption latency,
  5906. * which can also be traced by the function tracer.
  5907. */
  5908. preempt_disable_notrace();
  5909. preempt_latency_start(1);
  5910. __schedule(SM_PREEMPT);
  5911. preempt_latency_stop(1);
  5912. preempt_enable_no_resched_notrace();
  5913. /*
  5914. * Check again in case we missed a preemption opportunity
  5915. * between schedule and now.
  5916. */
  5917. } while (need_resched());
  5918. }
  5919. #ifdef CONFIG_PREEMPTION
  5920. /*
  5921. * This is the entry point to schedule() from in-kernel preemption
  5922. * off of preempt_enable.
  5923. */
  5924. asmlinkage __visible void __sched notrace preempt_schedule(void)
  5925. {
  5926. /*
  5927. * If there is a non-zero preempt_count or interrupts are disabled,
  5928. * we do not want to preempt the current task. Just return..
  5929. */
  5930. if (likely(!preemptible()))
  5931. return;
  5932. preempt_schedule_common();
  5933. }
  5934. NOKPROBE_SYMBOL(preempt_schedule);
  5935. EXPORT_SYMBOL(preempt_schedule);
  5936. #ifdef CONFIG_PREEMPT_DYNAMIC
  5937. #if defined(CONFIG_HAVE_PREEMPT_DYNAMIC_CALL)
  5938. #ifndef preempt_schedule_dynamic_enabled
  5939. #define preempt_schedule_dynamic_enabled preempt_schedule
  5940. #define preempt_schedule_dynamic_disabled NULL
  5941. #endif
  5942. DEFINE_STATIC_CALL(preempt_schedule, preempt_schedule_dynamic_enabled);
  5943. EXPORT_STATIC_CALL_TRAMP(preempt_schedule);
  5944. #elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY)
  5945. static DEFINE_STATIC_KEY_TRUE(sk_dynamic_preempt_schedule);
  5946. void __sched notrace dynamic_preempt_schedule(void)
  5947. {
  5948. if (!static_branch_unlikely(&sk_dynamic_preempt_schedule))
  5949. return;
  5950. preempt_schedule();
  5951. }
  5952. NOKPROBE_SYMBOL(dynamic_preempt_schedule);
  5953. EXPORT_SYMBOL(dynamic_preempt_schedule);
  5954. #endif
  5955. #endif
  5956. /**
  5957. * preempt_schedule_notrace - preempt_schedule called by tracing
  5958. *
  5959. * The tracing infrastructure uses preempt_enable_notrace to prevent
  5960. * recursion and tracing preempt enabling caused by the tracing
  5961. * infrastructure itself. But as tracing can happen in areas coming
  5962. * from userspace or just about to enter userspace, a preempt enable
  5963. * can occur before user_exit() is called. This will cause the scheduler
  5964. * to be called when the system is still in usermode.
  5965. *
  5966. * To prevent this, the preempt_enable_notrace will use this function
  5967. * instead of preempt_schedule() to exit user context if needed before
  5968. * calling the scheduler.
  5969. */
  5970. asmlinkage __visible void __sched notrace preempt_schedule_notrace(void)
  5971. {
  5972. enum ctx_state prev_ctx;
  5973. if (likely(!preemptible()))
  5974. return;
  5975. do {
  5976. /*
  5977. * Because the function tracer can trace preempt_count_sub()
  5978. * and it also uses preempt_enable/disable_notrace(), if
  5979. * NEED_RESCHED is set, the preempt_enable_notrace() called
  5980. * by the function tracer will call this function again and
  5981. * cause infinite recursion.
  5982. *
  5983. * Preemption must be disabled here before the function
  5984. * tracer can trace. Break up preempt_disable() into two
  5985. * calls. One to disable preemption without fear of being
  5986. * traced. The other to still record the preemption latency,
  5987. * which can also be traced by the function tracer.
  5988. */
  5989. preempt_disable_notrace();
  5990. preempt_latency_start(1);
  5991. /*
  5992. * Needs preempt disabled in case user_exit() is traced
  5993. * and the tracer calls preempt_enable_notrace() causing
  5994. * an infinite recursion.
  5995. */
  5996. prev_ctx = exception_enter();
  5997. __schedule(SM_PREEMPT);
  5998. exception_exit(prev_ctx);
  5999. preempt_latency_stop(1);
  6000. preempt_enable_no_resched_notrace();
  6001. } while (need_resched());
  6002. }
  6003. EXPORT_SYMBOL_GPL(preempt_schedule_notrace);
  6004. #ifdef CONFIG_PREEMPT_DYNAMIC
  6005. #if defined(CONFIG_HAVE_PREEMPT_DYNAMIC_CALL)
  6006. #ifndef preempt_schedule_notrace_dynamic_enabled
  6007. #define preempt_schedule_notrace_dynamic_enabled preempt_schedule_notrace
  6008. #define preempt_schedule_notrace_dynamic_disabled NULL
  6009. #endif
  6010. DEFINE_STATIC_CALL(preempt_schedule_notrace, preempt_schedule_notrace_dynamic_enabled);
  6011. EXPORT_STATIC_CALL_TRAMP(preempt_schedule_notrace);
  6012. #elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY)
  6013. static DEFINE_STATIC_KEY_TRUE(sk_dynamic_preempt_schedule_notrace);
  6014. void __sched notrace dynamic_preempt_schedule_notrace(void)
  6015. {
  6016. if (!static_branch_unlikely(&sk_dynamic_preempt_schedule_notrace))
  6017. return;
  6018. preempt_schedule_notrace();
  6019. }
  6020. NOKPROBE_SYMBOL(dynamic_preempt_schedule_notrace);
  6021. EXPORT_SYMBOL(dynamic_preempt_schedule_notrace);
  6022. #endif
  6023. #endif
  6024. #endif /* CONFIG_PREEMPTION */
  6025. /*
  6026. * This is the entry point to schedule() from kernel preemption
  6027. * off of IRQ context.
  6028. * Note, that this is called and return with IRQs disabled. This will
  6029. * protect us against recursive calling from IRQ contexts.
  6030. */
  6031. asmlinkage __visible void __sched preempt_schedule_irq(void)
  6032. {
  6033. enum ctx_state prev_state;
  6034. /* Catch callers which need to be fixed */
  6035. BUG_ON(preempt_count() || !irqs_disabled());
  6036. prev_state = exception_enter();
  6037. do {
  6038. preempt_disable();
  6039. local_irq_enable();
  6040. __schedule(SM_PREEMPT);
  6041. local_irq_disable();
  6042. sched_preempt_enable_no_resched();
  6043. } while (need_resched());
  6044. exception_exit(prev_state);
  6045. }
  6046. int default_wake_function(wait_queue_entry_t *curr, unsigned mode, int wake_flags,
  6047. void *key)
  6048. {
  6049. WARN_ON_ONCE(IS_ENABLED(CONFIG_SCHED_DEBUG) && wake_flags & ~(WF_SYNC|WF_CURRENT_CPU));
  6050. return try_to_wake_up(curr->private, mode, wake_flags);
  6051. }
  6052. EXPORT_SYMBOL(default_wake_function);
  6053. const struct sched_class *__setscheduler_class(int policy, int prio)
  6054. {
  6055. if (dl_prio(prio))
  6056. return &dl_sched_class;
  6057. if (rt_prio(prio))
  6058. return &rt_sched_class;
  6059. #ifdef CONFIG_SCHED_CLASS_EXT
  6060. if (task_should_scx(policy))
  6061. return &ext_sched_class;
  6062. #endif
  6063. return &fair_sched_class;
  6064. }
  6065. #ifdef CONFIG_RT_MUTEXES
  6066. /*
  6067. * Would be more useful with typeof()/auto_type but they don't mix with
  6068. * bit-fields. Since it's a local thing, use int. Keep the generic sounding
  6069. * name such that if someone were to implement this function we get to compare
  6070. * notes.
  6071. */
  6072. #define fetch_and_set(x, v) ({ int _x = (x); (x) = (v); _x; })
  6073. void rt_mutex_pre_schedule(void)
  6074. {
  6075. lockdep_assert(!fetch_and_set(current->sched_rt_mutex, 1));
  6076. sched_submit_work(current);
  6077. }
  6078. void rt_mutex_schedule(void)
  6079. {
  6080. lockdep_assert(current->sched_rt_mutex);
  6081. __schedule_loop(SM_NONE);
  6082. }
  6083. void rt_mutex_post_schedule(void)
  6084. {
  6085. sched_update_worker(current);
  6086. lockdep_assert(fetch_and_set(current->sched_rt_mutex, 0));
  6087. }
  6088. /*
  6089. * rt_mutex_setprio - set the current priority of a task
  6090. * @p: task to boost
  6091. * @pi_task: donor task
  6092. *
  6093. * This function changes the 'effective' priority of a task. It does
  6094. * not touch ->normal_prio like __setscheduler().
  6095. *
  6096. * Used by the rt_mutex code to implement priority inheritance
  6097. * logic. Call site only calls if the priority of the task changed.
  6098. */
  6099. void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task)
  6100. {
  6101. int prio, oldprio, queued, running, queue_flag =
  6102. DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
  6103. const struct sched_class *prev_class, *next_class;
  6104. struct rq_flags rf;
  6105. struct rq *rq;
  6106. /* XXX used to be waiter->prio, not waiter->task->prio */
  6107. prio = __rt_effective_prio(pi_task, p->normal_prio);
  6108. /*
  6109. * If nothing changed; bail early.
  6110. */
  6111. if (p->pi_top_task == pi_task && prio == p->prio && !dl_prio(prio))
  6112. return;
  6113. rq = __task_rq_lock(p, &rf);
  6114. update_rq_clock(rq);
  6115. /*
  6116. * Set under pi_lock && rq->lock, such that the value can be used under
  6117. * either lock.
  6118. *
  6119. * Note that there is loads of tricky to make this pointer cache work
  6120. * right. rt_mutex_slowunlock()+rt_mutex_postunlock() work together to
  6121. * ensure a task is de-boosted (pi_task is set to NULL) before the
  6122. * task is allowed to run again (and can exit). This ensures the pointer
  6123. * points to a blocked task -- which guarantees the task is present.
  6124. */
  6125. p->pi_top_task = pi_task;
  6126. /*
  6127. * For FIFO/RR we only need to set prio, if that matches we're done.
  6128. */
  6129. if (prio == p->prio && !dl_prio(prio))
  6130. goto out_unlock;
  6131. /*
  6132. * Idle task boosting is a no-no in general. There is one
  6133. * exception, when PREEMPT_RT and NOHZ is active:
  6134. *
  6135. * The idle task calls get_next_timer_interrupt() and holds
  6136. * the timer wheel base->lock on the CPU and another CPU wants
  6137. * to access the timer (probably to cancel it). We can safely
  6138. * ignore the boosting request, as the idle CPU runs this code
  6139. * with interrupts disabled and will complete the lock
  6140. * protected section without being interrupted. So there is no
  6141. * real need to boost.
  6142. */
  6143. if (unlikely(p == rq->idle)) {
  6144. WARN_ON(p != rq->curr);
  6145. WARN_ON(p->pi_blocked_on);
  6146. goto out_unlock;
  6147. }
  6148. trace_sched_pi_setprio(p, pi_task);
  6149. oldprio = p->prio;
  6150. if (oldprio == prio)
  6151. queue_flag &= ~DEQUEUE_MOVE;
  6152. prev_class = p->sched_class;
  6153. next_class = __setscheduler_class(p->policy, prio);
  6154. if (prev_class != next_class && p->se.sched_delayed)
  6155. dequeue_task(rq, p, DEQUEUE_SLEEP | DEQUEUE_DELAYED | DEQUEUE_NOCLOCK);
  6156. queued = task_on_rq_queued(p);
  6157. running = task_current(rq, p);
  6158. if (queued)
  6159. dequeue_task(rq, p, queue_flag);
  6160. if (running)
  6161. put_prev_task(rq, p);
  6162. /*
  6163. * Boosting condition are:
  6164. * 1. -rt task is running and holds mutex A
  6165. * --> -dl task blocks on mutex A
  6166. *
  6167. * 2. -dl task is running and holds mutex A
  6168. * --> -dl task blocks on mutex A and could preempt the
  6169. * running task
  6170. */
  6171. if (dl_prio(prio)) {
  6172. if (!dl_prio(p->normal_prio) ||
  6173. (pi_task && dl_prio(pi_task->prio) &&
  6174. dl_entity_preempt(&pi_task->dl, &p->dl))) {
  6175. p->dl.pi_se = pi_task->dl.pi_se;
  6176. queue_flag |= ENQUEUE_REPLENISH;
  6177. } else {
  6178. p->dl.pi_se = &p->dl;
  6179. }
  6180. } else if (rt_prio(prio)) {
  6181. if (dl_prio(oldprio))
  6182. p->dl.pi_se = &p->dl;
  6183. if (oldprio < prio)
  6184. queue_flag |= ENQUEUE_HEAD;
  6185. } else {
  6186. if (dl_prio(oldprio))
  6187. p->dl.pi_se = &p->dl;
  6188. if (rt_prio(oldprio))
  6189. p->rt.timeout = 0;
  6190. }
  6191. p->sched_class = next_class;
  6192. p->prio = prio;
  6193. check_class_changing(rq, p, prev_class);
  6194. if (queued)
  6195. enqueue_task(rq, p, queue_flag);
  6196. if (running)
  6197. set_next_task(rq, p);
  6198. check_class_changed(rq, p, prev_class, oldprio);
  6199. out_unlock:
  6200. /* Avoid rq from going away on us: */
  6201. preempt_disable();
  6202. rq_unpin_lock(rq, &rf);
  6203. __balance_callbacks(rq);
  6204. raw_spin_rq_unlock(rq);
  6205. preempt_enable();
  6206. }
  6207. #endif
  6208. #if !defined(CONFIG_PREEMPTION) || defined(CONFIG_PREEMPT_DYNAMIC)
  6209. int __sched __cond_resched(void)
  6210. {
  6211. if (should_resched(0) && !irqs_disabled()) {
  6212. preempt_schedule_common();
  6213. return 1;
  6214. }
  6215. /*
  6216. * In preemptible kernels, ->rcu_read_lock_nesting tells the tick
  6217. * whether the current CPU is in an RCU read-side critical section,
  6218. * so the tick can report quiescent states even for CPUs looping
  6219. * in kernel context. In contrast, in non-preemptible kernels,
  6220. * RCU readers leave no in-memory hints, which means that CPU-bound
  6221. * processes executing in kernel context might never report an
  6222. * RCU quiescent state. Therefore, the following code causes
  6223. * cond_resched() to report a quiescent state, but only when RCU
  6224. * is in urgent need of one.
  6225. */
  6226. #ifndef CONFIG_PREEMPT_RCU
  6227. rcu_all_qs();
  6228. #endif
  6229. return 0;
  6230. }
  6231. EXPORT_SYMBOL(__cond_resched);
  6232. #endif
  6233. #ifdef CONFIG_PREEMPT_DYNAMIC
  6234. #if defined(CONFIG_HAVE_PREEMPT_DYNAMIC_CALL)
  6235. #define cond_resched_dynamic_enabled __cond_resched
  6236. #define cond_resched_dynamic_disabled ((void *)&__static_call_return0)
  6237. DEFINE_STATIC_CALL_RET0(cond_resched, __cond_resched);
  6238. EXPORT_STATIC_CALL_TRAMP(cond_resched);
  6239. #define might_resched_dynamic_enabled __cond_resched
  6240. #define might_resched_dynamic_disabled ((void *)&__static_call_return0)
  6241. DEFINE_STATIC_CALL_RET0(might_resched, __cond_resched);
  6242. EXPORT_STATIC_CALL_TRAMP(might_resched);
  6243. #elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY)
  6244. static DEFINE_STATIC_KEY_FALSE(sk_dynamic_cond_resched);
  6245. int __sched dynamic_cond_resched(void)
  6246. {
  6247. klp_sched_try_switch();
  6248. if (!static_branch_unlikely(&sk_dynamic_cond_resched))
  6249. return 0;
  6250. return __cond_resched();
  6251. }
  6252. EXPORT_SYMBOL(dynamic_cond_resched);
  6253. static DEFINE_STATIC_KEY_FALSE(sk_dynamic_might_resched);
  6254. int __sched dynamic_might_resched(void)
  6255. {
  6256. if (!static_branch_unlikely(&sk_dynamic_might_resched))
  6257. return 0;
  6258. return __cond_resched();
  6259. }
  6260. EXPORT_SYMBOL(dynamic_might_resched);
  6261. #endif
  6262. #endif
  6263. /*
  6264. * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
  6265. * call schedule, and on return reacquire the lock.
  6266. *
  6267. * This works OK both with and without CONFIG_PREEMPTION. We do strange low-level
  6268. * operations here to prevent schedule() from being called twice (once via
  6269. * spin_unlock(), once by hand).
  6270. */
  6271. int __cond_resched_lock(spinlock_t *lock)
  6272. {
  6273. int resched = should_resched(PREEMPT_LOCK_OFFSET);
  6274. int ret = 0;
  6275. lockdep_assert_held(lock);
  6276. if (spin_needbreak(lock) || resched) {
  6277. spin_unlock(lock);
  6278. if (!_cond_resched())
  6279. cpu_relax();
  6280. ret = 1;
  6281. spin_lock(lock);
  6282. }
  6283. return ret;
  6284. }
  6285. EXPORT_SYMBOL(__cond_resched_lock);
  6286. int __cond_resched_rwlock_read(rwlock_t *lock)
  6287. {
  6288. int resched = should_resched(PREEMPT_LOCK_OFFSET);
  6289. int ret = 0;
  6290. lockdep_assert_held_read(lock);
  6291. if (rwlock_needbreak(lock) || resched) {
  6292. read_unlock(lock);
  6293. if (!_cond_resched())
  6294. cpu_relax();
  6295. ret = 1;
  6296. read_lock(lock);
  6297. }
  6298. return ret;
  6299. }
  6300. EXPORT_SYMBOL(__cond_resched_rwlock_read);
  6301. int __cond_resched_rwlock_write(rwlock_t *lock)
  6302. {
  6303. int resched = should_resched(PREEMPT_LOCK_OFFSET);
  6304. int ret = 0;
  6305. lockdep_assert_held_write(lock);
  6306. if (rwlock_needbreak(lock) || resched) {
  6307. write_unlock(lock);
  6308. if (!_cond_resched())
  6309. cpu_relax();
  6310. ret = 1;
  6311. write_lock(lock);
  6312. }
  6313. return ret;
  6314. }
  6315. EXPORT_SYMBOL(__cond_resched_rwlock_write);
  6316. #ifdef CONFIG_PREEMPT_DYNAMIC
  6317. #ifdef CONFIG_GENERIC_ENTRY
  6318. #include <linux/entry-common.h>
  6319. #endif
  6320. /*
  6321. * SC:cond_resched
  6322. * SC:might_resched
  6323. * SC:preempt_schedule
  6324. * SC:preempt_schedule_notrace
  6325. * SC:irqentry_exit_cond_resched
  6326. *
  6327. *
  6328. * NONE:
  6329. * cond_resched <- __cond_resched
  6330. * might_resched <- RET0
  6331. * preempt_schedule <- NOP
  6332. * preempt_schedule_notrace <- NOP
  6333. * irqentry_exit_cond_resched <- NOP
  6334. *
  6335. * VOLUNTARY:
  6336. * cond_resched <- __cond_resched
  6337. * might_resched <- __cond_resched
  6338. * preempt_schedule <- NOP
  6339. * preempt_schedule_notrace <- NOP
  6340. * irqentry_exit_cond_resched <- NOP
  6341. *
  6342. * FULL:
  6343. * cond_resched <- RET0
  6344. * might_resched <- RET0
  6345. * preempt_schedule <- preempt_schedule
  6346. * preempt_schedule_notrace <- preempt_schedule_notrace
  6347. * irqentry_exit_cond_resched <- irqentry_exit_cond_resched
  6348. */
  6349. enum {
  6350. preempt_dynamic_undefined = -1,
  6351. preempt_dynamic_none,
  6352. preempt_dynamic_voluntary,
  6353. preempt_dynamic_full,
  6354. };
  6355. int preempt_dynamic_mode = preempt_dynamic_undefined;
  6356. int sched_dynamic_mode(const char *str)
  6357. {
  6358. if (!strcmp(str, "none"))
  6359. return preempt_dynamic_none;
  6360. if (!strcmp(str, "voluntary"))
  6361. return preempt_dynamic_voluntary;
  6362. if (!strcmp(str, "full"))
  6363. return preempt_dynamic_full;
  6364. return -EINVAL;
  6365. }
  6366. #if defined(CONFIG_HAVE_PREEMPT_DYNAMIC_CALL)
  6367. #define preempt_dynamic_enable(f) static_call_update(f, f##_dynamic_enabled)
  6368. #define preempt_dynamic_disable(f) static_call_update(f, f##_dynamic_disabled)
  6369. #elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY)
  6370. #define preempt_dynamic_enable(f) static_key_enable(&sk_dynamic_##f.key)
  6371. #define preempt_dynamic_disable(f) static_key_disable(&sk_dynamic_##f.key)
  6372. #else
  6373. #error "Unsupported PREEMPT_DYNAMIC mechanism"
  6374. #endif
  6375. static DEFINE_MUTEX(sched_dynamic_mutex);
  6376. static bool klp_override;
  6377. static void __sched_dynamic_update(int mode)
  6378. {
  6379. /*
  6380. * Avoid {NONE,VOLUNTARY} -> FULL transitions from ever ending up in
  6381. * the ZERO state, which is invalid.
  6382. */
  6383. if (!klp_override)
  6384. preempt_dynamic_enable(cond_resched);
  6385. preempt_dynamic_enable(might_resched);
  6386. preempt_dynamic_enable(preempt_schedule);
  6387. preempt_dynamic_enable(preempt_schedule_notrace);
  6388. preempt_dynamic_enable(irqentry_exit_cond_resched);
  6389. switch (mode) {
  6390. case preempt_dynamic_none:
  6391. if (!klp_override)
  6392. preempt_dynamic_enable(cond_resched);
  6393. preempt_dynamic_disable(might_resched);
  6394. preempt_dynamic_disable(preempt_schedule);
  6395. preempt_dynamic_disable(preempt_schedule_notrace);
  6396. preempt_dynamic_disable(irqentry_exit_cond_resched);
  6397. if (mode != preempt_dynamic_mode)
  6398. pr_info("Dynamic Preempt: none\n");
  6399. break;
  6400. case preempt_dynamic_voluntary:
  6401. if (!klp_override)
  6402. preempt_dynamic_enable(cond_resched);
  6403. preempt_dynamic_enable(might_resched);
  6404. preempt_dynamic_disable(preempt_schedule);
  6405. preempt_dynamic_disable(preempt_schedule_notrace);
  6406. preempt_dynamic_disable(irqentry_exit_cond_resched);
  6407. if (mode != preempt_dynamic_mode)
  6408. pr_info("Dynamic Preempt: voluntary\n");
  6409. break;
  6410. case preempt_dynamic_full:
  6411. if (!klp_override)
  6412. preempt_dynamic_disable(cond_resched);
  6413. preempt_dynamic_disable(might_resched);
  6414. preempt_dynamic_enable(preempt_schedule);
  6415. preempt_dynamic_enable(preempt_schedule_notrace);
  6416. preempt_dynamic_enable(irqentry_exit_cond_resched);
  6417. if (mode != preempt_dynamic_mode)
  6418. pr_info("Dynamic Preempt: full\n");
  6419. break;
  6420. }
  6421. preempt_dynamic_mode = mode;
  6422. }
  6423. void sched_dynamic_update(int mode)
  6424. {
  6425. mutex_lock(&sched_dynamic_mutex);
  6426. __sched_dynamic_update(mode);
  6427. mutex_unlock(&sched_dynamic_mutex);
  6428. }
  6429. #ifdef CONFIG_HAVE_PREEMPT_DYNAMIC_CALL
  6430. static int klp_cond_resched(void)
  6431. {
  6432. __klp_sched_try_switch();
  6433. return __cond_resched();
  6434. }
  6435. void sched_dynamic_klp_enable(void)
  6436. {
  6437. mutex_lock(&sched_dynamic_mutex);
  6438. klp_override = true;
  6439. static_call_update(cond_resched, klp_cond_resched);
  6440. mutex_unlock(&sched_dynamic_mutex);
  6441. }
  6442. void sched_dynamic_klp_disable(void)
  6443. {
  6444. mutex_lock(&sched_dynamic_mutex);
  6445. klp_override = false;
  6446. __sched_dynamic_update(preempt_dynamic_mode);
  6447. mutex_unlock(&sched_dynamic_mutex);
  6448. }
  6449. #endif /* CONFIG_HAVE_PREEMPT_DYNAMIC_CALL */
  6450. static int __init setup_preempt_mode(char *str)
  6451. {
  6452. int mode = sched_dynamic_mode(str);
  6453. if (mode < 0) {
  6454. pr_warn("Dynamic Preempt: unsupported mode: %s\n", str);
  6455. return 0;
  6456. }
  6457. sched_dynamic_update(mode);
  6458. return 1;
  6459. }
  6460. __setup("preempt=", setup_preempt_mode);
  6461. static void __init preempt_dynamic_init(void)
  6462. {
  6463. if (preempt_dynamic_mode == preempt_dynamic_undefined) {
  6464. if (IS_ENABLED(CONFIG_PREEMPT_NONE)) {
  6465. sched_dynamic_update(preempt_dynamic_none);
  6466. } else if (IS_ENABLED(CONFIG_PREEMPT_VOLUNTARY)) {
  6467. sched_dynamic_update(preempt_dynamic_voluntary);
  6468. } else {
  6469. /* Default static call setting, nothing to do */
  6470. WARN_ON_ONCE(!IS_ENABLED(CONFIG_PREEMPT));
  6471. preempt_dynamic_mode = preempt_dynamic_full;
  6472. pr_info("Dynamic Preempt: full\n");
  6473. }
  6474. }
  6475. }
  6476. #define PREEMPT_MODEL_ACCESSOR(mode) \
  6477. bool preempt_model_##mode(void) \
  6478. { \
  6479. WARN_ON_ONCE(preempt_dynamic_mode == preempt_dynamic_undefined); \
  6480. return preempt_dynamic_mode == preempt_dynamic_##mode; \
  6481. } \
  6482. EXPORT_SYMBOL_GPL(preempt_model_##mode)
  6483. PREEMPT_MODEL_ACCESSOR(none);
  6484. PREEMPT_MODEL_ACCESSOR(voluntary);
  6485. PREEMPT_MODEL_ACCESSOR(full);
  6486. #else /* !CONFIG_PREEMPT_DYNAMIC: */
  6487. static inline void preempt_dynamic_init(void) { }
  6488. #endif /* CONFIG_PREEMPT_DYNAMIC */
  6489. int io_schedule_prepare(void)
  6490. {
  6491. int old_iowait = current->in_iowait;
  6492. current->in_iowait = 1;
  6493. blk_flush_plug(current->plug, true);
  6494. return old_iowait;
  6495. }
  6496. void io_schedule_finish(int token)
  6497. {
  6498. current->in_iowait = token;
  6499. }
  6500. /*
  6501. * This task is about to go to sleep on IO. Increment rq->nr_iowait so
  6502. * that process accounting knows that this is a task in IO wait state.
  6503. */
  6504. long __sched io_schedule_timeout(long timeout)
  6505. {
  6506. int token;
  6507. long ret;
  6508. token = io_schedule_prepare();
  6509. ret = schedule_timeout(timeout);
  6510. io_schedule_finish(token);
  6511. return ret;
  6512. }
  6513. EXPORT_SYMBOL(io_schedule_timeout);
  6514. void __sched io_schedule(void)
  6515. {
  6516. int token;
  6517. token = io_schedule_prepare();
  6518. schedule();
  6519. io_schedule_finish(token);
  6520. }
  6521. EXPORT_SYMBOL(io_schedule);
  6522. void sched_show_task(struct task_struct *p)
  6523. {
  6524. unsigned long free;
  6525. int ppid;
  6526. if (!try_get_task_stack(p))
  6527. return;
  6528. pr_info("task:%-15.15s state:%c", p->comm, task_state_to_char(p));
  6529. if (task_is_running(p))
  6530. pr_cont(" running task ");
  6531. free = stack_not_used(p);
  6532. ppid = 0;
  6533. rcu_read_lock();
  6534. if (pid_alive(p))
  6535. ppid = task_pid_nr(rcu_dereference(p->real_parent));
  6536. rcu_read_unlock();
  6537. pr_cont(" stack:%-5lu pid:%-5d tgid:%-5d ppid:%-6d flags:0x%08lx\n",
  6538. free, task_pid_nr(p), task_tgid_nr(p),
  6539. ppid, read_task_thread_flags(p));
  6540. print_worker_info(KERN_INFO, p);
  6541. print_stop_info(KERN_INFO, p);
  6542. print_scx_info(KERN_INFO, p);
  6543. show_stack(p, NULL, KERN_INFO);
  6544. put_task_stack(p);
  6545. }
  6546. EXPORT_SYMBOL_GPL(sched_show_task);
  6547. static inline bool
  6548. state_filter_match(unsigned long state_filter, struct task_struct *p)
  6549. {
  6550. unsigned int state = READ_ONCE(p->__state);
  6551. /* no filter, everything matches */
  6552. if (!state_filter)
  6553. return true;
  6554. /* filter, but doesn't match */
  6555. if (!(state & state_filter))
  6556. return false;
  6557. /*
  6558. * When looking for TASK_UNINTERRUPTIBLE skip TASK_IDLE (allows
  6559. * TASK_KILLABLE).
  6560. */
  6561. if (state_filter == TASK_UNINTERRUPTIBLE && (state & TASK_NOLOAD))
  6562. return false;
  6563. return true;
  6564. }
  6565. void show_state_filter(unsigned int state_filter)
  6566. {
  6567. struct task_struct *g, *p;
  6568. rcu_read_lock();
  6569. for_each_process_thread(g, p) {
  6570. /*
  6571. * reset the NMI-timeout, listing all files on a slow
  6572. * console might take a lot of time:
  6573. * Also, reset softlockup watchdogs on all CPUs, because
  6574. * another CPU might be blocked waiting for us to process
  6575. * an IPI.
  6576. */
  6577. touch_nmi_watchdog();
  6578. touch_all_softlockup_watchdogs();
  6579. if (state_filter_match(state_filter, p))
  6580. sched_show_task(p);
  6581. }
  6582. #ifdef CONFIG_SCHED_DEBUG
  6583. if (!state_filter)
  6584. sysrq_sched_debug_show();
  6585. #endif
  6586. rcu_read_unlock();
  6587. /*
  6588. * Only show locks if all tasks are dumped:
  6589. */
  6590. if (!state_filter)
  6591. debug_show_all_locks();
  6592. }
  6593. /**
  6594. * init_idle - set up an idle thread for a given CPU
  6595. * @idle: task in question
  6596. * @cpu: CPU the idle task belongs to
  6597. *
  6598. * NOTE: this function does not set the idle thread's NEED_RESCHED
  6599. * flag, to make booting more robust.
  6600. */
  6601. void __init init_idle(struct task_struct *idle, int cpu)
  6602. {
  6603. #ifdef CONFIG_SMP
  6604. struct affinity_context ac = (struct affinity_context) {
  6605. .new_mask = cpumask_of(cpu),
  6606. .flags = 0,
  6607. };
  6608. #endif
  6609. struct rq *rq = cpu_rq(cpu);
  6610. unsigned long flags;
  6611. raw_spin_lock_irqsave(&idle->pi_lock, flags);
  6612. raw_spin_rq_lock(rq);
  6613. idle->__state = TASK_RUNNING;
  6614. idle->se.exec_start = sched_clock();
  6615. /*
  6616. * PF_KTHREAD should already be set at this point; regardless, make it
  6617. * look like a proper per-CPU kthread.
  6618. */
  6619. idle->flags |= PF_KTHREAD | PF_NO_SETAFFINITY;
  6620. kthread_set_per_cpu(idle, cpu);
  6621. #ifdef CONFIG_SMP
  6622. /*
  6623. * No validation and serialization required at boot time and for
  6624. * setting up the idle tasks of not yet online CPUs.
  6625. */
  6626. set_cpus_allowed_common(idle, &ac);
  6627. #endif
  6628. /*
  6629. * We're having a chicken and egg problem, even though we are
  6630. * holding rq->lock, the CPU isn't yet set to this CPU so the
  6631. * lockdep check in task_group() will fail.
  6632. *
  6633. * Similar case to sched_fork(). / Alternatively we could
  6634. * use task_rq_lock() here and obtain the other rq->lock.
  6635. *
  6636. * Silence PROVE_RCU
  6637. */
  6638. rcu_read_lock();
  6639. __set_task_cpu(idle, cpu);
  6640. rcu_read_unlock();
  6641. rq->idle = idle;
  6642. rcu_assign_pointer(rq->curr, idle);
  6643. idle->on_rq = TASK_ON_RQ_QUEUED;
  6644. #ifdef CONFIG_SMP
  6645. idle->on_cpu = 1;
  6646. #endif
  6647. raw_spin_rq_unlock(rq);
  6648. raw_spin_unlock_irqrestore(&idle->pi_lock, flags);
  6649. /* Set the preempt count _outside_ the spinlocks! */
  6650. init_idle_preempt_count(idle, cpu);
  6651. /*
  6652. * The idle tasks have their own, simple scheduling class:
  6653. */
  6654. idle->sched_class = &idle_sched_class;
  6655. ftrace_graph_init_idle_task(idle, cpu);
  6656. vtime_init_idle(idle, cpu);
  6657. #ifdef CONFIG_SMP
  6658. sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu);
  6659. #endif
  6660. }
  6661. #ifdef CONFIG_SMP
  6662. int cpuset_cpumask_can_shrink(const struct cpumask *cur,
  6663. const struct cpumask *trial)
  6664. {
  6665. int ret = 1;
  6666. if (cpumask_empty(cur))
  6667. return ret;
  6668. ret = dl_cpuset_cpumask_can_shrink(cur, trial);
  6669. return ret;
  6670. }
  6671. int task_can_attach(struct task_struct *p)
  6672. {
  6673. int ret = 0;
  6674. /*
  6675. * Kthreads which disallow setaffinity shouldn't be moved
  6676. * to a new cpuset; we don't want to change their CPU
  6677. * affinity and isolating such threads by their set of
  6678. * allowed nodes is unnecessary. Thus, cpusets are not
  6679. * applicable for such threads. This prevents checking for
  6680. * success of set_cpus_allowed_ptr() on all attached tasks
  6681. * before cpus_mask may be changed.
  6682. */
  6683. if (p->flags & PF_NO_SETAFFINITY)
  6684. ret = -EINVAL;
  6685. return ret;
  6686. }
  6687. bool sched_smp_initialized __read_mostly;
  6688. #ifdef CONFIG_NUMA_BALANCING
  6689. /* Migrate current task p to target_cpu */
  6690. int migrate_task_to(struct task_struct *p, int target_cpu)
  6691. {
  6692. struct migration_arg arg = { p, target_cpu };
  6693. int curr_cpu = task_cpu(p);
  6694. if (curr_cpu == target_cpu)
  6695. return 0;
  6696. if (!cpumask_test_cpu(target_cpu, p->cpus_ptr))
  6697. return -EINVAL;
  6698. /* TODO: This is not properly updating schedstats */
  6699. trace_sched_move_numa(p, curr_cpu, target_cpu);
  6700. return stop_one_cpu(curr_cpu, migration_cpu_stop, &arg);
  6701. }
  6702. /*
  6703. * Requeue a task on a given node and accurately track the number of NUMA
  6704. * tasks on the runqueues
  6705. */
  6706. void sched_setnuma(struct task_struct *p, int nid)
  6707. {
  6708. bool queued, running;
  6709. struct rq_flags rf;
  6710. struct rq *rq;
  6711. rq = task_rq_lock(p, &rf);
  6712. queued = task_on_rq_queued(p);
  6713. running = task_current(rq, p);
  6714. if (queued)
  6715. dequeue_task(rq, p, DEQUEUE_SAVE);
  6716. if (running)
  6717. put_prev_task(rq, p);
  6718. p->numa_preferred_nid = nid;
  6719. if (queued)
  6720. enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
  6721. if (running)
  6722. set_next_task(rq, p);
  6723. task_rq_unlock(rq, p, &rf);
  6724. }
  6725. #endif /* CONFIG_NUMA_BALANCING */
  6726. #ifdef CONFIG_HOTPLUG_CPU
  6727. /*
  6728. * Ensure that the idle task is using init_mm right before its CPU goes
  6729. * offline.
  6730. */
  6731. void idle_task_exit(void)
  6732. {
  6733. struct mm_struct *mm = current->active_mm;
  6734. BUG_ON(cpu_online(smp_processor_id()));
  6735. BUG_ON(current != this_rq()->idle);
  6736. if (mm != &init_mm) {
  6737. switch_mm(mm, &init_mm, current);
  6738. finish_arch_post_lock_switch();
  6739. }
  6740. /* finish_cpu(), as ran on the BP, will clean up the active_mm state */
  6741. }
  6742. static int __balance_push_cpu_stop(void *arg)
  6743. {
  6744. struct task_struct *p = arg;
  6745. struct rq *rq = this_rq();
  6746. struct rq_flags rf;
  6747. int cpu;
  6748. raw_spin_lock_irq(&p->pi_lock);
  6749. rq_lock(rq, &rf);
  6750. update_rq_clock(rq);
  6751. if (task_rq(p) == rq && task_on_rq_queued(p)) {
  6752. cpu = select_fallback_rq(rq->cpu, p);
  6753. rq = __migrate_task(rq, &rf, p, cpu);
  6754. }
  6755. rq_unlock(rq, &rf);
  6756. raw_spin_unlock_irq(&p->pi_lock);
  6757. put_task_struct(p);
  6758. return 0;
  6759. }
  6760. static DEFINE_PER_CPU(struct cpu_stop_work, push_work);
  6761. /*
  6762. * Ensure we only run per-cpu kthreads once the CPU goes !active.
  6763. *
  6764. * This is enabled below SCHED_AP_ACTIVE; when !cpu_active(), but only
  6765. * effective when the hotplug motion is down.
  6766. */
  6767. static void balance_push(struct rq *rq)
  6768. {
  6769. struct task_struct *push_task = rq->curr;
  6770. lockdep_assert_rq_held(rq);
  6771. /*
  6772. * Ensure the thing is persistent until balance_push_set(.on = false);
  6773. */
  6774. rq->balance_callback = &balance_push_callback;
  6775. /*
  6776. * Only active while going offline and when invoked on the outgoing
  6777. * CPU.
  6778. */
  6779. if (!cpu_dying(rq->cpu) || rq != this_rq())
  6780. return;
  6781. /*
  6782. * Both the cpu-hotplug and stop task are in this case and are
  6783. * required to complete the hotplug process.
  6784. */
  6785. if (kthread_is_per_cpu(push_task) ||
  6786. is_migration_disabled(push_task)) {
  6787. /*
  6788. * If this is the idle task on the outgoing CPU try to wake
  6789. * up the hotplug control thread which might wait for the
  6790. * last task to vanish. The rcuwait_active() check is
  6791. * accurate here because the waiter is pinned on this CPU
  6792. * and can't obviously be running in parallel.
  6793. *
  6794. * On RT kernels this also has to check whether there are
  6795. * pinned and scheduled out tasks on the runqueue. They
  6796. * need to leave the migrate disabled section first.
  6797. */
  6798. if (!rq->nr_running && !rq_has_pinned_tasks(rq) &&
  6799. rcuwait_active(&rq->hotplug_wait)) {
  6800. raw_spin_rq_unlock(rq);
  6801. rcuwait_wake_up(&rq->hotplug_wait);
  6802. raw_spin_rq_lock(rq);
  6803. }
  6804. return;
  6805. }
  6806. get_task_struct(push_task);
  6807. /*
  6808. * Temporarily drop rq->lock such that we can wake-up the stop task.
  6809. * Both preemption and IRQs are still disabled.
  6810. */
  6811. preempt_disable();
  6812. raw_spin_rq_unlock(rq);
  6813. stop_one_cpu_nowait(rq->cpu, __balance_push_cpu_stop, push_task,
  6814. this_cpu_ptr(&push_work));
  6815. preempt_enable();
  6816. /*
  6817. * At this point need_resched() is true and we'll take the loop in
  6818. * schedule(). The next pick is obviously going to be the stop task
  6819. * which kthread_is_per_cpu() and will push this task away.
  6820. */
  6821. raw_spin_rq_lock(rq);
  6822. }
  6823. static void balance_push_set(int cpu, bool on)
  6824. {
  6825. struct rq *rq = cpu_rq(cpu);
  6826. struct rq_flags rf;
  6827. rq_lock_irqsave(rq, &rf);
  6828. if (on) {
  6829. WARN_ON_ONCE(rq->balance_callback);
  6830. rq->balance_callback = &balance_push_callback;
  6831. } else if (rq->balance_callback == &balance_push_callback) {
  6832. rq->balance_callback = NULL;
  6833. }
  6834. rq_unlock_irqrestore(rq, &rf);
  6835. }
  6836. /*
  6837. * Invoked from a CPUs hotplug control thread after the CPU has been marked
  6838. * inactive. All tasks which are not per CPU kernel threads are either
  6839. * pushed off this CPU now via balance_push() or placed on a different CPU
  6840. * during wakeup. Wait until the CPU is quiescent.
  6841. */
  6842. static void balance_hotplug_wait(void)
  6843. {
  6844. struct rq *rq = this_rq();
  6845. rcuwait_wait_event(&rq->hotplug_wait,
  6846. rq->nr_running == 1 && !rq_has_pinned_tasks(rq),
  6847. TASK_UNINTERRUPTIBLE);
  6848. }
  6849. #else
  6850. static inline void balance_push(struct rq *rq)
  6851. {
  6852. }
  6853. static inline void balance_push_set(int cpu, bool on)
  6854. {
  6855. }
  6856. static inline void balance_hotplug_wait(void)
  6857. {
  6858. }
  6859. #endif /* CONFIG_HOTPLUG_CPU */
  6860. void set_rq_online(struct rq *rq)
  6861. {
  6862. if (!rq->online) {
  6863. const struct sched_class *class;
  6864. cpumask_set_cpu(rq->cpu, rq->rd->online);
  6865. rq->online = 1;
  6866. for_each_class(class) {
  6867. if (class->rq_online)
  6868. class->rq_online(rq);
  6869. }
  6870. }
  6871. }
  6872. void set_rq_offline(struct rq *rq)
  6873. {
  6874. if (rq->online) {
  6875. const struct sched_class *class;
  6876. update_rq_clock(rq);
  6877. for_each_class(class) {
  6878. if (class->rq_offline)
  6879. class->rq_offline(rq);
  6880. }
  6881. cpumask_clear_cpu(rq->cpu, rq->rd->online);
  6882. rq->online = 0;
  6883. }
  6884. }
  6885. static inline void sched_set_rq_online(struct rq *rq, int cpu)
  6886. {
  6887. struct rq_flags rf;
  6888. rq_lock_irqsave(rq, &rf);
  6889. if (rq->rd) {
  6890. BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
  6891. set_rq_online(rq);
  6892. }
  6893. rq_unlock_irqrestore(rq, &rf);
  6894. }
  6895. static inline void sched_set_rq_offline(struct rq *rq, int cpu)
  6896. {
  6897. struct rq_flags rf;
  6898. rq_lock_irqsave(rq, &rf);
  6899. if (rq->rd) {
  6900. BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
  6901. set_rq_offline(rq);
  6902. }
  6903. rq_unlock_irqrestore(rq, &rf);
  6904. }
  6905. /*
  6906. * used to mark begin/end of suspend/resume:
  6907. */
  6908. static int num_cpus_frozen;
  6909. /*
  6910. * Update cpusets according to cpu_active mask. If cpusets are
  6911. * disabled, cpuset_update_active_cpus() becomes a simple wrapper
  6912. * around partition_sched_domains().
  6913. *
  6914. * If we come here as part of a suspend/resume, don't touch cpusets because we
  6915. * want to restore it back to its original state upon resume anyway.
  6916. */
  6917. static void cpuset_cpu_active(void)
  6918. {
  6919. if (cpuhp_tasks_frozen) {
  6920. /*
  6921. * num_cpus_frozen tracks how many CPUs are involved in suspend
  6922. * resume sequence. As long as this is not the last online
  6923. * operation in the resume sequence, just build a single sched
  6924. * domain, ignoring cpusets.
  6925. */
  6926. partition_sched_domains(1, NULL, NULL);
  6927. if (--num_cpus_frozen)
  6928. return;
  6929. /*
  6930. * This is the last CPU online operation. So fall through and
  6931. * restore the original sched domains by considering the
  6932. * cpuset configurations.
  6933. */
  6934. cpuset_force_rebuild();
  6935. }
  6936. cpuset_update_active_cpus();
  6937. }
  6938. static int cpuset_cpu_inactive(unsigned int cpu)
  6939. {
  6940. if (!cpuhp_tasks_frozen) {
  6941. int ret = dl_bw_check_overflow(cpu);
  6942. if (ret)
  6943. return ret;
  6944. cpuset_update_active_cpus();
  6945. } else {
  6946. num_cpus_frozen++;
  6947. partition_sched_domains(1, NULL, NULL);
  6948. }
  6949. return 0;
  6950. }
  6951. static inline void sched_smt_present_inc(int cpu)
  6952. {
  6953. #ifdef CONFIG_SCHED_SMT
  6954. if (cpumask_weight(cpu_smt_mask(cpu)) == 2)
  6955. static_branch_inc_cpuslocked(&sched_smt_present);
  6956. #endif
  6957. }
  6958. static inline void sched_smt_present_dec(int cpu)
  6959. {
  6960. #ifdef CONFIG_SCHED_SMT
  6961. if (cpumask_weight(cpu_smt_mask(cpu)) == 2)
  6962. static_branch_dec_cpuslocked(&sched_smt_present);
  6963. #endif
  6964. }
  6965. int sched_cpu_activate(unsigned int cpu)
  6966. {
  6967. struct rq *rq = cpu_rq(cpu);
  6968. /*
  6969. * Clear the balance_push callback and prepare to schedule
  6970. * regular tasks.
  6971. */
  6972. balance_push_set(cpu, false);
  6973. /*
  6974. * When going up, increment the number of cores with SMT present.
  6975. */
  6976. sched_smt_present_inc(cpu);
  6977. set_cpu_active(cpu, true);
  6978. if (sched_smp_initialized) {
  6979. sched_update_numa(cpu, true);
  6980. sched_domains_numa_masks_set(cpu);
  6981. cpuset_cpu_active();
  6982. }
  6983. scx_rq_activate(rq);
  6984. /*
  6985. * Put the rq online, if not already. This happens:
  6986. *
  6987. * 1) In the early boot process, because we build the real domains
  6988. * after all CPUs have been brought up.
  6989. *
  6990. * 2) At runtime, if cpuset_cpu_active() fails to rebuild the
  6991. * domains.
  6992. */
  6993. sched_set_rq_online(rq, cpu);
  6994. return 0;
  6995. }
  6996. int sched_cpu_deactivate(unsigned int cpu)
  6997. {
  6998. struct rq *rq = cpu_rq(cpu);
  6999. int ret;
  7000. /*
  7001. * Remove CPU from nohz.idle_cpus_mask to prevent participating in
  7002. * load balancing when not active
  7003. */
  7004. nohz_balance_exit_idle(rq);
  7005. set_cpu_active(cpu, false);
  7006. /*
  7007. * From this point forward, this CPU will refuse to run any task that
  7008. * is not: migrate_disable() or KTHREAD_IS_PER_CPU, and will actively
  7009. * push those tasks away until this gets cleared, see
  7010. * sched_cpu_dying().
  7011. */
  7012. balance_push_set(cpu, true);
  7013. /*
  7014. * We've cleared cpu_active_mask / set balance_push, wait for all
  7015. * preempt-disabled and RCU users of this state to go away such that
  7016. * all new such users will observe it.
  7017. *
  7018. * Specifically, we rely on ttwu to no longer target this CPU, see
  7019. * ttwu_queue_cond() and is_cpu_allowed().
  7020. *
  7021. * Do sync before park smpboot threads to take care the RCU boost case.
  7022. */
  7023. synchronize_rcu();
  7024. sched_set_rq_offline(rq, cpu);
  7025. scx_rq_deactivate(rq);
  7026. /*
  7027. * When going down, decrement the number of cores with SMT present.
  7028. */
  7029. sched_smt_present_dec(cpu);
  7030. #ifdef CONFIG_SCHED_SMT
  7031. sched_core_cpu_deactivate(cpu);
  7032. #endif
  7033. if (!sched_smp_initialized)
  7034. return 0;
  7035. sched_update_numa(cpu, false);
  7036. ret = cpuset_cpu_inactive(cpu);
  7037. if (ret) {
  7038. sched_smt_present_inc(cpu);
  7039. sched_set_rq_online(rq, cpu);
  7040. balance_push_set(cpu, false);
  7041. set_cpu_active(cpu, true);
  7042. sched_update_numa(cpu, true);
  7043. return ret;
  7044. }
  7045. sched_domains_numa_masks_clear(cpu);
  7046. return 0;
  7047. }
  7048. static void sched_rq_cpu_starting(unsigned int cpu)
  7049. {
  7050. struct rq *rq = cpu_rq(cpu);
  7051. rq->calc_load_update = calc_load_update;
  7052. update_max_interval();
  7053. }
  7054. int sched_cpu_starting(unsigned int cpu)
  7055. {
  7056. sched_core_cpu_starting(cpu);
  7057. sched_rq_cpu_starting(cpu);
  7058. sched_tick_start(cpu);
  7059. return 0;
  7060. }
  7061. #ifdef CONFIG_HOTPLUG_CPU
  7062. /*
  7063. * Invoked immediately before the stopper thread is invoked to bring the
  7064. * CPU down completely. At this point all per CPU kthreads except the
  7065. * hotplug thread (current) and the stopper thread (inactive) have been
  7066. * either parked or have been unbound from the outgoing CPU. Ensure that
  7067. * any of those which might be on the way out are gone.
  7068. *
  7069. * If after this point a bound task is being woken on this CPU then the
  7070. * responsible hotplug callback has failed to do it's job.
  7071. * sched_cpu_dying() will catch it with the appropriate fireworks.
  7072. */
  7073. int sched_cpu_wait_empty(unsigned int cpu)
  7074. {
  7075. balance_hotplug_wait();
  7076. return 0;
  7077. }
  7078. /*
  7079. * Since this CPU is going 'away' for a while, fold any nr_active delta we
  7080. * might have. Called from the CPU stopper task after ensuring that the
  7081. * stopper is the last running task on the CPU, so nr_active count is
  7082. * stable. We need to take the tear-down thread which is calling this into
  7083. * account, so we hand in adjust = 1 to the load calculation.
  7084. *
  7085. * Also see the comment "Global load-average calculations".
  7086. */
  7087. static void calc_load_migrate(struct rq *rq)
  7088. {
  7089. long delta = calc_load_fold_active(rq, 1);
  7090. if (delta)
  7091. atomic_long_add(delta, &calc_load_tasks);
  7092. }
  7093. static void dump_rq_tasks(struct rq *rq, const char *loglvl)
  7094. {
  7095. struct task_struct *g, *p;
  7096. int cpu = cpu_of(rq);
  7097. lockdep_assert_rq_held(rq);
  7098. printk("%sCPU%d enqueued tasks (%u total):\n", loglvl, cpu, rq->nr_running);
  7099. for_each_process_thread(g, p) {
  7100. if (task_cpu(p) != cpu)
  7101. continue;
  7102. if (!task_on_rq_queued(p))
  7103. continue;
  7104. printk("%s\tpid: %d, name: %s\n", loglvl, p->pid, p->comm);
  7105. }
  7106. }
  7107. int sched_cpu_dying(unsigned int cpu)
  7108. {
  7109. struct rq *rq = cpu_rq(cpu);
  7110. struct rq_flags rf;
  7111. /* Handle pending wakeups and then migrate everything off */
  7112. sched_tick_stop(cpu);
  7113. rq_lock_irqsave(rq, &rf);
  7114. if (rq->nr_running != 1 || rq_has_pinned_tasks(rq)) {
  7115. WARN(true, "Dying CPU not properly vacated!");
  7116. dump_rq_tasks(rq, KERN_WARNING);
  7117. }
  7118. rq_unlock_irqrestore(rq, &rf);
  7119. calc_load_migrate(rq);
  7120. update_max_interval();
  7121. hrtick_clear(rq);
  7122. sched_core_cpu_dying(cpu);
  7123. return 0;
  7124. }
  7125. #endif
  7126. void __init sched_init_smp(void)
  7127. {
  7128. sched_init_numa(NUMA_NO_NODE);
  7129. /*
  7130. * There's no userspace yet to cause hotplug operations; hence all the
  7131. * CPU masks are stable and all blatant races in the below code cannot
  7132. * happen.
  7133. */
  7134. mutex_lock(&sched_domains_mutex);
  7135. sched_init_domains(cpu_active_mask);
  7136. mutex_unlock(&sched_domains_mutex);
  7137. /* Move init over to a non-isolated CPU */
  7138. if (set_cpus_allowed_ptr(current, housekeeping_cpumask(HK_TYPE_DOMAIN)) < 0)
  7139. BUG();
  7140. current->flags &= ~PF_NO_SETAFFINITY;
  7141. sched_init_granularity();
  7142. init_sched_rt_class();
  7143. init_sched_dl_class();
  7144. sched_smp_initialized = true;
  7145. }
  7146. static int __init migration_init(void)
  7147. {
  7148. sched_cpu_starting(smp_processor_id());
  7149. return 0;
  7150. }
  7151. early_initcall(migration_init);
  7152. #else
  7153. void __init sched_init_smp(void)
  7154. {
  7155. sched_init_granularity();
  7156. }
  7157. #endif /* CONFIG_SMP */
  7158. int in_sched_functions(unsigned long addr)
  7159. {
  7160. return in_lock_functions(addr) ||
  7161. (addr >= (unsigned long)__sched_text_start
  7162. && addr < (unsigned long)__sched_text_end);
  7163. }
  7164. #ifdef CONFIG_CGROUP_SCHED
  7165. /*
  7166. * Default task group.
  7167. * Every task in system belongs to this group at bootup.
  7168. */
  7169. struct task_group root_task_group;
  7170. LIST_HEAD(task_groups);
  7171. /* Cacheline aligned slab cache for task_group */
  7172. static struct kmem_cache *task_group_cache __ro_after_init;
  7173. #endif
  7174. void __init sched_init(void)
  7175. {
  7176. unsigned long ptr = 0;
  7177. int i;
  7178. /* Make sure the linker didn't screw up */
  7179. #ifdef CONFIG_SMP
  7180. BUG_ON(!sched_class_above(&stop_sched_class, &dl_sched_class));
  7181. #endif
  7182. BUG_ON(!sched_class_above(&dl_sched_class, &rt_sched_class));
  7183. BUG_ON(!sched_class_above(&rt_sched_class, &fair_sched_class));
  7184. BUG_ON(!sched_class_above(&fair_sched_class, &idle_sched_class));
  7185. #ifdef CONFIG_SCHED_CLASS_EXT
  7186. BUG_ON(!sched_class_above(&fair_sched_class, &ext_sched_class));
  7187. BUG_ON(!sched_class_above(&ext_sched_class, &idle_sched_class));
  7188. #endif
  7189. wait_bit_init();
  7190. #ifdef CONFIG_FAIR_GROUP_SCHED
  7191. ptr += 2 * nr_cpu_ids * sizeof(void **);
  7192. #endif
  7193. #ifdef CONFIG_RT_GROUP_SCHED
  7194. ptr += 2 * nr_cpu_ids * sizeof(void **);
  7195. #endif
  7196. if (ptr) {
  7197. ptr = (unsigned long)kzalloc(ptr, GFP_NOWAIT);
  7198. #ifdef CONFIG_FAIR_GROUP_SCHED
  7199. root_task_group.se = (struct sched_entity **)ptr;
  7200. ptr += nr_cpu_ids * sizeof(void **);
  7201. root_task_group.cfs_rq = (struct cfs_rq **)ptr;
  7202. ptr += nr_cpu_ids * sizeof(void **);
  7203. root_task_group.shares = ROOT_TASK_GROUP_LOAD;
  7204. init_cfs_bandwidth(&root_task_group.cfs_bandwidth, NULL);
  7205. #endif /* CONFIG_FAIR_GROUP_SCHED */
  7206. #ifdef CONFIG_EXT_GROUP_SCHED
  7207. scx_tg_init(&root_task_group);
  7208. #endif /* CONFIG_EXT_GROUP_SCHED */
  7209. #ifdef CONFIG_RT_GROUP_SCHED
  7210. root_task_group.rt_se = (struct sched_rt_entity **)ptr;
  7211. ptr += nr_cpu_ids * sizeof(void **);
  7212. root_task_group.rt_rq = (struct rt_rq **)ptr;
  7213. ptr += nr_cpu_ids * sizeof(void **);
  7214. #endif /* CONFIG_RT_GROUP_SCHED */
  7215. }
  7216. #ifdef CONFIG_SMP
  7217. init_defrootdomain();
  7218. #endif
  7219. #ifdef CONFIG_RT_GROUP_SCHED
  7220. init_rt_bandwidth(&root_task_group.rt_bandwidth,
  7221. global_rt_period(), global_rt_runtime());
  7222. #endif /* CONFIG_RT_GROUP_SCHED */
  7223. #ifdef CONFIG_CGROUP_SCHED
  7224. task_group_cache = KMEM_CACHE(task_group, 0);
  7225. list_add(&root_task_group.list, &task_groups);
  7226. INIT_LIST_HEAD(&root_task_group.children);
  7227. INIT_LIST_HEAD(&root_task_group.siblings);
  7228. autogroup_init(&init_task);
  7229. #endif /* CONFIG_CGROUP_SCHED */
  7230. for_each_possible_cpu(i) {
  7231. struct rq *rq;
  7232. rq = cpu_rq(i);
  7233. raw_spin_lock_init(&rq->__lock);
  7234. rq->nr_running = 0;
  7235. rq->calc_load_active = 0;
  7236. rq->calc_load_update = jiffies + LOAD_FREQ;
  7237. init_cfs_rq(&rq->cfs);
  7238. init_rt_rq(&rq->rt);
  7239. init_dl_rq(&rq->dl);
  7240. #ifdef CONFIG_FAIR_GROUP_SCHED
  7241. INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
  7242. rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
  7243. /*
  7244. * How much CPU bandwidth does root_task_group get?
  7245. *
  7246. * In case of task-groups formed through the cgroup filesystem, it
  7247. * gets 100% of the CPU resources in the system. This overall
  7248. * system CPU resource is divided among the tasks of
  7249. * root_task_group and its child task-groups in a fair manner,
  7250. * based on each entity's (task or task-group's) weight
  7251. * (se->load.weight).
  7252. *
  7253. * In other words, if root_task_group has 10 tasks of weight
  7254. * 1024) and two child groups A0 and A1 (of weight 1024 each),
  7255. * then A0's share of the CPU resource is:
  7256. *
  7257. * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
  7258. *
  7259. * We achieve this by letting root_task_group's tasks sit
  7260. * directly in rq->cfs (i.e root_task_group->se[] = NULL).
  7261. */
  7262. init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL);
  7263. #endif /* CONFIG_FAIR_GROUP_SCHED */
  7264. #ifdef CONFIG_RT_GROUP_SCHED
  7265. /*
  7266. * This is required for init cpu because rt.c:__enable_runtime()
  7267. * starts working after scheduler_running, which is not the case
  7268. * yet.
  7269. */
  7270. rq->rt.rt_runtime = global_rt_runtime();
  7271. init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL);
  7272. #endif
  7273. #ifdef CONFIG_SMP
  7274. rq->sd = NULL;
  7275. rq->rd = NULL;
  7276. rq->cpu_capacity = SCHED_CAPACITY_SCALE;
  7277. rq->balance_callback = &balance_push_callback;
  7278. rq->active_balance = 0;
  7279. rq->next_balance = jiffies;
  7280. rq->push_cpu = 0;
  7281. rq->cpu = i;
  7282. rq->online = 0;
  7283. rq->idle_stamp = 0;
  7284. rq->avg_idle = 2*sysctl_sched_migration_cost;
  7285. rq->max_idle_balance_cost = sysctl_sched_migration_cost;
  7286. INIT_LIST_HEAD(&rq->cfs_tasks);
  7287. rq_attach_root(rq, &def_root_domain);
  7288. #ifdef CONFIG_NO_HZ_COMMON
  7289. rq->last_blocked_load_update_tick = jiffies;
  7290. atomic_set(&rq->nohz_flags, 0);
  7291. INIT_CSD(&rq->nohz_csd, nohz_csd_func, rq);
  7292. #endif
  7293. #ifdef CONFIG_HOTPLUG_CPU
  7294. rcuwait_init(&rq->hotplug_wait);
  7295. #endif
  7296. #endif /* CONFIG_SMP */
  7297. hrtick_rq_init(rq);
  7298. atomic_set(&rq->nr_iowait, 0);
  7299. fair_server_init(rq);
  7300. #ifdef CONFIG_SCHED_CORE
  7301. rq->core = rq;
  7302. rq->core_pick = NULL;
  7303. rq->core_dl_server = NULL;
  7304. rq->core_enabled = 0;
  7305. rq->core_tree = RB_ROOT;
  7306. rq->core_forceidle_count = 0;
  7307. rq->core_forceidle_occupation = 0;
  7308. rq->core_forceidle_start = 0;
  7309. rq->core_cookie = 0UL;
  7310. #endif
  7311. zalloc_cpumask_var_node(&rq->scratch_mask, GFP_KERNEL, cpu_to_node(i));
  7312. }
  7313. set_load_weight(&init_task, false);
  7314. init_task.se.slice = sysctl_sched_base_slice,
  7315. /*
  7316. * The boot idle thread does lazy MMU switching as well:
  7317. */
  7318. mmgrab_lazy_tlb(&init_mm);
  7319. enter_lazy_tlb(&init_mm, current);
  7320. /*
  7321. * The idle task doesn't need the kthread struct to function, but it
  7322. * is dressed up as a per-CPU kthread and thus needs to play the part
  7323. * if we want to avoid special-casing it in code that deals with per-CPU
  7324. * kthreads.
  7325. */
  7326. WARN_ON(!set_kthread_struct(current));
  7327. /*
  7328. * Make us the idle thread. Technically, schedule() should not be
  7329. * called from this thread, however somewhere below it might be,
  7330. * but because we are the idle thread, we just pick up running again
  7331. * when this runqueue becomes "idle".
  7332. */
  7333. __sched_fork(0, current);
  7334. init_idle(current, smp_processor_id());
  7335. calc_load_update = jiffies + LOAD_FREQ;
  7336. #ifdef CONFIG_SMP
  7337. idle_thread_set_boot_cpu();
  7338. balance_push_set(smp_processor_id(), false);
  7339. #endif
  7340. init_sched_fair_class();
  7341. init_sched_ext_class();
  7342. psi_init();
  7343. init_uclamp();
  7344. preempt_dynamic_init();
  7345. scheduler_running = 1;
  7346. }
  7347. #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
  7348. void __might_sleep(const char *file, int line)
  7349. {
  7350. unsigned int state = get_current_state();
  7351. /*
  7352. * Blocking primitives will set (and therefore destroy) current->state,
  7353. * since we will exit with TASK_RUNNING make sure we enter with it,
  7354. * otherwise we will destroy state.
  7355. */
  7356. WARN_ONCE(state != TASK_RUNNING && current->task_state_change,
  7357. "do not call blocking ops when !TASK_RUNNING; "
  7358. "state=%x set at [<%p>] %pS\n", state,
  7359. (void *)current->task_state_change,
  7360. (void *)current->task_state_change);
  7361. __might_resched(file, line, 0);
  7362. }
  7363. EXPORT_SYMBOL(__might_sleep);
  7364. static void print_preempt_disable_ip(int preempt_offset, unsigned long ip)
  7365. {
  7366. if (!IS_ENABLED(CONFIG_DEBUG_PREEMPT))
  7367. return;
  7368. if (preempt_count() == preempt_offset)
  7369. return;
  7370. pr_err("Preemption disabled at:");
  7371. print_ip_sym(KERN_ERR, ip);
  7372. }
  7373. static inline bool resched_offsets_ok(unsigned int offsets)
  7374. {
  7375. unsigned int nested = preempt_count();
  7376. nested += rcu_preempt_depth() << MIGHT_RESCHED_RCU_SHIFT;
  7377. return nested == offsets;
  7378. }
  7379. void __might_resched(const char *file, int line, unsigned int offsets)
  7380. {
  7381. /* Ratelimiting timestamp: */
  7382. static unsigned long prev_jiffy;
  7383. unsigned long preempt_disable_ip;
  7384. /* WARN_ON_ONCE() by default, no rate limit required: */
  7385. rcu_sleep_check();
  7386. if ((resched_offsets_ok(offsets) && !irqs_disabled() &&
  7387. !is_idle_task(current) && !current->non_block_count) ||
  7388. system_state == SYSTEM_BOOTING || system_state > SYSTEM_RUNNING ||
  7389. oops_in_progress)
  7390. return;
  7391. if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
  7392. return;
  7393. prev_jiffy = jiffies;
  7394. /* Save this before calling printk(), since that will clobber it: */
  7395. preempt_disable_ip = get_preempt_disable_ip(current);
  7396. pr_err("BUG: sleeping function called from invalid context at %s:%d\n",
  7397. file, line);
  7398. pr_err("in_atomic(): %d, irqs_disabled(): %d, non_block: %d, pid: %d, name: %s\n",
  7399. in_atomic(), irqs_disabled(), current->non_block_count,
  7400. current->pid, current->comm);
  7401. pr_err("preempt_count: %x, expected: %x\n", preempt_count(),
  7402. offsets & MIGHT_RESCHED_PREEMPT_MASK);
  7403. if (IS_ENABLED(CONFIG_PREEMPT_RCU)) {
  7404. pr_err("RCU nest depth: %d, expected: %u\n",
  7405. rcu_preempt_depth(), offsets >> MIGHT_RESCHED_RCU_SHIFT);
  7406. }
  7407. if (task_stack_end_corrupted(current))
  7408. pr_emerg("Thread overran stack, or stack corrupted\n");
  7409. debug_show_held_locks(current);
  7410. if (irqs_disabled())
  7411. print_irqtrace_events(current);
  7412. print_preempt_disable_ip(offsets & MIGHT_RESCHED_PREEMPT_MASK,
  7413. preempt_disable_ip);
  7414. dump_stack();
  7415. add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
  7416. }
  7417. EXPORT_SYMBOL(__might_resched);
  7418. void __cant_sleep(const char *file, int line, int preempt_offset)
  7419. {
  7420. static unsigned long prev_jiffy;
  7421. if (irqs_disabled())
  7422. return;
  7423. if (!IS_ENABLED(CONFIG_PREEMPT_COUNT))
  7424. return;
  7425. if (preempt_count() > preempt_offset)
  7426. return;
  7427. if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
  7428. return;
  7429. prev_jiffy = jiffies;
  7430. printk(KERN_ERR "BUG: assuming atomic context at %s:%d\n", file, line);
  7431. printk(KERN_ERR "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
  7432. in_atomic(), irqs_disabled(),
  7433. current->pid, current->comm);
  7434. debug_show_held_locks(current);
  7435. dump_stack();
  7436. add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
  7437. }
  7438. EXPORT_SYMBOL_GPL(__cant_sleep);
  7439. #ifdef CONFIG_SMP
  7440. void __cant_migrate(const char *file, int line)
  7441. {
  7442. static unsigned long prev_jiffy;
  7443. if (irqs_disabled())
  7444. return;
  7445. if (is_migration_disabled(current))
  7446. return;
  7447. if (!IS_ENABLED(CONFIG_PREEMPT_COUNT))
  7448. return;
  7449. if (preempt_count() > 0)
  7450. return;
  7451. if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
  7452. return;
  7453. prev_jiffy = jiffies;
  7454. pr_err("BUG: assuming non migratable context at %s:%d\n", file, line);
  7455. pr_err("in_atomic(): %d, irqs_disabled(): %d, migration_disabled() %u pid: %d, name: %s\n",
  7456. in_atomic(), irqs_disabled(), is_migration_disabled(current),
  7457. current->pid, current->comm);
  7458. debug_show_held_locks(current);
  7459. dump_stack();
  7460. add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
  7461. }
  7462. EXPORT_SYMBOL_GPL(__cant_migrate);
  7463. #endif
  7464. #endif
  7465. #ifdef CONFIG_MAGIC_SYSRQ
  7466. void normalize_rt_tasks(void)
  7467. {
  7468. struct task_struct *g, *p;
  7469. struct sched_attr attr = {
  7470. .sched_policy = SCHED_NORMAL,
  7471. };
  7472. read_lock(&tasklist_lock);
  7473. for_each_process_thread(g, p) {
  7474. /*
  7475. * Only normalize user tasks:
  7476. */
  7477. if (p->flags & PF_KTHREAD)
  7478. continue;
  7479. p->se.exec_start = 0;
  7480. schedstat_set(p->stats.wait_start, 0);
  7481. schedstat_set(p->stats.sleep_start, 0);
  7482. schedstat_set(p->stats.block_start, 0);
  7483. if (!rt_or_dl_task(p)) {
  7484. /*
  7485. * Renice negative nice level userspace
  7486. * tasks back to 0:
  7487. */
  7488. if (task_nice(p) < 0)
  7489. set_user_nice(p, 0);
  7490. continue;
  7491. }
  7492. __sched_setscheduler(p, &attr, false, false);
  7493. }
  7494. read_unlock(&tasklist_lock);
  7495. }
  7496. #endif /* CONFIG_MAGIC_SYSRQ */
  7497. #if defined(CONFIG_KGDB_KDB)
  7498. /*
  7499. * These functions are only useful for KDB.
  7500. *
  7501. * They can only be called when the whole system has been
  7502. * stopped - every CPU needs to be quiescent, and no scheduling
  7503. * activity can take place. Using them for anything else would
  7504. * be a serious bug, and as a result, they aren't even visible
  7505. * under any other configuration.
  7506. */
  7507. /**
  7508. * curr_task - return the current task for a given CPU.
  7509. * @cpu: the processor in question.
  7510. *
  7511. * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
  7512. *
  7513. * Return: The current task for @cpu.
  7514. */
  7515. struct task_struct *curr_task(int cpu)
  7516. {
  7517. return cpu_curr(cpu);
  7518. }
  7519. #endif /* defined(CONFIG_KGDB_KDB) */
  7520. #ifdef CONFIG_CGROUP_SCHED
  7521. /* task_group_lock serializes the addition/removal of task groups */
  7522. static DEFINE_SPINLOCK(task_group_lock);
  7523. static inline void alloc_uclamp_sched_group(struct task_group *tg,
  7524. struct task_group *parent)
  7525. {
  7526. #ifdef CONFIG_UCLAMP_TASK_GROUP
  7527. enum uclamp_id clamp_id;
  7528. for_each_clamp_id(clamp_id) {
  7529. uclamp_se_set(&tg->uclamp_req[clamp_id],
  7530. uclamp_none(clamp_id), false);
  7531. tg->uclamp[clamp_id] = parent->uclamp[clamp_id];
  7532. }
  7533. #endif
  7534. }
  7535. static void sched_free_group(struct task_group *tg)
  7536. {
  7537. free_fair_sched_group(tg);
  7538. free_rt_sched_group(tg);
  7539. autogroup_free(tg);
  7540. kmem_cache_free(task_group_cache, tg);
  7541. }
  7542. static void sched_free_group_rcu(struct rcu_head *rcu)
  7543. {
  7544. sched_free_group(container_of(rcu, struct task_group, rcu));
  7545. }
  7546. static void sched_unregister_group(struct task_group *tg)
  7547. {
  7548. unregister_fair_sched_group(tg);
  7549. unregister_rt_sched_group(tg);
  7550. /*
  7551. * We have to wait for yet another RCU grace period to expire, as
  7552. * print_cfs_stats() might run concurrently.
  7553. */
  7554. call_rcu(&tg->rcu, sched_free_group_rcu);
  7555. }
  7556. /* allocate runqueue etc for a new task group */
  7557. struct task_group *sched_create_group(struct task_group *parent)
  7558. {
  7559. struct task_group *tg;
  7560. tg = kmem_cache_alloc(task_group_cache, GFP_KERNEL | __GFP_ZERO);
  7561. if (!tg)
  7562. return ERR_PTR(-ENOMEM);
  7563. if (!alloc_fair_sched_group(tg, parent))
  7564. goto err;
  7565. if (!alloc_rt_sched_group(tg, parent))
  7566. goto err;
  7567. scx_tg_init(tg);
  7568. alloc_uclamp_sched_group(tg, parent);
  7569. return tg;
  7570. err:
  7571. sched_free_group(tg);
  7572. return ERR_PTR(-ENOMEM);
  7573. }
  7574. void sched_online_group(struct task_group *tg, struct task_group *parent)
  7575. {
  7576. unsigned long flags;
  7577. spin_lock_irqsave(&task_group_lock, flags);
  7578. list_add_rcu(&tg->list, &task_groups);
  7579. /* Root should already exist: */
  7580. WARN_ON(!parent);
  7581. tg->parent = parent;
  7582. INIT_LIST_HEAD(&tg->children);
  7583. list_add_rcu(&tg->siblings, &parent->children);
  7584. spin_unlock_irqrestore(&task_group_lock, flags);
  7585. online_fair_sched_group(tg);
  7586. }
  7587. /* RCU callback to free various structures associated with a task group */
  7588. static void sched_unregister_group_rcu(struct rcu_head *rhp)
  7589. {
  7590. /* Now it should be safe to free those cfs_rqs: */
  7591. sched_unregister_group(container_of(rhp, struct task_group, rcu));
  7592. }
  7593. void sched_destroy_group(struct task_group *tg)
  7594. {
  7595. /* Wait for possible concurrent references to cfs_rqs complete: */
  7596. call_rcu(&tg->rcu, sched_unregister_group_rcu);
  7597. }
  7598. void sched_release_group(struct task_group *tg)
  7599. {
  7600. unsigned long flags;
  7601. /*
  7602. * Unlink first, to avoid walk_tg_tree_from() from finding us (via
  7603. * sched_cfs_period_timer()).
  7604. *
  7605. * For this to be effective, we have to wait for all pending users of
  7606. * this task group to leave their RCU critical section to ensure no new
  7607. * user will see our dying task group any more. Specifically ensure
  7608. * that tg_unthrottle_up() won't add decayed cfs_rq's to it.
  7609. *
  7610. * We therefore defer calling unregister_fair_sched_group() to
  7611. * sched_unregister_group() which is guarantied to get called only after the
  7612. * current RCU grace period has expired.
  7613. */
  7614. spin_lock_irqsave(&task_group_lock, flags);
  7615. list_del_rcu(&tg->list);
  7616. list_del_rcu(&tg->siblings);
  7617. spin_unlock_irqrestore(&task_group_lock, flags);
  7618. }
  7619. static void sched_change_group(struct task_struct *tsk)
  7620. {
  7621. struct task_group *tg;
  7622. /*
  7623. * All callers are synchronized by task_rq_lock(); we do not use RCU
  7624. * which is pointless here. Thus, we pass "true" to task_css_check()
  7625. * to prevent lockdep warnings.
  7626. */
  7627. tg = container_of(task_css_check(tsk, cpu_cgrp_id, true),
  7628. struct task_group, css);
  7629. tg = autogroup_task_group(tsk, tg);
  7630. tsk->sched_task_group = tg;
  7631. #ifdef CONFIG_FAIR_GROUP_SCHED
  7632. if (tsk->sched_class->task_change_group)
  7633. tsk->sched_class->task_change_group(tsk);
  7634. else
  7635. #endif
  7636. set_task_rq(tsk, task_cpu(tsk));
  7637. }
  7638. /*
  7639. * Change task's runqueue when it moves between groups.
  7640. *
  7641. * The caller of this function should have put the task in its new group by
  7642. * now. This function just updates tsk->se.cfs_rq and tsk->se.parent to reflect
  7643. * its new group.
  7644. */
  7645. void sched_move_task(struct task_struct *tsk, bool for_autogroup)
  7646. {
  7647. int queued, running, queue_flags =
  7648. DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
  7649. struct rq *rq;
  7650. CLASS(task_rq_lock, rq_guard)(tsk);
  7651. rq = rq_guard.rq;
  7652. update_rq_clock(rq);
  7653. running = task_current(rq, tsk);
  7654. queued = task_on_rq_queued(tsk);
  7655. if (queued)
  7656. dequeue_task(rq, tsk, queue_flags);
  7657. if (running)
  7658. put_prev_task(rq, tsk);
  7659. sched_change_group(tsk);
  7660. if (!for_autogroup)
  7661. scx_cgroup_move_task(tsk);
  7662. if (queued)
  7663. enqueue_task(rq, tsk, queue_flags);
  7664. if (running) {
  7665. set_next_task(rq, tsk);
  7666. /*
  7667. * After changing group, the running task may have joined a
  7668. * throttled one but it's still the running task. Trigger a
  7669. * resched to make sure that task can still run.
  7670. */
  7671. resched_curr(rq);
  7672. }
  7673. }
  7674. static struct cgroup_subsys_state *
  7675. cpu_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
  7676. {
  7677. struct task_group *parent = css_tg(parent_css);
  7678. struct task_group *tg;
  7679. if (!parent) {
  7680. /* This is early initialization for the top cgroup */
  7681. return &root_task_group.css;
  7682. }
  7683. tg = sched_create_group(parent);
  7684. if (IS_ERR(tg))
  7685. return ERR_PTR(-ENOMEM);
  7686. return &tg->css;
  7687. }
  7688. /* Expose task group only after completing cgroup initialization */
  7689. static int cpu_cgroup_css_online(struct cgroup_subsys_state *css)
  7690. {
  7691. struct task_group *tg = css_tg(css);
  7692. struct task_group *parent = css_tg(css->parent);
  7693. int ret;
  7694. ret = scx_tg_online(tg);
  7695. if (ret)
  7696. return ret;
  7697. if (parent)
  7698. sched_online_group(tg, parent);
  7699. #ifdef CONFIG_UCLAMP_TASK_GROUP
  7700. /* Propagate the effective uclamp value for the new group */
  7701. guard(mutex)(&uclamp_mutex);
  7702. guard(rcu)();
  7703. cpu_util_update_eff(css);
  7704. #endif
  7705. return 0;
  7706. }
  7707. static void cpu_cgroup_css_offline(struct cgroup_subsys_state *css)
  7708. {
  7709. struct task_group *tg = css_tg(css);
  7710. scx_tg_offline(tg);
  7711. }
  7712. static void cpu_cgroup_css_released(struct cgroup_subsys_state *css)
  7713. {
  7714. struct task_group *tg = css_tg(css);
  7715. sched_release_group(tg);
  7716. }
  7717. static void cpu_cgroup_css_free(struct cgroup_subsys_state *css)
  7718. {
  7719. struct task_group *tg = css_tg(css);
  7720. /*
  7721. * Relies on the RCU grace period between css_released() and this.
  7722. */
  7723. sched_unregister_group(tg);
  7724. }
  7725. static int cpu_cgroup_can_attach(struct cgroup_taskset *tset)
  7726. {
  7727. #ifdef CONFIG_RT_GROUP_SCHED
  7728. struct task_struct *task;
  7729. struct cgroup_subsys_state *css;
  7730. cgroup_taskset_for_each(task, css, tset) {
  7731. if (!sched_rt_can_attach(css_tg(css), task))
  7732. return -EINVAL;
  7733. }
  7734. #endif
  7735. return scx_cgroup_can_attach(tset);
  7736. }
  7737. static void cpu_cgroup_attach(struct cgroup_taskset *tset)
  7738. {
  7739. struct task_struct *task;
  7740. struct cgroup_subsys_state *css;
  7741. cgroup_taskset_for_each(task, css, tset)
  7742. sched_move_task(task, false);
  7743. scx_cgroup_finish_attach();
  7744. }
  7745. static void cpu_cgroup_cancel_attach(struct cgroup_taskset *tset)
  7746. {
  7747. scx_cgroup_cancel_attach(tset);
  7748. }
  7749. #ifdef CONFIG_UCLAMP_TASK_GROUP
  7750. static void cpu_util_update_eff(struct cgroup_subsys_state *css)
  7751. {
  7752. struct cgroup_subsys_state *top_css = css;
  7753. struct uclamp_se *uc_parent = NULL;
  7754. struct uclamp_se *uc_se = NULL;
  7755. unsigned int eff[UCLAMP_CNT];
  7756. enum uclamp_id clamp_id;
  7757. unsigned int clamps;
  7758. lockdep_assert_held(&uclamp_mutex);
  7759. SCHED_WARN_ON(!rcu_read_lock_held());
  7760. css_for_each_descendant_pre(css, top_css) {
  7761. uc_parent = css_tg(css)->parent
  7762. ? css_tg(css)->parent->uclamp : NULL;
  7763. for_each_clamp_id(clamp_id) {
  7764. /* Assume effective clamps matches requested clamps */
  7765. eff[clamp_id] = css_tg(css)->uclamp_req[clamp_id].value;
  7766. /* Cap effective clamps with parent's effective clamps */
  7767. if (uc_parent &&
  7768. eff[clamp_id] > uc_parent[clamp_id].value) {
  7769. eff[clamp_id] = uc_parent[clamp_id].value;
  7770. }
  7771. }
  7772. /* Ensure protection is always capped by limit */
  7773. eff[UCLAMP_MIN] = min(eff[UCLAMP_MIN], eff[UCLAMP_MAX]);
  7774. /* Propagate most restrictive effective clamps */
  7775. clamps = 0x0;
  7776. uc_se = css_tg(css)->uclamp;
  7777. for_each_clamp_id(clamp_id) {
  7778. if (eff[clamp_id] == uc_se[clamp_id].value)
  7779. continue;
  7780. uc_se[clamp_id].value = eff[clamp_id];
  7781. uc_se[clamp_id].bucket_id = uclamp_bucket_id(eff[clamp_id]);
  7782. clamps |= (0x1 << clamp_id);
  7783. }
  7784. if (!clamps) {
  7785. css = css_rightmost_descendant(css);
  7786. continue;
  7787. }
  7788. /* Immediately update descendants RUNNABLE tasks */
  7789. uclamp_update_active_tasks(css);
  7790. }
  7791. }
  7792. /*
  7793. * Integer 10^N with a given N exponent by casting to integer the literal "1eN"
  7794. * C expression. Since there is no way to convert a macro argument (N) into a
  7795. * character constant, use two levels of macros.
  7796. */
  7797. #define _POW10(exp) ((unsigned int)1e##exp)
  7798. #define POW10(exp) _POW10(exp)
  7799. struct uclamp_request {
  7800. #define UCLAMP_PERCENT_SHIFT 2
  7801. #define UCLAMP_PERCENT_SCALE (100 * POW10(UCLAMP_PERCENT_SHIFT))
  7802. s64 percent;
  7803. u64 util;
  7804. int ret;
  7805. };
  7806. static inline struct uclamp_request
  7807. capacity_from_percent(char *buf)
  7808. {
  7809. struct uclamp_request req = {
  7810. .percent = UCLAMP_PERCENT_SCALE,
  7811. .util = SCHED_CAPACITY_SCALE,
  7812. .ret = 0,
  7813. };
  7814. buf = strim(buf);
  7815. if (strcmp(buf, "max")) {
  7816. req.ret = cgroup_parse_float(buf, UCLAMP_PERCENT_SHIFT,
  7817. &req.percent);
  7818. if (req.ret)
  7819. return req;
  7820. if ((u64)req.percent > UCLAMP_PERCENT_SCALE) {
  7821. req.ret = -ERANGE;
  7822. return req;
  7823. }
  7824. req.util = req.percent << SCHED_CAPACITY_SHIFT;
  7825. req.util = DIV_ROUND_CLOSEST_ULL(req.util, UCLAMP_PERCENT_SCALE);
  7826. }
  7827. return req;
  7828. }
  7829. static ssize_t cpu_uclamp_write(struct kernfs_open_file *of, char *buf,
  7830. size_t nbytes, loff_t off,
  7831. enum uclamp_id clamp_id)
  7832. {
  7833. struct uclamp_request req;
  7834. struct task_group *tg;
  7835. req = capacity_from_percent(buf);
  7836. if (req.ret)
  7837. return req.ret;
  7838. static_branch_enable(&sched_uclamp_used);
  7839. guard(mutex)(&uclamp_mutex);
  7840. guard(rcu)();
  7841. tg = css_tg(of_css(of));
  7842. if (tg->uclamp_req[clamp_id].value != req.util)
  7843. uclamp_se_set(&tg->uclamp_req[clamp_id], req.util, false);
  7844. /*
  7845. * Because of not recoverable conversion rounding we keep track of the
  7846. * exact requested value
  7847. */
  7848. tg->uclamp_pct[clamp_id] = req.percent;
  7849. /* Update effective clamps to track the most restrictive value */
  7850. cpu_util_update_eff(of_css(of));
  7851. return nbytes;
  7852. }
  7853. static ssize_t cpu_uclamp_min_write(struct kernfs_open_file *of,
  7854. char *buf, size_t nbytes,
  7855. loff_t off)
  7856. {
  7857. return cpu_uclamp_write(of, buf, nbytes, off, UCLAMP_MIN);
  7858. }
  7859. static ssize_t cpu_uclamp_max_write(struct kernfs_open_file *of,
  7860. char *buf, size_t nbytes,
  7861. loff_t off)
  7862. {
  7863. return cpu_uclamp_write(of, buf, nbytes, off, UCLAMP_MAX);
  7864. }
  7865. static inline void cpu_uclamp_print(struct seq_file *sf,
  7866. enum uclamp_id clamp_id)
  7867. {
  7868. struct task_group *tg;
  7869. u64 util_clamp;
  7870. u64 percent;
  7871. u32 rem;
  7872. scoped_guard (rcu) {
  7873. tg = css_tg(seq_css(sf));
  7874. util_clamp = tg->uclamp_req[clamp_id].value;
  7875. }
  7876. if (util_clamp == SCHED_CAPACITY_SCALE) {
  7877. seq_puts(sf, "max\n");
  7878. return;
  7879. }
  7880. percent = tg->uclamp_pct[clamp_id];
  7881. percent = div_u64_rem(percent, POW10(UCLAMP_PERCENT_SHIFT), &rem);
  7882. seq_printf(sf, "%llu.%0*u\n", percent, UCLAMP_PERCENT_SHIFT, rem);
  7883. }
  7884. static int cpu_uclamp_min_show(struct seq_file *sf, void *v)
  7885. {
  7886. cpu_uclamp_print(sf, UCLAMP_MIN);
  7887. return 0;
  7888. }
  7889. static int cpu_uclamp_max_show(struct seq_file *sf, void *v)
  7890. {
  7891. cpu_uclamp_print(sf, UCLAMP_MAX);
  7892. return 0;
  7893. }
  7894. #endif /* CONFIG_UCLAMP_TASK_GROUP */
  7895. #ifdef CONFIG_GROUP_SCHED_WEIGHT
  7896. static unsigned long tg_weight(struct task_group *tg)
  7897. {
  7898. #ifdef CONFIG_FAIR_GROUP_SCHED
  7899. return scale_load_down(tg->shares);
  7900. #else
  7901. return sched_weight_from_cgroup(tg->scx_weight);
  7902. #endif
  7903. }
  7904. static int cpu_shares_write_u64(struct cgroup_subsys_state *css,
  7905. struct cftype *cftype, u64 shareval)
  7906. {
  7907. int ret;
  7908. if (shareval > scale_load_down(ULONG_MAX))
  7909. shareval = MAX_SHARES;
  7910. ret = sched_group_set_shares(css_tg(css), scale_load(shareval));
  7911. if (!ret)
  7912. scx_group_set_weight(css_tg(css),
  7913. sched_weight_to_cgroup(shareval));
  7914. return ret;
  7915. }
  7916. static u64 cpu_shares_read_u64(struct cgroup_subsys_state *css,
  7917. struct cftype *cft)
  7918. {
  7919. return tg_weight(css_tg(css));
  7920. }
  7921. #endif /* CONFIG_GROUP_SCHED_WEIGHT */
  7922. #ifdef CONFIG_CFS_BANDWIDTH
  7923. static DEFINE_MUTEX(cfs_constraints_mutex);
  7924. const u64 max_cfs_quota_period = 1 * NSEC_PER_SEC; /* 1s */
  7925. static const u64 min_cfs_quota_period = 1 * NSEC_PER_MSEC; /* 1ms */
  7926. /* More than 203 days if BW_SHIFT equals 20. */
  7927. static const u64 max_cfs_runtime = MAX_BW * NSEC_PER_USEC;
  7928. static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime);
  7929. static int tg_set_cfs_bandwidth(struct task_group *tg, u64 period, u64 quota,
  7930. u64 burst)
  7931. {
  7932. int i, ret = 0, runtime_enabled, runtime_was_enabled;
  7933. struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
  7934. if (tg == &root_task_group)
  7935. return -EINVAL;
  7936. /*
  7937. * Ensure we have at some amount of bandwidth every period. This is
  7938. * to prevent reaching a state of large arrears when throttled via
  7939. * entity_tick() resulting in prolonged exit starvation.
  7940. */
  7941. if (quota < min_cfs_quota_period || period < min_cfs_quota_period)
  7942. return -EINVAL;
  7943. /*
  7944. * Likewise, bound things on the other side by preventing insane quota
  7945. * periods. This also allows us to normalize in computing quota
  7946. * feasibility.
  7947. */
  7948. if (period > max_cfs_quota_period)
  7949. return -EINVAL;
  7950. /*
  7951. * Bound quota to defend quota against overflow during bandwidth shift.
  7952. */
  7953. if (quota != RUNTIME_INF && quota > max_cfs_runtime)
  7954. return -EINVAL;
  7955. if (quota != RUNTIME_INF && (burst > quota ||
  7956. burst + quota > max_cfs_runtime))
  7957. return -EINVAL;
  7958. /*
  7959. * Prevent race between setting of cfs_rq->runtime_enabled and
  7960. * unthrottle_offline_cfs_rqs().
  7961. */
  7962. guard(cpus_read_lock)();
  7963. guard(mutex)(&cfs_constraints_mutex);
  7964. ret = __cfs_schedulable(tg, period, quota);
  7965. if (ret)
  7966. return ret;
  7967. runtime_enabled = quota != RUNTIME_INF;
  7968. runtime_was_enabled = cfs_b->quota != RUNTIME_INF;
  7969. /*
  7970. * If we need to toggle cfs_bandwidth_used, off->on must occur
  7971. * before making related changes, and on->off must occur afterwards
  7972. */
  7973. if (runtime_enabled && !runtime_was_enabled)
  7974. cfs_bandwidth_usage_inc();
  7975. scoped_guard (raw_spinlock_irq, &cfs_b->lock) {
  7976. cfs_b->period = ns_to_ktime(period);
  7977. cfs_b->quota = quota;
  7978. cfs_b->burst = burst;
  7979. __refill_cfs_bandwidth_runtime(cfs_b);
  7980. /*
  7981. * Restart the period timer (if active) to handle new
  7982. * period expiry:
  7983. */
  7984. if (runtime_enabled)
  7985. start_cfs_bandwidth(cfs_b);
  7986. }
  7987. for_each_online_cpu(i) {
  7988. struct cfs_rq *cfs_rq = tg->cfs_rq[i];
  7989. struct rq *rq = cfs_rq->rq;
  7990. guard(rq_lock_irq)(rq);
  7991. cfs_rq->runtime_enabled = runtime_enabled;
  7992. cfs_rq->runtime_remaining = 0;
  7993. if (cfs_rq->throttled)
  7994. unthrottle_cfs_rq(cfs_rq);
  7995. }
  7996. if (runtime_was_enabled && !runtime_enabled)
  7997. cfs_bandwidth_usage_dec();
  7998. return 0;
  7999. }
  8000. static int tg_set_cfs_quota(struct task_group *tg, long cfs_quota_us)
  8001. {
  8002. u64 quota, period, burst;
  8003. period = ktime_to_ns(tg->cfs_bandwidth.period);
  8004. burst = tg->cfs_bandwidth.burst;
  8005. if (cfs_quota_us < 0)
  8006. quota = RUNTIME_INF;
  8007. else if ((u64)cfs_quota_us <= U64_MAX / NSEC_PER_USEC)
  8008. quota = (u64)cfs_quota_us * NSEC_PER_USEC;
  8009. else
  8010. return -EINVAL;
  8011. return tg_set_cfs_bandwidth(tg, period, quota, burst);
  8012. }
  8013. static long tg_get_cfs_quota(struct task_group *tg)
  8014. {
  8015. u64 quota_us;
  8016. if (tg->cfs_bandwidth.quota == RUNTIME_INF)
  8017. return -1;
  8018. quota_us = tg->cfs_bandwidth.quota;
  8019. do_div(quota_us, NSEC_PER_USEC);
  8020. return quota_us;
  8021. }
  8022. static int tg_set_cfs_period(struct task_group *tg, long cfs_period_us)
  8023. {
  8024. u64 quota, period, burst;
  8025. if ((u64)cfs_period_us > U64_MAX / NSEC_PER_USEC)
  8026. return -EINVAL;
  8027. period = (u64)cfs_period_us * NSEC_PER_USEC;
  8028. quota = tg->cfs_bandwidth.quota;
  8029. burst = tg->cfs_bandwidth.burst;
  8030. return tg_set_cfs_bandwidth(tg, period, quota, burst);
  8031. }
  8032. static long tg_get_cfs_period(struct task_group *tg)
  8033. {
  8034. u64 cfs_period_us;
  8035. cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period);
  8036. do_div(cfs_period_us, NSEC_PER_USEC);
  8037. return cfs_period_us;
  8038. }
  8039. static int tg_set_cfs_burst(struct task_group *tg, long cfs_burst_us)
  8040. {
  8041. u64 quota, period, burst;
  8042. if ((u64)cfs_burst_us > U64_MAX / NSEC_PER_USEC)
  8043. return -EINVAL;
  8044. burst = (u64)cfs_burst_us * NSEC_PER_USEC;
  8045. period = ktime_to_ns(tg->cfs_bandwidth.period);
  8046. quota = tg->cfs_bandwidth.quota;
  8047. return tg_set_cfs_bandwidth(tg, period, quota, burst);
  8048. }
  8049. static long tg_get_cfs_burst(struct task_group *tg)
  8050. {
  8051. u64 burst_us;
  8052. burst_us = tg->cfs_bandwidth.burst;
  8053. do_div(burst_us, NSEC_PER_USEC);
  8054. return burst_us;
  8055. }
  8056. static s64 cpu_cfs_quota_read_s64(struct cgroup_subsys_state *css,
  8057. struct cftype *cft)
  8058. {
  8059. return tg_get_cfs_quota(css_tg(css));
  8060. }
  8061. static int cpu_cfs_quota_write_s64(struct cgroup_subsys_state *css,
  8062. struct cftype *cftype, s64 cfs_quota_us)
  8063. {
  8064. return tg_set_cfs_quota(css_tg(css), cfs_quota_us);
  8065. }
  8066. static u64 cpu_cfs_period_read_u64(struct cgroup_subsys_state *css,
  8067. struct cftype *cft)
  8068. {
  8069. return tg_get_cfs_period(css_tg(css));
  8070. }
  8071. static int cpu_cfs_period_write_u64(struct cgroup_subsys_state *css,
  8072. struct cftype *cftype, u64 cfs_period_us)
  8073. {
  8074. return tg_set_cfs_period(css_tg(css), cfs_period_us);
  8075. }
  8076. static u64 cpu_cfs_burst_read_u64(struct cgroup_subsys_state *css,
  8077. struct cftype *cft)
  8078. {
  8079. return tg_get_cfs_burst(css_tg(css));
  8080. }
  8081. static int cpu_cfs_burst_write_u64(struct cgroup_subsys_state *css,
  8082. struct cftype *cftype, u64 cfs_burst_us)
  8083. {
  8084. return tg_set_cfs_burst(css_tg(css), cfs_burst_us);
  8085. }
  8086. struct cfs_schedulable_data {
  8087. struct task_group *tg;
  8088. u64 period, quota;
  8089. };
  8090. /*
  8091. * normalize group quota/period to be quota/max_period
  8092. * note: units are usecs
  8093. */
  8094. static u64 normalize_cfs_quota(struct task_group *tg,
  8095. struct cfs_schedulable_data *d)
  8096. {
  8097. u64 quota, period;
  8098. if (tg == d->tg) {
  8099. period = d->period;
  8100. quota = d->quota;
  8101. } else {
  8102. period = tg_get_cfs_period(tg);
  8103. quota = tg_get_cfs_quota(tg);
  8104. }
  8105. /* note: these should typically be equivalent */
  8106. if (quota == RUNTIME_INF || quota == -1)
  8107. return RUNTIME_INF;
  8108. return to_ratio(period, quota);
  8109. }
  8110. static int tg_cfs_schedulable_down(struct task_group *tg, void *data)
  8111. {
  8112. struct cfs_schedulable_data *d = data;
  8113. struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
  8114. s64 quota = 0, parent_quota = -1;
  8115. if (!tg->parent) {
  8116. quota = RUNTIME_INF;
  8117. } else {
  8118. struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth;
  8119. quota = normalize_cfs_quota(tg, d);
  8120. parent_quota = parent_b->hierarchical_quota;
  8121. /*
  8122. * Ensure max(child_quota) <= parent_quota. On cgroup2,
  8123. * always take the non-RUNTIME_INF min. On cgroup1, only
  8124. * inherit when no limit is set. In both cases this is used
  8125. * by the scheduler to determine if a given CFS task has a
  8126. * bandwidth constraint at some higher level.
  8127. */
  8128. if (cgroup_subsys_on_dfl(cpu_cgrp_subsys)) {
  8129. if (quota == RUNTIME_INF)
  8130. quota = parent_quota;
  8131. else if (parent_quota != RUNTIME_INF)
  8132. quota = min(quota, parent_quota);
  8133. } else {
  8134. if (quota == RUNTIME_INF)
  8135. quota = parent_quota;
  8136. else if (parent_quota != RUNTIME_INF && quota > parent_quota)
  8137. return -EINVAL;
  8138. }
  8139. }
  8140. cfs_b->hierarchical_quota = quota;
  8141. return 0;
  8142. }
  8143. static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota)
  8144. {
  8145. struct cfs_schedulable_data data = {
  8146. .tg = tg,
  8147. .period = period,
  8148. .quota = quota,
  8149. };
  8150. if (quota != RUNTIME_INF) {
  8151. do_div(data.period, NSEC_PER_USEC);
  8152. do_div(data.quota, NSEC_PER_USEC);
  8153. }
  8154. guard(rcu)();
  8155. return walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data);
  8156. }
  8157. static int cpu_cfs_stat_show(struct seq_file *sf, void *v)
  8158. {
  8159. struct task_group *tg = css_tg(seq_css(sf));
  8160. struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
  8161. seq_printf(sf, "nr_periods %d\n", cfs_b->nr_periods);
  8162. seq_printf(sf, "nr_throttled %d\n", cfs_b->nr_throttled);
  8163. seq_printf(sf, "throttled_time %llu\n", cfs_b->throttled_time);
  8164. if (schedstat_enabled() && tg != &root_task_group) {
  8165. struct sched_statistics *stats;
  8166. u64 ws = 0;
  8167. int i;
  8168. for_each_possible_cpu(i) {
  8169. stats = __schedstats_from_se(tg->se[i]);
  8170. ws += schedstat_val(stats->wait_sum);
  8171. }
  8172. seq_printf(sf, "wait_sum %llu\n", ws);
  8173. }
  8174. seq_printf(sf, "nr_bursts %d\n", cfs_b->nr_burst);
  8175. seq_printf(sf, "burst_time %llu\n", cfs_b->burst_time);
  8176. return 0;
  8177. }
  8178. static u64 throttled_time_self(struct task_group *tg)
  8179. {
  8180. int i;
  8181. u64 total = 0;
  8182. for_each_possible_cpu(i) {
  8183. total += READ_ONCE(tg->cfs_rq[i]->throttled_clock_self_time);
  8184. }
  8185. return total;
  8186. }
  8187. static int cpu_cfs_local_stat_show(struct seq_file *sf, void *v)
  8188. {
  8189. struct task_group *tg = css_tg(seq_css(sf));
  8190. seq_printf(sf, "throttled_time %llu\n", throttled_time_self(tg));
  8191. return 0;
  8192. }
  8193. #endif /* CONFIG_CFS_BANDWIDTH */
  8194. #ifdef CONFIG_RT_GROUP_SCHED
  8195. static int cpu_rt_runtime_write(struct cgroup_subsys_state *css,
  8196. struct cftype *cft, s64 val)
  8197. {
  8198. return sched_group_set_rt_runtime(css_tg(css), val);
  8199. }
  8200. static s64 cpu_rt_runtime_read(struct cgroup_subsys_state *css,
  8201. struct cftype *cft)
  8202. {
  8203. return sched_group_rt_runtime(css_tg(css));
  8204. }
  8205. static int cpu_rt_period_write_uint(struct cgroup_subsys_state *css,
  8206. struct cftype *cftype, u64 rt_period_us)
  8207. {
  8208. return sched_group_set_rt_period(css_tg(css), rt_period_us);
  8209. }
  8210. static u64 cpu_rt_period_read_uint(struct cgroup_subsys_state *css,
  8211. struct cftype *cft)
  8212. {
  8213. return sched_group_rt_period(css_tg(css));
  8214. }
  8215. #endif /* CONFIG_RT_GROUP_SCHED */
  8216. #ifdef CONFIG_GROUP_SCHED_WEIGHT
  8217. static s64 cpu_idle_read_s64(struct cgroup_subsys_state *css,
  8218. struct cftype *cft)
  8219. {
  8220. return css_tg(css)->idle;
  8221. }
  8222. static int cpu_idle_write_s64(struct cgroup_subsys_state *css,
  8223. struct cftype *cft, s64 idle)
  8224. {
  8225. int ret;
  8226. ret = sched_group_set_idle(css_tg(css), idle);
  8227. if (!ret)
  8228. scx_group_set_idle(css_tg(css), idle);
  8229. return ret;
  8230. }
  8231. #endif
  8232. static struct cftype cpu_legacy_files[] = {
  8233. #ifdef CONFIG_GROUP_SCHED_WEIGHT
  8234. {
  8235. .name = "shares",
  8236. .read_u64 = cpu_shares_read_u64,
  8237. .write_u64 = cpu_shares_write_u64,
  8238. },
  8239. {
  8240. .name = "idle",
  8241. .read_s64 = cpu_idle_read_s64,
  8242. .write_s64 = cpu_idle_write_s64,
  8243. },
  8244. #endif
  8245. #ifdef CONFIG_CFS_BANDWIDTH
  8246. {
  8247. .name = "cfs_quota_us",
  8248. .read_s64 = cpu_cfs_quota_read_s64,
  8249. .write_s64 = cpu_cfs_quota_write_s64,
  8250. },
  8251. {
  8252. .name = "cfs_period_us",
  8253. .read_u64 = cpu_cfs_period_read_u64,
  8254. .write_u64 = cpu_cfs_period_write_u64,
  8255. },
  8256. {
  8257. .name = "cfs_burst_us",
  8258. .read_u64 = cpu_cfs_burst_read_u64,
  8259. .write_u64 = cpu_cfs_burst_write_u64,
  8260. },
  8261. {
  8262. .name = "stat",
  8263. .seq_show = cpu_cfs_stat_show,
  8264. },
  8265. {
  8266. .name = "stat.local",
  8267. .seq_show = cpu_cfs_local_stat_show,
  8268. },
  8269. #endif
  8270. #ifdef CONFIG_RT_GROUP_SCHED
  8271. {
  8272. .name = "rt_runtime_us",
  8273. .read_s64 = cpu_rt_runtime_read,
  8274. .write_s64 = cpu_rt_runtime_write,
  8275. },
  8276. {
  8277. .name = "rt_period_us",
  8278. .read_u64 = cpu_rt_period_read_uint,
  8279. .write_u64 = cpu_rt_period_write_uint,
  8280. },
  8281. #endif
  8282. #ifdef CONFIG_UCLAMP_TASK_GROUP
  8283. {
  8284. .name = "uclamp.min",
  8285. .flags = CFTYPE_NOT_ON_ROOT,
  8286. .seq_show = cpu_uclamp_min_show,
  8287. .write = cpu_uclamp_min_write,
  8288. },
  8289. {
  8290. .name = "uclamp.max",
  8291. .flags = CFTYPE_NOT_ON_ROOT,
  8292. .seq_show = cpu_uclamp_max_show,
  8293. .write = cpu_uclamp_max_write,
  8294. },
  8295. #endif
  8296. { } /* Terminate */
  8297. };
  8298. static int cpu_extra_stat_show(struct seq_file *sf,
  8299. struct cgroup_subsys_state *css)
  8300. {
  8301. #ifdef CONFIG_CFS_BANDWIDTH
  8302. {
  8303. struct task_group *tg = css_tg(css);
  8304. struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
  8305. u64 throttled_usec, burst_usec;
  8306. throttled_usec = cfs_b->throttled_time;
  8307. do_div(throttled_usec, NSEC_PER_USEC);
  8308. burst_usec = cfs_b->burst_time;
  8309. do_div(burst_usec, NSEC_PER_USEC);
  8310. seq_printf(sf, "nr_periods %d\n"
  8311. "nr_throttled %d\n"
  8312. "throttled_usec %llu\n"
  8313. "nr_bursts %d\n"
  8314. "burst_usec %llu\n",
  8315. cfs_b->nr_periods, cfs_b->nr_throttled,
  8316. throttled_usec, cfs_b->nr_burst, burst_usec);
  8317. }
  8318. #endif
  8319. return 0;
  8320. }
  8321. static int cpu_local_stat_show(struct seq_file *sf,
  8322. struct cgroup_subsys_state *css)
  8323. {
  8324. #ifdef CONFIG_CFS_BANDWIDTH
  8325. {
  8326. struct task_group *tg = css_tg(css);
  8327. u64 throttled_self_usec;
  8328. throttled_self_usec = throttled_time_self(tg);
  8329. do_div(throttled_self_usec, NSEC_PER_USEC);
  8330. seq_printf(sf, "throttled_usec %llu\n",
  8331. throttled_self_usec);
  8332. }
  8333. #endif
  8334. return 0;
  8335. }
  8336. #ifdef CONFIG_GROUP_SCHED_WEIGHT
  8337. static u64 cpu_weight_read_u64(struct cgroup_subsys_state *css,
  8338. struct cftype *cft)
  8339. {
  8340. return sched_weight_to_cgroup(tg_weight(css_tg(css)));
  8341. }
  8342. static int cpu_weight_write_u64(struct cgroup_subsys_state *css,
  8343. struct cftype *cft, u64 cgrp_weight)
  8344. {
  8345. unsigned long weight;
  8346. int ret;
  8347. if (cgrp_weight < CGROUP_WEIGHT_MIN || cgrp_weight > CGROUP_WEIGHT_MAX)
  8348. return -ERANGE;
  8349. weight = sched_weight_from_cgroup(cgrp_weight);
  8350. ret = sched_group_set_shares(css_tg(css), scale_load(weight));
  8351. if (!ret)
  8352. scx_group_set_weight(css_tg(css), cgrp_weight);
  8353. return ret;
  8354. }
  8355. static s64 cpu_weight_nice_read_s64(struct cgroup_subsys_state *css,
  8356. struct cftype *cft)
  8357. {
  8358. unsigned long weight = tg_weight(css_tg(css));
  8359. int last_delta = INT_MAX;
  8360. int prio, delta;
  8361. /* find the closest nice value to the current weight */
  8362. for (prio = 0; prio < ARRAY_SIZE(sched_prio_to_weight); prio++) {
  8363. delta = abs(sched_prio_to_weight[prio] - weight);
  8364. if (delta >= last_delta)
  8365. break;
  8366. last_delta = delta;
  8367. }
  8368. return PRIO_TO_NICE(prio - 1 + MAX_RT_PRIO);
  8369. }
  8370. static int cpu_weight_nice_write_s64(struct cgroup_subsys_state *css,
  8371. struct cftype *cft, s64 nice)
  8372. {
  8373. unsigned long weight;
  8374. int idx, ret;
  8375. if (nice < MIN_NICE || nice > MAX_NICE)
  8376. return -ERANGE;
  8377. idx = NICE_TO_PRIO(nice) - MAX_RT_PRIO;
  8378. idx = array_index_nospec(idx, 40);
  8379. weight = sched_prio_to_weight[idx];
  8380. ret = sched_group_set_shares(css_tg(css), scale_load(weight));
  8381. if (!ret)
  8382. scx_group_set_weight(css_tg(css),
  8383. sched_weight_to_cgroup(weight));
  8384. return ret;
  8385. }
  8386. #endif /* CONFIG_GROUP_SCHED_WEIGHT */
  8387. static void __maybe_unused cpu_period_quota_print(struct seq_file *sf,
  8388. long period, long quota)
  8389. {
  8390. if (quota < 0)
  8391. seq_puts(sf, "max");
  8392. else
  8393. seq_printf(sf, "%ld", quota);
  8394. seq_printf(sf, " %ld\n", period);
  8395. }
  8396. /* caller should put the current value in *@periodp before calling */
  8397. static int __maybe_unused cpu_period_quota_parse(char *buf,
  8398. u64 *periodp, u64 *quotap)
  8399. {
  8400. char tok[21]; /* U64_MAX */
  8401. if (sscanf(buf, "%20s %llu", tok, periodp) < 1)
  8402. return -EINVAL;
  8403. *periodp *= NSEC_PER_USEC;
  8404. if (sscanf(tok, "%llu", quotap))
  8405. *quotap *= NSEC_PER_USEC;
  8406. else if (!strcmp(tok, "max"))
  8407. *quotap = RUNTIME_INF;
  8408. else
  8409. return -EINVAL;
  8410. return 0;
  8411. }
  8412. #ifdef CONFIG_CFS_BANDWIDTH
  8413. static int cpu_max_show(struct seq_file *sf, void *v)
  8414. {
  8415. struct task_group *tg = css_tg(seq_css(sf));
  8416. cpu_period_quota_print(sf, tg_get_cfs_period(tg), tg_get_cfs_quota(tg));
  8417. return 0;
  8418. }
  8419. static ssize_t cpu_max_write(struct kernfs_open_file *of,
  8420. char *buf, size_t nbytes, loff_t off)
  8421. {
  8422. struct task_group *tg = css_tg(of_css(of));
  8423. u64 period = tg_get_cfs_period(tg);
  8424. u64 burst = tg->cfs_bandwidth.burst;
  8425. u64 quota;
  8426. int ret;
  8427. ret = cpu_period_quota_parse(buf, &period, &quota);
  8428. if (!ret)
  8429. ret = tg_set_cfs_bandwidth(tg, period, quota, burst);
  8430. return ret ?: nbytes;
  8431. }
  8432. #endif
  8433. static struct cftype cpu_files[] = {
  8434. #ifdef CONFIG_GROUP_SCHED_WEIGHT
  8435. {
  8436. .name = "weight",
  8437. .flags = CFTYPE_NOT_ON_ROOT,
  8438. .read_u64 = cpu_weight_read_u64,
  8439. .write_u64 = cpu_weight_write_u64,
  8440. },
  8441. {
  8442. .name = "weight.nice",
  8443. .flags = CFTYPE_NOT_ON_ROOT,
  8444. .read_s64 = cpu_weight_nice_read_s64,
  8445. .write_s64 = cpu_weight_nice_write_s64,
  8446. },
  8447. {
  8448. .name = "idle",
  8449. .flags = CFTYPE_NOT_ON_ROOT,
  8450. .read_s64 = cpu_idle_read_s64,
  8451. .write_s64 = cpu_idle_write_s64,
  8452. },
  8453. #endif
  8454. #ifdef CONFIG_CFS_BANDWIDTH
  8455. {
  8456. .name = "max",
  8457. .flags = CFTYPE_NOT_ON_ROOT,
  8458. .seq_show = cpu_max_show,
  8459. .write = cpu_max_write,
  8460. },
  8461. {
  8462. .name = "max.burst",
  8463. .flags = CFTYPE_NOT_ON_ROOT,
  8464. .read_u64 = cpu_cfs_burst_read_u64,
  8465. .write_u64 = cpu_cfs_burst_write_u64,
  8466. },
  8467. #endif
  8468. #ifdef CONFIG_UCLAMP_TASK_GROUP
  8469. {
  8470. .name = "uclamp.min",
  8471. .flags = CFTYPE_NOT_ON_ROOT,
  8472. .seq_show = cpu_uclamp_min_show,
  8473. .write = cpu_uclamp_min_write,
  8474. },
  8475. {
  8476. .name = "uclamp.max",
  8477. .flags = CFTYPE_NOT_ON_ROOT,
  8478. .seq_show = cpu_uclamp_max_show,
  8479. .write = cpu_uclamp_max_write,
  8480. },
  8481. #endif
  8482. { } /* terminate */
  8483. };
  8484. struct cgroup_subsys cpu_cgrp_subsys = {
  8485. .css_alloc = cpu_cgroup_css_alloc,
  8486. .css_online = cpu_cgroup_css_online,
  8487. .css_offline = cpu_cgroup_css_offline,
  8488. .css_released = cpu_cgroup_css_released,
  8489. .css_free = cpu_cgroup_css_free,
  8490. .css_extra_stat_show = cpu_extra_stat_show,
  8491. .css_local_stat_show = cpu_local_stat_show,
  8492. .can_attach = cpu_cgroup_can_attach,
  8493. .attach = cpu_cgroup_attach,
  8494. .cancel_attach = cpu_cgroup_cancel_attach,
  8495. .legacy_cftypes = cpu_legacy_files,
  8496. .dfl_cftypes = cpu_files,
  8497. .early_init = true,
  8498. .threaded = true,
  8499. };
  8500. #endif /* CONFIG_CGROUP_SCHED */
  8501. void dump_cpu_task(int cpu)
  8502. {
  8503. if (in_hardirq() && cpu == smp_processor_id()) {
  8504. struct pt_regs *regs;
  8505. regs = get_irq_regs();
  8506. if (regs) {
  8507. show_regs(regs);
  8508. return;
  8509. }
  8510. }
  8511. if (trigger_single_cpu_backtrace(cpu))
  8512. return;
  8513. pr_info("Task dump for CPU %d:\n", cpu);
  8514. sched_show_task(cpu_curr(cpu));
  8515. }
  8516. /*
  8517. * Nice levels are multiplicative, with a gentle 10% change for every
  8518. * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
  8519. * nice 1, it will get ~10% less CPU time than another CPU-bound task
  8520. * that remained on nice 0.
  8521. *
  8522. * The "10% effect" is relative and cumulative: from _any_ nice level,
  8523. * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
  8524. * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
  8525. * If a task goes up by ~10% and another task goes down by ~10% then
  8526. * the relative distance between them is ~25%.)
  8527. */
  8528. const int sched_prio_to_weight[40] = {
  8529. /* -20 */ 88761, 71755, 56483, 46273, 36291,
  8530. /* -15 */ 29154, 23254, 18705, 14949, 11916,
  8531. /* -10 */ 9548, 7620, 6100, 4904, 3906,
  8532. /* -5 */ 3121, 2501, 1991, 1586, 1277,
  8533. /* 0 */ 1024, 820, 655, 526, 423,
  8534. /* 5 */ 335, 272, 215, 172, 137,
  8535. /* 10 */ 110, 87, 70, 56, 45,
  8536. /* 15 */ 36, 29, 23, 18, 15,
  8537. };
  8538. /*
  8539. * Inverse (2^32/x) values of the sched_prio_to_weight[] array, pre-calculated.
  8540. *
  8541. * In cases where the weight does not change often, we can use the
  8542. * pre-calculated inverse to speed up arithmetics by turning divisions
  8543. * into multiplications:
  8544. */
  8545. const u32 sched_prio_to_wmult[40] = {
  8546. /* -20 */ 48388, 59856, 76040, 92818, 118348,
  8547. /* -15 */ 147320, 184698, 229616, 287308, 360437,
  8548. /* -10 */ 449829, 563644, 704093, 875809, 1099582,
  8549. /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
  8550. /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
  8551. /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
  8552. /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
  8553. /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
  8554. };
  8555. void call_trace_sched_update_nr_running(struct rq *rq, int count)
  8556. {
  8557. trace_sched_update_nr_running_tp(rq, count);
  8558. }
  8559. #ifdef CONFIG_SCHED_MM_CID
  8560. /*
  8561. * @cid_lock: Guarantee forward-progress of cid allocation.
  8562. *
  8563. * Concurrency ID allocation within a bitmap is mostly lock-free. The cid_lock
  8564. * is only used when contention is detected by the lock-free allocation so
  8565. * forward progress can be guaranteed.
  8566. */
  8567. DEFINE_RAW_SPINLOCK(cid_lock);
  8568. /*
  8569. * @use_cid_lock: Select cid allocation behavior: lock-free vs spinlock.
  8570. *
  8571. * When @use_cid_lock is 0, the cid allocation is lock-free. When contention is
  8572. * detected, it is set to 1 to ensure that all newly coming allocations are
  8573. * serialized by @cid_lock until the allocation which detected contention
  8574. * completes and sets @use_cid_lock back to 0. This guarantees forward progress
  8575. * of a cid allocation.
  8576. */
  8577. int use_cid_lock;
  8578. /*
  8579. * mm_cid remote-clear implements a lock-free algorithm to clear per-mm/cpu cid
  8580. * concurrently with respect to the execution of the source runqueue context
  8581. * switch.
  8582. *
  8583. * There is one basic properties we want to guarantee here:
  8584. *
  8585. * (1) Remote-clear should _never_ mark a per-cpu cid UNSET when it is actively
  8586. * used by a task. That would lead to concurrent allocation of the cid and
  8587. * userspace corruption.
  8588. *
  8589. * Provide this guarantee by introducing a Dekker memory ordering to guarantee
  8590. * that a pair of loads observe at least one of a pair of stores, which can be
  8591. * shown as:
  8592. *
  8593. * X = Y = 0
  8594. *
  8595. * w[X]=1 w[Y]=1
  8596. * MB MB
  8597. * r[Y]=y r[X]=x
  8598. *
  8599. * Which guarantees that x==0 && y==0 is impossible. But rather than using
  8600. * values 0 and 1, this algorithm cares about specific state transitions of the
  8601. * runqueue current task (as updated by the scheduler context switch), and the
  8602. * per-mm/cpu cid value.
  8603. *
  8604. * Let's introduce task (Y) which has task->mm == mm and task (N) which has
  8605. * task->mm != mm for the rest of the discussion. There are two scheduler state
  8606. * transitions on context switch we care about:
  8607. *
  8608. * (TSA) Store to rq->curr with transition from (N) to (Y)
  8609. *
  8610. * (TSB) Store to rq->curr with transition from (Y) to (N)
  8611. *
  8612. * On the remote-clear side, there is one transition we care about:
  8613. *
  8614. * (TMA) cmpxchg to *pcpu_cid to set the LAZY flag
  8615. *
  8616. * There is also a transition to UNSET state which can be performed from all
  8617. * sides (scheduler, remote-clear). It is always performed with a cmpxchg which
  8618. * guarantees that only a single thread will succeed:
  8619. *
  8620. * (TMB) cmpxchg to *pcpu_cid to mark UNSET
  8621. *
  8622. * Just to be clear, what we do _not_ want to happen is a transition to UNSET
  8623. * when a thread is actively using the cid (property (1)).
  8624. *
  8625. * Let's looks at the relevant combinations of TSA/TSB, and TMA transitions.
  8626. *
  8627. * Scenario A) (TSA)+(TMA) (from next task perspective)
  8628. *
  8629. * CPU0 CPU1
  8630. *
  8631. * Context switch CS-1 Remote-clear
  8632. * - store to rq->curr: (N)->(Y) (TSA) - cmpxchg to *pcpu_id to LAZY (TMA)
  8633. * (implied barrier after cmpxchg)
  8634. * - switch_mm_cid()
  8635. * - memory barrier (see switch_mm_cid()
  8636. * comment explaining how this barrier
  8637. * is combined with other scheduler
  8638. * barriers)
  8639. * - mm_cid_get (next)
  8640. * - READ_ONCE(*pcpu_cid) - rcu_dereference(src_rq->curr)
  8641. *
  8642. * This Dekker ensures that either task (Y) is observed by the
  8643. * rcu_dereference() or the LAZY flag is observed by READ_ONCE(), or both are
  8644. * observed.
  8645. *
  8646. * If task (Y) store is observed by rcu_dereference(), it means that there is
  8647. * still an active task on the cpu. Remote-clear will therefore not transition
  8648. * to UNSET, which fulfills property (1).
  8649. *
  8650. * If task (Y) is not observed, but the lazy flag is observed by READ_ONCE(),
  8651. * it will move its state to UNSET, which clears the percpu cid perhaps
  8652. * uselessly (which is not an issue for correctness). Because task (Y) is not
  8653. * observed, CPU1 can move ahead to set the state to UNSET. Because moving
  8654. * state to UNSET is done with a cmpxchg expecting that the old state has the
  8655. * LAZY flag set, only one thread will successfully UNSET.
  8656. *
  8657. * If both states (LAZY flag and task (Y)) are observed, the thread on CPU0
  8658. * will observe the LAZY flag and transition to UNSET (perhaps uselessly), and
  8659. * CPU1 will observe task (Y) and do nothing more, which is fine.
  8660. *
  8661. * What we are effectively preventing with this Dekker is a scenario where
  8662. * neither LAZY flag nor store (Y) are observed, which would fail property (1)
  8663. * because this would UNSET a cid which is actively used.
  8664. */
  8665. void sched_mm_cid_migrate_from(struct task_struct *t)
  8666. {
  8667. t->migrate_from_cpu = task_cpu(t);
  8668. }
  8669. static
  8670. int __sched_mm_cid_migrate_from_fetch_cid(struct rq *src_rq,
  8671. struct task_struct *t,
  8672. struct mm_cid *src_pcpu_cid)
  8673. {
  8674. struct mm_struct *mm = t->mm;
  8675. struct task_struct *src_task;
  8676. int src_cid, last_mm_cid;
  8677. if (!mm)
  8678. return -1;
  8679. last_mm_cid = t->last_mm_cid;
  8680. /*
  8681. * If the migrated task has no last cid, or if the current
  8682. * task on src rq uses the cid, it means the source cid does not need
  8683. * to be moved to the destination cpu.
  8684. */
  8685. if (last_mm_cid == -1)
  8686. return -1;
  8687. src_cid = READ_ONCE(src_pcpu_cid->cid);
  8688. if (!mm_cid_is_valid(src_cid) || last_mm_cid != src_cid)
  8689. return -1;
  8690. /*
  8691. * If we observe an active task using the mm on this rq, it means we
  8692. * are not the last task to be migrated from this cpu for this mm, so
  8693. * there is no need to move src_cid to the destination cpu.
  8694. */
  8695. guard(rcu)();
  8696. src_task = rcu_dereference(src_rq->curr);
  8697. if (READ_ONCE(src_task->mm_cid_active) && src_task->mm == mm) {
  8698. t->last_mm_cid = -1;
  8699. return -1;
  8700. }
  8701. return src_cid;
  8702. }
  8703. static
  8704. int __sched_mm_cid_migrate_from_try_steal_cid(struct rq *src_rq,
  8705. struct task_struct *t,
  8706. struct mm_cid *src_pcpu_cid,
  8707. int src_cid)
  8708. {
  8709. struct task_struct *src_task;
  8710. struct mm_struct *mm = t->mm;
  8711. int lazy_cid;
  8712. if (src_cid == -1)
  8713. return -1;
  8714. /*
  8715. * Attempt to clear the source cpu cid to move it to the destination
  8716. * cpu.
  8717. */
  8718. lazy_cid = mm_cid_set_lazy_put(src_cid);
  8719. if (!try_cmpxchg(&src_pcpu_cid->cid, &src_cid, lazy_cid))
  8720. return -1;
  8721. /*
  8722. * The implicit barrier after cmpxchg per-mm/cpu cid before loading
  8723. * rq->curr->mm matches the scheduler barrier in context_switch()
  8724. * between store to rq->curr and load of prev and next task's
  8725. * per-mm/cpu cid.
  8726. *
  8727. * The implicit barrier after cmpxchg per-mm/cpu cid before loading
  8728. * rq->curr->mm_cid_active matches the barrier in
  8729. * sched_mm_cid_exit_signals(), sched_mm_cid_before_execve(), and
  8730. * sched_mm_cid_after_execve() between store to t->mm_cid_active and
  8731. * load of per-mm/cpu cid.
  8732. */
  8733. /*
  8734. * If we observe an active task using the mm on this rq after setting
  8735. * the lazy-put flag, this task will be responsible for transitioning
  8736. * from lazy-put flag set to MM_CID_UNSET.
  8737. */
  8738. scoped_guard (rcu) {
  8739. src_task = rcu_dereference(src_rq->curr);
  8740. if (READ_ONCE(src_task->mm_cid_active) && src_task->mm == mm) {
  8741. /*
  8742. * We observed an active task for this mm, there is therefore
  8743. * no point in moving this cid to the destination cpu.
  8744. */
  8745. t->last_mm_cid = -1;
  8746. return -1;
  8747. }
  8748. }
  8749. /*
  8750. * The src_cid is unused, so it can be unset.
  8751. */
  8752. if (!try_cmpxchg(&src_pcpu_cid->cid, &lazy_cid, MM_CID_UNSET))
  8753. return -1;
  8754. return src_cid;
  8755. }
  8756. /*
  8757. * Migration to dst cpu. Called with dst_rq lock held.
  8758. * Interrupts are disabled, which keeps the window of cid ownership without the
  8759. * source rq lock held small.
  8760. */
  8761. void sched_mm_cid_migrate_to(struct rq *dst_rq, struct task_struct *t)
  8762. {
  8763. struct mm_cid *src_pcpu_cid, *dst_pcpu_cid;
  8764. struct mm_struct *mm = t->mm;
  8765. int src_cid, dst_cid, src_cpu;
  8766. struct rq *src_rq;
  8767. lockdep_assert_rq_held(dst_rq);
  8768. if (!mm)
  8769. return;
  8770. src_cpu = t->migrate_from_cpu;
  8771. if (src_cpu == -1) {
  8772. t->last_mm_cid = -1;
  8773. return;
  8774. }
  8775. /*
  8776. * Move the src cid if the dst cid is unset. This keeps id
  8777. * allocation closest to 0 in cases where few threads migrate around
  8778. * many CPUs.
  8779. *
  8780. * If destination cid is already set, we may have to just clear
  8781. * the src cid to ensure compactness in frequent migrations
  8782. * scenarios.
  8783. *
  8784. * It is not useful to clear the src cid when the number of threads is
  8785. * greater or equal to the number of allowed CPUs, because user-space
  8786. * can expect that the number of allowed cids can reach the number of
  8787. * allowed CPUs.
  8788. */
  8789. dst_pcpu_cid = per_cpu_ptr(mm->pcpu_cid, cpu_of(dst_rq));
  8790. dst_cid = READ_ONCE(dst_pcpu_cid->cid);
  8791. if (!mm_cid_is_unset(dst_cid) &&
  8792. atomic_read(&mm->mm_users) >= t->nr_cpus_allowed)
  8793. return;
  8794. src_pcpu_cid = per_cpu_ptr(mm->pcpu_cid, src_cpu);
  8795. src_rq = cpu_rq(src_cpu);
  8796. src_cid = __sched_mm_cid_migrate_from_fetch_cid(src_rq, t, src_pcpu_cid);
  8797. if (src_cid == -1)
  8798. return;
  8799. src_cid = __sched_mm_cid_migrate_from_try_steal_cid(src_rq, t, src_pcpu_cid,
  8800. src_cid);
  8801. if (src_cid == -1)
  8802. return;
  8803. if (!mm_cid_is_unset(dst_cid)) {
  8804. __mm_cid_put(mm, src_cid);
  8805. return;
  8806. }
  8807. /* Move src_cid to dst cpu. */
  8808. mm_cid_snapshot_time(dst_rq, mm);
  8809. WRITE_ONCE(dst_pcpu_cid->cid, src_cid);
  8810. }
  8811. static void sched_mm_cid_remote_clear(struct mm_struct *mm, struct mm_cid *pcpu_cid,
  8812. int cpu)
  8813. {
  8814. struct rq *rq = cpu_rq(cpu);
  8815. struct task_struct *t;
  8816. int cid, lazy_cid;
  8817. cid = READ_ONCE(pcpu_cid->cid);
  8818. if (!mm_cid_is_valid(cid))
  8819. return;
  8820. /*
  8821. * Clear the cpu cid if it is set to keep cid allocation compact. If
  8822. * there happens to be other tasks left on the source cpu using this
  8823. * mm, the next task using this mm will reallocate its cid on context
  8824. * switch.
  8825. */
  8826. lazy_cid = mm_cid_set_lazy_put(cid);
  8827. if (!try_cmpxchg(&pcpu_cid->cid, &cid, lazy_cid))
  8828. return;
  8829. /*
  8830. * The implicit barrier after cmpxchg per-mm/cpu cid before loading
  8831. * rq->curr->mm matches the scheduler barrier in context_switch()
  8832. * between store to rq->curr and load of prev and next task's
  8833. * per-mm/cpu cid.
  8834. *
  8835. * The implicit barrier after cmpxchg per-mm/cpu cid before loading
  8836. * rq->curr->mm_cid_active matches the barrier in
  8837. * sched_mm_cid_exit_signals(), sched_mm_cid_before_execve(), and
  8838. * sched_mm_cid_after_execve() between store to t->mm_cid_active and
  8839. * load of per-mm/cpu cid.
  8840. */
  8841. /*
  8842. * If we observe an active task using the mm on this rq after setting
  8843. * the lazy-put flag, that task will be responsible for transitioning
  8844. * from lazy-put flag set to MM_CID_UNSET.
  8845. */
  8846. scoped_guard (rcu) {
  8847. t = rcu_dereference(rq->curr);
  8848. if (READ_ONCE(t->mm_cid_active) && t->mm == mm)
  8849. return;
  8850. }
  8851. /*
  8852. * The cid is unused, so it can be unset.
  8853. * Disable interrupts to keep the window of cid ownership without rq
  8854. * lock small.
  8855. */
  8856. scoped_guard (irqsave) {
  8857. if (try_cmpxchg(&pcpu_cid->cid, &lazy_cid, MM_CID_UNSET))
  8858. __mm_cid_put(mm, cid);
  8859. }
  8860. }
  8861. static void sched_mm_cid_remote_clear_old(struct mm_struct *mm, int cpu)
  8862. {
  8863. struct rq *rq = cpu_rq(cpu);
  8864. struct mm_cid *pcpu_cid;
  8865. struct task_struct *curr;
  8866. u64 rq_clock;
  8867. /*
  8868. * rq->clock load is racy on 32-bit but one spurious clear once in a
  8869. * while is irrelevant.
  8870. */
  8871. rq_clock = READ_ONCE(rq->clock);
  8872. pcpu_cid = per_cpu_ptr(mm->pcpu_cid, cpu);
  8873. /*
  8874. * In order to take care of infrequently scheduled tasks, bump the time
  8875. * snapshot associated with this cid if an active task using the mm is
  8876. * observed on this rq.
  8877. */
  8878. scoped_guard (rcu) {
  8879. curr = rcu_dereference(rq->curr);
  8880. if (READ_ONCE(curr->mm_cid_active) && curr->mm == mm) {
  8881. WRITE_ONCE(pcpu_cid->time, rq_clock);
  8882. return;
  8883. }
  8884. }
  8885. if (rq_clock < pcpu_cid->time + SCHED_MM_CID_PERIOD_NS)
  8886. return;
  8887. sched_mm_cid_remote_clear(mm, pcpu_cid, cpu);
  8888. }
  8889. static void sched_mm_cid_remote_clear_weight(struct mm_struct *mm, int cpu,
  8890. int weight)
  8891. {
  8892. struct mm_cid *pcpu_cid;
  8893. int cid;
  8894. pcpu_cid = per_cpu_ptr(mm->pcpu_cid, cpu);
  8895. cid = READ_ONCE(pcpu_cid->cid);
  8896. if (!mm_cid_is_valid(cid) || cid < weight)
  8897. return;
  8898. sched_mm_cid_remote_clear(mm, pcpu_cid, cpu);
  8899. }
  8900. static void task_mm_cid_work(struct callback_head *work)
  8901. {
  8902. unsigned long now = jiffies, old_scan, next_scan;
  8903. struct task_struct *t = current;
  8904. struct cpumask *cidmask;
  8905. struct mm_struct *mm;
  8906. int weight, cpu;
  8907. SCHED_WARN_ON(t != container_of(work, struct task_struct, cid_work));
  8908. work->next = work; /* Prevent double-add */
  8909. if (t->flags & PF_EXITING)
  8910. return;
  8911. mm = t->mm;
  8912. if (!mm)
  8913. return;
  8914. old_scan = READ_ONCE(mm->mm_cid_next_scan);
  8915. next_scan = now + msecs_to_jiffies(MM_CID_SCAN_DELAY);
  8916. if (!old_scan) {
  8917. unsigned long res;
  8918. res = cmpxchg(&mm->mm_cid_next_scan, old_scan, next_scan);
  8919. if (res != old_scan)
  8920. old_scan = res;
  8921. else
  8922. old_scan = next_scan;
  8923. }
  8924. if (time_before(now, old_scan))
  8925. return;
  8926. if (!try_cmpxchg(&mm->mm_cid_next_scan, &old_scan, next_scan))
  8927. return;
  8928. cidmask = mm_cidmask(mm);
  8929. /* Clear cids that were not recently used. */
  8930. for_each_possible_cpu(cpu)
  8931. sched_mm_cid_remote_clear_old(mm, cpu);
  8932. weight = cpumask_weight(cidmask);
  8933. /*
  8934. * Clear cids that are greater or equal to the cidmask weight to
  8935. * recompact it.
  8936. */
  8937. for_each_possible_cpu(cpu)
  8938. sched_mm_cid_remote_clear_weight(mm, cpu, weight);
  8939. }
  8940. void init_sched_mm_cid(struct task_struct *t)
  8941. {
  8942. struct mm_struct *mm = t->mm;
  8943. int mm_users = 0;
  8944. if (mm) {
  8945. mm_users = atomic_read(&mm->mm_users);
  8946. if (mm_users == 1)
  8947. mm->mm_cid_next_scan = jiffies + msecs_to_jiffies(MM_CID_SCAN_DELAY);
  8948. }
  8949. t->cid_work.next = &t->cid_work; /* Protect against double add */
  8950. init_task_work(&t->cid_work, task_mm_cid_work);
  8951. }
  8952. void task_tick_mm_cid(struct rq *rq, struct task_struct *curr)
  8953. {
  8954. struct callback_head *work = &curr->cid_work;
  8955. unsigned long now = jiffies;
  8956. if (!curr->mm || (curr->flags & (PF_EXITING | PF_KTHREAD)) ||
  8957. work->next != work)
  8958. return;
  8959. if (time_before(now, READ_ONCE(curr->mm->mm_cid_next_scan)))
  8960. return;
  8961. /* No page allocation under rq lock */
  8962. task_work_add(curr, work, TWA_RESUME | TWAF_NO_ALLOC);
  8963. }
  8964. void sched_mm_cid_exit_signals(struct task_struct *t)
  8965. {
  8966. struct mm_struct *mm = t->mm;
  8967. struct rq *rq;
  8968. if (!mm)
  8969. return;
  8970. preempt_disable();
  8971. rq = this_rq();
  8972. guard(rq_lock_irqsave)(rq);
  8973. preempt_enable_no_resched(); /* holding spinlock */
  8974. WRITE_ONCE(t->mm_cid_active, 0);
  8975. /*
  8976. * Store t->mm_cid_active before loading per-mm/cpu cid.
  8977. * Matches barrier in sched_mm_cid_remote_clear_old().
  8978. */
  8979. smp_mb();
  8980. mm_cid_put(mm);
  8981. t->last_mm_cid = t->mm_cid = -1;
  8982. }
  8983. void sched_mm_cid_before_execve(struct task_struct *t)
  8984. {
  8985. struct mm_struct *mm = t->mm;
  8986. struct rq *rq;
  8987. if (!mm)
  8988. return;
  8989. preempt_disable();
  8990. rq = this_rq();
  8991. guard(rq_lock_irqsave)(rq);
  8992. preempt_enable_no_resched(); /* holding spinlock */
  8993. WRITE_ONCE(t->mm_cid_active, 0);
  8994. /*
  8995. * Store t->mm_cid_active before loading per-mm/cpu cid.
  8996. * Matches barrier in sched_mm_cid_remote_clear_old().
  8997. */
  8998. smp_mb();
  8999. mm_cid_put(mm);
  9000. t->last_mm_cid = t->mm_cid = -1;
  9001. }
  9002. void sched_mm_cid_after_execve(struct task_struct *t)
  9003. {
  9004. struct mm_struct *mm = t->mm;
  9005. struct rq *rq;
  9006. if (!mm)
  9007. return;
  9008. preempt_disable();
  9009. rq = this_rq();
  9010. scoped_guard (rq_lock_irqsave, rq) {
  9011. preempt_enable_no_resched(); /* holding spinlock */
  9012. WRITE_ONCE(t->mm_cid_active, 1);
  9013. /*
  9014. * Store t->mm_cid_active before loading per-mm/cpu cid.
  9015. * Matches barrier in sched_mm_cid_remote_clear_old().
  9016. */
  9017. smp_mb();
  9018. t->last_mm_cid = t->mm_cid = mm_cid_get(rq, mm);
  9019. }
  9020. rseq_set_notify_resume(t);
  9021. }
  9022. void sched_mm_cid_fork(struct task_struct *t)
  9023. {
  9024. WARN_ON_ONCE(!t->mm || t->mm_cid != -1);
  9025. t->mm_cid_active = 1;
  9026. }
  9027. #endif
  9028. #ifdef CONFIG_SCHED_CLASS_EXT
  9029. void sched_deq_and_put_task(struct task_struct *p, int queue_flags,
  9030. struct sched_enq_and_set_ctx *ctx)
  9031. {
  9032. struct rq *rq = task_rq(p);
  9033. lockdep_assert_rq_held(rq);
  9034. *ctx = (struct sched_enq_and_set_ctx){
  9035. .p = p,
  9036. .queue_flags = queue_flags,
  9037. .queued = task_on_rq_queued(p),
  9038. .running = task_current(rq, p),
  9039. };
  9040. update_rq_clock(rq);
  9041. if (ctx->queued)
  9042. dequeue_task(rq, p, queue_flags | DEQUEUE_NOCLOCK);
  9043. if (ctx->running)
  9044. put_prev_task(rq, p);
  9045. }
  9046. void sched_enq_and_set_task(struct sched_enq_and_set_ctx *ctx)
  9047. {
  9048. struct rq *rq = task_rq(ctx->p);
  9049. lockdep_assert_rq_held(rq);
  9050. if (ctx->queued)
  9051. enqueue_task(rq, ctx->p, ctx->queue_flags | ENQUEUE_NOCLOCK);
  9052. if (ctx->running)
  9053. set_next_task(rq, ctx->p);
  9054. }
  9055. #endif /* CONFIG_SCHED_CLASS_EXT */