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