core.c 205 KB

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