core.c 174 KB

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