sched.c 177 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059
  1. /*
  2. * kernel/sched.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. */
  20. #include <linux/mm.h>
  21. #include <linux/module.h>
  22. #include <linux/nmi.h>
  23. #include <linux/init.h>
  24. #include <asm/uaccess.h>
  25. #include <linux/highmem.h>
  26. #include <linux/smp_lock.h>
  27. #include <asm/mmu_context.h>
  28. #include <linux/interrupt.h>
  29. #include <linux/capability.h>
  30. #include <linux/completion.h>
  31. #include <linux/kernel_stat.h>
  32. #include <linux/debug_locks.h>
  33. #include <linux/security.h>
  34. #include <linux/notifier.h>
  35. #include <linux/profile.h>
  36. #include <linux/freezer.h>
  37. #include <linux/vmalloc.h>
  38. #include <linux/blkdev.h>
  39. #include <linux/delay.h>
  40. #include <linux/smp.h>
  41. #include <linux/threads.h>
  42. #include <linux/timer.h>
  43. #include <linux/rcupdate.h>
  44. #include <linux/cpu.h>
  45. #include <linux/cpuset.h>
  46. #include <linux/percpu.h>
  47. #include <linux/kthread.h>
  48. #include <linux/seq_file.h>
  49. #include <linux/syscalls.h>
  50. #include <linux/times.h>
  51. #include <linux/tsacct_kern.h>
  52. #include <linux/kprobes.h>
  53. #include <linux/delayacct.h>
  54. #include <asm/tlb.h>
  55. #include <asm/unistd.h>
  56. /*
  57. * Convert user-nice values [ -20 ... 0 ... 19 ]
  58. * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
  59. * and back.
  60. */
  61. #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
  62. #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
  63. #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
  64. /*
  65. * 'User priority' is the nice value converted to something we
  66. * can work with better when scaling various scheduler parameters,
  67. * it's a [ 0 ... 39 ] range.
  68. */
  69. #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
  70. #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
  71. #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
  72. /*
  73. * Some helpers for converting nanosecond timing to jiffy resolution
  74. */
  75. #define NS_TO_JIFFIES(TIME) ((TIME) / (1000000000 / HZ))
  76. #define JIFFIES_TO_NS(TIME) ((TIME) * (1000000000 / HZ))
  77. /*
  78. * These are the 'tuning knobs' of the scheduler:
  79. *
  80. * Minimum timeslice is 5 msecs (or 1 jiffy, whichever is larger),
  81. * default timeslice is 100 msecs, maximum timeslice is 800 msecs.
  82. * Timeslices get refilled after they expire.
  83. */
  84. #define MIN_TIMESLICE max(5 * HZ / 1000, 1)
  85. #define DEF_TIMESLICE (100 * HZ / 1000)
  86. #define ON_RUNQUEUE_WEIGHT 30
  87. #define CHILD_PENALTY 95
  88. #define PARENT_PENALTY 100
  89. #define EXIT_WEIGHT 3
  90. #define PRIO_BONUS_RATIO 25
  91. #define MAX_BONUS (MAX_USER_PRIO * PRIO_BONUS_RATIO / 100)
  92. #define INTERACTIVE_DELTA 2
  93. #define MAX_SLEEP_AVG (DEF_TIMESLICE * MAX_BONUS)
  94. #define STARVATION_LIMIT (MAX_SLEEP_AVG)
  95. #define NS_MAX_SLEEP_AVG (JIFFIES_TO_NS(MAX_SLEEP_AVG))
  96. /*
  97. * If a task is 'interactive' then we reinsert it in the active
  98. * array after it has expired its current timeslice. (it will not
  99. * continue to run immediately, it will still roundrobin with
  100. * other interactive tasks.)
  101. *
  102. * This part scales the interactivity limit depending on niceness.
  103. *
  104. * We scale it linearly, offset by the INTERACTIVE_DELTA delta.
  105. * Here are a few examples of different nice levels:
  106. *
  107. * TASK_INTERACTIVE(-20): [1,1,1,1,1,1,1,1,1,0,0]
  108. * TASK_INTERACTIVE(-10): [1,1,1,1,1,1,1,0,0,0,0]
  109. * TASK_INTERACTIVE( 0): [1,1,1,1,0,0,0,0,0,0,0]
  110. * TASK_INTERACTIVE( 10): [1,1,0,0,0,0,0,0,0,0,0]
  111. * TASK_INTERACTIVE( 19): [0,0,0,0,0,0,0,0,0,0,0]
  112. *
  113. * (the X axis represents the possible -5 ... 0 ... +5 dynamic
  114. * priority range a task can explore, a value of '1' means the
  115. * task is rated interactive.)
  116. *
  117. * Ie. nice +19 tasks can never get 'interactive' enough to be
  118. * reinserted into the active array. And only heavily CPU-hog nice -20
  119. * tasks will be expired. Default nice 0 tasks are somewhere between,
  120. * it takes some effort for them to get interactive, but it's not
  121. * too hard.
  122. */
  123. #define CURRENT_BONUS(p) \
  124. (NS_TO_JIFFIES((p)->sleep_avg) * MAX_BONUS / \
  125. MAX_SLEEP_AVG)
  126. #define GRANULARITY (10 * HZ / 1000 ? : 1)
  127. #ifdef CONFIG_SMP
  128. #define TIMESLICE_GRANULARITY(p) (GRANULARITY * \
  129. (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)) * \
  130. num_online_cpus())
  131. #else
  132. #define TIMESLICE_GRANULARITY(p) (GRANULARITY * \
  133. (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)))
  134. #endif
  135. #define SCALE(v1,v1_max,v2_max) \
  136. (v1) * (v2_max) / (v1_max)
  137. #define DELTA(p) \
  138. (SCALE(TASK_NICE(p) + 20, 40, MAX_BONUS) - 20 * MAX_BONUS / 40 + \
  139. INTERACTIVE_DELTA)
  140. #define TASK_INTERACTIVE(p) \
  141. ((p)->prio <= (p)->static_prio - DELTA(p))
  142. #define INTERACTIVE_SLEEP(p) \
  143. (JIFFIES_TO_NS(MAX_SLEEP_AVG * \
  144. (MAX_BONUS / 2 + DELTA((p)) + 1) / MAX_BONUS - 1))
  145. #define TASK_PREEMPTS_CURR(p, rq) \
  146. ((p)->prio < (rq)->curr->prio)
  147. #define SCALE_PRIO(x, prio) \
  148. max(x * (MAX_PRIO - prio) / (MAX_USER_PRIO / 2), MIN_TIMESLICE)
  149. static unsigned int static_prio_timeslice(int static_prio)
  150. {
  151. if (static_prio < NICE_TO_PRIO(0))
  152. return SCALE_PRIO(DEF_TIMESLICE * 4, static_prio);
  153. else
  154. return SCALE_PRIO(DEF_TIMESLICE, static_prio);
  155. }
  156. /*
  157. * task_timeslice() scales user-nice values [ -20 ... 0 ... 19 ]
  158. * to time slice values: [800ms ... 100ms ... 5ms]
  159. *
  160. * The higher a thread's priority, the bigger timeslices
  161. * it gets during one round of execution. But even the lowest
  162. * priority thread gets MIN_TIMESLICE worth of execution time.
  163. */
  164. static inline unsigned int task_timeslice(struct task_struct *p)
  165. {
  166. return static_prio_timeslice(p->static_prio);
  167. }
  168. /*
  169. * These are the runqueue data structures:
  170. */
  171. struct prio_array {
  172. unsigned int nr_active;
  173. DECLARE_BITMAP(bitmap, MAX_PRIO+1); /* include 1 bit for delimiter */
  174. struct list_head queue[MAX_PRIO];
  175. };
  176. /*
  177. * This is the main, per-CPU runqueue data structure.
  178. *
  179. * Locking rule: those places that want to lock multiple runqueues
  180. * (such as the load balancing or the thread migration code), lock
  181. * acquire operations must be ordered by ascending &runqueue.
  182. */
  183. struct rq {
  184. spinlock_t lock;
  185. /*
  186. * nr_running and cpu_load should be in the same cacheline because
  187. * remote CPUs use both these fields when doing load calculation.
  188. */
  189. unsigned long nr_running;
  190. unsigned long raw_weighted_load;
  191. #ifdef CONFIG_SMP
  192. unsigned long cpu_load[3];
  193. #endif
  194. unsigned long long nr_switches;
  195. /*
  196. * This is part of a global counter where only the total sum
  197. * over all CPUs matters. A task can increase this counter on
  198. * one CPU and if it got migrated afterwards it may decrease
  199. * it on another CPU. Always updated under the runqueue lock:
  200. */
  201. unsigned long nr_uninterruptible;
  202. unsigned long expired_timestamp;
  203. /* Cached timestamp set by update_cpu_clock() */
  204. unsigned long long most_recent_timestamp;
  205. struct task_struct *curr, *idle;
  206. unsigned long next_balance;
  207. struct mm_struct *prev_mm;
  208. struct prio_array *active, *expired, arrays[2];
  209. int best_expired_prio;
  210. atomic_t nr_iowait;
  211. #ifdef CONFIG_SMP
  212. struct sched_domain *sd;
  213. /* For active balancing */
  214. int active_balance;
  215. int push_cpu;
  216. int cpu; /* cpu of this runqueue */
  217. struct task_struct *migration_thread;
  218. struct list_head migration_queue;
  219. #endif
  220. #ifdef CONFIG_SCHEDSTATS
  221. /* latency stats */
  222. struct sched_info rq_sched_info;
  223. /* sys_sched_yield() stats */
  224. unsigned long yld_exp_empty;
  225. unsigned long yld_act_empty;
  226. unsigned long yld_both_empty;
  227. unsigned long yld_cnt;
  228. /* schedule() stats */
  229. unsigned long sched_switch;
  230. unsigned long sched_cnt;
  231. unsigned long sched_goidle;
  232. /* try_to_wake_up() stats */
  233. unsigned long ttwu_cnt;
  234. unsigned long ttwu_local;
  235. #endif
  236. struct lock_class_key rq_lock_key;
  237. };
  238. static DEFINE_PER_CPU(struct rq, runqueues);
  239. static inline int cpu_of(struct rq *rq)
  240. {
  241. #ifdef CONFIG_SMP
  242. return rq->cpu;
  243. #else
  244. return 0;
  245. #endif
  246. }
  247. /*
  248. * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
  249. * See detach_destroy_domains: synchronize_sched for details.
  250. *
  251. * The domain tree of any CPU may only be accessed from within
  252. * preempt-disabled sections.
  253. */
  254. #define for_each_domain(cpu, __sd) \
  255. for (__sd = rcu_dereference(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
  256. #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
  257. #define this_rq() (&__get_cpu_var(runqueues))
  258. #define task_rq(p) cpu_rq(task_cpu(p))
  259. #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
  260. #ifndef prepare_arch_switch
  261. # define prepare_arch_switch(next) do { } while (0)
  262. #endif
  263. #ifndef finish_arch_switch
  264. # define finish_arch_switch(prev) do { } while (0)
  265. #endif
  266. #ifndef __ARCH_WANT_UNLOCKED_CTXSW
  267. static inline int task_running(struct rq *rq, struct task_struct *p)
  268. {
  269. return rq->curr == p;
  270. }
  271. static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
  272. {
  273. }
  274. static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
  275. {
  276. #ifdef CONFIG_DEBUG_SPINLOCK
  277. /* this is a valid case when another task releases the spinlock */
  278. rq->lock.owner = current;
  279. #endif
  280. /*
  281. * If we are tracking spinlock dependencies then we have to
  282. * fix up the runqueue lock - which gets 'carried over' from
  283. * prev into current:
  284. */
  285. spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
  286. spin_unlock_irq(&rq->lock);
  287. }
  288. #else /* __ARCH_WANT_UNLOCKED_CTXSW */
  289. static inline int task_running(struct rq *rq, struct task_struct *p)
  290. {
  291. #ifdef CONFIG_SMP
  292. return p->oncpu;
  293. #else
  294. return rq->curr == p;
  295. #endif
  296. }
  297. static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
  298. {
  299. #ifdef CONFIG_SMP
  300. /*
  301. * We can optimise this out completely for !SMP, because the
  302. * SMP rebalancing from interrupt is the only thing that cares
  303. * here.
  304. */
  305. next->oncpu = 1;
  306. #endif
  307. #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
  308. spin_unlock_irq(&rq->lock);
  309. #else
  310. spin_unlock(&rq->lock);
  311. #endif
  312. }
  313. static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
  314. {
  315. #ifdef CONFIG_SMP
  316. /*
  317. * After ->oncpu is cleared, the task can be moved to a different CPU.
  318. * We must ensure this doesn't happen until the switch is completely
  319. * finished.
  320. */
  321. smp_wmb();
  322. prev->oncpu = 0;
  323. #endif
  324. #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
  325. local_irq_enable();
  326. #endif
  327. }
  328. #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
  329. /*
  330. * __task_rq_lock - lock the runqueue a given task resides on.
  331. * Must be called interrupts disabled.
  332. */
  333. static inline struct rq *__task_rq_lock(struct task_struct *p)
  334. __acquires(rq->lock)
  335. {
  336. struct rq *rq;
  337. repeat_lock_task:
  338. rq = task_rq(p);
  339. spin_lock(&rq->lock);
  340. if (unlikely(rq != task_rq(p))) {
  341. spin_unlock(&rq->lock);
  342. goto repeat_lock_task;
  343. }
  344. return rq;
  345. }
  346. /*
  347. * task_rq_lock - lock the runqueue a given task resides on and disable
  348. * interrupts. Note the ordering: we can safely lookup the task_rq without
  349. * explicitly disabling preemption.
  350. */
  351. static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
  352. __acquires(rq->lock)
  353. {
  354. struct rq *rq;
  355. repeat_lock_task:
  356. local_irq_save(*flags);
  357. rq = task_rq(p);
  358. spin_lock(&rq->lock);
  359. if (unlikely(rq != task_rq(p))) {
  360. spin_unlock_irqrestore(&rq->lock, *flags);
  361. goto repeat_lock_task;
  362. }
  363. return rq;
  364. }
  365. static inline void __task_rq_unlock(struct rq *rq)
  366. __releases(rq->lock)
  367. {
  368. spin_unlock(&rq->lock);
  369. }
  370. static inline void task_rq_unlock(struct rq *rq, unsigned long *flags)
  371. __releases(rq->lock)
  372. {
  373. spin_unlock_irqrestore(&rq->lock, *flags);
  374. }
  375. #ifdef CONFIG_SCHEDSTATS
  376. /*
  377. * bump this up when changing the output format or the meaning of an existing
  378. * format, so that tools can adapt (or abort)
  379. */
  380. #define SCHEDSTAT_VERSION 14
  381. static int show_schedstat(struct seq_file *seq, void *v)
  382. {
  383. int cpu;
  384. seq_printf(seq, "version %d\n", SCHEDSTAT_VERSION);
  385. seq_printf(seq, "timestamp %lu\n", jiffies);
  386. for_each_online_cpu(cpu) {
  387. struct rq *rq = cpu_rq(cpu);
  388. #ifdef CONFIG_SMP
  389. struct sched_domain *sd;
  390. int dcnt = 0;
  391. #endif
  392. /* runqueue-specific stats */
  393. seq_printf(seq,
  394. "cpu%d %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
  395. cpu, rq->yld_both_empty,
  396. rq->yld_act_empty, rq->yld_exp_empty, rq->yld_cnt,
  397. rq->sched_switch, rq->sched_cnt, rq->sched_goidle,
  398. rq->ttwu_cnt, rq->ttwu_local,
  399. rq->rq_sched_info.cpu_time,
  400. rq->rq_sched_info.run_delay, rq->rq_sched_info.pcnt);
  401. seq_printf(seq, "\n");
  402. #ifdef CONFIG_SMP
  403. /* domain-specific stats */
  404. preempt_disable();
  405. for_each_domain(cpu, sd) {
  406. enum idle_type itype;
  407. char mask_str[NR_CPUS];
  408. cpumask_scnprintf(mask_str, NR_CPUS, sd->span);
  409. seq_printf(seq, "domain%d %s", dcnt++, mask_str);
  410. for (itype = SCHED_IDLE; itype < MAX_IDLE_TYPES;
  411. itype++) {
  412. seq_printf(seq, " %lu %lu %lu %lu %lu %lu %lu "
  413. "%lu",
  414. sd->lb_cnt[itype],
  415. sd->lb_balanced[itype],
  416. sd->lb_failed[itype],
  417. sd->lb_imbalance[itype],
  418. sd->lb_gained[itype],
  419. sd->lb_hot_gained[itype],
  420. sd->lb_nobusyq[itype],
  421. sd->lb_nobusyg[itype]);
  422. }
  423. seq_printf(seq, " %lu %lu %lu %lu %lu %lu %lu %lu %lu"
  424. " %lu %lu %lu\n",
  425. sd->alb_cnt, sd->alb_failed, sd->alb_pushed,
  426. sd->sbe_cnt, sd->sbe_balanced, sd->sbe_pushed,
  427. sd->sbf_cnt, sd->sbf_balanced, sd->sbf_pushed,
  428. sd->ttwu_wake_remote, sd->ttwu_move_affine,
  429. sd->ttwu_move_balance);
  430. }
  431. preempt_enable();
  432. #endif
  433. }
  434. return 0;
  435. }
  436. static int schedstat_open(struct inode *inode, struct file *file)
  437. {
  438. unsigned int size = PAGE_SIZE * (1 + num_online_cpus() / 32);
  439. char *buf = kmalloc(size, GFP_KERNEL);
  440. struct seq_file *m;
  441. int res;
  442. if (!buf)
  443. return -ENOMEM;
  444. res = single_open(file, show_schedstat, NULL);
  445. if (!res) {
  446. m = file->private_data;
  447. m->buf = buf;
  448. m->size = size;
  449. } else
  450. kfree(buf);
  451. return res;
  452. }
  453. const struct file_operations proc_schedstat_operations = {
  454. .open = schedstat_open,
  455. .read = seq_read,
  456. .llseek = seq_lseek,
  457. .release = single_release,
  458. };
  459. /*
  460. * Expects runqueue lock to be held for atomicity of update
  461. */
  462. static inline void
  463. rq_sched_info_arrive(struct rq *rq, unsigned long delta_jiffies)
  464. {
  465. if (rq) {
  466. rq->rq_sched_info.run_delay += delta_jiffies;
  467. rq->rq_sched_info.pcnt++;
  468. }
  469. }
  470. /*
  471. * Expects runqueue lock to be held for atomicity of update
  472. */
  473. static inline void
  474. rq_sched_info_depart(struct rq *rq, unsigned long delta_jiffies)
  475. {
  476. if (rq)
  477. rq->rq_sched_info.cpu_time += delta_jiffies;
  478. }
  479. # define schedstat_inc(rq, field) do { (rq)->field++; } while (0)
  480. # define schedstat_add(rq, field, amt) do { (rq)->field += (amt); } while (0)
  481. #else /* !CONFIG_SCHEDSTATS */
  482. static inline void
  483. rq_sched_info_arrive(struct rq *rq, unsigned long delta_jiffies)
  484. {}
  485. static inline void
  486. rq_sched_info_depart(struct rq *rq, unsigned long delta_jiffies)
  487. {}
  488. # define schedstat_inc(rq, field) do { } while (0)
  489. # define schedstat_add(rq, field, amt) do { } while (0)
  490. #endif
  491. /*
  492. * this_rq_lock - lock this runqueue and disable interrupts.
  493. */
  494. static inline struct rq *this_rq_lock(void)
  495. __acquires(rq->lock)
  496. {
  497. struct rq *rq;
  498. local_irq_disable();
  499. rq = this_rq();
  500. spin_lock(&rq->lock);
  501. return rq;
  502. }
  503. #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
  504. /*
  505. * Called when a process is dequeued from the active array and given
  506. * the cpu. We should note that with the exception of interactive
  507. * tasks, the expired queue will become the active queue after the active
  508. * queue is empty, without explicitly dequeuing and requeuing tasks in the
  509. * expired queue. (Interactive tasks may be requeued directly to the
  510. * active queue, thus delaying tasks in the expired queue from running;
  511. * see scheduler_tick()).
  512. *
  513. * This function is only called from sched_info_arrive(), rather than
  514. * dequeue_task(). Even though a task may be queued and dequeued multiple
  515. * times as it is shuffled about, we're really interested in knowing how
  516. * long it was from the *first* time it was queued to the time that it
  517. * finally hit a cpu.
  518. */
  519. static inline void sched_info_dequeued(struct task_struct *t)
  520. {
  521. t->sched_info.last_queued = 0;
  522. }
  523. /*
  524. * Called when a task finally hits the cpu. We can now calculate how
  525. * long it was waiting to run. We also note when it began so that we
  526. * can keep stats on how long its timeslice is.
  527. */
  528. static void sched_info_arrive(struct task_struct *t)
  529. {
  530. unsigned long now = jiffies, delta_jiffies = 0;
  531. if (t->sched_info.last_queued)
  532. delta_jiffies = now - t->sched_info.last_queued;
  533. sched_info_dequeued(t);
  534. t->sched_info.run_delay += delta_jiffies;
  535. t->sched_info.last_arrival = now;
  536. t->sched_info.pcnt++;
  537. rq_sched_info_arrive(task_rq(t), delta_jiffies);
  538. }
  539. /*
  540. * Called when a process is queued into either the active or expired
  541. * array. The time is noted and later used to determine how long we
  542. * had to wait for us to reach the cpu. Since the expired queue will
  543. * become the active queue after active queue is empty, without dequeuing
  544. * and requeuing any tasks, we are interested in queuing to either. It
  545. * is unusual but not impossible for tasks to be dequeued and immediately
  546. * requeued in the same or another array: this can happen in sched_yield(),
  547. * set_user_nice(), and even load_balance() as it moves tasks from runqueue
  548. * to runqueue.
  549. *
  550. * This function is only called from enqueue_task(), but also only updates
  551. * the timestamp if it is already not set. It's assumed that
  552. * sched_info_dequeued() will clear that stamp when appropriate.
  553. */
  554. static inline void sched_info_queued(struct task_struct *t)
  555. {
  556. if (unlikely(sched_info_on()))
  557. if (!t->sched_info.last_queued)
  558. t->sched_info.last_queued = jiffies;
  559. }
  560. /*
  561. * Called when a process ceases being the active-running process, either
  562. * voluntarily or involuntarily. Now we can calculate how long we ran.
  563. */
  564. static inline void sched_info_depart(struct task_struct *t)
  565. {
  566. unsigned long delta_jiffies = jiffies - t->sched_info.last_arrival;
  567. t->sched_info.cpu_time += delta_jiffies;
  568. rq_sched_info_depart(task_rq(t), delta_jiffies);
  569. }
  570. /*
  571. * Called when tasks are switched involuntarily due, typically, to expiring
  572. * their time slice. (This may also be called when switching to or from
  573. * the idle task.) We are only called when prev != next.
  574. */
  575. static inline void
  576. __sched_info_switch(struct task_struct *prev, struct task_struct *next)
  577. {
  578. struct rq *rq = task_rq(prev);
  579. /*
  580. * prev now departs the cpu. It's not interesting to record
  581. * stats about how efficient we were at scheduling the idle
  582. * process, however.
  583. */
  584. if (prev != rq->idle)
  585. sched_info_depart(prev);
  586. if (next != rq->idle)
  587. sched_info_arrive(next);
  588. }
  589. static inline void
  590. sched_info_switch(struct task_struct *prev, struct task_struct *next)
  591. {
  592. if (unlikely(sched_info_on()))
  593. __sched_info_switch(prev, next);
  594. }
  595. #else
  596. #define sched_info_queued(t) do { } while (0)
  597. #define sched_info_switch(t, next) do { } while (0)
  598. #endif /* CONFIG_SCHEDSTATS || CONFIG_TASK_DELAY_ACCT */
  599. /*
  600. * Adding/removing a task to/from a priority array:
  601. */
  602. static void dequeue_task(struct task_struct *p, struct prio_array *array)
  603. {
  604. array->nr_active--;
  605. list_del(&p->run_list);
  606. if (list_empty(array->queue + p->prio))
  607. __clear_bit(p->prio, array->bitmap);
  608. }
  609. static void enqueue_task(struct task_struct *p, struct prio_array *array)
  610. {
  611. sched_info_queued(p);
  612. list_add_tail(&p->run_list, array->queue + p->prio);
  613. __set_bit(p->prio, array->bitmap);
  614. array->nr_active++;
  615. p->array = array;
  616. }
  617. /*
  618. * Put task to the end of the run list without the overhead of dequeue
  619. * followed by enqueue.
  620. */
  621. static void requeue_task(struct task_struct *p, struct prio_array *array)
  622. {
  623. list_move_tail(&p->run_list, array->queue + p->prio);
  624. }
  625. static inline void
  626. enqueue_task_head(struct task_struct *p, struct prio_array *array)
  627. {
  628. list_add(&p->run_list, array->queue + p->prio);
  629. __set_bit(p->prio, array->bitmap);
  630. array->nr_active++;
  631. p->array = array;
  632. }
  633. /*
  634. * __normal_prio - return the priority that is based on the static
  635. * priority but is modified by bonuses/penalties.
  636. *
  637. * We scale the actual sleep average [0 .... MAX_SLEEP_AVG]
  638. * into the -5 ... 0 ... +5 bonus/penalty range.
  639. *
  640. * We use 25% of the full 0...39 priority range so that:
  641. *
  642. * 1) nice +19 interactive tasks do not preempt nice 0 CPU hogs.
  643. * 2) nice -20 CPU hogs do not get preempted by nice 0 tasks.
  644. *
  645. * Both properties are important to certain workloads.
  646. */
  647. static inline int __normal_prio(struct task_struct *p)
  648. {
  649. int bonus, prio;
  650. bonus = CURRENT_BONUS(p) - MAX_BONUS / 2;
  651. prio = p->static_prio - bonus;
  652. if (prio < MAX_RT_PRIO)
  653. prio = MAX_RT_PRIO;
  654. if (prio > MAX_PRIO-1)
  655. prio = MAX_PRIO-1;
  656. return prio;
  657. }
  658. /*
  659. * To aid in avoiding the subversion of "niceness" due to uneven distribution
  660. * of tasks with abnormal "nice" values across CPUs the contribution that
  661. * each task makes to its run queue's load is weighted according to its
  662. * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
  663. * scaled version of the new time slice allocation that they receive on time
  664. * slice expiry etc.
  665. */
  666. /*
  667. * Assume: static_prio_timeslice(NICE_TO_PRIO(0)) == DEF_TIMESLICE
  668. * If static_prio_timeslice() is ever changed to break this assumption then
  669. * this code will need modification
  670. */
  671. #define TIME_SLICE_NICE_ZERO DEF_TIMESLICE
  672. #define LOAD_WEIGHT(lp) \
  673. (((lp) * SCHED_LOAD_SCALE) / TIME_SLICE_NICE_ZERO)
  674. #define PRIO_TO_LOAD_WEIGHT(prio) \
  675. LOAD_WEIGHT(static_prio_timeslice(prio))
  676. #define RTPRIO_TO_LOAD_WEIGHT(rp) \
  677. (PRIO_TO_LOAD_WEIGHT(MAX_RT_PRIO) + LOAD_WEIGHT(rp))
  678. static void set_load_weight(struct task_struct *p)
  679. {
  680. if (has_rt_policy(p)) {
  681. #ifdef CONFIG_SMP
  682. if (p == task_rq(p)->migration_thread)
  683. /*
  684. * The migration thread does the actual balancing.
  685. * Giving its load any weight will skew balancing
  686. * adversely.
  687. */
  688. p->load_weight = 0;
  689. else
  690. #endif
  691. p->load_weight = RTPRIO_TO_LOAD_WEIGHT(p->rt_priority);
  692. } else
  693. p->load_weight = PRIO_TO_LOAD_WEIGHT(p->static_prio);
  694. }
  695. static inline void
  696. inc_raw_weighted_load(struct rq *rq, const struct task_struct *p)
  697. {
  698. rq->raw_weighted_load += p->load_weight;
  699. }
  700. static inline void
  701. dec_raw_weighted_load(struct rq *rq, const struct task_struct *p)
  702. {
  703. rq->raw_weighted_load -= p->load_weight;
  704. }
  705. static inline void inc_nr_running(struct task_struct *p, struct rq *rq)
  706. {
  707. rq->nr_running++;
  708. inc_raw_weighted_load(rq, p);
  709. }
  710. static inline void dec_nr_running(struct task_struct *p, struct rq *rq)
  711. {
  712. rq->nr_running--;
  713. dec_raw_weighted_load(rq, p);
  714. }
  715. /*
  716. * Calculate the expected normal priority: i.e. priority
  717. * without taking RT-inheritance into account. Might be
  718. * boosted by interactivity modifiers. Changes upon fork,
  719. * setprio syscalls, and whenever the interactivity
  720. * estimator recalculates.
  721. */
  722. static inline int normal_prio(struct task_struct *p)
  723. {
  724. int prio;
  725. if (has_rt_policy(p))
  726. prio = MAX_RT_PRIO-1 - p->rt_priority;
  727. else
  728. prio = __normal_prio(p);
  729. return prio;
  730. }
  731. /*
  732. * Calculate the current priority, i.e. the priority
  733. * taken into account by the scheduler. This value might
  734. * be boosted by RT tasks, or might be boosted by
  735. * interactivity modifiers. Will be RT if the task got
  736. * RT-boosted. If not then it returns p->normal_prio.
  737. */
  738. static int effective_prio(struct task_struct *p)
  739. {
  740. p->normal_prio = normal_prio(p);
  741. /*
  742. * If we are RT tasks or we were boosted to RT priority,
  743. * keep the priority unchanged. Otherwise, update priority
  744. * to the normal priority:
  745. */
  746. if (!rt_prio(p->prio))
  747. return p->normal_prio;
  748. return p->prio;
  749. }
  750. /*
  751. * __activate_task - move a task to the runqueue.
  752. */
  753. static void __activate_task(struct task_struct *p, struct rq *rq)
  754. {
  755. struct prio_array *target = rq->active;
  756. if (batch_task(p))
  757. target = rq->expired;
  758. enqueue_task(p, target);
  759. inc_nr_running(p, rq);
  760. }
  761. /*
  762. * __activate_idle_task - move idle task to the _front_ of runqueue.
  763. */
  764. static inline void __activate_idle_task(struct task_struct *p, struct rq *rq)
  765. {
  766. enqueue_task_head(p, rq->active);
  767. inc_nr_running(p, rq);
  768. }
  769. /*
  770. * Recalculate p->normal_prio and p->prio after having slept,
  771. * updating the sleep-average too:
  772. */
  773. static int recalc_task_prio(struct task_struct *p, unsigned long long now)
  774. {
  775. /* Caller must always ensure 'now >= p->timestamp' */
  776. unsigned long sleep_time = now - p->timestamp;
  777. if (batch_task(p))
  778. sleep_time = 0;
  779. if (likely(sleep_time > 0)) {
  780. /*
  781. * This ceiling is set to the lowest priority that would allow
  782. * a task to be reinserted into the active array on timeslice
  783. * completion.
  784. */
  785. unsigned long ceiling = INTERACTIVE_SLEEP(p);
  786. if (p->mm && sleep_time > ceiling && p->sleep_avg < ceiling) {
  787. /*
  788. * Prevents user tasks from achieving best priority
  789. * with one single large enough sleep.
  790. */
  791. p->sleep_avg = ceiling;
  792. /*
  793. * Using INTERACTIVE_SLEEP() as a ceiling places a
  794. * nice(0) task 1ms sleep away from promotion, and
  795. * gives it 700ms to round-robin with no chance of
  796. * being demoted. This is more than generous, so
  797. * mark this sleep as non-interactive to prevent the
  798. * on-runqueue bonus logic from intervening should
  799. * this task not receive cpu immediately.
  800. */
  801. p->sleep_type = SLEEP_NONINTERACTIVE;
  802. } else {
  803. /*
  804. * Tasks waking from uninterruptible sleep are
  805. * limited in their sleep_avg rise as they
  806. * are likely to be waiting on I/O
  807. */
  808. if (p->sleep_type == SLEEP_NONINTERACTIVE && p->mm) {
  809. if (p->sleep_avg >= ceiling)
  810. sleep_time = 0;
  811. else if (p->sleep_avg + sleep_time >=
  812. ceiling) {
  813. p->sleep_avg = ceiling;
  814. sleep_time = 0;
  815. }
  816. }
  817. /*
  818. * This code gives a bonus to interactive tasks.
  819. *
  820. * The boost works by updating the 'average sleep time'
  821. * value here, based on ->timestamp. The more time a
  822. * task spends sleeping, the higher the average gets -
  823. * and the higher the priority boost gets as well.
  824. */
  825. p->sleep_avg += sleep_time;
  826. }
  827. if (p->sleep_avg > NS_MAX_SLEEP_AVG)
  828. p->sleep_avg = NS_MAX_SLEEP_AVG;
  829. }
  830. return effective_prio(p);
  831. }
  832. /*
  833. * activate_task - move a task to the runqueue and do priority recalculation
  834. *
  835. * Update all the scheduling statistics stuff. (sleep average
  836. * calculation, priority modifiers, etc.)
  837. */
  838. static void activate_task(struct task_struct *p, struct rq *rq, int local)
  839. {
  840. unsigned long long now;
  841. if (rt_task(p))
  842. goto out;
  843. now = sched_clock();
  844. #ifdef CONFIG_SMP
  845. if (!local) {
  846. /* Compensate for drifting sched_clock */
  847. struct rq *this_rq = this_rq();
  848. now = (now - this_rq->most_recent_timestamp)
  849. + rq->most_recent_timestamp;
  850. }
  851. #endif
  852. /*
  853. * Sleep time is in units of nanosecs, so shift by 20 to get a
  854. * milliseconds-range estimation of the amount of time that the task
  855. * spent sleeping:
  856. */
  857. if (unlikely(prof_on == SLEEP_PROFILING)) {
  858. if (p->state == TASK_UNINTERRUPTIBLE)
  859. profile_hits(SLEEP_PROFILING, (void *)get_wchan(p),
  860. (now - p->timestamp) >> 20);
  861. }
  862. p->prio = recalc_task_prio(p, now);
  863. /*
  864. * This checks to make sure it's not an uninterruptible task
  865. * that is now waking up.
  866. */
  867. if (p->sleep_type == SLEEP_NORMAL) {
  868. /*
  869. * Tasks which were woken up by interrupts (ie. hw events)
  870. * are most likely of interactive nature. So we give them
  871. * the credit of extending their sleep time to the period
  872. * of time they spend on the runqueue, waiting for execution
  873. * on a CPU, first time around:
  874. */
  875. if (in_interrupt())
  876. p->sleep_type = SLEEP_INTERRUPTED;
  877. else {
  878. /*
  879. * Normal first-time wakeups get a credit too for
  880. * on-runqueue time, but it will be weighted down:
  881. */
  882. p->sleep_type = SLEEP_INTERACTIVE;
  883. }
  884. }
  885. p->timestamp = now;
  886. out:
  887. __activate_task(p, rq);
  888. }
  889. /*
  890. * deactivate_task - remove a task from the runqueue.
  891. */
  892. static void deactivate_task(struct task_struct *p, struct rq *rq)
  893. {
  894. dec_nr_running(p, rq);
  895. dequeue_task(p, p->array);
  896. p->array = NULL;
  897. }
  898. /*
  899. * resched_task - mark a task 'to be rescheduled now'.
  900. *
  901. * On UP this means the setting of the need_resched flag, on SMP it
  902. * might also involve a cross-CPU call to trigger the scheduler on
  903. * the target CPU.
  904. */
  905. #ifdef CONFIG_SMP
  906. #ifndef tsk_is_polling
  907. #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
  908. #endif
  909. static void resched_task(struct task_struct *p)
  910. {
  911. int cpu;
  912. assert_spin_locked(&task_rq(p)->lock);
  913. if (unlikely(test_tsk_thread_flag(p, TIF_NEED_RESCHED)))
  914. return;
  915. set_tsk_thread_flag(p, TIF_NEED_RESCHED);
  916. cpu = task_cpu(p);
  917. if (cpu == smp_processor_id())
  918. return;
  919. /* NEED_RESCHED must be visible before we test polling */
  920. smp_mb();
  921. if (!tsk_is_polling(p))
  922. smp_send_reschedule(cpu);
  923. }
  924. #else
  925. static inline void resched_task(struct task_struct *p)
  926. {
  927. assert_spin_locked(&task_rq(p)->lock);
  928. set_tsk_need_resched(p);
  929. }
  930. #endif
  931. /**
  932. * task_curr - is this task currently executing on a CPU?
  933. * @p: the task in question.
  934. */
  935. inline int task_curr(const struct task_struct *p)
  936. {
  937. return cpu_curr(task_cpu(p)) == p;
  938. }
  939. /* Used instead of source_load when we know the type == 0 */
  940. unsigned long weighted_cpuload(const int cpu)
  941. {
  942. return cpu_rq(cpu)->raw_weighted_load;
  943. }
  944. #ifdef CONFIG_SMP
  945. struct migration_req {
  946. struct list_head list;
  947. struct task_struct *task;
  948. int dest_cpu;
  949. struct completion done;
  950. };
  951. /*
  952. * The task's runqueue lock must be held.
  953. * Returns true if you have to wait for migration thread.
  954. */
  955. static int
  956. migrate_task(struct task_struct *p, int dest_cpu, struct migration_req *req)
  957. {
  958. struct rq *rq = task_rq(p);
  959. /*
  960. * If the task is not on a runqueue (and not running), then
  961. * it is sufficient to simply update the task's cpu field.
  962. */
  963. if (!p->array && !task_running(rq, p)) {
  964. set_task_cpu(p, dest_cpu);
  965. return 0;
  966. }
  967. init_completion(&req->done);
  968. req->task = p;
  969. req->dest_cpu = dest_cpu;
  970. list_add(&req->list, &rq->migration_queue);
  971. return 1;
  972. }
  973. /*
  974. * wait_task_inactive - wait for a thread to unschedule.
  975. *
  976. * The caller must ensure that the task *will* unschedule sometime soon,
  977. * else this function might spin for a *long* time. This function can't
  978. * be called with interrupts off, or it may introduce deadlock with
  979. * smp_call_function() if an IPI is sent by the same process we are
  980. * waiting to become inactive.
  981. */
  982. void wait_task_inactive(struct task_struct *p)
  983. {
  984. unsigned long flags;
  985. struct rq *rq;
  986. int preempted;
  987. repeat:
  988. rq = task_rq_lock(p, &flags);
  989. /* Must be off runqueue entirely, not preempted. */
  990. if (unlikely(p->array || task_running(rq, p))) {
  991. /* If it's preempted, we yield. It could be a while. */
  992. preempted = !task_running(rq, p);
  993. task_rq_unlock(rq, &flags);
  994. cpu_relax();
  995. if (preempted)
  996. yield();
  997. goto repeat;
  998. }
  999. task_rq_unlock(rq, &flags);
  1000. }
  1001. /***
  1002. * kick_process - kick a running thread to enter/exit the kernel
  1003. * @p: the to-be-kicked thread
  1004. *
  1005. * Cause a process which is running on another CPU to enter
  1006. * kernel-mode, without any delay. (to get signals handled.)
  1007. *
  1008. * NOTE: this function doesnt have to take the runqueue lock,
  1009. * because all it wants to ensure is that the remote task enters
  1010. * the kernel. If the IPI races and the task has been migrated
  1011. * to another CPU then no harm is done and the purpose has been
  1012. * achieved as well.
  1013. */
  1014. void kick_process(struct task_struct *p)
  1015. {
  1016. int cpu;
  1017. preempt_disable();
  1018. cpu = task_cpu(p);
  1019. if ((cpu != smp_processor_id()) && task_curr(p))
  1020. smp_send_reschedule(cpu);
  1021. preempt_enable();
  1022. }
  1023. /*
  1024. * Return a low guess at the load of a migration-source cpu weighted
  1025. * according to the scheduling class and "nice" value.
  1026. *
  1027. * We want to under-estimate the load of migration sources, to
  1028. * balance conservatively.
  1029. */
  1030. static inline unsigned long source_load(int cpu, int type)
  1031. {
  1032. struct rq *rq = cpu_rq(cpu);
  1033. if (type == 0)
  1034. return rq->raw_weighted_load;
  1035. return min(rq->cpu_load[type-1], rq->raw_weighted_load);
  1036. }
  1037. /*
  1038. * Return a high guess at the load of a migration-target cpu weighted
  1039. * according to the scheduling class and "nice" value.
  1040. */
  1041. static inline unsigned long target_load(int cpu, int type)
  1042. {
  1043. struct rq *rq = cpu_rq(cpu);
  1044. if (type == 0)
  1045. return rq->raw_weighted_load;
  1046. return max(rq->cpu_load[type-1], rq->raw_weighted_load);
  1047. }
  1048. /*
  1049. * Return the average load per task on the cpu's run queue
  1050. */
  1051. static inline unsigned long cpu_avg_load_per_task(int cpu)
  1052. {
  1053. struct rq *rq = cpu_rq(cpu);
  1054. unsigned long n = rq->nr_running;
  1055. return n ? rq->raw_weighted_load / n : SCHED_LOAD_SCALE;
  1056. }
  1057. /*
  1058. * find_idlest_group finds and returns the least busy CPU group within the
  1059. * domain.
  1060. */
  1061. static struct sched_group *
  1062. find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
  1063. {
  1064. struct sched_group *idlest = NULL, *this = NULL, *group = sd->groups;
  1065. unsigned long min_load = ULONG_MAX, this_load = 0;
  1066. int load_idx = sd->forkexec_idx;
  1067. int imbalance = 100 + (sd->imbalance_pct-100)/2;
  1068. do {
  1069. unsigned long load, avg_load;
  1070. int local_group;
  1071. int i;
  1072. /* Skip over this group if it has no CPUs allowed */
  1073. if (!cpus_intersects(group->cpumask, p->cpus_allowed))
  1074. goto nextgroup;
  1075. local_group = cpu_isset(this_cpu, group->cpumask);
  1076. /* Tally up the load of all CPUs in the group */
  1077. avg_load = 0;
  1078. for_each_cpu_mask(i, group->cpumask) {
  1079. /* Bias balancing toward cpus of our domain */
  1080. if (local_group)
  1081. load = source_load(i, load_idx);
  1082. else
  1083. load = target_load(i, load_idx);
  1084. avg_load += load;
  1085. }
  1086. /* Adjust by relative CPU power of the group */
  1087. avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
  1088. if (local_group) {
  1089. this_load = avg_load;
  1090. this = group;
  1091. } else if (avg_load < min_load) {
  1092. min_load = avg_load;
  1093. idlest = group;
  1094. }
  1095. nextgroup:
  1096. group = group->next;
  1097. } while (group != sd->groups);
  1098. if (!idlest || 100*this_load < imbalance*min_load)
  1099. return NULL;
  1100. return idlest;
  1101. }
  1102. /*
  1103. * find_idlest_cpu - find the idlest cpu among the cpus in group.
  1104. */
  1105. static int
  1106. find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
  1107. {
  1108. cpumask_t tmp;
  1109. unsigned long load, min_load = ULONG_MAX;
  1110. int idlest = -1;
  1111. int i;
  1112. /* Traverse only the allowed CPUs */
  1113. cpus_and(tmp, group->cpumask, p->cpus_allowed);
  1114. for_each_cpu_mask(i, tmp) {
  1115. load = weighted_cpuload(i);
  1116. if (load < min_load || (load == min_load && i == this_cpu)) {
  1117. min_load = load;
  1118. idlest = i;
  1119. }
  1120. }
  1121. return idlest;
  1122. }
  1123. /*
  1124. * sched_balance_self: balance the current task (running on cpu) in domains
  1125. * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
  1126. * SD_BALANCE_EXEC.
  1127. *
  1128. * Balance, ie. select the least loaded group.
  1129. *
  1130. * Returns the target CPU number, or the same CPU if no balancing is needed.
  1131. *
  1132. * preempt must be disabled.
  1133. */
  1134. static int sched_balance_self(int cpu, int flag)
  1135. {
  1136. struct task_struct *t = current;
  1137. struct sched_domain *tmp, *sd = NULL;
  1138. for_each_domain(cpu, tmp) {
  1139. /*
  1140. * If power savings logic is enabled for a domain, stop there.
  1141. */
  1142. if (tmp->flags & SD_POWERSAVINGS_BALANCE)
  1143. break;
  1144. if (tmp->flags & flag)
  1145. sd = tmp;
  1146. }
  1147. while (sd) {
  1148. cpumask_t span;
  1149. struct sched_group *group;
  1150. int new_cpu, weight;
  1151. if (!(sd->flags & flag)) {
  1152. sd = sd->child;
  1153. continue;
  1154. }
  1155. span = sd->span;
  1156. group = find_idlest_group(sd, t, cpu);
  1157. if (!group) {
  1158. sd = sd->child;
  1159. continue;
  1160. }
  1161. new_cpu = find_idlest_cpu(group, t, cpu);
  1162. if (new_cpu == -1 || new_cpu == cpu) {
  1163. /* Now try balancing at a lower domain level of cpu */
  1164. sd = sd->child;
  1165. continue;
  1166. }
  1167. /* Now try balancing at a lower domain level of new_cpu */
  1168. cpu = new_cpu;
  1169. sd = NULL;
  1170. weight = cpus_weight(span);
  1171. for_each_domain(cpu, tmp) {
  1172. if (weight <= cpus_weight(tmp->span))
  1173. break;
  1174. if (tmp->flags & flag)
  1175. sd = tmp;
  1176. }
  1177. /* while loop will break here if sd == NULL */
  1178. }
  1179. return cpu;
  1180. }
  1181. #endif /* CONFIG_SMP */
  1182. /*
  1183. * wake_idle() will wake a task on an idle cpu if task->cpu is
  1184. * not idle and an idle cpu is available. The span of cpus to
  1185. * search starts with cpus closest then further out as needed,
  1186. * so we always favor a closer, idle cpu.
  1187. *
  1188. * Returns the CPU we should wake onto.
  1189. */
  1190. #if defined(ARCH_HAS_SCHED_WAKE_IDLE)
  1191. static int wake_idle(int cpu, struct task_struct *p)
  1192. {
  1193. cpumask_t tmp;
  1194. struct sched_domain *sd;
  1195. int i;
  1196. if (idle_cpu(cpu))
  1197. return cpu;
  1198. for_each_domain(cpu, sd) {
  1199. if (sd->flags & SD_WAKE_IDLE) {
  1200. cpus_and(tmp, sd->span, p->cpus_allowed);
  1201. for_each_cpu_mask(i, tmp) {
  1202. if (idle_cpu(i))
  1203. return i;
  1204. }
  1205. }
  1206. else
  1207. break;
  1208. }
  1209. return cpu;
  1210. }
  1211. #else
  1212. static inline int wake_idle(int cpu, struct task_struct *p)
  1213. {
  1214. return cpu;
  1215. }
  1216. #endif
  1217. /***
  1218. * try_to_wake_up - wake up a thread
  1219. * @p: the to-be-woken-up thread
  1220. * @state: the mask of task states that can be woken
  1221. * @sync: do a synchronous wakeup?
  1222. *
  1223. * Put it on the run-queue if it's not already there. The "current"
  1224. * thread is always on the run-queue (except when the actual
  1225. * re-schedule is in progress), and as such you're allowed to do
  1226. * the simpler "current->state = TASK_RUNNING" to mark yourself
  1227. * runnable without the overhead of this.
  1228. *
  1229. * returns failure only if the task is already active.
  1230. */
  1231. static int try_to_wake_up(struct task_struct *p, unsigned int state, int sync)
  1232. {
  1233. int cpu, this_cpu, success = 0;
  1234. unsigned long flags;
  1235. long old_state;
  1236. struct rq *rq;
  1237. #ifdef CONFIG_SMP
  1238. struct sched_domain *sd, *this_sd = NULL;
  1239. unsigned long load, this_load;
  1240. int new_cpu;
  1241. #endif
  1242. rq = task_rq_lock(p, &flags);
  1243. old_state = p->state;
  1244. if (!(old_state & state))
  1245. goto out;
  1246. if (p->array)
  1247. goto out_running;
  1248. cpu = task_cpu(p);
  1249. this_cpu = smp_processor_id();
  1250. #ifdef CONFIG_SMP
  1251. if (unlikely(task_running(rq, p)))
  1252. goto out_activate;
  1253. new_cpu = cpu;
  1254. schedstat_inc(rq, ttwu_cnt);
  1255. if (cpu == this_cpu) {
  1256. schedstat_inc(rq, ttwu_local);
  1257. goto out_set_cpu;
  1258. }
  1259. for_each_domain(this_cpu, sd) {
  1260. if (cpu_isset(cpu, sd->span)) {
  1261. schedstat_inc(sd, ttwu_wake_remote);
  1262. this_sd = sd;
  1263. break;
  1264. }
  1265. }
  1266. if (unlikely(!cpu_isset(this_cpu, p->cpus_allowed)))
  1267. goto out_set_cpu;
  1268. /*
  1269. * Check for affine wakeup and passive balancing possibilities.
  1270. */
  1271. if (this_sd) {
  1272. int idx = this_sd->wake_idx;
  1273. unsigned int imbalance;
  1274. imbalance = 100 + (this_sd->imbalance_pct - 100) / 2;
  1275. load = source_load(cpu, idx);
  1276. this_load = target_load(this_cpu, idx);
  1277. new_cpu = this_cpu; /* Wake to this CPU if we can */
  1278. if (this_sd->flags & SD_WAKE_AFFINE) {
  1279. unsigned long tl = this_load;
  1280. unsigned long tl_per_task;
  1281. tl_per_task = cpu_avg_load_per_task(this_cpu);
  1282. /*
  1283. * If sync wakeup then subtract the (maximum possible)
  1284. * effect of the currently running task from the load
  1285. * of the current CPU:
  1286. */
  1287. if (sync)
  1288. tl -= current->load_weight;
  1289. if ((tl <= load &&
  1290. tl + target_load(cpu, idx) <= tl_per_task) ||
  1291. 100*(tl + p->load_weight) <= imbalance*load) {
  1292. /*
  1293. * This domain has SD_WAKE_AFFINE and
  1294. * p is cache cold in this domain, and
  1295. * there is no bad imbalance.
  1296. */
  1297. schedstat_inc(this_sd, ttwu_move_affine);
  1298. goto out_set_cpu;
  1299. }
  1300. }
  1301. /*
  1302. * Start passive balancing when half the imbalance_pct
  1303. * limit is reached.
  1304. */
  1305. if (this_sd->flags & SD_WAKE_BALANCE) {
  1306. if (imbalance*this_load <= 100*load) {
  1307. schedstat_inc(this_sd, ttwu_move_balance);
  1308. goto out_set_cpu;
  1309. }
  1310. }
  1311. }
  1312. new_cpu = cpu; /* Could not wake to this_cpu. Wake to cpu instead */
  1313. out_set_cpu:
  1314. new_cpu = wake_idle(new_cpu, p);
  1315. if (new_cpu != cpu) {
  1316. set_task_cpu(p, new_cpu);
  1317. task_rq_unlock(rq, &flags);
  1318. /* might preempt at this point */
  1319. rq = task_rq_lock(p, &flags);
  1320. old_state = p->state;
  1321. if (!(old_state & state))
  1322. goto out;
  1323. if (p->array)
  1324. goto out_running;
  1325. this_cpu = smp_processor_id();
  1326. cpu = task_cpu(p);
  1327. }
  1328. out_activate:
  1329. #endif /* CONFIG_SMP */
  1330. if (old_state == TASK_UNINTERRUPTIBLE) {
  1331. rq->nr_uninterruptible--;
  1332. /*
  1333. * Tasks on involuntary sleep don't earn
  1334. * sleep_avg beyond just interactive state.
  1335. */
  1336. p->sleep_type = SLEEP_NONINTERACTIVE;
  1337. } else
  1338. /*
  1339. * Tasks that have marked their sleep as noninteractive get
  1340. * woken up with their sleep average not weighted in an
  1341. * interactive way.
  1342. */
  1343. if (old_state & TASK_NONINTERACTIVE)
  1344. p->sleep_type = SLEEP_NONINTERACTIVE;
  1345. activate_task(p, rq, cpu == this_cpu);
  1346. /*
  1347. * Sync wakeups (i.e. those types of wakeups where the waker
  1348. * has indicated that it will leave the CPU in short order)
  1349. * don't trigger a preemption, if the woken up task will run on
  1350. * this cpu. (in this case the 'I will reschedule' promise of
  1351. * the waker guarantees that the freshly woken up task is going
  1352. * to be considered on this CPU.)
  1353. */
  1354. if (!sync || cpu != this_cpu) {
  1355. if (TASK_PREEMPTS_CURR(p, rq))
  1356. resched_task(rq->curr);
  1357. }
  1358. success = 1;
  1359. out_running:
  1360. p->state = TASK_RUNNING;
  1361. out:
  1362. task_rq_unlock(rq, &flags);
  1363. return success;
  1364. }
  1365. int fastcall wake_up_process(struct task_struct *p)
  1366. {
  1367. return try_to_wake_up(p, TASK_STOPPED | TASK_TRACED |
  1368. TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
  1369. }
  1370. EXPORT_SYMBOL(wake_up_process);
  1371. int fastcall wake_up_state(struct task_struct *p, unsigned int state)
  1372. {
  1373. return try_to_wake_up(p, state, 0);
  1374. }
  1375. static void task_running_tick(struct rq *rq, struct task_struct *p);
  1376. /*
  1377. * Perform scheduler related setup for a newly forked process p.
  1378. * p is forked by current.
  1379. */
  1380. void fastcall sched_fork(struct task_struct *p, int clone_flags)
  1381. {
  1382. int cpu = get_cpu();
  1383. #ifdef CONFIG_SMP
  1384. cpu = sched_balance_self(cpu, SD_BALANCE_FORK);
  1385. #endif
  1386. set_task_cpu(p, cpu);
  1387. /*
  1388. * We mark the process as running here, but have not actually
  1389. * inserted it onto the runqueue yet. This guarantees that
  1390. * nobody will actually run it, and a signal or other external
  1391. * event cannot wake it up and insert it on the runqueue either.
  1392. */
  1393. p->state = TASK_RUNNING;
  1394. /*
  1395. * Make sure we do not leak PI boosting priority to the child:
  1396. */
  1397. p->prio = current->normal_prio;
  1398. INIT_LIST_HEAD(&p->run_list);
  1399. p->array = NULL;
  1400. #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
  1401. if (unlikely(sched_info_on()))
  1402. memset(&p->sched_info, 0, sizeof(p->sched_info));
  1403. #endif
  1404. #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
  1405. p->oncpu = 0;
  1406. #endif
  1407. #ifdef CONFIG_PREEMPT
  1408. /* Want to start with kernel preemption disabled. */
  1409. task_thread_info(p)->preempt_count = 1;
  1410. #endif
  1411. /*
  1412. * Share the timeslice between parent and child, thus the
  1413. * total amount of pending timeslices in the system doesn't change,
  1414. * resulting in more scheduling fairness.
  1415. */
  1416. local_irq_disable();
  1417. p->time_slice = (current->time_slice + 1) >> 1;
  1418. /*
  1419. * The remainder of the first timeslice might be recovered by
  1420. * the parent if the child exits early enough.
  1421. */
  1422. p->first_time_slice = 1;
  1423. current->time_slice >>= 1;
  1424. p->timestamp = sched_clock();
  1425. if (unlikely(!current->time_slice)) {
  1426. /*
  1427. * This case is rare, it happens when the parent has only
  1428. * a single jiffy left from its timeslice. Taking the
  1429. * runqueue lock is not a problem.
  1430. */
  1431. current->time_slice = 1;
  1432. task_running_tick(cpu_rq(cpu), current);
  1433. }
  1434. local_irq_enable();
  1435. put_cpu();
  1436. }
  1437. /*
  1438. * wake_up_new_task - wake up a newly created task for the first time.
  1439. *
  1440. * This function will do some initial scheduler statistics housekeeping
  1441. * that must be done for every newly created context, then puts the task
  1442. * on the runqueue and wakes it.
  1443. */
  1444. void fastcall wake_up_new_task(struct task_struct *p, unsigned long clone_flags)
  1445. {
  1446. struct rq *rq, *this_rq;
  1447. unsigned long flags;
  1448. int this_cpu, cpu;
  1449. rq = task_rq_lock(p, &flags);
  1450. BUG_ON(p->state != TASK_RUNNING);
  1451. this_cpu = smp_processor_id();
  1452. cpu = task_cpu(p);
  1453. /*
  1454. * We decrease the sleep average of forking parents
  1455. * and children as well, to keep max-interactive tasks
  1456. * from forking tasks that are max-interactive. The parent
  1457. * (current) is done further down, under its lock.
  1458. */
  1459. p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
  1460. CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
  1461. p->prio = effective_prio(p);
  1462. if (likely(cpu == this_cpu)) {
  1463. if (!(clone_flags & CLONE_VM)) {
  1464. /*
  1465. * The VM isn't cloned, so we're in a good position to
  1466. * do child-runs-first in anticipation of an exec. This
  1467. * usually avoids a lot of COW overhead.
  1468. */
  1469. if (unlikely(!current->array))
  1470. __activate_task(p, rq);
  1471. else {
  1472. p->prio = current->prio;
  1473. p->normal_prio = current->normal_prio;
  1474. list_add_tail(&p->run_list, &current->run_list);
  1475. p->array = current->array;
  1476. p->array->nr_active++;
  1477. inc_nr_running(p, rq);
  1478. }
  1479. set_need_resched();
  1480. } else
  1481. /* Run child last */
  1482. __activate_task(p, rq);
  1483. /*
  1484. * We skip the following code due to cpu == this_cpu
  1485. *
  1486. * task_rq_unlock(rq, &flags);
  1487. * this_rq = task_rq_lock(current, &flags);
  1488. */
  1489. this_rq = rq;
  1490. } else {
  1491. this_rq = cpu_rq(this_cpu);
  1492. /*
  1493. * Not the local CPU - must adjust timestamp. This should
  1494. * get optimised away in the !CONFIG_SMP case.
  1495. */
  1496. p->timestamp = (p->timestamp - this_rq->most_recent_timestamp)
  1497. + rq->most_recent_timestamp;
  1498. __activate_task(p, rq);
  1499. if (TASK_PREEMPTS_CURR(p, rq))
  1500. resched_task(rq->curr);
  1501. /*
  1502. * Parent and child are on different CPUs, now get the
  1503. * parent runqueue to update the parent's ->sleep_avg:
  1504. */
  1505. task_rq_unlock(rq, &flags);
  1506. this_rq = task_rq_lock(current, &flags);
  1507. }
  1508. current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
  1509. PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
  1510. task_rq_unlock(this_rq, &flags);
  1511. }
  1512. /*
  1513. * Potentially available exiting-child timeslices are
  1514. * retrieved here - this way the parent does not get
  1515. * penalized for creating too many threads.
  1516. *
  1517. * (this cannot be used to 'generate' timeslices
  1518. * artificially, because any timeslice recovered here
  1519. * was given away by the parent in the first place.)
  1520. */
  1521. void fastcall sched_exit(struct task_struct *p)
  1522. {
  1523. unsigned long flags;
  1524. struct rq *rq;
  1525. /*
  1526. * If the child was a (relative-) CPU hog then decrease
  1527. * the sleep_avg of the parent as well.
  1528. */
  1529. rq = task_rq_lock(p->parent, &flags);
  1530. if (p->first_time_slice && task_cpu(p) == task_cpu(p->parent)) {
  1531. p->parent->time_slice += p->time_slice;
  1532. if (unlikely(p->parent->time_slice > task_timeslice(p)))
  1533. p->parent->time_slice = task_timeslice(p);
  1534. }
  1535. if (p->sleep_avg < p->parent->sleep_avg)
  1536. p->parent->sleep_avg = p->parent->sleep_avg /
  1537. (EXIT_WEIGHT + 1) * EXIT_WEIGHT + p->sleep_avg /
  1538. (EXIT_WEIGHT + 1);
  1539. task_rq_unlock(rq, &flags);
  1540. }
  1541. /**
  1542. * prepare_task_switch - prepare to switch tasks
  1543. * @rq: the runqueue preparing to switch
  1544. * @next: the task we are going to switch to.
  1545. *
  1546. * This is called with the rq lock held and interrupts off. It must
  1547. * be paired with a subsequent finish_task_switch after the context
  1548. * switch.
  1549. *
  1550. * prepare_task_switch sets up locking and calls architecture specific
  1551. * hooks.
  1552. */
  1553. static inline void prepare_task_switch(struct rq *rq, struct task_struct *next)
  1554. {
  1555. prepare_lock_switch(rq, next);
  1556. prepare_arch_switch(next);
  1557. }
  1558. /**
  1559. * finish_task_switch - clean up after a task-switch
  1560. * @rq: runqueue associated with task-switch
  1561. * @prev: the thread we just switched away from.
  1562. *
  1563. * finish_task_switch must be called after the context switch, paired
  1564. * with a prepare_task_switch call before the context switch.
  1565. * finish_task_switch will reconcile locking set up by prepare_task_switch,
  1566. * and do any other architecture-specific cleanup actions.
  1567. *
  1568. * Note that we may have delayed dropping an mm in context_switch(). If
  1569. * so, we finish that here outside of the runqueue lock. (Doing it
  1570. * with the lock held can cause deadlocks; see schedule() for
  1571. * details.)
  1572. */
  1573. static inline void finish_task_switch(struct rq *rq, struct task_struct *prev)
  1574. __releases(rq->lock)
  1575. {
  1576. struct mm_struct *mm = rq->prev_mm;
  1577. long prev_state;
  1578. rq->prev_mm = NULL;
  1579. /*
  1580. * A task struct has one reference for the use as "current".
  1581. * If a task dies, then it sets TASK_DEAD in tsk->state and calls
  1582. * schedule one last time. The schedule call will never return, and
  1583. * the scheduled task must drop that reference.
  1584. * The test for TASK_DEAD must occur while the runqueue locks are
  1585. * still held, otherwise prev could be scheduled on another cpu, die
  1586. * there before we look at prev->state, and then the reference would
  1587. * be dropped twice.
  1588. * Manfred Spraul <manfred@colorfullife.com>
  1589. */
  1590. prev_state = prev->state;
  1591. finish_arch_switch(prev);
  1592. finish_lock_switch(rq, prev);
  1593. if (mm)
  1594. mmdrop(mm);
  1595. if (unlikely(prev_state == TASK_DEAD)) {
  1596. /*
  1597. * Remove function-return probe instances associated with this
  1598. * task and put them back on the free list.
  1599. */
  1600. kprobe_flush_task(prev);
  1601. put_task_struct(prev);
  1602. }
  1603. }
  1604. /**
  1605. * schedule_tail - first thing a freshly forked thread must call.
  1606. * @prev: the thread we just switched away from.
  1607. */
  1608. asmlinkage void schedule_tail(struct task_struct *prev)
  1609. __releases(rq->lock)
  1610. {
  1611. struct rq *rq = this_rq();
  1612. finish_task_switch(rq, prev);
  1613. #ifdef __ARCH_WANT_UNLOCKED_CTXSW
  1614. /* In this case, finish_task_switch does not reenable preemption */
  1615. preempt_enable();
  1616. #endif
  1617. if (current->set_child_tid)
  1618. put_user(current->pid, current->set_child_tid);
  1619. }
  1620. /*
  1621. * context_switch - switch to the new MM and the new
  1622. * thread's register state.
  1623. */
  1624. static inline struct task_struct *
  1625. context_switch(struct rq *rq, struct task_struct *prev,
  1626. struct task_struct *next)
  1627. {
  1628. struct mm_struct *mm = next->mm;
  1629. struct mm_struct *oldmm = prev->active_mm;
  1630. if (!mm) {
  1631. next->active_mm = oldmm;
  1632. atomic_inc(&oldmm->mm_count);
  1633. enter_lazy_tlb(oldmm, next);
  1634. } else
  1635. switch_mm(oldmm, mm, next);
  1636. if (!prev->mm) {
  1637. prev->active_mm = NULL;
  1638. WARN_ON(rq->prev_mm);
  1639. rq->prev_mm = oldmm;
  1640. }
  1641. /*
  1642. * Since the runqueue lock will be released by the next
  1643. * task (which is an invalid locking op but in the case
  1644. * of the scheduler it's an obvious special-case), so we
  1645. * do an early lockdep release here:
  1646. */
  1647. #ifndef __ARCH_WANT_UNLOCKED_CTXSW
  1648. spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
  1649. #endif
  1650. /* Here we just switch the register state and the stack. */
  1651. switch_to(prev, next, prev);
  1652. return prev;
  1653. }
  1654. /*
  1655. * nr_running, nr_uninterruptible and nr_context_switches:
  1656. *
  1657. * externally visible scheduler statistics: current number of runnable
  1658. * threads, current number of uninterruptible-sleeping threads, total
  1659. * number of context switches performed since bootup.
  1660. */
  1661. unsigned long nr_running(void)
  1662. {
  1663. unsigned long i, sum = 0;
  1664. for_each_online_cpu(i)
  1665. sum += cpu_rq(i)->nr_running;
  1666. return sum;
  1667. }
  1668. unsigned long nr_uninterruptible(void)
  1669. {
  1670. unsigned long i, sum = 0;
  1671. for_each_possible_cpu(i)
  1672. sum += cpu_rq(i)->nr_uninterruptible;
  1673. /*
  1674. * Since we read the counters lockless, it might be slightly
  1675. * inaccurate. Do not allow it to go below zero though:
  1676. */
  1677. if (unlikely((long)sum < 0))
  1678. sum = 0;
  1679. return sum;
  1680. }
  1681. unsigned long long nr_context_switches(void)
  1682. {
  1683. int i;
  1684. unsigned long long sum = 0;
  1685. for_each_possible_cpu(i)
  1686. sum += cpu_rq(i)->nr_switches;
  1687. return sum;
  1688. }
  1689. unsigned long nr_iowait(void)
  1690. {
  1691. unsigned long i, sum = 0;
  1692. for_each_possible_cpu(i)
  1693. sum += atomic_read(&cpu_rq(i)->nr_iowait);
  1694. return sum;
  1695. }
  1696. unsigned long nr_active(void)
  1697. {
  1698. unsigned long i, running = 0, uninterruptible = 0;
  1699. for_each_online_cpu(i) {
  1700. running += cpu_rq(i)->nr_running;
  1701. uninterruptible += cpu_rq(i)->nr_uninterruptible;
  1702. }
  1703. if (unlikely((long)uninterruptible < 0))
  1704. uninterruptible = 0;
  1705. return running + uninterruptible;
  1706. }
  1707. #ifdef CONFIG_SMP
  1708. /*
  1709. * Is this task likely cache-hot:
  1710. */
  1711. static inline int
  1712. task_hot(struct task_struct *p, unsigned long long now, struct sched_domain *sd)
  1713. {
  1714. return (long long)(now - p->last_ran) < (long long)sd->cache_hot_time;
  1715. }
  1716. /*
  1717. * double_rq_lock - safely lock two runqueues
  1718. *
  1719. * Note this does not disable interrupts like task_rq_lock,
  1720. * you need to do so manually before calling.
  1721. */
  1722. static void double_rq_lock(struct rq *rq1, struct rq *rq2)
  1723. __acquires(rq1->lock)
  1724. __acquires(rq2->lock)
  1725. {
  1726. BUG_ON(!irqs_disabled());
  1727. if (rq1 == rq2) {
  1728. spin_lock(&rq1->lock);
  1729. __acquire(rq2->lock); /* Fake it out ;) */
  1730. } else {
  1731. if (rq1 < rq2) {
  1732. spin_lock(&rq1->lock);
  1733. spin_lock(&rq2->lock);
  1734. } else {
  1735. spin_lock(&rq2->lock);
  1736. spin_lock(&rq1->lock);
  1737. }
  1738. }
  1739. }
  1740. /*
  1741. * double_rq_unlock - safely unlock two runqueues
  1742. *
  1743. * Note this does not restore interrupts like task_rq_unlock,
  1744. * you need to do so manually after calling.
  1745. */
  1746. static void double_rq_unlock(struct rq *rq1, struct rq *rq2)
  1747. __releases(rq1->lock)
  1748. __releases(rq2->lock)
  1749. {
  1750. spin_unlock(&rq1->lock);
  1751. if (rq1 != rq2)
  1752. spin_unlock(&rq2->lock);
  1753. else
  1754. __release(rq2->lock);
  1755. }
  1756. /*
  1757. * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
  1758. */
  1759. static void double_lock_balance(struct rq *this_rq, struct rq *busiest)
  1760. __releases(this_rq->lock)
  1761. __acquires(busiest->lock)
  1762. __acquires(this_rq->lock)
  1763. {
  1764. if (unlikely(!irqs_disabled())) {
  1765. /* printk() doesn't work good under rq->lock */
  1766. spin_unlock(&this_rq->lock);
  1767. BUG_ON(1);
  1768. }
  1769. if (unlikely(!spin_trylock(&busiest->lock))) {
  1770. if (busiest < this_rq) {
  1771. spin_unlock(&this_rq->lock);
  1772. spin_lock(&busiest->lock);
  1773. spin_lock(&this_rq->lock);
  1774. } else
  1775. spin_lock(&busiest->lock);
  1776. }
  1777. }
  1778. /*
  1779. * If dest_cpu is allowed for this process, migrate the task to it.
  1780. * This is accomplished by forcing the cpu_allowed mask to only
  1781. * allow dest_cpu, which will force the cpu onto dest_cpu. Then
  1782. * the cpu_allowed mask is restored.
  1783. */
  1784. static void sched_migrate_task(struct task_struct *p, int dest_cpu)
  1785. {
  1786. struct migration_req req;
  1787. unsigned long flags;
  1788. struct rq *rq;
  1789. rq = task_rq_lock(p, &flags);
  1790. if (!cpu_isset(dest_cpu, p->cpus_allowed)
  1791. || unlikely(cpu_is_offline(dest_cpu)))
  1792. goto out;
  1793. /* force the process onto the specified CPU */
  1794. if (migrate_task(p, dest_cpu, &req)) {
  1795. /* Need to wait for migration thread (might exit: take ref). */
  1796. struct task_struct *mt = rq->migration_thread;
  1797. get_task_struct(mt);
  1798. task_rq_unlock(rq, &flags);
  1799. wake_up_process(mt);
  1800. put_task_struct(mt);
  1801. wait_for_completion(&req.done);
  1802. return;
  1803. }
  1804. out:
  1805. task_rq_unlock(rq, &flags);
  1806. }
  1807. /*
  1808. * sched_exec - execve() is a valuable balancing opportunity, because at
  1809. * this point the task has the smallest effective memory and cache footprint.
  1810. */
  1811. void sched_exec(void)
  1812. {
  1813. int new_cpu, this_cpu = get_cpu();
  1814. new_cpu = sched_balance_self(this_cpu, SD_BALANCE_EXEC);
  1815. put_cpu();
  1816. if (new_cpu != this_cpu)
  1817. sched_migrate_task(current, new_cpu);
  1818. }
  1819. /*
  1820. * pull_task - move a task from a remote runqueue to the local runqueue.
  1821. * Both runqueues must be locked.
  1822. */
  1823. static void pull_task(struct rq *src_rq, struct prio_array *src_array,
  1824. struct task_struct *p, struct rq *this_rq,
  1825. struct prio_array *this_array, int this_cpu)
  1826. {
  1827. dequeue_task(p, src_array);
  1828. dec_nr_running(p, src_rq);
  1829. set_task_cpu(p, this_cpu);
  1830. inc_nr_running(p, this_rq);
  1831. enqueue_task(p, this_array);
  1832. p->timestamp = (p->timestamp - src_rq->most_recent_timestamp)
  1833. + this_rq->most_recent_timestamp;
  1834. /*
  1835. * Note that idle threads have a prio of MAX_PRIO, for this test
  1836. * to be always true for them.
  1837. */
  1838. if (TASK_PREEMPTS_CURR(p, this_rq))
  1839. resched_task(this_rq->curr);
  1840. }
  1841. /*
  1842. * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
  1843. */
  1844. static
  1845. int can_migrate_task(struct task_struct *p, struct rq *rq, int this_cpu,
  1846. struct sched_domain *sd, enum idle_type idle,
  1847. int *all_pinned)
  1848. {
  1849. /*
  1850. * We do not migrate tasks that are:
  1851. * 1) running (obviously), or
  1852. * 2) cannot be migrated to this CPU due to cpus_allowed, or
  1853. * 3) are cache-hot on their current CPU.
  1854. */
  1855. if (!cpu_isset(this_cpu, p->cpus_allowed))
  1856. return 0;
  1857. *all_pinned = 0;
  1858. if (task_running(rq, p))
  1859. return 0;
  1860. /*
  1861. * Aggressive migration if:
  1862. * 1) task is cache cold, or
  1863. * 2) too many balance attempts have failed.
  1864. */
  1865. if (sd->nr_balance_failed > sd->cache_nice_tries) {
  1866. #ifdef CONFIG_SCHEDSTATS
  1867. if (task_hot(p, rq->most_recent_timestamp, sd))
  1868. schedstat_inc(sd, lb_hot_gained[idle]);
  1869. #endif
  1870. return 1;
  1871. }
  1872. if (task_hot(p, rq->most_recent_timestamp, sd))
  1873. return 0;
  1874. return 1;
  1875. }
  1876. #define rq_best_prio(rq) min((rq)->curr->prio, (rq)->best_expired_prio)
  1877. /*
  1878. * move_tasks tries to move up to max_nr_move tasks and max_load_move weighted
  1879. * load from busiest to this_rq, as part of a balancing operation within
  1880. * "domain". Returns the number of tasks moved.
  1881. *
  1882. * Called with both runqueues locked.
  1883. */
  1884. static int move_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
  1885. unsigned long max_nr_move, unsigned long max_load_move,
  1886. struct sched_domain *sd, enum idle_type idle,
  1887. int *all_pinned)
  1888. {
  1889. int idx, pulled = 0, pinned = 0, this_best_prio, best_prio,
  1890. best_prio_seen, skip_for_load;
  1891. struct prio_array *array, *dst_array;
  1892. struct list_head *head, *curr;
  1893. struct task_struct *tmp;
  1894. long rem_load_move;
  1895. if (max_nr_move == 0 || max_load_move == 0)
  1896. goto out;
  1897. rem_load_move = max_load_move;
  1898. pinned = 1;
  1899. this_best_prio = rq_best_prio(this_rq);
  1900. best_prio = rq_best_prio(busiest);
  1901. /*
  1902. * Enable handling of the case where there is more than one task
  1903. * with the best priority. If the current running task is one
  1904. * of those with prio==best_prio we know it won't be moved
  1905. * and therefore it's safe to override the skip (based on load) of
  1906. * any task we find with that prio.
  1907. */
  1908. best_prio_seen = best_prio == busiest->curr->prio;
  1909. /*
  1910. * We first consider expired tasks. Those will likely not be
  1911. * executed in the near future, and they are most likely to
  1912. * be cache-cold, thus switching CPUs has the least effect
  1913. * on them.
  1914. */
  1915. if (busiest->expired->nr_active) {
  1916. array = busiest->expired;
  1917. dst_array = this_rq->expired;
  1918. } else {
  1919. array = busiest->active;
  1920. dst_array = this_rq->active;
  1921. }
  1922. new_array:
  1923. /* Start searching at priority 0: */
  1924. idx = 0;
  1925. skip_bitmap:
  1926. if (!idx)
  1927. idx = sched_find_first_bit(array->bitmap);
  1928. else
  1929. idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
  1930. if (idx >= MAX_PRIO) {
  1931. if (array == busiest->expired && busiest->active->nr_active) {
  1932. array = busiest->active;
  1933. dst_array = this_rq->active;
  1934. goto new_array;
  1935. }
  1936. goto out;
  1937. }
  1938. head = array->queue + idx;
  1939. curr = head->prev;
  1940. skip_queue:
  1941. tmp = list_entry(curr, struct task_struct, run_list);
  1942. curr = curr->prev;
  1943. /*
  1944. * To help distribute high priority tasks accross CPUs we don't
  1945. * skip a task if it will be the highest priority task (i.e. smallest
  1946. * prio value) on its new queue regardless of its load weight
  1947. */
  1948. skip_for_load = tmp->load_weight > rem_load_move;
  1949. if (skip_for_load && idx < this_best_prio)
  1950. skip_for_load = !best_prio_seen && idx == best_prio;
  1951. if (skip_for_load ||
  1952. !can_migrate_task(tmp, busiest, this_cpu, sd, idle, &pinned)) {
  1953. best_prio_seen |= idx == best_prio;
  1954. if (curr != head)
  1955. goto skip_queue;
  1956. idx++;
  1957. goto skip_bitmap;
  1958. }
  1959. pull_task(busiest, array, tmp, this_rq, dst_array, this_cpu);
  1960. pulled++;
  1961. rem_load_move -= tmp->load_weight;
  1962. /*
  1963. * We only want to steal up to the prescribed number of tasks
  1964. * and the prescribed amount of weighted load.
  1965. */
  1966. if (pulled < max_nr_move && rem_load_move > 0) {
  1967. if (idx < this_best_prio)
  1968. this_best_prio = idx;
  1969. if (curr != head)
  1970. goto skip_queue;
  1971. idx++;
  1972. goto skip_bitmap;
  1973. }
  1974. out:
  1975. /*
  1976. * Right now, this is the only place pull_task() is called,
  1977. * so we can safely collect pull_task() stats here rather than
  1978. * inside pull_task().
  1979. */
  1980. schedstat_add(sd, lb_gained[idle], pulled);
  1981. if (all_pinned)
  1982. *all_pinned = pinned;
  1983. return pulled;
  1984. }
  1985. /*
  1986. * find_busiest_group finds and returns the busiest CPU group within the
  1987. * domain. It calculates and returns the amount of weighted load which
  1988. * should be moved to restore balance via the imbalance parameter.
  1989. */
  1990. static struct sched_group *
  1991. find_busiest_group(struct sched_domain *sd, int this_cpu,
  1992. unsigned long *imbalance, enum idle_type idle, int *sd_idle,
  1993. cpumask_t *cpus, int *balance)
  1994. {
  1995. struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
  1996. unsigned long max_load, avg_load, total_load, this_load, total_pwr;
  1997. unsigned long max_pull;
  1998. unsigned long busiest_load_per_task, busiest_nr_running;
  1999. unsigned long this_load_per_task, this_nr_running;
  2000. int load_idx;
  2001. #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
  2002. int power_savings_balance = 1;
  2003. unsigned long leader_nr_running = 0, min_load_per_task = 0;
  2004. unsigned long min_nr_running = ULONG_MAX;
  2005. struct sched_group *group_min = NULL, *group_leader = NULL;
  2006. #endif
  2007. max_load = this_load = total_load = total_pwr = 0;
  2008. busiest_load_per_task = busiest_nr_running = 0;
  2009. this_load_per_task = this_nr_running = 0;
  2010. if (idle == NOT_IDLE)
  2011. load_idx = sd->busy_idx;
  2012. else if (idle == NEWLY_IDLE)
  2013. load_idx = sd->newidle_idx;
  2014. else
  2015. load_idx = sd->idle_idx;
  2016. do {
  2017. unsigned long load, group_capacity;
  2018. int local_group;
  2019. int i;
  2020. unsigned int balance_cpu = -1, first_idle_cpu = 0;
  2021. unsigned long sum_nr_running, sum_weighted_load;
  2022. local_group = cpu_isset(this_cpu, group->cpumask);
  2023. if (local_group)
  2024. balance_cpu = first_cpu(group->cpumask);
  2025. /* Tally up the load of all CPUs in the group */
  2026. sum_weighted_load = sum_nr_running = avg_load = 0;
  2027. for_each_cpu_mask(i, group->cpumask) {
  2028. struct rq *rq;
  2029. if (!cpu_isset(i, *cpus))
  2030. continue;
  2031. rq = cpu_rq(i);
  2032. if (*sd_idle && !idle_cpu(i))
  2033. *sd_idle = 0;
  2034. /* Bias balancing toward cpus of our domain */
  2035. if (local_group) {
  2036. if (idle_cpu(i) && !first_idle_cpu) {
  2037. first_idle_cpu = 1;
  2038. balance_cpu = i;
  2039. }
  2040. load = target_load(i, load_idx);
  2041. } else
  2042. load = source_load(i, load_idx);
  2043. avg_load += load;
  2044. sum_nr_running += rq->nr_running;
  2045. sum_weighted_load += rq->raw_weighted_load;
  2046. }
  2047. /*
  2048. * First idle cpu or the first cpu(busiest) in this sched group
  2049. * is eligible for doing load balancing at this and above
  2050. * domains.
  2051. */
  2052. if (local_group && balance_cpu != this_cpu && balance) {
  2053. *balance = 0;
  2054. goto ret;
  2055. }
  2056. total_load += avg_load;
  2057. total_pwr += group->cpu_power;
  2058. /* Adjust by relative CPU power of the group */
  2059. avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
  2060. group_capacity = group->cpu_power / SCHED_LOAD_SCALE;
  2061. if (local_group) {
  2062. this_load = avg_load;
  2063. this = group;
  2064. this_nr_running = sum_nr_running;
  2065. this_load_per_task = sum_weighted_load;
  2066. } else if (avg_load > max_load &&
  2067. sum_nr_running > group_capacity) {
  2068. max_load = avg_load;
  2069. busiest = group;
  2070. busiest_nr_running = sum_nr_running;
  2071. busiest_load_per_task = sum_weighted_load;
  2072. }
  2073. #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
  2074. /*
  2075. * Busy processors will not participate in power savings
  2076. * balance.
  2077. */
  2078. if (idle == NOT_IDLE || !(sd->flags & SD_POWERSAVINGS_BALANCE))
  2079. goto group_next;
  2080. /*
  2081. * If the local group is idle or completely loaded
  2082. * no need to do power savings balance at this domain
  2083. */
  2084. if (local_group && (this_nr_running >= group_capacity ||
  2085. !this_nr_running))
  2086. power_savings_balance = 0;
  2087. /*
  2088. * If a group is already running at full capacity or idle,
  2089. * don't include that group in power savings calculations
  2090. */
  2091. if (!power_savings_balance || sum_nr_running >= group_capacity
  2092. || !sum_nr_running)
  2093. goto group_next;
  2094. /*
  2095. * Calculate the group which has the least non-idle load.
  2096. * This is the group from where we need to pick up the load
  2097. * for saving power
  2098. */
  2099. if ((sum_nr_running < min_nr_running) ||
  2100. (sum_nr_running == min_nr_running &&
  2101. first_cpu(group->cpumask) <
  2102. first_cpu(group_min->cpumask))) {
  2103. group_min = group;
  2104. min_nr_running = sum_nr_running;
  2105. min_load_per_task = sum_weighted_load /
  2106. sum_nr_running;
  2107. }
  2108. /*
  2109. * Calculate the group which is almost near its
  2110. * capacity but still has some space to pick up some load
  2111. * from other group and save more power
  2112. */
  2113. if (sum_nr_running <= group_capacity - 1) {
  2114. if (sum_nr_running > leader_nr_running ||
  2115. (sum_nr_running == leader_nr_running &&
  2116. first_cpu(group->cpumask) >
  2117. first_cpu(group_leader->cpumask))) {
  2118. group_leader = group;
  2119. leader_nr_running = sum_nr_running;
  2120. }
  2121. }
  2122. group_next:
  2123. #endif
  2124. group = group->next;
  2125. } while (group != sd->groups);
  2126. if (!busiest || this_load >= max_load || busiest_nr_running == 0)
  2127. goto out_balanced;
  2128. avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
  2129. if (this_load >= avg_load ||
  2130. 100*max_load <= sd->imbalance_pct*this_load)
  2131. goto out_balanced;
  2132. busiest_load_per_task /= busiest_nr_running;
  2133. /*
  2134. * We're trying to get all the cpus to the average_load, so we don't
  2135. * want to push ourselves above the average load, nor do we wish to
  2136. * reduce the max loaded cpu below the average load, as either of these
  2137. * actions would just result in more rebalancing later, and ping-pong
  2138. * tasks around. Thus we look for the minimum possible imbalance.
  2139. * Negative imbalances (*we* are more loaded than anyone else) will
  2140. * be counted as no imbalance for these purposes -- we can't fix that
  2141. * by pulling tasks to us. Be careful of negative numbers as they'll
  2142. * appear as very large values with unsigned longs.
  2143. */
  2144. if (max_load <= busiest_load_per_task)
  2145. goto out_balanced;
  2146. /*
  2147. * In the presence of smp nice balancing, certain scenarios can have
  2148. * max load less than avg load(as we skip the groups at or below
  2149. * its cpu_power, while calculating max_load..)
  2150. */
  2151. if (max_load < avg_load) {
  2152. *imbalance = 0;
  2153. goto small_imbalance;
  2154. }
  2155. /* Don't want to pull so many tasks that a group would go idle */
  2156. max_pull = min(max_load - avg_load, max_load - busiest_load_per_task);
  2157. /* How much load to actually move to equalise the imbalance */
  2158. *imbalance = min(max_pull * busiest->cpu_power,
  2159. (avg_load - this_load) * this->cpu_power)
  2160. / SCHED_LOAD_SCALE;
  2161. /*
  2162. * if *imbalance is less than the average load per runnable task
  2163. * there is no gaurantee that any tasks will be moved so we'll have
  2164. * a think about bumping its value to force at least one task to be
  2165. * moved
  2166. */
  2167. if (*imbalance < busiest_load_per_task) {
  2168. unsigned long tmp, pwr_now, pwr_move;
  2169. unsigned int imbn;
  2170. small_imbalance:
  2171. pwr_move = pwr_now = 0;
  2172. imbn = 2;
  2173. if (this_nr_running) {
  2174. this_load_per_task /= this_nr_running;
  2175. if (busiest_load_per_task > this_load_per_task)
  2176. imbn = 1;
  2177. } else
  2178. this_load_per_task = SCHED_LOAD_SCALE;
  2179. if (max_load - this_load >= busiest_load_per_task * imbn) {
  2180. *imbalance = busiest_load_per_task;
  2181. return busiest;
  2182. }
  2183. /*
  2184. * OK, we don't have enough imbalance to justify moving tasks,
  2185. * however we may be able to increase total CPU power used by
  2186. * moving them.
  2187. */
  2188. pwr_now += busiest->cpu_power *
  2189. min(busiest_load_per_task, max_load);
  2190. pwr_now += this->cpu_power *
  2191. min(this_load_per_task, this_load);
  2192. pwr_now /= SCHED_LOAD_SCALE;
  2193. /* Amount of load we'd subtract */
  2194. tmp = busiest_load_per_task * SCHED_LOAD_SCALE /
  2195. busiest->cpu_power;
  2196. if (max_load > tmp)
  2197. pwr_move += busiest->cpu_power *
  2198. min(busiest_load_per_task, max_load - tmp);
  2199. /* Amount of load we'd add */
  2200. if (max_load * busiest->cpu_power <
  2201. busiest_load_per_task * SCHED_LOAD_SCALE)
  2202. tmp = max_load * busiest->cpu_power / this->cpu_power;
  2203. else
  2204. tmp = busiest_load_per_task * SCHED_LOAD_SCALE /
  2205. this->cpu_power;
  2206. pwr_move += this->cpu_power *
  2207. min(this_load_per_task, this_load + tmp);
  2208. pwr_move /= SCHED_LOAD_SCALE;
  2209. /* Move if we gain throughput */
  2210. if (pwr_move <= pwr_now)
  2211. goto out_balanced;
  2212. *imbalance = busiest_load_per_task;
  2213. }
  2214. return busiest;
  2215. out_balanced:
  2216. #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
  2217. if (idle == NOT_IDLE || !(sd->flags & SD_POWERSAVINGS_BALANCE))
  2218. goto ret;
  2219. if (this == group_leader && group_leader != group_min) {
  2220. *imbalance = min_load_per_task;
  2221. return group_min;
  2222. }
  2223. #endif
  2224. ret:
  2225. *imbalance = 0;
  2226. return NULL;
  2227. }
  2228. /*
  2229. * find_busiest_queue - find the busiest runqueue among the cpus in group.
  2230. */
  2231. static struct rq *
  2232. find_busiest_queue(struct sched_group *group, enum idle_type idle,
  2233. unsigned long imbalance, cpumask_t *cpus)
  2234. {
  2235. struct rq *busiest = NULL, *rq;
  2236. unsigned long max_load = 0;
  2237. int i;
  2238. for_each_cpu_mask(i, group->cpumask) {
  2239. if (!cpu_isset(i, *cpus))
  2240. continue;
  2241. rq = cpu_rq(i);
  2242. if (rq->nr_running == 1 && rq->raw_weighted_load > imbalance)
  2243. continue;
  2244. if (rq->raw_weighted_load > max_load) {
  2245. max_load = rq->raw_weighted_load;
  2246. busiest = rq;
  2247. }
  2248. }
  2249. return busiest;
  2250. }
  2251. /*
  2252. * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
  2253. * so long as it is large enough.
  2254. */
  2255. #define MAX_PINNED_INTERVAL 512
  2256. static inline unsigned long minus_1_or_zero(unsigned long n)
  2257. {
  2258. return n > 0 ? n - 1 : 0;
  2259. }
  2260. /*
  2261. * Check this_cpu to ensure it is balanced within domain. Attempt to move
  2262. * tasks if there is an imbalance.
  2263. */
  2264. static int load_balance(int this_cpu, struct rq *this_rq,
  2265. struct sched_domain *sd, enum idle_type idle,
  2266. int *balance)
  2267. {
  2268. int nr_moved, all_pinned = 0, active_balance = 0, sd_idle = 0;
  2269. struct sched_group *group;
  2270. unsigned long imbalance;
  2271. struct rq *busiest;
  2272. cpumask_t cpus = CPU_MASK_ALL;
  2273. unsigned long flags;
  2274. /*
  2275. * When power savings policy is enabled for the parent domain, idle
  2276. * sibling can pick up load irrespective of busy siblings. In this case,
  2277. * let the state of idle sibling percolate up as IDLE, instead of
  2278. * portraying it as NOT_IDLE.
  2279. */
  2280. if (idle != NOT_IDLE && sd->flags & SD_SHARE_CPUPOWER &&
  2281. !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
  2282. sd_idle = 1;
  2283. schedstat_inc(sd, lb_cnt[idle]);
  2284. redo:
  2285. group = find_busiest_group(sd, this_cpu, &imbalance, idle, &sd_idle,
  2286. &cpus, balance);
  2287. if (*balance == 0)
  2288. goto out_balanced;
  2289. if (!group) {
  2290. schedstat_inc(sd, lb_nobusyg[idle]);
  2291. goto out_balanced;
  2292. }
  2293. busiest = find_busiest_queue(group, idle, imbalance, &cpus);
  2294. if (!busiest) {
  2295. schedstat_inc(sd, lb_nobusyq[idle]);
  2296. goto out_balanced;
  2297. }
  2298. BUG_ON(busiest == this_rq);
  2299. schedstat_add(sd, lb_imbalance[idle], imbalance);
  2300. nr_moved = 0;
  2301. if (busiest->nr_running > 1) {
  2302. /*
  2303. * Attempt to move tasks. If find_busiest_group has found
  2304. * an imbalance but busiest->nr_running <= 1, the group is
  2305. * still unbalanced. nr_moved simply stays zero, so it is
  2306. * correctly treated as an imbalance.
  2307. */
  2308. local_irq_save(flags);
  2309. double_rq_lock(this_rq, busiest);
  2310. nr_moved = move_tasks(this_rq, this_cpu, busiest,
  2311. minus_1_or_zero(busiest->nr_running),
  2312. imbalance, sd, idle, &all_pinned);
  2313. double_rq_unlock(this_rq, busiest);
  2314. local_irq_restore(flags);
  2315. /* All tasks on this runqueue were pinned by CPU affinity */
  2316. if (unlikely(all_pinned)) {
  2317. cpu_clear(cpu_of(busiest), cpus);
  2318. if (!cpus_empty(cpus))
  2319. goto redo;
  2320. goto out_balanced;
  2321. }
  2322. }
  2323. if (!nr_moved) {
  2324. schedstat_inc(sd, lb_failed[idle]);
  2325. sd->nr_balance_failed++;
  2326. if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
  2327. spin_lock_irqsave(&busiest->lock, flags);
  2328. /* don't kick the migration_thread, if the curr
  2329. * task on busiest cpu can't be moved to this_cpu
  2330. */
  2331. if (!cpu_isset(this_cpu, busiest->curr->cpus_allowed)) {
  2332. spin_unlock_irqrestore(&busiest->lock, flags);
  2333. all_pinned = 1;
  2334. goto out_one_pinned;
  2335. }
  2336. if (!busiest->active_balance) {
  2337. busiest->active_balance = 1;
  2338. busiest->push_cpu = this_cpu;
  2339. active_balance = 1;
  2340. }
  2341. spin_unlock_irqrestore(&busiest->lock, flags);
  2342. if (active_balance)
  2343. wake_up_process(busiest->migration_thread);
  2344. /*
  2345. * We've kicked active balancing, reset the failure
  2346. * counter.
  2347. */
  2348. sd->nr_balance_failed = sd->cache_nice_tries+1;
  2349. }
  2350. } else
  2351. sd->nr_balance_failed = 0;
  2352. if (likely(!active_balance)) {
  2353. /* We were unbalanced, so reset the balancing interval */
  2354. sd->balance_interval = sd->min_interval;
  2355. } else {
  2356. /*
  2357. * If we've begun active balancing, start to back off. This
  2358. * case may not be covered by the all_pinned logic if there
  2359. * is only 1 task on the busy runqueue (because we don't call
  2360. * move_tasks).
  2361. */
  2362. if (sd->balance_interval < sd->max_interval)
  2363. sd->balance_interval *= 2;
  2364. }
  2365. if (!nr_moved && !sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
  2366. !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
  2367. return -1;
  2368. return nr_moved;
  2369. out_balanced:
  2370. schedstat_inc(sd, lb_balanced[idle]);
  2371. sd->nr_balance_failed = 0;
  2372. out_one_pinned:
  2373. /* tune up the balancing interval */
  2374. if ((all_pinned && sd->balance_interval < MAX_PINNED_INTERVAL) ||
  2375. (sd->balance_interval < sd->max_interval))
  2376. sd->balance_interval *= 2;
  2377. if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
  2378. !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
  2379. return -1;
  2380. return 0;
  2381. }
  2382. /*
  2383. * Check this_cpu to ensure it is balanced within domain. Attempt to move
  2384. * tasks if there is an imbalance.
  2385. *
  2386. * Called from schedule when this_rq is about to become idle (NEWLY_IDLE).
  2387. * this_rq is locked.
  2388. */
  2389. static int
  2390. load_balance_newidle(int this_cpu, struct rq *this_rq, struct sched_domain *sd)
  2391. {
  2392. struct sched_group *group;
  2393. struct rq *busiest = NULL;
  2394. unsigned long imbalance;
  2395. int nr_moved = 0;
  2396. int sd_idle = 0;
  2397. cpumask_t cpus = CPU_MASK_ALL;
  2398. /*
  2399. * When power savings policy is enabled for the parent domain, idle
  2400. * sibling can pick up load irrespective of busy siblings. In this case,
  2401. * let the state of idle sibling percolate up as IDLE, instead of
  2402. * portraying it as NOT_IDLE.
  2403. */
  2404. if (sd->flags & SD_SHARE_CPUPOWER &&
  2405. !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
  2406. sd_idle = 1;
  2407. schedstat_inc(sd, lb_cnt[NEWLY_IDLE]);
  2408. redo:
  2409. group = find_busiest_group(sd, this_cpu, &imbalance, NEWLY_IDLE,
  2410. &sd_idle, &cpus, NULL);
  2411. if (!group) {
  2412. schedstat_inc(sd, lb_nobusyg[NEWLY_IDLE]);
  2413. goto out_balanced;
  2414. }
  2415. busiest = find_busiest_queue(group, NEWLY_IDLE, imbalance,
  2416. &cpus);
  2417. if (!busiest) {
  2418. schedstat_inc(sd, lb_nobusyq[NEWLY_IDLE]);
  2419. goto out_balanced;
  2420. }
  2421. BUG_ON(busiest == this_rq);
  2422. schedstat_add(sd, lb_imbalance[NEWLY_IDLE], imbalance);
  2423. nr_moved = 0;
  2424. if (busiest->nr_running > 1) {
  2425. /* Attempt to move tasks */
  2426. double_lock_balance(this_rq, busiest);
  2427. nr_moved = move_tasks(this_rq, this_cpu, busiest,
  2428. minus_1_or_zero(busiest->nr_running),
  2429. imbalance, sd, NEWLY_IDLE, NULL);
  2430. spin_unlock(&busiest->lock);
  2431. if (!nr_moved) {
  2432. cpu_clear(cpu_of(busiest), cpus);
  2433. if (!cpus_empty(cpus))
  2434. goto redo;
  2435. }
  2436. }
  2437. if (!nr_moved) {
  2438. schedstat_inc(sd, lb_failed[NEWLY_IDLE]);
  2439. if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
  2440. !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
  2441. return -1;
  2442. } else
  2443. sd->nr_balance_failed = 0;
  2444. return nr_moved;
  2445. out_balanced:
  2446. schedstat_inc(sd, lb_balanced[NEWLY_IDLE]);
  2447. if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
  2448. !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
  2449. return -1;
  2450. sd->nr_balance_failed = 0;
  2451. return 0;
  2452. }
  2453. /*
  2454. * idle_balance is called by schedule() if this_cpu is about to become
  2455. * idle. Attempts to pull tasks from other CPUs.
  2456. */
  2457. static void idle_balance(int this_cpu, struct rq *this_rq)
  2458. {
  2459. struct sched_domain *sd;
  2460. int pulled_task = 0;
  2461. unsigned long next_balance = jiffies + 60 * HZ;
  2462. for_each_domain(this_cpu, sd) {
  2463. if (sd->flags & SD_BALANCE_NEWIDLE) {
  2464. /* If we've pulled tasks over stop searching: */
  2465. pulled_task = load_balance_newidle(this_cpu,
  2466. this_rq, sd);
  2467. if (time_after(next_balance,
  2468. sd->last_balance + sd->balance_interval))
  2469. next_balance = sd->last_balance
  2470. + sd->balance_interval;
  2471. if (pulled_task)
  2472. break;
  2473. }
  2474. }
  2475. if (!pulled_task)
  2476. /*
  2477. * We are going idle. next_balance may be set based on
  2478. * a busy processor. So reset next_balance.
  2479. */
  2480. this_rq->next_balance = next_balance;
  2481. }
  2482. /*
  2483. * active_load_balance is run by migration threads. It pushes running tasks
  2484. * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
  2485. * running on each physical CPU where possible, and avoids physical /
  2486. * logical imbalances.
  2487. *
  2488. * Called with busiest_rq locked.
  2489. */
  2490. static void active_load_balance(struct rq *busiest_rq, int busiest_cpu)
  2491. {
  2492. int target_cpu = busiest_rq->push_cpu;
  2493. struct sched_domain *sd;
  2494. struct rq *target_rq;
  2495. /* Is there any task to move? */
  2496. if (busiest_rq->nr_running <= 1)
  2497. return;
  2498. target_rq = cpu_rq(target_cpu);
  2499. /*
  2500. * This condition is "impossible", if it occurs
  2501. * we need to fix it. Originally reported by
  2502. * Bjorn Helgaas on a 128-cpu setup.
  2503. */
  2504. BUG_ON(busiest_rq == target_rq);
  2505. /* move a task from busiest_rq to target_rq */
  2506. double_lock_balance(busiest_rq, target_rq);
  2507. /* Search for an sd spanning us and the target CPU. */
  2508. for_each_domain(target_cpu, sd) {
  2509. if ((sd->flags & SD_LOAD_BALANCE) &&
  2510. cpu_isset(busiest_cpu, sd->span))
  2511. break;
  2512. }
  2513. if (likely(sd)) {
  2514. schedstat_inc(sd, alb_cnt);
  2515. if (move_tasks(target_rq, target_cpu, busiest_rq, 1,
  2516. RTPRIO_TO_LOAD_WEIGHT(100), sd, SCHED_IDLE,
  2517. NULL))
  2518. schedstat_inc(sd, alb_pushed);
  2519. else
  2520. schedstat_inc(sd, alb_failed);
  2521. }
  2522. spin_unlock(&target_rq->lock);
  2523. }
  2524. static void update_load(struct rq *this_rq)
  2525. {
  2526. unsigned long this_load;
  2527. int i, scale;
  2528. this_load = this_rq->raw_weighted_load;
  2529. /* Update our load: */
  2530. for (i = 0, scale = 1; i < 3; i++, scale <<= 1) {
  2531. unsigned long old_load, new_load;
  2532. old_load = this_rq->cpu_load[i];
  2533. new_load = this_load;
  2534. /*
  2535. * Round up the averaging division if load is increasing. This
  2536. * prevents us from getting stuck on 9 if the load is 10, for
  2537. * example.
  2538. */
  2539. if (new_load > old_load)
  2540. new_load += scale-1;
  2541. this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) / scale;
  2542. }
  2543. }
  2544. /*
  2545. * run_rebalance_domains is triggered when needed from the scheduler tick.
  2546. *
  2547. * It checks each scheduling domain to see if it is due to be balanced,
  2548. * and initiates a balancing operation if so.
  2549. *
  2550. * Balancing parameters are set up in arch_init_sched_domains.
  2551. */
  2552. static DEFINE_SPINLOCK(balancing);
  2553. static void run_rebalance_domains(struct softirq_action *h)
  2554. {
  2555. int this_cpu = smp_processor_id(), balance = 1;
  2556. struct rq *this_rq = cpu_rq(this_cpu);
  2557. unsigned long interval;
  2558. struct sched_domain *sd;
  2559. /*
  2560. * We are idle if there are no processes running. This
  2561. * is valid even if we are the idle process (SMT).
  2562. */
  2563. enum idle_type idle = !this_rq->nr_running ?
  2564. SCHED_IDLE : NOT_IDLE;
  2565. /* Earliest time when we have to call run_rebalance_domains again */
  2566. unsigned long next_balance = jiffies + 60*HZ;
  2567. for_each_domain(this_cpu, sd) {
  2568. if (!(sd->flags & SD_LOAD_BALANCE))
  2569. continue;
  2570. interval = sd->balance_interval;
  2571. if (idle != SCHED_IDLE)
  2572. interval *= sd->busy_factor;
  2573. /* scale ms to jiffies */
  2574. interval = msecs_to_jiffies(interval);
  2575. if (unlikely(!interval))
  2576. interval = 1;
  2577. if (sd->flags & SD_SERIALIZE) {
  2578. if (!spin_trylock(&balancing))
  2579. goto out;
  2580. }
  2581. if (time_after_eq(jiffies, sd->last_balance + interval)) {
  2582. if (load_balance(this_cpu, this_rq, sd, idle, &balance)) {
  2583. /*
  2584. * We've pulled tasks over so either we're no
  2585. * longer idle, or one of our SMT siblings is
  2586. * not idle.
  2587. */
  2588. idle = NOT_IDLE;
  2589. }
  2590. sd->last_balance = jiffies;
  2591. }
  2592. if (sd->flags & SD_SERIALIZE)
  2593. spin_unlock(&balancing);
  2594. out:
  2595. if (time_after(next_balance, sd->last_balance + interval))
  2596. next_balance = sd->last_balance + interval;
  2597. /*
  2598. * Stop the load balance at this level. There is another
  2599. * CPU in our sched group which is doing load balancing more
  2600. * actively.
  2601. */
  2602. if (!balance)
  2603. break;
  2604. }
  2605. this_rq->next_balance = next_balance;
  2606. }
  2607. #else
  2608. /*
  2609. * on UP we do not need to balance between CPUs:
  2610. */
  2611. static inline void idle_balance(int cpu, struct rq *rq)
  2612. {
  2613. }
  2614. #endif
  2615. static inline void wake_priority_sleeper(struct rq *rq)
  2616. {
  2617. #ifdef CONFIG_SCHED_SMT
  2618. if (!rq->nr_running)
  2619. return;
  2620. spin_lock(&rq->lock);
  2621. /*
  2622. * If an SMT sibling task has been put to sleep for priority
  2623. * reasons reschedule the idle task to see if it can now run.
  2624. */
  2625. if (rq->nr_running)
  2626. resched_task(rq->idle);
  2627. spin_unlock(&rq->lock);
  2628. #endif
  2629. }
  2630. DEFINE_PER_CPU(struct kernel_stat, kstat);
  2631. EXPORT_PER_CPU_SYMBOL(kstat);
  2632. /*
  2633. * This is called on clock ticks and on context switches.
  2634. * Bank in p->sched_time the ns elapsed since the last tick or switch.
  2635. */
  2636. static inline void
  2637. update_cpu_clock(struct task_struct *p, struct rq *rq, unsigned long long now)
  2638. {
  2639. p->sched_time += now - p->last_ran;
  2640. p->last_ran = rq->most_recent_timestamp = now;
  2641. }
  2642. /*
  2643. * Return current->sched_time plus any more ns on the sched_clock
  2644. * that have not yet been banked.
  2645. */
  2646. unsigned long long current_sched_time(const struct task_struct *p)
  2647. {
  2648. unsigned long long ns;
  2649. unsigned long flags;
  2650. local_irq_save(flags);
  2651. ns = p->sched_time + sched_clock() - p->last_ran;
  2652. local_irq_restore(flags);
  2653. return ns;
  2654. }
  2655. /*
  2656. * We place interactive tasks back into the active array, if possible.
  2657. *
  2658. * To guarantee that this does not starve expired tasks we ignore the
  2659. * interactivity of a task if the first expired task had to wait more
  2660. * than a 'reasonable' amount of time. This deadline timeout is
  2661. * load-dependent, as the frequency of array switched decreases with
  2662. * increasing number of running tasks. We also ignore the interactivity
  2663. * if a better static_prio task has expired:
  2664. */
  2665. static inline int expired_starving(struct rq *rq)
  2666. {
  2667. if (rq->curr->static_prio > rq->best_expired_prio)
  2668. return 1;
  2669. if (!STARVATION_LIMIT || !rq->expired_timestamp)
  2670. return 0;
  2671. if (jiffies - rq->expired_timestamp > STARVATION_LIMIT * rq->nr_running)
  2672. return 1;
  2673. return 0;
  2674. }
  2675. /*
  2676. * Account user cpu time to a process.
  2677. * @p: the process that the cpu time gets accounted to
  2678. * @hardirq_offset: the offset to subtract from hardirq_count()
  2679. * @cputime: the cpu time spent in user space since the last update
  2680. */
  2681. void account_user_time(struct task_struct *p, cputime_t cputime)
  2682. {
  2683. struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
  2684. cputime64_t tmp;
  2685. p->utime = cputime_add(p->utime, cputime);
  2686. /* Add user time to cpustat. */
  2687. tmp = cputime_to_cputime64(cputime);
  2688. if (TASK_NICE(p) > 0)
  2689. cpustat->nice = cputime64_add(cpustat->nice, tmp);
  2690. else
  2691. cpustat->user = cputime64_add(cpustat->user, tmp);
  2692. }
  2693. /*
  2694. * Account system cpu time to a process.
  2695. * @p: the process that the cpu time gets accounted to
  2696. * @hardirq_offset: the offset to subtract from hardirq_count()
  2697. * @cputime: the cpu time spent in kernel space since the last update
  2698. */
  2699. void account_system_time(struct task_struct *p, int hardirq_offset,
  2700. cputime_t cputime)
  2701. {
  2702. struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
  2703. struct rq *rq = this_rq();
  2704. cputime64_t tmp;
  2705. p->stime = cputime_add(p->stime, cputime);
  2706. /* Add system time to cpustat. */
  2707. tmp = cputime_to_cputime64(cputime);
  2708. if (hardirq_count() - hardirq_offset)
  2709. cpustat->irq = cputime64_add(cpustat->irq, tmp);
  2710. else if (softirq_count())
  2711. cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
  2712. else if (p != rq->idle)
  2713. cpustat->system = cputime64_add(cpustat->system, tmp);
  2714. else if (atomic_read(&rq->nr_iowait) > 0)
  2715. cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
  2716. else
  2717. cpustat->idle = cputime64_add(cpustat->idle, tmp);
  2718. /* Account for system time used */
  2719. acct_update_integrals(p);
  2720. }
  2721. /*
  2722. * Account for involuntary wait time.
  2723. * @p: the process from which the cpu time has been stolen
  2724. * @steal: the cpu time spent in involuntary wait
  2725. */
  2726. void account_steal_time(struct task_struct *p, cputime_t steal)
  2727. {
  2728. struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
  2729. cputime64_t tmp = cputime_to_cputime64(steal);
  2730. struct rq *rq = this_rq();
  2731. if (p == rq->idle) {
  2732. p->stime = cputime_add(p->stime, steal);
  2733. if (atomic_read(&rq->nr_iowait) > 0)
  2734. cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
  2735. else
  2736. cpustat->idle = cputime64_add(cpustat->idle, tmp);
  2737. } else
  2738. cpustat->steal = cputime64_add(cpustat->steal, tmp);
  2739. }
  2740. static void task_running_tick(struct rq *rq, struct task_struct *p)
  2741. {
  2742. if (p->array != rq->active) {
  2743. /* Task has expired but was not scheduled yet */
  2744. set_tsk_need_resched(p);
  2745. return;
  2746. }
  2747. spin_lock(&rq->lock);
  2748. /*
  2749. * The task was running during this tick - update the
  2750. * time slice counter. Note: we do not update a thread's
  2751. * priority until it either goes to sleep or uses up its
  2752. * timeslice. This makes it possible for interactive tasks
  2753. * to use up their timeslices at their highest priority levels.
  2754. */
  2755. if (rt_task(p)) {
  2756. /*
  2757. * RR tasks need a special form of timeslice management.
  2758. * FIFO tasks have no timeslices.
  2759. */
  2760. if ((p->policy == SCHED_RR) && !--p->time_slice) {
  2761. p->time_slice = task_timeslice(p);
  2762. p->first_time_slice = 0;
  2763. set_tsk_need_resched(p);
  2764. /* put it at the end of the queue: */
  2765. requeue_task(p, rq->active);
  2766. }
  2767. goto out_unlock;
  2768. }
  2769. if (!--p->time_slice) {
  2770. dequeue_task(p, rq->active);
  2771. set_tsk_need_resched(p);
  2772. p->prio = effective_prio(p);
  2773. p->time_slice = task_timeslice(p);
  2774. p->first_time_slice = 0;
  2775. if (!rq->expired_timestamp)
  2776. rq->expired_timestamp = jiffies;
  2777. if (!TASK_INTERACTIVE(p) || expired_starving(rq)) {
  2778. enqueue_task(p, rq->expired);
  2779. if (p->static_prio < rq->best_expired_prio)
  2780. rq->best_expired_prio = p->static_prio;
  2781. } else
  2782. enqueue_task(p, rq->active);
  2783. } else {
  2784. /*
  2785. * Prevent a too long timeslice allowing a task to monopolize
  2786. * the CPU. We do this by splitting up the timeslice into
  2787. * smaller pieces.
  2788. *
  2789. * Note: this does not mean the task's timeslices expire or
  2790. * get lost in any way, they just might be preempted by
  2791. * another task of equal priority. (one with higher
  2792. * priority would have preempted this task already.) We
  2793. * requeue this task to the end of the list on this priority
  2794. * level, which is in essence a round-robin of tasks with
  2795. * equal priority.
  2796. *
  2797. * This only applies to tasks in the interactive
  2798. * delta range with at least TIMESLICE_GRANULARITY to requeue.
  2799. */
  2800. if (TASK_INTERACTIVE(p) && !((task_timeslice(p) -
  2801. p->time_slice) % TIMESLICE_GRANULARITY(p)) &&
  2802. (p->time_slice >= TIMESLICE_GRANULARITY(p)) &&
  2803. (p->array == rq->active)) {
  2804. requeue_task(p, rq->active);
  2805. set_tsk_need_resched(p);
  2806. }
  2807. }
  2808. out_unlock:
  2809. spin_unlock(&rq->lock);
  2810. }
  2811. /*
  2812. * This function gets called by the timer code, with HZ frequency.
  2813. * We call it with interrupts disabled.
  2814. *
  2815. * It also gets called by the fork code, when changing the parent's
  2816. * timeslices.
  2817. */
  2818. void scheduler_tick(void)
  2819. {
  2820. unsigned long long now = sched_clock();
  2821. struct task_struct *p = current;
  2822. int cpu = smp_processor_id();
  2823. struct rq *rq = cpu_rq(cpu);
  2824. update_cpu_clock(p, rq, now);
  2825. if (p == rq->idle)
  2826. /* Task on the idle queue */
  2827. wake_priority_sleeper(rq);
  2828. else
  2829. task_running_tick(rq, p);
  2830. #ifdef CONFIG_SMP
  2831. update_load(rq);
  2832. if (time_after_eq(jiffies, rq->next_balance))
  2833. raise_softirq(SCHED_SOFTIRQ);
  2834. #endif
  2835. }
  2836. #ifdef CONFIG_SCHED_SMT
  2837. static inline void wakeup_busy_runqueue(struct rq *rq)
  2838. {
  2839. /* If an SMT runqueue is sleeping due to priority reasons wake it up */
  2840. if (rq->curr == rq->idle && rq->nr_running)
  2841. resched_task(rq->idle);
  2842. }
  2843. /*
  2844. * Called with interrupt disabled and this_rq's runqueue locked.
  2845. */
  2846. static void wake_sleeping_dependent(int this_cpu)
  2847. {
  2848. struct sched_domain *tmp, *sd = NULL;
  2849. int i;
  2850. for_each_domain(this_cpu, tmp) {
  2851. if (tmp->flags & SD_SHARE_CPUPOWER) {
  2852. sd = tmp;
  2853. break;
  2854. }
  2855. }
  2856. if (!sd)
  2857. return;
  2858. for_each_cpu_mask(i, sd->span) {
  2859. struct rq *smt_rq = cpu_rq(i);
  2860. if (i == this_cpu)
  2861. continue;
  2862. if (unlikely(!spin_trylock(&smt_rq->lock)))
  2863. continue;
  2864. wakeup_busy_runqueue(smt_rq);
  2865. spin_unlock(&smt_rq->lock);
  2866. }
  2867. }
  2868. /*
  2869. * number of 'lost' timeslices this task wont be able to fully
  2870. * utilize, if another task runs on a sibling. This models the
  2871. * slowdown effect of other tasks running on siblings:
  2872. */
  2873. static inline unsigned long
  2874. smt_slice(struct task_struct *p, struct sched_domain *sd)
  2875. {
  2876. return p->time_slice * (100 - sd->per_cpu_gain) / 100;
  2877. }
  2878. /*
  2879. * To minimise lock contention and not have to drop this_rq's runlock we only
  2880. * trylock the sibling runqueues and bypass those runqueues if we fail to
  2881. * acquire their lock. As we only trylock the normal locking order does not
  2882. * need to be obeyed.
  2883. */
  2884. static int
  2885. dependent_sleeper(int this_cpu, struct rq *this_rq, struct task_struct *p)
  2886. {
  2887. struct sched_domain *tmp, *sd = NULL;
  2888. int ret = 0, i;
  2889. /* kernel/rt threads do not participate in dependent sleeping */
  2890. if (!p->mm || rt_task(p))
  2891. return 0;
  2892. for_each_domain(this_cpu, tmp) {
  2893. if (tmp->flags & SD_SHARE_CPUPOWER) {
  2894. sd = tmp;
  2895. break;
  2896. }
  2897. }
  2898. if (!sd)
  2899. return 0;
  2900. for_each_cpu_mask(i, sd->span) {
  2901. struct task_struct *smt_curr;
  2902. struct rq *smt_rq;
  2903. if (i == this_cpu)
  2904. continue;
  2905. smt_rq = cpu_rq(i);
  2906. if (unlikely(!spin_trylock(&smt_rq->lock)))
  2907. continue;
  2908. smt_curr = smt_rq->curr;
  2909. if (!smt_curr->mm)
  2910. goto unlock;
  2911. /*
  2912. * If a user task with lower static priority than the
  2913. * running task on the SMT sibling is trying to schedule,
  2914. * delay it till there is proportionately less timeslice
  2915. * left of the sibling task to prevent a lower priority
  2916. * task from using an unfair proportion of the
  2917. * physical cpu's resources. -ck
  2918. */
  2919. if (rt_task(smt_curr)) {
  2920. /*
  2921. * With real time tasks we run non-rt tasks only
  2922. * per_cpu_gain% of the time.
  2923. */
  2924. if ((jiffies % DEF_TIMESLICE) >
  2925. (sd->per_cpu_gain * DEF_TIMESLICE / 100))
  2926. ret = 1;
  2927. } else {
  2928. if (smt_curr->static_prio < p->static_prio &&
  2929. !TASK_PREEMPTS_CURR(p, smt_rq) &&
  2930. smt_slice(smt_curr, sd) > task_timeslice(p))
  2931. ret = 1;
  2932. }
  2933. unlock:
  2934. spin_unlock(&smt_rq->lock);
  2935. }
  2936. return ret;
  2937. }
  2938. #else
  2939. static inline void wake_sleeping_dependent(int this_cpu)
  2940. {
  2941. }
  2942. static inline int
  2943. dependent_sleeper(int this_cpu, struct rq *this_rq, struct task_struct *p)
  2944. {
  2945. return 0;
  2946. }
  2947. #endif
  2948. #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
  2949. void fastcall add_preempt_count(int val)
  2950. {
  2951. /*
  2952. * Underflow?
  2953. */
  2954. if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
  2955. return;
  2956. preempt_count() += val;
  2957. /*
  2958. * Spinlock count overflowing soon?
  2959. */
  2960. DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
  2961. PREEMPT_MASK - 10);
  2962. }
  2963. EXPORT_SYMBOL(add_preempt_count);
  2964. void fastcall sub_preempt_count(int val)
  2965. {
  2966. /*
  2967. * Underflow?
  2968. */
  2969. if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
  2970. return;
  2971. /*
  2972. * Is the spinlock portion underflowing?
  2973. */
  2974. if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
  2975. !(preempt_count() & PREEMPT_MASK)))
  2976. return;
  2977. preempt_count() -= val;
  2978. }
  2979. EXPORT_SYMBOL(sub_preempt_count);
  2980. #endif
  2981. static inline int interactive_sleep(enum sleep_type sleep_type)
  2982. {
  2983. return (sleep_type == SLEEP_INTERACTIVE ||
  2984. sleep_type == SLEEP_INTERRUPTED);
  2985. }
  2986. /*
  2987. * schedule() is the main scheduler function.
  2988. */
  2989. asmlinkage void __sched schedule(void)
  2990. {
  2991. struct task_struct *prev, *next;
  2992. struct prio_array *array;
  2993. struct list_head *queue;
  2994. unsigned long long now;
  2995. unsigned long run_time;
  2996. int cpu, idx, new_prio;
  2997. long *switch_count;
  2998. struct rq *rq;
  2999. /*
  3000. * Test if we are atomic. Since do_exit() needs to call into
  3001. * schedule() atomically, we ignore that path for now.
  3002. * Otherwise, whine if we are scheduling when we should not be.
  3003. */
  3004. if (unlikely(in_atomic() && !current->exit_state)) {
  3005. printk(KERN_ERR "BUG: scheduling while atomic: "
  3006. "%s/0x%08x/%d\n",
  3007. current->comm, preempt_count(), current->pid);
  3008. debug_show_held_locks(current);
  3009. if (irqs_disabled())
  3010. print_irqtrace_events(current);
  3011. dump_stack();
  3012. }
  3013. profile_hit(SCHED_PROFILING, __builtin_return_address(0));
  3014. need_resched:
  3015. preempt_disable();
  3016. prev = current;
  3017. release_kernel_lock(prev);
  3018. need_resched_nonpreemptible:
  3019. rq = this_rq();
  3020. /*
  3021. * The idle thread is not allowed to schedule!
  3022. * Remove this check after it has been exercised a bit.
  3023. */
  3024. if (unlikely(prev == rq->idle) && prev->state != TASK_RUNNING) {
  3025. printk(KERN_ERR "bad: scheduling from the idle thread!\n");
  3026. dump_stack();
  3027. }
  3028. schedstat_inc(rq, sched_cnt);
  3029. now = sched_clock();
  3030. if (likely((long long)(now - prev->timestamp) < NS_MAX_SLEEP_AVG)) {
  3031. run_time = now - prev->timestamp;
  3032. if (unlikely((long long)(now - prev->timestamp) < 0))
  3033. run_time = 0;
  3034. } else
  3035. run_time = NS_MAX_SLEEP_AVG;
  3036. /*
  3037. * Tasks charged proportionately less run_time at high sleep_avg to
  3038. * delay them losing their interactive status
  3039. */
  3040. run_time /= (CURRENT_BONUS(prev) ? : 1);
  3041. spin_lock_irq(&rq->lock);
  3042. switch_count = &prev->nivcsw;
  3043. if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
  3044. switch_count = &prev->nvcsw;
  3045. if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
  3046. unlikely(signal_pending(prev))))
  3047. prev->state = TASK_RUNNING;
  3048. else {
  3049. if (prev->state == TASK_UNINTERRUPTIBLE)
  3050. rq->nr_uninterruptible++;
  3051. deactivate_task(prev, rq);
  3052. }
  3053. }
  3054. cpu = smp_processor_id();
  3055. if (unlikely(!rq->nr_running)) {
  3056. idle_balance(cpu, rq);
  3057. if (!rq->nr_running) {
  3058. next = rq->idle;
  3059. rq->expired_timestamp = 0;
  3060. wake_sleeping_dependent(cpu);
  3061. goto switch_tasks;
  3062. }
  3063. }
  3064. array = rq->active;
  3065. if (unlikely(!array->nr_active)) {
  3066. /*
  3067. * Switch the active and expired arrays.
  3068. */
  3069. schedstat_inc(rq, sched_switch);
  3070. rq->active = rq->expired;
  3071. rq->expired = array;
  3072. array = rq->active;
  3073. rq->expired_timestamp = 0;
  3074. rq->best_expired_prio = MAX_PRIO;
  3075. }
  3076. idx = sched_find_first_bit(array->bitmap);
  3077. queue = array->queue + idx;
  3078. next = list_entry(queue->next, struct task_struct, run_list);
  3079. if (!rt_task(next) && interactive_sleep(next->sleep_type)) {
  3080. unsigned long long delta = now - next->timestamp;
  3081. if (unlikely((long long)(now - next->timestamp) < 0))
  3082. delta = 0;
  3083. if (next->sleep_type == SLEEP_INTERACTIVE)
  3084. delta = delta * (ON_RUNQUEUE_WEIGHT * 128 / 100) / 128;
  3085. array = next->array;
  3086. new_prio = recalc_task_prio(next, next->timestamp + delta);
  3087. if (unlikely(next->prio != new_prio)) {
  3088. dequeue_task(next, array);
  3089. next->prio = new_prio;
  3090. enqueue_task(next, array);
  3091. }
  3092. }
  3093. next->sleep_type = SLEEP_NORMAL;
  3094. if (dependent_sleeper(cpu, rq, next))
  3095. next = rq->idle;
  3096. switch_tasks:
  3097. if (next == rq->idle)
  3098. schedstat_inc(rq, sched_goidle);
  3099. prefetch(next);
  3100. prefetch_stack(next);
  3101. clear_tsk_need_resched(prev);
  3102. rcu_qsctr_inc(task_cpu(prev));
  3103. update_cpu_clock(prev, rq, now);
  3104. prev->sleep_avg -= run_time;
  3105. if ((long)prev->sleep_avg <= 0)
  3106. prev->sleep_avg = 0;
  3107. prev->timestamp = prev->last_ran = now;
  3108. sched_info_switch(prev, next);
  3109. if (likely(prev != next)) {
  3110. next->timestamp = now;
  3111. rq->nr_switches++;
  3112. rq->curr = next;
  3113. ++*switch_count;
  3114. prepare_task_switch(rq, next);
  3115. prev = context_switch(rq, prev, next);
  3116. barrier();
  3117. /*
  3118. * this_rq must be evaluated again because prev may have moved
  3119. * CPUs since it called schedule(), thus the 'rq' on its stack
  3120. * frame will be invalid.
  3121. */
  3122. finish_task_switch(this_rq(), prev);
  3123. } else
  3124. spin_unlock_irq(&rq->lock);
  3125. prev = current;
  3126. if (unlikely(reacquire_kernel_lock(prev) < 0))
  3127. goto need_resched_nonpreemptible;
  3128. preempt_enable_no_resched();
  3129. if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
  3130. goto need_resched;
  3131. }
  3132. EXPORT_SYMBOL(schedule);
  3133. #ifdef CONFIG_PREEMPT
  3134. /*
  3135. * this is the entry point to schedule() from in-kernel preemption
  3136. * off of preempt_enable. Kernel preemptions off return from interrupt
  3137. * occur there and call schedule directly.
  3138. */
  3139. asmlinkage void __sched preempt_schedule(void)
  3140. {
  3141. struct thread_info *ti = current_thread_info();
  3142. #ifdef CONFIG_PREEMPT_BKL
  3143. struct task_struct *task = current;
  3144. int saved_lock_depth;
  3145. #endif
  3146. /*
  3147. * If there is a non-zero preempt_count or interrupts are disabled,
  3148. * we do not want to preempt the current task. Just return..
  3149. */
  3150. if (likely(ti->preempt_count || irqs_disabled()))
  3151. return;
  3152. need_resched:
  3153. add_preempt_count(PREEMPT_ACTIVE);
  3154. /*
  3155. * We keep the big kernel semaphore locked, but we
  3156. * clear ->lock_depth so that schedule() doesnt
  3157. * auto-release the semaphore:
  3158. */
  3159. #ifdef CONFIG_PREEMPT_BKL
  3160. saved_lock_depth = task->lock_depth;
  3161. task->lock_depth = -1;
  3162. #endif
  3163. schedule();
  3164. #ifdef CONFIG_PREEMPT_BKL
  3165. task->lock_depth = saved_lock_depth;
  3166. #endif
  3167. sub_preempt_count(PREEMPT_ACTIVE);
  3168. /* we could miss a preemption opportunity between schedule and now */
  3169. barrier();
  3170. if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
  3171. goto need_resched;
  3172. }
  3173. EXPORT_SYMBOL(preempt_schedule);
  3174. /*
  3175. * this is the entry point to schedule() from kernel preemption
  3176. * off of irq context.
  3177. * Note, that this is called and return with irqs disabled. This will
  3178. * protect us against recursive calling from irq.
  3179. */
  3180. asmlinkage void __sched preempt_schedule_irq(void)
  3181. {
  3182. struct thread_info *ti = current_thread_info();
  3183. #ifdef CONFIG_PREEMPT_BKL
  3184. struct task_struct *task = current;
  3185. int saved_lock_depth;
  3186. #endif
  3187. /* Catch callers which need to be fixed */
  3188. BUG_ON(ti->preempt_count || !irqs_disabled());
  3189. need_resched:
  3190. add_preempt_count(PREEMPT_ACTIVE);
  3191. /*
  3192. * We keep the big kernel semaphore locked, but we
  3193. * clear ->lock_depth so that schedule() doesnt
  3194. * auto-release the semaphore:
  3195. */
  3196. #ifdef CONFIG_PREEMPT_BKL
  3197. saved_lock_depth = task->lock_depth;
  3198. task->lock_depth = -1;
  3199. #endif
  3200. local_irq_enable();
  3201. schedule();
  3202. local_irq_disable();
  3203. #ifdef CONFIG_PREEMPT_BKL
  3204. task->lock_depth = saved_lock_depth;
  3205. #endif
  3206. sub_preempt_count(PREEMPT_ACTIVE);
  3207. /* we could miss a preemption opportunity between schedule and now */
  3208. barrier();
  3209. if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
  3210. goto need_resched;
  3211. }
  3212. #endif /* CONFIG_PREEMPT */
  3213. int default_wake_function(wait_queue_t *curr, unsigned mode, int sync,
  3214. void *key)
  3215. {
  3216. return try_to_wake_up(curr->private, mode, sync);
  3217. }
  3218. EXPORT_SYMBOL(default_wake_function);
  3219. /*
  3220. * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
  3221. * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
  3222. * number) then we wake all the non-exclusive tasks and one exclusive task.
  3223. *
  3224. * There are circumstances in which we can try to wake a task which has already
  3225. * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
  3226. * zero in this (rare) case, and we handle it by continuing to scan the queue.
  3227. */
  3228. static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
  3229. int nr_exclusive, int sync, void *key)
  3230. {
  3231. struct list_head *tmp, *next;
  3232. list_for_each_safe(tmp, next, &q->task_list) {
  3233. wait_queue_t *curr = list_entry(tmp, wait_queue_t, task_list);
  3234. unsigned flags = curr->flags;
  3235. if (curr->func(curr, mode, sync, key) &&
  3236. (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
  3237. break;
  3238. }
  3239. }
  3240. /**
  3241. * __wake_up - wake up threads blocked on a waitqueue.
  3242. * @q: the waitqueue
  3243. * @mode: which threads
  3244. * @nr_exclusive: how many wake-one or wake-many threads to wake up
  3245. * @key: is directly passed to the wakeup function
  3246. */
  3247. void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
  3248. int nr_exclusive, void *key)
  3249. {
  3250. unsigned long flags;
  3251. spin_lock_irqsave(&q->lock, flags);
  3252. __wake_up_common(q, mode, nr_exclusive, 0, key);
  3253. spin_unlock_irqrestore(&q->lock, flags);
  3254. }
  3255. EXPORT_SYMBOL(__wake_up);
  3256. /*
  3257. * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
  3258. */
  3259. void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
  3260. {
  3261. __wake_up_common(q, mode, 1, 0, NULL);
  3262. }
  3263. /**
  3264. * __wake_up_sync - wake up threads blocked on a waitqueue.
  3265. * @q: the waitqueue
  3266. * @mode: which threads
  3267. * @nr_exclusive: how many wake-one or wake-many threads to wake up
  3268. *
  3269. * The sync wakeup differs that the waker knows that it will schedule
  3270. * away soon, so while the target thread will be woken up, it will not
  3271. * be migrated to another CPU - ie. the two threads are 'synchronized'
  3272. * with each other. This can prevent needless bouncing between CPUs.
  3273. *
  3274. * On UP it can prevent extra preemption.
  3275. */
  3276. void fastcall
  3277. __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
  3278. {
  3279. unsigned long flags;
  3280. int sync = 1;
  3281. if (unlikely(!q))
  3282. return;
  3283. if (unlikely(!nr_exclusive))
  3284. sync = 0;
  3285. spin_lock_irqsave(&q->lock, flags);
  3286. __wake_up_common(q, mode, nr_exclusive, sync, NULL);
  3287. spin_unlock_irqrestore(&q->lock, flags);
  3288. }
  3289. EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
  3290. void fastcall complete(struct completion *x)
  3291. {
  3292. unsigned long flags;
  3293. spin_lock_irqsave(&x->wait.lock, flags);
  3294. x->done++;
  3295. __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
  3296. 1, 0, NULL);
  3297. spin_unlock_irqrestore(&x->wait.lock, flags);
  3298. }
  3299. EXPORT_SYMBOL(complete);
  3300. void fastcall complete_all(struct completion *x)
  3301. {
  3302. unsigned long flags;
  3303. spin_lock_irqsave(&x->wait.lock, flags);
  3304. x->done += UINT_MAX/2;
  3305. __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
  3306. 0, 0, NULL);
  3307. spin_unlock_irqrestore(&x->wait.lock, flags);
  3308. }
  3309. EXPORT_SYMBOL(complete_all);
  3310. void fastcall __sched wait_for_completion(struct completion *x)
  3311. {
  3312. might_sleep();
  3313. spin_lock_irq(&x->wait.lock);
  3314. if (!x->done) {
  3315. DECLARE_WAITQUEUE(wait, current);
  3316. wait.flags |= WQ_FLAG_EXCLUSIVE;
  3317. __add_wait_queue_tail(&x->wait, &wait);
  3318. do {
  3319. __set_current_state(TASK_UNINTERRUPTIBLE);
  3320. spin_unlock_irq(&x->wait.lock);
  3321. schedule();
  3322. spin_lock_irq(&x->wait.lock);
  3323. } while (!x->done);
  3324. __remove_wait_queue(&x->wait, &wait);
  3325. }
  3326. x->done--;
  3327. spin_unlock_irq(&x->wait.lock);
  3328. }
  3329. EXPORT_SYMBOL(wait_for_completion);
  3330. unsigned long fastcall __sched
  3331. wait_for_completion_timeout(struct completion *x, unsigned long timeout)
  3332. {
  3333. might_sleep();
  3334. spin_lock_irq(&x->wait.lock);
  3335. if (!x->done) {
  3336. DECLARE_WAITQUEUE(wait, current);
  3337. wait.flags |= WQ_FLAG_EXCLUSIVE;
  3338. __add_wait_queue_tail(&x->wait, &wait);
  3339. do {
  3340. __set_current_state(TASK_UNINTERRUPTIBLE);
  3341. spin_unlock_irq(&x->wait.lock);
  3342. timeout = schedule_timeout(timeout);
  3343. spin_lock_irq(&x->wait.lock);
  3344. if (!timeout) {
  3345. __remove_wait_queue(&x->wait, &wait);
  3346. goto out;
  3347. }
  3348. } while (!x->done);
  3349. __remove_wait_queue(&x->wait, &wait);
  3350. }
  3351. x->done--;
  3352. out:
  3353. spin_unlock_irq(&x->wait.lock);
  3354. return timeout;
  3355. }
  3356. EXPORT_SYMBOL(wait_for_completion_timeout);
  3357. int fastcall __sched wait_for_completion_interruptible(struct completion *x)
  3358. {
  3359. int ret = 0;
  3360. might_sleep();
  3361. spin_lock_irq(&x->wait.lock);
  3362. if (!x->done) {
  3363. DECLARE_WAITQUEUE(wait, current);
  3364. wait.flags |= WQ_FLAG_EXCLUSIVE;
  3365. __add_wait_queue_tail(&x->wait, &wait);
  3366. do {
  3367. if (signal_pending(current)) {
  3368. ret = -ERESTARTSYS;
  3369. __remove_wait_queue(&x->wait, &wait);
  3370. goto out;
  3371. }
  3372. __set_current_state(TASK_INTERRUPTIBLE);
  3373. spin_unlock_irq(&x->wait.lock);
  3374. schedule();
  3375. spin_lock_irq(&x->wait.lock);
  3376. } while (!x->done);
  3377. __remove_wait_queue(&x->wait, &wait);
  3378. }
  3379. x->done--;
  3380. out:
  3381. spin_unlock_irq(&x->wait.lock);
  3382. return ret;
  3383. }
  3384. EXPORT_SYMBOL(wait_for_completion_interruptible);
  3385. unsigned long fastcall __sched
  3386. wait_for_completion_interruptible_timeout(struct completion *x,
  3387. unsigned long timeout)
  3388. {
  3389. might_sleep();
  3390. spin_lock_irq(&x->wait.lock);
  3391. if (!x->done) {
  3392. DECLARE_WAITQUEUE(wait, current);
  3393. wait.flags |= WQ_FLAG_EXCLUSIVE;
  3394. __add_wait_queue_tail(&x->wait, &wait);
  3395. do {
  3396. if (signal_pending(current)) {
  3397. timeout = -ERESTARTSYS;
  3398. __remove_wait_queue(&x->wait, &wait);
  3399. goto out;
  3400. }
  3401. __set_current_state(TASK_INTERRUPTIBLE);
  3402. spin_unlock_irq(&x->wait.lock);
  3403. timeout = schedule_timeout(timeout);
  3404. spin_lock_irq(&x->wait.lock);
  3405. if (!timeout) {
  3406. __remove_wait_queue(&x->wait, &wait);
  3407. goto out;
  3408. }
  3409. } while (!x->done);
  3410. __remove_wait_queue(&x->wait, &wait);
  3411. }
  3412. x->done--;
  3413. out:
  3414. spin_unlock_irq(&x->wait.lock);
  3415. return timeout;
  3416. }
  3417. EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
  3418. #define SLEEP_ON_VAR \
  3419. unsigned long flags; \
  3420. wait_queue_t wait; \
  3421. init_waitqueue_entry(&wait, current);
  3422. #define SLEEP_ON_HEAD \
  3423. spin_lock_irqsave(&q->lock,flags); \
  3424. __add_wait_queue(q, &wait); \
  3425. spin_unlock(&q->lock);
  3426. #define SLEEP_ON_TAIL \
  3427. spin_lock_irq(&q->lock); \
  3428. __remove_wait_queue(q, &wait); \
  3429. spin_unlock_irqrestore(&q->lock, flags);
  3430. void fastcall __sched interruptible_sleep_on(wait_queue_head_t *q)
  3431. {
  3432. SLEEP_ON_VAR
  3433. current->state = TASK_INTERRUPTIBLE;
  3434. SLEEP_ON_HEAD
  3435. schedule();
  3436. SLEEP_ON_TAIL
  3437. }
  3438. EXPORT_SYMBOL(interruptible_sleep_on);
  3439. long fastcall __sched
  3440. interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
  3441. {
  3442. SLEEP_ON_VAR
  3443. current->state = TASK_INTERRUPTIBLE;
  3444. SLEEP_ON_HEAD
  3445. timeout = schedule_timeout(timeout);
  3446. SLEEP_ON_TAIL
  3447. return timeout;
  3448. }
  3449. EXPORT_SYMBOL(interruptible_sleep_on_timeout);
  3450. void fastcall __sched sleep_on(wait_queue_head_t *q)
  3451. {
  3452. SLEEP_ON_VAR
  3453. current->state = TASK_UNINTERRUPTIBLE;
  3454. SLEEP_ON_HEAD
  3455. schedule();
  3456. SLEEP_ON_TAIL
  3457. }
  3458. EXPORT_SYMBOL(sleep_on);
  3459. long fastcall __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
  3460. {
  3461. SLEEP_ON_VAR
  3462. current->state = TASK_UNINTERRUPTIBLE;
  3463. SLEEP_ON_HEAD
  3464. timeout = schedule_timeout(timeout);
  3465. SLEEP_ON_TAIL
  3466. return timeout;
  3467. }
  3468. EXPORT_SYMBOL(sleep_on_timeout);
  3469. #ifdef CONFIG_RT_MUTEXES
  3470. /*
  3471. * rt_mutex_setprio - set the current priority of a task
  3472. * @p: task
  3473. * @prio: prio value (kernel-internal form)
  3474. *
  3475. * This function changes the 'effective' priority of a task. It does
  3476. * not touch ->normal_prio like __setscheduler().
  3477. *
  3478. * Used by the rt_mutex code to implement priority inheritance logic.
  3479. */
  3480. void rt_mutex_setprio(struct task_struct *p, int prio)
  3481. {
  3482. struct prio_array *array;
  3483. unsigned long flags;
  3484. struct rq *rq;
  3485. int oldprio;
  3486. BUG_ON(prio < 0 || prio > MAX_PRIO);
  3487. rq = task_rq_lock(p, &flags);
  3488. oldprio = p->prio;
  3489. array = p->array;
  3490. if (array)
  3491. dequeue_task(p, array);
  3492. p->prio = prio;
  3493. if (array) {
  3494. /*
  3495. * If changing to an RT priority then queue it
  3496. * in the active array!
  3497. */
  3498. if (rt_task(p))
  3499. array = rq->active;
  3500. enqueue_task(p, array);
  3501. /*
  3502. * Reschedule if we are currently running on this runqueue and
  3503. * our priority decreased, or if we are not currently running on
  3504. * this runqueue and our priority is higher than the current's
  3505. */
  3506. if (task_running(rq, p)) {
  3507. if (p->prio > oldprio)
  3508. resched_task(rq->curr);
  3509. } else if (TASK_PREEMPTS_CURR(p, rq))
  3510. resched_task(rq->curr);
  3511. }
  3512. task_rq_unlock(rq, &flags);
  3513. }
  3514. #endif
  3515. void set_user_nice(struct task_struct *p, long nice)
  3516. {
  3517. struct prio_array *array;
  3518. int old_prio, delta;
  3519. unsigned long flags;
  3520. struct rq *rq;
  3521. if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
  3522. return;
  3523. /*
  3524. * We have to be careful, if called from sys_setpriority(),
  3525. * the task might be in the middle of scheduling on another CPU.
  3526. */
  3527. rq = task_rq_lock(p, &flags);
  3528. /*
  3529. * The RT priorities are set via sched_setscheduler(), but we still
  3530. * allow the 'normal' nice value to be set - but as expected
  3531. * it wont have any effect on scheduling until the task is
  3532. * not SCHED_NORMAL/SCHED_BATCH:
  3533. */
  3534. if (has_rt_policy(p)) {
  3535. p->static_prio = NICE_TO_PRIO(nice);
  3536. goto out_unlock;
  3537. }
  3538. array = p->array;
  3539. if (array) {
  3540. dequeue_task(p, array);
  3541. dec_raw_weighted_load(rq, p);
  3542. }
  3543. p->static_prio = NICE_TO_PRIO(nice);
  3544. set_load_weight(p);
  3545. old_prio = p->prio;
  3546. p->prio = effective_prio(p);
  3547. delta = p->prio - old_prio;
  3548. if (array) {
  3549. enqueue_task(p, array);
  3550. inc_raw_weighted_load(rq, p);
  3551. /*
  3552. * If the task increased its priority or is running and
  3553. * lowered its priority, then reschedule its CPU:
  3554. */
  3555. if (delta < 0 || (delta > 0 && task_running(rq, p)))
  3556. resched_task(rq->curr);
  3557. }
  3558. out_unlock:
  3559. task_rq_unlock(rq, &flags);
  3560. }
  3561. EXPORT_SYMBOL(set_user_nice);
  3562. /*
  3563. * can_nice - check if a task can reduce its nice value
  3564. * @p: task
  3565. * @nice: nice value
  3566. */
  3567. int can_nice(const struct task_struct *p, const int nice)
  3568. {
  3569. /* convert nice value [19,-20] to rlimit style value [1,40] */
  3570. int nice_rlim = 20 - nice;
  3571. return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
  3572. capable(CAP_SYS_NICE));
  3573. }
  3574. #ifdef __ARCH_WANT_SYS_NICE
  3575. /*
  3576. * sys_nice - change the priority of the current process.
  3577. * @increment: priority increment
  3578. *
  3579. * sys_setpriority is a more generic, but much slower function that
  3580. * does similar things.
  3581. */
  3582. asmlinkage long sys_nice(int increment)
  3583. {
  3584. long nice, retval;
  3585. /*
  3586. * Setpriority might change our priority at the same moment.
  3587. * We don't have to worry. Conceptually one call occurs first
  3588. * and we have a single winner.
  3589. */
  3590. if (increment < -40)
  3591. increment = -40;
  3592. if (increment > 40)
  3593. increment = 40;
  3594. nice = PRIO_TO_NICE(current->static_prio) + increment;
  3595. if (nice < -20)
  3596. nice = -20;
  3597. if (nice > 19)
  3598. nice = 19;
  3599. if (increment < 0 && !can_nice(current, nice))
  3600. return -EPERM;
  3601. retval = security_task_setnice(current, nice);
  3602. if (retval)
  3603. return retval;
  3604. set_user_nice(current, nice);
  3605. return 0;
  3606. }
  3607. #endif
  3608. /**
  3609. * task_prio - return the priority value of a given task.
  3610. * @p: the task in question.
  3611. *
  3612. * This is the priority value as seen by users in /proc.
  3613. * RT tasks are offset by -200. Normal tasks are centered
  3614. * around 0, value goes from -16 to +15.
  3615. */
  3616. int task_prio(const struct task_struct *p)
  3617. {
  3618. return p->prio - MAX_RT_PRIO;
  3619. }
  3620. /**
  3621. * task_nice - return the nice value of a given task.
  3622. * @p: the task in question.
  3623. */
  3624. int task_nice(const struct task_struct *p)
  3625. {
  3626. return TASK_NICE(p);
  3627. }
  3628. EXPORT_SYMBOL_GPL(task_nice);
  3629. /**
  3630. * idle_cpu - is a given cpu idle currently?
  3631. * @cpu: the processor in question.
  3632. */
  3633. int idle_cpu(int cpu)
  3634. {
  3635. return cpu_curr(cpu) == cpu_rq(cpu)->idle;
  3636. }
  3637. /**
  3638. * idle_task - return the idle task for a given cpu.
  3639. * @cpu: the processor in question.
  3640. */
  3641. struct task_struct *idle_task(int cpu)
  3642. {
  3643. return cpu_rq(cpu)->idle;
  3644. }
  3645. /**
  3646. * find_process_by_pid - find a process with a matching PID value.
  3647. * @pid: the pid in question.
  3648. */
  3649. static inline struct task_struct *find_process_by_pid(pid_t pid)
  3650. {
  3651. return pid ? find_task_by_pid(pid) : current;
  3652. }
  3653. /* Actually do priority change: must hold rq lock. */
  3654. static void __setscheduler(struct task_struct *p, int policy, int prio)
  3655. {
  3656. BUG_ON(p->array);
  3657. p->policy = policy;
  3658. p->rt_priority = prio;
  3659. p->normal_prio = normal_prio(p);
  3660. /* we are holding p->pi_lock already */
  3661. p->prio = rt_mutex_getprio(p);
  3662. /*
  3663. * SCHED_BATCH tasks are treated as perpetual CPU hogs:
  3664. */
  3665. if (policy == SCHED_BATCH)
  3666. p->sleep_avg = 0;
  3667. set_load_weight(p);
  3668. }
  3669. /**
  3670. * sched_setscheduler - change the scheduling policy and/or RT priority of
  3671. * a thread.
  3672. * @p: the task in question.
  3673. * @policy: new policy.
  3674. * @param: structure containing the new RT priority.
  3675. *
  3676. * NOTE: the task may be already dead
  3677. */
  3678. int sched_setscheduler(struct task_struct *p, int policy,
  3679. struct sched_param *param)
  3680. {
  3681. int retval, oldprio, oldpolicy = -1;
  3682. struct prio_array *array;
  3683. unsigned long flags;
  3684. struct rq *rq;
  3685. /* may grab non-irq protected spin_locks */
  3686. BUG_ON(in_interrupt());
  3687. recheck:
  3688. /* double check policy once rq lock held */
  3689. if (policy < 0)
  3690. policy = oldpolicy = p->policy;
  3691. else if (policy != SCHED_FIFO && policy != SCHED_RR &&
  3692. policy != SCHED_NORMAL && policy != SCHED_BATCH)
  3693. return -EINVAL;
  3694. /*
  3695. * Valid priorities for SCHED_FIFO and SCHED_RR are
  3696. * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL and
  3697. * SCHED_BATCH is 0.
  3698. */
  3699. if (param->sched_priority < 0 ||
  3700. (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
  3701. (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
  3702. return -EINVAL;
  3703. if (is_rt_policy(policy) != (param->sched_priority != 0))
  3704. return -EINVAL;
  3705. /*
  3706. * Allow unprivileged RT tasks to decrease priority:
  3707. */
  3708. if (!capable(CAP_SYS_NICE)) {
  3709. if (is_rt_policy(policy)) {
  3710. unsigned long rlim_rtprio;
  3711. unsigned long flags;
  3712. if (!lock_task_sighand(p, &flags))
  3713. return -ESRCH;
  3714. rlim_rtprio = p->signal->rlim[RLIMIT_RTPRIO].rlim_cur;
  3715. unlock_task_sighand(p, &flags);
  3716. /* can't set/change the rt policy */
  3717. if (policy != p->policy && !rlim_rtprio)
  3718. return -EPERM;
  3719. /* can't increase priority */
  3720. if (param->sched_priority > p->rt_priority &&
  3721. param->sched_priority > rlim_rtprio)
  3722. return -EPERM;
  3723. }
  3724. /* can't change other user's priorities */
  3725. if ((current->euid != p->euid) &&
  3726. (current->euid != p->uid))
  3727. return -EPERM;
  3728. }
  3729. retval = security_task_setscheduler(p, policy, param);
  3730. if (retval)
  3731. return retval;
  3732. /*
  3733. * make sure no PI-waiters arrive (or leave) while we are
  3734. * changing the priority of the task:
  3735. */
  3736. spin_lock_irqsave(&p->pi_lock, flags);
  3737. /*
  3738. * To be able to change p->policy safely, the apropriate
  3739. * runqueue lock must be held.
  3740. */
  3741. rq = __task_rq_lock(p);
  3742. /* recheck policy now with rq lock held */
  3743. if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
  3744. policy = oldpolicy = -1;
  3745. __task_rq_unlock(rq);
  3746. spin_unlock_irqrestore(&p->pi_lock, flags);
  3747. goto recheck;
  3748. }
  3749. array = p->array;
  3750. if (array)
  3751. deactivate_task(p, rq);
  3752. oldprio = p->prio;
  3753. __setscheduler(p, policy, param->sched_priority);
  3754. if (array) {
  3755. __activate_task(p, rq);
  3756. /*
  3757. * Reschedule if we are currently running on this runqueue and
  3758. * our priority decreased, or if we are not currently running on
  3759. * this runqueue and our priority is higher than the current's
  3760. */
  3761. if (task_running(rq, p)) {
  3762. if (p->prio > oldprio)
  3763. resched_task(rq->curr);
  3764. } else if (TASK_PREEMPTS_CURR(p, rq))
  3765. resched_task(rq->curr);
  3766. }
  3767. __task_rq_unlock(rq);
  3768. spin_unlock_irqrestore(&p->pi_lock, flags);
  3769. rt_mutex_adjust_pi(p);
  3770. return 0;
  3771. }
  3772. EXPORT_SYMBOL_GPL(sched_setscheduler);
  3773. static int
  3774. do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
  3775. {
  3776. struct sched_param lparam;
  3777. struct task_struct *p;
  3778. int retval;
  3779. if (!param || pid < 0)
  3780. return -EINVAL;
  3781. if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
  3782. return -EFAULT;
  3783. rcu_read_lock();
  3784. retval = -ESRCH;
  3785. p = find_process_by_pid(pid);
  3786. if (p != NULL)
  3787. retval = sched_setscheduler(p, policy, &lparam);
  3788. rcu_read_unlock();
  3789. return retval;
  3790. }
  3791. /**
  3792. * sys_sched_setscheduler - set/change the scheduler policy and RT priority
  3793. * @pid: the pid in question.
  3794. * @policy: new policy.
  3795. * @param: structure containing the new RT priority.
  3796. */
  3797. asmlinkage long sys_sched_setscheduler(pid_t pid, int policy,
  3798. struct sched_param __user *param)
  3799. {
  3800. /* negative values for policy are not valid */
  3801. if (policy < 0)
  3802. return -EINVAL;
  3803. return do_sched_setscheduler(pid, policy, param);
  3804. }
  3805. /**
  3806. * sys_sched_setparam - set/change the RT priority of a thread
  3807. * @pid: the pid in question.
  3808. * @param: structure containing the new RT priority.
  3809. */
  3810. asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
  3811. {
  3812. return do_sched_setscheduler(pid, -1, param);
  3813. }
  3814. /**
  3815. * sys_sched_getscheduler - get the policy (scheduling class) of a thread
  3816. * @pid: the pid in question.
  3817. */
  3818. asmlinkage long sys_sched_getscheduler(pid_t pid)
  3819. {
  3820. struct task_struct *p;
  3821. int retval = -EINVAL;
  3822. if (pid < 0)
  3823. goto out_nounlock;
  3824. retval = -ESRCH;
  3825. read_lock(&tasklist_lock);
  3826. p = find_process_by_pid(pid);
  3827. if (p) {
  3828. retval = security_task_getscheduler(p);
  3829. if (!retval)
  3830. retval = p->policy;
  3831. }
  3832. read_unlock(&tasklist_lock);
  3833. out_nounlock:
  3834. return retval;
  3835. }
  3836. /**
  3837. * sys_sched_getscheduler - get the RT priority of a thread
  3838. * @pid: the pid in question.
  3839. * @param: structure containing the RT priority.
  3840. */
  3841. asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
  3842. {
  3843. struct sched_param lp;
  3844. struct task_struct *p;
  3845. int retval = -EINVAL;
  3846. if (!param || pid < 0)
  3847. goto out_nounlock;
  3848. read_lock(&tasklist_lock);
  3849. p = find_process_by_pid(pid);
  3850. retval = -ESRCH;
  3851. if (!p)
  3852. goto out_unlock;
  3853. retval = security_task_getscheduler(p);
  3854. if (retval)
  3855. goto out_unlock;
  3856. lp.sched_priority = p->rt_priority;
  3857. read_unlock(&tasklist_lock);
  3858. /*
  3859. * This one might sleep, we cannot do it with a spinlock held ...
  3860. */
  3861. retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
  3862. out_nounlock:
  3863. return retval;
  3864. out_unlock:
  3865. read_unlock(&tasklist_lock);
  3866. return retval;
  3867. }
  3868. long sched_setaffinity(pid_t pid, cpumask_t new_mask)
  3869. {
  3870. cpumask_t cpus_allowed;
  3871. struct task_struct *p;
  3872. int retval;
  3873. lock_cpu_hotplug();
  3874. read_lock(&tasklist_lock);
  3875. p = find_process_by_pid(pid);
  3876. if (!p) {
  3877. read_unlock(&tasklist_lock);
  3878. unlock_cpu_hotplug();
  3879. return -ESRCH;
  3880. }
  3881. /*
  3882. * It is not safe to call set_cpus_allowed with the
  3883. * tasklist_lock held. We will bump the task_struct's
  3884. * usage count and then drop tasklist_lock.
  3885. */
  3886. get_task_struct(p);
  3887. read_unlock(&tasklist_lock);
  3888. retval = -EPERM;
  3889. if ((current->euid != p->euid) && (current->euid != p->uid) &&
  3890. !capable(CAP_SYS_NICE))
  3891. goto out_unlock;
  3892. retval = security_task_setscheduler(p, 0, NULL);
  3893. if (retval)
  3894. goto out_unlock;
  3895. cpus_allowed = cpuset_cpus_allowed(p);
  3896. cpus_and(new_mask, new_mask, cpus_allowed);
  3897. retval = set_cpus_allowed(p, new_mask);
  3898. out_unlock:
  3899. put_task_struct(p);
  3900. unlock_cpu_hotplug();
  3901. return retval;
  3902. }
  3903. static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
  3904. cpumask_t *new_mask)
  3905. {
  3906. if (len < sizeof(cpumask_t)) {
  3907. memset(new_mask, 0, sizeof(cpumask_t));
  3908. } else if (len > sizeof(cpumask_t)) {
  3909. len = sizeof(cpumask_t);
  3910. }
  3911. return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
  3912. }
  3913. /**
  3914. * sys_sched_setaffinity - set the cpu affinity of a process
  3915. * @pid: pid of the process
  3916. * @len: length in bytes of the bitmask pointed to by user_mask_ptr
  3917. * @user_mask_ptr: user-space pointer to the new cpu mask
  3918. */
  3919. asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
  3920. unsigned long __user *user_mask_ptr)
  3921. {
  3922. cpumask_t new_mask;
  3923. int retval;
  3924. retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
  3925. if (retval)
  3926. return retval;
  3927. return sched_setaffinity(pid, new_mask);
  3928. }
  3929. /*
  3930. * Represents all cpu's present in the system
  3931. * In systems capable of hotplug, this map could dynamically grow
  3932. * as new cpu's are detected in the system via any platform specific
  3933. * method, such as ACPI for e.g.
  3934. */
  3935. cpumask_t cpu_present_map __read_mostly;
  3936. EXPORT_SYMBOL(cpu_present_map);
  3937. #ifndef CONFIG_SMP
  3938. cpumask_t cpu_online_map __read_mostly = CPU_MASK_ALL;
  3939. EXPORT_SYMBOL(cpu_online_map);
  3940. cpumask_t cpu_possible_map __read_mostly = CPU_MASK_ALL;
  3941. EXPORT_SYMBOL(cpu_possible_map);
  3942. #endif
  3943. long sched_getaffinity(pid_t pid, cpumask_t *mask)
  3944. {
  3945. struct task_struct *p;
  3946. int retval;
  3947. lock_cpu_hotplug();
  3948. read_lock(&tasklist_lock);
  3949. retval = -ESRCH;
  3950. p = find_process_by_pid(pid);
  3951. if (!p)
  3952. goto out_unlock;
  3953. retval = security_task_getscheduler(p);
  3954. if (retval)
  3955. goto out_unlock;
  3956. cpus_and(*mask, p->cpus_allowed, cpu_online_map);
  3957. out_unlock:
  3958. read_unlock(&tasklist_lock);
  3959. unlock_cpu_hotplug();
  3960. if (retval)
  3961. return retval;
  3962. return 0;
  3963. }
  3964. /**
  3965. * sys_sched_getaffinity - get the cpu affinity of a process
  3966. * @pid: pid of the process
  3967. * @len: length in bytes of the bitmask pointed to by user_mask_ptr
  3968. * @user_mask_ptr: user-space pointer to hold the current cpu mask
  3969. */
  3970. asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
  3971. unsigned long __user *user_mask_ptr)
  3972. {
  3973. int ret;
  3974. cpumask_t mask;
  3975. if (len < sizeof(cpumask_t))
  3976. return -EINVAL;
  3977. ret = sched_getaffinity(pid, &mask);
  3978. if (ret < 0)
  3979. return ret;
  3980. if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
  3981. return -EFAULT;
  3982. return sizeof(cpumask_t);
  3983. }
  3984. /**
  3985. * sys_sched_yield - yield the current processor to other threads.
  3986. *
  3987. * this function yields the current CPU by moving the calling thread
  3988. * to the expired array. If there are no other threads running on this
  3989. * CPU then this function will return.
  3990. */
  3991. asmlinkage long sys_sched_yield(void)
  3992. {
  3993. struct rq *rq = this_rq_lock();
  3994. struct prio_array *array = current->array, *target = rq->expired;
  3995. schedstat_inc(rq, yld_cnt);
  3996. /*
  3997. * We implement yielding by moving the task into the expired
  3998. * queue.
  3999. *
  4000. * (special rule: RT tasks will just roundrobin in the active
  4001. * array.)
  4002. */
  4003. if (rt_task(current))
  4004. target = rq->active;
  4005. if (array->nr_active == 1) {
  4006. schedstat_inc(rq, yld_act_empty);
  4007. if (!rq->expired->nr_active)
  4008. schedstat_inc(rq, yld_both_empty);
  4009. } else if (!rq->expired->nr_active)
  4010. schedstat_inc(rq, yld_exp_empty);
  4011. if (array != target) {
  4012. dequeue_task(current, array);
  4013. enqueue_task(current, target);
  4014. } else
  4015. /*
  4016. * requeue_task is cheaper so perform that if possible.
  4017. */
  4018. requeue_task(current, array);
  4019. /*
  4020. * Since we are going to call schedule() anyway, there's
  4021. * no need to preempt or enable interrupts:
  4022. */
  4023. __release(rq->lock);
  4024. spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
  4025. _raw_spin_unlock(&rq->lock);
  4026. preempt_enable_no_resched();
  4027. schedule();
  4028. return 0;
  4029. }
  4030. static void __cond_resched(void)
  4031. {
  4032. #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
  4033. __might_sleep(__FILE__, __LINE__);
  4034. #endif
  4035. /*
  4036. * The BKS might be reacquired before we have dropped
  4037. * PREEMPT_ACTIVE, which could trigger a second
  4038. * cond_resched() call.
  4039. */
  4040. do {
  4041. add_preempt_count(PREEMPT_ACTIVE);
  4042. schedule();
  4043. sub_preempt_count(PREEMPT_ACTIVE);
  4044. } while (need_resched());
  4045. }
  4046. int __sched cond_resched(void)
  4047. {
  4048. if (need_resched() && !(preempt_count() & PREEMPT_ACTIVE) &&
  4049. system_state == SYSTEM_RUNNING) {
  4050. __cond_resched();
  4051. return 1;
  4052. }
  4053. return 0;
  4054. }
  4055. EXPORT_SYMBOL(cond_resched);
  4056. /*
  4057. * cond_resched_lock() - if a reschedule is pending, drop the given lock,
  4058. * call schedule, and on return reacquire the lock.
  4059. *
  4060. * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
  4061. * operations here to prevent schedule() from being called twice (once via
  4062. * spin_unlock(), once by hand).
  4063. */
  4064. int cond_resched_lock(spinlock_t *lock)
  4065. {
  4066. int ret = 0;
  4067. if (need_lockbreak(lock)) {
  4068. spin_unlock(lock);
  4069. cpu_relax();
  4070. ret = 1;
  4071. spin_lock(lock);
  4072. }
  4073. if (need_resched() && system_state == SYSTEM_RUNNING) {
  4074. spin_release(&lock->dep_map, 1, _THIS_IP_);
  4075. _raw_spin_unlock(lock);
  4076. preempt_enable_no_resched();
  4077. __cond_resched();
  4078. ret = 1;
  4079. spin_lock(lock);
  4080. }
  4081. return ret;
  4082. }
  4083. EXPORT_SYMBOL(cond_resched_lock);
  4084. int __sched cond_resched_softirq(void)
  4085. {
  4086. BUG_ON(!in_softirq());
  4087. if (need_resched() && system_state == SYSTEM_RUNNING) {
  4088. raw_local_irq_disable();
  4089. _local_bh_enable();
  4090. raw_local_irq_enable();
  4091. __cond_resched();
  4092. local_bh_disable();
  4093. return 1;
  4094. }
  4095. return 0;
  4096. }
  4097. EXPORT_SYMBOL(cond_resched_softirq);
  4098. /**
  4099. * yield - yield the current processor to other threads.
  4100. *
  4101. * this is a shortcut for kernel-space yielding - it marks the
  4102. * thread runnable and calls sys_sched_yield().
  4103. */
  4104. void __sched yield(void)
  4105. {
  4106. set_current_state(TASK_RUNNING);
  4107. sys_sched_yield();
  4108. }
  4109. EXPORT_SYMBOL(yield);
  4110. /*
  4111. * This task is about to go to sleep on IO. Increment rq->nr_iowait so
  4112. * that process accounting knows that this is a task in IO wait state.
  4113. *
  4114. * But don't do that if it is a deliberate, throttling IO wait (this task
  4115. * has set its backing_dev_info: the queue against which it should throttle)
  4116. */
  4117. void __sched io_schedule(void)
  4118. {
  4119. struct rq *rq = &__raw_get_cpu_var(runqueues);
  4120. delayacct_blkio_start();
  4121. atomic_inc(&rq->nr_iowait);
  4122. schedule();
  4123. atomic_dec(&rq->nr_iowait);
  4124. delayacct_blkio_end();
  4125. }
  4126. EXPORT_SYMBOL(io_schedule);
  4127. long __sched io_schedule_timeout(long timeout)
  4128. {
  4129. struct rq *rq = &__raw_get_cpu_var(runqueues);
  4130. long ret;
  4131. delayacct_blkio_start();
  4132. atomic_inc(&rq->nr_iowait);
  4133. ret = schedule_timeout(timeout);
  4134. atomic_dec(&rq->nr_iowait);
  4135. delayacct_blkio_end();
  4136. return ret;
  4137. }
  4138. /**
  4139. * sys_sched_get_priority_max - return maximum RT priority.
  4140. * @policy: scheduling class.
  4141. *
  4142. * this syscall returns the maximum rt_priority that can be used
  4143. * by a given scheduling class.
  4144. */
  4145. asmlinkage long sys_sched_get_priority_max(int policy)
  4146. {
  4147. int ret = -EINVAL;
  4148. switch (policy) {
  4149. case SCHED_FIFO:
  4150. case SCHED_RR:
  4151. ret = MAX_USER_RT_PRIO-1;
  4152. break;
  4153. case SCHED_NORMAL:
  4154. case SCHED_BATCH:
  4155. ret = 0;
  4156. break;
  4157. }
  4158. return ret;
  4159. }
  4160. /**
  4161. * sys_sched_get_priority_min - return minimum RT priority.
  4162. * @policy: scheduling class.
  4163. *
  4164. * this syscall returns the minimum rt_priority that can be used
  4165. * by a given scheduling class.
  4166. */
  4167. asmlinkage long sys_sched_get_priority_min(int policy)
  4168. {
  4169. int ret = -EINVAL;
  4170. switch (policy) {
  4171. case SCHED_FIFO:
  4172. case SCHED_RR:
  4173. ret = 1;
  4174. break;
  4175. case SCHED_NORMAL:
  4176. case SCHED_BATCH:
  4177. ret = 0;
  4178. }
  4179. return ret;
  4180. }
  4181. /**
  4182. * sys_sched_rr_get_interval - return the default timeslice of a process.
  4183. * @pid: pid of the process.
  4184. * @interval: userspace pointer to the timeslice value.
  4185. *
  4186. * this syscall writes the default timeslice value of a given process
  4187. * into the user-space timespec buffer. A value of '0' means infinity.
  4188. */
  4189. asmlinkage
  4190. long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
  4191. {
  4192. struct task_struct *p;
  4193. int retval = -EINVAL;
  4194. struct timespec t;
  4195. if (pid < 0)
  4196. goto out_nounlock;
  4197. retval = -ESRCH;
  4198. read_lock(&tasklist_lock);
  4199. p = find_process_by_pid(pid);
  4200. if (!p)
  4201. goto out_unlock;
  4202. retval = security_task_getscheduler(p);
  4203. if (retval)
  4204. goto out_unlock;
  4205. jiffies_to_timespec(p->policy == SCHED_FIFO ?
  4206. 0 : task_timeslice(p), &t);
  4207. read_unlock(&tasklist_lock);
  4208. retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
  4209. out_nounlock:
  4210. return retval;
  4211. out_unlock:
  4212. read_unlock(&tasklist_lock);
  4213. return retval;
  4214. }
  4215. static inline struct task_struct *eldest_child(struct task_struct *p)
  4216. {
  4217. if (list_empty(&p->children))
  4218. return NULL;
  4219. return list_entry(p->children.next,struct task_struct,sibling);
  4220. }
  4221. static inline struct task_struct *older_sibling(struct task_struct *p)
  4222. {
  4223. if (p->sibling.prev==&p->parent->children)
  4224. return NULL;
  4225. return list_entry(p->sibling.prev,struct task_struct,sibling);
  4226. }
  4227. static inline struct task_struct *younger_sibling(struct task_struct *p)
  4228. {
  4229. if (p->sibling.next==&p->parent->children)
  4230. return NULL;
  4231. return list_entry(p->sibling.next,struct task_struct,sibling);
  4232. }
  4233. static const char stat_nam[] = "RSDTtZX";
  4234. static void show_task(struct task_struct *p)
  4235. {
  4236. struct task_struct *relative;
  4237. unsigned long free = 0;
  4238. unsigned state;
  4239. state = p->state ? __ffs(p->state) + 1 : 0;
  4240. printk("%-13.13s %c", p->comm,
  4241. state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
  4242. #if (BITS_PER_LONG == 32)
  4243. if (state == TASK_RUNNING)
  4244. printk(" running ");
  4245. else
  4246. printk(" %08lX ", thread_saved_pc(p));
  4247. #else
  4248. if (state == TASK_RUNNING)
  4249. printk(" running task ");
  4250. else
  4251. printk(" %016lx ", thread_saved_pc(p));
  4252. #endif
  4253. #ifdef CONFIG_DEBUG_STACK_USAGE
  4254. {
  4255. unsigned long *n = end_of_stack(p);
  4256. while (!*n)
  4257. n++;
  4258. free = (unsigned long)n - (unsigned long)end_of_stack(p);
  4259. }
  4260. #endif
  4261. printk("%5lu %5d %6d ", free, p->pid, p->parent->pid);
  4262. if ((relative = eldest_child(p)))
  4263. printk("%5d ", relative->pid);
  4264. else
  4265. printk(" ");
  4266. if ((relative = younger_sibling(p)))
  4267. printk("%7d", relative->pid);
  4268. else
  4269. printk(" ");
  4270. if ((relative = older_sibling(p)))
  4271. printk(" %5d", relative->pid);
  4272. else
  4273. printk(" ");
  4274. if (!p->mm)
  4275. printk(" (L-TLB)\n");
  4276. else
  4277. printk(" (NOTLB)\n");
  4278. if (state != TASK_RUNNING)
  4279. show_stack(p, NULL);
  4280. }
  4281. void show_state_filter(unsigned long state_filter)
  4282. {
  4283. struct task_struct *g, *p;
  4284. #if (BITS_PER_LONG == 32)
  4285. printk("\n"
  4286. " free sibling\n");
  4287. printk(" task PC stack pid father child younger older\n");
  4288. #else
  4289. printk("\n"
  4290. " free sibling\n");
  4291. printk(" task PC stack pid father child younger older\n");
  4292. #endif
  4293. read_lock(&tasklist_lock);
  4294. do_each_thread(g, p) {
  4295. /*
  4296. * reset the NMI-timeout, listing all files on a slow
  4297. * console might take alot of time:
  4298. */
  4299. touch_nmi_watchdog();
  4300. if (p->state & state_filter)
  4301. show_task(p);
  4302. } while_each_thread(g, p);
  4303. read_unlock(&tasklist_lock);
  4304. /*
  4305. * Only show locks if all tasks are dumped:
  4306. */
  4307. if (state_filter == -1)
  4308. debug_show_all_locks();
  4309. }
  4310. /**
  4311. * init_idle - set up an idle thread for a given CPU
  4312. * @idle: task in question
  4313. * @cpu: cpu the idle task belongs to
  4314. *
  4315. * NOTE: this function does not set the idle thread's NEED_RESCHED
  4316. * flag, to make booting more robust.
  4317. */
  4318. void __cpuinit init_idle(struct task_struct *idle, int cpu)
  4319. {
  4320. struct rq *rq = cpu_rq(cpu);
  4321. unsigned long flags;
  4322. idle->timestamp = sched_clock();
  4323. idle->sleep_avg = 0;
  4324. idle->array = NULL;
  4325. idle->prio = idle->normal_prio = MAX_PRIO;
  4326. idle->state = TASK_RUNNING;
  4327. idle->cpus_allowed = cpumask_of_cpu(cpu);
  4328. set_task_cpu(idle, cpu);
  4329. spin_lock_irqsave(&rq->lock, flags);
  4330. rq->curr = rq->idle = idle;
  4331. #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
  4332. idle->oncpu = 1;
  4333. #endif
  4334. spin_unlock_irqrestore(&rq->lock, flags);
  4335. /* Set the preempt count _outside_ the spinlocks! */
  4336. #if defined(CONFIG_PREEMPT) && !defined(CONFIG_PREEMPT_BKL)
  4337. task_thread_info(idle)->preempt_count = (idle->lock_depth >= 0);
  4338. #else
  4339. task_thread_info(idle)->preempt_count = 0;
  4340. #endif
  4341. }
  4342. /*
  4343. * In a system that switches off the HZ timer nohz_cpu_mask
  4344. * indicates which cpus entered this state. This is used
  4345. * in the rcu update to wait only for active cpus. For system
  4346. * which do not switch off the HZ timer nohz_cpu_mask should
  4347. * always be CPU_MASK_NONE.
  4348. */
  4349. cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
  4350. #ifdef CONFIG_SMP
  4351. /*
  4352. * This is how migration works:
  4353. *
  4354. * 1) we queue a struct migration_req structure in the source CPU's
  4355. * runqueue and wake up that CPU's migration thread.
  4356. * 2) we down() the locked semaphore => thread blocks.
  4357. * 3) migration thread wakes up (implicitly it forces the migrated
  4358. * thread off the CPU)
  4359. * 4) it gets the migration request and checks whether the migrated
  4360. * task is still in the wrong runqueue.
  4361. * 5) if it's in the wrong runqueue then the migration thread removes
  4362. * it and puts it into the right queue.
  4363. * 6) migration thread up()s the semaphore.
  4364. * 7) we wake up and the migration is done.
  4365. */
  4366. /*
  4367. * Change a given task's CPU affinity. Migrate the thread to a
  4368. * proper CPU and schedule it away if the CPU it's executing on
  4369. * is removed from the allowed bitmask.
  4370. *
  4371. * NOTE: the caller must have a valid reference to the task, the
  4372. * task must not exit() & deallocate itself prematurely. The
  4373. * call is not atomic; no spinlocks may be held.
  4374. */
  4375. int set_cpus_allowed(struct task_struct *p, cpumask_t new_mask)
  4376. {
  4377. struct migration_req req;
  4378. unsigned long flags;
  4379. struct rq *rq;
  4380. int ret = 0;
  4381. rq = task_rq_lock(p, &flags);
  4382. if (!cpus_intersects(new_mask, cpu_online_map)) {
  4383. ret = -EINVAL;
  4384. goto out;
  4385. }
  4386. p->cpus_allowed = new_mask;
  4387. /* Can the task run on the task's current CPU? If so, we're done */
  4388. if (cpu_isset(task_cpu(p), new_mask))
  4389. goto out;
  4390. if (migrate_task(p, any_online_cpu(new_mask), &req)) {
  4391. /* Need help from migration thread: drop lock and wait. */
  4392. task_rq_unlock(rq, &flags);
  4393. wake_up_process(rq->migration_thread);
  4394. wait_for_completion(&req.done);
  4395. tlb_migrate_finish(p->mm);
  4396. return 0;
  4397. }
  4398. out:
  4399. task_rq_unlock(rq, &flags);
  4400. return ret;
  4401. }
  4402. EXPORT_SYMBOL_GPL(set_cpus_allowed);
  4403. /*
  4404. * Move (not current) task off this cpu, onto dest cpu. We're doing
  4405. * this because either it can't run here any more (set_cpus_allowed()
  4406. * away from this CPU, or CPU going down), or because we're
  4407. * attempting to rebalance this task on exec (sched_exec).
  4408. *
  4409. * So we race with normal scheduler movements, but that's OK, as long
  4410. * as the task is no longer on this CPU.
  4411. *
  4412. * Returns non-zero if task was successfully migrated.
  4413. */
  4414. static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
  4415. {
  4416. struct rq *rq_dest, *rq_src;
  4417. int ret = 0;
  4418. if (unlikely(cpu_is_offline(dest_cpu)))
  4419. return ret;
  4420. rq_src = cpu_rq(src_cpu);
  4421. rq_dest = cpu_rq(dest_cpu);
  4422. double_rq_lock(rq_src, rq_dest);
  4423. /* Already moved. */
  4424. if (task_cpu(p) != src_cpu)
  4425. goto out;
  4426. /* Affinity changed (again). */
  4427. if (!cpu_isset(dest_cpu, p->cpus_allowed))
  4428. goto out;
  4429. set_task_cpu(p, dest_cpu);
  4430. if (p->array) {
  4431. /*
  4432. * Sync timestamp with rq_dest's before activating.
  4433. * The same thing could be achieved by doing this step
  4434. * afterwards, and pretending it was a local activate.
  4435. * This way is cleaner and logically correct.
  4436. */
  4437. p->timestamp = p->timestamp - rq_src->most_recent_timestamp
  4438. + rq_dest->most_recent_timestamp;
  4439. deactivate_task(p, rq_src);
  4440. __activate_task(p, rq_dest);
  4441. if (TASK_PREEMPTS_CURR(p, rq_dest))
  4442. resched_task(rq_dest->curr);
  4443. }
  4444. ret = 1;
  4445. out:
  4446. double_rq_unlock(rq_src, rq_dest);
  4447. return ret;
  4448. }
  4449. /*
  4450. * migration_thread - this is a highprio system thread that performs
  4451. * thread migration by bumping thread off CPU then 'pushing' onto
  4452. * another runqueue.
  4453. */
  4454. static int migration_thread(void *data)
  4455. {
  4456. int cpu = (long)data;
  4457. struct rq *rq;
  4458. rq = cpu_rq(cpu);
  4459. BUG_ON(rq->migration_thread != current);
  4460. set_current_state(TASK_INTERRUPTIBLE);
  4461. while (!kthread_should_stop()) {
  4462. struct migration_req *req;
  4463. struct list_head *head;
  4464. try_to_freeze();
  4465. spin_lock_irq(&rq->lock);
  4466. if (cpu_is_offline(cpu)) {
  4467. spin_unlock_irq(&rq->lock);
  4468. goto wait_to_die;
  4469. }
  4470. if (rq->active_balance) {
  4471. active_load_balance(rq, cpu);
  4472. rq->active_balance = 0;
  4473. }
  4474. head = &rq->migration_queue;
  4475. if (list_empty(head)) {
  4476. spin_unlock_irq(&rq->lock);
  4477. schedule();
  4478. set_current_state(TASK_INTERRUPTIBLE);
  4479. continue;
  4480. }
  4481. req = list_entry(head->next, struct migration_req, list);
  4482. list_del_init(head->next);
  4483. spin_unlock(&rq->lock);
  4484. __migrate_task(req->task, cpu, req->dest_cpu);
  4485. local_irq_enable();
  4486. complete(&req->done);
  4487. }
  4488. __set_current_state(TASK_RUNNING);
  4489. return 0;
  4490. wait_to_die:
  4491. /* Wait for kthread_stop */
  4492. set_current_state(TASK_INTERRUPTIBLE);
  4493. while (!kthread_should_stop()) {
  4494. schedule();
  4495. set_current_state(TASK_INTERRUPTIBLE);
  4496. }
  4497. __set_current_state(TASK_RUNNING);
  4498. return 0;
  4499. }
  4500. #ifdef CONFIG_HOTPLUG_CPU
  4501. /*
  4502. * Figure out where task on dead CPU should go, use force if neccessary.
  4503. * NOTE: interrupts should be disabled by the caller
  4504. */
  4505. static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *p)
  4506. {
  4507. unsigned long flags;
  4508. cpumask_t mask;
  4509. struct rq *rq;
  4510. int dest_cpu;
  4511. restart:
  4512. /* On same node? */
  4513. mask = node_to_cpumask(cpu_to_node(dead_cpu));
  4514. cpus_and(mask, mask, p->cpus_allowed);
  4515. dest_cpu = any_online_cpu(mask);
  4516. /* On any allowed CPU? */
  4517. if (dest_cpu == NR_CPUS)
  4518. dest_cpu = any_online_cpu(p->cpus_allowed);
  4519. /* No more Mr. Nice Guy. */
  4520. if (dest_cpu == NR_CPUS) {
  4521. rq = task_rq_lock(p, &flags);
  4522. cpus_setall(p->cpus_allowed);
  4523. dest_cpu = any_online_cpu(p->cpus_allowed);
  4524. task_rq_unlock(rq, &flags);
  4525. /*
  4526. * Don't tell them about moving exiting tasks or
  4527. * kernel threads (both mm NULL), since they never
  4528. * leave kernel.
  4529. */
  4530. if (p->mm && printk_ratelimit())
  4531. printk(KERN_INFO "process %d (%s) no "
  4532. "longer affine to cpu%d\n",
  4533. p->pid, p->comm, dead_cpu);
  4534. }
  4535. if (!__migrate_task(p, dead_cpu, dest_cpu))
  4536. goto restart;
  4537. }
  4538. /*
  4539. * While a dead CPU has no uninterruptible tasks queued at this point,
  4540. * it might still have a nonzero ->nr_uninterruptible counter, because
  4541. * for performance reasons the counter is not stricly tracking tasks to
  4542. * their home CPUs. So we just add the counter to another CPU's counter,
  4543. * to keep the global sum constant after CPU-down:
  4544. */
  4545. static void migrate_nr_uninterruptible(struct rq *rq_src)
  4546. {
  4547. struct rq *rq_dest = cpu_rq(any_online_cpu(CPU_MASK_ALL));
  4548. unsigned long flags;
  4549. local_irq_save(flags);
  4550. double_rq_lock(rq_src, rq_dest);
  4551. rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
  4552. rq_src->nr_uninterruptible = 0;
  4553. double_rq_unlock(rq_src, rq_dest);
  4554. local_irq_restore(flags);
  4555. }
  4556. /* Run through task list and migrate tasks from the dead cpu. */
  4557. static void migrate_live_tasks(int src_cpu)
  4558. {
  4559. struct task_struct *p, *t;
  4560. write_lock_irq(&tasklist_lock);
  4561. do_each_thread(t, p) {
  4562. if (p == current)
  4563. continue;
  4564. if (task_cpu(p) == src_cpu)
  4565. move_task_off_dead_cpu(src_cpu, p);
  4566. } while_each_thread(t, p);
  4567. write_unlock_irq(&tasklist_lock);
  4568. }
  4569. /* Schedules idle task to be the next runnable task on current CPU.
  4570. * It does so by boosting its priority to highest possible and adding it to
  4571. * the _front_ of the runqueue. Used by CPU offline code.
  4572. */
  4573. void sched_idle_next(void)
  4574. {
  4575. int this_cpu = smp_processor_id();
  4576. struct rq *rq = cpu_rq(this_cpu);
  4577. struct task_struct *p = rq->idle;
  4578. unsigned long flags;
  4579. /* cpu has to be offline */
  4580. BUG_ON(cpu_online(this_cpu));
  4581. /*
  4582. * Strictly not necessary since rest of the CPUs are stopped by now
  4583. * and interrupts disabled on the current cpu.
  4584. */
  4585. spin_lock_irqsave(&rq->lock, flags);
  4586. __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
  4587. /* Add idle task to the _front_ of its priority queue: */
  4588. __activate_idle_task(p, rq);
  4589. spin_unlock_irqrestore(&rq->lock, flags);
  4590. }
  4591. /*
  4592. * Ensures that the idle task is using init_mm right before its cpu goes
  4593. * offline.
  4594. */
  4595. void idle_task_exit(void)
  4596. {
  4597. struct mm_struct *mm = current->active_mm;
  4598. BUG_ON(cpu_online(smp_processor_id()));
  4599. if (mm != &init_mm)
  4600. switch_mm(mm, &init_mm, current);
  4601. mmdrop(mm);
  4602. }
  4603. /* called under rq->lock with disabled interrupts */
  4604. static void migrate_dead(unsigned int dead_cpu, struct task_struct *p)
  4605. {
  4606. struct rq *rq = cpu_rq(dead_cpu);
  4607. /* Must be exiting, otherwise would be on tasklist. */
  4608. BUG_ON(p->exit_state != EXIT_ZOMBIE && p->exit_state != EXIT_DEAD);
  4609. /* Cannot have done final schedule yet: would have vanished. */
  4610. BUG_ON(p->state == TASK_DEAD);
  4611. get_task_struct(p);
  4612. /*
  4613. * Drop lock around migration; if someone else moves it,
  4614. * that's OK. No task can be added to this CPU, so iteration is
  4615. * fine.
  4616. * NOTE: interrupts should be left disabled --dev@
  4617. */
  4618. spin_unlock(&rq->lock);
  4619. move_task_off_dead_cpu(dead_cpu, p);
  4620. spin_lock(&rq->lock);
  4621. put_task_struct(p);
  4622. }
  4623. /* release_task() removes task from tasklist, so we won't find dead tasks. */
  4624. static void migrate_dead_tasks(unsigned int dead_cpu)
  4625. {
  4626. struct rq *rq = cpu_rq(dead_cpu);
  4627. unsigned int arr, i;
  4628. for (arr = 0; arr < 2; arr++) {
  4629. for (i = 0; i < MAX_PRIO; i++) {
  4630. struct list_head *list = &rq->arrays[arr].queue[i];
  4631. while (!list_empty(list))
  4632. migrate_dead(dead_cpu, list_entry(list->next,
  4633. struct task_struct, run_list));
  4634. }
  4635. }
  4636. }
  4637. #endif /* CONFIG_HOTPLUG_CPU */
  4638. /*
  4639. * migration_call - callback that gets triggered when a CPU is added.
  4640. * Here we can start up the necessary migration thread for the new CPU.
  4641. */
  4642. static int __cpuinit
  4643. migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
  4644. {
  4645. struct task_struct *p;
  4646. int cpu = (long)hcpu;
  4647. unsigned long flags;
  4648. struct rq *rq;
  4649. switch (action) {
  4650. case CPU_UP_PREPARE:
  4651. p = kthread_create(migration_thread, hcpu, "migration/%d",cpu);
  4652. if (IS_ERR(p))
  4653. return NOTIFY_BAD;
  4654. p->flags |= PF_NOFREEZE;
  4655. kthread_bind(p, cpu);
  4656. /* Must be high prio: stop_machine expects to yield to it. */
  4657. rq = task_rq_lock(p, &flags);
  4658. __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
  4659. task_rq_unlock(rq, &flags);
  4660. cpu_rq(cpu)->migration_thread = p;
  4661. break;
  4662. case CPU_ONLINE:
  4663. /* Strictly unneccessary, as first user will wake it. */
  4664. wake_up_process(cpu_rq(cpu)->migration_thread);
  4665. break;
  4666. #ifdef CONFIG_HOTPLUG_CPU
  4667. case CPU_UP_CANCELED:
  4668. if (!cpu_rq(cpu)->migration_thread)
  4669. break;
  4670. /* Unbind it from offline cpu so it can run. Fall thru. */
  4671. kthread_bind(cpu_rq(cpu)->migration_thread,
  4672. any_online_cpu(cpu_online_map));
  4673. kthread_stop(cpu_rq(cpu)->migration_thread);
  4674. cpu_rq(cpu)->migration_thread = NULL;
  4675. break;
  4676. case CPU_DEAD:
  4677. migrate_live_tasks(cpu);
  4678. rq = cpu_rq(cpu);
  4679. kthread_stop(rq->migration_thread);
  4680. rq->migration_thread = NULL;
  4681. /* Idle task back to normal (off runqueue, low prio) */
  4682. rq = task_rq_lock(rq->idle, &flags);
  4683. deactivate_task(rq->idle, rq);
  4684. rq->idle->static_prio = MAX_PRIO;
  4685. __setscheduler(rq->idle, SCHED_NORMAL, 0);
  4686. migrate_dead_tasks(cpu);
  4687. task_rq_unlock(rq, &flags);
  4688. migrate_nr_uninterruptible(rq);
  4689. BUG_ON(rq->nr_running != 0);
  4690. /* No need to migrate the tasks: it was best-effort if
  4691. * they didn't do lock_cpu_hotplug(). Just wake up
  4692. * the requestors. */
  4693. spin_lock_irq(&rq->lock);
  4694. while (!list_empty(&rq->migration_queue)) {
  4695. struct migration_req *req;
  4696. req = list_entry(rq->migration_queue.next,
  4697. struct migration_req, list);
  4698. list_del_init(&req->list);
  4699. complete(&req->done);
  4700. }
  4701. spin_unlock_irq(&rq->lock);
  4702. break;
  4703. #endif
  4704. }
  4705. return NOTIFY_OK;
  4706. }
  4707. /* Register at highest priority so that task migration (migrate_all_tasks)
  4708. * happens before everything else.
  4709. */
  4710. static struct notifier_block __cpuinitdata migration_notifier = {
  4711. .notifier_call = migration_call,
  4712. .priority = 10
  4713. };
  4714. int __init migration_init(void)
  4715. {
  4716. void *cpu = (void *)(long)smp_processor_id();
  4717. int err;
  4718. /* Start one for the boot CPU: */
  4719. err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
  4720. BUG_ON(err == NOTIFY_BAD);
  4721. migration_call(&migration_notifier, CPU_ONLINE, cpu);
  4722. register_cpu_notifier(&migration_notifier);
  4723. return 0;
  4724. }
  4725. #endif
  4726. #ifdef CONFIG_SMP
  4727. #undef SCHED_DOMAIN_DEBUG
  4728. #ifdef SCHED_DOMAIN_DEBUG
  4729. static void sched_domain_debug(struct sched_domain *sd, int cpu)
  4730. {
  4731. int level = 0;
  4732. if (!sd) {
  4733. printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
  4734. return;
  4735. }
  4736. printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
  4737. do {
  4738. int i;
  4739. char str[NR_CPUS];
  4740. struct sched_group *group = sd->groups;
  4741. cpumask_t groupmask;
  4742. cpumask_scnprintf(str, NR_CPUS, sd->span);
  4743. cpus_clear(groupmask);
  4744. printk(KERN_DEBUG);
  4745. for (i = 0; i < level + 1; i++)
  4746. printk(" ");
  4747. printk("domain %d: ", level);
  4748. if (!(sd->flags & SD_LOAD_BALANCE)) {
  4749. printk("does not load-balance\n");
  4750. if (sd->parent)
  4751. printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
  4752. " has parent");
  4753. break;
  4754. }
  4755. printk("span %s\n", str);
  4756. if (!cpu_isset(cpu, sd->span))
  4757. printk(KERN_ERR "ERROR: domain->span does not contain "
  4758. "CPU%d\n", cpu);
  4759. if (!cpu_isset(cpu, group->cpumask))
  4760. printk(KERN_ERR "ERROR: domain->groups does not contain"
  4761. " CPU%d\n", cpu);
  4762. printk(KERN_DEBUG);
  4763. for (i = 0; i < level + 2; i++)
  4764. printk(" ");
  4765. printk("groups:");
  4766. do {
  4767. if (!group) {
  4768. printk("\n");
  4769. printk(KERN_ERR "ERROR: group is NULL\n");
  4770. break;
  4771. }
  4772. if (!group->cpu_power) {
  4773. printk("\n");
  4774. printk(KERN_ERR "ERROR: domain->cpu_power not "
  4775. "set\n");
  4776. }
  4777. if (!cpus_weight(group->cpumask)) {
  4778. printk("\n");
  4779. printk(KERN_ERR "ERROR: empty group\n");
  4780. }
  4781. if (cpus_intersects(groupmask, group->cpumask)) {
  4782. printk("\n");
  4783. printk(KERN_ERR "ERROR: repeated CPUs\n");
  4784. }
  4785. cpus_or(groupmask, groupmask, group->cpumask);
  4786. cpumask_scnprintf(str, NR_CPUS, group->cpumask);
  4787. printk(" %s", str);
  4788. group = group->next;
  4789. } while (group != sd->groups);
  4790. printk("\n");
  4791. if (!cpus_equal(sd->span, groupmask))
  4792. printk(KERN_ERR "ERROR: groups don't span "
  4793. "domain->span\n");
  4794. level++;
  4795. sd = sd->parent;
  4796. if (!sd)
  4797. continue;
  4798. if (!cpus_subset(groupmask, sd->span))
  4799. printk(KERN_ERR "ERROR: parent span is not a superset "
  4800. "of domain->span\n");
  4801. } while (sd);
  4802. }
  4803. #else
  4804. # define sched_domain_debug(sd, cpu) do { } while (0)
  4805. #endif
  4806. static int sd_degenerate(struct sched_domain *sd)
  4807. {
  4808. if (cpus_weight(sd->span) == 1)
  4809. return 1;
  4810. /* Following flags need at least 2 groups */
  4811. if (sd->flags & (SD_LOAD_BALANCE |
  4812. SD_BALANCE_NEWIDLE |
  4813. SD_BALANCE_FORK |
  4814. SD_BALANCE_EXEC |
  4815. SD_SHARE_CPUPOWER |
  4816. SD_SHARE_PKG_RESOURCES)) {
  4817. if (sd->groups != sd->groups->next)
  4818. return 0;
  4819. }
  4820. /* Following flags don't use groups */
  4821. if (sd->flags & (SD_WAKE_IDLE |
  4822. SD_WAKE_AFFINE |
  4823. SD_WAKE_BALANCE))
  4824. return 0;
  4825. return 1;
  4826. }
  4827. static int
  4828. sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
  4829. {
  4830. unsigned long cflags = sd->flags, pflags = parent->flags;
  4831. if (sd_degenerate(parent))
  4832. return 1;
  4833. if (!cpus_equal(sd->span, parent->span))
  4834. return 0;
  4835. /* Does parent contain flags not in child? */
  4836. /* WAKE_BALANCE is a subset of WAKE_AFFINE */
  4837. if (cflags & SD_WAKE_AFFINE)
  4838. pflags &= ~SD_WAKE_BALANCE;
  4839. /* Flags needing groups don't count if only 1 group in parent */
  4840. if (parent->groups == parent->groups->next) {
  4841. pflags &= ~(SD_LOAD_BALANCE |
  4842. SD_BALANCE_NEWIDLE |
  4843. SD_BALANCE_FORK |
  4844. SD_BALANCE_EXEC |
  4845. SD_SHARE_CPUPOWER |
  4846. SD_SHARE_PKG_RESOURCES);
  4847. }
  4848. if (~cflags & pflags)
  4849. return 0;
  4850. return 1;
  4851. }
  4852. /*
  4853. * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
  4854. * hold the hotplug lock.
  4855. */
  4856. static void cpu_attach_domain(struct sched_domain *sd, int cpu)
  4857. {
  4858. struct rq *rq = cpu_rq(cpu);
  4859. struct sched_domain *tmp;
  4860. /* Remove the sched domains which do not contribute to scheduling. */
  4861. for (tmp = sd; tmp; tmp = tmp->parent) {
  4862. struct sched_domain *parent = tmp->parent;
  4863. if (!parent)
  4864. break;
  4865. if (sd_parent_degenerate(tmp, parent)) {
  4866. tmp->parent = parent->parent;
  4867. if (parent->parent)
  4868. parent->parent->child = tmp;
  4869. }
  4870. }
  4871. if (sd && sd_degenerate(sd)) {
  4872. sd = sd->parent;
  4873. if (sd)
  4874. sd->child = NULL;
  4875. }
  4876. sched_domain_debug(sd, cpu);
  4877. rcu_assign_pointer(rq->sd, sd);
  4878. }
  4879. /* cpus with isolated domains */
  4880. static cpumask_t cpu_isolated_map = CPU_MASK_NONE;
  4881. /* Setup the mask of cpus configured for isolated domains */
  4882. static int __init isolated_cpu_setup(char *str)
  4883. {
  4884. int ints[NR_CPUS], i;
  4885. str = get_options(str, ARRAY_SIZE(ints), ints);
  4886. cpus_clear(cpu_isolated_map);
  4887. for (i = 1; i <= ints[0]; i++)
  4888. if (ints[i] < NR_CPUS)
  4889. cpu_set(ints[i], cpu_isolated_map);
  4890. return 1;
  4891. }
  4892. __setup ("isolcpus=", isolated_cpu_setup);
  4893. /*
  4894. * init_sched_build_groups takes the cpumask we wish to span, and a pointer
  4895. * to a function which identifies what group(along with sched group) a CPU
  4896. * belongs to. The return value of group_fn must be a >= 0 and < NR_CPUS
  4897. * (due to the fact that we keep track of groups covered with a cpumask_t).
  4898. *
  4899. * init_sched_build_groups will build a circular linked list of the groups
  4900. * covered by the given span, and will set each group's ->cpumask correctly,
  4901. * and ->cpu_power to 0.
  4902. */
  4903. static void
  4904. init_sched_build_groups(cpumask_t span, const cpumask_t *cpu_map,
  4905. int (*group_fn)(int cpu, const cpumask_t *cpu_map,
  4906. struct sched_group **sg))
  4907. {
  4908. struct sched_group *first = NULL, *last = NULL;
  4909. cpumask_t covered = CPU_MASK_NONE;
  4910. int i;
  4911. for_each_cpu_mask(i, span) {
  4912. struct sched_group *sg;
  4913. int group = group_fn(i, cpu_map, &sg);
  4914. int j;
  4915. if (cpu_isset(i, covered))
  4916. continue;
  4917. sg->cpumask = CPU_MASK_NONE;
  4918. sg->cpu_power = 0;
  4919. for_each_cpu_mask(j, span) {
  4920. if (group_fn(j, cpu_map, NULL) != group)
  4921. continue;
  4922. cpu_set(j, covered);
  4923. cpu_set(j, sg->cpumask);
  4924. }
  4925. if (!first)
  4926. first = sg;
  4927. if (last)
  4928. last->next = sg;
  4929. last = sg;
  4930. }
  4931. last->next = first;
  4932. }
  4933. #define SD_NODES_PER_DOMAIN 16
  4934. /*
  4935. * Self-tuning task migration cost measurement between source and target CPUs.
  4936. *
  4937. * This is done by measuring the cost of manipulating buffers of varying
  4938. * sizes. For a given buffer-size here are the steps that are taken:
  4939. *
  4940. * 1) the source CPU reads+dirties a shared buffer
  4941. * 2) the target CPU reads+dirties the same shared buffer
  4942. *
  4943. * We measure how long they take, in the following 4 scenarios:
  4944. *
  4945. * - source: CPU1, target: CPU2 | cost1
  4946. * - source: CPU2, target: CPU1 | cost2
  4947. * - source: CPU1, target: CPU1 | cost3
  4948. * - source: CPU2, target: CPU2 | cost4
  4949. *
  4950. * We then calculate the cost3+cost4-cost1-cost2 difference - this is
  4951. * the cost of migration.
  4952. *
  4953. * We then start off from a small buffer-size and iterate up to larger
  4954. * buffer sizes, in 5% steps - measuring each buffer-size separately, and
  4955. * doing a maximum search for the cost. (The maximum cost for a migration
  4956. * normally occurs when the working set size is around the effective cache
  4957. * size.)
  4958. */
  4959. #define SEARCH_SCOPE 2
  4960. #define MIN_CACHE_SIZE (64*1024U)
  4961. #define DEFAULT_CACHE_SIZE (5*1024*1024U)
  4962. #define ITERATIONS 1
  4963. #define SIZE_THRESH 130
  4964. #define COST_THRESH 130
  4965. /*
  4966. * The migration cost is a function of 'domain distance'. Domain
  4967. * distance is the number of steps a CPU has to iterate down its
  4968. * domain tree to share a domain with the other CPU. The farther
  4969. * two CPUs are from each other, the larger the distance gets.
  4970. *
  4971. * Note that we use the distance only to cache measurement results,
  4972. * the distance value is not used numerically otherwise. When two
  4973. * CPUs have the same distance it is assumed that the migration
  4974. * cost is the same. (this is a simplification but quite practical)
  4975. */
  4976. #define MAX_DOMAIN_DISTANCE 32
  4977. static unsigned long long migration_cost[MAX_DOMAIN_DISTANCE] =
  4978. { [ 0 ... MAX_DOMAIN_DISTANCE-1 ] =
  4979. /*
  4980. * Architectures may override the migration cost and thus avoid
  4981. * boot-time calibration. Unit is nanoseconds. Mostly useful for
  4982. * virtualized hardware:
  4983. */
  4984. #ifdef CONFIG_DEFAULT_MIGRATION_COST
  4985. CONFIG_DEFAULT_MIGRATION_COST
  4986. #else
  4987. -1LL
  4988. #endif
  4989. };
  4990. /*
  4991. * Allow override of migration cost - in units of microseconds.
  4992. * E.g. migration_cost=1000,2000,3000 will set up a level-1 cost
  4993. * of 1 msec, level-2 cost of 2 msecs and level3 cost of 3 msecs:
  4994. */
  4995. static int __init migration_cost_setup(char *str)
  4996. {
  4997. int ints[MAX_DOMAIN_DISTANCE+1], i;
  4998. str = get_options(str, ARRAY_SIZE(ints), ints);
  4999. printk("#ints: %d\n", ints[0]);
  5000. for (i = 1; i <= ints[0]; i++) {
  5001. migration_cost[i-1] = (unsigned long long)ints[i]*1000;
  5002. printk("migration_cost[%d]: %Ld\n", i-1, migration_cost[i-1]);
  5003. }
  5004. return 1;
  5005. }
  5006. __setup ("migration_cost=", migration_cost_setup);
  5007. /*
  5008. * Global multiplier (divisor) for migration-cutoff values,
  5009. * in percentiles. E.g. use a value of 150 to get 1.5 times
  5010. * longer cache-hot cutoff times.
  5011. *
  5012. * (We scale it from 100 to 128 to long long handling easier.)
  5013. */
  5014. #define MIGRATION_FACTOR_SCALE 128
  5015. static unsigned int migration_factor = MIGRATION_FACTOR_SCALE;
  5016. static int __init setup_migration_factor(char *str)
  5017. {
  5018. get_option(&str, &migration_factor);
  5019. migration_factor = migration_factor * MIGRATION_FACTOR_SCALE / 100;
  5020. return 1;
  5021. }
  5022. __setup("migration_factor=", setup_migration_factor);
  5023. /*
  5024. * Estimated distance of two CPUs, measured via the number of domains
  5025. * we have to pass for the two CPUs to be in the same span:
  5026. */
  5027. static unsigned long domain_distance(int cpu1, int cpu2)
  5028. {
  5029. unsigned long distance = 0;
  5030. struct sched_domain *sd;
  5031. for_each_domain(cpu1, sd) {
  5032. WARN_ON(!cpu_isset(cpu1, sd->span));
  5033. if (cpu_isset(cpu2, sd->span))
  5034. return distance;
  5035. distance++;
  5036. }
  5037. if (distance >= MAX_DOMAIN_DISTANCE) {
  5038. WARN_ON(1);
  5039. distance = MAX_DOMAIN_DISTANCE-1;
  5040. }
  5041. return distance;
  5042. }
  5043. static unsigned int migration_debug;
  5044. static int __init setup_migration_debug(char *str)
  5045. {
  5046. get_option(&str, &migration_debug);
  5047. return 1;
  5048. }
  5049. __setup("migration_debug=", setup_migration_debug);
  5050. /*
  5051. * Maximum cache-size that the scheduler should try to measure.
  5052. * Architectures with larger caches should tune this up during
  5053. * bootup. Gets used in the domain-setup code (i.e. during SMP
  5054. * bootup).
  5055. */
  5056. unsigned int max_cache_size;
  5057. static int __init setup_max_cache_size(char *str)
  5058. {
  5059. get_option(&str, &max_cache_size);
  5060. return 1;
  5061. }
  5062. __setup("max_cache_size=", setup_max_cache_size);
  5063. /*
  5064. * Dirty a big buffer in a hard-to-predict (for the L2 cache) way. This
  5065. * is the operation that is timed, so we try to generate unpredictable
  5066. * cachemisses that still end up filling the L2 cache:
  5067. */
  5068. static void touch_cache(void *__cache, unsigned long __size)
  5069. {
  5070. unsigned long size = __size / sizeof(long);
  5071. unsigned long chunk1 = size / 3;
  5072. unsigned long chunk2 = 2 * size / 3;
  5073. unsigned long *cache = __cache;
  5074. int i;
  5075. for (i = 0; i < size/6; i += 8) {
  5076. switch (i % 6) {
  5077. case 0: cache[i]++;
  5078. case 1: cache[size-1-i]++;
  5079. case 2: cache[chunk1-i]++;
  5080. case 3: cache[chunk1+i]++;
  5081. case 4: cache[chunk2-i]++;
  5082. case 5: cache[chunk2+i]++;
  5083. }
  5084. }
  5085. }
  5086. /*
  5087. * Measure the cache-cost of one task migration. Returns in units of nsec.
  5088. */
  5089. static unsigned long long
  5090. measure_one(void *cache, unsigned long size, int source, int target)
  5091. {
  5092. cpumask_t mask, saved_mask;
  5093. unsigned long long t0, t1, t2, t3, cost;
  5094. saved_mask = current->cpus_allowed;
  5095. /*
  5096. * Flush source caches to RAM and invalidate them:
  5097. */
  5098. sched_cacheflush();
  5099. /*
  5100. * Migrate to the source CPU:
  5101. */
  5102. mask = cpumask_of_cpu(source);
  5103. set_cpus_allowed(current, mask);
  5104. WARN_ON(smp_processor_id() != source);
  5105. /*
  5106. * Dirty the working set:
  5107. */
  5108. t0 = sched_clock();
  5109. touch_cache(cache, size);
  5110. t1 = sched_clock();
  5111. /*
  5112. * Migrate to the target CPU, dirty the L2 cache and access
  5113. * the shared buffer. (which represents the working set
  5114. * of a migrated task.)
  5115. */
  5116. mask = cpumask_of_cpu(target);
  5117. set_cpus_allowed(current, mask);
  5118. WARN_ON(smp_processor_id() != target);
  5119. t2 = sched_clock();
  5120. touch_cache(cache, size);
  5121. t3 = sched_clock();
  5122. cost = t1-t0 + t3-t2;
  5123. if (migration_debug >= 2)
  5124. printk("[%d->%d]: %8Ld %8Ld %8Ld => %10Ld.\n",
  5125. source, target, t1-t0, t1-t0, t3-t2, cost);
  5126. /*
  5127. * Flush target caches to RAM and invalidate them:
  5128. */
  5129. sched_cacheflush();
  5130. set_cpus_allowed(current, saved_mask);
  5131. return cost;
  5132. }
  5133. /*
  5134. * Measure a series of task migrations and return the average
  5135. * result. Since this code runs early during bootup the system
  5136. * is 'undisturbed' and the average latency makes sense.
  5137. *
  5138. * The algorithm in essence auto-detects the relevant cache-size,
  5139. * so it will properly detect different cachesizes for different
  5140. * cache-hierarchies, depending on how the CPUs are connected.
  5141. *
  5142. * Architectures can prime the upper limit of the search range via
  5143. * max_cache_size, otherwise the search range defaults to 20MB...64K.
  5144. */
  5145. static unsigned long long
  5146. measure_cost(int cpu1, int cpu2, void *cache, unsigned int size)
  5147. {
  5148. unsigned long long cost1, cost2;
  5149. int i;
  5150. /*
  5151. * Measure the migration cost of 'size' bytes, over an
  5152. * average of 10 runs:
  5153. *
  5154. * (We perturb the cache size by a small (0..4k)
  5155. * value to compensate size/alignment related artifacts.
  5156. * We also subtract the cost of the operation done on
  5157. * the same CPU.)
  5158. */
  5159. cost1 = 0;
  5160. /*
  5161. * dry run, to make sure we start off cache-cold on cpu1,
  5162. * and to get any vmalloc pagefaults in advance:
  5163. */
  5164. measure_one(cache, size, cpu1, cpu2);
  5165. for (i = 0; i < ITERATIONS; i++)
  5166. cost1 += measure_one(cache, size - i * 1024, cpu1, cpu2);
  5167. measure_one(cache, size, cpu2, cpu1);
  5168. for (i = 0; i < ITERATIONS; i++)
  5169. cost1 += measure_one(cache, size - i * 1024, cpu2, cpu1);
  5170. /*
  5171. * (We measure the non-migrating [cached] cost on both
  5172. * cpu1 and cpu2, to handle CPUs with different speeds)
  5173. */
  5174. cost2 = 0;
  5175. measure_one(cache, size, cpu1, cpu1);
  5176. for (i = 0; i < ITERATIONS; i++)
  5177. cost2 += measure_one(cache, size - i * 1024, cpu1, cpu1);
  5178. measure_one(cache, size, cpu2, cpu2);
  5179. for (i = 0; i < ITERATIONS; i++)
  5180. cost2 += measure_one(cache, size - i * 1024, cpu2, cpu2);
  5181. /*
  5182. * Get the per-iteration migration cost:
  5183. */
  5184. do_div(cost1, 2 * ITERATIONS);
  5185. do_div(cost2, 2 * ITERATIONS);
  5186. return cost1 - cost2;
  5187. }
  5188. static unsigned long long measure_migration_cost(int cpu1, int cpu2)
  5189. {
  5190. unsigned long long max_cost = 0, fluct = 0, avg_fluct = 0;
  5191. unsigned int max_size, size, size_found = 0;
  5192. long long cost = 0, prev_cost;
  5193. void *cache;
  5194. /*
  5195. * Search from max_cache_size*5 down to 64K - the real relevant
  5196. * cachesize has to lie somewhere inbetween.
  5197. */
  5198. if (max_cache_size) {
  5199. max_size = max(max_cache_size * SEARCH_SCOPE, MIN_CACHE_SIZE);
  5200. size = max(max_cache_size / SEARCH_SCOPE, MIN_CACHE_SIZE);
  5201. } else {
  5202. /*
  5203. * Since we have no estimation about the relevant
  5204. * search range
  5205. */
  5206. max_size = DEFAULT_CACHE_SIZE * SEARCH_SCOPE;
  5207. size = MIN_CACHE_SIZE;
  5208. }
  5209. if (!cpu_online(cpu1) || !cpu_online(cpu2)) {
  5210. printk("cpu %d and %d not both online!\n", cpu1, cpu2);
  5211. return 0;
  5212. }
  5213. /*
  5214. * Allocate the working set:
  5215. */
  5216. cache = vmalloc(max_size);
  5217. if (!cache) {
  5218. printk("could not vmalloc %d bytes for cache!\n", 2 * max_size);
  5219. return 1000000; /* return 1 msec on very small boxen */
  5220. }
  5221. while (size <= max_size) {
  5222. prev_cost = cost;
  5223. cost = measure_cost(cpu1, cpu2, cache, size);
  5224. /*
  5225. * Update the max:
  5226. */
  5227. if (cost > 0) {
  5228. if (max_cost < cost) {
  5229. max_cost = cost;
  5230. size_found = size;
  5231. }
  5232. }
  5233. /*
  5234. * Calculate average fluctuation, we use this to prevent
  5235. * noise from triggering an early break out of the loop:
  5236. */
  5237. fluct = abs(cost - prev_cost);
  5238. avg_fluct = (avg_fluct + fluct)/2;
  5239. if (migration_debug)
  5240. printk("-> [%d][%d][%7d] %3ld.%ld [%3ld.%ld] (%ld): "
  5241. "(%8Ld %8Ld)\n",
  5242. cpu1, cpu2, size,
  5243. (long)cost / 1000000,
  5244. ((long)cost / 100000) % 10,
  5245. (long)max_cost / 1000000,
  5246. ((long)max_cost / 100000) % 10,
  5247. domain_distance(cpu1, cpu2),
  5248. cost, avg_fluct);
  5249. /*
  5250. * If we iterated at least 20% past the previous maximum,
  5251. * and the cost has dropped by more than 20% already,
  5252. * (taking fluctuations into account) then we assume to
  5253. * have found the maximum and break out of the loop early:
  5254. */
  5255. if (size_found && (size*100 > size_found*SIZE_THRESH))
  5256. if (cost+avg_fluct <= 0 ||
  5257. max_cost*100 > (cost+avg_fluct)*COST_THRESH) {
  5258. if (migration_debug)
  5259. printk("-> found max.\n");
  5260. break;
  5261. }
  5262. /*
  5263. * Increase the cachesize in 10% steps:
  5264. */
  5265. size = size * 10 / 9;
  5266. }
  5267. if (migration_debug)
  5268. printk("[%d][%d] working set size found: %d, cost: %Ld\n",
  5269. cpu1, cpu2, size_found, max_cost);
  5270. vfree(cache);
  5271. /*
  5272. * A task is considered 'cache cold' if at least 2 times
  5273. * the worst-case cost of migration has passed.
  5274. *
  5275. * (this limit is only listened to if the load-balancing
  5276. * situation is 'nice' - if there is a large imbalance we
  5277. * ignore it for the sake of CPU utilization and
  5278. * processing fairness.)
  5279. */
  5280. return 2 * max_cost * migration_factor / MIGRATION_FACTOR_SCALE;
  5281. }
  5282. static void calibrate_migration_costs(const cpumask_t *cpu_map)
  5283. {
  5284. int cpu1 = -1, cpu2 = -1, cpu, orig_cpu = raw_smp_processor_id();
  5285. unsigned long j0, j1, distance, max_distance = 0;
  5286. struct sched_domain *sd;
  5287. j0 = jiffies;
  5288. /*
  5289. * First pass - calculate the cacheflush times:
  5290. */
  5291. for_each_cpu_mask(cpu1, *cpu_map) {
  5292. for_each_cpu_mask(cpu2, *cpu_map) {
  5293. if (cpu1 == cpu2)
  5294. continue;
  5295. distance = domain_distance(cpu1, cpu2);
  5296. max_distance = max(max_distance, distance);
  5297. /*
  5298. * No result cached yet?
  5299. */
  5300. if (migration_cost[distance] == -1LL)
  5301. migration_cost[distance] =
  5302. measure_migration_cost(cpu1, cpu2);
  5303. }
  5304. }
  5305. /*
  5306. * Second pass - update the sched domain hierarchy with
  5307. * the new cache-hot-time estimations:
  5308. */
  5309. for_each_cpu_mask(cpu, *cpu_map) {
  5310. distance = 0;
  5311. for_each_domain(cpu, sd) {
  5312. sd->cache_hot_time = migration_cost[distance];
  5313. distance++;
  5314. }
  5315. }
  5316. /*
  5317. * Print the matrix:
  5318. */
  5319. if (migration_debug)
  5320. printk("migration: max_cache_size: %d, cpu: %d MHz:\n",
  5321. max_cache_size,
  5322. #ifdef CONFIG_X86
  5323. cpu_khz/1000
  5324. #else
  5325. -1
  5326. #endif
  5327. );
  5328. if (system_state == SYSTEM_BOOTING && num_online_cpus() > 1) {
  5329. printk("migration_cost=");
  5330. for (distance = 0; distance <= max_distance; distance++) {
  5331. if (distance)
  5332. printk(",");
  5333. printk("%ld", (long)migration_cost[distance] / 1000);
  5334. }
  5335. printk("\n");
  5336. }
  5337. j1 = jiffies;
  5338. if (migration_debug)
  5339. printk("migration: %ld seconds\n", (j1-j0) / HZ);
  5340. /*
  5341. * Move back to the original CPU. NUMA-Q gets confused
  5342. * if we migrate to another quad during bootup.
  5343. */
  5344. if (raw_smp_processor_id() != orig_cpu) {
  5345. cpumask_t mask = cpumask_of_cpu(orig_cpu),
  5346. saved_mask = current->cpus_allowed;
  5347. set_cpus_allowed(current, mask);
  5348. set_cpus_allowed(current, saved_mask);
  5349. }
  5350. }
  5351. #ifdef CONFIG_NUMA
  5352. /**
  5353. * find_next_best_node - find the next node to include in a sched_domain
  5354. * @node: node whose sched_domain we're building
  5355. * @used_nodes: nodes already in the sched_domain
  5356. *
  5357. * Find the next node to include in a given scheduling domain. Simply
  5358. * finds the closest node not already in the @used_nodes map.
  5359. *
  5360. * Should use nodemask_t.
  5361. */
  5362. static int find_next_best_node(int node, unsigned long *used_nodes)
  5363. {
  5364. int i, n, val, min_val, best_node = 0;
  5365. min_val = INT_MAX;
  5366. for (i = 0; i < MAX_NUMNODES; i++) {
  5367. /* Start at @node */
  5368. n = (node + i) % MAX_NUMNODES;
  5369. if (!nr_cpus_node(n))
  5370. continue;
  5371. /* Skip already used nodes */
  5372. if (test_bit(n, used_nodes))
  5373. continue;
  5374. /* Simple min distance search */
  5375. val = node_distance(node, n);
  5376. if (val < min_val) {
  5377. min_val = val;
  5378. best_node = n;
  5379. }
  5380. }
  5381. set_bit(best_node, used_nodes);
  5382. return best_node;
  5383. }
  5384. /**
  5385. * sched_domain_node_span - get a cpumask for a node's sched_domain
  5386. * @node: node whose cpumask we're constructing
  5387. * @size: number of nodes to include in this span
  5388. *
  5389. * Given a node, construct a good cpumask for its sched_domain to span. It
  5390. * should be one that prevents unnecessary balancing, but also spreads tasks
  5391. * out optimally.
  5392. */
  5393. static cpumask_t sched_domain_node_span(int node)
  5394. {
  5395. DECLARE_BITMAP(used_nodes, MAX_NUMNODES);
  5396. cpumask_t span, nodemask;
  5397. int i;
  5398. cpus_clear(span);
  5399. bitmap_zero(used_nodes, MAX_NUMNODES);
  5400. nodemask = node_to_cpumask(node);
  5401. cpus_or(span, span, nodemask);
  5402. set_bit(node, used_nodes);
  5403. for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
  5404. int next_node = find_next_best_node(node, used_nodes);
  5405. nodemask = node_to_cpumask(next_node);
  5406. cpus_or(span, span, nodemask);
  5407. }
  5408. return span;
  5409. }
  5410. #endif
  5411. int sched_smt_power_savings = 0, sched_mc_power_savings = 0;
  5412. /*
  5413. * SMT sched-domains:
  5414. */
  5415. #ifdef CONFIG_SCHED_SMT
  5416. static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
  5417. static DEFINE_PER_CPU(struct sched_group, sched_group_cpus);
  5418. static int cpu_to_cpu_group(int cpu, const cpumask_t *cpu_map,
  5419. struct sched_group **sg)
  5420. {
  5421. if (sg)
  5422. *sg = &per_cpu(sched_group_cpus, cpu);
  5423. return cpu;
  5424. }
  5425. #endif
  5426. /*
  5427. * multi-core sched-domains:
  5428. */
  5429. #ifdef CONFIG_SCHED_MC
  5430. static DEFINE_PER_CPU(struct sched_domain, core_domains);
  5431. static DEFINE_PER_CPU(struct sched_group, sched_group_core);
  5432. #endif
  5433. #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
  5434. static int cpu_to_core_group(int cpu, const cpumask_t *cpu_map,
  5435. struct sched_group **sg)
  5436. {
  5437. int group;
  5438. cpumask_t mask = cpu_sibling_map[cpu];
  5439. cpus_and(mask, mask, *cpu_map);
  5440. group = first_cpu(mask);
  5441. if (sg)
  5442. *sg = &per_cpu(sched_group_core, group);
  5443. return group;
  5444. }
  5445. #elif defined(CONFIG_SCHED_MC)
  5446. static int cpu_to_core_group(int cpu, const cpumask_t *cpu_map,
  5447. struct sched_group **sg)
  5448. {
  5449. if (sg)
  5450. *sg = &per_cpu(sched_group_core, cpu);
  5451. return cpu;
  5452. }
  5453. #endif
  5454. static DEFINE_PER_CPU(struct sched_domain, phys_domains);
  5455. static DEFINE_PER_CPU(struct sched_group, sched_group_phys);
  5456. static int cpu_to_phys_group(int cpu, const cpumask_t *cpu_map,
  5457. struct sched_group **sg)
  5458. {
  5459. int group;
  5460. #ifdef CONFIG_SCHED_MC
  5461. cpumask_t mask = cpu_coregroup_map(cpu);
  5462. cpus_and(mask, mask, *cpu_map);
  5463. group = first_cpu(mask);
  5464. #elif defined(CONFIG_SCHED_SMT)
  5465. cpumask_t mask = cpu_sibling_map[cpu];
  5466. cpus_and(mask, mask, *cpu_map);
  5467. group = first_cpu(mask);
  5468. #else
  5469. group = cpu;
  5470. #endif
  5471. if (sg)
  5472. *sg = &per_cpu(sched_group_phys, group);
  5473. return group;
  5474. }
  5475. #ifdef CONFIG_NUMA
  5476. /*
  5477. * The init_sched_build_groups can't handle what we want to do with node
  5478. * groups, so roll our own. Now each node has its own list of groups which
  5479. * gets dynamically allocated.
  5480. */
  5481. static DEFINE_PER_CPU(struct sched_domain, node_domains);
  5482. static struct sched_group **sched_group_nodes_bycpu[NR_CPUS];
  5483. static DEFINE_PER_CPU(struct sched_domain, allnodes_domains);
  5484. static DEFINE_PER_CPU(struct sched_group, sched_group_allnodes);
  5485. static int cpu_to_allnodes_group(int cpu, const cpumask_t *cpu_map,
  5486. struct sched_group **sg)
  5487. {
  5488. cpumask_t nodemask = node_to_cpumask(cpu_to_node(cpu));
  5489. int group;
  5490. cpus_and(nodemask, nodemask, *cpu_map);
  5491. group = first_cpu(nodemask);
  5492. if (sg)
  5493. *sg = &per_cpu(sched_group_allnodes, group);
  5494. return group;
  5495. }
  5496. static void init_numa_sched_groups_power(struct sched_group *group_head)
  5497. {
  5498. struct sched_group *sg = group_head;
  5499. int j;
  5500. if (!sg)
  5501. return;
  5502. next_sg:
  5503. for_each_cpu_mask(j, sg->cpumask) {
  5504. struct sched_domain *sd;
  5505. sd = &per_cpu(phys_domains, j);
  5506. if (j != first_cpu(sd->groups->cpumask)) {
  5507. /*
  5508. * Only add "power" once for each
  5509. * physical package.
  5510. */
  5511. continue;
  5512. }
  5513. sg->cpu_power += sd->groups->cpu_power;
  5514. }
  5515. sg = sg->next;
  5516. if (sg != group_head)
  5517. goto next_sg;
  5518. }
  5519. #endif
  5520. #ifdef CONFIG_NUMA
  5521. /* Free memory allocated for various sched_group structures */
  5522. static void free_sched_groups(const cpumask_t *cpu_map)
  5523. {
  5524. int cpu, i;
  5525. for_each_cpu_mask(cpu, *cpu_map) {
  5526. struct sched_group **sched_group_nodes
  5527. = sched_group_nodes_bycpu[cpu];
  5528. if (!sched_group_nodes)
  5529. continue;
  5530. for (i = 0; i < MAX_NUMNODES; i++) {
  5531. cpumask_t nodemask = node_to_cpumask(i);
  5532. struct sched_group *oldsg, *sg = sched_group_nodes[i];
  5533. cpus_and(nodemask, nodemask, *cpu_map);
  5534. if (cpus_empty(nodemask))
  5535. continue;
  5536. if (sg == NULL)
  5537. continue;
  5538. sg = sg->next;
  5539. next_sg:
  5540. oldsg = sg;
  5541. sg = sg->next;
  5542. kfree(oldsg);
  5543. if (oldsg != sched_group_nodes[i])
  5544. goto next_sg;
  5545. }
  5546. kfree(sched_group_nodes);
  5547. sched_group_nodes_bycpu[cpu] = NULL;
  5548. }
  5549. }
  5550. #else
  5551. static void free_sched_groups(const cpumask_t *cpu_map)
  5552. {
  5553. }
  5554. #endif
  5555. /*
  5556. * Initialize sched groups cpu_power.
  5557. *
  5558. * cpu_power indicates the capacity of sched group, which is used while
  5559. * distributing the load between different sched groups in a sched domain.
  5560. * Typically cpu_power for all the groups in a sched domain will be same unless
  5561. * there are asymmetries in the topology. If there are asymmetries, group
  5562. * having more cpu_power will pickup more load compared to the group having
  5563. * less cpu_power.
  5564. *
  5565. * cpu_power will be a multiple of SCHED_LOAD_SCALE. This multiple represents
  5566. * the maximum number of tasks a group can handle in the presence of other idle
  5567. * or lightly loaded groups in the same sched domain.
  5568. */
  5569. static void init_sched_groups_power(int cpu, struct sched_domain *sd)
  5570. {
  5571. struct sched_domain *child;
  5572. struct sched_group *group;
  5573. WARN_ON(!sd || !sd->groups);
  5574. if (cpu != first_cpu(sd->groups->cpumask))
  5575. return;
  5576. child = sd->child;
  5577. /*
  5578. * For perf policy, if the groups in child domain share resources
  5579. * (for example cores sharing some portions of the cache hierarchy
  5580. * or SMT), then set this domain groups cpu_power such that each group
  5581. * can handle only one task, when there are other idle groups in the
  5582. * same sched domain.
  5583. */
  5584. if (!child || (!(sd->flags & SD_POWERSAVINGS_BALANCE) &&
  5585. (child->flags &
  5586. (SD_SHARE_CPUPOWER | SD_SHARE_PKG_RESOURCES)))) {
  5587. sd->groups->cpu_power = SCHED_LOAD_SCALE;
  5588. return;
  5589. }
  5590. sd->groups->cpu_power = 0;
  5591. /*
  5592. * add cpu_power of each child group to this groups cpu_power
  5593. */
  5594. group = child->groups;
  5595. do {
  5596. sd->groups->cpu_power += group->cpu_power;
  5597. group = group->next;
  5598. } while (group != child->groups);
  5599. }
  5600. /*
  5601. * Build sched domains for a given set of cpus and attach the sched domains
  5602. * to the individual cpus
  5603. */
  5604. static int build_sched_domains(const cpumask_t *cpu_map)
  5605. {
  5606. int i;
  5607. struct sched_domain *sd;
  5608. #ifdef CONFIG_NUMA
  5609. struct sched_group **sched_group_nodes = NULL;
  5610. int sd_allnodes = 0;
  5611. /*
  5612. * Allocate the per-node list of sched groups
  5613. */
  5614. sched_group_nodes = kzalloc(sizeof(struct sched_group*)*MAX_NUMNODES,
  5615. GFP_KERNEL);
  5616. if (!sched_group_nodes) {
  5617. printk(KERN_WARNING "Can not alloc sched group node list\n");
  5618. return -ENOMEM;
  5619. }
  5620. sched_group_nodes_bycpu[first_cpu(*cpu_map)] = sched_group_nodes;
  5621. #endif
  5622. /*
  5623. * Set up domains for cpus specified by the cpu_map.
  5624. */
  5625. for_each_cpu_mask(i, *cpu_map) {
  5626. struct sched_domain *sd = NULL, *p;
  5627. cpumask_t nodemask = node_to_cpumask(cpu_to_node(i));
  5628. cpus_and(nodemask, nodemask, *cpu_map);
  5629. #ifdef CONFIG_NUMA
  5630. if (cpus_weight(*cpu_map)
  5631. > SD_NODES_PER_DOMAIN*cpus_weight(nodemask)) {
  5632. sd = &per_cpu(allnodes_domains, i);
  5633. *sd = SD_ALLNODES_INIT;
  5634. sd->span = *cpu_map;
  5635. cpu_to_allnodes_group(i, cpu_map, &sd->groups);
  5636. p = sd;
  5637. sd_allnodes = 1;
  5638. } else
  5639. p = NULL;
  5640. sd = &per_cpu(node_domains, i);
  5641. *sd = SD_NODE_INIT;
  5642. sd->span = sched_domain_node_span(cpu_to_node(i));
  5643. sd->parent = p;
  5644. if (p)
  5645. p->child = sd;
  5646. cpus_and(sd->span, sd->span, *cpu_map);
  5647. #endif
  5648. p = sd;
  5649. sd = &per_cpu(phys_domains, i);
  5650. *sd = SD_CPU_INIT;
  5651. sd->span = nodemask;
  5652. sd->parent = p;
  5653. if (p)
  5654. p->child = sd;
  5655. cpu_to_phys_group(i, cpu_map, &sd->groups);
  5656. #ifdef CONFIG_SCHED_MC
  5657. p = sd;
  5658. sd = &per_cpu(core_domains, i);
  5659. *sd = SD_MC_INIT;
  5660. sd->span = cpu_coregroup_map(i);
  5661. cpus_and(sd->span, sd->span, *cpu_map);
  5662. sd->parent = p;
  5663. p->child = sd;
  5664. cpu_to_core_group(i, cpu_map, &sd->groups);
  5665. #endif
  5666. #ifdef CONFIG_SCHED_SMT
  5667. p = sd;
  5668. sd = &per_cpu(cpu_domains, i);
  5669. *sd = SD_SIBLING_INIT;
  5670. sd->span = cpu_sibling_map[i];
  5671. cpus_and(sd->span, sd->span, *cpu_map);
  5672. sd->parent = p;
  5673. p->child = sd;
  5674. cpu_to_cpu_group(i, cpu_map, &sd->groups);
  5675. #endif
  5676. }
  5677. #ifdef CONFIG_SCHED_SMT
  5678. /* Set up CPU (sibling) groups */
  5679. for_each_cpu_mask(i, *cpu_map) {
  5680. cpumask_t this_sibling_map = cpu_sibling_map[i];
  5681. cpus_and(this_sibling_map, this_sibling_map, *cpu_map);
  5682. if (i != first_cpu(this_sibling_map))
  5683. continue;
  5684. init_sched_build_groups(this_sibling_map, cpu_map, &cpu_to_cpu_group);
  5685. }
  5686. #endif
  5687. #ifdef CONFIG_SCHED_MC
  5688. /* Set up multi-core groups */
  5689. for_each_cpu_mask(i, *cpu_map) {
  5690. cpumask_t this_core_map = cpu_coregroup_map(i);
  5691. cpus_and(this_core_map, this_core_map, *cpu_map);
  5692. if (i != first_cpu(this_core_map))
  5693. continue;
  5694. init_sched_build_groups(this_core_map, cpu_map, &cpu_to_core_group);
  5695. }
  5696. #endif
  5697. /* Set up physical groups */
  5698. for (i = 0; i < MAX_NUMNODES; i++) {
  5699. cpumask_t nodemask = node_to_cpumask(i);
  5700. cpus_and(nodemask, nodemask, *cpu_map);
  5701. if (cpus_empty(nodemask))
  5702. continue;
  5703. init_sched_build_groups(nodemask, cpu_map, &cpu_to_phys_group);
  5704. }
  5705. #ifdef CONFIG_NUMA
  5706. /* Set up node groups */
  5707. if (sd_allnodes)
  5708. init_sched_build_groups(*cpu_map, cpu_map, &cpu_to_allnodes_group);
  5709. for (i = 0; i < MAX_NUMNODES; i++) {
  5710. /* Set up node groups */
  5711. struct sched_group *sg, *prev;
  5712. cpumask_t nodemask = node_to_cpumask(i);
  5713. cpumask_t domainspan;
  5714. cpumask_t covered = CPU_MASK_NONE;
  5715. int j;
  5716. cpus_and(nodemask, nodemask, *cpu_map);
  5717. if (cpus_empty(nodemask)) {
  5718. sched_group_nodes[i] = NULL;
  5719. continue;
  5720. }
  5721. domainspan = sched_domain_node_span(i);
  5722. cpus_and(domainspan, domainspan, *cpu_map);
  5723. sg = kmalloc_node(sizeof(struct sched_group), GFP_KERNEL, i);
  5724. if (!sg) {
  5725. printk(KERN_WARNING "Can not alloc domain group for "
  5726. "node %d\n", i);
  5727. goto error;
  5728. }
  5729. sched_group_nodes[i] = sg;
  5730. for_each_cpu_mask(j, nodemask) {
  5731. struct sched_domain *sd;
  5732. sd = &per_cpu(node_domains, j);
  5733. sd->groups = sg;
  5734. }
  5735. sg->cpu_power = 0;
  5736. sg->cpumask = nodemask;
  5737. sg->next = sg;
  5738. cpus_or(covered, covered, nodemask);
  5739. prev = sg;
  5740. for (j = 0; j < MAX_NUMNODES; j++) {
  5741. cpumask_t tmp, notcovered;
  5742. int n = (i + j) % MAX_NUMNODES;
  5743. cpus_complement(notcovered, covered);
  5744. cpus_and(tmp, notcovered, *cpu_map);
  5745. cpus_and(tmp, tmp, domainspan);
  5746. if (cpus_empty(tmp))
  5747. break;
  5748. nodemask = node_to_cpumask(n);
  5749. cpus_and(tmp, tmp, nodemask);
  5750. if (cpus_empty(tmp))
  5751. continue;
  5752. sg = kmalloc_node(sizeof(struct sched_group),
  5753. GFP_KERNEL, i);
  5754. if (!sg) {
  5755. printk(KERN_WARNING
  5756. "Can not alloc domain group for node %d\n", j);
  5757. goto error;
  5758. }
  5759. sg->cpu_power = 0;
  5760. sg->cpumask = tmp;
  5761. sg->next = prev->next;
  5762. cpus_or(covered, covered, tmp);
  5763. prev->next = sg;
  5764. prev = sg;
  5765. }
  5766. }
  5767. #endif
  5768. /* Calculate CPU power for physical packages and nodes */
  5769. #ifdef CONFIG_SCHED_SMT
  5770. for_each_cpu_mask(i, *cpu_map) {
  5771. sd = &per_cpu(cpu_domains, i);
  5772. init_sched_groups_power(i, sd);
  5773. }
  5774. #endif
  5775. #ifdef CONFIG_SCHED_MC
  5776. for_each_cpu_mask(i, *cpu_map) {
  5777. sd = &per_cpu(core_domains, i);
  5778. init_sched_groups_power(i, sd);
  5779. }
  5780. #endif
  5781. for_each_cpu_mask(i, *cpu_map) {
  5782. sd = &per_cpu(phys_domains, i);
  5783. init_sched_groups_power(i, sd);
  5784. }
  5785. #ifdef CONFIG_NUMA
  5786. for (i = 0; i < MAX_NUMNODES; i++)
  5787. init_numa_sched_groups_power(sched_group_nodes[i]);
  5788. if (sd_allnodes) {
  5789. struct sched_group *sg;
  5790. cpu_to_allnodes_group(first_cpu(*cpu_map), cpu_map, &sg);
  5791. init_numa_sched_groups_power(sg);
  5792. }
  5793. #endif
  5794. /* Attach the domains */
  5795. for_each_cpu_mask(i, *cpu_map) {
  5796. struct sched_domain *sd;
  5797. #ifdef CONFIG_SCHED_SMT
  5798. sd = &per_cpu(cpu_domains, i);
  5799. #elif defined(CONFIG_SCHED_MC)
  5800. sd = &per_cpu(core_domains, i);
  5801. #else
  5802. sd = &per_cpu(phys_domains, i);
  5803. #endif
  5804. cpu_attach_domain(sd, i);
  5805. }
  5806. /*
  5807. * Tune cache-hot values:
  5808. */
  5809. calibrate_migration_costs(cpu_map);
  5810. return 0;
  5811. #ifdef CONFIG_NUMA
  5812. error:
  5813. free_sched_groups(cpu_map);
  5814. return -ENOMEM;
  5815. #endif
  5816. }
  5817. /*
  5818. * Set up scheduler domains and groups. Callers must hold the hotplug lock.
  5819. */
  5820. static int arch_init_sched_domains(const cpumask_t *cpu_map)
  5821. {
  5822. cpumask_t cpu_default_map;
  5823. int err;
  5824. /*
  5825. * Setup mask for cpus without special case scheduling requirements.
  5826. * For now this just excludes isolated cpus, but could be used to
  5827. * exclude other special cases in the future.
  5828. */
  5829. cpus_andnot(cpu_default_map, *cpu_map, cpu_isolated_map);
  5830. err = build_sched_domains(&cpu_default_map);
  5831. return err;
  5832. }
  5833. static void arch_destroy_sched_domains(const cpumask_t *cpu_map)
  5834. {
  5835. free_sched_groups(cpu_map);
  5836. }
  5837. /*
  5838. * Detach sched domains from a group of cpus specified in cpu_map
  5839. * These cpus will now be attached to the NULL domain
  5840. */
  5841. static void detach_destroy_domains(const cpumask_t *cpu_map)
  5842. {
  5843. int i;
  5844. for_each_cpu_mask(i, *cpu_map)
  5845. cpu_attach_domain(NULL, i);
  5846. synchronize_sched();
  5847. arch_destroy_sched_domains(cpu_map);
  5848. }
  5849. /*
  5850. * Partition sched domains as specified by the cpumasks below.
  5851. * This attaches all cpus from the cpumasks to the NULL domain,
  5852. * waits for a RCU quiescent period, recalculates sched
  5853. * domain information and then attaches them back to the
  5854. * correct sched domains
  5855. * Call with hotplug lock held
  5856. */
  5857. int partition_sched_domains(cpumask_t *partition1, cpumask_t *partition2)
  5858. {
  5859. cpumask_t change_map;
  5860. int err = 0;
  5861. cpus_and(*partition1, *partition1, cpu_online_map);
  5862. cpus_and(*partition2, *partition2, cpu_online_map);
  5863. cpus_or(change_map, *partition1, *partition2);
  5864. /* Detach sched domains from all of the affected cpus */
  5865. detach_destroy_domains(&change_map);
  5866. if (!cpus_empty(*partition1))
  5867. err = build_sched_domains(partition1);
  5868. if (!err && !cpus_empty(*partition2))
  5869. err = build_sched_domains(partition2);
  5870. return err;
  5871. }
  5872. #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
  5873. int arch_reinit_sched_domains(void)
  5874. {
  5875. int err;
  5876. lock_cpu_hotplug();
  5877. detach_destroy_domains(&cpu_online_map);
  5878. err = arch_init_sched_domains(&cpu_online_map);
  5879. unlock_cpu_hotplug();
  5880. return err;
  5881. }
  5882. static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt)
  5883. {
  5884. int ret;
  5885. if (buf[0] != '0' && buf[0] != '1')
  5886. return -EINVAL;
  5887. if (smt)
  5888. sched_smt_power_savings = (buf[0] == '1');
  5889. else
  5890. sched_mc_power_savings = (buf[0] == '1');
  5891. ret = arch_reinit_sched_domains();
  5892. return ret ? ret : count;
  5893. }
  5894. int sched_create_sysfs_power_savings_entries(struct sysdev_class *cls)
  5895. {
  5896. int err = 0;
  5897. #ifdef CONFIG_SCHED_SMT
  5898. if (smt_capable())
  5899. err = sysfs_create_file(&cls->kset.kobj,
  5900. &attr_sched_smt_power_savings.attr);
  5901. #endif
  5902. #ifdef CONFIG_SCHED_MC
  5903. if (!err && mc_capable())
  5904. err = sysfs_create_file(&cls->kset.kobj,
  5905. &attr_sched_mc_power_savings.attr);
  5906. #endif
  5907. return err;
  5908. }
  5909. #endif
  5910. #ifdef CONFIG_SCHED_MC
  5911. static ssize_t sched_mc_power_savings_show(struct sys_device *dev, char *page)
  5912. {
  5913. return sprintf(page, "%u\n", sched_mc_power_savings);
  5914. }
  5915. static ssize_t sched_mc_power_savings_store(struct sys_device *dev,
  5916. const char *buf, size_t count)
  5917. {
  5918. return sched_power_savings_store(buf, count, 0);
  5919. }
  5920. SYSDEV_ATTR(sched_mc_power_savings, 0644, sched_mc_power_savings_show,
  5921. sched_mc_power_savings_store);
  5922. #endif
  5923. #ifdef CONFIG_SCHED_SMT
  5924. static ssize_t sched_smt_power_savings_show(struct sys_device *dev, char *page)
  5925. {
  5926. return sprintf(page, "%u\n", sched_smt_power_savings);
  5927. }
  5928. static ssize_t sched_smt_power_savings_store(struct sys_device *dev,
  5929. const char *buf, size_t count)
  5930. {
  5931. return sched_power_savings_store(buf, count, 1);
  5932. }
  5933. SYSDEV_ATTR(sched_smt_power_savings, 0644, sched_smt_power_savings_show,
  5934. sched_smt_power_savings_store);
  5935. #endif
  5936. /*
  5937. * Force a reinitialization of the sched domains hierarchy. The domains
  5938. * and groups cannot be updated in place without racing with the balancing
  5939. * code, so we temporarily attach all running cpus to the NULL domain
  5940. * which will prevent rebalancing while the sched domains are recalculated.
  5941. */
  5942. static int update_sched_domains(struct notifier_block *nfb,
  5943. unsigned long action, void *hcpu)
  5944. {
  5945. switch (action) {
  5946. case CPU_UP_PREPARE:
  5947. case CPU_DOWN_PREPARE:
  5948. detach_destroy_domains(&cpu_online_map);
  5949. return NOTIFY_OK;
  5950. case CPU_UP_CANCELED:
  5951. case CPU_DOWN_FAILED:
  5952. case CPU_ONLINE:
  5953. case CPU_DEAD:
  5954. /*
  5955. * Fall through and re-initialise the domains.
  5956. */
  5957. break;
  5958. default:
  5959. return NOTIFY_DONE;
  5960. }
  5961. /* The hotplug lock is already held by cpu_up/cpu_down */
  5962. arch_init_sched_domains(&cpu_online_map);
  5963. return NOTIFY_OK;
  5964. }
  5965. void __init sched_init_smp(void)
  5966. {
  5967. cpumask_t non_isolated_cpus;
  5968. lock_cpu_hotplug();
  5969. arch_init_sched_domains(&cpu_online_map);
  5970. cpus_andnot(non_isolated_cpus, cpu_possible_map, cpu_isolated_map);
  5971. if (cpus_empty(non_isolated_cpus))
  5972. cpu_set(smp_processor_id(), non_isolated_cpus);
  5973. unlock_cpu_hotplug();
  5974. /* XXX: Theoretical race here - CPU may be hotplugged now */
  5975. hotcpu_notifier(update_sched_domains, 0);
  5976. /* Move init over to a non-isolated CPU */
  5977. if (set_cpus_allowed(current, non_isolated_cpus) < 0)
  5978. BUG();
  5979. }
  5980. #else
  5981. void __init sched_init_smp(void)
  5982. {
  5983. }
  5984. #endif /* CONFIG_SMP */
  5985. int in_sched_functions(unsigned long addr)
  5986. {
  5987. /* Linker adds these: start and end of __sched functions */
  5988. extern char __sched_text_start[], __sched_text_end[];
  5989. return in_lock_functions(addr) ||
  5990. (addr >= (unsigned long)__sched_text_start
  5991. && addr < (unsigned long)__sched_text_end);
  5992. }
  5993. void __init sched_init(void)
  5994. {
  5995. int i, j, k;
  5996. for_each_possible_cpu(i) {
  5997. struct prio_array *array;
  5998. struct rq *rq;
  5999. rq = cpu_rq(i);
  6000. spin_lock_init(&rq->lock);
  6001. lockdep_set_class(&rq->lock, &rq->rq_lock_key);
  6002. rq->nr_running = 0;
  6003. rq->active = rq->arrays;
  6004. rq->expired = rq->arrays + 1;
  6005. rq->best_expired_prio = MAX_PRIO;
  6006. #ifdef CONFIG_SMP
  6007. rq->sd = NULL;
  6008. for (j = 1; j < 3; j++)
  6009. rq->cpu_load[j] = 0;
  6010. rq->active_balance = 0;
  6011. rq->push_cpu = 0;
  6012. rq->cpu = i;
  6013. rq->migration_thread = NULL;
  6014. INIT_LIST_HEAD(&rq->migration_queue);
  6015. #endif
  6016. atomic_set(&rq->nr_iowait, 0);
  6017. for (j = 0; j < 2; j++) {
  6018. array = rq->arrays + j;
  6019. for (k = 0; k < MAX_PRIO; k++) {
  6020. INIT_LIST_HEAD(array->queue + k);
  6021. __clear_bit(k, array->bitmap);
  6022. }
  6023. // delimiter for bitsearch
  6024. __set_bit(MAX_PRIO, array->bitmap);
  6025. }
  6026. }
  6027. set_load_weight(&init_task);
  6028. #ifdef CONFIG_SMP
  6029. open_softirq(SCHED_SOFTIRQ, run_rebalance_domains, NULL);
  6030. #endif
  6031. #ifdef CONFIG_RT_MUTEXES
  6032. plist_head_init(&init_task.pi_waiters, &init_task.pi_lock);
  6033. #endif
  6034. /*
  6035. * The boot idle thread does lazy MMU switching as well:
  6036. */
  6037. atomic_inc(&init_mm.mm_count);
  6038. enter_lazy_tlb(&init_mm, current);
  6039. /*
  6040. * Make us the idle thread. Technically, schedule() should not be
  6041. * called from this thread, however somewhere below it might be,
  6042. * but because we are the idle thread, we just pick up running again
  6043. * when this runqueue becomes "idle".
  6044. */
  6045. init_idle(current, smp_processor_id());
  6046. }
  6047. #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
  6048. void __might_sleep(char *file, int line)
  6049. {
  6050. #ifdef in_atomic
  6051. static unsigned long prev_jiffy; /* ratelimiting */
  6052. if ((in_atomic() || irqs_disabled()) &&
  6053. system_state == SYSTEM_RUNNING && !oops_in_progress) {
  6054. if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
  6055. return;
  6056. prev_jiffy = jiffies;
  6057. printk(KERN_ERR "BUG: sleeping function called from invalid"
  6058. " context at %s:%d\n", file, line);
  6059. printk("in_atomic():%d, irqs_disabled():%d\n",
  6060. in_atomic(), irqs_disabled());
  6061. debug_show_held_locks(current);
  6062. if (irqs_disabled())
  6063. print_irqtrace_events(current);
  6064. dump_stack();
  6065. }
  6066. #endif
  6067. }
  6068. EXPORT_SYMBOL(__might_sleep);
  6069. #endif
  6070. #ifdef CONFIG_MAGIC_SYSRQ
  6071. void normalize_rt_tasks(void)
  6072. {
  6073. struct prio_array *array;
  6074. struct task_struct *p;
  6075. unsigned long flags;
  6076. struct rq *rq;
  6077. read_lock_irq(&tasklist_lock);
  6078. for_each_process(p) {
  6079. if (!rt_task(p))
  6080. continue;
  6081. spin_lock_irqsave(&p->pi_lock, flags);
  6082. rq = __task_rq_lock(p);
  6083. array = p->array;
  6084. if (array)
  6085. deactivate_task(p, task_rq(p));
  6086. __setscheduler(p, SCHED_NORMAL, 0);
  6087. if (array) {
  6088. __activate_task(p, task_rq(p));
  6089. resched_task(rq->curr);
  6090. }
  6091. __task_rq_unlock(rq);
  6092. spin_unlock_irqrestore(&p->pi_lock, flags);
  6093. }
  6094. read_unlock_irq(&tasklist_lock);
  6095. }
  6096. #endif /* CONFIG_MAGIC_SYSRQ */
  6097. #ifdef CONFIG_IA64
  6098. /*
  6099. * These functions are only useful for the IA64 MCA handling.
  6100. *
  6101. * They can only be called when the whole system has been
  6102. * stopped - every CPU needs to be quiescent, and no scheduling
  6103. * activity can take place. Using them for anything else would
  6104. * be a serious bug, and as a result, they aren't even visible
  6105. * under any other configuration.
  6106. */
  6107. /**
  6108. * curr_task - return the current task for a given cpu.
  6109. * @cpu: the processor in question.
  6110. *
  6111. * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
  6112. */
  6113. struct task_struct *curr_task(int cpu)
  6114. {
  6115. return cpu_curr(cpu);
  6116. }
  6117. /**
  6118. * set_curr_task - set the current task for a given cpu.
  6119. * @cpu: the processor in question.
  6120. * @p: the task pointer to set.
  6121. *
  6122. * Description: This function must only be used when non-maskable interrupts
  6123. * are serviced on a separate stack. It allows the architecture to switch the
  6124. * notion of the current task on a cpu in a non-blocking manner. This function
  6125. * must be called with all CPU's synchronized, and interrupts disabled, the
  6126. * and caller must save the original value of the current task (see
  6127. * curr_task() above) and restore that value before reenabling interrupts and
  6128. * re-starting the system.
  6129. *
  6130. * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
  6131. */
  6132. void set_curr_task(int cpu, struct task_struct *p)
  6133. {
  6134. cpu_curr(cpu) = p;
  6135. }
  6136. #endif