sched.c 130 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256
  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. local_group = cpu_isset(this_cpu, group->cpumask);
  853. /* XXX: put a cpus allowed check */
  854. /* Tally up the load of all CPUs in the group */
  855. avg_load = 0;
  856. for_each_cpu_mask(i, group->cpumask) {
  857. /* Bias balancing toward cpus of our domain */
  858. if (local_group)
  859. load = source_load(i, load_idx);
  860. else
  861. load = target_load(i, load_idx);
  862. avg_load += load;
  863. }
  864. /* Adjust by relative CPU power of the group */
  865. avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
  866. if (local_group) {
  867. this_load = avg_load;
  868. this = group;
  869. } else if (avg_load < min_load) {
  870. min_load = avg_load;
  871. idlest = group;
  872. }
  873. group = group->next;
  874. } while (group != sd->groups);
  875. if (!idlest || 100*this_load < imbalance*min_load)
  876. return NULL;
  877. return idlest;
  878. }
  879. /*
  880. * find_idlest_queue - find the idlest runqueue among the cpus in group.
  881. */
  882. static int find_idlest_cpu(struct sched_group *group, int this_cpu)
  883. {
  884. unsigned long load, min_load = ULONG_MAX;
  885. int idlest = -1;
  886. int i;
  887. for_each_cpu_mask(i, group->cpumask) {
  888. load = source_load(i, 0);
  889. if (load < min_load || (load == min_load && i == this_cpu)) {
  890. min_load = load;
  891. idlest = i;
  892. }
  893. }
  894. return idlest;
  895. }
  896. /*
  897. * sched_balance_self: balance the current task (running on cpu) in domains
  898. * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
  899. * SD_BALANCE_EXEC.
  900. *
  901. * Balance, ie. select the least loaded group.
  902. *
  903. * Returns the target CPU number, or the same CPU if no balancing is needed.
  904. *
  905. * preempt must be disabled.
  906. */
  907. static int sched_balance_self(int cpu, int flag)
  908. {
  909. struct task_struct *t = current;
  910. struct sched_domain *tmp, *sd = NULL;
  911. for_each_domain(cpu, tmp)
  912. if (tmp->flags & flag)
  913. sd = tmp;
  914. while (sd) {
  915. cpumask_t span;
  916. struct sched_group *group;
  917. int new_cpu;
  918. int weight;
  919. span = sd->span;
  920. group = find_idlest_group(sd, t, cpu);
  921. if (!group)
  922. goto nextlevel;
  923. new_cpu = find_idlest_cpu(group, cpu);
  924. if (new_cpu == -1 || new_cpu == cpu)
  925. goto nextlevel;
  926. /* Now try balancing at a lower domain level */
  927. cpu = new_cpu;
  928. nextlevel:
  929. sd = NULL;
  930. weight = cpus_weight(span);
  931. for_each_domain(cpu, tmp) {
  932. if (weight <= cpus_weight(tmp->span))
  933. break;
  934. if (tmp->flags & flag)
  935. sd = tmp;
  936. }
  937. /* while loop will break here if sd == NULL */
  938. }
  939. return cpu;
  940. }
  941. #endif /* CONFIG_SMP */
  942. /*
  943. * wake_idle() will wake a task on an idle cpu if task->cpu is
  944. * not idle and an idle cpu is available. The span of cpus to
  945. * search starts with cpus closest then further out as needed,
  946. * so we always favor a closer, idle cpu.
  947. *
  948. * Returns the CPU we should wake onto.
  949. */
  950. #if defined(ARCH_HAS_SCHED_WAKE_IDLE)
  951. static int wake_idle(int cpu, task_t *p)
  952. {
  953. cpumask_t tmp;
  954. struct sched_domain *sd;
  955. int i;
  956. if (idle_cpu(cpu))
  957. return cpu;
  958. for_each_domain(cpu, sd) {
  959. if (sd->flags & SD_WAKE_IDLE) {
  960. cpus_and(tmp, sd->span, p->cpus_allowed);
  961. for_each_cpu_mask(i, tmp) {
  962. if (idle_cpu(i))
  963. return i;
  964. }
  965. }
  966. else
  967. break;
  968. }
  969. return cpu;
  970. }
  971. #else
  972. static inline int wake_idle(int cpu, task_t *p)
  973. {
  974. return cpu;
  975. }
  976. #endif
  977. /***
  978. * try_to_wake_up - wake up a thread
  979. * @p: the to-be-woken-up thread
  980. * @state: the mask of task states that can be woken
  981. * @sync: do a synchronous wakeup?
  982. *
  983. * Put it on the run-queue if it's not already there. The "current"
  984. * thread is always on the run-queue (except when the actual
  985. * re-schedule is in progress), and as such you're allowed to do
  986. * the simpler "current->state = TASK_RUNNING" to mark yourself
  987. * runnable without the overhead of this.
  988. *
  989. * returns failure only if the task is already active.
  990. */
  991. static int try_to_wake_up(task_t * p, unsigned int state, int sync)
  992. {
  993. int cpu, this_cpu, success = 0;
  994. unsigned long flags;
  995. long old_state;
  996. runqueue_t *rq;
  997. #ifdef CONFIG_SMP
  998. unsigned long load, this_load;
  999. struct sched_domain *sd, *this_sd = NULL;
  1000. int new_cpu;
  1001. #endif
  1002. rq = task_rq_lock(p, &flags);
  1003. old_state = p->state;
  1004. if (!(old_state & state))
  1005. goto out;
  1006. if (p->array)
  1007. goto out_running;
  1008. cpu = task_cpu(p);
  1009. this_cpu = smp_processor_id();
  1010. #ifdef CONFIG_SMP
  1011. if (unlikely(task_running(rq, p)))
  1012. goto out_activate;
  1013. new_cpu = cpu;
  1014. schedstat_inc(rq, ttwu_cnt);
  1015. if (cpu == this_cpu) {
  1016. schedstat_inc(rq, ttwu_local);
  1017. goto out_set_cpu;
  1018. }
  1019. for_each_domain(this_cpu, sd) {
  1020. if (cpu_isset(cpu, sd->span)) {
  1021. schedstat_inc(sd, ttwu_wake_remote);
  1022. this_sd = sd;
  1023. break;
  1024. }
  1025. }
  1026. if (unlikely(!cpu_isset(this_cpu, p->cpus_allowed)))
  1027. goto out_set_cpu;
  1028. /*
  1029. * Check for affine wakeup and passive balancing possibilities.
  1030. */
  1031. if (this_sd) {
  1032. int idx = this_sd->wake_idx;
  1033. unsigned int imbalance;
  1034. imbalance = 100 + (this_sd->imbalance_pct - 100) / 2;
  1035. load = source_load(cpu, idx);
  1036. this_load = target_load(this_cpu, idx);
  1037. new_cpu = this_cpu; /* Wake to this CPU if we can */
  1038. if (this_sd->flags & SD_WAKE_AFFINE) {
  1039. unsigned long tl = this_load;
  1040. /*
  1041. * If sync wakeup then subtract the (maximum possible)
  1042. * effect of the currently running task from the load
  1043. * of the current CPU:
  1044. */
  1045. if (sync)
  1046. tl -= SCHED_LOAD_SCALE;
  1047. if ((tl <= load &&
  1048. tl + target_load(cpu, idx) <= SCHED_LOAD_SCALE) ||
  1049. 100*(tl + SCHED_LOAD_SCALE) <= imbalance*load) {
  1050. /*
  1051. * This domain has SD_WAKE_AFFINE and
  1052. * p is cache cold in this domain, and
  1053. * there is no bad imbalance.
  1054. */
  1055. schedstat_inc(this_sd, ttwu_move_affine);
  1056. goto out_set_cpu;
  1057. }
  1058. }
  1059. /*
  1060. * Start passive balancing when half the imbalance_pct
  1061. * limit is reached.
  1062. */
  1063. if (this_sd->flags & SD_WAKE_BALANCE) {
  1064. if (imbalance*this_load <= 100*load) {
  1065. schedstat_inc(this_sd, ttwu_move_balance);
  1066. goto out_set_cpu;
  1067. }
  1068. }
  1069. }
  1070. new_cpu = cpu; /* Could not wake to this_cpu. Wake to cpu instead */
  1071. out_set_cpu:
  1072. new_cpu = wake_idle(new_cpu, p);
  1073. if (new_cpu != cpu) {
  1074. set_task_cpu(p, new_cpu);
  1075. task_rq_unlock(rq, &flags);
  1076. /* might preempt at this point */
  1077. rq = task_rq_lock(p, &flags);
  1078. old_state = p->state;
  1079. if (!(old_state & state))
  1080. goto out;
  1081. if (p->array)
  1082. goto out_running;
  1083. this_cpu = smp_processor_id();
  1084. cpu = task_cpu(p);
  1085. }
  1086. out_activate:
  1087. #endif /* CONFIG_SMP */
  1088. if (old_state == TASK_UNINTERRUPTIBLE) {
  1089. rq->nr_uninterruptible--;
  1090. /*
  1091. * Tasks on involuntary sleep don't earn
  1092. * sleep_avg beyond just interactive state.
  1093. */
  1094. p->activated = -1;
  1095. }
  1096. /*
  1097. * Sync wakeups (i.e. those types of wakeups where the waker
  1098. * has indicated that it will leave the CPU in short order)
  1099. * don't trigger a preemption, if the woken up task will run on
  1100. * this cpu. (in this case the 'I will reschedule' promise of
  1101. * the waker guarantees that the freshly woken up task is going
  1102. * to be considered on this CPU.)
  1103. */
  1104. activate_task(p, rq, cpu == this_cpu);
  1105. if (!sync || cpu != this_cpu) {
  1106. if (TASK_PREEMPTS_CURR(p, rq))
  1107. resched_task(rq->curr);
  1108. }
  1109. success = 1;
  1110. out_running:
  1111. p->state = TASK_RUNNING;
  1112. out:
  1113. task_rq_unlock(rq, &flags);
  1114. return success;
  1115. }
  1116. int fastcall wake_up_process(task_t * p)
  1117. {
  1118. return try_to_wake_up(p, TASK_STOPPED | TASK_TRACED |
  1119. TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
  1120. }
  1121. EXPORT_SYMBOL(wake_up_process);
  1122. int fastcall wake_up_state(task_t *p, unsigned int state)
  1123. {
  1124. return try_to_wake_up(p, state, 0);
  1125. }
  1126. /*
  1127. * Perform scheduler related setup for a newly forked process p.
  1128. * p is forked by current.
  1129. */
  1130. void fastcall sched_fork(task_t *p, int clone_flags)
  1131. {
  1132. int cpu = get_cpu();
  1133. #ifdef CONFIG_SMP
  1134. cpu = sched_balance_self(cpu, SD_BALANCE_FORK);
  1135. #endif
  1136. set_task_cpu(p, cpu);
  1137. /*
  1138. * We mark the process as running here, but have not actually
  1139. * inserted it onto the runqueue yet. This guarantees that
  1140. * nobody will actually run it, and a signal or other external
  1141. * event cannot wake it up and insert it on the runqueue either.
  1142. */
  1143. p->state = TASK_RUNNING;
  1144. INIT_LIST_HEAD(&p->run_list);
  1145. p->array = NULL;
  1146. #ifdef CONFIG_SCHEDSTATS
  1147. memset(&p->sched_info, 0, sizeof(p->sched_info));
  1148. #endif
  1149. #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
  1150. p->oncpu = 0;
  1151. #endif
  1152. #ifdef CONFIG_PREEMPT
  1153. /* Want to start with kernel preemption disabled. */
  1154. p->thread_info->preempt_count = 1;
  1155. #endif
  1156. /*
  1157. * Share the timeslice between parent and child, thus the
  1158. * total amount of pending timeslices in the system doesn't change,
  1159. * resulting in more scheduling fairness.
  1160. */
  1161. local_irq_disable();
  1162. p->time_slice = (current->time_slice + 1) >> 1;
  1163. /*
  1164. * The remainder of the first timeslice might be recovered by
  1165. * the parent if the child exits early enough.
  1166. */
  1167. p->first_time_slice = 1;
  1168. current->time_slice >>= 1;
  1169. p->timestamp = sched_clock();
  1170. if (unlikely(!current->time_slice)) {
  1171. /*
  1172. * This case is rare, it happens when the parent has only
  1173. * a single jiffy left from its timeslice. Taking the
  1174. * runqueue lock is not a problem.
  1175. */
  1176. current->time_slice = 1;
  1177. scheduler_tick();
  1178. }
  1179. local_irq_enable();
  1180. put_cpu();
  1181. }
  1182. /*
  1183. * wake_up_new_task - wake up a newly created task for the first time.
  1184. *
  1185. * This function will do some initial scheduler statistics housekeeping
  1186. * that must be done for every newly created context, then puts the task
  1187. * on the runqueue and wakes it.
  1188. */
  1189. void fastcall wake_up_new_task(task_t * p, unsigned long clone_flags)
  1190. {
  1191. unsigned long flags;
  1192. int this_cpu, cpu;
  1193. runqueue_t *rq, *this_rq;
  1194. rq = task_rq_lock(p, &flags);
  1195. BUG_ON(p->state != TASK_RUNNING);
  1196. this_cpu = smp_processor_id();
  1197. cpu = task_cpu(p);
  1198. /*
  1199. * We decrease the sleep average of forking parents
  1200. * and children as well, to keep max-interactive tasks
  1201. * from forking tasks that are max-interactive. The parent
  1202. * (current) is done further down, under its lock.
  1203. */
  1204. p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
  1205. CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
  1206. p->prio = effective_prio(p);
  1207. if (likely(cpu == this_cpu)) {
  1208. if (!(clone_flags & CLONE_VM)) {
  1209. /*
  1210. * The VM isn't cloned, so we're in a good position to
  1211. * do child-runs-first in anticipation of an exec. This
  1212. * usually avoids a lot of COW overhead.
  1213. */
  1214. if (unlikely(!current->array))
  1215. __activate_task(p, rq);
  1216. else {
  1217. p->prio = current->prio;
  1218. list_add_tail(&p->run_list, &current->run_list);
  1219. p->array = current->array;
  1220. p->array->nr_active++;
  1221. rq->nr_running++;
  1222. }
  1223. set_need_resched();
  1224. } else
  1225. /* Run child last */
  1226. __activate_task(p, rq);
  1227. /*
  1228. * We skip the following code due to cpu == this_cpu
  1229. *
  1230. * task_rq_unlock(rq, &flags);
  1231. * this_rq = task_rq_lock(current, &flags);
  1232. */
  1233. this_rq = rq;
  1234. } else {
  1235. this_rq = cpu_rq(this_cpu);
  1236. /*
  1237. * Not the local CPU - must adjust timestamp. This should
  1238. * get optimised away in the !CONFIG_SMP case.
  1239. */
  1240. p->timestamp = (p->timestamp - this_rq->timestamp_last_tick)
  1241. + rq->timestamp_last_tick;
  1242. __activate_task(p, rq);
  1243. if (TASK_PREEMPTS_CURR(p, rq))
  1244. resched_task(rq->curr);
  1245. /*
  1246. * Parent and child are on different CPUs, now get the
  1247. * parent runqueue to update the parent's ->sleep_avg:
  1248. */
  1249. task_rq_unlock(rq, &flags);
  1250. this_rq = task_rq_lock(current, &flags);
  1251. }
  1252. current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
  1253. PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
  1254. task_rq_unlock(this_rq, &flags);
  1255. }
  1256. /*
  1257. * Potentially available exiting-child timeslices are
  1258. * retrieved here - this way the parent does not get
  1259. * penalized for creating too many threads.
  1260. *
  1261. * (this cannot be used to 'generate' timeslices
  1262. * artificially, because any timeslice recovered here
  1263. * was given away by the parent in the first place.)
  1264. */
  1265. void fastcall sched_exit(task_t * p)
  1266. {
  1267. unsigned long flags;
  1268. runqueue_t *rq;
  1269. /*
  1270. * If the child was a (relative-) CPU hog then decrease
  1271. * the sleep_avg of the parent as well.
  1272. */
  1273. rq = task_rq_lock(p->parent, &flags);
  1274. if (p->first_time_slice) {
  1275. p->parent->time_slice += p->time_slice;
  1276. if (unlikely(p->parent->time_slice > task_timeslice(p)))
  1277. p->parent->time_slice = task_timeslice(p);
  1278. }
  1279. if (p->sleep_avg < p->parent->sleep_avg)
  1280. p->parent->sleep_avg = p->parent->sleep_avg /
  1281. (EXIT_WEIGHT + 1) * EXIT_WEIGHT + p->sleep_avg /
  1282. (EXIT_WEIGHT + 1);
  1283. task_rq_unlock(rq, &flags);
  1284. }
  1285. /**
  1286. * prepare_task_switch - prepare to switch tasks
  1287. * @rq: the runqueue preparing to switch
  1288. * @next: the task we are going to switch to.
  1289. *
  1290. * This is called with the rq lock held and interrupts off. It must
  1291. * be paired with a subsequent finish_task_switch after the context
  1292. * switch.
  1293. *
  1294. * prepare_task_switch sets up locking and calls architecture specific
  1295. * hooks.
  1296. */
  1297. static inline void prepare_task_switch(runqueue_t *rq, task_t *next)
  1298. {
  1299. prepare_lock_switch(rq, next);
  1300. prepare_arch_switch(next);
  1301. }
  1302. /**
  1303. * finish_task_switch - clean up after a task-switch
  1304. * @prev: the thread we just switched away from.
  1305. *
  1306. * finish_task_switch must be called after the context switch, paired
  1307. * with a prepare_task_switch call before the context switch.
  1308. * finish_task_switch will reconcile locking set up by prepare_task_switch,
  1309. * and do any other architecture-specific cleanup actions.
  1310. *
  1311. * Note that we may have delayed dropping an mm in context_switch(). If
  1312. * so, we finish that here outside of the runqueue lock. (Doing it
  1313. * with the lock held can cause deadlocks; see schedule() for
  1314. * details.)
  1315. */
  1316. static inline void finish_task_switch(runqueue_t *rq, task_t *prev)
  1317. __releases(rq->lock)
  1318. {
  1319. struct mm_struct *mm = rq->prev_mm;
  1320. unsigned long prev_task_flags;
  1321. rq->prev_mm = NULL;
  1322. /*
  1323. * A task struct has one reference for the use as "current".
  1324. * If a task dies, then it sets EXIT_ZOMBIE in tsk->exit_state and
  1325. * calls schedule one last time. The schedule call will never return,
  1326. * and the scheduled task must drop that reference.
  1327. * The test for EXIT_ZOMBIE must occur while the runqueue locks are
  1328. * still held, otherwise prev could be scheduled on another cpu, die
  1329. * there before we look at prev->state, and then the reference would
  1330. * be dropped twice.
  1331. * Manfred Spraul <manfred@colorfullife.com>
  1332. */
  1333. prev_task_flags = prev->flags;
  1334. finish_arch_switch(prev);
  1335. finish_lock_switch(rq, prev);
  1336. if (mm)
  1337. mmdrop(mm);
  1338. if (unlikely(prev_task_flags & PF_DEAD))
  1339. put_task_struct(prev);
  1340. }
  1341. /**
  1342. * schedule_tail - first thing a freshly forked thread must call.
  1343. * @prev: the thread we just switched away from.
  1344. */
  1345. asmlinkage void schedule_tail(task_t *prev)
  1346. __releases(rq->lock)
  1347. {
  1348. runqueue_t *rq = this_rq();
  1349. finish_task_switch(rq, prev);
  1350. #ifdef __ARCH_WANT_UNLOCKED_CTXSW
  1351. /* In this case, finish_task_switch does not reenable preemption */
  1352. preempt_enable();
  1353. #endif
  1354. if (current->set_child_tid)
  1355. put_user(current->pid, current->set_child_tid);
  1356. }
  1357. /*
  1358. * context_switch - switch to the new MM and the new
  1359. * thread's register state.
  1360. */
  1361. static inline
  1362. task_t * context_switch(runqueue_t *rq, task_t *prev, task_t *next)
  1363. {
  1364. struct mm_struct *mm = next->mm;
  1365. struct mm_struct *oldmm = prev->active_mm;
  1366. if (unlikely(!mm)) {
  1367. next->active_mm = oldmm;
  1368. atomic_inc(&oldmm->mm_count);
  1369. enter_lazy_tlb(oldmm, next);
  1370. } else
  1371. switch_mm(oldmm, mm, next);
  1372. if (unlikely(!prev->mm)) {
  1373. prev->active_mm = NULL;
  1374. WARN_ON(rq->prev_mm);
  1375. rq->prev_mm = oldmm;
  1376. }
  1377. /* Here we just switch the register state and the stack. */
  1378. switch_to(prev, next, prev);
  1379. return prev;
  1380. }
  1381. /*
  1382. * nr_running, nr_uninterruptible and nr_context_switches:
  1383. *
  1384. * externally visible scheduler statistics: current number of runnable
  1385. * threads, current number of uninterruptible-sleeping threads, total
  1386. * number of context switches performed since bootup.
  1387. */
  1388. unsigned long nr_running(void)
  1389. {
  1390. unsigned long i, sum = 0;
  1391. for_each_online_cpu(i)
  1392. sum += cpu_rq(i)->nr_running;
  1393. return sum;
  1394. }
  1395. unsigned long nr_uninterruptible(void)
  1396. {
  1397. unsigned long i, sum = 0;
  1398. for_each_cpu(i)
  1399. sum += cpu_rq(i)->nr_uninterruptible;
  1400. /*
  1401. * Since we read the counters lockless, it might be slightly
  1402. * inaccurate. Do not allow it to go below zero though:
  1403. */
  1404. if (unlikely((long)sum < 0))
  1405. sum = 0;
  1406. return sum;
  1407. }
  1408. unsigned long long nr_context_switches(void)
  1409. {
  1410. unsigned long long i, sum = 0;
  1411. for_each_cpu(i)
  1412. sum += cpu_rq(i)->nr_switches;
  1413. return sum;
  1414. }
  1415. unsigned long nr_iowait(void)
  1416. {
  1417. unsigned long i, sum = 0;
  1418. for_each_cpu(i)
  1419. sum += atomic_read(&cpu_rq(i)->nr_iowait);
  1420. return sum;
  1421. }
  1422. #ifdef CONFIG_SMP
  1423. /*
  1424. * double_rq_lock - safely lock two runqueues
  1425. *
  1426. * Note this does not disable interrupts like task_rq_lock,
  1427. * you need to do so manually before calling.
  1428. */
  1429. static void double_rq_lock(runqueue_t *rq1, runqueue_t *rq2)
  1430. __acquires(rq1->lock)
  1431. __acquires(rq2->lock)
  1432. {
  1433. if (rq1 == rq2) {
  1434. spin_lock(&rq1->lock);
  1435. __acquire(rq2->lock); /* Fake it out ;) */
  1436. } else {
  1437. if (rq1 < rq2) {
  1438. spin_lock(&rq1->lock);
  1439. spin_lock(&rq2->lock);
  1440. } else {
  1441. spin_lock(&rq2->lock);
  1442. spin_lock(&rq1->lock);
  1443. }
  1444. }
  1445. }
  1446. /*
  1447. * double_rq_unlock - safely unlock two runqueues
  1448. *
  1449. * Note this does not restore interrupts like task_rq_unlock,
  1450. * you need to do so manually after calling.
  1451. */
  1452. static void double_rq_unlock(runqueue_t *rq1, runqueue_t *rq2)
  1453. __releases(rq1->lock)
  1454. __releases(rq2->lock)
  1455. {
  1456. spin_unlock(&rq1->lock);
  1457. if (rq1 != rq2)
  1458. spin_unlock(&rq2->lock);
  1459. else
  1460. __release(rq2->lock);
  1461. }
  1462. /*
  1463. * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
  1464. */
  1465. static void double_lock_balance(runqueue_t *this_rq, runqueue_t *busiest)
  1466. __releases(this_rq->lock)
  1467. __acquires(busiest->lock)
  1468. __acquires(this_rq->lock)
  1469. {
  1470. if (unlikely(!spin_trylock(&busiest->lock))) {
  1471. if (busiest < this_rq) {
  1472. spin_unlock(&this_rq->lock);
  1473. spin_lock(&busiest->lock);
  1474. spin_lock(&this_rq->lock);
  1475. } else
  1476. spin_lock(&busiest->lock);
  1477. }
  1478. }
  1479. /*
  1480. * If dest_cpu is allowed for this process, migrate the task to it.
  1481. * This is accomplished by forcing the cpu_allowed mask to only
  1482. * allow dest_cpu, which will force the cpu onto dest_cpu. Then
  1483. * the cpu_allowed mask is restored.
  1484. */
  1485. static void sched_migrate_task(task_t *p, int dest_cpu)
  1486. {
  1487. migration_req_t req;
  1488. runqueue_t *rq;
  1489. unsigned long flags;
  1490. rq = task_rq_lock(p, &flags);
  1491. if (!cpu_isset(dest_cpu, p->cpus_allowed)
  1492. || unlikely(cpu_is_offline(dest_cpu)))
  1493. goto out;
  1494. /* force the process onto the specified CPU */
  1495. if (migrate_task(p, dest_cpu, &req)) {
  1496. /* Need to wait for migration thread (might exit: take ref). */
  1497. struct task_struct *mt = rq->migration_thread;
  1498. get_task_struct(mt);
  1499. task_rq_unlock(rq, &flags);
  1500. wake_up_process(mt);
  1501. put_task_struct(mt);
  1502. wait_for_completion(&req.done);
  1503. return;
  1504. }
  1505. out:
  1506. task_rq_unlock(rq, &flags);
  1507. }
  1508. /*
  1509. * sched_exec - execve() is a valuable balancing opportunity, because at
  1510. * this point the task has the smallest effective memory and cache footprint.
  1511. */
  1512. void sched_exec(void)
  1513. {
  1514. int new_cpu, this_cpu = get_cpu();
  1515. new_cpu = sched_balance_self(this_cpu, SD_BALANCE_EXEC);
  1516. put_cpu();
  1517. if (new_cpu != this_cpu)
  1518. sched_migrate_task(current, new_cpu);
  1519. }
  1520. /*
  1521. * pull_task - move a task from a remote runqueue to the local runqueue.
  1522. * Both runqueues must be locked.
  1523. */
  1524. static inline
  1525. void pull_task(runqueue_t *src_rq, prio_array_t *src_array, task_t *p,
  1526. runqueue_t *this_rq, prio_array_t *this_array, int this_cpu)
  1527. {
  1528. dequeue_task(p, src_array);
  1529. src_rq->nr_running--;
  1530. set_task_cpu(p, this_cpu);
  1531. this_rq->nr_running++;
  1532. enqueue_task(p, this_array);
  1533. p->timestamp = (p->timestamp - src_rq->timestamp_last_tick)
  1534. + this_rq->timestamp_last_tick;
  1535. /*
  1536. * Note that idle threads have a prio of MAX_PRIO, for this test
  1537. * to be always true for them.
  1538. */
  1539. if (TASK_PREEMPTS_CURR(p, this_rq))
  1540. resched_task(this_rq->curr);
  1541. }
  1542. /*
  1543. * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
  1544. */
  1545. static inline
  1546. int can_migrate_task(task_t *p, runqueue_t *rq, int this_cpu,
  1547. struct sched_domain *sd, enum idle_type idle, int *all_pinned)
  1548. {
  1549. /*
  1550. * We do not migrate tasks that are:
  1551. * 1) running (obviously), or
  1552. * 2) cannot be migrated to this CPU due to cpus_allowed, or
  1553. * 3) are cache-hot on their current CPU.
  1554. */
  1555. if (!cpu_isset(this_cpu, p->cpus_allowed))
  1556. return 0;
  1557. *all_pinned = 0;
  1558. if (task_running(rq, p))
  1559. return 0;
  1560. /*
  1561. * Aggressive migration if:
  1562. * 1) task is cache cold, or
  1563. * 2) too many balance attempts have failed.
  1564. */
  1565. if (sd->nr_balance_failed > sd->cache_nice_tries)
  1566. return 1;
  1567. if (task_hot(p, rq->timestamp_last_tick, sd))
  1568. return 0;
  1569. return 1;
  1570. }
  1571. /*
  1572. * move_tasks tries to move up to max_nr_move tasks from busiest to this_rq,
  1573. * as part of a balancing operation within "domain". Returns the number of
  1574. * tasks moved.
  1575. *
  1576. * Called with both runqueues locked.
  1577. */
  1578. static int move_tasks(runqueue_t *this_rq, int this_cpu, runqueue_t *busiest,
  1579. unsigned long max_nr_move, struct sched_domain *sd,
  1580. enum idle_type idle, int *all_pinned)
  1581. {
  1582. prio_array_t *array, *dst_array;
  1583. struct list_head *head, *curr;
  1584. int idx, pulled = 0, pinned = 0;
  1585. task_t *tmp;
  1586. if (max_nr_move == 0)
  1587. goto out;
  1588. pinned = 1;
  1589. /*
  1590. * We first consider expired tasks. Those will likely not be
  1591. * executed in the near future, and they are most likely to
  1592. * be cache-cold, thus switching CPUs has the least effect
  1593. * on them.
  1594. */
  1595. if (busiest->expired->nr_active) {
  1596. array = busiest->expired;
  1597. dst_array = this_rq->expired;
  1598. } else {
  1599. array = busiest->active;
  1600. dst_array = this_rq->active;
  1601. }
  1602. new_array:
  1603. /* Start searching at priority 0: */
  1604. idx = 0;
  1605. skip_bitmap:
  1606. if (!idx)
  1607. idx = sched_find_first_bit(array->bitmap);
  1608. else
  1609. idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
  1610. if (idx >= MAX_PRIO) {
  1611. if (array == busiest->expired && busiest->active->nr_active) {
  1612. array = busiest->active;
  1613. dst_array = this_rq->active;
  1614. goto new_array;
  1615. }
  1616. goto out;
  1617. }
  1618. head = array->queue + idx;
  1619. curr = head->prev;
  1620. skip_queue:
  1621. tmp = list_entry(curr, task_t, run_list);
  1622. curr = curr->prev;
  1623. if (!can_migrate_task(tmp, busiest, this_cpu, sd, idle, &pinned)) {
  1624. if (curr != head)
  1625. goto skip_queue;
  1626. idx++;
  1627. goto skip_bitmap;
  1628. }
  1629. #ifdef CONFIG_SCHEDSTATS
  1630. if (task_hot(tmp, busiest->timestamp_last_tick, sd))
  1631. schedstat_inc(sd, lb_hot_gained[idle]);
  1632. #endif
  1633. pull_task(busiest, array, tmp, this_rq, dst_array, this_cpu);
  1634. pulled++;
  1635. /* We only want to steal up to the prescribed number of tasks. */
  1636. if (pulled < max_nr_move) {
  1637. if (curr != head)
  1638. goto skip_queue;
  1639. idx++;
  1640. goto skip_bitmap;
  1641. }
  1642. out:
  1643. /*
  1644. * Right now, this is the only place pull_task() is called,
  1645. * so we can safely collect pull_task() stats here rather than
  1646. * inside pull_task().
  1647. */
  1648. schedstat_add(sd, lb_gained[idle], pulled);
  1649. if (all_pinned)
  1650. *all_pinned = pinned;
  1651. return pulled;
  1652. }
  1653. /*
  1654. * find_busiest_group finds and returns the busiest CPU group within the
  1655. * domain. It calculates and returns the number of tasks which should be
  1656. * moved to restore balance via the imbalance parameter.
  1657. */
  1658. static struct sched_group *
  1659. find_busiest_group(struct sched_domain *sd, int this_cpu,
  1660. unsigned long *imbalance, enum idle_type idle)
  1661. {
  1662. struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
  1663. unsigned long max_load, avg_load, total_load, this_load, total_pwr;
  1664. int load_idx;
  1665. max_load = this_load = total_load = total_pwr = 0;
  1666. if (idle == NOT_IDLE)
  1667. load_idx = sd->busy_idx;
  1668. else if (idle == NEWLY_IDLE)
  1669. load_idx = sd->newidle_idx;
  1670. else
  1671. load_idx = sd->idle_idx;
  1672. do {
  1673. unsigned long load;
  1674. int local_group;
  1675. int i;
  1676. local_group = cpu_isset(this_cpu, group->cpumask);
  1677. /* Tally up the load of all CPUs in the group */
  1678. avg_load = 0;
  1679. for_each_cpu_mask(i, group->cpumask) {
  1680. /* Bias balancing toward cpus of our domain */
  1681. if (local_group)
  1682. load = target_load(i, load_idx);
  1683. else
  1684. load = source_load(i, load_idx);
  1685. avg_load += load;
  1686. }
  1687. total_load += avg_load;
  1688. total_pwr += group->cpu_power;
  1689. /* Adjust by relative CPU power of the group */
  1690. avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
  1691. if (local_group) {
  1692. this_load = avg_load;
  1693. this = group;
  1694. } else if (avg_load > max_load) {
  1695. max_load = avg_load;
  1696. busiest = group;
  1697. }
  1698. group = group->next;
  1699. } while (group != sd->groups);
  1700. if (!busiest || this_load >= max_load)
  1701. goto out_balanced;
  1702. avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
  1703. if (this_load >= avg_load ||
  1704. 100*max_load <= sd->imbalance_pct*this_load)
  1705. goto out_balanced;
  1706. /*
  1707. * We're trying to get all the cpus to the average_load, so we don't
  1708. * want to push ourselves above the average load, nor do we wish to
  1709. * reduce the max loaded cpu below the average load, as either of these
  1710. * actions would just result in more rebalancing later, and ping-pong
  1711. * tasks around. Thus we look for the minimum possible imbalance.
  1712. * Negative imbalances (*we* are more loaded than anyone else) will
  1713. * be counted as no imbalance for these purposes -- we can't fix that
  1714. * by pulling tasks to us. Be careful of negative numbers as they'll
  1715. * appear as very large values with unsigned longs.
  1716. */
  1717. /* How much load to actually move to equalise the imbalance */
  1718. *imbalance = min((max_load - avg_load) * busiest->cpu_power,
  1719. (avg_load - this_load) * this->cpu_power)
  1720. / SCHED_LOAD_SCALE;
  1721. if (*imbalance < SCHED_LOAD_SCALE) {
  1722. unsigned long pwr_now = 0, pwr_move = 0;
  1723. unsigned long tmp;
  1724. if (max_load - this_load >= SCHED_LOAD_SCALE*2) {
  1725. *imbalance = 1;
  1726. return busiest;
  1727. }
  1728. /*
  1729. * OK, we don't have enough imbalance to justify moving tasks,
  1730. * however we may be able to increase total CPU power used by
  1731. * moving them.
  1732. */
  1733. pwr_now += busiest->cpu_power*min(SCHED_LOAD_SCALE, max_load);
  1734. pwr_now += this->cpu_power*min(SCHED_LOAD_SCALE, this_load);
  1735. pwr_now /= SCHED_LOAD_SCALE;
  1736. /* Amount of load we'd subtract */
  1737. tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/busiest->cpu_power;
  1738. if (max_load > tmp)
  1739. pwr_move += busiest->cpu_power*min(SCHED_LOAD_SCALE,
  1740. max_load - tmp);
  1741. /* Amount of load we'd add */
  1742. if (max_load*busiest->cpu_power <
  1743. SCHED_LOAD_SCALE*SCHED_LOAD_SCALE)
  1744. tmp = max_load*busiest->cpu_power/this->cpu_power;
  1745. else
  1746. tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/this->cpu_power;
  1747. pwr_move += this->cpu_power*min(SCHED_LOAD_SCALE, this_load + tmp);
  1748. pwr_move /= SCHED_LOAD_SCALE;
  1749. /* Move if we gain throughput */
  1750. if (pwr_move <= pwr_now)
  1751. goto out_balanced;
  1752. *imbalance = 1;
  1753. return busiest;
  1754. }
  1755. /* Get rid of the scaling factor, rounding down as we divide */
  1756. *imbalance = *imbalance / SCHED_LOAD_SCALE;
  1757. return busiest;
  1758. out_balanced:
  1759. *imbalance = 0;
  1760. return NULL;
  1761. }
  1762. /*
  1763. * find_busiest_queue - find the busiest runqueue among the cpus in group.
  1764. */
  1765. static runqueue_t *find_busiest_queue(struct sched_group *group)
  1766. {
  1767. unsigned long load, max_load = 0;
  1768. runqueue_t *busiest = NULL;
  1769. int i;
  1770. for_each_cpu_mask(i, group->cpumask) {
  1771. load = source_load(i, 0);
  1772. if (load > max_load) {
  1773. max_load = load;
  1774. busiest = cpu_rq(i);
  1775. }
  1776. }
  1777. return busiest;
  1778. }
  1779. /*
  1780. * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
  1781. * so long as it is large enough.
  1782. */
  1783. #define MAX_PINNED_INTERVAL 512
  1784. /*
  1785. * Check this_cpu to ensure it is balanced within domain. Attempt to move
  1786. * tasks if there is an imbalance.
  1787. *
  1788. * Called with this_rq unlocked.
  1789. */
  1790. static int load_balance(int this_cpu, runqueue_t *this_rq,
  1791. struct sched_domain *sd, enum idle_type idle)
  1792. {
  1793. struct sched_group *group;
  1794. runqueue_t *busiest;
  1795. unsigned long imbalance;
  1796. int nr_moved, all_pinned = 0;
  1797. int active_balance = 0;
  1798. spin_lock(&this_rq->lock);
  1799. schedstat_inc(sd, lb_cnt[idle]);
  1800. group = find_busiest_group(sd, this_cpu, &imbalance, idle);
  1801. if (!group) {
  1802. schedstat_inc(sd, lb_nobusyg[idle]);
  1803. goto out_balanced;
  1804. }
  1805. busiest = find_busiest_queue(group);
  1806. if (!busiest) {
  1807. schedstat_inc(sd, lb_nobusyq[idle]);
  1808. goto out_balanced;
  1809. }
  1810. BUG_ON(busiest == this_rq);
  1811. schedstat_add(sd, lb_imbalance[idle], imbalance);
  1812. nr_moved = 0;
  1813. if (busiest->nr_running > 1) {
  1814. /*
  1815. * Attempt to move tasks. If find_busiest_group has found
  1816. * an imbalance but busiest->nr_running <= 1, the group is
  1817. * still unbalanced. nr_moved simply stays zero, so it is
  1818. * correctly treated as an imbalance.
  1819. */
  1820. double_lock_balance(this_rq, busiest);
  1821. nr_moved = move_tasks(this_rq, this_cpu, busiest,
  1822. imbalance, sd, idle,
  1823. &all_pinned);
  1824. spin_unlock(&busiest->lock);
  1825. /* All tasks on this runqueue were pinned by CPU affinity */
  1826. if (unlikely(all_pinned))
  1827. goto out_balanced;
  1828. }
  1829. spin_unlock(&this_rq->lock);
  1830. if (!nr_moved) {
  1831. schedstat_inc(sd, lb_failed[idle]);
  1832. sd->nr_balance_failed++;
  1833. if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
  1834. spin_lock(&busiest->lock);
  1835. if (!busiest->active_balance) {
  1836. busiest->active_balance = 1;
  1837. busiest->push_cpu = this_cpu;
  1838. active_balance = 1;
  1839. }
  1840. spin_unlock(&busiest->lock);
  1841. if (active_balance)
  1842. wake_up_process(busiest->migration_thread);
  1843. /*
  1844. * We've kicked active balancing, reset the failure
  1845. * counter.
  1846. */
  1847. sd->nr_balance_failed = sd->cache_nice_tries+1;
  1848. }
  1849. } else
  1850. sd->nr_balance_failed = 0;
  1851. if (likely(!active_balance)) {
  1852. /* We were unbalanced, so reset the balancing interval */
  1853. sd->balance_interval = sd->min_interval;
  1854. } else {
  1855. /*
  1856. * If we've begun active balancing, start to back off. This
  1857. * case may not be covered by the all_pinned logic if there
  1858. * is only 1 task on the busy runqueue (because we don't call
  1859. * move_tasks).
  1860. */
  1861. if (sd->balance_interval < sd->max_interval)
  1862. sd->balance_interval *= 2;
  1863. }
  1864. return nr_moved;
  1865. out_balanced:
  1866. spin_unlock(&this_rq->lock);
  1867. schedstat_inc(sd, lb_balanced[idle]);
  1868. sd->nr_balance_failed = 0;
  1869. /* tune up the balancing interval */
  1870. if ((all_pinned && sd->balance_interval < MAX_PINNED_INTERVAL) ||
  1871. (sd->balance_interval < sd->max_interval))
  1872. sd->balance_interval *= 2;
  1873. return 0;
  1874. }
  1875. /*
  1876. * Check this_cpu to ensure it is balanced within domain. Attempt to move
  1877. * tasks if there is an imbalance.
  1878. *
  1879. * Called from schedule when this_rq is about to become idle (NEWLY_IDLE).
  1880. * this_rq is locked.
  1881. */
  1882. static int load_balance_newidle(int this_cpu, runqueue_t *this_rq,
  1883. struct sched_domain *sd)
  1884. {
  1885. struct sched_group *group;
  1886. runqueue_t *busiest = NULL;
  1887. unsigned long imbalance;
  1888. int nr_moved = 0;
  1889. schedstat_inc(sd, lb_cnt[NEWLY_IDLE]);
  1890. group = find_busiest_group(sd, this_cpu, &imbalance, NEWLY_IDLE);
  1891. if (!group) {
  1892. schedstat_inc(sd, lb_nobusyg[NEWLY_IDLE]);
  1893. goto out_balanced;
  1894. }
  1895. busiest = find_busiest_queue(group);
  1896. if (!busiest) {
  1897. schedstat_inc(sd, lb_nobusyq[NEWLY_IDLE]);
  1898. goto out_balanced;
  1899. }
  1900. BUG_ON(busiest == this_rq);
  1901. /* Attempt to move tasks */
  1902. double_lock_balance(this_rq, busiest);
  1903. schedstat_add(sd, lb_imbalance[NEWLY_IDLE], imbalance);
  1904. nr_moved = move_tasks(this_rq, this_cpu, busiest,
  1905. imbalance, sd, NEWLY_IDLE, NULL);
  1906. if (!nr_moved)
  1907. schedstat_inc(sd, lb_failed[NEWLY_IDLE]);
  1908. else
  1909. sd->nr_balance_failed = 0;
  1910. spin_unlock(&busiest->lock);
  1911. return nr_moved;
  1912. out_balanced:
  1913. schedstat_inc(sd, lb_balanced[NEWLY_IDLE]);
  1914. sd->nr_balance_failed = 0;
  1915. return 0;
  1916. }
  1917. /*
  1918. * idle_balance is called by schedule() if this_cpu is about to become
  1919. * idle. Attempts to pull tasks from other CPUs.
  1920. */
  1921. static inline void idle_balance(int this_cpu, runqueue_t *this_rq)
  1922. {
  1923. struct sched_domain *sd;
  1924. for_each_domain(this_cpu, sd) {
  1925. if (sd->flags & SD_BALANCE_NEWIDLE) {
  1926. if (load_balance_newidle(this_cpu, this_rq, sd)) {
  1927. /* We've pulled tasks over so stop searching */
  1928. break;
  1929. }
  1930. }
  1931. }
  1932. }
  1933. /*
  1934. * active_load_balance is run by migration threads. It pushes running tasks
  1935. * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
  1936. * running on each physical CPU where possible, and avoids physical /
  1937. * logical imbalances.
  1938. *
  1939. * Called with busiest_rq locked.
  1940. */
  1941. static void active_load_balance(runqueue_t *busiest_rq, int busiest_cpu)
  1942. {
  1943. struct sched_domain *sd;
  1944. runqueue_t *target_rq;
  1945. int target_cpu = busiest_rq->push_cpu;
  1946. if (busiest_rq->nr_running <= 1)
  1947. /* no task to move */
  1948. return;
  1949. target_rq = cpu_rq(target_cpu);
  1950. /*
  1951. * This condition is "impossible", if it occurs
  1952. * we need to fix it. Originally reported by
  1953. * Bjorn Helgaas on a 128-cpu setup.
  1954. */
  1955. BUG_ON(busiest_rq == target_rq);
  1956. /* move a task from busiest_rq to target_rq */
  1957. double_lock_balance(busiest_rq, target_rq);
  1958. /* Search for an sd spanning us and the target CPU. */
  1959. for_each_domain(target_cpu, sd)
  1960. if ((sd->flags & SD_LOAD_BALANCE) &&
  1961. cpu_isset(busiest_cpu, sd->span))
  1962. break;
  1963. if (unlikely(sd == NULL))
  1964. goto out;
  1965. schedstat_inc(sd, alb_cnt);
  1966. if (move_tasks(target_rq, target_cpu, busiest_rq, 1, sd, SCHED_IDLE, NULL))
  1967. schedstat_inc(sd, alb_pushed);
  1968. else
  1969. schedstat_inc(sd, alb_failed);
  1970. out:
  1971. spin_unlock(&target_rq->lock);
  1972. }
  1973. /*
  1974. * rebalance_tick will get called every timer tick, on every CPU.
  1975. *
  1976. * It checks each scheduling domain to see if it is due to be balanced,
  1977. * and initiates a balancing operation if so.
  1978. *
  1979. * Balancing parameters are set up in arch_init_sched_domains.
  1980. */
  1981. /* Don't have all balancing operations going off at once */
  1982. #define CPU_OFFSET(cpu) (HZ * cpu / NR_CPUS)
  1983. static void rebalance_tick(int this_cpu, runqueue_t *this_rq,
  1984. enum idle_type idle)
  1985. {
  1986. unsigned long old_load, this_load;
  1987. unsigned long j = jiffies + CPU_OFFSET(this_cpu);
  1988. struct sched_domain *sd;
  1989. int i;
  1990. this_load = this_rq->nr_running * SCHED_LOAD_SCALE;
  1991. /* Update our load */
  1992. for (i = 0; i < 3; i++) {
  1993. unsigned long new_load = this_load;
  1994. int scale = 1 << i;
  1995. old_load = this_rq->cpu_load[i];
  1996. /*
  1997. * Round up the averaging division if load is increasing. This
  1998. * prevents us from getting stuck on 9 if the load is 10, for
  1999. * example.
  2000. */
  2001. if (new_load > old_load)
  2002. new_load += scale-1;
  2003. this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) / scale;
  2004. }
  2005. for_each_domain(this_cpu, sd) {
  2006. unsigned long interval;
  2007. if (!(sd->flags & SD_LOAD_BALANCE))
  2008. continue;
  2009. interval = sd->balance_interval;
  2010. if (idle != SCHED_IDLE)
  2011. interval *= sd->busy_factor;
  2012. /* scale ms to jiffies */
  2013. interval = msecs_to_jiffies(interval);
  2014. if (unlikely(!interval))
  2015. interval = 1;
  2016. if (j - sd->last_balance >= interval) {
  2017. if (load_balance(this_cpu, this_rq, sd, idle)) {
  2018. /* We've pulled tasks over so no longer idle */
  2019. idle = NOT_IDLE;
  2020. }
  2021. sd->last_balance += interval;
  2022. }
  2023. }
  2024. }
  2025. #else
  2026. /*
  2027. * on UP we do not need to balance between CPUs:
  2028. */
  2029. static inline void rebalance_tick(int cpu, runqueue_t *rq, enum idle_type idle)
  2030. {
  2031. }
  2032. static inline void idle_balance(int cpu, runqueue_t *rq)
  2033. {
  2034. }
  2035. #endif
  2036. static inline int wake_priority_sleeper(runqueue_t *rq)
  2037. {
  2038. int ret = 0;
  2039. #ifdef CONFIG_SCHED_SMT
  2040. spin_lock(&rq->lock);
  2041. /*
  2042. * If an SMT sibling task has been put to sleep for priority
  2043. * reasons reschedule the idle task to see if it can now run.
  2044. */
  2045. if (rq->nr_running) {
  2046. resched_task(rq->idle);
  2047. ret = 1;
  2048. }
  2049. spin_unlock(&rq->lock);
  2050. #endif
  2051. return ret;
  2052. }
  2053. DEFINE_PER_CPU(struct kernel_stat, kstat);
  2054. EXPORT_PER_CPU_SYMBOL(kstat);
  2055. /*
  2056. * This is called on clock ticks and on context switches.
  2057. * Bank in p->sched_time the ns elapsed since the last tick or switch.
  2058. */
  2059. static inline void update_cpu_clock(task_t *p, runqueue_t *rq,
  2060. unsigned long long now)
  2061. {
  2062. unsigned long long last = max(p->timestamp, rq->timestamp_last_tick);
  2063. p->sched_time += now - last;
  2064. }
  2065. /*
  2066. * Return current->sched_time plus any more ns on the sched_clock
  2067. * that have not yet been banked.
  2068. */
  2069. unsigned long long current_sched_time(const task_t *tsk)
  2070. {
  2071. unsigned long long ns;
  2072. unsigned long flags;
  2073. local_irq_save(flags);
  2074. ns = max(tsk->timestamp, task_rq(tsk)->timestamp_last_tick);
  2075. ns = tsk->sched_time + (sched_clock() - ns);
  2076. local_irq_restore(flags);
  2077. return ns;
  2078. }
  2079. /*
  2080. * We place interactive tasks back into the active array, if possible.
  2081. *
  2082. * To guarantee that this does not starve expired tasks we ignore the
  2083. * interactivity of a task if the first expired task had to wait more
  2084. * than a 'reasonable' amount of time. This deadline timeout is
  2085. * load-dependent, as the frequency of array switched decreases with
  2086. * increasing number of running tasks. We also ignore the interactivity
  2087. * if a better static_prio task has expired:
  2088. */
  2089. #define EXPIRED_STARVING(rq) \
  2090. ((STARVATION_LIMIT && ((rq)->expired_timestamp && \
  2091. (jiffies - (rq)->expired_timestamp >= \
  2092. STARVATION_LIMIT * ((rq)->nr_running) + 1))) || \
  2093. ((rq)->curr->static_prio > (rq)->best_expired_prio))
  2094. /*
  2095. * Account user cpu time to a process.
  2096. * @p: the process that the cpu time gets accounted to
  2097. * @hardirq_offset: the offset to subtract from hardirq_count()
  2098. * @cputime: the cpu time spent in user space since the last update
  2099. */
  2100. void account_user_time(struct task_struct *p, cputime_t cputime)
  2101. {
  2102. struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
  2103. cputime64_t tmp;
  2104. p->utime = cputime_add(p->utime, cputime);
  2105. /* Add user time to cpustat. */
  2106. tmp = cputime_to_cputime64(cputime);
  2107. if (TASK_NICE(p) > 0)
  2108. cpustat->nice = cputime64_add(cpustat->nice, tmp);
  2109. else
  2110. cpustat->user = cputime64_add(cpustat->user, tmp);
  2111. }
  2112. /*
  2113. * Account system cpu time to a process.
  2114. * @p: the process that the cpu time gets accounted to
  2115. * @hardirq_offset: the offset to subtract from hardirq_count()
  2116. * @cputime: the cpu time spent in kernel space since the last update
  2117. */
  2118. void account_system_time(struct task_struct *p, int hardirq_offset,
  2119. cputime_t cputime)
  2120. {
  2121. struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
  2122. runqueue_t *rq = this_rq();
  2123. cputime64_t tmp;
  2124. p->stime = cputime_add(p->stime, cputime);
  2125. /* Add system time to cpustat. */
  2126. tmp = cputime_to_cputime64(cputime);
  2127. if (hardirq_count() - hardirq_offset)
  2128. cpustat->irq = cputime64_add(cpustat->irq, tmp);
  2129. else if (softirq_count())
  2130. cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
  2131. else if (p != rq->idle)
  2132. cpustat->system = cputime64_add(cpustat->system, tmp);
  2133. else if (atomic_read(&rq->nr_iowait) > 0)
  2134. cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
  2135. else
  2136. cpustat->idle = cputime64_add(cpustat->idle, tmp);
  2137. /* Account for system time used */
  2138. acct_update_integrals(p);
  2139. /* Update rss highwater mark */
  2140. update_mem_hiwater(p);
  2141. }
  2142. /*
  2143. * Account for involuntary wait time.
  2144. * @p: the process from which the cpu time has been stolen
  2145. * @steal: the cpu time spent in involuntary wait
  2146. */
  2147. void account_steal_time(struct task_struct *p, cputime_t steal)
  2148. {
  2149. struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
  2150. cputime64_t tmp = cputime_to_cputime64(steal);
  2151. runqueue_t *rq = this_rq();
  2152. if (p == rq->idle) {
  2153. p->stime = cputime_add(p->stime, steal);
  2154. if (atomic_read(&rq->nr_iowait) > 0)
  2155. cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
  2156. else
  2157. cpustat->idle = cputime64_add(cpustat->idle, tmp);
  2158. } else
  2159. cpustat->steal = cputime64_add(cpustat->steal, tmp);
  2160. }
  2161. /*
  2162. * This function gets called by the timer code, with HZ frequency.
  2163. * We call it with interrupts disabled.
  2164. *
  2165. * It also gets called by the fork code, when changing the parent's
  2166. * timeslices.
  2167. */
  2168. void scheduler_tick(void)
  2169. {
  2170. int cpu = smp_processor_id();
  2171. runqueue_t *rq = this_rq();
  2172. task_t *p = current;
  2173. unsigned long long now = sched_clock();
  2174. update_cpu_clock(p, rq, now);
  2175. rq->timestamp_last_tick = now;
  2176. if (p == rq->idle) {
  2177. if (wake_priority_sleeper(rq))
  2178. goto out;
  2179. rebalance_tick(cpu, rq, SCHED_IDLE);
  2180. return;
  2181. }
  2182. /* Task might have expired already, but not scheduled off yet */
  2183. if (p->array != rq->active) {
  2184. set_tsk_need_resched(p);
  2185. goto out;
  2186. }
  2187. spin_lock(&rq->lock);
  2188. /*
  2189. * The task was running during this tick - update the
  2190. * time slice counter. Note: we do not update a thread's
  2191. * priority until it either goes to sleep or uses up its
  2192. * timeslice. This makes it possible for interactive tasks
  2193. * to use up their timeslices at their highest priority levels.
  2194. */
  2195. if (rt_task(p)) {
  2196. /*
  2197. * RR tasks need a special form of timeslice management.
  2198. * FIFO tasks have no timeslices.
  2199. */
  2200. if ((p->policy == SCHED_RR) && !--p->time_slice) {
  2201. p->time_slice = task_timeslice(p);
  2202. p->first_time_slice = 0;
  2203. set_tsk_need_resched(p);
  2204. /* put it at the end of the queue: */
  2205. requeue_task(p, rq->active);
  2206. }
  2207. goto out_unlock;
  2208. }
  2209. if (!--p->time_slice) {
  2210. dequeue_task(p, rq->active);
  2211. set_tsk_need_resched(p);
  2212. p->prio = effective_prio(p);
  2213. p->time_slice = task_timeslice(p);
  2214. p->first_time_slice = 0;
  2215. if (!rq->expired_timestamp)
  2216. rq->expired_timestamp = jiffies;
  2217. if (!TASK_INTERACTIVE(p) || EXPIRED_STARVING(rq)) {
  2218. enqueue_task(p, rq->expired);
  2219. if (p->static_prio < rq->best_expired_prio)
  2220. rq->best_expired_prio = p->static_prio;
  2221. } else
  2222. enqueue_task(p, rq->active);
  2223. } else {
  2224. /*
  2225. * Prevent a too long timeslice allowing a task to monopolize
  2226. * the CPU. We do this by splitting up the timeslice into
  2227. * smaller pieces.
  2228. *
  2229. * Note: this does not mean the task's timeslices expire or
  2230. * get lost in any way, they just might be preempted by
  2231. * another task of equal priority. (one with higher
  2232. * priority would have preempted this task already.) We
  2233. * requeue this task to the end of the list on this priority
  2234. * level, which is in essence a round-robin of tasks with
  2235. * equal priority.
  2236. *
  2237. * This only applies to tasks in the interactive
  2238. * delta range with at least TIMESLICE_GRANULARITY to requeue.
  2239. */
  2240. if (TASK_INTERACTIVE(p) && !((task_timeslice(p) -
  2241. p->time_slice) % TIMESLICE_GRANULARITY(p)) &&
  2242. (p->time_slice >= TIMESLICE_GRANULARITY(p)) &&
  2243. (p->array == rq->active)) {
  2244. requeue_task(p, rq->active);
  2245. set_tsk_need_resched(p);
  2246. }
  2247. }
  2248. out_unlock:
  2249. spin_unlock(&rq->lock);
  2250. out:
  2251. rebalance_tick(cpu, rq, NOT_IDLE);
  2252. }
  2253. #ifdef CONFIG_SCHED_SMT
  2254. static inline void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
  2255. {
  2256. struct sched_domain *tmp, *sd = NULL;
  2257. cpumask_t sibling_map;
  2258. int i;
  2259. for_each_domain(this_cpu, tmp)
  2260. if (tmp->flags & SD_SHARE_CPUPOWER)
  2261. sd = tmp;
  2262. if (!sd)
  2263. return;
  2264. /*
  2265. * Unlock the current runqueue because we have to lock in
  2266. * CPU order to avoid deadlocks. Caller knows that we might
  2267. * unlock. We keep IRQs disabled.
  2268. */
  2269. spin_unlock(&this_rq->lock);
  2270. sibling_map = sd->span;
  2271. for_each_cpu_mask(i, sibling_map)
  2272. spin_lock(&cpu_rq(i)->lock);
  2273. /*
  2274. * We clear this CPU from the mask. This both simplifies the
  2275. * inner loop and keps this_rq locked when we exit:
  2276. */
  2277. cpu_clear(this_cpu, sibling_map);
  2278. for_each_cpu_mask(i, sibling_map) {
  2279. runqueue_t *smt_rq = cpu_rq(i);
  2280. /*
  2281. * If an SMT sibling task is sleeping due to priority
  2282. * reasons wake it up now.
  2283. */
  2284. if (smt_rq->curr == smt_rq->idle && smt_rq->nr_running)
  2285. resched_task(smt_rq->idle);
  2286. }
  2287. for_each_cpu_mask(i, sibling_map)
  2288. spin_unlock(&cpu_rq(i)->lock);
  2289. /*
  2290. * We exit with this_cpu's rq still held and IRQs
  2291. * still disabled:
  2292. */
  2293. }
  2294. static inline int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
  2295. {
  2296. struct sched_domain *tmp, *sd = NULL;
  2297. cpumask_t sibling_map;
  2298. prio_array_t *array;
  2299. int ret = 0, i;
  2300. task_t *p;
  2301. for_each_domain(this_cpu, tmp)
  2302. if (tmp->flags & SD_SHARE_CPUPOWER)
  2303. sd = tmp;
  2304. if (!sd)
  2305. return 0;
  2306. /*
  2307. * The same locking rules and details apply as for
  2308. * wake_sleeping_dependent():
  2309. */
  2310. spin_unlock(&this_rq->lock);
  2311. sibling_map = sd->span;
  2312. for_each_cpu_mask(i, sibling_map)
  2313. spin_lock(&cpu_rq(i)->lock);
  2314. cpu_clear(this_cpu, sibling_map);
  2315. /*
  2316. * Establish next task to be run - it might have gone away because
  2317. * we released the runqueue lock above:
  2318. */
  2319. if (!this_rq->nr_running)
  2320. goto out_unlock;
  2321. array = this_rq->active;
  2322. if (!array->nr_active)
  2323. array = this_rq->expired;
  2324. BUG_ON(!array->nr_active);
  2325. p = list_entry(array->queue[sched_find_first_bit(array->bitmap)].next,
  2326. task_t, run_list);
  2327. for_each_cpu_mask(i, sibling_map) {
  2328. runqueue_t *smt_rq = cpu_rq(i);
  2329. task_t *smt_curr = smt_rq->curr;
  2330. /*
  2331. * If a user task with lower static priority than the
  2332. * running task on the SMT sibling is trying to schedule,
  2333. * delay it till there is proportionately less timeslice
  2334. * left of the sibling task to prevent a lower priority
  2335. * task from using an unfair proportion of the
  2336. * physical cpu's resources. -ck
  2337. */
  2338. if (((smt_curr->time_slice * (100 - sd->per_cpu_gain) / 100) >
  2339. task_timeslice(p) || rt_task(smt_curr)) &&
  2340. p->mm && smt_curr->mm && !rt_task(p))
  2341. ret = 1;
  2342. /*
  2343. * Reschedule a lower priority task on the SMT sibling,
  2344. * or wake it up if it has been put to sleep for priority
  2345. * reasons.
  2346. */
  2347. if ((((p->time_slice * (100 - sd->per_cpu_gain) / 100) >
  2348. task_timeslice(smt_curr) || rt_task(p)) &&
  2349. smt_curr->mm && p->mm && !rt_task(smt_curr)) ||
  2350. (smt_curr == smt_rq->idle && smt_rq->nr_running))
  2351. resched_task(smt_curr);
  2352. }
  2353. out_unlock:
  2354. for_each_cpu_mask(i, sibling_map)
  2355. spin_unlock(&cpu_rq(i)->lock);
  2356. return ret;
  2357. }
  2358. #else
  2359. static inline void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
  2360. {
  2361. }
  2362. static inline int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
  2363. {
  2364. return 0;
  2365. }
  2366. #endif
  2367. #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
  2368. void fastcall add_preempt_count(int val)
  2369. {
  2370. /*
  2371. * Underflow?
  2372. */
  2373. BUG_ON((preempt_count() < 0));
  2374. preempt_count() += val;
  2375. /*
  2376. * Spinlock count overflowing soon?
  2377. */
  2378. BUG_ON((preempt_count() & PREEMPT_MASK) >= PREEMPT_MASK-10);
  2379. }
  2380. EXPORT_SYMBOL(add_preempt_count);
  2381. void fastcall sub_preempt_count(int val)
  2382. {
  2383. /*
  2384. * Underflow?
  2385. */
  2386. BUG_ON(val > preempt_count());
  2387. /*
  2388. * Is the spinlock portion underflowing?
  2389. */
  2390. BUG_ON((val < PREEMPT_MASK) && !(preempt_count() & PREEMPT_MASK));
  2391. preempt_count() -= val;
  2392. }
  2393. EXPORT_SYMBOL(sub_preempt_count);
  2394. #endif
  2395. /*
  2396. * schedule() is the main scheduler function.
  2397. */
  2398. asmlinkage void __sched schedule(void)
  2399. {
  2400. long *switch_count;
  2401. task_t *prev, *next;
  2402. runqueue_t *rq;
  2403. prio_array_t *array;
  2404. struct list_head *queue;
  2405. unsigned long long now;
  2406. unsigned long run_time;
  2407. int cpu, idx, new_prio;
  2408. /*
  2409. * Test if we are atomic. Since do_exit() needs to call into
  2410. * schedule() atomically, we ignore that path for now.
  2411. * Otherwise, whine if we are scheduling when we should not be.
  2412. */
  2413. if (likely(!current->exit_state)) {
  2414. if (unlikely(in_atomic())) {
  2415. printk(KERN_ERR "scheduling while atomic: "
  2416. "%s/0x%08x/%d\n",
  2417. current->comm, preempt_count(), current->pid);
  2418. dump_stack();
  2419. }
  2420. }
  2421. profile_hit(SCHED_PROFILING, __builtin_return_address(0));
  2422. need_resched:
  2423. preempt_disable();
  2424. prev = current;
  2425. release_kernel_lock(prev);
  2426. need_resched_nonpreemptible:
  2427. rq = this_rq();
  2428. /*
  2429. * The idle thread is not allowed to schedule!
  2430. * Remove this check after it has been exercised a bit.
  2431. */
  2432. if (unlikely(prev == rq->idle) && prev->state != TASK_RUNNING) {
  2433. printk(KERN_ERR "bad: scheduling from the idle thread!\n");
  2434. dump_stack();
  2435. }
  2436. schedstat_inc(rq, sched_cnt);
  2437. now = sched_clock();
  2438. if (likely((long long)(now - prev->timestamp) < NS_MAX_SLEEP_AVG)) {
  2439. run_time = now - prev->timestamp;
  2440. if (unlikely((long long)(now - prev->timestamp) < 0))
  2441. run_time = 0;
  2442. } else
  2443. run_time = NS_MAX_SLEEP_AVG;
  2444. /*
  2445. * Tasks charged proportionately less run_time at high sleep_avg to
  2446. * delay them losing their interactive status
  2447. */
  2448. run_time /= (CURRENT_BONUS(prev) ? : 1);
  2449. spin_lock_irq(&rq->lock);
  2450. if (unlikely(prev->flags & PF_DEAD))
  2451. prev->state = EXIT_DEAD;
  2452. switch_count = &prev->nivcsw;
  2453. if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
  2454. switch_count = &prev->nvcsw;
  2455. if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
  2456. unlikely(signal_pending(prev))))
  2457. prev->state = TASK_RUNNING;
  2458. else {
  2459. if (prev->state == TASK_UNINTERRUPTIBLE)
  2460. rq->nr_uninterruptible++;
  2461. deactivate_task(prev, rq);
  2462. }
  2463. }
  2464. cpu = smp_processor_id();
  2465. if (unlikely(!rq->nr_running)) {
  2466. go_idle:
  2467. idle_balance(cpu, rq);
  2468. if (!rq->nr_running) {
  2469. next = rq->idle;
  2470. rq->expired_timestamp = 0;
  2471. wake_sleeping_dependent(cpu, rq);
  2472. /*
  2473. * wake_sleeping_dependent() might have released
  2474. * the runqueue, so break out if we got new
  2475. * tasks meanwhile:
  2476. */
  2477. if (!rq->nr_running)
  2478. goto switch_tasks;
  2479. }
  2480. } else {
  2481. if (dependent_sleeper(cpu, rq)) {
  2482. next = rq->idle;
  2483. goto switch_tasks;
  2484. }
  2485. /*
  2486. * dependent_sleeper() releases and reacquires the runqueue
  2487. * lock, hence go into the idle loop if the rq went
  2488. * empty meanwhile:
  2489. */
  2490. if (unlikely(!rq->nr_running))
  2491. goto go_idle;
  2492. }
  2493. array = rq->active;
  2494. if (unlikely(!array->nr_active)) {
  2495. /*
  2496. * Switch the active and expired arrays.
  2497. */
  2498. schedstat_inc(rq, sched_switch);
  2499. rq->active = rq->expired;
  2500. rq->expired = array;
  2501. array = rq->active;
  2502. rq->expired_timestamp = 0;
  2503. rq->best_expired_prio = MAX_PRIO;
  2504. }
  2505. idx = sched_find_first_bit(array->bitmap);
  2506. queue = array->queue + idx;
  2507. next = list_entry(queue->next, task_t, run_list);
  2508. if (!rt_task(next) && next->activated > 0) {
  2509. unsigned long long delta = now - next->timestamp;
  2510. if (unlikely((long long)(now - next->timestamp) < 0))
  2511. delta = 0;
  2512. if (next->activated == 1)
  2513. delta = delta * (ON_RUNQUEUE_WEIGHT * 128 / 100) / 128;
  2514. array = next->array;
  2515. new_prio = recalc_task_prio(next, next->timestamp + delta);
  2516. if (unlikely(next->prio != new_prio)) {
  2517. dequeue_task(next, array);
  2518. next->prio = new_prio;
  2519. enqueue_task(next, array);
  2520. } else
  2521. requeue_task(next, array);
  2522. }
  2523. next->activated = 0;
  2524. switch_tasks:
  2525. if (next == rq->idle)
  2526. schedstat_inc(rq, sched_goidle);
  2527. prefetch(next);
  2528. clear_tsk_need_resched(prev);
  2529. rcu_qsctr_inc(task_cpu(prev));
  2530. update_cpu_clock(prev, rq, now);
  2531. prev->sleep_avg -= run_time;
  2532. if ((long)prev->sleep_avg <= 0)
  2533. prev->sleep_avg = 0;
  2534. prev->timestamp = prev->last_ran = now;
  2535. sched_info_switch(prev, next);
  2536. if (likely(prev != next)) {
  2537. next->timestamp = now;
  2538. rq->nr_switches++;
  2539. rq->curr = next;
  2540. ++*switch_count;
  2541. prepare_task_switch(rq, next);
  2542. prev = context_switch(rq, prev, next);
  2543. barrier();
  2544. /*
  2545. * this_rq must be evaluated again because prev may have moved
  2546. * CPUs since it called schedule(), thus the 'rq' on its stack
  2547. * frame will be invalid.
  2548. */
  2549. finish_task_switch(this_rq(), prev);
  2550. } else
  2551. spin_unlock_irq(&rq->lock);
  2552. prev = current;
  2553. if (unlikely(reacquire_kernel_lock(prev) < 0))
  2554. goto need_resched_nonpreemptible;
  2555. preempt_enable_no_resched();
  2556. if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
  2557. goto need_resched;
  2558. }
  2559. EXPORT_SYMBOL(schedule);
  2560. #ifdef CONFIG_PREEMPT
  2561. /*
  2562. * this is is the entry point to schedule() from in-kernel preemption
  2563. * off of preempt_enable. Kernel preemptions off return from interrupt
  2564. * occur there and call schedule directly.
  2565. */
  2566. asmlinkage void __sched preempt_schedule(void)
  2567. {
  2568. struct thread_info *ti = current_thread_info();
  2569. #ifdef CONFIG_PREEMPT_BKL
  2570. struct task_struct *task = current;
  2571. int saved_lock_depth;
  2572. #endif
  2573. /*
  2574. * If there is a non-zero preempt_count or interrupts are disabled,
  2575. * we do not want to preempt the current task. Just return..
  2576. */
  2577. if (unlikely(ti->preempt_count || irqs_disabled()))
  2578. return;
  2579. need_resched:
  2580. add_preempt_count(PREEMPT_ACTIVE);
  2581. /*
  2582. * We keep the big kernel semaphore locked, but we
  2583. * clear ->lock_depth so that schedule() doesnt
  2584. * auto-release the semaphore:
  2585. */
  2586. #ifdef CONFIG_PREEMPT_BKL
  2587. saved_lock_depth = task->lock_depth;
  2588. task->lock_depth = -1;
  2589. #endif
  2590. schedule();
  2591. #ifdef CONFIG_PREEMPT_BKL
  2592. task->lock_depth = saved_lock_depth;
  2593. #endif
  2594. sub_preempt_count(PREEMPT_ACTIVE);
  2595. /* we could miss a preemption opportunity between schedule and now */
  2596. barrier();
  2597. if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
  2598. goto need_resched;
  2599. }
  2600. EXPORT_SYMBOL(preempt_schedule);
  2601. /*
  2602. * this is is the entry point to schedule() from kernel preemption
  2603. * off of irq context.
  2604. * Note, that this is called and return with irqs disabled. This will
  2605. * protect us against recursive calling from irq.
  2606. */
  2607. asmlinkage void __sched preempt_schedule_irq(void)
  2608. {
  2609. struct thread_info *ti = current_thread_info();
  2610. #ifdef CONFIG_PREEMPT_BKL
  2611. struct task_struct *task = current;
  2612. int saved_lock_depth;
  2613. #endif
  2614. /* Catch callers which need to be fixed*/
  2615. BUG_ON(ti->preempt_count || !irqs_disabled());
  2616. need_resched:
  2617. add_preempt_count(PREEMPT_ACTIVE);
  2618. /*
  2619. * We keep the big kernel semaphore locked, but we
  2620. * clear ->lock_depth so that schedule() doesnt
  2621. * auto-release the semaphore:
  2622. */
  2623. #ifdef CONFIG_PREEMPT_BKL
  2624. saved_lock_depth = task->lock_depth;
  2625. task->lock_depth = -1;
  2626. #endif
  2627. local_irq_enable();
  2628. schedule();
  2629. local_irq_disable();
  2630. #ifdef CONFIG_PREEMPT_BKL
  2631. task->lock_depth = saved_lock_depth;
  2632. #endif
  2633. sub_preempt_count(PREEMPT_ACTIVE);
  2634. /* we could miss a preemption opportunity between schedule and now */
  2635. barrier();
  2636. if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
  2637. goto need_resched;
  2638. }
  2639. #endif /* CONFIG_PREEMPT */
  2640. int default_wake_function(wait_queue_t *curr, unsigned mode, int sync, void *key)
  2641. {
  2642. task_t *p = curr->private;
  2643. return try_to_wake_up(p, mode, sync);
  2644. }
  2645. EXPORT_SYMBOL(default_wake_function);
  2646. /*
  2647. * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
  2648. * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
  2649. * number) then we wake all the non-exclusive tasks and one exclusive task.
  2650. *
  2651. * There are circumstances in which we can try to wake a task which has already
  2652. * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
  2653. * zero in this (rare) case, and we handle it by continuing to scan the queue.
  2654. */
  2655. static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
  2656. int nr_exclusive, int sync, void *key)
  2657. {
  2658. struct list_head *tmp, *next;
  2659. list_for_each_safe(tmp, next, &q->task_list) {
  2660. wait_queue_t *curr;
  2661. unsigned flags;
  2662. curr = list_entry(tmp, wait_queue_t, task_list);
  2663. flags = curr->flags;
  2664. if (curr->func(curr, mode, sync, key) &&
  2665. (flags & WQ_FLAG_EXCLUSIVE) &&
  2666. !--nr_exclusive)
  2667. break;
  2668. }
  2669. }
  2670. /**
  2671. * __wake_up - wake up threads blocked on a waitqueue.
  2672. * @q: the waitqueue
  2673. * @mode: which threads
  2674. * @nr_exclusive: how many wake-one or wake-many threads to wake up
  2675. * @key: is directly passed to the wakeup function
  2676. */
  2677. void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
  2678. int nr_exclusive, void *key)
  2679. {
  2680. unsigned long flags;
  2681. spin_lock_irqsave(&q->lock, flags);
  2682. __wake_up_common(q, mode, nr_exclusive, 0, key);
  2683. spin_unlock_irqrestore(&q->lock, flags);
  2684. }
  2685. EXPORT_SYMBOL(__wake_up);
  2686. /*
  2687. * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
  2688. */
  2689. void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
  2690. {
  2691. __wake_up_common(q, mode, 1, 0, NULL);
  2692. }
  2693. /**
  2694. * __wake_up_sync - wake up threads blocked on a waitqueue.
  2695. * @q: the waitqueue
  2696. * @mode: which threads
  2697. * @nr_exclusive: how many wake-one or wake-many threads to wake up
  2698. *
  2699. * The sync wakeup differs that the waker knows that it will schedule
  2700. * away soon, so while the target thread will be woken up, it will not
  2701. * be migrated to another CPU - ie. the two threads are 'synchronized'
  2702. * with each other. This can prevent needless bouncing between CPUs.
  2703. *
  2704. * On UP it can prevent extra preemption.
  2705. */
  2706. void fastcall __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
  2707. {
  2708. unsigned long flags;
  2709. int sync = 1;
  2710. if (unlikely(!q))
  2711. return;
  2712. if (unlikely(!nr_exclusive))
  2713. sync = 0;
  2714. spin_lock_irqsave(&q->lock, flags);
  2715. __wake_up_common(q, mode, nr_exclusive, sync, NULL);
  2716. spin_unlock_irqrestore(&q->lock, flags);
  2717. }
  2718. EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
  2719. void fastcall complete(struct completion *x)
  2720. {
  2721. unsigned long flags;
  2722. spin_lock_irqsave(&x->wait.lock, flags);
  2723. x->done++;
  2724. __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
  2725. 1, 0, NULL);
  2726. spin_unlock_irqrestore(&x->wait.lock, flags);
  2727. }
  2728. EXPORT_SYMBOL(complete);
  2729. void fastcall complete_all(struct completion *x)
  2730. {
  2731. unsigned long flags;
  2732. spin_lock_irqsave(&x->wait.lock, flags);
  2733. x->done += UINT_MAX/2;
  2734. __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
  2735. 0, 0, NULL);
  2736. spin_unlock_irqrestore(&x->wait.lock, flags);
  2737. }
  2738. EXPORT_SYMBOL(complete_all);
  2739. void fastcall __sched wait_for_completion(struct completion *x)
  2740. {
  2741. might_sleep();
  2742. spin_lock_irq(&x->wait.lock);
  2743. if (!x->done) {
  2744. DECLARE_WAITQUEUE(wait, current);
  2745. wait.flags |= WQ_FLAG_EXCLUSIVE;
  2746. __add_wait_queue_tail(&x->wait, &wait);
  2747. do {
  2748. __set_current_state(TASK_UNINTERRUPTIBLE);
  2749. spin_unlock_irq(&x->wait.lock);
  2750. schedule();
  2751. spin_lock_irq(&x->wait.lock);
  2752. } while (!x->done);
  2753. __remove_wait_queue(&x->wait, &wait);
  2754. }
  2755. x->done--;
  2756. spin_unlock_irq(&x->wait.lock);
  2757. }
  2758. EXPORT_SYMBOL(wait_for_completion);
  2759. unsigned long fastcall __sched
  2760. wait_for_completion_timeout(struct completion *x, unsigned long timeout)
  2761. {
  2762. might_sleep();
  2763. spin_lock_irq(&x->wait.lock);
  2764. if (!x->done) {
  2765. DECLARE_WAITQUEUE(wait, current);
  2766. wait.flags |= WQ_FLAG_EXCLUSIVE;
  2767. __add_wait_queue_tail(&x->wait, &wait);
  2768. do {
  2769. __set_current_state(TASK_UNINTERRUPTIBLE);
  2770. spin_unlock_irq(&x->wait.lock);
  2771. timeout = schedule_timeout(timeout);
  2772. spin_lock_irq(&x->wait.lock);
  2773. if (!timeout) {
  2774. __remove_wait_queue(&x->wait, &wait);
  2775. goto out;
  2776. }
  2777. } while (!x->done);
  2778. __remove_wait_queue(&x->wait, &wait);
  2779. }
  2780. x->done--;
  2781. out:
  2782. spin_unlock_irq(&x->wait.lock);
  2783. return timeout;
  2784. }
  2785. EXPORT_SYMBOL(wait_for_completion_timeout);
  2786. int fastcall __sched wait_for_completion_interruptible(struct completion *x)
  2787. {
  2788. int ret = 0;
  2789. might_sleep();
  2790. spin_lock_irq(&x->wait.lock);
  2791. if (!x->done) {
  2792. DECLARE_WAITQUEUE(wait, current);
  2793. wait.flags |= WQ_FLAG_EXCLUSIVE;
  2794. __add_wait_queue_tail(&x->wait, &wait);
  2795. do {
  2796. if (signal_pending(current)) {
  2797. ret = -ERESTARTSYS;
  2798. __remove_wait_queue(&x->wait, &wait);
  2799. goto out;
  2800. }
  2801. __set_current_state(TASK_INTERRUPTIBLE);
  2802. spin_unlock_irq(&x->wait.lock);
  2803. schedule();
  2804. spin_lock_irq(&x->wait.lock);
  2805. } while (!x->done);
  2806. __remove_wait_queue(&x->wait, &wait);
  2807. }
  2808. x->done--;
  2809. out:
  2810. spin_unlock_irq(&x->wait.lock);
  2811. return ret;
  2812. }
  2813. EXPORT_SYMBOL(wait_for_completion_interruptible);
  2814. unsigned long fastcall __sched
  2815. wait_for_completion_interruptible_timeout(struct completion *x,
  2816. unsigned long timeout)
  2817. {
  2818. might_sleep();
  2819. spin_lock_irq(&x->wait.lock);
  2820. if (!x->done) {
  2821. DECLARE_WAITQUEUE(wait, current);
  2822. wait.flags |= WQ_FLAG_EXCLUSIVE;
  2823. __add_wait_queue_tail(&x->wait, &wait);
  2824. do {
  2825. if (signal_pending(current)) {
  2826. timeout = -ERESTARTSYS;
  2827. __remove_wait_queue(&x->wait, &wait);
  2828. goto out;
  2829. }
  2830. __set_current_state(TASK_INTERRUPTIBLE);
  2831. spin_unlock_irq(&x->wait.lock);
  2832. timeout = schedule_timeout(timeout);
  2833. spin_lock_irq(&x->wait.lock);
  2834. if (!timeout) {
  2835. __remove_wait_queue(&x->wait, &wait);
  2836. goto out;
  2837. }
  2838. } while (!x->done);
  2839. __remove_wait_queue(&x->wait, &wait);
  2840. }
  2841. x->done--;
  2842. out:
  2843. spin_unlock_irq(&x->wait.lock);
  2844. return timeout;
  2845. }
  2846. EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
  2847. #define SLEEP_ON_VAR \
  2848. unsigned long flags; \
  2849. wait_queue_t wait; \
  2850. init_waitqueue_entry(&wait, current);
  2851. #define SLEEP_ON_HEAD \
  2852. spin_lock_irqsave(&q->lock,flags); \
  2853. __add_wait_queue(q, &wait); \
  2854. spin_unlock(&q->lock);
  2855. #define SLEEP_ON_TAIL \
  2856. spin_lock_irq(&q->lock); \
  2857. __remove_wait_queue(q, &wait); \
  2858. spin_unlock_irqrestore(&q->lock, flags);
  2859. void fastcall __sched interruptible_sleep_on(wait_queue_head_t *q)
  2860. {
  2861. SLEEP_ON_VAR
  2862. current->state = TASK_INTERRUPTIBLE;
  2863. SLEEP_ON_HEAD
  2864. schedule();
  2865. SLEEP_ON_TAIL
  2866. }
  2867. EXPORT_SYMBOL(interruptible_sleep_on);
  2868. long fastcall __sched interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
  2869. {
  2870. SLEEP_ON_VAR
  2871. current->state = TASK_INTERRUPTIBLE;
  2872. SLEEP_ON_HEAD
  2873. timeout = schedule_timeout(timeout);
  2874. SLEEP_ON_TAIL
  2875. return timeout;
  2876. }
  2877. EXPORT_SYMBOL(interruptible_sleep_on_timeout);
  2878. void fastcall __sched sleep_on(wait_queue_head_t *q)
  2879. {
  2880. SLEEP_ON_VAR
  2881. current->state = TASK_UNINTERRUPTIBLE;
  2882. SLEEP_ON_HEAD
  2883. schedule();
  2884. SLEEP_ON_TAIL
  2885. }
  2886. EXPORT_SYMBOL(sleep_on);
  2887. long fastcall __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
  2888. {
  2889. SLEEP_ON_VAR
  2890. current->state = TASK_UNINTERRUPTIBLE;
  2891. SLEEP_ON_HEAD
  2892. timeout = schedule_timeout(timeout);
  2893. SLEEP_ON_TAIL
  2894. return timeout;
  2895. }
  2896. EXPORT_SYMBOL(sleep_on_timeout);
  2897. void set_user_nice(task_t *p, long nice)
  2898. {
  2899. unsigned long flags;
  2900. prio_array_t *array;
  2901. runqueue_t *rq;
  2902. int old_prio, new_prio, delta;
  2903. if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
  2904. return;
  2905. /*
  2906. * We have to be careful, if called from sys_setpriority(),
  2907. * the task might be in the middle of scheduling on another CPU.
  2908. */
  2909. rq = task_rq_lock(p, &flags);
  2910. /*
  2911. * The RT priorities are set via sched_setscheduler(), but we still
  2912. * allow the 'normal' nice value to be set - but as expected
  2913. * it wont have any effect on scheduling until the task is
  2914. * not SCHED_NORMAL:
  2915. */
  2916. if (rt_task(p)) {
  2917. p->static_prio = NICE_TO_PRIO(nice);
  2918. goto out_unlock;
  2919. }
  2920. array = p->array;
  2921. if (array)
  2922. dequeue_task(p, array);
  2923. old_prio = p->prio;
  2924. new_prio = NICE_TO_PRIO(nice);
  2925. delta = new_prio - old_prio;
  2926. p->static_prio = NICE_TO_PRIO(nice);
  2927. p->prio += delta;
  2928. if (array) {
  2929. enqueue_task(p, array);
  2930. /*
  2931. * If the task increased its priority or is running and
  2932. * lowered its priority, then reschedule its CPU:
  2933. */
  2934. if (delta < 0 || (delta > 0 && task_running(rq, p)))
  2935. resched_task(rq->curr);
  2936. }
  2937. out_unlock:
  2938. task_rq_unlock(rq, &flags);
  2939. }
  2940. EXPORT_SYMBOL(set_user_nice);
  2941. /*
  2942. * can_nice - check if a task can reduce its nice value
  2943. * @p: task
  2944. * @nice: nice value
  2945. */
  2946. int can_nice(const task_t *p, const int nice)
  2947. {
  2948. /* convert nice value [19,-20] to rlimit style value [0,39] */
  2949. int nice_rlim = 19 - nice;
  2950. return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
  2951. capable(CAP_SYS_NICE));
  2952. }
  2953. #ifdef __ARCH_WANT_SYS_NICE
  2954. /*
  2955. * sys_nice - change the priority of the current process.
  2956. * @increment: priority increment
  2957. *
  2958. * sys_setpriority is a more generic, but much slower function that
  2959. * does similar things.
  2960. */
  2961. asmlinkage long sys_nice(int increment)
  2962. {
  2963. int retval;
  2964. long nice;
  2965. /*
  2966. * Setpriority might change our priority at the same moment.
  2967. * We don't have to worry. Conceptually one call occurs first
  2968. * and we have a single winner.
  2969. */
  2970. if (increment < -40)
  2971. increment = -40;
  2972. if (increment > 40)
  2973. increment = 40;
  2974. nice = PRIO_TO_NICE(current->static_prio) + increment;
  2975. if (nice < -20)
  2976. nice = -20;
  2977. if (nice > 19)
  2978. nice = 19;
  2979. if (increment < 0 && !can_nice(current, nice))
  2980. return -EPERM;
  2981. retval = security_task_setnice(current, nice);
  2982. if (retval)
  2983. return retval;
  2984. set_user_nice(current, nice);
  2985. return 0;
  2986. }
  2987. #endif
  2988. /**
  2989. * task_prio - return the priority value of a given task.
  2990. * @p: the task in question.
  2991. *
  2992. * This is the priority value as seen by users in /proc.
  2993. * RT tasks are offset by -200. Normal tasks are centered
  2994. * around 0, value goes from -16 to +15.
  2995. */
  2996. int task_prio(const task_t *p)
  2997. {
  2998. return p->prio - MAX_RT_PRIO;
  2999. }
  3000. /**
  3001. * task_nice - return the nice value of a given task.
  3002. * @p: the task in question.
  3003. */
  3004. int task_nice(const task_t *p)
  3005. {
  3006. return TASK_NICE(p);
  3007. }
  3008. EXPORT_SYMBOL_GPL(task_nice);
  3009. /**
  3010. * idle_cpu - is a given cpu idle currently?
  3011. * @cpu: the processor in question.
  3012. */
  3013. int idle_cpu(int cpu)
  3014. {
  3015. return cpu_curr(cpu) == cpu_rq(cpu)->idle;
  3016. }
  3017. EXPORT_SYMBOL_GPL(idle_cpu);
  3018. /**
  3019. * idle_task - return the idle task for a given cpu.
  3020. * @cpu: the processor in question.
  3021. */
  3022. task_t *idle_task(int cpu)
  3023. {
  3024. return cpu_rq(cpu)->idle;
  3025. }
  3026. /**
  3027. * find_process_by_pid - find a process with a matching PID value.
  3028. * @pid: the pid in question.
  3029. */
  3030. static inline task_t *find_process_by_pid(pid_t pid)
  3031. {
  3032. return pid ? find_task_by_pid(pid) : current;
  3033. }
  3034. /* Actually do priority change: must hold rq lock. */
  3035. static void __setscheduler(struct task_struct *p, int policy, int prio)
  3036. {
  3037. BUG_ON(p->array);
  3038. p->policy = policy;
  3039. p->rt_priority = prio;
  3040. if (policy != SCHED_NORMAL)
  3041. p->prio = MAX_USER_RT_PRIO-1 - p->rt_priority;
  3042. else
  3043. p->prio = p->static_prio;
  3044. }
  3045. /**
  3046. * sched_setscheduler - change the scheduling policy and/or RT priority of
  3047. * a thread.
  3048. * @p: the task in question.
  3049. * @policy: new policy.
  3050. * @param: structure containing the new RT priority.
  3051. */
  3052. int sched_setscheduler(struct task_struct *p, int policy, struct sched_param *param)
  3053. {
  3054. int retval;
  3055. int oldprio, oldpolicy = -1;
  3056. prio_array_t *array;
  3057. unsigned long flags;
  3058. runqueue_t *rq;
  3059. recheck:
  3060. /* double check policy once rq lock held */
  3061. if (policy < 0)
  3062. policy = oldpolicy = p->policy;
  3063. else if (policy != SCHED_FIFO && policy != SCHED_RR &&
  3064. policy != SCHED_NORMAL)
  3065. return -EINVAL;
  3066. /*
  3067. * Valid priorities for SCHED_FIFO and SCHED_RR are
  3068. * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL is 0.
  3069. */
  3070. if (param->sched_priority < 0 ||
  3071. param->sched_priority > MAX_USER_RT_PRIO-1)
  3072. return -EINVAL;
  3073. if ((policy == SCHED_NORMAL) != (param->sched_priority == 0))
  3074. return -EINVAL;
  3075. /*
  3076. * Allow unprivileged RT tasks to decrease priority:
  3077. */
  3078. if (!capable(CAP_SYS_NICE)) {
  3079. /* can't change policy */
  3080. if (policy != p->policy)
  3081. return -EPERM;
  3082. /* can't increase priority */
  3083. if (policy != SCHED_NORMAL &&
  3084. param->sched_priority > p->rt_priority &&
  3085. param->sched_priority >
  3086. p->signal->rlim[RLIMIT_RTPRIO].rlim_cur)
  3087. return -EPERM;
  3088. /* can't change other user's priorities */
  3089. if ((current->euid != p->euid) &&
  3090. (current->euid != p->uid))
  3091. return -EPERM;
  3092. }
  3093. retval = security_task_setscheduler(p, policy, param);
  3094. if (retval)
  3095. return retval;
  3096. /*
  3097. * To be able to change p->policy safely, the apropriate
  3098. * runqueue lock must be held.
  3099. */
  3100. rq = task_rq_lock(p, &flags);
  3101. /* recheck policy now with rq lock held */
  3102. if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
  3103. policy = oldpolicy = -1;
  3104. task_rq_unlock(rq, &flags);
  3105. goto recheck;
  3106. }
  3107. array = p->array;
  3108. if (array)
  3109. deactivate_task(p, rq);
  3110. oldprio = p->prio;
  3111. __setscheduler(p, policy, param->sched_priority);
  3112. if (array) {
  3113. __activate_task(p, rq);
  3114. /*
  3115. * Reschedule if we are currently running on this runqueue and
  3116. * our priority decreased, or if we are not currently running on
  3117. * this runqueue and our priority is higher than the current's
  3118. */
  3119. if (task_running(rq, p)) {
  3120. if (p->prio > oldprio)
  3121. resched_task(rq->curr);
  3122. } else if (TASK_PREEMPTS_CURR(p, rq))
  3123. resched_task(rq->curr);
  3124. }
  3125. task_rq_unlock(rq, &flags);
  3126. return 0;
  3127. }
  3128. EXPORT_SYMBOL_GPL(sched_setscheduler);
  3129. static int do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
  3130. {
  3131. int retval;
  3132. struct sched_param lparam;
  3133. struct task_struct *p;
  3134. if (!param || pid < 0)
  3135. return -EINVAL;
  3136. if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
  3137. return -EFAULT;
  3138. read_lock_irq(&tasklist_lock);
  3139. p = find_process_by_pid(pid);
  3140. if (!p) {
  3141. read_unlock_irq(&tasklist_lock);
  3142. return -ESRCH;
  3143. }
  3144. retval = sched_setscheduler(p, policy, &lparam);
  3145. read_unlock_irq(&tasklist_lock);
  3146. return retval;
  3147. }
  3148. /**
  3149. * sys_sched_setscheduler - set/change the scheduler policy and RT priority
  3150. * @pid: the pid in question.
  3151. * @policy: new policy.
  3152. * @param: structure containing the new RT priority.
  3153. */
  3154. asmlinkage long sys_sched_setscheduler(pid_t pid, int policy,
  3155. struct sched_param __user *param)
  3156. {
  3157. return do_sched_setscheduler(pid, policy, param);
  3158. }
  3159. /**
  3160. * sys_sched_setparam - set/change the RT priority of a thread
  3161. * @pid: the pid in question.
  3162. * @param: structure containing the new RT priority.
  3163. */
  3164. asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
  3165. {
  3166. return do_sched_setscheduler(pid, -1, param);
  3167. }
  3168. /**
  3169. * sys_sched_getscheduler - get the policy (scheduling class) of a thread
  3170. * @pid: the pid in question.
  3171. */
  3172. asmlinkage long sys_sched_getscheduler(pid_t pid)
  3173. {
  3174. int retval = -EINVAL;
  3175. task_t *p;
  3176. if (pid < 0)
  3177. goto out_nounlock;
  3178. retval = -ESRCH;
  3179. read_lock(&tasklist_lock);
  3180. p = find_process_by_pid(pid);
  3181. if (p) {
  3182. retval = security_task_getscheduler(p);
  3183. if (!retval)
  3184. retval = p->policy;
  3185. }
  3186. read_unlock(&tasklist_lock);
  3187. out_nounlock:
  3188. return retval;
  3189. }
  3190. /**
  3191. * sys_sched_getscheduler - get the RT priority of a thread
  3192. * @pid: the pid in question.
  3193. * @param: structure containing the RT priority.
  3194. */
  3195. asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
  3196. {
  3197. struct sched_param lp;
  3198. int retval = -EINVAL;
  3199. task_t *p;
  3200. if (!param || pid < 0)
  3201. goto out_nounlock;
  3202. read_lock(&tasklist_lock);
  3203. p = find_process_by_pid(pid);
  3204. retval = -ESRCH;
  3205. if (!p)
  3206. goto out_unlock;
  3207. retval = security_task_getscheduler(p);
  3208. if (retval)
  3209. goto out_unlock;
  3210. lp.sched_priority = p->rt_priority;
  3211. read_unlock(&tasklist_lock);
  3212. /*
  3213. * This one might sleep, we cannot do it with a spinlock held ...
  3214. */
  3215. retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
  3216. out_nounlock:
  3217. return retval;
  3218. out_unlock:
  3219. read_unlock(&tasklist_lock);
  3220. return retval;
  3221. }
  3222. long sched_setaffinity(pid_t pid, cpumask_t new_mask)
  3223. {
  3224. task_t *p;
  3225. int retval;
  3226. cpumask_t cpus_allowed;
  3227. lock_cpu_hotplug();
  3228. read_lock(&tasklist_lock);
  3229. p = find_process_by_pid(pid);
  3230. if (!p) {
  3231. read_unlock(&tasklist_lock);
  3232. unlock_cpu_hotplug();
  3233. return -ESRCH;
  3234. }
  3235. /*
  3236. * It is not safe to call set_cpus_allowed with the
  3237. * tasklist_lock held. We will bump the task_struct's
  3238. * usage count and then drop tasklist_lock.
  3239. */
  3240. get_task_struct(p);
  3241. read_unlock(&tasklist_lock);
  3242. retval = -EPERM;
  3243. if ((current->euid != p->euid) && (current->euid != p->uid) &&
  3244. !capable(CAP_SYS_NICE))
  3245. goto out_unlock;
  3246. cpus_allowed = cpuset_cpus_allowed(p);
  3247. cpus_and(new_mask, new_mask, cpus_allowed);
  3248. retval = set_cpus_allowed(p, new_mask);
  3249. out_unlock:
  3250. put_task_struct(p);
  3251. unlock_cpu_hotplug();
  3252. return retval;
  3253. }
  3254. static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
  3255. cpumask_t *new_mask)
  3256. {
  3257. if (len < sizeof(cpumask_t)) {
  3258. memset(new_mask, 0, sizeof(cpumask_t));
  3259. } else if (len > sizeof(cpumask_t)) {
  3260. len = sizeof(cpumask_t);
  3261. }
  3262. return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
  3263. }
  3264. /**
  3265. * sys_sched_setaffinity - set the cpu affinity of a process
  3266. * @pid: pid of the process
  3267. * @len: length in bytes of the bitmask pointed to by user_mask_ptr
  3268. * @user_mask_ptr: user-space pointer to the new cpu mask
  3269. */
  3270. asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
  3271. unsigned long __user *user_mask_ptr)
  3272. {
  3273. cpumask_t new_mask;
  3274. int retval;
  3275. retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
  3276. if (retval)
  3277. return retval;
  3278. return sched_setaffinity(pid, new_mask);
  3279. }
  3280. /*
  3281. * Represents all cpu's present in the system
  3282. * In systems capable of hotplug, this map could dynamically grow
  3283. * as new cpu's are detected in the system via any platform specific
  3284. * method, such as ACPI for e.g.
  3285. */
  3286. cpumask_t cpu_present_map;
  3287. EXPORT_SYMBOL(cpu_present_map);
  3288. #ifndef CONFIG_SMP
  3289. cpumask_t cpu_online_map = CPU_MASK_ALL;
  3290. cpumask_t cpu_possible_map = CPU_MASK_ALL;
  3291. #endif
  3292. long sched_getaffinity(pid_t pid, cpumask_t *mask)
  3293. {
  3294. int retval;
  3295. task_t *p;
  3296. lock_cpu_hotplug();
  3297. read_lock(&tasklist_lock);
  3298. retval = -ESRCH;
  3299. p = find_process_by_pid(pid);
  3300. if (!p)
  3301. goto out_unlock;
  3302. retval = 0;
  3303. cpus_and(*mask, p->cpus_allowed, cpu_possible_map);
  3304. out_unlock:
  3305. read_unlock(&tasklist_lock);
  3306. unlock_cpu_hotplug();
  3307. if (retval)
  3308. return retval;
  3309. return 0;
  3310. }
  3311. /**
  3312. * sys_sched_getaffinity - get the cpu affinity of a process
  3313. * @pid: pid of the process
  3314. * @len: length in bytes of the bitmask pointed to by user_mask_ptr
  3315. * @user_mask_ptr: user-space pointer to hold the current cpu mask
  3316. */
  3317. asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
  3318. unsigned long __user *user_mask_ptr)
  3319. {
  3320. int ret;
  3321. cpumask_t mask;
  3322. if (len < sizeof(cpumask_t))
  3323. return -EINVAL;
  3324. ret = sched_getaffinity(pid, &mask);
  3325. if (ret < 0)
  3326. return ret;
  3327. if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
  3328. return -EFAULT;
  3329. return sizeof(cpumask_t);
  3330. }
  3331. /**
  3332. * sys_sched_yield - yield the current processor to other threads.
  3333. *
  3334. * this function yields the current CPU by moving the calling thread
  3335. * to the expired array. If there are no other threads running on this
  3336. * CPU then this function will return.
  3337. */
  3338. asmlinkage long sys_sched_yield(void)
  3339. {
  3340. runqueue_t *rq = this_rq_lock();
  3341. prio_array_t *array = current->array;
  3342. prio_array_t *target = rq->expired;
  3343. schedstat_inc(rq, yld_cnt);
  3344. /*
  3345. * We implement yielding by moving the task into the expired
  3346. * queue.
  3347. *
  3348. * (special rule: RT tasks will just roundrobin in the active
  3349. * array.)
  3350. */
  3351. if (rt_task(current))
  3352. target = rq->active;
  3353. if (current->array->nr_active == 1) {
  3354. schedstat_inc(rq, yld_act_empty);
  3355. if (!rq->expired->nr_active)
  3356. schedstat_inc(rq, yld_both_empty);
  3357. } else if (!rq->expired->nr_active)
  3358. schedstat_inc(rq, yld_exp_empty);
  3359. if (array != target) {
  3360. dequeue_task(current, array);
  3361. enqueue_task(current, target);
  3362. } else
  3363. /*
  3364. * requeue_task is cheaper so perform that if possible.
  3365. */
  3366. requeue_task(current, array);
  3367. /*
  3368. * Since we are going to call schedule() anyway, there's
  3369. * no need to preempt or enable interrupts:
  3370. */
  3371. __release(rq->lock);
  3372. _raw_spin_unlock(&rq->lock);
  3373. preempt_enable_no_resched();
  3374. schedule();
  3375. return 0;
  3376. }
  3377. static inline void __cond_resched(void)
  3378. {
  3379. do {
  3380. add_preempt_count(PREEMPT_ACTIVE);
  3381. schedule();
  3382. sub_preempt_count(PREEMPT_ACTIVE);
  3383. } while (need_resched());
  3384. }
  3385. int __sched cond_resched(void)
  3386. {
  3387. if (need_resched()) {
  3388. __cond_resched();
  3389. return 1;
  3390. }
  3391. return 0;
  3392. }
  3393. EXPORT_SYMBOL(cond_resched);
  3394. /*
  3395. * cond_resched_lock() - if a reschedule is pending, drop the given lock,
  3396. * call schedule, and on return reacquire the lock.
  3397. *
  3398. * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
  3399. * operations here to prevent schedule() from being called twice (once via
  3400. * spin_unlock(), once by hand).
  3401. */
  3402. int cond_resched_lock(spinlock_t * lock)
  3403. {
  3404. int ret = 0;
  3405. if (need_lockbreak(lock)) {
  3406. spin_unlock(lock);
  3407. cpu_relax();
  3408. ret = 1;
  3409. spin_lock(lock);
  3410. }
  3411. if (need_resched()) {
  3412. _raw_spin_unlock(lock);
  3413. preempt_enable_no_resched();
  3414. __cond_resched();
  3415. ret = 1;
  3416. spin_lock(lock);
  3417. }
  3418. return ret;
  3419. }
  3420. EXPORT_SYMBOL(cond_resched_lock);
  3421. int __sched cond_resched_softirq(void)
  3422. {
  3423. BUG_ON(!in_softirq());
  3424. if (need_resched()) {
  3425. __local_bh_enable();
  3426. __cond_resched();
  3427. local_bh_disable();
  3428. return 1;
  3429. }
  3430. return 0;
  3431. }
  3432. EXPORT_SYMBOL(cond_resched_softirq);
  3433. /**
  3434. * yield - yield the current processor to other threads.
  3435. *
  3436. * this is a shortcut for kernel-space yielding - it marks the
  3437. * thread runnable and calls sys_sched_yield().
  3438. */
  3439. void __sched yield(void)
  3440. {
  3441. set_current_state(TASK_RUNNING);
  3442. sys_sched_yield();
  3443. }
  3444. EXPORT_SYMBOL(yield);
  3445. /*
  3446. * This task is about to go to sleep on IO. Increment rq->nr_iowait so
  3447. * that process accounting knows that this is a task in IO wait state.
  3448. *
  3449. * But don't do that if it is a deliberate, throttling IO wait (this task
  3450. * has set its backing_dev_info: the queue against which it should throttle)
  3451. */
  3452. void __sched io_schedule(void)
  3453. {
  3454. struct runqueue *rq = &per_cpu(runqueues, raw_smp_processor_id());
  3455. atomic_inc(&rq->nr_iowait);
  3456. schedule();
  3457. atomic_dec(&rq->nr_iowait);
  3458. }
  3459. EXPORT_SYMBOL(io_schedule);
  3460. long __sched io_schedule_timeout(long timeout)
  3461. {
  3462. struct runqueue *rq = &per_cpu(runqueues, raw_smp_processor_id());
  3463. long ret;
  3464. atomic_inc(&rq->nr_iowait);
  3465. ret = schedule_timeout(timeout);
  3466. atomic_dec(&rq->nr_iowait);
  3467. return ret;
  3468. }
  3469. /**
  3470. * sys_sched_get_priority_max - return maximum RT priority.
  3471. * @policy: scheduling class.
  3472. *
  3473. * this syscall returns the maximum rt_priority that can be used
  3474. * by a given scheduling class.
  3475. */
  3476. asmlinkage long sys_sched_get_priority_max(int policy)
  3477. {
  3478. int ret = -EINVAL;
  3479. switch (policy) {
  3480. case SCHED_FIFO:
  3481. case SCHED_RR:
  3482. ret = MAX_USER_RT_PRIO-1;
  3483. break;
  3484. case SCHED_NORMAL:
  3485. ret = 0;
  3486. break;
  3487. }
  3488. return ret;
  3489. }
  3490. /**
  3491. * sys_sched_get_priority_min - return minimum RT priority.
  3492. * @policy: scheduling class.
  3493. *
  3494. * this syscall returns the minimum rt_priority that can be used
  3495. * by a given scheduling class.
  3496. */
  3497. asmlinkage long sys_sched_get_priority_min(int policy)
  3498. {
  3499. int ret = -EINVAL;
  3500. switch (policy) {
  3501. case SCHED_FIFO:
  3502. case SCHED_RR:
  3503. ret = 1;
  3504. break;
  3505. case SCHED_NORMAL:
  3506. ret = 0;
  3507. }
  3508. return ret;
  3509. }
  3510. /**
  3511. * sys_sched_rr_get_interval - return the default timeslice of a process.
  3512. * @pid: pid of the process.
  3513. * @interval: userspace pointer to the timeslice value.
  3514. *
  3515. * this syscall writes the default timeslice value of a given process
  3516. * into the user-space timespec buffer. A value of '0' means infinity.
  3517. */
  3518. asmlinkage
  3519. long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
  3520. {
  3521. int retval = -EINVAL;
  3522. struct timespec t;
  3523. task_t *p;
  3524. if (pid < 0)
  3525. goto out_nounlock;
  3526. retval = -ESRCH;
  3527. read_lock(&tasklist_lock);
  3528. p = find_process_by_pid(pid);
  3529. if (!p)
  3530. goto out_unlock;
  3531. retval = security_task_getscheduler(p);
  3532. if (retval)
  3533. goto out_unlock;
  3534. jiffies_to_timespec(p->policy & SCHED_FIFO ?
  3535. 0 : task_timeslice(p), &t);
  3536. read_unlock(&tasklist_lock);
  3537. retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
  3538. out_nounlock:
  3539. return retval;
  3540. out_unlock:
  3541. read_unlock(&tasklist_lock);
  3542. return retval;
  3543. }
  3544. static inline struct task_struct *eldest_child(struct task_struct *p)
  3545. {
  3546. if (list_empty(&p->children)) return NULL;
  3547. return list_entry(p->children.next,struct task_struct,sibling);
  3548. }
  3549. static inline struct task_struct *older_sibling(struct task_struct *p)
  3550. {
  3551. if (p->sibling.prev==&p->parent->children) return NULL;
  3552. return list_entry(p->sibling.prev,struct task_struct,sibling);
  3553. }
  3554. static inline struct task_struct *younger_sibling(struct task_struct *p)
  3555. {
  3556. if (p->sibling.next==&p->parent->children) return NULL;
  3557. return list_entry(p->sibling.next,struct task_struct,sibling);
  3558. }
  3559. static void show_task(task_t * p)
  3560. {
  3561. task_t *relative;
  3562. unsigned state;
  3563. unsigned long free = 0;
  3564. static const char *stat_nam[] = { "R", "S", "D", "T", "t", "Z", "X" };
  3565. printk("%-13.13s ", p->comm);
  3566. state = p->state ? __ffs(p->state) + 1 : 0;
  3567. if (state < ARRAY_SIZE(stat_nam))
  3568. printk(stat_nam[state]);
  3569. else
  3570. printk("?");
  3571. #if (BITS_PER_LONG == 32)
  3572. if (state == TASK_RUNNING)
  3573. printk(" running ");
  3574. else
  3575. printk(" %08lX ", thread_saved_pc(p));
  3576. #else
  3577. if (state == TASK_RUNNING)
  3578. printk(" running task ");
  3579. else
  3580. printk(" %016lx ", thread_saved_pc(p));
  3581. #endif
  3582. #ifdef CONFIG_DEBUG_STACK_USAGE
  3583. {
  3584. unsigned long * n = (unsigned long *) (p->thread_info+1);
  3585. while (!*n)
  3586. n++;
  3587. free = (unsigned long) n - (unsigned long)(p->thread_info+1);
  3588. }
  3589. #endif
  3590. printk("%5lu %5d %6d ", free, p->pid, p->parent->pid);
  3591. if ((relative = eldest_child(p)))
  3592. printk("%5d ", relative->pid);
  3593. else
  3594. printk(" ");
  3595. if ((relative = younger_sibling(p)))
  3596. printk("%7d", relative->pid);
  3597. else
  3598. printk(" ");
  3599. if ((relative = older_sibling(p)))
  3600. printk(" %5d", relative->pid);
  3601. else
  3602. printk(" ");
  3603. if (!p->mm)
  3604. printk(" (L-TLB)\n");
  3605. else
  3606. printk(" (NOTLB)\n");
  3607. if (state != TASK_RUNNING)
  3608. show_stack(p, NULL);
  3609. }
  3610. void show_state(void)
  3611. {
  3612. task_t *g, *p;
  3613. #if (BITS_PER_LONG == 32)
  3614. printk("\n"
  3615. " sibling\n");
  3616. printk(" task PC pid father child younger older\n");
  3617. #else
  3618. printk("\n"
  3619. " sibling\n");
  3620. printk(" task PC pid father child younger older\n");
  3621. #endif
  3622. read_lock(&tasklist_lock);
  3623. do_each_thread(g, p) {
  3624. /*
  3625. * reset the NMI-timeout, listing all files on a slow
  3626. * console might take alot of time:
  3627. */
  3628. touch_nmi_watchdog();
  3629. show_task(p);
  3630. } while_each_thread(g, p);
  3631. read_unlock(&tasklist_lock);
  3632. }
  3633. /**
  3634. * init_idle - set up an idle thread for a given CPU
  3635. * @idle: task in question
  3636. * @cpu: cpu the idle task belongs to
  3637. *
  3638. * NOTE: this function does not set the idle thread's NEED_RESCHED
  3639. * flag, to make booting more robust.
  3640. */
  3641. void __devinit init_idle(task_t *idle, int cpu)
  3642. {
  3643. runqueue_t *rq = cpu_rq(cpu);
  3644. unsigned long flags;
  3645. idle->sleep_avg = 0;
  3646. idle->array = NULL;
  3647. idle->prio = MAX_PRIO;
  3648. idle->state = TASK_RUNNING;
  3649. idle->cpus_allowed = cpumask_of_cpu(cpu);
  3650. set_task_cpu(idle, cpu);
  3651. spin_lock_irqsave(&rq->lock, flags);
  3652. rq->curr = rq->idle = idle;
  3653. #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
  3654. idle->oncpu = 1;
  3655. #endif
  3656. spin_unlock_irqrestore(&rq->lock, flags);
  3657. /* Set the preempt count _outside_ the spinlocks! */
  3658. #if defined(CONFIG_PREEMPT) && !defined(CONFIG_PREEMPT_BKL)
  3659. idle->thread_info->preempt_count = (idle->lock_depth >= 0);
  3660. #else
  3661. idle->thread_info->preempt_count = 0;
  3662. #endif
  3663. }
  3664. /*
  3665. * In a system that switches off the HZ timer nohz_cpu_mask
  3666. * indicates which cpus entered this state. This is used
  3667. * in the rcu update to wait only for active cpus. For system
  3668. * which do not switch off the HZ timer nohz_cpu_mask should
  3669. * always be CPU_MASK_NONE.
  3670. */
  3671. cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
  3672. #ifdef CONFIG_SMP
  3673. /*
  3674. * This is how migration works:
  3675. *
  3676. * 1) we queue a migration_req_t structure in the source CPU's
  3677. * runqueue and wake up that CPU's migration thread.
  3678. * 2) we down() the locked semaphore => thread blocks.
  3679. * 3) migration thread wakes up (implicitly it forces the migrated
  3680. * thread off the CPU)
  3681. * 4) it gets the migration request and checks whether the migrated
  3682. * task is still in the wrong runqueue.
  3683. * 5) if it's in the wrong runqueue then the migration thread removes
  3684. * it and puts it into the right queue.
  3685. * 6) migration thread up()s the semaphore.
  3686. * 7) we wake up and the migration is done.
  3687. */
  3688. /*
  3689. * Change a given task's CPU affinity. Migrate the thread to a
  3690. * proper CPU and schedule it away if the CPU it's executing on
  3691. * is removed from the allowed bitmask.
  3692. *
  3693. * NOTE: the caller must have a valid reference to the task, the
  3694. * task must not exit() & deallocate itself prematurely. The
  3695. * call is not atomic; no spinlocks may be held.
  3696. */
  3697. int set_cpus_allowed(task_t *p, cpumask_t new_mask)
  3698. {
  3699. unsigned long flags;
  3700. int ret = 0;
  3701. migration_req_t req;
  3702. runqueue_t *rq;
  3703. rq = task_rq_lock(p, &flags);
  3704. if (!cpus_intersects(new_mask, cpu_online_map)) {
  3705. ret = -EINVAL;
  3706. goto out;
  3707. }
  3708. p->cpus_allowed = new_mask;
  3709. /* Can the task run on the task's current CPU? If so, we're done */
  3710. if (cpu_isset(task_cpu(p), new_mask))
  3711. goto out;
  3712. if (migrate_task(p, any_online_cpu(new_mask), &req)) {
  3713. /* Need help from migration thread: drop lock and wait. */
  3714. task_rq_unlock(rq, &flags);
  3715. wake_up_process(rq->migration_thread);
  3716. wait_for_completion(&req.done);
  3717. tlb_migrate_finish(p->mm);
  3718. return 0;
  3719. }
  3720. out:
  3721. task_rq_unlock(rq, &flags);
  3722. return ret;
  3723. }
  3724. EXPORT_SYMBOL_GPL(set_cpus_allowed);
  3725. /*
  3726. * Move (not current) task off this cpu, onto dest cpu. We're doing
  3727. * this because either it can't run here any more (set_cpus_allowed()
  3728. * away from this CPU, or CPU going down), or because we're
  3729. * attempting to rebalance this task on exec (sched_exec).
  3730. *
  3731. * So we race with normal scheduler movements, but that's OK, as long
  3732. * as the task is no longer on this CPU.
  3733. */
  3734. static void __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
  3735. {
  3736. runqueue_t *rq_dest, *rq_src;
  3737. if (unlikely(cpu_is_offline(dest_cpu)))
  3738. return;
  3739. rq_src = cpu_rq(src_cpu);
  3740. rq_dest = cpu_rq(dest_cpu);
  3741. double_rq_lock(rq_src, rq_dest);
  3742. /* Already moved. */
  3743. if (task_cpu(p) != src_cpu)
  3744. goto out;
  3745. /* Affinity changed (again). */
  3746. if (!cpu_isset(dest_cpu, p->cpus_allowed))
  3747. goto out;
  3748. set_task_cpu(p, dest_cpu);
  3749. if (p->array) {
  3750. /*
  3751. * Sync timestamp with rq_dest's before activating.
  3752. * The same thing could be achieved by doing this step
  3753. * afterwards, and pretending it was a local activate.
  3754. * This way is cleaner and logically correct.
  3755. */
  3756. p->timestamp = p->timestamp - rq_src->timestamp_last_tick
  3757. + rq_dest->timestamp_last_tick;
  3758. deactivate_task(p, rq_src);
  3759. activate_task(p, rq_dest, 0);
  3760. if (TASK_PREEMPTS_CURR(p, rq_dest))
  3761. resched_task(rq_dest->curr);
  3762. }
  3763. out:
  3764. double_rq_unlock(rq_src, rq_dest);
  3765. }
  3766. /*
  3767. * migration_thread - this is a highprio system thread that performs
  3768. * thread migration by bumping thread off CPU then 'pushing' onto
  3769. * another runqueue.
  3770. */
  3771. static int migration_thread(void * data)
  3772. {
  3773. runqueue_t *rq;
  3774. int cpu = (long)data;
  3775. rq = cpu_rq(cpu);
  3776. BUG_ON(rq->migration_thread != current);
  3777. set_current_state(TASK_INTERRUPTIBLE);
  3778. while (!kthread_should_stop()) {
  3779. struct list_head *head;
  3780. migration_req_t *req;
  3781. try_to_freeze();
  3782. spin_lock_irq(&rq->lock);
  3783. if (cpu_is_offline(cpu)) {
  3784. spin_unlock_irq(&rq->lock);
  3785. goto wait_to_die;
  3786. }
  3787. if (rq->active_balance) {
  3788. active_load_balance(rq, cpu);
  3789. rq->active_balance = 0;
  3790. }
  3791. head = &rq->migration_queue;
  3792. if (list_empty(head)) {
  3793. spin_unlock_irq(&rq->lock);
  3794. schedule();
  3795. set_current_state(TASK_INTERRUPTIBLE);
  3796. continue;
  3797. }
  3798. req = list_entry(head->next, migration_req_t, list);
  3799. list_del_init(head->next);
  3800. spin_unlock(&rq->lock);
  3801. __migrate_task(req->task, cpu, req->dest_cpu);
  3802. local_irq_enable();
  3803. complete(&req->done);
  3804. }
  3805. __set_current_state(TASK_RUNNING);
  3806. return 0;
  3807. wait_to_die:
  3808. /* Wait for kthread_stop */
  3809. set_current_state(TASK_INTERRUPTIBLE);
  3810. while (!kthread_should_stop()) {
  3811. schedule();
  3812. set_current_state(TASK_INTERRUPTIBLE);
  3813. }
  3814. __set_current_state(TASK_RUNNING);
  3815. return 0;
  3816. }
  3817. #ifdef CONFIG_HOTPLUG_CPU
  3818. /* Figure out where task on dead CPU should go, use force if neccessary. */
  3819. static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *tsk)
  3820. {
  3821. int dest_cpu;
  3822. cpumask_t mask;
  3823. /* On same node? */
  3824. mask = node_to_cpumask(cpu_to_node(dead_cpu));
  3825. cpus_and(mask, mask, tsk->cpus_allowed);
  3826. dest_cpu = any_online_cpu(mask);
  3827. /* On any allowed CPU? */
  3828. if (dest_cpu == NR_CPUS)
  3829. dest_cpu = any_online_cpu(tsk->cpus_allowed);
  3830. /* No more Mr. Nice Guy. */
  3831. if (dest_cpu == NR_CPUS) {
  3832. cpus_setall(tsk->cpus_allowed);
  3833. dest_cpu = any_online_cpu(tsk->cpus_allowed);
  3834. /*
  3835. * Don't tell them about moving exiting tasks or
  3836. * kernel threads (both mm NULL), since they never
  3837. * leave kernel.
  3838. */
  3839. if (tsk->mm && printk_ratelimit())
  3840. printk(KERN_INFO "process %d (%s) no "
  3841. "longer affine to cpu%d\n",
  3842. tsk->pid, tsk->comm, dead_cpu);
  3843. }
  3844. __migrate_task(tsk, dead_cpu, dest_cpu);
  3845. }
  3846. /*
  3847. * While a dead CPU has no uninterruptible tasks queued at this point,
  3848. * it might still have a nonzero ->nr_uninterruptible counter, because
  3849. * for performance reasons the counter is not stricly tracking tasks to
  3850. * their home CPUs. So we just add the counter to another CPU's counter,
  3851. * to keep the global sum constant after CPU-down:
  3852. */
  3853. static void migrate_nr_uninterruptible(runqueue_t *rq_src)
  3854. {
  3855. runqueue_t *rq_dest = cpu_rq(any_online_cpu(CPU_MASK_ALL));
  3856. unsigned long flags;
  3857. local_irq_save(flags);
  3858. double_rq_lock(rq_src, rq_dest);
  3859. rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
  3860. rq_src->nr_uninterruptible = 0;
  3861. double_rq_unlock(rq_src, rq_dest);
  3862. local_irq_restore(flags);
  3863. }
  3864. /* Run through task list and migrate tasks from the dead cpu. */
  3865. static void migrate_live_tasks(int src_cpu)
  3866. {
  3867. struct task_struct *tsk, *t;
  3868. write_lock_irq(&tasklist_lock);
  3869. do_each_thread(t, tsk) {
  3870. if (tsk == current)
  3871. continue;
  3872. if (task_cpu(tsk) == src_cpu)
  3873. move_task_off_dead_cpu(src_cpu, tsk);
  3874. } while_each_thread(t, tsk);
  3875. write_unlock_irq(&tasklist_lock);
  3876. }
  3877. /* Schedules idle task to be the next runnable task on current CPU.
  3878. * It does so by boosting its priority to highest possible and adding it to
  3879. * the _front_ of runqueue. Used by CPU offline code.
  3880. */
  3881. void sched_idle_next(void)
  3882. {
  3883. int cpu = smp_processor_id();
  3884. runqueue_t *rq = this_rq();
  3885. struct task_struct *p = rq->idle;
  3886. unsigned long flags;
  3887. /* cpu has to be offline */
  3888. BUG_ON(cpu_online(cpu));
  3889. /* Strictly not necessary since rest of the CPUs are stopped by now
  3890. * and interrupts disabled on current cpu.
  3891. */
  3892. spin_lock_irqsave(&rq->lock, flags);
  3893. __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
  3894. /* Add idle task to _front_ of it's priority queue */
  3895. __activate_idle_task(p, rq);
  3896. spin_unlock_irqrestore(&rq->lock, flags);
  3897. }
  3898. /* Ensures that the idle task is using init_mm right before its cpu goes
  3899. * offline.
  3900. */
  3901. void idle_task_exit(void)
  3902. {
  3903. struct mm_struct *mm = current->active_mm;
  3904. BUG_ON(cpu_online(smp_processor_id()));
  3905. if (mm != &init_mm)
  3906. switch_mm(mm, &init_mm, current);
  3907. mmdrop(mm);
  3908. }
  3909. static void migrate_dead(unsigned int dead_cpu, task_t *tsk)
  3910. {
  3911. struct runqueue *rq = cpu_rq(dead_cpu);
  3912. /* Must be exiting, otherwise would be on tasklist. */
  3913. BUG_ON(tsk->exit_state != EXIT_ZOMBIE && tsk->exit_state != EXIT_DEAD);
  3914. /* Cannot have done final schedule yet: would have vanished. */
  3915. BUG_ON(tsk->flags & PF_DEAD);
  3916. get_task_struct(tsk);
  3917. /*
  3918. * Drop lock around migration; if someone else moves it,
  3919. * that's OK. No task can be added to this CPU, so iteration is
  3920. * fine.
  3921. */
  3922. spin_unlock_irq(&rq->lock);
  3923. move_task_off_dead_cpu(dead_cpu, tsk);
  3924. spin_lock_irq(&rq->lock);
  3925. put_task_struct(tsk);
  3926. }
  3927. /* release_task() removes task from tasklist, so we won't find dead tasks. */
  3928. static void migrate_dead_tasks(unsigned int dead_cpu)
  3929. {
  3930. unsigned arr, i;
  3931. struct runqueue *rq = cpu_rq(dead_cpu);
  3932. for (arr = 0; arr < 2; arr++) {
  3933. for (i = 0; i < MAX_PRIO; i++) {
  3934. struct list_head *list = &rq->arrays[arr].queue[i];
  3935. while (!list_empty(list))
  3936. migrate_dead(dead_cpu,
  3937. list_entry(list->next, task_t,
  3938. run_list));
  3939. }
  3940. }
  3941. }
  3942. #endif /* CONFIG_HOTPLUG_CPU */
  3943. /*
  3944. * migration_call - callback that gets triggered when a CPU is added.
  3945. * Here we can start up the necessary migration thread for the new CPU.
  3946. */
  3947. static int migration_call(struct notifier_block *nfb, unsigned long action,
  3948. void *hcpu)
  3949. {
  3950. int cpu = (long)hcpu;
  3951. struct task_struct *p;
  3952. struct runqueue *rq;
  3953. unsigned long flags;
  3954. switch (action) {
  3955. case CPU_UP_PREPARE:
  3956. p = kthread_create(migration_thread, hcpu, "migration/%d",cpu);
  3957. if (IS_ERR(p))
  3958. return NOTIFY_BAD;
  3959. p->flags |= PF_NOFREEZE;
  3960. kthread_bind(p, cpu);
  3961. /* Must be high prio: stop_machine expects to yield to it. */
  3962. rq = task_rq_lock(p, &flags);
  3963. __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
  3964. task_rq_unlock(rq, &flags);
  3965. cpu_rq(cpu)->migration_thread = p;
  3966. break;
  3967. case CPU_ONLINE:
  3968. /* Strictly unneccessary, as first user will wake it. */
  3969. wake_up_process(cpu_rq(cpu)->migration_thread);
  3970. break;
  3971. #ifdef CONFIG_HOTPLUG_CPU
  3972. case CPU_UP_CANCELED:
  3973. /* Unbind it from offline cpu so it can run. Fall thru. */
  3974. kthread_bind(cpu_rq(cpu)->migration_thread,smp_processor_id());
  3975. kthread_stop(cpu_rq(cpu)->migration_thread);
  3976. cpu_rq(cpu)->migration_thread = NULL;
  3977. break;
  3978. case CPU_DEAD:
  3979. migrate_live_tasks(cpu);
  3980. rq = cpu_rq(cpu);
  3981. kthread_stop(rq->migration_thread);
  3982. rq->migration_thread = NULL;
  3983. /* Idle task back to normal (off runqueue, low prio) */
  3984. rq = task_rq_lock(rq->idle, &flags);
  3985. deactivate_task(rq->idle, rq);
  3986. rq->idle->static_prio = MAX_PRIO;
  3987. __setscheduler(rq->idle, SCHED_NORMAL, 0);
  3988. migrate_dead_tasks(cpu);
  3989. task_rq_unlock(rq, &flags);
  3990. migrate_nr_uninterruptible(rq);
  3991. BUG_ON(rq->nr_running != 0);
  3992. /* No need to migrate the tasks: it was best-effort if
  3993. * they didn't do lock_cpu_hotplug(). Just wake up
  3994. * the requestors. */
  3995. spin_lock_irq(&rq->lock);
  3996. while (!list_empty(&rq->migration_queue)) {
  3997. migration_req_t *req;
  3998. req = list_entry(rq->migration_queue.next,
  3999. migration_req_t, list);
  4000. list_del_init(&req->list);
  4001. complete(&req->done);
  4002. }
  4003. spin_unlock_irq(&rq->lock);
  4004. break;
  4005. #endif
  4006. }
  4007. return NOTIFY_OK;
  4008. }
  4009. /* Register at highest priority so that task migration (migrate_all_tasks)
  4010. * happens before everything else.
  4011. */
  4012. static struct notifier_block __devinitdata migration_notifier = {
  4013. .notifier_call = migration_call,
  4014. .priority = 10
  4015. };
  4016. int __init migration_init(void)
  4017. {
  4018. void *cpu = (void *)(long)smp_processor_id();
  4019. /* Start one for boot CPU. */
  4020. migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
  4021. migration_call(&migration_notifier, CPU_ONLINE, cpu);
  4022. register_cpu_notifier(&migration_notifier);
  4023. return 0;
  4024. }
  4025. #endif
  4026. #ifdef CONFIG_SMP
  4027. #undef SCHED_DOMAIN_DEBUG
  4028. #ifdef SCHED_DOMAIN_DEBUG
  4029. static void sched_domain_debug(struct sched_domain *sd, int cpu)
  4030. {
  4031. int level = 0;
  4032. if (!sd) {
  4033. printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
  4034. return;
  4035. }
  4036. printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
  4037. do {
  4038. int i;
  4039. char str[NR_CPUS];
  4040. struct sched_group *group = sd->groups;
  4041. cpumask_t groupmask;
  4042. cpumask_scnprintf(str, NR_CPUS, sd->span);
  4043. cpus_clear(groupmask);
  4044. printk(KERN_DEBUG);
  4045. for (i = 0; i < level + 1; i++)
  4046. printk(" ");
  4047. printk("domain %d: ", level);
  4048. if (!(sd->flags & SD_LOAD_BALANCE)) {
  4049. printk("does not load-balance\n");
  4050. if (sd->parent)
  4051. printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain has parent");
  4052. break;
  4053. }
  4054. printk("span %s\n", str);
  4055. if (!cpu_isset(cpu, sd->span))
  4056. printk(KERN_ERR "ERROR: domain->span does not contain CPU%d\n", cpu);
  4057. if (!cpu_isset(cpu, group->cpumask))
  4058. printk(KERN_ERR "ERROR: domain->groups does not contain CPU%d\n", cpu);
  4059. printk(KERN_DEBUG);
  4060. for (i = 0; i < level + 2; i++)
  4061. printk(" ");
  4062. printk("groups:");
  4063. do {
  4064. if (!group) {
  4065. printk("\n");
  4066. printk(KERN_ERR "ERROR: group is NULL\n");
  4067. break;
  4068. }
  4069. if (!group->cpu_power) {
  4070. printk("\n");
  4071. printk(KERN_ERR "ERROR: domain->cpu_power not set\n");
  4072. }
  4073. if (!cpus_weight(group->cpumask)) {
  4074. printk("\n");
  4075. printk(KERN_ERR "ERROR: empty group\n");
  4076. }
  4077. if (cpus_intersects(groupmask, group->cpumask)) {
  4078. printk("\n");
  4079. printk(KERN_ERR "ERROR: repeated CPUs\n");
  4080. }
  4081. cpus_or(groupmask, groupmask, group->cpumask);
  4082. cpumask_scnprintf(str, NR_CPUS, group->cpumask);
  4083. printk(" %s", str);
  4084. group = group->next;
  4085. } while (group != sd->groups);
  4086. printk("\n");
  4087. if (!cpus_equal(sd->span, groupmask))
  4088. printk(KERN_ERR "ERROR: groups don't span domain->span\n");
  4089. level++;
  4090. sd = sd->parent;
  4091. if (sd) {
  4092. if (!cpus_subset(groupmask, sd->span))
  4093. printk(KERN_ERR "ERROR: parent span is not a superset of domain->span\n");
  4094. }
  4095. } while (sd);
  4096. }
  4097. #else
  4098. #define sched_domain_debug(sd, cpu) {}
  4099. #endif
  4100. static int sd_degenerate(struct sched_domain *sd)
  4101. {
  4102. if (cpus_weight(sd->span) == 1)
  4103. return 1;
  4104. /* Following flags need at least 2 groups */
  4105. if (sd->flags & (SD_LOAD_BALANCE |
  4106. SD_BALANCE_NEWIDLE |
  4107. SD_BALANCE_FORK |
  4108. SD_BALANCE_EXEC)) {
  4109. if (sd->groups != sd->groups->next)
  4110. return 0;
  4111. }
  4112. /* Following flags don't use groups */
  4113. if (sd->flags & (SD_WAKE_IDLE |
  4114. SD_WAKE_AFFINE |
  4115. SD_WAKE_BALANCE))
  4116. return 0;
  4117. return 1;
  4118. }
  4119. static int sd_parent_degenerate(struct sched_domain *sd,
  4120. struct sched_domain *parent)
  4121. {
  4122. unsigned long cflags = sd->flags, pflags = parent->flags;
  4123. if (sd_degenerate(parent))
  4124. return 1;
  4125. if (!cpus_equal(sd->span, parent->span))
  4126. return 0;
  4127. /* Does parent contain flags not in child? */
  4128. /* WAKE_BALANCE is a subset of WAKE_AFFINE */
  4129. if (cflags & SD_WAKE_AFFINE)
  4130. pflags &= ~SD_WAKE_BALANCE;
  4131. /* Flags needing groups don't count if only 1 group in parent */
  4132. if (parent->groups == parent->groups->next) {
  4133. pflags &= ~(SD_LOAD_BALANCE |
  4134. SD_BALANCE_NEWIDLE |
  4135. SD_BALANCE_FORK |
  4136. SD_BALANCE_EXEC);
  4137. }
  4138. if (~cflags & pflags)
  4139. return 0;
  4140. return 1;
  4141. }
  4142. /*
  4143. * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
  4144. * hold the hotplug lock.
  4145. */
  4146. void cpu_attach_domain(struct sched_domain *sd, int cpu)
  4147. {
  4148. runqueue_t *rq = cpu_rq(cpu);
  4149. struct sched_domain *tmp;
  4150. /* Remove the sched domains which do not contribute to scheduling. */
  4151. for (tmp = sd; tmp; tmp = tmp->parent) {
  4152. struct sched_domain *parent = tmp->parent;
  4153. if (!parent)
  4154. break;
  4155. if (sd_parent_degenerate(tmp, parent))
  4156. tmp->parent = parent->parent;
  4157. }
  4158. if (sd && sd_degenerate(sd))
  4159. sd = sd->parent;
  4160. sched_domain_debug(sd, cpu);
  4161. rcu_assign_pointer(rq->sd, sd);
  4162. }
  4163. /* cpus with isolated domains */
  4164. cpumask_t __devinitdata cpu_isolated_map = CPU_MASK_NONE;
  4165. /* Setup the mask of cpus configured for isolated domains */
  4166. static int __init isolated_cpu_setup(char *str)
  4167. {
  4168. int ints[NR_CPUS], i;
  4169. str = get_options(str, ARRAY_SIZE(ints), ints);
  4170. cpus_clear(cpu_isolated_map);
  4171. for (i = 1; i <= ints[0]; i++)
  4172. if (ints[i] < NR_CPUS)
  4173. cpu_set(ints[i], cpu_isolated_map);
  4174. return 1;
  4175. }
  4176. __setup ("isolcpus=", isolated_cpu_setup);
  4177. /*
  4178. * init_sched_build_groups takes an array of groups, the cpumask we wish
  4179. * to span, and a pointer to a function which identifies what group a CPU
  4180. * belongs to. The return value of group_fn must be a valid index into the
  4181. * groups[] array, and must be >= 0 and < NR_CPUS (due to the fact that we
  4182. * keep track of groups covered with a cpumask_t).
  4183. *
  4184. * init_sched_build_groups will build a circular linked list of the groups
  4185. * covered by the given span, and will set each group's ->cpumask correctly,
  4186. * and ->cpu_power to 0.
  4187. */
  4188. void init_sched_build_groups(struct sched_group groups[],
  4189. cpumask_t span, int (*group_fn)(int cpu))
  4190. {
  4191. struct sched_group *first = NULL, *last = NULL;
  4192. cpumask_t covered = CPU_MASK_NONE;
  4193. int i;
  4194. for_each_cpu_mask(i, span) {
  4195. int group = group_fn(i);
  4196. struct sched_group *sg = &groups[group];
  4197. int j;
  4198. if (cpu_isset(i, covered))
  4199. continue;
  4200. sg->cpumask = CPU_MASK_NONE;
  4201. sg->cpu_power = 0;
  4202. for_each_cpu_mask(j, span) {
  4203. if (group_fn(j) != group)
  4204. continue;
  4205. cpu_set(j, covered);
  4206. cpu_set(j, sg->cpumask);
  4207. }
  4208. if (!first)
  4209. first = sg;
  4210. if (last)
  4211. last->next = sg;
  4212. last = sg;
  4213. }
  4214. last->next = first;
  4215. }
  4216. #ifdef ARCH_HAS_SCHED_DOMAIN
  4217. extern void build_sched_domains(const cpumask_t *cpu_map);
  4218. extern void arch_init_sched_domains(const cpumask_t *cpu_map);
  4219. extern void arch_destroy_sched_domains(const cpumask_t *cpu_map);
  4220. #else
  4221. #ifdef CONFIG_SCHED_SMT
  4222. static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
  4223. static struct sched_group sched_group_cpus[NR_CPUS];
  4224. static int cpu_to_cpu_group(int cpu)
  4225. {
  4226. return cpu;
  4227. }
  4228. #endif
  4229. static DEFINE_PER_CPU(struct sched_domain, phys_domains);
  4230. static struct sched_group sched_group_phys[NR_CPUS];
  4231. static int cpu_to_phys_group(int cpu)
  4232. {
  4233. #ifdef CONFIG_SCHED_SMT
  4234. return first_cpu(cpu_sibling_map[cpu]);
  4235. #else
  4236. return cpu;
  4237. #endif
  4238. }
  4239. #ifdef CONFIG_NUMA
  4240. static DEFINE_PER_CPU(struct sched_domain, node_domains);
  4241. static struct sched_group sched_group_nodes[MAX_NUMNODES];
  4242. static int cpu_to_node_group(int cpu)
  4243. {
  4244. return cpu_to_node(cpu);
  4245. }
  4246. #endif
  4247. #if defined(CONFIG_SCHED_SMT) && defined(CONFIG_NUMA)
  4248. /*
  4249. * The domains setup code relies on siblings not spanning
  4250. * multiple nodes. Make sure the architecture has a proper
  4251. * siblings map:
  4252. */
  4253. static void check_sibling_maps(void)
  4254. {
  4255. int i, j;
  4256. for_each_online_cpu(i) {
  4257. for_each_cpu_mask(j, cpu_sibling_map[i]) {
  4258. if (cpu_to_node(i) != cpu_to_node(j)) {
  4259. printk(KERN_INFO "warning: CPU %d siblings map "
  4260. "to different node - isolating "
  4261. "them.\n", i);
  4262. cpu_sibling_map[i] = cpumask_of_cpu(i);
  4263. break;
  4264. }
  4265. }
  4266. }
  4267. }
  4268. #endif
  4269. /*
  4270. * Build sched domains for a given set of cpus and attach the sched domains
  4271. * to the individual cpus
  4272. */
  4273. static void build_sched_domains(const cpumask_t *cpu_map)
  4274. {
  4275. int i;
  4276. /*
  4277. * Set up domains for cpus specified by the cpu_map.
  4278. */
  4279. for_each_cpu_mask(i, *cpu_map) {
  4280. int group;
  4281. struct sched_domain *sd = NULL, *p;
  4282. cpumask_t nodemask = node_to_cpumask(cpu_to_node(i));
  4283. cpus_and(nodemask, nodemask, *cpu_map);
  4284. #ifdef CONFIG_NUMA
  4285. sd = &per_cpu(node_domains, i);
  4286. group = cpu_to_node_group(i);
  4287. *sd = SD_NODE_INIT;
  4288. sd->span = *cpu_map;
  4289. sd->groups = &sched_group_nodes[group];
  4290. #endif
  4291. p = sd;
  4292. sd = &per_cpu(phys_domains, i);
  4293. group = cpu_to_phys_group(i);
  4294. *sd = SD_CPU_INIT;
  4295. sd->span = nodemask;
  4296. sd->parent = p;
  4297. sd->groups = &sched_group_phys[group];
  4298. #ifdef CONFIG_SCHED_SMT
  4299. p = sd;
  4300. sd = &per_cpu(cpu_domains, i);
  4301. group = cpu_to_cpu_group(i);
  4302. *sd = SD_SIBLING_INIT;
  4303. sd->span = cpu_sibling_map[i];
  4304. cpus_and(sd->span, sd->span, *cpu_map);
  4305. sd->parent = p;
  4306. sd->groups = &sched_group_cpus[group];
  4307. #endif
  4308. }
  4309. #ifdef CONFIG_SCHED_SMT
  4310. /* Set up CPU (sibling) groups */
  4311. for_each_online_cpu(i) {
  4312. cpumask_t this_sibling_map = cpu_sibling_map[i];
  4313. cpus_and(this_sibling_map, this_sibling_map, *cpu_map);
  4314. if (i != first_cpu(this_sibling_map))
  4315. continue;
  4316. init_sched_build_groups(sched_group_cpus, this_sibling_map,
  4317. &cpu_to_cpu_group);
  4318. }
  4319. #endif
  4320. /* Set up physical groups */
  4321. for (i = 0; i < MAX_NUMNODES; i++) {
  4322. cpumask_t nodemask = node_to_cpumask(i);
  4323. cpus_and(nodemask, nodemask, *cpu_map);
  4324. if (cpus_empty(nodemask))
  4325. continue;
  4326. init_sched_build_groups(sched_group_phys, nodemask,
  4327. &cpu_to_phys_group);
  4328. }
  4329. #ifdef CONFIG_NUMA
  4330. /* Set up node groups */
  4331. init_sched_build_groups(sched_group_nodes, *cpu_map,
  4332. &cpu_to_node_group);
  4333. #endif
  4334. /* Calculate CPU power for physical packages and nodes */
  4335. for_each_cpu_mask(i, *cpu_map) {
  4336. int power;
  4337. struct sched_domain *sd;
  4338. #ifdef CONFIG_SCHED_SMT
  4339. sd = &per_cpu(cpu_domains, i);
  4340. power = SCHED_LOAD_SCALE;
  4341. sd->groups->cpu_power = power;
  4342. #endif
  4343. sd = &per_cpu(phys_domains, i);
  4344. power = SCHED_LOAD_SCALE + SCHED_LOAD_SCALE *
  4345. (cpus_weight(sd->groups->cpumask)-1) / 10;
  4346. sd->groups->cpu_power = power;
  4347. #ifdef CONFIG_NUMA
  4348. if (i == first_cpu(sd->groups->cpumask)) {
  4349. /* Only add "power" once for each physical package. */
  4350. sd = &per_cpu(node_domains, i);
  4351. sd->groups->cpu_power += power;
  4352. }
  4353. #endif
  4354. }
  4355. /* Attach the domains */
  4356. for_each_cpu_mask(i, *cpu_map) {
  4357. struct sched_domain *sd;
  4358. #ifdef CONFIG_SCHED_SMT
  4359. sd = &per_cpu(cpu_domains, i);
  4360. #else
  4361. sd = &per_cpu(phys_domains, i);
  4362. #endif
  4363. cpu_attach_domain(sd, i);
  4364. }
  4365. }
  4366. /*
  4367. * Set up scheduler domains and groups. Callers must hold the hotplug lock.
  4368. */
  4369. static void arch_init_sched_domains(cpumask_t *cpu_map)
  4370. {
  4371. cpumask_t cpu_default_map;
  4372. #if defined(CONFIG_SCHED_SMT) && defined(CONFIG_NUMA)
  4373. check_sibling_maps();
  4374. #endif
  4375. /*
  4376. * Setup mask for cpus without special case scheduling requirements.
  4377. * For now this just excludes isolated cpus, but could be used to
  4378. * exclude other special cases in the future.
  4379. */
  4380. cpus_andnot(cpu_default_map, *cpu_map, cpu_isolated_map);
  4381. build_sched_domains(&cpu_default_map);
  4382. }
  4383. static void arch_destroy_sched_domains(const cpumask_t *cpu_map)
  4384. {
  4385. /* Do nothing: everything is statically allocated. */
  4386. }
  4387. #endif /* ARCH_HAS_SCHED_DOMAIN */
  4388. /*
  4389. * Detach sched domains from a group of cpus specified in cpu_map
  4390. * These cpus will now be attached to the NULL domain
  4391. */
  4392. static inline void detach_destroy_domains(const cpumask_t *cpu_map)
  4393. {
  4394. int i;
  4395. for_each_cpu_mask(i, *cpu_map)
  4396. cpu_attach_domain(NULL, i);
  4397. synchronize_sched();
  4398. arch_destroy_sched_domains(cpu_map);
  4399. }
  4400. /*
  4401. * Partition sched domains as specified by the cpumasks below.
  4402. * This attaches all cpus from the cpumasks to the NULL domain,
  4403. * waits for a RCU quiescent period, recalculates sched
  4404. * domain information and then attaches them back to the
  4405. * correct sched domains
  4406. * Call with hotplug lock held
  4407. */
  4408. void partition_sched_domains(cpumask_t *partition1, cpumask_t *partition2)
  4409. {
  4410. cpumask_t change_map;
  4411. cpus_and(*partition1, *partition1, cpu_online_map);
  4412. cpus_and(*partition2, *partition2, cpu_online_map);
  4413. cpus_or(change_map, *partition1, *partition2);
  4414. /* Detach sched domains from all of the affected cpus */
  4415. detach_destroy_domains(&change_map);
  4416. if (!cpus_empty(*partition1))
  4417. build_sched_domains(partition1);
  4418. if (!cpus_empty(*partition2))
  4419. build_sched_domains(partition2);
  4420. }
  4421. #ifdef CONFIG_HOTPLUG_CPU
  4422. /*
  4423. * Force a reinitialization of the sched domains hierarchy. The domains
  4424. * and groups cannot be updated in place without racing with the balancing
  4425. * code, so we temporarily attach all running cpus to the NULL domain
  4426. * which will prevent rebalancing while the sched domains are recalculated.
  4427. */
  4428. static int update_sched_domains(struct notifier_block *nfb,
  4429. unsigned long action, void *hcpu)
  4430. {
  4431. switch (action) {
  4432. case CPU_UP_PREPARE:
  4433. case CPU_DOWN_PREPARE:
  4434. detach_destroy_domains(&cpu_online_map);
  4435. return NOTIFY_OK;
  4436. case CPU_UP_CANCELED:
  4437. case CPU_DOWN_FAILED:
  4438. case CPU_ONLINE:
  4439. case CPU_DEAD:
  4440. /*
  4441. * Fall through and re-initialise the domains.
  4442. */
  4443. break;
  4444. default:
  4445. return NOTIFY_DONE;
  4446. }
  4447. /* The hotplug lock is already held by cpu_up/cpu_down */
  4448. arch_init_sched_domains(&cpu_online_map);
  4449. return NOTIFY_OK;
  4450. }
  4451. #endif
  4452. void __init sched_init_smp(void)
  4453. {
  4454. lock_cpu_hotplug();
  4455. arch_init_sched_domains(&cpu_online_map);
  4456. unlock_cpu_hotplug();
  4457. /* XXX: Theoretical race here - CPU may be hotplugged now */
  4458. hotcpu_notifier(update_sched_domains, 0);
  4459. }
  4460. #else
  4461. void __init sched_init_smp(void)
  4462. {
  4463. }
  4464. #endif /* CONFIG_SMP */
  4465. int in_sched_functions(unsigned long addr)
  4466. {
  4467. /* Linker adds these: start and end of __sched functions */
  4468. extern char __sched_text_start[], __sched_text_end[];
  4469. return in_lock_functions(addr) ||
  4470. (addr >= (unsigned long)__sched_text_start
  4471. && addr < (unsigned long)__sched_text_end);
  4472. }
  4473. void __init sched_init(void)
  4474. {
  4475. runqueue_t *rq;
  4476. int i, j, k;
  4477. for (i = 0; i < NR_CPUS; i++) {
  4478. prio_array_t *array;
  4479. rq = cpu_rq(i);
  4480. spin_lock_init(&rq->lock);
  4481. rq->nr_running = 0;
  4482. rq->active = rq->arrays;
  4483. rq->expired = rq->arrays + 1;
  4484. rq->best_expired_prio = MAX_PRIO;
  4485. #ifdef CONFIG_SMP
  4486. rq->sd = NULL;
  4487. for (j = 1; j < 3; j++)
  4488. rq->cpu_load[j] = 0;
  4489. rq->active_balance = 0;
  4490. rq->push_cpu = 0;
  4491. rq->migration_thread = NULL;
  4492. INIT_LIST_HEAD(&rq->migration_queue);
  4493. #endif
  4494. atomic_set(&rq->nr_iowait, 0);
  4495. for (j = 0; j < 2; j++) {
  4496. array = rq->arrays + j;
  4497. for (k = 0; k < MAX_PRIO; k++) {
  4498. INIT_LIST_HEAD(array->queue + k);
  4499. __clear_bit(k, array->bitmap);
  4500. }
  4501. // delimiter for bitsearch
  4502. __set_bit(MAX_PRIO, array->bitmap);
  4503. }
  4504. }
  4505. /*
  4506. * The boot idle thread does lazy MMU switching as well:
  4507. */
  4508. atomic_inc(&init_mm.mm_count);
  4509. enter_lazy_tlb(&init_mm, current);
  4510. /*
  4511. * Make us the idle thread. Technically, schedule() should not be
  4512. * called from this thread, however somewhere below it might be,
  4513. * but because we are the idle thread, we just pick up running again
  4514. * when this runqueue becomes "idle".
  4515. */
  4516. init_idle(current, smp_processor_id());
  4517. }
  4518. #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
  4519. void __might_sleep(char *file, int line)
  4520. {
  4521. #if defined(in_atomic)
  4522. static unsigned long prev_jiffy; /* ratelimiting */
  4523. if ((in_atomic() || irqs_disabled()) &&
  4524. system_state == SYSTEM_RUNNING && !oops_in_progress) {
  4525. if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
  4526. return;
  4527. prev_jiffy = jiffies;
  4528. printk(KERN_ERR "Debug: sleeping function called from invalid"
  4529. " context at %s:%d\n", file, line);
  4530. printk("in_atomic():%d, irqs_disabled():%d\n",
  4531. in_atomic(), irqs_disabled());
  4532. dump_stack();
  4533. }
  4534. #endif
  4535. }
  4536. EXPORT_SYMBOL(__might_sleep);
  4537. #endif
  4538. #ifdef CONFIG_MAGIC_SYSRQ
  4539. void normalize_rt_tasks(void)
  4540. {
  4541. struct task_struct *p;
  4542. prio_array_t *array;
  4543. unsigned long flags;
  4544. runqueue_t *rq;
  4545. read_lock_irq(&tasklist_lock);
  4546. for_each_process (p) {
  4547. if (!rt_task(p))
  4548. continue;
  4549. rq = task_rq_lock(p, &flags);
  4550. array = p->array;
  4551. if (array)
  4552. deactivate_task(p, task_rq(p));
  4553. __setscheduler(p, SCHED_NORMAL, 0);
  4554. if (array) {
  4555. __activate_task(p, task_rq(p));
  4556. resched_task(rq->curr);
  4557. }
  4558. task_rq_unlock(rq, &flags);
  4559. }
  4560. read_unlock_irq(&tasklist_lock);
  4561. }
  4562. #endif /* CONFIG_MAGIC_SYSRQ */