sched.c 138 KB

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