core.c 193 KB

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