core.c 194 KB

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