sched.c 168 KB

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