core.c 180 KB

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