core.c 179 KB

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