core.c 178 KB

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