core.c 174 KB

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