sched.c 153 KB

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