core.c 171 KB

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