core.c 200 KB

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