core.c 217 KB

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