core.c 178 KB

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