core.c 180 KB

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