core.c 195 KB

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