sched.c 124 KB

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