sched.c 177 KB

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