core.c 170 KB

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