core.c 204 KB

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