core.c 179 KB

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