core.c 206 KB

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