core.c 194 KB

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