core.c 174 KB

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