sched.c 153 KB

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