core.c 201 KB

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