core.c 173 KB

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