core.c 180 KB

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