sched.c 176 KB

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