sched.c 154 KB

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