sched.c 153 KB

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