core.c 201 KB

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