core.c 206 KB

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