fair.c 136 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493
  1. /*
  2. * Completely Fair Scheduling (CFS) Class (SCHED_NORMAL/SCHED_BATCH)
  3. *
  4. * Copyright (C) 2007 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
  5. *
  6. * Interactivity improvements by Mike Galbraith
  7. * (C) 2007 Mike Galbraith <efault@gmx.de>
  8. *
  9. * Various enhancements by Dmitry Adamushko.
  10. * (C) 2007 Dmitry Adamushko <dmitry.adamushko@gmail.com>
  11. *
  12. * Group scheduling enhancements by Srivatsa Vaddagiri
  13. * Copyright IBM Corporation, 2007
  14. * Author: Srivatsa Vaddagiri <vatsa@linux.vnet.ibm.com>
  15. *
  16. * Scaled math optimizations by Thomas Gleixner
  17. * Copyright (C) 2007, Thomas Gleixner <tglx@linutronix.de>
  18. *
  19. * Adaptive scheduling granularity, math enhancements by Peter Zijlstra
  20. * Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra <pzijlstr@redhat.com>
  21. */
  22. #include <linux/latencytop.h>
  23. #include <linux/sched.h>
  24. #include <linux/cpumask.h>
  25. #include <linux/slab.h>
  26. #include <linux/profile.h>
  27. #include <linux/interrupt.h>
  28. #include <linux/mempolicy.h>
  29. #include <linux/task_work.h>
  30. #include <trace/events/sched.h>
  31. #include "sched.h"
  32. /*
  33. * Targeted preemption latency for CPU-bound tasks:
  34. * (default: 6ms * (1 + ilog(ncpus)), units: nanoseconds)
  35. *
  36. * NOTE: this latency value is not the same as the concept of
  37. * 'timeslice length' - timeslices in CFS are of variable length
  38. * and have no persistent notion like in traditional, time-slice
  39. * based scheduling concepts.
  40. *
  41. * (to see the precise effective timeslice length of your workload,
  42. * run vmstat and monitor the context-switches (cs) field)
  43. */
  44. unsigned int sysctl_sched_latency = 6000000ULL;
  45. unsigned int normalized_sysctl_sched_latency = 6000000ULL;
  46. /*
  47. * The initial- and re-scaling of tunables is configurable
  48. * (default SCHED_TUNABLESCALING_LOG = *(1+ilog(ncpus))
  49. *
  50. * Options are:
  51. * SCHED_TUNABLESCALING_NONE - unscaled, always *1
  52. * SCHED_TUNABLESCALING_LOG - scaled logarithmical, *1+ilog(ncpus)
  53. * SCHED_TUNABLESCALING_LINEAR - scaled linear, *ncpus
  54. */
  55. enum sched_tunable_scaling sysctl_sched_tunable_scaling
  56. = SCHED_TUNABLESCALING_LOG;
  57. /*
  58. * Minimal preemption granularity for CPU-bound tasks:
  59. * (default: 0.75 msec * (1 + ilog(ncpus)), units: nanoseconds)
  60. */
  61. unsigned int sysctl_sched_min_granularity = 750000ULL;
  62. unsigned int normalized_sysctl_sched_min_granularity = 750000ULL;
  63. /*
  64. * is kept at sysctl_sched_latency / sysctl_sched_min_granularity
  65. */
  66. static unsigned int sched_nr_latency = 8;
  67. /*
  68. * After fork, child runs first. If set to 0 (default) then
  69. * parent will (try to) run first.
  70. */
  71. unsigned int sysctl_sched_child_runs_first __read_mostly;
  72. /*
  73. * SCHED_OTHER wake-up granularity.
  74. * (default: 1 msec * (1 + ilog(ncpus)), units: nanoseconds)
  75. *
  76. * This option delays the preemption effects of decoupled workloads
  77. * and reduces their over-scheduling. Synchronous workloads will still
  78. * have immediate wakeup/sleep latencies.
  79. */
  80. unsigned int sysctl_sched_wakeup_granularity = 1000000UL;
  81. unsigned int normalized_sysctl_sched_wakeup_granularity = 1000000UL;
  82. const_debug unsigned int sysctl_sched_migration_cost = 500000UL;
  83. /*
  84. * The exponential sliding window over which load is averaged for shares
  85. * distribution.
  86. * (default: 10msec)
  87. */
  88. unsigned int __read_mostly sysctl_sched_shares_window = 10000000UL;
  89. #ifdef CONFIG_CFS_BANDWIDTH
  90. /*
  91. * Amount of runtime to allocate from global (tg) to local (per-cfs_rq) pool
  92. * each time a cfs_rq requests quota.
  93. *
  94. * Note: in the case that the slice exceeds the runtime remaining (either due
  95. * to consumption or the quota being specified to be smaller than the slice)
  96. * we will always only issue the remaining available time.
  97. *
  98. * default: 5 msec, units: microseconds
  99. */
  100. unsigned int sysctl_sched_cfs_bandwidth_slice = 5000UL;
  101. #endif
  102. /*
  103. * Increase the granularity value when there are more CPUs,
  104. * because with more CPUs the 'effective latency' as visible
  105. * to users decreases. But the relationship is not linear,
  106. * so pick a second-best guess by going with the log2 of the
  107. * number of CPUs.
  108. *
  109. * This idea comes from the SD scheduler of Con Kolivas:
  110. */
  111. static int get_update_sysctl_factor(void)
  112. {
  113. unsigned int cpus = min_t(int, num_online_cpus(), 8);
  114. unsigned int factor;
  115. switch (sysctl_sched_tunable_scaling) {
  116. case SCHED_TUNABLESCALING_NONE:
  117. factor = 1;
  118. break;
  119. case SCHED_TUNABLESCALING_LINEAR:
  120. factor = cpus;
  121. break;
  122. case SCHED_TUNABLESCALING_LOG:
  123. default:
  124. factor = 1 + ilog2(cpus);
  125. break;
  126. }
  127. return factor;
  128. }
  129. static void update_sysctl(void)
  130. {
  131. unsigned int factor = get_update_sysctl_factor();
  132. #define SET_SYSCTL(name) \
  133. (sysctl_##name = (factor) * normalized_sysctl_##name)
  134. SET_SYSCTL(sched_min_granularity);
  135. SET_SYSCTL(sched_latency);
  136. SET_SYSCTL(sched_wakeup_granularity);
  137. #undef SET_SYSCTL
  138. }
  139. void sched_init_granularity(void)
  140. {
  141. update_sysctl();
  142. }
  143. #if BITS_PER_LONG == 32
  144. # define WMULT_CONST (~0UL)
  145. #else
  146. # define WMULT_CONST (1UL << 32)
  147. #endif
  148. #define WMULT_SHIFT 32
  149. /*
  150. * Shift right and round:
  151. */
  152. #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
  153. /*
  154. * delta *= weight / lw
  155. */
  156. static unsigned long
  157. calc_delta_mine(unsigned long delta_exec, unsigned long weight,
  158. struct load_weight *lw)
  159. {
  160. u64 tmp;
  161. /*
  162. * weight can be less than 2^SCHED_LOAD_RESOLUTION for task group sched
  163. * entities since MIN_SHARES = 2. Treat weight as 1 if less than
  164. * 2^SCHED_LOAD_RESOLUTION.
  165. */
  166. if (likely(weight > (1UL << SCHED_LOAD_RESOLUTION)))
  167. tmp = (u64)delta_exec * scale_load_down(weight);
  168. else
  169. tmp = (u64)delta_exec;
  170. if (!lw->inv_weight) {
  171. unsigned long w = scale_load_down(lw->weight);
  172. if (BITS_PER_LONG > 32 && unlikely(w >= WMULT_CONST))
  173. lw->inv_weight = 1;
  174. else if (unlikely(!w))
  175. lw->inv_weight = WMULT_CONST;
  176. else
  177. lw->inv_weight = WMULT_CONST / w;
  178. }
  179. /*
  180. * Check whether we'd overflow the 64-bit multiplication:
  181. */
  182. if (unlikely(tmp > WMULT_CONST))
  183. tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
  184. WMULT_SHIFT/2);
  185. else
  186. tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);
  187. return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);
  188. }
  189. const struct sched_class fair_sched_class;
  190. /**************************************************************
  191. * CFS operations on generic schedulable entities:
  192. */
  193. #ifdef CONFIG_FAIR_GROUP_SCHED
  194. /* cpu runqueue to which this cfs_rq is attached */
  195. static inline struct rq *rq_of(struct cfs_rq *cfs_rq)
  196. {
  197. return cfs_rq->rq;
  198. }
  199. /* An entity is a task if it doesn't "own" a runqueue */
  200. #define entity_is_task(se) (!se->my_q)
  201. static inline struct task_struct *task_of(struct sched_entity *se)
  202. {
  203. #ifdef CONFIG_SCHED_DEBUG
  204. WARN_ON_ONCE(!entity_is_task(se));
  205. #endif
  206. return container_of(se, struct task_struct, se);
  207. }
  208. /* Walk up scheduling entities hierarchy */
  209. #define for_each_sched_entity(se) \
  210. for (; se; se = se->parent)
  211. static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
  212. {
  213. return p->se.cfs_rq;
  214. }
  215. /* runqueue on which this entity is (to be) queued */
  216. static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se)
  217. {
  218. return se->cfs_rq;
  219. }
  220. /* runqueue "owned" by this group */
  221. static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
  222. {
  223. return grp->my_q;
  224. }
  225. static inline void list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
  226. {
  227. if (!cfs_rq->on_list) {
  228. /*
  229. * Ensure we either appear before our parent (if already
  230. * enqueued) or force our parent to appear after us when it is
  231. * enqueued. The fact that we always enqueue bottom-up
  232. * reduces this to two cases.
  233. */
  234. if (cfs_rq->tg->parent &&
  235. cfs_rq->tg->parent->cfs_rq[cpu_of(rq_of(cfs_rq))]->on_list) {
  236. list_add_rcu(&cfs_rq->leaf_cfs_rq_list,
  237. &rq_of(cfs_rq)->leaf_cfs_rq_list);
  238. } else {
  239. list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
  240. &rq_of(cfs_rq)->leaf_cfs_rq_list);
  241. }
  242. cfs_rq->on_list = 1;
  243. }
  244. }
  245. static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
  246. {
  247. if (cfs_rq->on_list) {
  248. list_del_rcu(&cfs_rq->leaf_cfs_rq_list);
  249. cfs_rq->on_list = 0;
  250. }
  251. }
  252. /* Iterate thr' all leaf cfs_rq's on a runqueue */
  253. #define for_each_leaf_cfs_rq(rq, cfs_rq) \
  254. list_for_each_entry_rcu(cfs_rq, &rq->leaf_cfs_rq_list, leaf_cfs_rq_list)
  255. /* Do the two (enqueued) entities belong to the same group ? */
  256. static inline int
  257. is_same_group(struct sched_entity *se, struct sched_entity *pse)
  258. {
  259. if (se->cfs_rq == pse->cfs_rq)
  260. return 1;
  261. return 0;
  262. }
  263. static inline struct sched_entity *parent_entity(struct sched_entity *se)
  264. {
  265. return se->parent;
  266. }
  267. /* return depth at which a sched entity is present in the hierarchy */
  268. static inline int depth_se(struct sched_entity *se)
  269. {
  270. int depth = 0;
  271. for_each_sched_entity(se)
  272. depth++;
  273. return depth;
  274. }
  275. static void
  276. find_matching_se(struct sched_entity **se, struct sched_entity **pse)
  277. {
  278. int se_depth, pse_depth;
  279. /*
  280. * preemption test can be made between sibling entities who are in the
  281. * same cfs_rq i.e who have a common parent. Walk up the hierarchy of
  282. * both tasks until we find their ancestors who are siblings of common
  283. * parent.
  284. */
  285. /* First walk up until both entities are at same depth */
  286. se_depth = depth_se(*se);
  287. pse_depth = depth_se(*pse);
  288. while (se_depth > pse_depth) {
  289. se_depth--;
  290. *se = parent_entity(*se);
  291. }
  292. while (pse_depth > se_depth) {
  293. pse_depth--;
  294. *pse = parent_entity(*pse);
  295. }
  296. while (!is_same_group(*se, *pse)) {
  297. *se = parent_entity(*se);
  298. *pse = parent_entity(*pse);
  299. }
  300. }
  301. #else /* !CONFIG_FAIR_GROUP_SCHED */
  302. static inline struct task_struct *task_of(struct sched_entity *se)
  303. {
  304. return container_of(se, struct task_struct, se);
  305. }
  306. static inline struct rq *rq_of(struct cfs_rq *cfs_rq)
  307. {
  308. return container_of(cfs_rq, struct rq, cfs);
  309. }
  310. #define entity_is_task(se) 1
  311. #define for_each_sched_entity(se) \
  312. for (; se; se = NULL)
  313. static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
  314. {
  315. return &task_rq(p)->cfs;
  316. }
  317. static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se)
  318. {
  319. struct task_struct *p = task_of(se);
  320. struct rq *rq = task_rq(p);
  321. return &rq->cfs;
  322. }
  323. /* runqueue "owned" by this group */
  324. static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
  325. {
  326. return NULL;
  327. }
  328. static inline void list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
  329. {
  330. }
  331. static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
  332. {
  333. }
  334. #define for_each_leaf_cfs_rq(rq, cfs_rq) \
  335. for (cfs_rq = &rq->cfs; cfs_rq; cfs_rq = NULL)
  336. static inline int
  337. is_same_group(struct sched_entity *se, struct sched_entity *pse)
  338. {
  339. return 1;
  340. }
  341. static inline struct sched_entity *parent_entity(struct sched_entity *se)
  342. {
  343. return NULL;
  344. }
  345. static inline void
  346. find_matching_se(struct sched_entity **se, struct sched_entity **pse)
  347. {
  348. }
  349. #endif /* CONFIG_FAIR_GROUP_SCHED */
  350. static __always_inline
  351. void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, unsigned long delta_exec);
  352. /**************************************************************
  353. * Scheduling class tree data structure manipulation methods:
  354. */
  355. static inline u64 max_vruntime(u64 min_vruntime, u64 vruntime)
  356. {
  357. s64 delta = (s64)(vruntime - min_vruntime);
  358. if (delta > 0)
  359. min_vruntime = vruntime;
  360. return min_vruntime;
  361. }
  362. static inline u64 min_vruntime(u64 min_vruntime, u64 vruntime)
  363. {
  364. s64 delta = (s64)(vruntime - min_vruntime);
  365. if (delta < 0)
  366. min_vruntime = vruntime;
  367. return min_vruntime;
  368. }
  369. static inline int entity_before(struct sched_entity *a,
  370. struct sched_entity *b)
  371. {
  372. return (s64)(a->vruntime - b->vruntime) < 0;
  373. }
  374. static void update_min_vruntime(struct cfs_rq *cfs_rq)
  375. {
  376. u64 vruntime = cfs_rq->min_vruntime;
  377. if (cfs_rq->curr)
  378. vruntime = cfs_rq->curr->vruntime;
  379. if (cfs_rq->rb_leftmost) {
  380. struct sched_entity *se = rb_entry(cfs_rq->rb_leftmost,
  381. struct sched_entity,
  382. run_node);
  383. if (!cfs_rq->curr)
  384. vruntime = se->vruntime;
  385. else
  386. vruntime = min_vruntime(vruntime, se->vruntime);
  387. }
  388. cfs_rq->min_vruntime = max_vruntime(cfs_rq->min_vruntime, vruntime);
  389. #ifndef CONFIG_64BIT
  390. smp_wmb();
  391. cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
  392. #endif
  393. }
  394. /*
  395. * Enqueue an entity into the rb-tree:
  396. */
  397. static void __enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
  398. {
  399. struct rb_node **link = &cfs_rq->tasks_timeline.rb_node;
  400. struct rb_node *parent = NULL;
  401. struct sched_entity *entry;
  402. int leftmost = 1;
  403. /*
  404. * Find the right place in the rbtree:
  405. */
  406. while (*link) {
  407. parent = *link;
  408. entry = rb_entry(parent, struct sched_entity, run_node);
  409. /*
  410. * We dont care about collisions. Nodes with
  411. * the same key stay together.
  412. */
  413. if (entity_before(se, entry)) {
  414. link = &parent->rb_left;
  415. } else {
  416. link = &parent->rb_right;
  417. leftmost = 0;
  418. }
  419. }
  420. /*
  421. * Maintain a cache of leftmost tree entries (it is frequently
  422. * used):
  423. */
  424. if (leftmost)
  425. cfs_rq->rb_leftmost = &se->run_node;
  426. rb_link_node(&se->run_node, parent, link);
  427. rb_insert_color(&se->run_node, &cfs_rq->tasks_timeline);
  428. }
  429. static void __dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
  430. {
  431. if (cfs_rq->rb_leftmost == &se->run_node) {
  432. struct rb_node *next_node;
  433. next_node = rb_next(&se->run_node);
  434. cfs_rq->rb_leftmost = next_node;
  435. }
  436. rb_erase(&se->run_node, &cfs_rq->tasks_timeline);
  437. }
  438. struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq)
  439. {
  440. struct rb_node *left = cfs_rq->rb_leftmost;
  441. if (!left)
  442. return NULL;
  443. return rb_entry(left, struct sched_entity, run_node);
  444. }
  445. static struct sched_entity *__pick_next_entity(struct sched_entity *se)
  446. {
  447. struct rb_node *next = rb_next(&se->run_node);
  448. if (!next)
  449. return NULL;
  450. return rb_entry(next, struct sched_entity, run_node);
  451. }
  452. #ifdef CONFIG_SCHED_DEBUG
  453. struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq)
  454. {
  455. struct rb_node *last = rb_last(&cfs_rq->tasks_timeline);
  456. if (!last)
  457. return NULL;
  458. return rb_entry(last, struct sched_entity, run_node);
  459. }
  460. /**************************************************************
  461. * Scheduling class statistics methods:
  462. */
  463. int sched_proc_update_handler(struct ctl_table *table, int write,
  464. void __user *buffer, size_t *lenp,
  465. loff_t *ppos)
  466. {
  467. int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
  468. int factor = get_update_sysctl_factor();
  469. if (ret || !write)
  470. return ret;
  471. sched_nr_latency = DIV_ROUND_UP(sysctl_sched_latency,
  472. sysctl_sched_min_granularity);
  473. #define WRT_SYSCTL(name) \
  474. (normalized_sysctl_##name = sysctl_##name / (factor))
  475. WRT_SYSCTL(sched_min_granularity);
  476. WRT_SYSCTL(sched_latency);
  477. WRT_SYSCTL(sched_wakeup_granularity);
  478. #undef WRT_SYSCTL
  479. return 0;
  480. }
  481. #endif
  482. /*
  483. * delta /= w
  484. */
  485. static inline unsigned long
  486. calc_delta_fair(unsigned long delta, struct sched_entity *se)
  487. {
  488. if (unlikely(se->load.weight != NICE_0_LOAD))
  489. delta = calc_delta_mine(delta, NICE_0_LOAD, &se->load);
  490. return delta;
  491. }
  492. /*
  493. * The idea is to set a period in which each task runs once.
  494. *
  495. * When there are too many tasks (sched_nr_latency) we have to stretch
  496. * this period because otherwise the slices get too small.
  497. *
  498. * p = (nr <= nl) ? l : l*nr/nl
  499. */
  500. static u64 __sched_period(unsigned long nr_running)
  501. {
  502. u64 period = sysctl_sched_latency;
  503. unsigned long nr_latency = sched_nr_latency;
  504. if (unlikely(nr_running > nr_latency)) {
  505. period = sysctl_sched_min_granularity;
  506. period *= nr_running;
  507. }
  508. return period;
  509. }
  510. /*
  511. * We calculate the wall-time slice from the period by taking a part
  512. * proportional to the weight.
  513. *
  514. * s = p*P[w/rw]
  515. */
  516. static u64 sched_slice(struct cfs_rq *cfs_rq, struct sched_entity *se)
  517. {
  518. u64 slice = __sched_period(cfs_rq->nr_running + !se->on_rq);
  519. for_each_sched_entity(se) {
  520. struct load_weight *load;
  521. struct load_weight lw;
  522. cfs_rq = cfs_rq_of(se);
  523. load = &cfs_rq->load;
  524. if (unlikely(!se->on_rq)) {
  525. lw = cfs_rq->load;
  526. update_load_add(&lw, se->load.weight);
  527. load = &lw;
  528. }
  529. slice = calc_delta_mine(slice, se->load.weight, load);
  530. }
  531. return slice;
  532. }
  533. /*
  534. * We calculate the vruntime slice of a to be inserted task
  535. *
  536. * vs = s/w
  537. */
  538. static u64 sched_vslice(struct cfs_rq *cfs_rq, struct sched_entity *se)
  539. {
  540. return calc_delta_fair(sched_slice(cfs_rq, se), se);
  541. }
  542. static void update_cfs_load(struct cfs_rq *cfs_rq, int global_update);
  543. static void update_cfs_shares(struct cfs_rq *cfs_rq);
  544. /*
  545. * Update the current task's runtime statistics. Skip current tasks that
  546. * are not in our scheduling class.
  547. */
  548. static inline void
  549. __update_curr(struct cfs_rq *cfs_rq, struct sched_entity *curr,
  550. unsigned long delta_exec)
  551. {
  552. unsigned long delta_exec_weighted;
  553. schedstat_set(curr->statistics.exec_max,
  554. max((u64)delta_exec, curr->statistics.exec_max));
  555. curr->sum_exec_runtime += delta_exec;
  556. schedstat_add(cfs_rq, exec_clock, delta_exec);
  557. delta_exec_weighted = calc_delta_fair(delta_exec, curr);
  558. curr->vruntime += delta_exec_weighted;
  559. update_min_vruntime(cfs_rq);
  560. #if defined CONFIG_SMP && defined CONFIG_FAIR_GROUP_SCHED
  561. cfs_rq->load_unacc_exec_time += delta_exec;
  562. #endif
  563. }
  564. static void update_curr(struct cfs_rq *cfs_rq)
  565. {
  566. struct sched_entity *curr = cfs_rq->curr;
  567. u64 now = rq_of(cfs_rq)->clock_task;
  568. unsigned long delta_exec;
  569. if (unlikely(!curr))
  570. return;
  571. /*
  572. * Get the amount of time the current task was running
  573. * since the last time we changed load (this cannot
  574. * overflow on 32 bits):
  575. */
  576. delta_exec = (unsigned long)(now - curr->exec_start);
  577. if (!delta_exec)
  578. return;
  579. __update_curr(cfs_rq, curr, delta_exec);
  580. curr->exec_start = now;
  581. if (entity_is_task(curr)) {
  582. struct task_struct *curtask = task_of(curr);
  583. trace_sched_stat_runtime(curtask, delta_exec, curr->vruntime);
  584. cpuacct_charge(curtask, delta_exec);
  585. account_group_exec_runtime(curtask, delta_exec);
  586. }
  587. account_cfs_rq_runtime(cfs_rq, delta_exec);
  588. }
  589. static inline void
  590. update_stats_wait_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
  591. {
  592. schedstat_set(se->statistics.wait_start, rq_of(cfs_rq)->clock);
  593. }
  594. /*
  595. * Task is being enqueued - update stats:
  596. */
  597. static void update_stats_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
  598. {
  599. /*
  600. * Are we enqueueing a waiting task? (for current tasks
  601. * a dequeue/enqueue event is a NOP)
  602. */
  603. if (se != cfs_rq->curr)
  604. update_stats_wait_start(cfs_rq, se);
  605. }
  606. static void
  607. update_stats_wait_end(struct cfs_rq *cfs_rq, struct sched_entity *se)
  608. {
  609. schedstat_set(se->statistics.wait_max, max(se->statistics.wait_max,
  610. rq_of(cfs_rq)->clock - se->statistics.wait_start));
  611. schedstat_set(se->statistics.wait_count, se->statistics.wait_count + 1);
  612. schedstat_set(se->statistics.wait_sum, se->statistics.wait_sum +
  613. rq_of(cfs_rq)->clock - se->statistics.wait_start);
  614. #ifdef CONFIG_SCHEDSTATS
  615. if (entity_is_task(se)) {
  616. trace_sched_stat_wait(task_of(se),
  617. rq_of(cfs_rq)->clock - se->statistics.wait_start);
  618. }
  619. #endif
  620. schedstat_set(se->statistics.wait_start, 0);
  621. }
  622. static inline void
  623. update_stats_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
  624. {
  625. /*
  626. * Mark the end of the wait period if dequeueing a
  627. * waiting task:
  628. */
  629. if (se != cfs_rq->curr)
  630. update_stats_wait_end(cfs_rq, se);
  631. }
  632. /*
  633. * We are picking a new current task - update its stats:
  634. */
  635. static inline void
  636. update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
  637. {
  638. /*
  639. * We are starting a new run period:
  640. */
  641. se->exec_start = rq_of(cfs_rq)->clock_task;
  642. }
  643. /**************************************************
  644. * Scheduling class queueing methods:
  645. */
  646. #ifdef CONFIG_NUMA_BALANCING
  647. /*
  648. * numa task sample period in ms: 5s
  649. */
  650. unsigned int sysctl_numa_balancing_scan_period_min = 5000;
  651. unsigned int sysctl_numa_balancing_scan_period_max = 5000*16;
  652. static void task_numa_placement(struct task_struct *p)
  653. {
  654. int seq = ACCESS_ONCE(p->mm->numa_scan_seq);
  655. if (p->numa_scan_seq == seq)
  656. return;
  657. p->numa_scan_seq = seq;
  658. /* FIXME: Scheduling placement policy hints go here */
  659. }
  660. /*
  661. * Got a PROT_NONE fault for a page on @node.
  662. */
  663. void task_numa_fault(int node, int pages)
  664. {
  665. struct task_struct *p = current;
  666. /* FIXME: Allocate task-specific structure for placement policy here */
  667. task_numa_placement(p);
  668. }
  669. /*
  670. * The expensive part of numa migration is done from task_work context.
  671. * Triggered from task_tick_numa().
  672. */
  673. void task_numa_work(struct callback_head *work)
  674. {
  675. unsigned long migrate, next_scan, now = jiffies;
  676. struct task_struct *p = current;
  677. struct mm_struct *mm = p->mm;
  678. WARN_ON_ONCE(p != container_of(work, struct task_struct, numa_work));
  679. work->next = work; /* protect against double add */
  680. /*
  681. * Who cares about NUMA placement when they're dying.
  682. *
  683. * NOTE: make sure not to dereference p->mm before this check,
  684. * exit_task_work() happens _after_ exit_mm() so we could be called
  685. * without p->mm even though we still had it when we enqueued this
  686. * work.
  687. */
  688. if (p->flags & PF_EXITING)
  689. return;
  690. /*
  691. * Enforce maximal scan/migration frequency..
  692. */
  693. migrate = mm->numa_next_scan;
  694. if (time_before(now, migrate))
  695. return;
  696. if (p->numa_scan_period == 0)
  697. p->numa_scan_period = sysctl_numa_balancing_scan_period_min;
  698. next_scan = now + 2*msecs_to_jiffies(p->numa_scan_period);
  699. if (cmpxchg(&mm->numa_next_scan, migrate, next_scan) != migrate)
  700. return;
  701. ACCESS_ONCE(mm->numa_scan_seq)++;
  702. {
  703. struct vm_area_struct *vma;
  704. down_read(&mm->mmap_sem);
  705. for (vma = mm->mmap; vma; vma = vma->vm_next) {
  706. if (!vma_migratable(vma))
  707. continue;
  708. change_prot_numa(vma, vma->vm_start, vma->vm_end);
  709. }
  710. up_read(&mm->mmap_sem);
  711. }
  712. }
  713. /*
  714. * Drive the periodic memory faults..
  715. */
  716. void task_tick_numa(struct rq *rq, struct task_struct *curr)
  717. {
  718. struct callback_head *work = &curr->numa_work;
  719. u64 period, now;
  720. /*
  721. * We don't care about NUMA placement if we don't have memory.
  722. */
  723. if (!curr->mm || (curr->flags & PF_EXITING) || work->next != work)
  724. return;
  725. /*
  726. * Using runtime rather than walltime has the dual advantage that
  727. * we (mostly) drive the selection from busy threads and that the
  728. * task needs to have done some actual work before we bother with
  729. * NUMA placement.
  730. */
  731. now = curr->se.sum_exec_runtime;
  732. period = (u64)curr->numa_scan_period * NSEC_PER_MSEC;
  733. if (now - curr->node_stamp > period) {
  734. curr->node_stamp = now;
  735. if (!time_before(jiffies, curr->mm->numa_next_scan)) {
  736. init_task_work(work, task_numa_work); /* TODO: move this into sched_fork() */
  737. task_work_add(curr, work, true);
  738. }
  739. }
  740. }
  741. #else
  742. static void task_tick_numa(struct rq *rq, struct task_struct *curr)
  743. {
  744. }
  745. #endif /* CONFIG_NUMA_BALANCING */
  746. static void
  747. account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
  748. {
  749. update_load_add(&cfs_rq->load, se->load.weight);
  750. if (!parent_entity(se))
  751. update_load_add(&rq_of(cfs_rq)->load, se->load.weight);
  752. #ifdef CONFIG_SMP
  753. if (entity_is_task(se))
  754. list_add(&se->group_node, &rq_of(cfs_rq)->cfs_tasks);
  755. #endif
  756. cfs_rq->nr_running++;
  757. }
  758. static void
  759. account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
  760. {
  761. update_load_sub(&cfs_rq->load, se->load.weight);
  762. if (!parent_entity(se))
  763. update_load_sub(&rq_of(cfs_rq)->load, se->load.weight);
  764. if (entity_is_task(se))
  765. list_del_init(&se->group_node);
  766. cfs_rq->nr_running--;
  767. }
  768. #ifdef CONFIG_FAIR_GROUP_SCHED
  769. /* we need this in update_cfs_load and load-balance functions below */
  770. static inline int throttled_hierarchy(struct cfs_rq *cfs_rq);
  771. # ifdef CONFIG_SMP
  772. static void update_cfs_rq_load_contribution(struct cfs_rq *cfs_rq,
  773. int global_update)
  774. {
  775. struct task_group *tg = cfs_rq->tg;
  776. long load_avg;
  777. load_avg = div64_u64(cfs_rq->load_avg, cfs_rq->load_period+1);
  778. load_avg -= cfs_rq->load_contribution;
  779. if (global_update || abs(load_avg) > cfs_rq->load_contribution / 8) {
  780. atomic_add(load_avg, &tg->load_weight);
  781. cfs_rq->load_contribution += load_avg;
  782. }
  783. }
  784. static void update_cfs_load(struct cfs_rq *cfs_rq, int global_update)
  785. {
  786. u64 period = sysctl_sched_shares_window;
  787. u64 now, delta;
  788. unsigned long load = cfs_rq->load.weight;
  789. if (cfs_rq->tg == &root_task_group || throttled_hierarchy(cfs_rq))
  790. return;
  791. now = rq_of(cfs_rq)->clock_task;
  792. delta = now - cfs_rq->load_stamp;
  793. /* truncate load history at 4 idle periods */
  794. if (cfs_rq->load_stamp > cfs_rq->load_last &&
  795. now - cfs_rq->load_last > 4 * period) {
  796. cfs_rq->load_period = 0;
  797. cfs_rq->load_avg = 0;
  798. delta = period - 1;
  799. }
  800. cfs_rq->load_stamp = now;
  801. cfs_rq->load_unacc_exec_time = 0;
  802. cfs_rq->load_period += delta;
  803. if (load) {
  804. cfs_rq->load_last = now;
  805. cfs_rq->load_avg += delta * load;
  806. }
  807. /* consider updating load contribution on each fold or truncate */
  808. if (global_update || cfs_rq->load_period > period
  809. || !cfs_rq->load_period)
  810. update_cfs_rq_load_contribution(cfs_rq, global_update);
  811. while (cfs_rq->load_period > period) {
  812. /*
  813. * Inline assembly required to prevent the compiler
  814. * optimising this loop into a divmod call.
  815. * See __iter_div_u64_rem() for another example of this.
  816. */
  817. asm("" : "+rm" (cfs_rq->load_period));
  818. cfs_rq->load_period /= 2;
  819. cfs_rq->load_avg /= 2;
  820. }
  821. if (!cfs_rq->curr && !cfs_rq->nr_running && !cfs_rq->load_avg)
  822. list_del_leaf_cfs_rq(cfs_rq);
  823. }
  824. static inline long calc_tg_weight(struct task_group *tg, struct cfs_rq *cfs_rq)
  825. {
  826. long tg_weight;
  827. /*
  828. * Use this CPU's actual weight instead of the last load_contribution
  829. * to gain a more accurate current total weight. See
  830. * update_cfs_rq_load_contribution().
  831. */
  832. tg_weight = atomic_read(&tg->load_weight);
  833. tg_weight -= cfs_rq->load_contribution;
  834. tg_weight += cfs_rq->load.weight;
  835. return tg_weight;
  836. }
  837. static long calc_cfs_shares(struct cfs_rq *cfs_rq, struct task_group *tg)
  838. {
  839. long tg_weight, load, shares;
  840. tg_weight = calc_tg_weight(tg, cfs_rq);
  841. load = cfs_rq->load.weight;
  842. shares = (tg->shares * load);
  843. if (tg_weight)
  844. shares /= tg_weight;
  845. if (shares < MIN_SHARES)
  846. shares = MIN_SHARES;
  847. if (shares > tg->shares)
  848. shares = tg->shares;
  849. return shares;
  850. }
  851. static void update_entity_shares_tick(struct cfs_rq *cfs_rq)
  852. {
  853. if (cfs_rq->load_unacc_exec_time > sysctl_sched_shares_window) {
  854. update_cfs_load(cfs_rq, 0);
  855. update_cfs_shares(cfs_rq);
  856. }
  857. }
  858. # else /* CONFIG_SMP */
  859. static void update_cfs_load(struct cfs_rq *cfs_rq, int global_update)
  860. {
  861. }
  862. static inline long calc_cfs_shares(struct cfs_rq *cfs_rq, struct task_group *tg)
  863. {
  864. return tg->shares;
  865. }
  866. static inline void update_entity_shares_tick(struct cfs_rq *cfs_rq)
  867. {
  868. }
  869. # endif /* CONFIG_SMP */
  870. static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se,
  871. unsigned long weight)
  872. {
  873. if (se->on_rq) {
  874. /* commit outstanding execution time */
  875. if (cfs_rq->curr == se)
  876. update_curr(cfs_rq);
  877. account_entity_dequeue(cfs_rq, se);
  878. }
  879. update_load_set(&se->load, weight);
  880. if (se->on_rq)
  881. account_entity_enqueue(cfs_rq, se);
  882. }
  883. static void update_cfs_shares(struct cfs_rq *cfs_rq)
  884. {
  885. struct task_group *tg;
  886. struct sched_entity *se;
  887. long shares;
  888. tg = cfs_rq->tg;
  889. se = tg->se[cpu_of(rq_of(cfs_rq))];
  890. if (!se || throttled_hierarchy(cfs_rq))
  891. return;
  892. #ifndef CONFIG_SMP
  893. if (likely(se->load.weight == tg->shares))
  894. return;
  895. #endif
  896. shares = calc_cfs_shares(cfs_rq, tg);
  897. reweight_entity(cfs_rq_of(se), se, shares);
  898. }
  899. #else /* CONFIG_FAIR_GROUP_SCHED */
  900. static void update_cfs_load(struct cfs_rq *cfs_rq, int global_update)
  901. {
  902. }
  903. static inline void update_cfs_shares(struct cfs_rq *cfs_rq)
  904. {
  905. }
  906. static inline void update_entity_shares_tick(struct cfs_rq *cfs_rq)
  907. {
  908. }
  909. #endif /* CONFIG_FAIR_GROUP_SCHED */
  910. static void enqueue_sleeper(struct cfs_rq *cfs_rq, struct sched_entity *se)
  911. {
  912. #ifdef CONFIG_SCHEDSTATS
  913. struct task_struct *tsk = NULL;
  914. if (entity_is_task(se))
  915. tsk = task_of(se);
  916. if (se->statistics.sleep_start) {
  917. u64 delta = rq_of(cfs_rq)->clock - se->statistics.sleep_start;
  918. if ((s64)delta < 0)
  919. delta = 0;
  920. if (unlikely(delta > se->statistics.sleep_max))
  921. se->statistics.sleep_max = delta;
  922. se->statistics.sleep_start = 0;
  923. se->statistics.sum_sleep_runtime += delta;
  924. if (tsk) {
  925. account_scheduler_latency(tsk, delta >> 10, 1);
  926. trace_sched_stat_sleep(tsk, delta);
  927. }
  928. }
  929. if (se->statistics.block_start) {
  930. u64 delta = rq_of(cfs_rq)->clock - se->statistics.block_start;
  931. if ((s64)delta < 0)
  932. delta = 0;
  933. if (unlikely(delta > se->statistics.block_max))
  934. se->statistics.block_max = delta;
  935. se->statistics.block_start = 0;
  936. se->statistics.sum_sleep_runtime += delta;
  937. if (tsk) {
  938. if (tsk->in_iowait) {
  939. se->statistics.iowait_sum += delta;
  940. se->statistics.iowait_count++;
  941. trace_sched_stat_iowait(tsk, delta);
  942. }
  943. trace_sched_stat_blocked(tsk, delta);
  944. /*
  945. * Blocking time is in units of nanosecs, so shift by
  946. * 20 to get a milliseconds-range estimation of the
  947. * amount of time that the task spent sleeping:
  948. */
  949. if (unlikely(prof_on == SLEEP_PROFILING)) {
  950. profile_hits(SLEEP_PROFILING,
  951. (void *)get_wchan(tsk),
  952. delta >> 20);
  953. }
  954. account_scheduler_latency(tsk, delta >> 10, 0);
  955. }
  956. }
  957. #endif
  958. }
  959. static void check_spread(struct cfs_rq *cfs_rq, struct sched_entity *se)
  960. {
  961. #ifdef CONFIG_SCHED_DEBUG
  962. s64 d = se->vruntime - cfs_rq->min_vruntime;
  963. if (d < 0)
  964. d = -d;
  965. if (d > 3*sysctl_sched_latency)
  966. schedstat_inc(cfs_rq, nr_spread_over);
  967. #endif
  968. }
  969. static void
  970. place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int initial)
  971. {
  972. u64 vruntime = cfs_rq->min_vruntime;
  973. /*
  974. * The 'current' period is already promised to the current tasks,
  975. * however the extra weight of the new task will slow them down a
  976. * little, place the new task so that it fits in the slot that
  977. * stays open at the end.
  978. */
  979. if (initial && sched_feat(START_DEBIT))
  980. vruntime += sched_vslice(cfs_rq, se);
  981. /* sleeps up to a single latency don't count. */
  982. if (!initial) {
  983. unsigned long thresh = sysctl_sched_latency;
  984. /*
  985. * Halve their sleep time's effect, to allow
  986. * for a gentler effect of sleepers:
  987. */
  988. if (sched_feat(GENTLE_FAIR_SLEEPERS))
  989. thresh >>= 1;
  990. vruntime -= thresh;
  991. }
  992. /* ensure we never gain time by being placed backwards. */
  993. vruntime = max_vruntime(se->vruntime, vruntime);
  994. se->vruntime = vruntime;
  995. }
  996. static void check_enqueue_throttle(struct cfs_rq *cfs_rq);
  997. static void
  998. enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
  999. {
  1000. /*
  1001. * Update the normalized vruntime before updating min_vruntime
  1002. * through callig update_curr().
  1003. */
  1004. if (!(flags & ENQUEUE_WAKEUP) || (flags & ENQUEUE_WAKING))
  1005. se->vruntime += cfs_rq->min_vruntime;
  1006. /*
  1007. * Update run-time statistics of the 'current'.
  1008. */
  1009. update_curr(cfs_rq);
  1010. update_cfs_load(cfs_rq, 0);
  1011. account_entity_enqueue(cfs_rq, se);
  1012. update_cfs_shares(cfs_rq);
  1013. if (flags & ENQUEUE_WAKEUP) {
  1014. place_entity(cfs_rq, se, 0);
  1015. enqueue_sleeper(cfs_rq, se);
  1016. }
  1017. update_stats_enqueue(cfs_rq, se);
  1018. check_spread(cfs_rq, se);
  1019. if (se != cfs_rq->curr)
  1020. __enqueue_entity(cfs_rq, se);
  1021. se->on_rq = 1;
  1022. if (cfs_rq->nr_running == 1) {
  1023. list_add_leaf_cfs_rq(cfs_rq);
  1024. check_enqueue_throttle(cfs_rq);
  1025. }
  1026. }
  1027. static void __clear_buddies_last(struct sched_entity *se)
  1028. {
  1029. for_each_sched_entity(se) {
  1030. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  1031. if (cfs_rq->last == se)
  1032. cfs_rq->last = NULL;
  1033. else
  1034. break;
  1035. }
  1036. }
  1037. static void __clear_buddies_next(struct sched_entity *se)
  1038. {
  1039. for_each_sched_entity(se) {
  1040. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  1041. if (cfs_rq->next == se)
  1042. cfs_rq->next = NULL;
  1043. else
  1044. break;
  1045. }
  1046. }
  1047. static void __clear_buddies_skip(struct sched_entity *se)
  1048. {
  1049. for_each_sched_entity(se) {
  1050. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  1051. if (cfs_rq->skip == se)
  1052. cfs_rq->skip = NULL;
  1053. else
  1054. break;
  1055. }
  1056. }
  1057. static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
  1058. {
  1059. if (cfs_rq->last == se)
  1060. __clear_buddies_last(se);
  1061. if (cfs_rq->next == se)
  1062. __clear_buddies_next(se);
  1063. if (cfs_rq->skip == se)
  1064. __clear_buddies_skip(se);
  1065. }
  1066. static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq);
  1067. static void
  1068. dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
  1069. {
  1070. /*
  1071. * Update run-time statistics of the 'current'.
  1072. */
  1073. update_curr(cfs_rq);
  1074. update_stats_dequeue(cfs_rq, se);
  1075. if (flags & DEQUEUE_SLEEP) {
  1076. #ifdef CONFIG_SCHEDSTATS
  1077. if (entity_is_task(se)) {
  1078. struct task_struct *tsk = task_of(se);
  1079. if (tsk->state & TASK_INTERRUPTIBLE)
  1080. se->statistics.sleep_start = rq_of(cfs_rq)->clock;
  1081. if (tsk->state & TASK_UNINTERRUPTIBLE)
  1082. se->statistics.block_start = rq_of(cfs_rq)->clock;
  1083. }
  1084. #endif
  1085. }
  1086. clear_buddies(cfs_rq, se);
  1087. if (se != cfs_rq->curr)
  1088. __dequeue_entity(cfs_rq, se);
  1089. se->on_rq = 0;
  1090. update_cfs_load(cfs_rq, 0);
  1091. account_entity_dequeue(cfs_rq, se);
  1092. /*
  1093. * Normalize the entity after updating the min_vruntime because the
  1094. * update can refer to the ->curr item and we need to reflect this
  1095. * movement in our normalized position.
  1096. */
  1097. if (!(flags & DEQUEUE_SLEEP))
  1098. se->vruntime -= cfs_rq->min_vruntime;
  1099. /* return excess runtime on last dequeue */
  1100. return_cfs_rq_runtime(cfs_rq);
  1101. update_min_vruntime(cfs_rq);
  1102. update_cfs_shares(cfs_rq);
  1103. }
  1104. /*
  1105. * Preempt the current task with a newly woken task if needed:
  1106. */
  1107. static void
  1108. check_preempt_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr)
  1109. {
  1110. unsigned long ideal_runtime, delta_exec;
  1111. struct sched_entity *se;
  1112. s64 delta;
  1113. ideal_runtime = sched_slice(cfs_rq, curr);
  1114. delta_exec = curr->sum_exec_runtime - curr->prev_sum_exec_runtime;
  1115. if (delta_exec > ideal_runtime) {
  1116. resched_task(rq_of(cfs_rq)->curr);
  1117. /*
  1118. * The current task ran long enough, ensure it doesn't get
  1119. * re-elected due to buddy favours.
  1120. */
  1121. clear_buddies(cfs_rq, curr);
  1122. return;
  1123. }
  1124. /*
  1125. * Ensure that a task that missed wakeup preemption by a
  1126. * narrow margin doesn't have to wait for a full slice.
  1127. * This also mitigates buddy induced latencies under load.
  1128. */
  1129. if (delta_exec < sysctl_sched_min_granularity)
  1130. return;
  1131. se = __pick_first_entity(cfs_rq);
  1132. delta = curr->vruntime - se->vruntime;
  1133. if (delta < 0)
  1134. return;
  1135. if (delta > ideal_runtime)
  1136. resched_task(rq_of(cfs_rq)->curr);
  1137. }
  1138. static void
  1139. set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
  1140. {
  1141. /* 'current' is not kept within the tree. */
  1142. if (se->on_rq) {
  1143. /*
  1144. * Any task has to be enqueued before it get to execute on
  1145. * a CPU. So account for the time it spent waiting on the
  1146. * runqueue.
  1147. */
  1148. update_stats_wait_end(cfs_rq, se);
  1149. __dequeue_entity(cfs_rq, se);
  1150. }
  1151. update_stats_curr_start(cfs_rq, se);
  1152. cfs_rq->curr = se;
  1153. #ifdef CONFIG_SCHEDSTATS
  1154. /*
  1155. * Track our maximum slice length, if the CPU's load is at
  1156. * least twice that of our own weight (i.e. dont track it
  1157. * when there are only lesser-weight tasks around):
  1158. */
  1159. if (rq_of(cfs_rq)->load.weight >= 2*se->load.weight) {
  1160. se->statistics.slice_max = max(se->statistics.slice_max,
  1161. se->sum_exec_runtime - se->prev_sum_exec_runtime);
  1162. }
  1163. #endif
  1164. se->prev_sum_exec_runtime = se->sum_exec_runtime;
  1165. }
  1166. static int
  1167. wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se);
  1168. /*
  1169. * Pick the next process, keeping these things in mind, in this order:
  1170. * 1) keep things fair between processes/task groups
  1171. * 2) pick the "next" process, since someone really wants that to run
  1172. * 3) pick the "last" process, for cache locality
  1173. * 4) do not run the "skip" process, if something else is available
  1174. */
  1175. static struct sched_entity *pick_next_entity(struct cfs_rq *cfs_rq)
  1176. {
  1177. struct sched_entity *se = __pick_first_entity(cfs_rq);
  1178. struct sched_entity *left = se;
  1179. /*
  1180. * Avoid running the skip buddy, if running something else can
  1181. * be done without getting too unfair.
  1182. */
  1183. if (cfs_rq->skip == se) {
  1184. struct sched_entity *second = __pick_next_entity(se);
  1185. if (second && wakeup_preempt_entity(second, left) < 1)
  1186. se = second;
  1187. }
  1188. /*
  1189. * Prefer last buddy, try to return the CPU to a preempted task.
  1190. */
  1191. if (cfs_rq->last && wakeup_preempt_entity(cfs_rq->last, left) < 1)
  1192. se = cfs_rq->last;
  1193. /*
  1194. * Someone really wants this to run. If it's not unfair, run it.
  1195. */
  1196. if (cfs_rq->next && wakeup_preempt_entity(cfs_rq->next, left) < 1)
  1197. se = cfs_rq->next;
  1198. clear_buddies(cfs_rq, se);
  1199. return se;
  1200. }
  1201. static void check_cfs_rq_runtime(struct cfs_rq *cfs_rq);
  1202. static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
  1203. {
  1204. /*
  1205. * If still on the runqueue then deactivate_task()
  1206. * was not called and update_curr() has to be done:
  1207. */
  1208. if (prev->on_rq)
  1209. update_curr(cfs_rq);
  1210. /* throttle cfs_rqs exceeding runtime */
  1211. check_cfs_rq_runtime(cfs_rq);
  1212. check_spread(cfs_rq, prev);
  1213. if (prev->on_rq) {
  1214. update_stats_wait_start(cfs_rq, prev);
  1215. /* Put 'current' back into the tree. */
  1216. __enqueue_entity(cfs_rq, prev);
  1217. }
  1218. cfs_rq->curr = NULL;
  1219. }
  1220. static void
  1221. entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
  1222. {
  1223. /*
  1224. * Update run-time statistics of the 'current'.
  1225. */
  1226. update_curr(cfs_rq);
  1227. /*
  1228. * Update share accounting for long-running entities.
  1229. */
  1230. update_entity_shares_tick(cfs_rq);
  1231. #ifdef CONFIG_SCHED_HRTICK
  1232. /*
  1233. * queued ticks are scheduled to match the slice, so don't bother
  1234. * validating it and just reschedule.
  1235. */
  1236. if (queued) {
  1237. resched_task(rq_of(cfs_rq)->curr);
  1238. return;
  1239. }
  1240. /*
  1241. * don't let the period tick interfere with the hrtick preemption
  1242. */
  1243. if (!sched_feat(DOUBLE_TICK) &&
  1244. hrtimer_active(&rq_of(cfs_rq)->hrtick_timer))
  1245. return;
  1246. #endif
  1247. if (cfs_rq->nr_running > 1)
  1248. check_preempt_tick(cfs_rq, curr);
  1249. }
  1250. /**************************************************
  1251. * CFS bandwidth control machinery
  1252. */
  1253. #ifdef CONFIG_CFS_BANDWIDTH
  1254. #ifdef HAVE_JUMP_LABEL
  1255. static struct static_key __cfs_bandwidth_used;
  1256. static inline bool cfs_bandwidth_used(void)
  1257. {
  1258. return static_key_false(&__cfs_bandwidth_used);
  1259. }
  1260. void account_cfs_bandwidth_used(int enabled, int was_enabled)
  1261. {
  1262. /* only need to count groups transitioning between enabled/!enabled */
  1263. if (enabled && !was_enabled)
  1264. static_key_slow_inc(&__cfs_bandwidth_used);
  1265. else if (!enabled && was_enabled)
  1266. static_key_slow_dec(&__cfs_bandwidth_used);
  1267. }
  1268. #else /* HAVE_JUMP_LABEL */
  1269. static bool cfs_bandwidth_used(void)
  1270. {
  1271. return true;
  1272. }
  1273. void account_cfs_bandwidth_used(int enabled, int was_enabled) {}
  1274. #endif /* HAVE_JUMP_LABEL */
  1275. /*
  1276. * default period for cfs group bandwidth.
  1277. * default: 0.1s, units: nanoseconds
  1278. */
  1279. static inline u64 default_cfs_period(void)
  1280. {
  1281. return 100000000ULL;
  1282. }
  1283. static inline u64 sched_cfs_bandwidth_slice(void)
  1284. {
  1285. return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC;
  1286. }
  1287. /*
  1288. * Replenish runtime according to assigned quota and update expiration time.
  1289. * We use sched_clock_cpu directly instead of rq->clock to avoid adding
  1290. * additional synchronization around rq->lock.
  1291. *
  1292. * requires cfs_b->lock
  1293. */
  1294. void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
  1295. {
  1296. u64 now;
  1297. if (cfs_b->quota == RUNTIME_INF)
  1298. return;
  1299. now = sched_clock_cpu(smp_processor_id());
  1300. cfs_b->runtime = cfs_b->quota;
  1301. cfs_b->runtime_expires = now + ktime_to_ns(cfs_b->period);
  1302. }
  1303. static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
  1304. {
  1305. return &tg->cfs_bandwidth;
  1306. }
  1307. /* returns 0 on failure to allocate runtime */
  1308. static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  1309. {
  1310. struct task_group *tg = cfs_rq->tg;
  1311. struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(tg);
  1312. u64 amount = 0, min_amount, expires;
  1313. /* note: this is a positive sum as runtime_remaining <= 0 */
  1314. min_amount = sched_cfs_bandwidth_slice() - cfs_rq->runtime_remaining;
  1315. raw_spin_lock(&cfs_b->lock);
  1316. if (cfs_b->quota == RUNTIME_INF)
  1317. amount = min_amount;
  1318. else {
  1319. /*
  1320. * If the bandwidth pool has become inactive, then at least one
  1321. * period must have elapsed since the last consumption.
  1322. * Refresh the global state and ensure bandwidth timer becomes
  1323. * active.
  1324. */
  1325. if (!cfs_b->timer_active) {
  1326. __refill_cfs_bandwidth_runtime(cfs_b);
  1327. __start_cfs_bandwidth(cfs_b);
  1328. }
  1329. if (cfs_b->runtime > 0) {
  1330. amount = min(cfs_b->runtime, min_amount);
  1331. cfs_b->runtime -= amount;
  1332. cfs_b->idle = 0;
  1333. }
  1334. }
  1335. expires = cfs_b->runtime_expires;
  1336. raw_spin_unlock(&cfs_b->lock);
  1337. cfs_rq->runtime_remaining += amount;
  1338. /*
  1339. * we may have advanced our local expiration to account for allowed
  1340. * spread between our sched_clock and the one on which runtime was
  1341. * issued.
  1342. */
  1343. if ((s64)(expires - cfs_rq->runtime_expires) > 0)
  1344. cfs_rq->runtime_expires = expires;
  1345. return cfs_rq->runtime_remaining > 0;
  1346. }
  1347. /*
  1348. * Note: This depends on the synchronization provided by sched_clock and the
  1349. * fact that rq->clock snapshots this value.
  1350. */
  1351. static void expire_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  1352. {
  1353. struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
  1354. struct rq *rq = rq_of(cfs_rq);
  1355. /* if the deadline is ahead of our clock, nothing to do */
  1356. if (likely((s64)(rq->clock - cfs_rq->runtime_expires) < 0))
  1357. return;
  1358. if (cfs_rq->runtime_remaining < 0)
  1359. return;
  1360. /*
  1361. * If the local deadline has passed we have to consider the
  1362. * possibility that our sched_clock is 'fast' and the global deadline
  1363. * has not truly expired.
  1364. *
  1365. * Fortunately we can check determine whether this the case by checking
  1366. * whether the global deadline has advanced.
  1367. */
  1368. if ((s64)(cfs_rq->runtime_expires - cfs_b->runtime_expires) >= 0) {
  1369. /* extend local deadline, drift is bounded above by 2 ticks */
  1370. cfs_rq->runtime_expires += TICK_NSEC;
  1371. } else {
  1372. /* global deadline is ahead, expiration has passed */
  1373. cfs_rq->runtime_remaining = 0;
  1374. }
  1375. }
  1376. static void __account_cfs_rq_runtime(struct cfs_rq *cfs_rq,
  1377. unsigned long delta_exec)
  1378. {
  1379. /* dock delta_exec before expiring quota (as it could span periods) */
  1380. cfs_rq->runtime_remaining -= delta_exec;
  1381. expire_cfs_rq_runtime(cfs_rq);
  1382. if (likely(cfs_rq->runtime_remaining > 0))
  1383. return;
  1384. /*
  1385. * if we're unable to extend our runtime we resched so that the active
  1386. * hierarchy can be throttled
  1387. */
  1388. if (!assign_cfs_rq_runtime(cfs_rq) && likely(cfs_rq->curr))
  1389. resched_task(rq_of(cfs_rq)->curr);
  1390. }
  1391. static __always_inline
  1392. void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, unsigned long delta_exec)
  1393. {
  1394. if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled)
  1395. return;
  1396. __account_cfs_rq_runtime(cfs_rq, delta_exec);
  1397. }
  1398. static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
  1399. {
  1400. return cfs_bandwidth_used() && cfs_rq->throttled;
  1401. }
  1402. /* check whether cfs_rq, or any parent, is throttled */
  1403. static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
  1404. {
  1405. return cfs_bandwidth_used() && cfs_rq->throttle_count;
  1406. }
  1407. /*
  1408. * Ensure that neither of the group entities corresponding to src_cpu or
  1409. * dest_cpu are members of a throttled hierarchy when performing group
  1410. * load-balance operations.
  1411. */
  1412. static inline int throttled_lb_pair(struct task_group *tg,
  1413. int src_cpu, int dest_cpu)
  1414. {
  1415. struct cfs_rq *src_cfs_rq, *dest_cfs_rq;
  1416. src_cfs_rq = tg->cfs_rq[src_cpu];
  1417. dest_cfs_rq = tg->cfs_rq[dest_cpu];
  1418. return throttled_hierarchy(src_cfs_rq) ||
  1419. throttled_hierarchy(dest_cfs_rq);
  1420. }
  1421. /* updated child weight may affect parent so we have to do this bottom up */
  1422. static int tg_unthrottle_up(struct task_group *tg, void *data)
  1423. {
  1424. struct rq *rq = data;
  1425. struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
  1426. cfs_rq->throttle_count--;
  1427. #ifdef CONFIG_SMP
  1428. if (!cfs_rq->throttle_count) {
  1429. u64 delta = rq->clock_task - cfs_rq->load_stamp;
  1430. /* leaving throttled state, advance shares averaging windows */
  1431. cfs_rq->load_stamp += delta;
  1432. cfs_rq->load_last += delta;
  1433. /* update entity weight now that we are on_rq again */
  1434. update_cfs_shares(cfs_rq);
  1435. }
  1436. #endif
  1437. return 0;
  1438. }
  1439. static int tg_throttle_down(struct task_group *tg, void *data)
  1440. {
  1441. struct rq *rq = data;
  1442. struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
  1443. /* group is entering throttled state, record last load */
  1444. if (!cfs_rq->throttle_count)
  1445. update_cfs_load(cfs_rq, 0);
  1446. cfs_rq->throttle_count++;
  1447. return 0;
  1448. }
  1449. static void throttle_cfs_rq(struct cfs_rq *cfs_rq)
  1450. {
  1451. struct rq *rq = rq_of(cfs_rq);
  1452. struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
  1453. struct sched_entity *se;
  1454. long task_delta, dequeue = 1;
  1455. se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))];
  1456. /* account load preceding throttle */
  1457. rcu_read_lock();
  1458. walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq);
  1459. rcu_read_unlock();
  1460. task_delta = cfs_rq->h_nr_running;
  1461. for_each_sched_entity(se) {
  1462. struct cfs_rq *qcfs_rq = cfs_rq_of(se);
  1463. /* throttled entity or throttle-on-deactivate */
  1464. if (!se->on_rq)
  1465. break;
  1466. if (dequeue)
  1467. dequeue_entity(qcfs_rq, se, DEQUEUE_SLEEP);
  1468. qcfs_rq->h_nr_running -= task_delta;
  1469. if (qcfs_rq->load.weight)
  1470. dequeue = 0;
  1471. }
  1472. if (!se)
  1473. rq->nr_running -= task_delta;
  1474. cfs_rq->throttled = 1;
  1475. cfs_rq->throttled_timestamp = rq->clock;
  1476. raw_spin_lock(&cfs_b->lock);
  1477. list_add_tail_rcu(&cfs_rq->throttled_list, &cfs_b->throttled_cfs_rq);
  1478. raw_spin_unlock(&cfs_b->lock);
  1479. }
  1480. void unthrottle_cfs_rq(struct cfs_rq *cfs_rq)
  1481. {
  1482. struct rq *rq = rq_of(cfs_rq);
  1483. struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
  1484. struct sched_entity *se;
  1485. int enqueue = 1;
  1486. long task_delta;
  1487. se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))];
  1488. cfs_rq->throttled = 0;
  1489. raw_spin_lock(&cfs_b->lock);
  1490. cfs_b->throttled_time += rq->clock - cfs_rq->throttled_timestamp;
  1491. list_del_rcu(&cfs_rq->throttled_list);
  1492. raw_spin_unlock(&cfs_b->lock);
  1493. cfs_rq->throttled_timestamp = 0;
  1494. update_rq_clock(rq);
  1495. /* update hierarchical throttle state */
  1496. walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq);
  1497. if (!cfs_rq->load.weight)
  1498. return;
  1499. task_delta = cfs_rq->h_nr_running;
  1500. for_each_sched_entity(se) {
  1501. if (se->on_rq)
  1502. enqueue = 0;
  1503. cfs_rq = cfs_rq_of(se);
  1504. if (enqueue)
  1505. enqueue_entity(cfs_rq, se, ENQUEUE_WAKEUP);
  1506. cfs_rq->h_nr_running += task_delta;
  1507. if (cfs_rq_throttled(cfs_rq))
  1508. break;
  1509. }
  1510. if (!se)
  1511. rq->nr_running += task_delta;
  1512. /* determine whether we need to wake up potentially idle cpu */
  1513. if (rq->curr == rq->idle && rq->cfs.nr_running)
  1514. resched_task(rq->curr);
  1515. }
  1516. static u64 distribute_cfs_runtime(struct cfs_bandwidth *cfs_b,
  1517. u64 remaining, u64 expires)
  1518. {
  1519. struct cfs_rq *cfs_rq;
  1520. u64 runtime = remaining;
  1521. rcu_read_lock();
  1522. list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
  1523. throttled_list) {
  1524. struct rq *rq = rq_of(cfs_rq);
  1525. raw_spin_lock(&rq->lock);
  1526. if (!cfs_rq_throttled(cfs_rq))
  1527. goto next;
  1528. runtime = -cfs_rq->runtime_remaining + 1;
  1529. if (runtime > remaining)
  1530. runtime = remaining;
  1531. remaining -= runtime;
  1532. cfs_rq->runtime_remaining += runtime;
  1533. cfs_rq->runtime_expires = expires;
  1534. /* we check whether we're throttled above */
  1535. if (cfs_rq->runtime_remaining > 0)
  1536. unthrottle_cfs_rq(cfs_rq);
  1537. next:
  1538. raw_spin_unlock(&rq->lock);
  1539. if (!remaining)
  1540. break;
  1541. }
  1542. rcu_read_unlock();
  1543. return remaining;
  1544. }
  1545. /*
  1546. * Responsible for refilling a task_group's bandwidth and unthrottling its
  1547. * cfs_rqs as appropriate. If there has been no activity within the last
  1548. * period the timer is deactivated until scheduling resumes; cfs_b->idle is
  1549. * used to track this state.
  1550. */
  1551. static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun)
  1552. {
  1553. u64 runtime, runtime_expires;
  1554. int idle = 1, throttled;
  1555. raw_spin_lock(&cfs_b->lock);
  1556. /* no need to continue the timer with no bandwidth constraint */
  1557. if (cfs_b->quota == RUNTIME_INF)
  1558. goto out_unlock;
  1559. throttled = !list_empty(&cfs_b->throttled_cfs_rq);
  1560. /* idle depends on !throttled (for the case of a large deficit) */
  1561. idle = cfs_b->idle && !throttled;
  1562. cfs_b->nr_periods += overrun;
  1563. /* if we're going inactive then everything else can be deferred */
  1564. if (idle)
  1565. goto out_unlock;
  1566. __refill_cfs_bandwidth_runtime(cfs_b);
  1567. if (!throttled) {
  1568. /* mark as potentially idle for the upcoming period */
  1569. cfs_b->idle = 1;
  1570. goto out_unlock;
  1571. }
  1572. /* account preceding periods in which throttling occurred */
  1573. cfs_b->nr_throttled += overrun;
  1574. /*
  1575. * There are throttled entities so we must first use the new bandwidth
  1576. * to unthrottle them before making it generally available. This
  1577. * ensures that all existing debts will be paid before a new cfs_rq is
  1578. * allowed to run.
  1579. */
  1580. runtime = cfs_b->runtime;
  1581. runtime_expires = cfs_b->runtime_expires;
  1582. cfs_b->runtime = 0;
  1583. /*
  1584. * This check is repeated as we are holding onto the new bandwidth
  1585. * while we unthrottle. This can potentially race with an unthrottled
  1586. * group trying to acquire new bandwidth from the global pool.
  1587. */
  1588. while (throttled && runtime > 0) {
  1589. raw_spin_unlock(&cfs_b->lock);
  1590. /* we can't nest cfs_b->lock while distributing bandwidth */
  1591. runtime = distribute_cfs_runtime(cfs_b, runtime,
  1592. runtime_expires);
  1593. raw_spin_lock(&cfs_b->lock);
  1594. throttled = !list_empty(&cfs_b->throttled_cfs_rq);
  1595. }
  1596. /* return (any) remaining runtime */
  1597. cfs_b->runtime = runtime;
  1598. /*
  1599. * While we are ensured activity in the period following an
  1600. * unthrottle, this also covers the case in which the new bandwidth is
  1601. * insufficient to cover the existing bandwidth deficit. (Forcing the
  1602. * timer to remain active while there are any throttled entities.)
  1603. */
  1604. cfs_b->idle = 0;
  1605. out_unlock:
  1606. if (idle)
  1607. cfs_b->timer_active = 0;
  1608. raw_spin_unlock(&cfs_b->lock);
  1609. return idle;
  1610. }
  1611. /* a cfs_rq won't donate quota below this amount */
  1612. static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC;
  1613. /* minimum remaining period time to redistribute slack quota */
  1614. static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC;
  1615. /* how long we wait to gather additional slack before distributing */
  1616. static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC;
  1617. /* are we near the end of the current quota period? */
  1618. static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire)
  1619. {
  1620. struct hrtimer *refresh_timer = &cfs_b->period_timer;
  1621. u64 remaining;
  1622. /* if the call-back is running a quota refresh is already occurring */
  1623. if (hrtimer_callback_running(refresh_timer))
  1624. return 1;
  1625. /* is a quota refresh about to occur? */
  1626. remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer));
  1627. if (remaining < min_expire)
  1628. return 1;
  1629. return 0;
  1630. }
  1631. static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b)
  1632. {
  1633. u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration;
  1634. /* if there's a quota refresh soon don't bother with slack */
  1635. if (runtime_refresh_within(cfs_b, min_left))
  1636. return;
  1637. start_bandwidth_timer(&cfs_b->slack_timer,
  1638. ns_to_ktime(cfs_bandwidth_slack_period));
  1639. }
  1640. /* we know any runtime found here is valid as update_curr() precedes return */
  1641. static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  1642. {
  1643. struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
  1644. s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;
  1645. if (slack_runtime <= 0)
  1646. return;
  1647. raw_spin_lock(&cfs_b->lock);
  1648. if (cfs_b->quota != RUNTIME_INF &&
  1649. cfs_rq->runtime_expires == cfs_b->runtime_expires) {
  1650. cfs_b->runtime += slack_runtime;
  1651. /* we are under rq->lock, defer unthrottling using a timer */
  1652. if (cfs_b->runtime > sched_cfs_bandwidth_slice() &&
  1653. !list_empty(&cfs_b->throttled_cfs_rq))
  1654. start_cfs_slack_bandwidth(cfs_b);
  1655. }
  1656. raw_spin_unlock(&cfs_b->lock);
  1657. /* even if it's not valid for return we don't want to try again */
  1658. cfs_rq->runtime_remaining -= slack_runtime;
  1659. }
  1660. static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  1661. {
  1662. if (!cfs_bandwidth_used())
  1663. return;
  1664. if (!cfs_rq->runtime_enabled || cfs_rq->nr_running)
  1665. return;
  1666. __return_cfs_rq_runtime(cfs_rq);
  1667. }
  1668. /*
  1669. * This is done with a timer (instead of inline with bandwidth return) since
  1670. * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
  1671. */
  1672. static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)
  1673. {
  1674. u64 runtime = 0, slice = sched_cfs_bandwidth_slice();
  1675. u64 expires;
  1676. /* confirm we're still not at a refresh boundary */
  1677. if (runtime_refresh_within(cfs_b, min_bandwidth_expiration))
  1678. return;
  1679. raw_spin_lock(&cfs_b->lock);
  1680. if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice) {
  1681. runtime = cfs_b->runtime;
  1682. cfs_b->runtime = 0;
  1683. }
  1684. expires = cfs_b->runtime_expires;
  1685. raw_spin_unlock(&cfs_b->lock);
  1686. if (!runtime)
  1687. return;
  1688. runtime = distribute_cfs_runtime(cfs_b, runtime, expires);
  1689. raw_spin_lock(&cfs_b->lock);
  1690. if (expires == cfs_b->runtime_expires)
  1691. cfs_b->runtime = runtime;
  1692. raw_spin_unlock(&cfs_b->lock);
  1693. }
  1694. /*
  1695. * When a group wakes up we want to make sure that its quota is not already
  1696. * expired/exceeded, otherwise it may be allowed to steal additional ticks of
  1697. * runtime as update_curr() throttling can not not trigger until it's on-rq.
  1698. */
  1699. static void check_enqueue_throttle(struct cfs_rq *cfs_rq)
  1700. {
  1701. if (!cfs_bandwidth_used())
  1702. return;
  1703. /* an active group must be handled by the update_curr()->put() path */
  1704. if (!cfs_rq->runtime_enabled || cfs_rq->curr)
  1705. return;
  1706. /* ensure the group is not already throttled */
  1707. if (cfs_rq_throttled(cfs_rq))
  1708. return;
  1709. /* update runtime allocation */
  1710. account_cfs_rq_runtime(cfs_rq, 0);
  1711. if (cfs_rq->runtime_remaining <= 0)
  1712. throttle_cfs_rq(cfs_rq);
  1713. }
  1714. /* conditionally throttle active cfs_rq's from put_prev_entity() */
  1715. static void check_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  1716. {
  1717. if (!cfs_bandwidth_used())
  1718. return;
  1719. if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0))
  1720. return;
  1721. /*
  1722. * it's possible for a throttled entity to be forced into a running
  1723. * state (e.g. set_curr_task), in this case we're finished.
  1724. */
  1725. if (cfs_rq_throttled(cfs_rq))
  1726. return;
  1727. throttle_cfs_rq(cfs_rq);
  1728. }
  1729. static inline u64 default_cfs_period(void);
  1730. static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun);
  1731. static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b);
  1732. static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer)
  1733. {
  1734. struct cfs_bandwidth *cfs_b =
  1735. container_of(timer, struct cfs_bandwidth, slack_timer);
  1736. do_sched_cfs_slack_timer(cfs_b);
  1737. return HRTIMER_NORESTART;
  1738. }
  1739. static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)
  1740. {
  1741. struct cfs_bandwidth *cfs_b =
  1742. container_of(timer, struct cfs_bandwidth, period_timer);
  1743. ktime_t now;
  1744. int overrun;
  1745. int idle = 0;
  1746. for (;;) {
  1747. now = hrtimer_cb_get_time(timer);
  1748. overrun = hrtimer_forward(timer, now, cfs_b->period);
  1749. if (!overrun)
  1750. break;
  1751. idle = do_sched_cfs_period_timer(cfs_b, overrun);
  1752. }
  1753. return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
  1754. }
  1755. void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
  1756. {
  1757. raw_spin_lock_init(&cfs_b->lock);
  1758. cfs_b->runtime = 0;
  1759. cfs_b->quota = RUNTIME_INF;
  1760. cfs_b->period = ns_to_ktime(default_cfs_period());
  1761. INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq);
  1762. hrtimer_init(&cfs_b->period_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
  1763. cfs_b->period_timer.function = sched_cfs_period_timer;
  1764. hrtimer_init(&cfs_b->slack_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
  1765. cfs_b->slack_timer.function = sched_cfs_slack_timer;
  1766. }
  1767. static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  1768. {
  1769. cfs_rq->runtime_enabled = 0;
  1770. INIT_LIST_HEAD(&cfs_rq->throttled_list);
  1771. }
  1772. /* requires cfs_b->lock, may release to reprogram timer */
  1773. void __start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
  1774. {
  1775. /*
  1776. * The timer may be active because we're trying to set a new bandwidth
  1777. * period or because we're racing with the tear-down path
  1778. * (timer_active==0 becomes visible before the hrtimer call-back
  1779. * terminates). In either case we ensure that it's re-programmed
  1780. */
  1781. while (unlikely(hrtimer_active(&cfs_b->period_timer))) {
  1782. raw_spin_unlock(&cfs_b->lock);
  1783. /* ensure cfs_b->lock is available while we wait */
  1784. hrtimer_cancel(&cfs_b->period_timer);
  1785. raw_spin_lock(&cfs_b->lock);
  1786. /* if someone else restarted the timer then we're done */
  1787. if (cfs_b->timer_active)
  1788. return;
  1789. }
  1790. cfs_b->timer_active = 1;
  1791. start_bandwidth_timer(&cfs_b->period_timer, cfs_b->period);
  1792. }
  1793. static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
  1794. {
  1795. hrtimer_cancel(&cfs_b->period_timer);
  1796. hrtimer_cancel(&cfs_b->slack_timer);
  1797. }
  1798. static void unthrottle_offline_cfs_rqs(struct rq *rq)
  1799. {
  1800. struct cfs_rq *cfs_rq;
  1801. for_each_leaf_cfs_rq(rq, cfs_rq) {
  1802. struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
  1803. if (!cfs_rq->runtime_enabled)
  1804. continue;
  1805. /*
  1806. * clock_task is not advancing so we just need to make sure
  1807. * there's some valid quota amount
  1808. */
  1809. cfs_rq->runtime_remaining = cfs_b->quota;
  1810. if (cfs_rq_throttled(cfs_rq))
  1811. unthrottle_cfs_rq(cfs_rq);
  1812. }
  1813. }
  1814. #else /* CONFIG_CFS_BANDWIDTH */
  1815. static __always_inline
  1816. void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, unsigned long delta_exec) {}
  1817. static void check_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
  1818. static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {}
  1819. static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
  1820. static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
  1821. {
  1822. return 0;
  1823. }
  1824. static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
  1825. {
  1826. return 0;
  1827. }
  1828. static inline int throttled_lb_pair(struct task_group *tg,
  1829. int src_cpu, int dest_cpu)
  1830. {
  1831. return 0;
  1832. }
  1833. void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
  1834. #ifdef CONFIG_FAIR_GROUP_SCHED
  1835. static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
  1836. #endif
  1837. static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
  1838. {
  1839. return NULL;
  1840. }
  1841. static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
  1842. static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {}
  1843. #endif /* CONFIG_CFS_BANDWIDTH */
  1844. /**************************************************
  1845. * CFS operations on tasks:
  1846. */
  1847. #ifdef CONFIG_SCHED_HRTICK
  1848. static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
  1849. {
  1850. struct sched_entity *se = &p->se;
  1851. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  1852. WARN_ON(task_rq(p) != rq);
  1853. if (cfs_rq->nr_running > 1) {
  1854. u64 slice = sched_slice(cfs_rq, se);
  1855. u64 ran = se->sum_exec_runtime - se->prev_sum_exec_runtime;
  1856. s64 delta = slice - ran;
  1857. if (delta < 0) {
  1858. if (rq->curr == p)
  1859. resched_task(p);
  1860. return;
  1861. }
  1862. /*
  1863. * Don't schedule slices shorter than 10000ns, that just
  1864. * doesn't make sense. Rely on vruntime for fairness.
  1865. */
  1866. if (rq->curr != p)
  1867. delta = max_t(s64, 10000LL, delta);
  1868. hrtick_start(rq, delta);
  1869. }
  1870. }
  1871. /*
  1872. * called from enqueue/dequeue and updates the hrtick when the
  1873. * current task is from our class and nr_running is low enough
  1874. * to matter.
  1875. */
  1876. static void hrtick_update(struct rq *rq)
  1877. {
  1878. struct task_struct *curr = rq->curr;
  1879. if (!hrtick_enabled(rq) || curr->sched_class != &fair_sched_class)
  1880. return;
  1881. if (cfs_rq_of(&curr->se)->nr_running < sched_nr_latency)
  1882. hrtick_start_fair(rq, curr);
  1883. }
  1884. #else /* !CONFIG_SCHED_HRTICK */
  1885. static inline void
  1886. hrtick_start_fair(struct rq *rq, struct task_struct *p)
  1887. {
  1888. }
  1889. static inline void hrtick_update(struct rq *rq)
  1890. {
  1891. }
  1892. #endif
  1893. /*
  1894. * The enqueue_task method is called before nr_running is
  1895. * increased. Here we update the fair scheduling stats and
  1896. * then put the task into the rbtree:
  1897. */
  1898. static void
  1899. enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
  1900. {
  1901. struct cfs_rq *cfs_rq;
  1902. struct sched_entity *se = &p->se;
  1903. for_each_sched_entity(se) {
  1904. if (se->on_rq)
  1905. break;
  1906. cfs_rq = cfs_rq_of(se);
  1907. enqueue_entity(cfs_rq, se, flags);
  1908. /*
  1909. * end evaluation on encountering a throttled cfs_rq
  1910. *
  1911. * note: in the case of encountering a throttled cfs_rq we will
  1912. * post the final h_nr_running increment below.
  1913. */
  1914. if (cfs_rq_throttled(cfs_rq))
  1915. break;
  1916. cfs_rq->h_nr_running++;
  1917. flags = ENQUEUE_WAKEUP;
  1918. }
  1919. for_each_sched_entity(se) {
  1920. cfs_rq = cfs_rq_of(se);
  1921. cfs_rq->h_nr_running++;
  1922. if (cfs_rq_throttled(cfs_rq))
  1923. break;
  1924. update_cfs_load(cfs_rq, 0);
  1925. update_cfs_shares(cfs_rq);
  1926. }
  1927. if (!se)
  1928. inc_nr_running(rq);
  1929. hrtick_update(rq);
  1930. }
  1931. static void set_next_buddy(struct sched_entity *se);
  1932. /*
  1933. * The dequeue_task method is called before nr_running is
  1934. * decreased. We remove the task from the rbtree and
  1935. * update the fair scheduling stats:
  1936. */
  1937. static void dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
  1938. {
  1939. struct cfs_rq *cfs_rq;
  1940. struct sched_entity *se = &p->se;
  1941. int task_sleep = flags & DEQUEUE_SLEEP;
  1942. for_each_sched_entity(se) {
  1943. cfs_rq = cfs_rq_of(se);
  1944. dequeue_entity(cfs_rq, se, flags);
  1945. /*
  1946. * end evaluation on encountering a throttled cfs_rq
  1947. *
  1948. * note: in the case of encountering a throttled cfs_rq we will
  1949. * post the final h_nr_running decrement below.
  1950. */
  1951. if (cfs_rq_throttled(cfs_rq))
  1952. break;
  1953. cfs_rq->h_nr_running--;
  1954. /* Don't dequeue parent if it has other entities besides us */
  1955. if (cfs_rq->load.weight) {
  1956. /*
  1957. * Bias pick_next to pick a task from this cfs_rq, as
  1958. * p is sleeping when it is within its sched_slice.
  1959. */
  1960. if (task_sleep && parent_entity(se))
  1961. set_next_buddy(parent_entity(se));
  1962. /* avoid re-evaluating load for this entity */
  1963. se = parent_entity(se);
  1964. break;
  1965. }
  1966. flags |= DEQUEUE_SLEEP;
  1967. }
  1968. for_each_sched_entity(se) {
  1969. cfs_rq = cfs_rq_of(se);
  1970. cfs_rq->h_nr_running--;
  1971. if (cfs_rq_throttled(cfs_rq))
  1972. break;
  1973. update_cfs_load(cfs_rq, 0);
  1974. update_cfs_shares(cfs_rq);
  1975. }
  1976. if (!se)
  1977. dec_nr_running(rq);
  1978. hrtick_update(rq);
  1979. }
  1980. #ifdef CONFIG_SMP
  1981. /* Used instead of source_load when we know the type == 0 */
  1982. static unsigned long weighted_cpuload(const int cpu)
  1983. {
  1984. return cpu_rq(cpu)->load.weight;
  1985. }
  1986. /*
  1987. * Return a low guess at the load of a migration-source cpu weighted
  1988. * according to the scheduling class and "nice" value.
  1989. *
  1990. * We want to under-estimate the load of migration sources, to
  1991. * balance conservatively.
  1992. */
  1993. static unsigned long source_load(int cpu, int type)
  1994. {
  1995. struct rq *rq = cpu_rq(cpu);
  1996. unsigned long total = weighted_cpuload(cpu);
  1997. if (type == 0 || !sched_feat(LB_BIAS))
  1998. return total;
  1999. return min(rq->cpu_load[type-1], total);
  2000. }
  2001. /*
  2002. * Return a high guess at the load of a migration-target cpu weighted
  2003. * according to the scheduling class and "nice" value.
  2004. */
  2005. static unsigned long target_load(int cpu, int type)
  2006. {
  2007. struct rq *rq = cpu_rq(cpu);
  2008. unsigned long total = weighted_cpuload(cpu);
  2009. if (type == 0 || !sched_feat(LB_BIAS))
  2010. return total;
  2011. return max(rq->cpu_load[type-1], total);
  2012. }
  2013. static unsigned long power_of(int cpu)
  2014. {
  2015. return cpu_rq(cpu)->cpu_power;
  2016. }
  2017. static unsigned long cpu_avg_load_per_task(int cpu)
  2018. {
  2019. struct rq *rq = cpu_rq(cpu);
  2020. unsigned long nr_running = ACCESS_ONCE(rq->nr_running);
  2021. if (nr_running)
  2022. return rq->load.weight / nr_running;
  2023. return 0;
  2024. }
  2025. static void task_waking_fair(struct task_struct *p)
  2026. {
  2027. struct sched_entity *se = &p->se;
  2028. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  2029. u64 min_vruntime;
  2030. #ifndef CONFIG_64BIT
  2031. u64 min_vruntime_copy;
  2032. do {
  2033. min_vruntime_copy = cfs_rq->min_vruntime_copy;
  2034. smp_rmb();
  2035. min_vruntime = cfs_rq->min_vruntime;
  2036. } while (min_vruntime != min_vruntime_copy);
  2037. #else
  2038. min_vruntime = cfs_rq->min_vruntime;
  2039. #endif
  2040. se->vruntime -= min_vruntime;
  2041. }
  2042. #ifdef CONFIG_FAIR_GROUP_SCHED
  2043. /*
  2044. * effective_load() calculates the load change as seen from the root_task_group
  2045. *
  2046. * Adding load to a group doesn't make a group heavier, but can cause movement
  2047. * of group shares between cpus. Assuming the shares were perfectly aligned one
  2048. * can calculate the shift in shares.
  2049. *
  2050. * Calculate the effective load difference if @wl is added (subtracted) to @tg
  2051. * on this @cpu and results in a total addition (subtraction) of @wg to the
  2052. * total group weight.
  2053. *
  2054. * Given a runqueue weight distribution (rw_i) we can compute a shares
  2055. * distribution (s_i) using:
  2056. *
  2057. * s_i = rw_i / \Sum rw_j (1)
  2058. *
  2059. * Suppose we have 4 CPUs and our @tg is a direct child of the root group and
  2060. * has 7 equal weight tasks, distributed as below (rw_i), with the resulting
  2061. * shares distribution (s_i):
  2062. *
  2063. * rw_i = { 2, 4, 1, 0 }
  2064. * s_i = { 2/7, 4/7, 1/7, 0 }
  2065. *
  2066. * As per wake_affine() we're interested in the load of two CPUs (the CPU the
  2067. * task used to run on and the CPU the waker is running on), we need to
  2068. * compute the effect of waking a task on either CPU and, in case of a sync
  2069. * wakeup, compute the effect of the current task going to sleep.
  2070. *
  2071. * So for a change of @wl to the local @cpu with an overall group weight change
  2072. * of @wl we can compute the new shares distribution (s'_i) using:
  2073. *
  2074. * s'_i = (rw_i + @wl) / (@wg + \Sum rw_j) (2)
  2075. *
  2076. * Suppose we're interested in CPUs 0 and 1, and want to compute the load
  2077. * differences in waking a task to CPU 0. The additional task changes the
  2078. * weight and shares distributions like:
  2079. *
  2080. * rw'_i = { 3, 4, 1, 0 }
  2081. * s'_i = { 3/8, 4/8, 1/8, 0 }
  2082. *
  2083. * We can then compute the difference in effective weight by using:
  2084. *
  2085. * dw_i = S * (s'_i - s_i) (3)
  2086. *
  2087. * Where 'S' is the group weight as seen by its parent.
  2088. *
  2089. * Therefore the effective change in loads on CPU 0 would be 5/56 (3/8 - 2/7)
  2090. * times the weight of the group. The effect on CPU 1 would be -4/56 (4/8 -
  2091. * 4/7) times the weight of the group.
  2092. */
  2093. static long effective_load(struct task_group *tg, int cpu, long wl, long wg)
  2094. {
  2095. struct sched_entity *se = tg->se[cpu];
  2096. if (!tg->parent) /* the trivial, non-cgroup case */
  2097. return wl;
  2098. for_each_sched_entity(se) {
  2099. long w, W;
  2100. tg = se->my_q->tg;
  2101. /*
  2102. * W = @wg + \Sum rw_j
  2103. */
  2104. W = wg + calc_tg_weight(tg, se->my_q);
  2105. /*
  2106. * w = rw_i + @wl
  2107. */
  2108. w = se->my_q->load.weight + wl;
  2109. /*
  2110. * wl = S * s'_i; see (2)
  2111. */
  2112. if (W > 0 && w < W)
  2113. wl = (w * tg->shares) / W;
  2114. else
  2115. wl = tg->shares;
  2116. /*
  2117. * Per the above, wl is the new se->load.weight value; since
  2118. * those are clipped to [MIN_SHARES, ...) do so now. See
  2119. * calc_cfs_shares().
  2120. */
  2121. if (wl < MIN_SHARES)
  2122. wl = MIN_SHARES;
  2123. /*
  2124. * wl = dw_i = S * (s'_i - s_i); see (3)
  2125. */
  2126. wl -= se->load.weight;
  2127. /*
  2128. * Recursively apply this logic to all parent groups to compute
  2129. * the final effective load change on the root group. Since
  2130. * only the @tg group gets extra weight, all parent groups can
  2131. * only redistribute existing shares. @wl is the shift in shares
  2132. * resulting from this level per the above.
  2133. */
  2134. wg = 0;
  2135. }
  2136. return wl;
  2137. }
  2138. #else
  2139. static inline unsigned long effective_load(struct task_group *tg, int cpu,
  2140. unsigned long wl, unsigned long wg)
  2141. {
  2142. return wl;
  2143. }
  2144. #endif
  2145. static int wake_affine(struct sched_domain *sd, struct task_struct *p, int sync)
  2146. {
  2147. s64 this_load, load;
  2148. int idx, this_cpu, prev_cpu;
  2149. unsigned long tl_per_task;
  2150. struct task_group *tg;
  2151. unsigned long weight;
  2152. int balanced;
  2153. idx = sd->wake_idx;
  2154. this_cpu = smp_processor_id();
  2155. prev_cpu = task_cpu(p);
  2156. load = source_load(prev_cpu, idx);
  2157. this_load = target_load(this_cpu, idx);
  2158. /*
  2159. * If sync wakeup then subtract the (maximum possible)
  2160. * effect of the currently running task from the load
  2161. * of the current CPU:
  2162. */
  2163. if (sync) {
  2164. tg = task_group(current);
  2165. weight = current->se.load.weight;
  2166. this_load += effective_load(tg, this_cpu, -weight, -weight);
  2167. load += effective_load(tg, prev_cpu, 0, -weight);
  2168. }
  2169. tg = task_group(p);
  2170. weight = p->se.load.weight;
  2171. /*
  2172. * In low-load situations, where prev_cpu is idle and this_cpu is idle
  2173. * due to the sync cause above having dropped this_load to 0, we'll
  2174. * always have an imbalance, but there's really nothing you can do
  2175. * about that, so that's good too.
  2176. *
  2177. * Otherwise check if either cpus are near enough in load to allow this
  2178. * task to be woken on this_cpu.
  2179. */
  2180. if (this_load > 0) {
  2181. s64 this_eff_load, prev_eff_load;
  2182. this_eff_load = 100;
  2183. this_eff_load *= power_of(prev_cpu);
  2184. this_eff_load *= this_load +
  2185. effective_load(tg, this_cpu, weight, weight);
  2186. prev_eff_load = 100 + (sd->imbalance_pct - 100) / 2;
  2187. prev_eff_load *= power_of(this_cpu);
  2188. prev_eff_load *= load + effective_load(tg, prev_cpu, 0, weight);
  2189. balanced = this_eff_load <= prev_eff_load;
  2190. } else
  2191. balanced = true;
  2192. /*
  2193. * If the currently running task will sleep within
  2194. * a reasonable amount of time then attract this newly
  2195. * woken task:
  2196. */
  2197. if (sync && balanced)
  2198. return 1;
  2199. schedstat_inc(p, se.statistics.nr_wakeups_affine_attempts);
  2200. tl_per_task = cpu_avg_load_per_task(this_cpu);
  2201. if (balanced ||
  2202. (this_load <= load &&
  2203. this_load + target_load(prev_cpu, idx) <= tl_per_task)) {
  2204. /*
  2205. * This domain has SD_WAKE_AFFINE and
  2206. * p is cache cold in this domain, and
  2207. * there is no bad imbalance.
  2208. */
  2209. schedstat_inc(sd, ttwu_move_affine);
  2210. schedstat_inc(p, se.statistics.nr_wakeups_affine);
  2211. return 1;
  2212. }
  2213. return 0;
  2214. }
  2215. /*
  2216. * find_idlest_group finds and returns the least busy CPU group within the
  2217. * domain.
  2218. */
  2219. static struct sched_group *
  2220. find_idlest_group(struct sched_domain *sd, struct task_struct *p,
  2221. int this_cpu, int load_idx)
  2222. {
  2223. struct sched_group *idlest = NULL, *group = sd->groups;
  2224. unsigned long min_load = ULONG_MAX, this_load = 0;
  2225. int imbalance = 100 + (sd->imbalance_pct-100)/2;
  2226. do {
  2227. unsigned long load, avg_load;
  2228. int local_group;
  2229. int i;
  2230. /* Skip over this group if it has no CPUs allowed */
  2231. if (!cpumask_intersects(sched_group_cpus(group),
  2232. tsk_cpus_allowed(p)))
  2233. continue;
  2234. local_group = cpumask_test_cpu(this_cpu,
  2235. sched_group_cpus(group));
  2236. /* Tally up the load of all CPUs in the group */
  2237. avg_load = 0;
  2238. for_each_cpu(i, sched_group_cpus(group)) {
  2239. /* Bias balancing toward cpus of our domain */
  2240. if (local_group)
  2241. load = source_load(i, load_idx);
  2242. else
  2243. load = target_load(i, load_idx);
  2244. avg_load += load;
  2245. }
  2246. /* Adjust by relative CPU power of the group */
  2247. avg_load = (avg_load * SCHED_POWER_SCALE) / group->sgp->power;
  2248. if (local_group) {
  2249. this_load = avg_load;
  2250. } else if (avg_load < min_load) {
  2251. min_load = avg_load;
  2252. idlest = group;
  2253. }
  2254. } while (group = group->next, group != sd->groups);
  2255. if (!idlest || 100*this_load < imbalance*min_load)
  2256. return NULL;
  2257. return idlest;
  2258. }
  2259. /*
  2260. * find_idlest_cpu - find the idlest cpu among the cpus in group.
  2261. */
  2262. static int
  2263. find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
  2264. {
  2265. unsigned long load, min_load = ULONG_MAX;
  2266. int idlest = -1;
  2267. int i;
  2268. /* Traverse only the allowed CPUs */
  2269. for_each_cpu_and(i, sched_group_cpus(group), tsk_cpus_allowed(p)) {
  2270. load = weighted_cpuload(i);
  2271. if (load < min_load || (load == min_load && i == this_cpu)) {
  2272. min_load = load;
  2273. idlest = i;
  2274. }
  2275. }
  2276. return idlest;
  2277. }
  2278. /*
  2279. * Try and locate an idle CPU in the sched_domain.
  2280. */
  2281. static int select_idle_sibling(struct task_struct *p, int target)
  2282. {
  2283. int cpu = smp_processor_id();
  2284. int prev_cpu = task_cpu(p);
  2285. struct sched_domain *sd;
  2286. struct sched_group *sg;
  2287. int i;
  2288. /*
  2289. * If the task is going to be woken-up on this cpu and if it is
  2290. * already idle, then it is the right target.
  2291. */
  2292. if (target == cpu && idle_cpu(cpu))
  2293. return cpu;
  2294. /*
  2295. * If the task is going to be woken-up on the cpu where it previously
  2296. * ran and if it is currently idle, then it the right target.
  2297. */
  2298. if (target == prev_cpu && idle_cpu(prev_cpu))
  2299. return prev_cpu;
  2300. /*
  2301. * Otherwise, iterate the domains and find an elegible idle cpu.
  2302. */
  2303. sd = rcu_dereference(per_cpu(sd_llc, target));
  2304. for_each_lower_domain(sd) {
  2305. sg = sd->groups;
  2306. do {
  2307. if (!cpumask_intersects(sched_group_cpus(sg),
  2308. tsk_cpus_allowed(p)))
  2309. goto next;
  2310. for_each_cpu(i, sched_group_cpus(sg)) {
  2311. if (!idle_cpu(i))
  2312. goto next;
  2313. }
  2314. target = cpumask_first_and(sched_group_cpus(sg),
  2315. tsk_cpus_allowed(p));
  2316. goto done;
  2317. next:
  2318. sg = sg->next;
  2319. } while (sg != sd->groups);
  2320. }
  2321. done:
  2322. return target;
  2323. }
  2324. /*
  2325. * sched_balance_self: balance the current task (running on cpu) in domains
  2326. * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
  2327. * SD_BALANCE_EXEC.
  2328. *
  2329. * Balance, ie. select the least loaded group.
  2330. *
  2331. * Returns the target CPU number, or the same CPU if no balancing is needed.
  2332. *
  2333. * preempt must be disabled.
  2334. */
  2335. static int
  2336. select_task_rq_fair(struct task_struct *p, int sd_flag, int wake_flags)
  2337. {
  2338. struct sched_domain *tmp, *affine_sd = NULL, *sd = NULL;
  2339. int cpu = smp_processor_id();
  2340. int prev_cpu = task_cpu(p);
  2341. int new_cpu = cpu;
  2342. int want_affine = 0;
  2343. int sync = wake_flags & WF_SYNC;
  2344. if (p->nr_cpus_allowed == 1)
  2345. return prev_cpu;
  2346. if (sd_flag & SD_BALANCE_WAKE) {
  2347. if (cpumask_test_cpu(cpu, tsk_cpus_allowed(p)))
  2348. want_affine = 1;
  2349. new_cpu = prev_cpu;
  2350. }
  2351. rcu_read_lock();
  2352. for_each_domain(cpu, tmp) {
  2353. if (!(tmp->flags & SD_LOAD_BALANCE))
  2354. continue;
  2355. /*
  2356. * If both cpu and prev_cpu are part of this domain,
  2357. * cpu is a valid SD_WAKE_AFFINE target.
  2358. */
  2359. if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
  2360. cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
  2361. affine_sd = tmp;
  2362. break;
  2363. }
  2364. if (tmp->flags & sd_flag)
  2365. sd = tmp;
  2366. }
  2367. if (affine_sd) {
  2368. if (cpu != prev_cpu && wake_affine(affine_sd, p, sync))
  2369. prev_cpu = cpu;
  2370. new_cpu = select_idle_sibling(p, prev_cpu);
  2371. goto unlock;
  2372. }
  2373. while (sd) {
  2374. int load_idx = sd->forkexec_idx;
  2375. struct sched_group *group;
  2376. int weight;
  2377. if (!(sd->flags & sd_flag)) {
  2378. sd = sd->child;
  2379. continue;
  2380. }
  2381. if (sd_flag & SD_BALANCE_WAKE)
  2382. load_idx = sd->wake_idx;
  2383. group = find_idlest_group(sd, p, cpu, load_idx);
  2384. if (!group) {
  2385. sd = sd->child;
  2386. continue;
  2387. }
  2388. new_cpu = find_idlest_cpu(group, p, cpu);
  2389. if (new_cpu == -1 || new_cpu == cpu) {
  2390. /* Now try balancing at a lower domain level of cpu */
  2391. sd = sd->child;
  2392. continue;
  2393. }
  2394. /* Now try balancing at a lower domain level of new_cpu */
  2395. cpu = new_cpu;
  2396. weight = sd->span_weight;
  2397. sd = NULL;
  2398. for_each_domain(cpu, tmp) {
  2399. if (weight <= tmp->span_weight)
  2400. break;
  2401. if (tmp->flags & sd_flag)
  2402. sd = tmp;
  2403. }
  2404. /* while loop will break here if sd == NULL */
  2405. }
  2406. unlock:
  2407. rcu_read_unlock();
  2408. return new_cpu;
  2409. }
  2410. #endif /* CONFIG_SMP */
  2411. static unsigned long
  2412. wakeup_gran(struct sched_entity *curr, struct sched_entity *se)
  2413. {
  2414. unsigned long gran = sysctl_sched_wakeup_granularity;
  2415. /*
  2416. * Since its curr running now, convert the gran from real-time
  2417. * to virtual-time in his units.
  2418. *
  2419. * By using 'se' instead of 'curr' we penalize light tasks, so
  2420. * they get preempted easier. That is, if 'se' < 'curr' then
  2421. * the resulting gran will be larger, therefore penalizing the
  2422. * lighter, if otoh 'se' > 'curr' then the resulting gran will
  2423. * be smaller, again penalizing the lighter task.
  2424. *
  2425. * This is especially important for buddies when the leftmost
  2426. * task is higher priority than the buddy.
  2427. */
  2428. return calc_delta_fair(gran, se);
  2429. }
  2430. /*
  2431. * Should 'se' preempt 'curr'.
  2432. *
  2433. * |s1
  2434. * |s2
  2435. * |s3
  2436. * g
  2437. * |<--->|c
  2438. *
  2439. * w(c, s1) = -1
  2440. * w(c, s2) = 0
  2441. * w(c, s3) = 1
  2442. *
  2443. */
  2444. static int
  2445. wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se)
  2446. {
  2447. s64 gran, vdiff = curr->vruntime - se->vruntime;
  2448. if (vdiff <= 0)
  2449. return -1;
  2450. gran = wakeup_gran(curr, se);
  2451. if (vdiff > gran)
  2452. return 1;
  2453. return 0;
  2454. }
  2455. static void set_last_buddy(struct sched_entity *se)
  2456. {
  2457. if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE))
  2458. return;
  2459. for_each_sched_entity(se)
  2460. cfs_rq_of(se)->last = se;
  2461. }
  2462. static void set_next_buddy(struct sched_entity *se)
  2463. {
  2464. if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE))
  2465. return;
  2466. for_each_sched_entity(se)
  2467. cfs_rq_of(se)->next = se;
  2468. }
  2469. static void set_skip_buddy(struct sched_entity *se)
  2470. {
  2471. for_each_sched_entity(se)
  2472. cfs_rq_of(se)->skip = se;
  2473. }
  2474. /*
  2475. * Preempt the current task with a newly woken task if needed:
  2476. */
  2477. static void check_preempt_wakeup(struct rq *rq, struct task_struct *p, int wake_flags)
  2478. {
  2479. struct task_struct *curr = rq->curr;
  2480. struct sched_entity *se = &curr->se, *pse = &p->se;
  2481. struct cfs_rq *cfs_rq = task_cfs_rq(curr);
  2482. int scale = cfs_rq->nr_running >= sched_nr_latency;
  2483. int next_buddy_marked = 0;
  2484. if (unlikely(se == pse))
  2485. return;
  2486. /*
  2487. * This is possible from callers such as move_task(), in which we
  2488. * unconditionally check_prempt_curr() after an enqueue (which may have
  2489. * lead to a throttle). This both saves work and prevents false
  2490. * next-buddy nomination below.
  2491. */
  2492. if (unlikely(throttled_hierarchy(cfs_rq_of(pse))))
  2493. return;
  2494. if (sched_feat(NEXT_BUDDY) && scale && !(wake_flags & WF_FORK)) {
  2495. set_next_buddy(pse);
  2496. next_buddy_marked = 1;
  2497. }
  2498. /*
  2499. * We can come here with TIF_NEED_RESCHED already set from new task
  2500. * wake up path.
  2501. *
  2502. * Note: this also catches the edge-case of curr being in a throttled
  2503. * group (e.g. via set_curr_task), since update_curr() (in the
  2504. * enqueue of curr) will have resulted in resched being set. This
  2505. * prevents us from potentially nominating it as a false LAST_BUDDY
  2506. * below.
  2507. */
  2508. if (test_tsk_need_resched(curr))
  2509. return;
  2510. /* Idle tasks are by definition preempted by non-idle tasks. */
  2511. if (unlikely(curr->policy == SCHED_IDLE) &&
  2512. likely(p->policy != SCHED_IDLE))
  2513. goto preempt;
  2514. /*
  2515. * Batch and idle tasks do not preempt non-idle tasks (their preemption
  2516. * is driven by the tick):
  2517. */
  2518. if (unlikely(p->policy != SCHED_NORMAL))
  2519. return;
  2520. find_matching_se(&se, &pse);
  2521. update_curr(cfs_rq_of(se));
  2522. BUG_ON(!pse);
  2523. if (wakeup_preempt_entity(se, pse) == 1) {
  2524. /*
  2525. * Bias pick_next to pick the sched entity that is
  2526. * triggering this preemption.
  2527. */
  2528. if (!next_buddy_marked)
  2529. set_next_buddy(pse);
  2530. goto preempt;
  2531. }
  2532. return;
  2533. preempt:
  2534. resched_task(curr);
  2535. /*
  2536. * Only set the backward buddy when the current task is still
  2537. * on the rq. This can happen when a wakeup gets interleaved
  2538. * with schedule on the ->pre_schedule() or idle_balance()
  2539. * point, either of which can * drop the rq lock.
  2540. *
  2541. * Also, during early boot the idle thread is in the fair class,
  2542. * for obvious reasons its a bad idea to schedule back to it.
  2543. */
  2544. if (unlikely(!se->on_rq || curr == rq->idle))
  2545. return;
  2546. if (sched_feat(LAST_BUDDY) && scale && entity_is_task(se))
  2547. set_last_buddy(se);
  2548. }
  2549. static struct task_struct *pick_next_task_fair(struct rq *rq)
  2550. {
  2551. struct task_struct *p;
  2552. struct cfs_rq *cfs_rq = &rq->cfs;
  2553. struct sched_entity *se;
  2554. if (!cfs_rq->nr_running)
  2555. return NULL;
  2556. do {
  2557. se = pick_next_entity(cfs_rq);
  2558. set_next_entity(cfs_rq, se);
  2559. cfs_rq = group_cfs_rq(se);
  2560. } while (cfs_rq);
  2561. p = task_of(se);
  2562. if (hrtick_enabled(rq))
  2563. hrtick_start_fair(rq, p);
  2564. return p;
  2565. }
  2566. /*
  2567. * Account for a descheduled task:
  2568. */
  2569. static void put_prev_task_fair(struct rq *rq, struct task_struct *prev)
  2570. {
  2571. struct sched_entity *se = &prev->se;
  2572. struct cfs_rq *cfs_rq;
  2573. for_each_sched_entity(se) {
  2574. cfs_rq = cfs_rq_of(se);
  2575. put_prev_entity(cfs_rq, se);
  2576. }
  2577. }
  2578. /*
  2579. * sched_yield() is very simple
  2580. *
  2581. * The magic of dealing with the ->skip buddy is in pick_next_entity.
  2582. */
  2583. static void yield_task_fair(struct rq *rq)
  2584. {
  2585. struct task_struct *curr = rq->curr;
  2586. struct cfs_rq *cfs_rq = task_cfs_rq(curr);
  2587. struct sched_entity *se = &curr->se;
  2588. /*
  2589. * Are we the only task in the tree?
  2590. */
  2591. if (unlikely(rq->nr_running == 1))
  2592. return;
  2593. clear_buddies(cfs_rq, se);
  2594. if (curr->policy != SCHED_BATCH) {
  2595. update_rq_clock(rq);
  2596. /*
  2597. * Update run-time statistics of the 'current'.
  2598. */
  2599. update_curr(cfs_rq);
  2600. /*
  2601. * Tell update_rq_clock() that we've just updated,
  2602. * so we don't do microscopic update in schedule()
  2603. * and double the fastpath cost.
  2604. */
  2605. rq->skip_clock_update = 1;
  2606. }
  2607. set_skip_buddy(se);
  2608. }
  2609. static bool yield_to_task_fair(struct rq *rq, struct task_struct *p, bool preempt)
  2610. {
  2611. struct sched_entity *se = &p->se;
  2612. /* throttled hierarchies are not runnable */
  2613. if (!se->on_rq || throttled_hierarchy(cfs_rq_of(se)))
  2614. return false;
  2615. /* Tell the scheduler that we'd really like pse to run next. */
  2616. set_next_buddy(se);
  2617. yield_task_fair(rq);
  2618. return true;
  2619. }
  2620. #ifdef CONFIG_SMP
  2621. /**************************************************
  2622. * Fair scheduling class load-balancing methods:
  2623. */
  2624. static unsigned long __read_mostly max_load_balance_interval = HZ/10;
  2625. #define LBF_ALL_PINNED 0x01
  2626. #define LBF_NEED_BREAK 0x02
  2627. #define LBF_SOME_PINNED 0x04
  2628. struct lb_env {
  2629. struct sched_domain *sd;
  2630. struct rq *src_rq;
  2631. int src_cpu;
  2632. int dst_cpu;
  2633. struct rq *dst_rq;
  2634. struct cpumask *dst_grpmask;
  2635. int new_dst_cpu;
  2636. enum cpu_idle_type idle;
  2637. long imbalance;
  2638. /* The set of CPUs under consideration for load-balancing */
  2639. struct cpumask *cpus;
  2640. unsigned int flags;
  2641. unsigned int loop;
  2642. unsigned int loop_break;
  2643. unsigned int loop_max;
  2644. };
  2645. /*
  2646. * move_task - move a task from one runqueue to another runqueue.
  2647. * Both runqueues must be locked.
  2648. */
  2649. static void move_task(struct task_struct *p, struct lb_env *env)
  2650. {
  2651. deactivate_task(env->src_rq, p, 0);
  2652. set_task_cpu(p, env->dst_cpu);
  2653. activate_task(env->dst_rq, p, 0);
  2654. check_preempt_curr(env->dst_rq, p, 0);
  2655. }
  2656. /*
  2657. * Is this task likely cache-hot:
  2658. */
  2659. static int
  2660. task_hot(struct task_struct *p, u64 now, struct sched_domain *sd)
  2661. {
  2662. s64 delta;
  2663. if (p->sched_class != &fair_sched_class)
  2664. return 0;
  2665. if (unlikely(p->policy == SCHED_IDLE))
  2666. return 0;
  2667. /*
  2668. * Buddy candidates are cache hot:
  2669. */
  2670. if (sched_feat(CACHE_HOT_BUDDY) && this_rq()->nr_running &&
  2671. (&p->se == cfs_rq_of(&p->se)->next ||
  2672. &p->se == cfs_rq_of(&p->se)->last))
  2673. return 1;
  2674. if (sysctl_sched_migration_cost == -1)
  2675. return 1;
  2676. if (sysctl_sched_migration_cost == 0)
  2677. return 0;
  2678. delta = now - p->se.exec_start;
  2679. return delta < (s64)sysctl_sched_migration_cost;
  2680. }
  2681. /*
  2682. * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
  2683. */
  2684. static
  2685. int can_migrate_task(struct task_struct *p, struct lb_env *env)
  2686. {
  2687. int tsk_cache_hot = 0;
  2688. /*
  2689. * We do not migrate tasks that are:
  2690. * 1) running (obviously), or
  2691. * 2) cannot be migrated to this CPU due to cpus_allowed, or
  2692. * 3) are cache-hot on their current CPU.
  2693. */
  2694. if (!cpumask_test_cpu(env->dst_cpu, tsk_cpus_allowed(p))) {
  2695. int new_dst_cpu;
  2696. schedstat_inc(p, se.statistics.nr_failed_migrations_affine);
  2697. /*
  2698. * Remember if this task can be migrated to any other cpu in
  2699. * our sched_group. We may want to revisit it if we couldn't
  2700. * meet load balance goals by pulling other tasks on src_cpu.
  2701. *
  2702. * Also avoid computing new_dst_cpu if we have already computed
  2703. * one in current iteration.
  2704. */
  2705. if (!env->dst_grpmask || (env->flags & LBF_SOME_PINNED))
  2706. return 0;
  2707. new_dst_cpu = cpumask_first_and(env->dst_grpmask,
  2708. tsk_cpus_allowed(p));
  2709. if (new_dst_cpu < nr_cpu_ids) {
  2710. env->flags |= LBF_SOME_PINNED;
  2711. env->new_dst_cpu = new_dst_cpu;
  2712. }
  2713. return 0;
  2714. }
  2715. /* Record that we found atleast one task that could run on dst_cpu */
  2716. env->flags &= ~LBF_ALL_PINNED;
  2717. if (task_running(env->src_rq, p)) {
  2718. schedstat_inc(p, se.statistics.nr_failed_migrations_running);
  2719. return 0;
  2720. }
  2721. /*
  2722. * Aggressive migration if:
  2723. * 1) task is cache cold, or
  2724. * 2) too many balance attempts have failed.
  2725. */
  2726. tsk_cache_hot = task_hot(p, env->src_rq->clock_task, env->sd);
  2727. if (!tsk_cache_hot ||
  2728. env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
  2729. #ifdef CONFIG_SCHEDSTATS
  2730. if (tsk_cache_hot) {
  2731. schedstat_inc(env->sd, lb_hot_gained[env->idle]);
  2732. schedstat_inc(p, se.statistics.nr_forced_migrations);
  2733. }
  2734. #endif
  2735. return 1;
  2736. }
  2737. if (tsk_cache_hot) {
  2738. schedstat_inc(p, se.statistics.nr_failed_migrations_hot);
  2739. return 0;
  2740. }
  2741. return 1;
  2742. }
  2743. /*
  2744. * move_one_task tries to move exactly one task from busiest to this_rq, as
  2745. * part of active balancing operations within "domain".
  2746. * Returns 1 if successful and 0 otherwise.
  2747. *
  2748. * Called with both runqueues locked.
  2749. */
  2750. static int move_one_task(struct lb_env *env)
  2751. {
  2752. struct task_struct *p, *n;
  2753. list_for_each_entry_safe(p, n, &env->src_rq->cfs_tasks, se.group_node) {
  2754. if (throttled_lb_pair(task_group(p), env->src_rq->cpu, env->dst_cpu))
  2755. continue;
  2756. if (!can_migrate_task(p, env))
  2757. continue;
  2758. move_task(p, env);
  2759. /*
  2760. * Right now, this is only the second place move_task()
  2761. * is called, so we can safely collect move_task()
  2762. * stats here rather than inside move_task().
  2763. */
  2764. schedstat_inc(env->sd, lb_gained[env->idle]);
  2765. return 1;
  2766. }
  2767. return 0;
  2768. }
  2769. static unsigned long task_h_load(struct task_struct *p);
  2770. static const unsigned int sched_nr_migrate_break = 32;
  2771. /*
  2772. * move_tasks tries to move up to imbalance weighted load from busiest to
  2773. * this_rq, as part of a balancing operation within domain "sd".
  2774. * Returns 1 if successful and 0 otherwise.
  2775. *
  2776. * Called with both runqueues locked.
  2777. */
  2778. static int move_tasks(struct lb_env *env)
  2779. {
  2780. struct list_head *tasks = &env->src_rq->cfs_tasks;
  2781. struct task_struct *p;
  2782. unsigned long load;
  2783. int pulled = 0;
  2784. if (env->imbalance <= 0)
  2785. return 0;
  2786. while (!list_empty(tasks)) {
  2787. p = list_first_entry(tasks, struct task_struct, se.group_node);
  2788. env->loop++;
  2789. /* We've more or less seen every task there is, call it quits */
  2790. if (env->loop > env->loop_max)
  2791. break;
  2792. /* take a breather every nr_migrate tasks */
  2793. if (env->loop > env->loop_break) {
  2794. env->loop_break += sched_nr_migrate_break;
  2795. env->flags |= LBF_NEED_BREAK;
  2796. break;
  2797. }
  2798. if (throttled_lb_pair(task_group(p), env->src_cpu, env->dst_cpu))
  2799. goto next;
  2800. load = task_h_load(p);
  2801. if (sched_feat(LB_MIN) && load < 16 && !env->sd->nr_balance_failed)
  2802. goto next;
  2803. if ((load / 2) > env->imbalance)
  2804. goto next;
  2805. if (!can_migrate_task(p, env))
  2806. goto next;
  2807. move_task(p, env);
  2808. pulled++;
  2809. env->imbalance -= load;
  2810. #ifdef CONFIG_PREEMPT
  2811. /*
  2812. * NEWIDLE balancing is a source of latency, so preemptible
  2813. * kernels will stop after the first task is pulled to minimize
  2814. * the critical section.
  2815. */
  2816. if (env->idle == CPU_NEWLY_IDLE)
  2817. break;
  2818. #endif
  2819. /*
  2820. * We only want to steal up to the prescribed amount of
  2821. * weighted load.
  2822. */
  2823. if (env->imbalance <= 0)
  2824. break;
  2825. continue;
  2826. next:
  2827. list_move_tail(&p->se.group_node, tasks);
  2828. }
  2829. /*
  2830. * Right now, this is one of only two places move_task() is called,
  2831. * so we can safely collect move_task() stats here rather than
  2832. * inside move_task().
  2833. */
  2834. schedstat_add(env->sd, lb_gained[env->idle], pulled);
  2835. return pulled;
  2836. }
  2837. #ifdef CONFIG_FAIR_GROUP_SCHED
  2838. /*
  2839. * update tg->load_weight by folding this cpu's load_avg
  2840. */
  2841. static int update_shares_cpu(struct task_group *tg, int cpu)
  2842. {
  2843. struct cfs_rq *cfs_rq;
  2844. unsigned long flags;
  2845. struct rq *rq;
  2846. if (!tg->se[cpu])
  2847. return 0;
  2848. rq = cpu_rq(cpu);
  2849. cfs_rq = tg->cfs_rq[cpu];
  2850. raw_spin_lock_irqsave(&rq->lock, flags);
  2851. update_rq_clock(rq);
  2852. update_cfs_load(cfs_rq, 1);
  2853. /*
  2854. * We need to update shares after updating tg->load_weight in
  2855. * order to adjust the weight of groups with long running tasks.
  2856. */
  2857. update_cfs_shares(cfs_rq);
  2858. raw_spin_unlock_irqrestore(&rq->lock, flags);
  2859. return 0;
  2860. }
  2861. static void update_shares(int cpu)
  2862. {
  2863. struct cfs_rq *cfs_rq;
  2864. struct rq *rq = cpu_rq(cpu);
  2865. rcu_read_lock();
  2866. /*
  2867. * Iterates the task_group tree in a bottom up fashion, see
  2868. * list_add_leaf_cfs_rq() for details.
  2869. */
  2870. for_each_leaf_cfs_rq(rq, cfs_rq) {
  2871. /* throttled entities do not contribute to load */
  2872. if (throttled_hierarchy(cfs_rq))
  2873. continue;
  2874. update_shares_cpu(cfs_rq->tg, cpu);
  2875. }
  2876. rcu_read_unlock();
  2877. }
  2878. /*
  2879. * Compute the cpu's hierarchical load factor for each task group.
  2880. * This needs to be done in a top-down fashion because the load of a child
  2881. * group is a fraction of its parents load.
  2882. */
  2883. static int tg_load_down(struct task_group *tg, void *data)
  2884. {
  2885. unsigned long load;
  2886. long cpu = (long)data;
  2887. if (!tg->parent) {
  2888. load = cpu_rq(cpu)->load.weight;
  2889. } else {
  2890. load = tg->parent->cfs_rq[cpu]->h_load;
  2891. load *= tg->se[cpu]->load.weight;
  2892. load /= tg->parent->cfs_rq[cpu]->load.weight + 1;
  2893. }
  2894. tg->cfs_rq[cpu]->h_load = load;
  2895. return 0;
  2896. }
  2897. static void update_h_load(long cpu)
  2898. {
  2899. struct rq *rq = cpu_rq(cpu);
  2900. unsigned long now = jiffies;
  2901. if (rq->h_load_throttle == now)
  2902. return;
  2903. rq->h_load_throttle = now;
  2904. rcu_read_lock();
  2905. walk_tg_tree(tg_load_down, tg_nop, (void *)cpu);
  2906. rcu_read_unlock();
  2907. }
  2908. static unsigned long task_h_load(struct task_struct *p)
  2909. {
  2910. struct cfs_rq *cfs_rq = task_cfs_rq(p);
  2911. unsigned long load;
  2912. load = p->se.load.weight;
  2913. load = div_u64(load * cfs_rq->h_load, cfs_rq->load.weight + 1);
  2914. return load;
  2915. }
  2916. #else
  2917. static inline void update_shares(int cpu)
  2918. {
  2919. }
  2920. static inline void update_h_load(long cpu)
  2921. {
  2922. }
  2923. static unsigned long task_h_load(struct task_struct *p)
  2924. {
  2925. return p->se.load.weight;
  2926. }
  2927. #endif
  2928. /********** Helpers for find_busiest_group ************************/
  2929. /*
  2930. * sd_lb_stats - Structure to store the statistics of a sched_domain
  2931. * during load balancing.
  2932. */
  2933. struct sd_lb_stats {
  2934. struct sched_group *busiest; /* Busiest group in this sd */
  2935. struct sched_group *this; /* Local group in this sd */
  2936. unsigned long total_load; /* Total load of all groups in sd */
  2937. unsigned long total_pwr; /* Total power of all groups in sd */
  2938. unsigned long avg_load; /* Average load across all groups in sd */
  2939. /** Statistics of this group */
  2940. unsigned long this_load;
  2941. unsigned long this_load_per_task;
  2942. unsigned long this_nr_running;
  2943. unsigned long this_has_capacity;
  2944. unsigned int this_idle_cpus;
  2945. /* Statistics of the busiest group */
  2946. unsigned int busiest_idle_cpus;
  2947. unsigned long max_load;
  2948. unsigned long busiest_load_per_task;
  2949. unsigned long busiest_nr_running;
  2950. unsigned long busiest_group_capacity;
  2951. unsigned long busiest_has_capacity;
  2952. unsigned int busiest_group_weight;
  2953. int group_imb; /* Is there imbalance in this sd */
  2954. };
  2955. /*
  2956. * sg_lb_stats - stats of a sched_group required for load_balancing
  2957. */
  2958. struct sg_lb_stats {
  2959. unsigned long avg_load; /*Avg load across the CPUs of the group */
  2960. unsigned long group_load; /* Total load over the CPUs of the group */
  2961. unsigned long sum_nr_running; /* Nr tasks running in the group */
  2962. unsigned long sum_weighted_load; /* Weighted load of group's tasks */
  2963. unsigned long group_capacity;
  2964. unsigned long idle_cpus;
  2965. unsigned long group_weight;
  2966. int group_imb; /* Is there an imbalance in the group ? */
  2967. int group_has_capacity; /* Is there extra capacity in the group? */
  2968. };
  2969. /**
  2970. * get_sd_load_idx - Obtain the load index for a given sched domain.
  2971. * @sd: The sched_domain whose load_idx is to be obtained.
  2972. * @idle: The Idle status of the CPU for whose sd load_icx is obtained.
  2973. */
  2974. static inline int get_sd_load_idx(struct sched_domain *sd,
  2975. enum cpu_idle_type idle)
  2976. {
  2977. int load_idx;
  2978. switch (idle) {
  2979. case CPU_NOT_IDLE:
  2980. load_idx = sd->busy_idx;
  2981. break;
  2982. case CPU_NEWLY_IDLE:
  2983. load_idx = sd->newidle_idx;
  2984. break;
  2985. default:
  2986. load_idx = sd->idle_idx;
  2987. break;
  2988. }
  2989. return load_idx;
  2990. }
  2991. unsigned long default_scale_freq_power(struct sched_domain *sd, int cpu)
  2992. {
  2993. return SCHED_POWER_SCALE;
  2994. }
  2995. unsigned long __weak arch_scale_freq_power(struct sched_domain *sd, int cpu)
  2996. {
  2997. return default_scale_freq_power(sd, cpu);
  2998. }
  2999. unsigned long default_scale_smt_power(struct sched_domain *sd, int cpu)
  3000. {
  3001. unsigned long weight = sd->span_weight;
  3002. unsigned long smt_gain = sd->smt_gain;
  3003. smt_gain /= weight;
  3004. return smt_gain;
  3005. }
  3006. unsigned long __weak arch_scale_smt_power(struct sched_domain *sd, int cpu)
  3007. {
  3008. return default_scale_smt_power(sd, cpu);
  3009. }
  3010. unsigned long scale_rt_power(int cpu)
  3011. {
  3012. struct rq *rq = cpu_rq(cpu);
  3013. u64 total, available, age_stamp, avg;
  3014. /*
  3015. * Since we're reading these variables without serialization make sure
  3016. * we read them once before doing sanity checks on them.
  3017. */
  3018. age_stamp = ACCESS_ONCE(rq->age_stamp);
  3019. avg = ACCESS_ONCE(rq->rt_avg);
  3020. total = sched_avg_period() + (rq->clock - age_stamp);
  3021. if (unlikely(total < avg)) {
  3022. /* Ensures that power won't end up being negative */
  3023. available = 0;
  3024. } else {
  3025. available = total - avg;
  3026. }
  3027. if (unlikely((s64)total < SCHED_POWER_SCALE))
  3028. total = SCHED_POWER_SCALE;
  3029. total >>= SCHED_POWER_SHIFT;
  3030. return div_u64(available, total);
  3031. }
  3032. static void update_cpu_power(struct sched_domain *sd, int cpu)
  3033. {
  3034. unsigned long weight = sd->span_weight;
  3035. unsigned long power = SCHED_POWER_SCALE;
  3036. struct sched_group *sdg = sd->groups;
  3037. if ((sd->flags & SD_SHARE_CPUPOWER) && weight > 1) {
  3038. if (sched_feat(ARCH_POWER))
  3039. power *= arch_scale_smt_power(sd, cpu);
  3040. else
  3041. power *= default_scale_smt_power(sd, cpu);
  3042. power >>= SCHED_POWER_SHIFT;
  3043. }
  3044. sdg->sgp->power_orig = power;
  3045. if (sched_feat(ARCH_POWER))
  3046. power *= arch_scale_freq_power(sd, cpu);
  3047. else
  3048. power *= default_scale_freq_power(sd, cpu);
  3049. power >>= SCHED_POWER_SHIFT;
  3050. power *= scale_rt_power(cpu);
  3051. power >>= SCHED_POWER_SHIFT;
  3052. if (!power)
  3053. power = 1;
  3054. cpu_rq(cpu)->cpu_power = power;
  3055. sdg->sgp->power = power;
  3056. }
  3057. void update_group_power(struct sched_domain *sd, int cpu)
  3058. {
  3059. struct sched_domain *child = sd->child;
  3060. struct sched_group *group, *sdg = sd->groups;
  3061. unsigned long power;
  3062. unsigned long interval;
  3063. interval = msecs_to_jiffies(sd->balance_interval);
  3064. interval = clamp(interval, 1UL, max_load_balance_interval);
  3065. sdg->sgp->next_update = jiffies + interval;
  3066. if (!child) {
  3067. update_cpu_power(sd, cpu);
  3068. return;
  3069. }
  3070. power = 0;
  3071. if (child->flags & SD_OVERLAP) {
  3072. /*
  3073. * SD_OVERLAP domains cannot assume that child groups
  3074. * span the current group.
  3075. */
  3076. for_each_cpu(cpu, sched_group_cpus(sdg))
  3077. power += power_of(cpu);
  3078. } else {
  3079. /*
  3080. * !SD_OVERLAP domains can assume that child groups
  3081. * span the current group.
  3082. */
  3083. group = child->groups;
  3084. do {
  3085. power += group->sgp->power;
  3086. group = group->next;
  3087. } while (group != child->groups);
  3088. }
  3089. sdg->sgp->power_orig = sdg->sgp->power = power;
  3090. }
  3091. /*
  3092. * Try and fix up capacity for tiny siblings, this is needed when
  3093. * things like SD_ASYM_PACKING need f_b_g to select another sibling
  3094. * which on its own isn't powerful enough.
  3095. *
  3096. * See update_sd_pick_busiest() and check_asym_packing().
  3097. */
  3098. static inline int
  3099. fix_small_capacity(struct sched_domain *sd, struct sched_group *group)
  3100. {
  3101. /*
  3102. * Only siblings can have significantly less than SCHED_POWER_SCALE
  3103. */
  3104. if (!(sd->flags & SD_SHARE_CPUPOWER))
  3105. return 0;
  3106. /*
  3107. * If ~90% of the cpu_power is still there, we're good.
  3108. */
  3109. if (group->sgp->power * 32 > group->sgp->power_orig * 29)
  3110. return 1;
  3111. return 0;
  3112. }
  3113. /**
  3114. * update_sg_lb_stats - Update sched_group's statistics for load balancing.
  3115. * @env: The load balancing environment.
  3116. * @group: sched_group whose statistics are to be updated.
  3117. * @load_idx: Load index of sched_domain of this_cpu for load calc.
  3118. * @local_group: Does group contain this_cpu.
  3119. * @balance: Should we balance.
  3120. * @sgs: variable to hold the statistics for this group.
  3121. */
  3122. static inline void update_sg_lb_stats(struct lb_env *env,
  3123. struct sched_group *group, int load_idx,
  3124. int local_group, int *balance, struct sg_lb_stats *sgs)
  3125. {
  3126. unsigned long nr_running, max_nr_running, min_nr_running;
  3127. unsigned long load, max_cpu_load, min_cpu_load;
  3128. unsigned int balance_cpu = -1, first_idle_cpu = 0;
  3129. unsigned long avg_load_per_task = 0;
  3130. int i;
  3131. if (local_group)
  3132. balance_cpu = group_balance_cpu(group);
  3133. /* Tally up the load of all CPUs in the group */
  3134. max_cpu_load = 0;
  3135. min_cpu_load = ~0UL;
  3136. max_nr_running = 0;
  3137. min_nr_running = ~0UL;
  3138. for_each_cpu_and(i, sched_group_cpus(group), env->cpus) {
  3139. struct rq *rq = cpu_rq(i);
  3140. nr_running = rq->nr_running;
  3141. /* Bias balancing toward cpus of our domain */
  3142. if (local_group) {
  3143. if (idle_cpu(i) && !first_idle_cpu &&
  3144. cpumask_test_cpu(i, sched_group_mask(group))) {
  3145. first_idle_cpu = 1;
  3146. balance_cpu = i;
  3147. }
  3148. load = target_load(i, load_idx);
  3149. } else {
  3150. load = source_load(i, load_idx);
  3151. if (load > max_cpu_load)
  3152. max_cpu_load = load;
  3153. if (min_cpu_load > load)
  3154. min_cpu_load = load;
  3155. if (nr_running > max_nr_running)
  3156. max_nr_running = nr_running;
  3157. if (min_nr_running > nr_running)
  3158. min_nr_running = nr_running;
  3159. }
  3160. sgs->group_load += load;
  3161. sgs->sum_nr_running += nr_running;
  3162. sgs->sum_weighted_load += weighted_cpuload(i);
  3163. if (idle_cpu(i))
  3164. sgs->idle_cpus++;
  3165. }
  3166. /*
  3167. * First idle cpu or the first cpu(busiest) in this sched group
  3168. * is eligible for doing load balancing at this and above
  3169. * domains. In the newly idle case, we will allow all the cpu's
  3170. * to do the newly idle load balance.
  3171. */
  3172. if (local_group) {
  3173. if (env->idle != CPU_NEWLY_IDLE) {
  3174. if (balance_cpu != env->dst_cpu) {
  3175. *balance = 0;
  3176. return;
  3177. }
  3178. update_group_power(env->sd, env->dst_cpu);
  3179. } else if (time_after_eq(jiffies, group->sgp->next_update))
  3180. update_group_power(env->sd, env->dst_cpu);
  3181. }
  3182. /* Adjust by relative CPU power of the group */
  3183. sgs->avg_load = (sgs->group_load*SCHED_POWER_SCALE) / group->sgp->power;
  3184. /*
  3185. * Consider the group unbalanced when the imbalance is larger
  3186. * than the average weight of a task.
  3187. *
  3188. * APZ: with cgroup the avg task weight can vary wildly and
  3189. * might not be a suitable number - should we keep a
  3190. * normalized nr_running number somewhere that negates
  3191. * the hierarchy?
  3192. */
  3193. if (sgs->sum_nr_running)
  3194. avg_load_per_task = sgs->sum_weighted_load / sgs->sum_nr_running;
  3195. if ((max_cpu_load - min_cpu_load) >= avg_load_per_task &&
  3196. (max_nr_running - min_nr_running) > 1)
  3197. sgs->group_imb = 1;
  3198. sgs->group_capacity = DIV_ROUND_CLOSEST(group->sgp->power,
  3199. SCHED_POWER_SCALE);
  3200. if (!sgs->group_capacity)
  3201. sgs->group_capacity = fix_small_capacity(env->sd, group);
  3202. sgs->group_weight = group->group_weight;
  3203. if (sgs->group_capacity > sgs->sum_nr_running)
  3204. sgs->group_has_capacity = 1;
  3205. }
  3206. /**
  3207. * update_sd_pick_busiest - return 1 on busiest group
  3208. * @env: The load balancing environment.
  3209. * @sds: sched_domain statistics
  3210. * @sg: sched_group candidate to be checked for being the busiest
  3211. * @sgs: sched_group statistics
  3212. *
  3213. * Determine if @sg is a busier group than the previously selected
  3214. * busiest group.
  3215. */
  3216. static bool update_sd_pick_busiest(struct lb_env *env,
  3217. struct sd_lb_stats *sds,
  3218. struct sched_group *sg,
  3219. struct sg_lb_stats *sgs)
  3220. {
  3221. if (sgs->avg_load <= sds->max_load)
  3222. return false;
  3223. if (sgs->sum_nr_running > sgs->group_capacity)
  3224. return true;
  3225. if (sgs->group_imb)
  3226. return true;
  3227. /*
  3228. * ASYM_PACKING needs to move all the work to the lowest
  3229. * numbered CPUs in the group, therefore mark all groups
  3230. * higher than ourself as busy.
  3231. */
  3232. if ((env->sd->flags & SD_ASYM_PACKING) && sgs->sum_nr_running &&
  3233. env->dst_cpu < group_first_cpu(sg)) {
  3234. if (!sds->busiest)
  3235. return true;
  3236. if (group_first_cpu(sds->busiest) > group_first_cpu(sg))
  3237. return true;
  3238. }
  3239. return false;
  3240. }
  3241. /**
  3242. * update_sd_lb_stats - Update sched_domain's statistics for load balancing.
  3243. * @env: The load balancing environment.
  3244. * @balance: Should we balance.
  3245. * @sds: variable to hold the statistics for this sched_domain.
  3246. */
  3247. static inline void update_sd_lb_stats(struct lb_env *env,
  3248. int *balance, struct sd_lb_stats *sds)
  3249. {
  3250. struct sched_domain *child = env->sd->child;
  3251. struct sched_group *sg = env->sd->groups;
  3252. struct sg_lb_stats sgs;
  3253. int load_idx, prefer_sibling = 0;
  3254. if (child && child->flags & SD_PREFER_SIBLING)
  3255. prefer_sibling = 1;
  3256. load_idx = get_sd_load_idx(env->sd, env->idle);
  3257. do {
  3258. int local_group;
  3259. local_group = cpumask_test_cpu(env->dst_cpu, sched_group_cpus(sg));
  3260. memset(&sgs, 0, sizeof(sgs));
  3261. update_sg_lb_stats(env, sg, load_idx, local_group, balance, &sgs);
  3262. if (local_group && !(*balance))
  3263. return;
  3264. sds->total_load += sgs.group_load;
  3265. sds->total_pwr += sg->sgp->power;
  3266. /*
  3267. * In case the child domain prefers tasks go to siblings
  3268. * first, lower the sg capacity to one so that we'll try
  3269. * and move all the excess tasks away. We lower the capacity
  3270. * of a group only if the local group has the capacity to fit
  3271. * these excess tasks, i.e. nr_running < group_capacity. The
  3272. * extra check prevents the case where you always pull from the
  3273. * heaviest group when it is already under-utilized (possible
  3274. * with a large weight task outweighs the tasks on the system).
  3275. */
  3276. if (prefer_sibling && !local_group && sds->this_has_capacity)
  3277. sgs.group_capacity = min(sgs.group_capacity, 1UL);
  3278. if (local_group) {
  3279. sds->this_load = sgs.avg_load;
  3280. sds->this = sg;
  3281. sds->this_nr_running = sgs.sum_nr_running;
  3282. sds->this_load_per_task = sgs.sum_weighted_load;
  3283. sds->this_has_capacity = sgs.group_has_capacity;
  3284. sds->this_idle_cpus = sgs.idle_cpus;
  3285. } else if (update_sd_pick_busiest(env, sds, sg, &sgs)) {
  3286. sds->max_load = sgs.avg_load;
  3287. sds->busiest = sg;
  3288. sds->busiest_nr_running = sgs.sum_nr_running;
  3289. sds->busiest_idle_cpus = sgs.idle_cpus;
  3290. sds->busiest_group_capacity = sgs.group_capacity;
  3291. sds->busiest_load_per_task = sgs.sum_weighted_load;
  3292. sds->busiest_has_capacity = sgs.group_has_capacity;
  3293. sds->busiest_group_weight = sgs.group_weight;
  3294. sds->group_imb = sgs.group_imb;
  3295. }
  3296. sg = sg->next;
  3297. } while (sg != env->sd->groups);
  3298. }
  3299. /**
  3300. * check_asym_packing - Check to see if the group is packed into the
  3301. * sched doman.
  3302. *
  3303. * This is primarily intended to used at the sibling level. Some
  3304. * cores like POWER7 prefer to use lower numbered SMT threads. In the
  3305. * case of POWER7, it can move to lower SMT modes only when higher
  3306. * threads are idle. When in lower SMT modes, the threads will
  3307. * perform better since they share less core resources. Hence when we
  3308. * have idle threads, we want them to be the higher ones.
  3309. *
  3310. * This packing function is run on idle threads. It checks to see if
  3311. * the busiest CPU in this domain (core in the P7 case) has a higher
  3312. * CPU number than the packing function is being run on. Here we are
  3313. * assuming lower CPU number will be equivalent to lower a SMT thread
  3314. * number.
  3315. *
  3316. * Returns 1 when packing is required and a task should be moved to
  3317. * this CPU. The amount of the imbalance is returned in *imbalance.
  3318. *
  3319. * @env: The load balancing environment.
  3320. * @sds: Statistics of the sched_domain which is to be packed
  3321. */
  3322. static int check_asym_packing(struct lb_env *env, struct sd_lb_stats *sds)
  3323. {
  3324. int busiest_cpu;
  3325. if (!(env->sd->flags & SD_ASYM_PACKING))
  3326. return 0;
  3327. if (!sds->busiest)
  3328. return 0;
  3329. busiest_cpu = group_first_cpu(sds->busiest);
  3330. if (env->dst_cpu > busiest_cpu)
  3331. return 0;
  3332. env->imbalance = DIV_ROUND_CLOSEST(
  3333. sds->max_load * sds->busiest->sgp->power, SCHED_POWER_SCALE);
  3334. return 1;
  3335. }
  3336. /**
  3337. * fix_small_imbalance - Calculate the minor imbalance that exists
  3338. * amongst the groups of a sched_domain, during
  3339. * load balancing.
  3340. * @env: The load balancing environment.
  3341. * @sds: Statistics of the sched_domain whose imbalance is to be calculated.
  3342. */
  3343. static inline
  3344. void fix_small_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
  3345. {
  3346. unsigned long tmp, pwr_now = 0, pwr_move = 0;
  3347. unsigned int imbn = 2;
  3348. unsigned long scaled_busy_load_per_task;
  3349. if (sds->this_nr_running) {
  3350. sds->this_load_per_task /= sds->this_nr_running;
  3351. if (sds->busiest_load_per_task >
  3352. sds->this_load_per_task)
  3353. imbn = 1;
  3354. } else {
  3355. sds->this_load_per_task =
  3356. cpu_avg_load_per_task(env->dst_cpu);
  3357. }
  3358. scaled_busy_load_per_task = sds->busiest_load_per_task
  3359. * SCHED_POWER_SCALE;
  3360. scaled_busy_load_per_task /= sds->busiest->sgp->power;
  3361. if (sds->max_load - sds->this_load + scaled_busy_load_per_task >=
  3362. (scaled_busy_load_per_task * imbn)) {
  3363. env->imbalance = sds->busiest_load_per_task;
  3364. return;
  3365. }
  3366. /*
  3367. * OK, we don't have enough imbalance to justify moving tasks,
  3368. * however we may be able to increase total CPU power used by
  3369. * moving them.
  3370. */
  3371. pwr_now += sds->busiest->sgp->power *
  3372. min(sds->busiest_load_per_task, sds->max_load);
  3373. pwr_now += sds->this->sgp->power *
  3374. min(sds->this_load_per_task, sds->this_load);
  3375. pwr_now /= SCHED_POWER_SCALE;
  3376. /* Amount of load we'd subtract */
  3377. tmp = (sds->busiest_load_per_task * SCHED_POWER_SCALE) /
  3378. sds->busiest->sgp->power;
  3379. if (sds->max_load > tmp)
  3380. pwr_move += sds->busiest->sgp->power *
  3381. min(sds->busiest_load_per_task, sds->max_load - tmp);
  3382. /* Amount of load we'd add */
  3383. if (sds->max_load * sds->busiest->sgp->power <
  3384. sds->busiest_load_per_task * SCHED_POWER_SCALE)
  3385. tmp = (sds->max_load * sds->busiest->sgp->power) /
  3386. sds->this->sgp->power;
  3387. else
  3388. tmp = (sds->busiest_load_per_task * SCHED_POWER_SCALE) /
  3389. sds->this->sgp->power;
  3390. pwr_move += sds->this->sgp->power *
  3391. min(sds->this_load_per_task, sds->this_load + tmp);
  3392. pwr_move /= SCHED_POWER_SCALE;
  3393. /* Move if we gain throughput */
  3394. if (pwr_move > pwr_now)
  3395. env->imbalance = sds->busiest_load_per_task;
  3396. }
  3397. /**
  3398. * calculate_imbalance - Calculate the amount of imbalance present within the
  3399. * groups of a given sched_domain during load balance.
  3400. * @env: load balance environment
  3401. * @sds: statistics of the sched_domain whose imbalance is to be calculated.
  3402. */
  3403. static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
  3404. {
  3405. unsigned long max_pull, load_above_capacity = ~0UL;
  3406. sds->busiest_load_per_task /= sds->busiest_nr_running;
  3407. if (sds->group_imb) {
  3408. sds->busiest_load_per_task =
  3409. min(sds->busiest_load_per_task, sds->avg_load);
  3410. }
  3411. /*
  3412. * In the presence of smp nice balancing, certain scenarios can have
  3413. * max load less than avg load(as we skip the groups at or below
  3414. * its cpu_power, while calculating max_load..)
  3415. */
  3416. if (sds->max_load < sds->avg_load) {
  3417. env->imbalance = 0;
  3418. return fix_small_imbalance(env, sds);
  3419. }
  3420. if (!sds->group_imb) {
  3421. /*
  3422. * Don't want to pull so many tasks that a group would go idle.
  3423. */
  3424. load_above_capacity = (sds->busiest_nr_running -
  3425. sds->busiest_group_capacity);
  3426. load_above_capacity *= (SCHED_LOAD_SCALE * SCHED_POWER_SCALE);
  3427. load_above_capacity /= sds->busiest->sgp->power;
  3428. }
  3429. /*
  3430. * We're trying to get all the cpus to the average_load, so we don't
  3431. * want to push ourselves above the average load, nor do we wish to
  3432. * reduce the max loaded cpu below the average load. At the same time,
  3433. * we also don't want to reduce the group load below the group capacity
  3434. * (so that we can implement power-savings policies etc). Thus we look
  3435. * for the minimum possible imbalance.
  3436. * Be careful of negative numbers as they'll appear as very large values
  3437. * with unsigned longs.
  3438. */
  3439. max_pull = min(sds->max_load - sds->avg_load, load_above_capacity);
  3440. /* How much load to actually move to equalise the imbalance */
  3441. env->imbalance = min(max_pull * sds->busiest->sgp->power,
  3442. (sds->avg_load - sds->this_load) * sds->this->sgp->power)
  3443. / SCHED_POWER_SCALE;
  3444. /*
  3445. * if *imbalance is less than the average load per runnable task
  3446. * there is no guarantee that any tasks will be moved so we'll have
  3447. * a think about bumping its value to force at least one task to be
  3448. * moved
  3449. */
  3450. if (env->imbalance < sds->busiest_load_per_task)
  3451. return fix_small_imbalance(env, sds);
  3452. }
  3453. /******* find_busiest_group() helpers end here *********************/
  3454. /**
  3455. * find_busiest_group - Returns the busiest group within the sched_domain
  3456. * if there is an imbalance. If there isn't an imbalance, and
  3457. * the user has opted for power-savings, it returns a group whose
  3458. * CPUs can be put to idle by rebalancing those tasks elsewhere, if
  3459. * such a group exists.
  3460. *
  3461. * Also calculates the amount of weighted load which should be moved
  3462. * to restore balance.
  3463. *
  3464. * @env: The load balancing environment.
  3465. * @balance: Pointer to a variable indicating if this_cpu
  3466. * is the appropriate cpu to perform load balancing at this_level.
  3467. *
  3468. * Returns: - the busiest group if imbalance exists.
  3469. * - If no imbalance and user has opted for power-savings balance,
  3470. * return the least loaded group whose CPUs can be
  3471. * put to idle by rebalancing its tasks onto our group.
  3472. */
  3473. static struct sched_group *
  3474. find_busiest_group(struct lb_env *env, int *balance)
  3475. {
  3476. struct sd_lb_stats sds;
  3477. memset(&sds, 0, sizeof(sds));
  3478. /*
  3479. * Compute the various statistics relavent for load balancing at
  3480. * this level.
  3481. */
  3482. update_sd_lb_stats(env, balance, &sds);
  3483. /*
  3484. * this_cpu is not the appropriate cpu to perform load balancing at
  3485. * this level.
  3486. */
  3487. if (!(*balance))
  3488. goto ret;
  3489. if ((env->idle == CPU_IDLE || env->idle == CPU_NEWLY_IDLE) &&
  3490. check_asym_packing(env, &sds))
  3491. return sds.busiest;
  3492. /* There is no busy sibling group to pull tasks from */
  3493. if (!sds.busiest || sds.busiest_nr_running == 0)
  3494. goto out_balanced;
  3495. sds.avg_load = (SCHED_POWER_SCALE * sds.total_load) / sds.total_pwr;
  3496. /*
  3497. * If the busiest group is imbalanced the below checks don't
  3498. * work because they assumes all things are equal, which typically
  3499. * isn't true due to cpus_allowed constraints and the like.
  3500. */
  3501. if (sds.group_imb)
  3502. goto force_balance;
  3503. /* SD_BALANCE_NEWIDLE trumps SMP nice when underutilized */
  3504. if (env->idle == CPU_NEWLY_IDLE && sds.this_has_capacity &&
  3505. !sds.busiest_has_capacity)
  3506. goto force_balance;
  3507. /*
  3508. * If the local group is more busy than the selected busiest group
  3509. * don't try and pull any tasks.
  3510. */
  3511. if (sds.this_load >= sds.max_load)
  3512. goto out_balanced;
  3513. /*
  3514. * Don't pull any tasks if this group is already above the domain
  3515. * average load.
  3516. */
  3517. if (sds.this_load >= sds.avg_load)
  3518. goto out_balanced;
  3519. if (env->idle == CPU_IDLE) {
  3520. /*
  3521. * This cpu is idle. If the busiest group load doesn't
  3522. * have more tasks than the number of available cpu's and
  3523. * there is no imbalance between this and busiest group
  3524. * wrt to idle cpu's, it is balanced.
  3525. */
  3526. if ((sds.this_idle_cpus <= sds.busiest_idle_cpus + 1) &&
  3527. sds.busiest_nr_running <= sds.busiest_group_weight)
  3528. goto out_balanced;
  3529. } else {
  3530. /*
  3531. * In the CPU_NEWLY_IDLE, CPU_NOT_IDLE cases, use
  3532. * imbalance_pct to be conservative.
  3533. */
  3534. if (100 * sds.max_load <= env->sd->imbalance_pct * sds.this_load)
  3535. goto out_balanced;
  3536. }
  3537. force_balance:
  3538. /* Looks like there is an imbalance. Compute it */
  3539. calculate_imbalance(env, &sds);
  3540. return sds.busiest;
  3541. out_balanced:
  3542. ret:
  3543. env->imbalance = 0;
  3544. return NULL;
  3545. }
  3546. /*
  3547. * find_busiest_queue - find the busiest runqueue among the cpus in group.
  3548. */
  3549. static struct rq *find_busiest_queue(struct lb_env *env,
  3550. struct sched_group *group)
  3551. {
  3552. struct rq *busiest = NULL, *rq;
  3553. unsigned long max_load = 0;
  3554. int i;
  3555. for_each_cpu(i, sched_group_cpus(group)) {
  3556. unsigned long power = power_of(i);
  3557. unsigned long capacity = DIV_ROUND_CLOSEST(power,
  3558. SCHED_POWER_SCALE);
  3559. unsigned long wl;
  3560. if (!capacity)
  3561. capacity = fix_small_capacity(env->sd, group);
  3562. if (!cpumask_test_cpu(i, env->cpus))
  3563. continue;
  3564. rq = cpu_rq(i);
  3565. wl = weighted_cpuload(i);
  3566. /*
  3567. * When comparing with imbalance, use weighted_cpuload()
  3568. * which is not scaled with the cpu power.
  3569. */
  3570. if (capacity && rq->nr_running == 1 && wl > env->imbalance)
  3571. continue;
  3572. /*
  3573. * For the load comparisons with the other cpu's, consider
  3574. * the weighted_cpuload() scaled with the cpu power, so that
  3575. * the load can be moved away from the cpu that is potentially
  3576. * running at a lower capacity.
  3577. */
  3578. wl = (wl * SCHED_POWER_SCALE) / power;
  3579. if (wl > max_load) {
  3580. max_load = wl;
  3581. busiest = rq;
  3582. }
  3583. }
  3584. return busiest;
  3585. }
  3586. /*
  3587. * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
  3588. * so long as it is large enough.
  3589. */
  3590. #define MAX_PINNED_INTERVAL 512
  3591. /* Working cpumask for load_balance and load_balance_newidle. */
  3592. DEFINE_PER_CPU(cpumask_var_t, load_balance_tmpmask);
  3593. static int need_active_balance(struct lb_env *env)
  3594. {
  3595. struct sched_domain *sd = env->sd;
  3596. if (env->idle == CPU_NEWLY_IDLE) {
  3597. /*
  3598. * ASYM_PACKING needs to force migrate tasks from busy but
  3599. * higher numbered CPUs in order to pack all tasks in the
  3600. * lowest numbered CPUs.
  3601. */
  3602. if ((sd->flags & SD_ASYM_PACKING) && env->src_cpu > env->dst_cpu)
  3603. return 1;
  3604. }
  3605. return unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2);
  3606. }
  3607. static int active_load_balance_cpu_stop(void *data);
  3608. /*
  3609. * Check this_cpu to ensure it is balanced within domain. Attempt to move
  3610. * tasks if there is an imbalance.
  3611. */
  3612. static int load_balance(int this_cpu, struct rq *this_rq,
  3613. struct sched_domain *sd, enum cpu_idle_type idle,
  3614. int *balance)
  3615. {
  3616. int ld_moved, cur_ld_moved, active_balance = 0;
  3617. int lb_iterations, max_lb_iterations;
  3618. struct sched_group *group;
  3619. struct rq *busiest;
  3620. unsigned long flags;
  3621. struct cpumask *cpus = __get_cpu_var(load_balance_tmpmask);
  3622. struct lb_env env = {
  3623. .sd = sd,
  3624. .dst_cpu = this_cpu,
  3625. .dst_rq = this_rq,
  3626. .dst_grpmask = sched_group_cpus(sd->groups),
  3627. .idle = idle,
  3628. .loop_break = sched_nr_migrate_break,
  3629. .cpus = cpus,
  3630. };
  3631. cpumask_copy(cpus, cpu_active_mask);
  3632. max_lb_iterations = cpumask_weight(env.dst_grpmask);
  3633. schedstat_inc(sd, lb_count[idle]);
  3634. redo:
  3635. group = find_busiest_group(&env, balance);
  3636. if (*balance == 0)
  3637. goto out_balanced;
  3638. if (!group) {
  3639. schedstat_inc(sd, lb_nobusyg[idle]);
  3640. goto out_balanced;
  3641. }
  3642. busiest = find_busiest_queue(&env, group);
  3643. if (!busiest) {
  3644. schedstat_inc(sd, lb_nobusyq[idle]);
  3645. goto out_balanced;
  3646. }
  3647. BUG_ON(busiest == env.dst_rq);
  3648. schedstat_add(sd, lb_imbalance[idle], env.imbalance);
  3649. ld_moved = 0;
  3650. lb_iterations = 1;
  3651. if (busiest->nr_running > 1) {
  3652. /*
  3653. * Attempt to move tasks. If find_busiest_group has found
  3654. * an imbalance but busiest->nr_running <= 1, the group is
  3655. * still unbalanced. ld_moved simply stays zero, so it is
  3656. * correctly treated as an imbalance.
  3657. */
  3658. env.flags |= LBF_ALL_PINNED;
  3659. env.src_cpu = busiest->cpu;
  3660. env.src_rq = busiest;
  3661. env.loop_max = min(sysctl_sched_nr_migrate, busiest->nr_running);
  3662. update_h_load(env.src_cpu);
  3663. more_balance:
  3664. local_irq_save(flags);
  3665. double_rq_lock(env.dst_rq, busiest);
  3666. /*
  3667. * cur_ld_moved - load moved in current iteration
  3668. * ld_moved - cumulative load moved across iterations
  3669. */
  3670. cur_ld_moved = move_tasks(&env);
  3671. ld_moved += cur_ld_moved;
  3672. double_rq_unlock(env.dst_rq, busiest);
  3673. local_irq_restore(flags);
  3674. if (env.flags & LBF_NEED_BREAK) {
  3675. env.flags &= ~LBF_NEED_BREAK;
  3676. goto more_balance;
  3677. }
  3678. /*
  3679. * some other cpu did the load balance for us.
  3680. */
  3681. if (cur_ld_moved && env.dst_cpu != smp_processor_id())
  3682. resched_cpu(env.dst_cpu);
  3683. /*
  3684. * Revisit (affine) tasks on src_cpu that couldn't be moved to
  3685. * us and move them to an alternate dst_cpu in our sched_group
  3686. * where they can run. The upper limit on how many times we
  3687. * iterate on same src_cpu is dependent on number of cpus in our
  3688. * sched_group.
  3689. *
  3690. * This changes load balance semantics a bit on who can move
  3691. * load to a given_cpu. In addition to the given_cpu itself
  3692. * (or a ilb_cpu acting on its behalf where given_cpu is
  3693. * nohz-idle), we now have balance_cpu in a position to move
  3694. * load to given_cpu. In rare situations, this may cause
  3695. * conflicts (balance_cpu and given_cpu/ilb_cpu deciding
  3696. * _independently_ and at _same_ time to move some load to
  3697. * given_cpu) causing exceess load to be moved to given_cpu.
  3698. * This however should not happen so much in practice and
  3699. * moreover subsequent load balance cycles should correct the
  3700. * excess load moved.
  3701. */
  3702. if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0 &&
  3703. lb_iterations++ < max_lb_iterations) {
  3704. env.dst_rq = cpu_rq(env.new_dst_cpu);
  3705. env.dst_cpu = env.new_dst_cpu;
  3706. env.flags &= ~LBF_SOME_PINNED;
  3707. env.loop = 0;
  3708. env.loop_break = sched_nr_migrate_break;
  3709. /*
  3710. * Go back to "more_balance" rather than "redo" since we
  3711. * need to continue with same src_cpu.
  3712. */
  3713. goto more_balance;
  3714. }
  3715. /* All tasks on this runqueue were pinned by CPU affinity */
  3716. if (unlikely(env.flags & LBF_ALL_PINNED)) {
  3717. cpumask_clear_cpu(cpu_of(busiest), cpus);
  3718. if (!cpumask_empty(cpus)) {
  3719. env.loop = 0;
  3720. env.loop_break = sched_nr_migrate_break;
  3721. goto redo;
  3722. }
  3723. goto out_balanced;
  3724. }
  3725. }
  3726. if (!ld_moved) {
  3727. schedstat_inc(sd, lb_failed[idle]);
  3728. /*
  3729. * Increment the failure counter only on periodic balance.
  3730. * We do not want newidle balance, which can be very
  3731. * frequent, pollute the failure counter causing
  3732. * excessive cache_hot migrations and active balances.
  3733. */
  3734. if (idle != CPU_NEWLY_IDLE)
  3735. sd->nr_balance_failed++;
  3736. if (need_active_balance(&env)) {
  3737. raw_spin_lock_irqsave(&busiest->lock, flags);
  3738. /* don't kick the active_load_balance_cpu_stop,
  3739. * if the curr task on busiest cpu can't be
  3740. * moved to this_cpu
  3741. */
  3742. if (!cpumask_test_cpu(this_cpu,
  3743. tsk_cpus_allowed(busiest->curr))) {
  3744. raw_spin_unlock_irqrestore(&busiest->lock,
  3745. flags);
  3746. env.flags |= LBF_ALL_PINNED;
  3747. goto out_one_pinned;
  3748. }
  3749. /*
  3750. * ->active_balance synchronizes accesses to
  3751. * ->active_balance_work. Once set, it's cleared
  3752. * only after active load balance is finished.
  3753. */
  3754. if (!busiest->active_balance) {
  3755. busiest->active_balance = 1;
  3756. busiest->push_cpu = this_cpu;
  3757. active_balance = 1;
  3758. }
  3759. raw_spin_unlock_irqrestore(&busiest->lock, flags);
  3760. if (active_balance) {
  3761. stop_one_cpu_nowait(cpu_of(busiest),
  3762. active_load_balance_cpu_stop, busiest,
  3763. &busiest->active_balance_work);
  3764. }
  3765. /*
  3766. * We've kicked active balancing, reset the failure
  3767. * counter.
  3768. */
  3769. sd->nr_balance_failed = sd->cache_nice_tries+1;
  3770. }
  3771. } else
  3772. sd->nr_balance_failed = 0;
  3773. if (likely(!active_balance)) {
  3774. /* We were unbalanced, so reset the balancing interval */
  3775. sd->balance_interval = sd->min_interval;
  3776. } else {
  3777. /*
  3778. * If we've begun active balancing, start to back off. This
  3779. * case may not be covered by the all_pinned logic if there
  3780. * is only 1 task on the busy runqueue (because we don't call
  3781. * move_tasks).
  3782. */
  3783. if (sd->balance_interval < sd->max_interval)
  3784. sd->balance_interval *= 2;
  3785. }
  3786. goto out;
  3787. out_balanced:
  3788. schedstat_inc(sd, lb_balanced[idle]);
  3789. sd->nr_balance_failed = 0;
  3790. out_one_pinned:
  3791. /* tune up the balancing interval */
  3792. if (((env.flags & LBF_ALL_PINNED) &&
  3793. sd->balance_interval < MAX_PINNED_INTERVAL) ||
  3794. (sd->balance_interval < sd->max_interval))
  3795. sd->balance_interval *= 2;
  3796. ld_moved = 0;
  3797. out:
  3798. return ld_moved;
  3799. }
  3800. /*
  3801. * idle_balance is called by schedule() if this_cpu is about to become
  3802. * idle. Attempts to pull tasks from other CPUs.
  3803. */
  3804. void idle_balance(int this_cpu, struct rq *this_rq)
  3805. {
  3806. struct sched_domain *sd;
  3807. int pulled_task = 0;
  3808. unsigned long next_balance = jiffies + HZ;
  3809. this_rq->idle_stamp = this_rq->clock;
  3810. if (this_rq->avg_idle < sysctl_sched_migration_cost)
  3811. return;
  3812. /*
  3813. * Drop the rq->lock, but keep IRQ/preempt disabled.
  3814. */
  3815. raw_spin_unlock(&this_rq->lock);
  3816. update_shares(this_cpu);
  3817. rcu_read_lock();
  3818. for_each_domain(this_cpu, sd) {
  3819. unsigned long interval;
  3820. int balance = 1;
  3821. if (!(sd->flags & SD_LOAD_BALANCE))
  3822. continue;
  3823. if (sd->flags & SD_BALANCE_NEWIDLE) {
  3824. /* If we've pulled tasks over stop searching: */
  3825. pulled_task = load_balance(this_cpu, this_rq,
  3826. sd, CPU_NEWLY_IDLE, &balance);
  3827. }
  3828. interval = msecs_to_jiffies(sd->balance_interval);
  3829. if (time_after(next_balance, sd->last_balance + interval))
  3830. next_balance = sd->last_balance + interval;
  3831. if (pulled_task) {
  3832. this_rq->idle_stamp = 0;
  3833. break;
  3834. }
  3835. }
  3836. rcu_read_unlock();
  3837. raw_spin_lock(&this_rq->lock);
  3838. if (pulled_task || time_after(jiffies, this_rq->next_balance)) {
  3839. /*
  3840. * We are going idle. next_balance may be set based on
  3841. * a busy processor. So reset next_balance.
  3842. */
  3843. this_rq->next_balance = next_balance;
  3844. }
  3845. }
  3846. /*
  3847. * active_load_balance_cpu_stop is run by cpu stopper. It pushes
  3848. * running tasks off the busiest CPU onto idle CPUs. It requires at
  3849. * least 1 task to be running on each physical CPU where possible, and
  3850. * avoids physical / logical imbalances.
  3851. */
  3852. static int active_load_balance_cpu_stop(void *data)
  3853. {
  3854. struct rq *busiest_rq = data;
  3855. int busiest_cpu = cpu_of(busiest_rq);
  3856. int target_cpu = busiest_rq->push_cpu;
  3857. struct rq *target_rq = cpu_rq(target_cpu);
  3858. struct sched_domain *sd;
  3859. raw_spin_lock_irq(&busiest_rq->lock);
  3860. /* make sure the requested cpu hasn't gone down in the meantime */
  3861. if (unlikely(busiest_cpu != smp_processor_id() ||
  3862. !busiest_rq->active_balance))
  3863. goto out_unlock;
  3864. /* Is there any task to move? */
  3865. if (busiest_rq->nr_running <= 1)
  3866. goto out_unlock;
  3867. /*
  3868. * This condition is "impossible", if it occurs
  3869. * we need to fix it. Originally reported by
  3870. * Bjorn Helgaas on a 128-cpu setup.
  3871. */
  3872. BUG_ON(busiest_rq == target_rq);
  3873. /* move a task from busiest_rq to target_rq */
  3874. double_lock_balance(busiest_rq, target_rq);
  3875. /* Search for an sd spanning us and the target CPU. */
  3876. rcu_read_lock();
  3877. for_each_domain(target_cpu, sd) {
  3878. if ((sd->flags & SD_LOAD_BALANCE) &&
  3879. cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
  3880. break;
  3881. }
  3882. if (likely(sd)) {
  3883. struct lb_env env = {
  3884. .sd = sd,
  3885. .dst_cpu = target_cpu,
  3886. .dst_rq = target_rq,
  3887. .src_cpu = busiest_rq->cpu,
  3888. .src_rq = busiest_rq,
  3889. .idle = CPU_IDLE,
  3890. };
  3891. schedstat_inc(sd, alb_count);
  3892. if (move_one_task(&env))
  3893. schedstat_inc(sd, alb_pushed);
  3894. else
  3895. schedstat_inc(sd, alb_failed);
  3896. }
  3897. rcu_read_unlock();
  3898. double_unlock_balance(busiest_rq, target_rq);
  3899. out_unlock:
  3900. busiest_rq->active_balance = 0;
  3901. raw_spin_unlock_irq(&busiest_rq->lock);
  3902. return 0;
  3903. }
  3904. #ifdef CONFIG_NO_HZ
  3905. /*
  3906. * idle load balancing details
  3907. * - When one of the busy CPUs notice that there may be an idle rebalancing
  3908. * needed, they will kick the idle load balancer, which then does idle
  3909. * load balancing for all the idle CPUs.
  3910. */
  3911. static struct {
  3912. cpumask_var_t idle_cpus_mask;
  3913. atomic_t nr_cpus;
  3914. unsigned long next_balance; /* in jiffy units */
  3915. } nohz ____cacheline_aligned;
  3916. static inline int find_new_ilb(int call_cpu)
  3917. {
  3918. int ilb = cpumask_first(nohz.idle_cpus_mask);
  3919. if (ilb < nr_cpu_ids && idle_cpu(ilb))
  3920. return ilb;
  3921. return nr_cpu_ids;
  3922. }
  3923. /*
  3924. * Kick a CPU to do the nohz balancing, if it is time for it. We pick the
  3925. * nohz_load_balancer CPU (if there is one) otherwise fallback to any idle
  3926. * CPU (if there is one).
  3927. */
  3928. static void nohz_balancer_kick(int cpu)
  3929. {
  3930. int ilb_cpu;
  3931. nohz.next_balance++;
  3932. ilb_cpu = find_new_ilb(cpu);
  3933. if (ilb_cpu >= nr_cpu_ids)
  3934. return;
  3935. if (test_and_set_bit(NOHZ_BALANCE_KICK, nohz_flags(ilb_cpu)))
  3936. return;
  3937. /*
  3938. * Use smp_send_reschedule() instead of resched_cpu().
  3939. * This way we generate a sched IPI on the target cpu which
  3940. * is idle. And the softirq performing nohz idle load balance
  3941. * will be run before returning from the IPI.
  3942. */
  3943. smp_send_reschedule(ilb_cpu);
  3944. return;
  3945. }
  3946. static inline void nohz_balance_exit_idle(int cpu)
  3947. {
  3948. if (unlikely(test_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu)))) {
  3949. cpumask_clear_cpu(cpu, nohz.idle_cpus_mask);
  3950. atomic_dec(&nohz.nr_cpus);
  3951. clear_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu));
  3952. }
  3953. }
  3954. static inline void set_cpu_sd_state_busy(void)
  3955. {
  3956. struct sched_domain *sd;
  3957. int cpu = smp_processor_id();
  3958. if (!test_bit(NOHZ_IDLE, nohz_flags(cpu)))
  3959. return;
  3960. clear_bit(NOHZ_IDLE, nohz_flags(cpu));
  3961. rcu_read_lock();
  3962. for_each_domain(cpu, sd)
  3963. atomic_inc(&sd->groups->sgp->nr_busy_cpus);
  3964. rcu_read_unlock();
  3965. }
  3966. void set_cpu_sd_state_idle(void)
  3967. {
  3968. struct sched_domain *sd;
  3969. int cpu = smp_processor_id();
  3970. if (test_bit(NOHZ_IDLE, nohz_flags(cpu)))
  3971. return;
  3972. set_bit(NOHZ_IDLE, nohz_flags(cpu));
  3973. rcu_read_lock();
  3974. for_each_domain(cpu, sd)
  3975. atomic_dec(&sd->groups->sgp->nr_busy_cpus);
  3976. rcu_read_unlock();
  3977. }
  3978. /*
  3979. * This routine will record that the cpu is going idle with tick stopped.
  3980. * This info will be used in performing idle load balancing in the future.
  3981. */
  3982. void nohz_balance_enter_idle(int cpu)
  3983. {
  3984. /*
  3985. * If this cpu is going down, then nothing needs to be done.
  3986. */
  3987. if (!cpu_active(cpu))
  3988. return;
  3989. if (test_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu)))
  3990. return;
  3991. cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
  3992. atomic_inc(&nohz.nr_cpus);
  3993. set_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu));
  3994. }
  3995. static int __cpuinit sched_ilb_notifier(struct notifier_block *nfb,
  3996. unsigned long action, void *hcpu)
  3997. {
  3998. switch (action & ~CPU_TASKS_FROZEN) {
  3999. case CPU_DYING:
  4000. nohz_balance_exit_idle(smp_processor_id());
  4001. return NOTIFY_OK;
  4002. default:
  4003. return NOTIFY_DONE;
  4004. }
  4005. }
  4006. #endif
  4007. static DEFINE_SPINLOCK(balancing);
  4008. /*
  4009. * Scale the max load_balance interval with the number of CPUs in the system.
  4010. * This trades load-balance latency on larger machines for less cross talk.
  4011. */
  4012. void update_max_interval(void)
  4013. {
  4014. max_load_balance_interval = HZ*num_online_cpus()/10;
  4015. }
  4016. /*
  4017. * It checks each scheduling domain to see if it is due to be balanced,
  4018. * and initiates a balancing operation if so.
  4019. *
  4020. * Balancing parameters are set up in arch_init_sched_domains.
  4021. */
  4022. static void rebalance_domains(int cpu, enum cpu_idle_type idle)
  4023. {
  4024. int balance = 1;
  4025. struct rq *rq = cpu_rq(cpu);
  4026. unsigned long interval;
  4027. struct sched_domain *sd;
  4028. /* Earliest time when we have to do rebalance again */
  4029. unsigned long next_balance = jiffies + 60*HZ;
  4030. int update_next_balance = 0;
  4031. int need_serialize;
  4032. update_shares(cpu);
  4033. rcu_read_lock();
  4034. for_each_domain(cpu, sd) {
  4035. if (!(sd->flags & SD_LOAD_BALANCE))
  4036. continue;
  4037. interval = sd->balance_interval;
  4038. if (idle != CPU_IDLE)
  4039. interval *= sd->busy_factor;
  4040. /* scale ms to jiffies */
  4041. interval = msecs_to_jiffies(interval);
  4042. interval = clamp(interval, 1UL, max_load_balance_interval);
  4043. need_serialize = sd->flags & SD_SERIALIZE;
  4044. if (need_serialize) {
  4045. if (!spin_trylock(&balancing))
  4046. goto out;
  4047. }
  4048. if (time_after_eq(jiffies, sd->last_balance + interval)) {
  4049. if (load_balance(cpu, rq, sd, idle, &balance)) {
  4050. /*
  4051. * We've pulled tasks over so either we're no
  4052. * longer idle.
  4053. */
  4054. idle = CPU_NOT_IDLE;
  4055. }
  4056. sd->last_balance = jiffies;
  4057. }
  4058. if (need_serialize)
  4059. spin_unlock(&balancing);
  4060. out:
  4061. if (time_after(next_balance, sd->last_balance + interval)) {
  4062. next_balance = sd->last_balance + interval;
  4063. update_next_balance = 1;
  4064. }
  4065. /*
  4066. * Stop the load balance at this level. There is another
  4067. * CPU in our sched group which is doing load balancing more
  4068. * actively.
  4069. */
  4070. if (!balance)
  4071. break;
  4072. }
  4073. rcu_read_unlock();
  4074. /*
  4075. * next_balance will be updated only when there is a need.
  4076. * When the cpu is attached to null domain for ex, it will not be
  4077. * updated.
  4078. */
  4079. if (likely(update_next_balance))
  4080. rq->next_balance = next_balance;
  4081. }
  4082. #ifdef CONFIG_NO_HZ
  4083. /*
  4084. * In CONFIG_NO_HZ case, the idle balance kickee will do the
  4085. * rebalancing for all the cpus for whom scheduler ticks are stopped.
  4086. */
  4087. static void nohz_idle_balance(int this_cpu, enum cpu_idle_type idle)
  4088. {
  4089. struct rq *this_rq = cpu_rq(this_cpu);
  4090. struct rq *rq;
  4091. int balance_cpu;
  4092. if (idle != CPU_IDLE ||
  4093. !test_bit(NOHZ_BALANCE_KICK, nohz_flags(this_cpu)))
  4094. goto end;
  4095. for_each_cpu(balance_cpu, nohz.idle_cpus_mask) {
  4096. if (balance_cpu == this_cpu || !idle_cpu(balance_cpu))
  4097. continue;
  4098. /*
  4099. * If this cpu gets work to do, stop the load balancing
  4100. * work being done for other cpus. Next load
  4101. * balancing owner will pick it up.
  4102. */
  4103. if (need_resched())
  4104. break;
  4105. rq = cpu_rq(balance_cpu);
  4106. raw_spin_lock_irq(&rq->lock);
  4107. update_rq_clock(rq);
  4108. update_idle_cpu_load(rq);
  4109. raw_spin_unlock_irq(&rq->lock);
  4110. rebalance_domains(balance_cpu, CPU_IDLE);
  4111. if (time_after(this_rq->next_balance, rq->next_balance))
  4112. this_rq->next_balance = rq->next_balance;
  4113. }
  4114. nohz.next_balance = this_rq->next_balance;
  4115. end:
  4116. clear_bit(NOHZ_BALANCE_KICK, nohz_flags(this_cpu));
  4117. }
  4118. /*
  4119. * Current heuristic for kicking the idle load balancer in the presence
  4120. * of an idle cpu is the system.
  4121. * - This rq has more than one task.
  4122. * - At any scheduler domain level, this cpu's scheduler group has multiple
  4123. * busy cpu's exceeding the group's power.
  4124. * - For SD_ASYM_PACKING, if the lower numbered cpu's in the scheduler
  4125. * domain span are idle.
  4126. */
  4127. static inline int nohz_kick_needed(struct rq *rq, int cpu)
  4128. {
  4129. unsigned long now = jiffies;
  4130. struct sched_domain *sd;
  4131. if (unlikely(idle_cpu(cpu)))
  4132. return 0;
  4133. /*
  4134. * We may be recently in ticked or tickless idle mode. At the first
  4135. * busy tick after returning from idle, we will update the busy stats.
  4136. */
  4137. set_cpu_sd_state_busy();
  4138. nohz_balance_exit_idle(cpu);
  4139. /*
  4140. * None are in tickless mode and hence no need for NOHZ idle load
  4141. * balancing.
  4142. */
  4143. if (likely(!atomic_read(&nohz.nr_cpus)))
  4144. return 0;
  4145. if (time_before(now, nohz.next_balance))
  4146. return 0;
  4147. if (rq->nr_running >= 2)
  4148. goto need_kick;
  4149. rcu_read_lock();
  4150. for_each_domain(cpu, sd) {
  4151. struct sched_group *sg = sd->groups;
  4152. struct sched_group_power *sgp = sg->sgp;
  4153. int nr_busy = atomic_read(&sgp->nr_busy_cpus);
  4154. if (sd->flags & SD_SHARE_PKG_RESOURCES && nr_busy > 1)
  4155. goto need_kick_unlock;
  4156. if (sd->flags & SD_ASYM_PACKING && nr_busy != sg->group_weight
  4157. && (cpumask_first_and(nohz.idle_cpus_mask,
  4158. sched_domain_span(sd)) < cpu))
  4159. goto need_kick_unlock;
  4160. if (!(sd->flags & (SD_SHARE_PKG_RESOURCES | SD_ASYM_PACKING)))
  4161. break;
  4162. }
  4163. rcu_read_unlock();
  4164. return 0;
  4165. need_kick_unlock:
  4166. rcu_read_unlock();
  4167. need_kick:
  4168. return 1;
  4169. }
  4170. #else
  4171. static void nohz_idle_balance(int this_cpu, enum cpu_idle_type idle) { }
  4172. #endif
  4173. /*
  4174. * run_rebalance_domains is triggered when needed from the scheduler tick.
  4175. * Also triggered for nohz idle balancing (with nohz_balancing_kick set).
  4176. */
  4177. static void run_rebalance_domains(struct softirq_action *h)
  4178. {
  4179. int this_cpu = smp_processor_id();
  4180. struct rq *this_rq = cpu_rq(this_cpu);
  4181. enum cpu_idle_type idle = this_rq->idle_balance ?
  4182. CPU_IDLE : CPU_NOT_IDLE;
  4183. rebalance_domains(this_cpu, idle);
  4184. /*
  4185. * If this cpu has a pending nohz_balance_kick, then do the
  4186. * balancing on behalf of the other idle cpus whose ticks are
  4187. * stopped.
  4188. */
  4189. nohz_idle_balance(this_cpu, idle);
  4190. }
  4191. static inline int on_null_domain(int cpu)
  4192. {
  4193. return !rcu_dereference_sched(cpu_rq(cpu)->sd);
  4194. }
  4195. /*
  4196. * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
  4197. */
  4198. void trigger_load_balance(struct rq *rq, int cpu)
  4199. {
  4200. /* Don't need to rebalance while attached to NULL domain */
  4201. if (time_after_eq(jiffies, rq->next_balance) &&
  4202. likely(!on_null_domain(cpu)))
  4203. raise_softirq(SCHED_SOFTIRQ);
  4204. #ifdef CONFIG_NO_HZ
  4205. if (nohz_kick_needed(rq, cpu) && likely(!on_null_domain(cpu)))
  4206. nohz_balancer_kick(cpu);
  4207. #endif
  4208. }
  4209. static void rq_online_fair(struct rq *rq)
  4210. {
  4211. update_sysctl();
  4212. }
  4213. static void rq_offline_fair(struct rq *rq)
  4214. {
  4215. update_sysctl();
  4216. /* Ensure any throttled groups are reachable by pick_next_task */
  4217. unthrottle_offline_cfs_rqs(rq);
  4218. }
  4219. #endif /* CONFIG_SMP */
  4220. /*
  4221. * scheduler tick hitting a task of our scheduling class:
  4222. */
  4223. static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)
  4224. {
  4225. struct cfs_rq *cfs_rq;
  4226. struct sched_entity *se = &curr->se;
  4227. for_each_sched_entity(se) {
  4228. cfs_rq = cfs_rq_of(se);
  4229. entity_tick(cfs_rq, se, queued);
  4230. }
  4231. if (sched_feat_numa(NUMA))
  4232. task_tick_numa(rq, curr);
  4233. }
  4234. /*
  4235. * called on fork with the child task as argument from the parent's context
  4236. * - child not yet on the tasklist
  4237. * - preemption disabled
  4238. */
  4239. static void task_fork_fair(struct task_struct *p)
  4240. {
  4241. struct cfs_rq *cfs_rq;
  4242. struct sched_entity *se = &p->se, *curr;
  4243. int this_cpu = smp_processor_id();
  4244. struct rq *rq = this_rq();
  4245. unsigned long flags;
  4246. raw_spin_lock_irqsave(&rq->lock, flags);
  4247. update_rq_clock(rq);
  4248. cfs_rq = task_cfs_rq(current);
  4249. curr = cfs_rq->curr;
  4250. if (unlikely(task_cpu(p) != this_cpu)) {
  4251. rcu_read_lock();
  4252. __set_task_cpu(p, this_cpu);
  4253. rcu_read_unlock();
  4254. }
  4255. update_curr(cfs_rq);
  4256. if (curr)
  4257. se->vruntime = curr->vruntime;
  4258. place_entity(cfs_rq, se, 1);
  4259. if (sysctl_sched_child_runs_first && curr && entity_before(curr, se)) {
  4260. /*
  4261. * Upon rescheduling, sched_class::put_prev_task() will place
  4262. * 'current' within the tree based on its new key value.
  4263. */
  4264. swap(curr->vruntime, se->vruntime);
  4265. resched_task(rq->curr);
  4266. }
  4267. se->vruntime -= cfs_rq->min_vruntime;
  4268. raw_spin_unlock_irqrestore(&rq->lock, flags);
  4269. }
  4270. /*
  4271. * Priority of the task has changed. Check to see if we preempt
  4272. * the current task.
  4273. */
  4274. static void
  4275. prio_changed_fair(struct rq *rq, struct task_struct *p, int oldprio)
  4276. {
  4277. if (!p->se.on_rq)
  4278. return;
  4279. /*
  4280. * Reschedule if we are currently running on this runqueue and
  4281. * our priority decreased, or if we are not currently running on
  4282. * this runqueue and our priority is higher than the current's
  4283. */
  4284. if (rq->curr == p) {
  4285. if (p->prio > oldprio)
  4286. resched_task(rq->curr);
  4287. } else
  4288. check_preempt_curr(rq, p, 0);
  4289. }
  4290. static void switched_from_fair(struct rq *rq, struct task_struct *p)
  4291. {
  4292. struct sched_entity *se = &p->se;
  4293. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  4294. /*
  4295. * Ensure the task's vruntime is normalized, so that when its
  4296. * switched back to the fair class the enqueue_entity(.flags=0) will
  4297. * do the right thing.
  4298. *
  4299. * If it was on_rq, then the dequeue_entity(.flags=0) will already
  4300. * have normalized the vruntime, if it was !on_rq, then only when
  4301. * the task is sleeping will it still have non-normalized vruntime.
  4302. */
  4303. if (!se->on_rq && p->state != TASK_RUNNING) {
  4304. /*
  4305. * Fix up our vruntime so that the current sleep doesn't
  4306. * cause 'unlimited' sleep bonus.
  4307. */
  4308. place_entity(cfs_rq, se, 0);
  4309. se->vruntime -= cfs_rq->min_vruntime;
  4310. }
  4311. }
  4312. /*
  4313. * We switched to the sched_fair class.
  4314. */
  4315. static void switched_to_fair(struct rq *rq, struct task_struct *p)
  4316. {
  4317. if (!p->se.on_rq)
  4318. return;
  4319. /*
  4320. * We were most likely switched from sched_rt, so
  4321. * kick off the schedule if running, otherwise just see
  4322. * if we can still preempt the current task.
  4323. */
  4324. if (rq->curr == p)
  4325. resched_task(rq->curr);
  4326. else
  4327. check_preempt_curr(rq, p, 0);
  4328. }
  4329. /* Account for a task changing its policy or group.
  4330. *
  4331. * This routine is mostly called to set cfs_rq->curr field when a task
  4332. * migrates between groups/classes.
  4333. */
  4334. static void set_curr_task_fair(struct rq *rq)
  4335. {
  4336. struct sched_entity *se = &rq->curr->se;
  4337. for_each_sched_entity(se) {
  4338. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  4339. set_next_entity(cfs_rq, se);
  4340. /* ensure bandwidth has been allocated on our new cfs_rq */
  4341. account_cfs_rq_runtime(cfs_rq, 0);
  4342. }
  4343. }
  4344. void init_cfs_rq(struct cfs_rq *cfs_rq)
  4345. {
  4346. cfs_rq->tasks_timeline = RB_ROOT;
  4347. cfs_rq->min_vruntime = (u64)(-(1LL << 20));
  4348. #ifndef CONFIG_64BIT
  4349. cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
  4350. #endif
  4351. }
  4352. #ifdef CONFIG_FAIR_GROUP_SCHED
  4353. static void task_move_group_fair(struct task_struct *p, int on_rq)
  4354. {
  4355. /*
  4356. * If the task was not on the rq at the time of this cgroup movement
  4357. * it must have been asleep, sleeping tasks keep their ->vruntime
  4358. * absolute on their old rq until wakeup (needed for the fair sleeper
  4359. * bonus in place_entity()).
  4360. *
  4361. * If it was on the rq, we've just 'preempted' it, which does convert
  4362. * ->vruntime to a relative base.
  4363. *
  4364. * Make sure both cases convert their relative position when migrating
  4365. * to another cgroup's rq. This does somewhat interfere with the
  4366. * fair sleeper stuff for the first placement, but who cares.
  4367. */
  4368. /*
  4369. * When !on_rq, vruntime of the task has usually NOT been normalized.
  4370. * But there are some cases where it has already been normalized:
  4371. *
  4372. * - Moving a forked child which is waiting for being woken up by
  4373. * wake_up_new_task().
  4374. * - Moving a task which has been woken up by try_to_wake_up() and
  4375. * waiting for actually being woken up by sched_ttwu_pending().
  4376. *
  4377. * To prevent boost or penalty in the new cfs_rq caused by delta
  4378. * min_vruntime between the two cfs_rqs, we skip vruntime adjustment.
  4379. */
  4380. if (!on_rq && (!p->se.sum_exec_runtime || p->state == TASK_WAKING))
  4381. on_rq = 1;
  4382. if (!on_rq)
  4383. p->se.vruntime -= cfs_rq_of(&p->se)->min_vruntime;
  4384. set_task_rq(p, task_cpu(p));
  4385. if (!on_rq)
  4386. p->se.vruntime += cfs_rq_of(&p->se)->min_vruntime;
  4387. }
  4388. void free_fair_sched_group(struct task_group *tg)
  4389. {
  4390. int i;
  4391. destroy_cfs_bandwidth(tg_cfs_bandwidth(tg));
  4392. for_each_possible_cpu(i) {
  4393. if (tg->cfs_rq)
  4394. kfree(tg->cfs_rq[i]);
  4395. if (tg->se)
  4396. kfree(tg->se[i]);
  4397. }
  4398. kfree(tg->cfs_rq);
  4399. kfree(tg->se);
  4400. }
  4401. int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
  4402. {
  4403. struct cfs_rq *cfs_rq;
  4404. struct sched_entity *se;
  4405. int i;
  4406. tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL);
  4407. if (!tg->cfs_rq)
  4408. goto err;
  4409. tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL);
  4410. if (!tg->se)
  4411. goto err;
  4412. tg->shares = NICE_0_LOAD;
  4413. init_cfs_bandwidth(tg_cfs_bandwidth(tg));
  4414. for_each_possible_cpu(i) {
  4415. cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
  4416. GFP_KERNEL, cpu_to_node(i));
  4417. if (!cfs_rq)
  4418. goto err;
  4419. se = kzalloc_node(sizeof(struct sched_entity),
  4420. GFP_KERNEL, cpu_to_node(i));
  4421. if (!se)
  4422. goto err_free_rq;
  4423. init_cfs_rq(cfs_rq);
  4424. init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
  4425. }
  4426. return 1;
  4427. err_free_rq:
  4428. kfree(cfs_rq);
  4429. err:
  4430. return 0;
  4431. }
  4432. void unregister_fair_sched_group(struct task_group *tg, int cpu)
  4433. {
  4434. struct rq *rq = cpu_rq(cpu);
  4435. unsigned long flags;
  4436. /*
  4437. * Only empty task groups can be destroyed; so we can speculatively
  4438. * check on_list without danger of it being re-added.
  4439. */
  4440. if (!tg->cfs_rq[cpu]->on_list)
  4441. return;
  4442. raw_spin_lock_irqsave(&rq->lock, flags);
  4443. list_del_leaf_cfs_rq(tg->cfs_rq[cpu]);
  4444. raw_spin_unlock_irqrestore(&rq->lock, flags);
  4445. }
  4446. void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
  4447. struct sched_entity *se, int cpu,
  4448. struct sched_entity *parent)
  4449. {
  4450. struct rq *rq = cpu_rq(cpu);
  4451. cfs_rq->tg = tg;
  4452. cfs_rq->rq = rq;
  4453. #ifdef CONFIG_SMP
  4454. /* allow initial update_cfs_load() to truncate */
  4455. cfs_rq->load_stamp = 1;
  4456. #endif
  4457. init_cfs_rq_runtime(cfs_rq);
  4458. tg->cfs_rq[cpu] = cfs_rq;
  4459. tg->se[cpu] = se;
  4460. /* se could be NULL for root_task_group */
  4461. if (!se)
  4462. return;
  4463. if (!parent)
  4464. se->cfs_rq = &rq->cfs;
  4465. else
  4466. se->cfs_rq = parent->my_q;
  4467. se->my_q = cfs_rq;
  4468. update_load_set(&se->load, 0);
  4469. se->parent = parent;
  4470. }
  4471. static DEFINE_MUTEX(shares_mutex);
  4472. int sched_group_set_shares(struct task_group *tg, unsigned long shares)
  4473. {
  4474. int i;
  4475. unsigned long flags;
  4476. /*
  4477. * We can't change the weight of the root cgroup.
  4478. */
  4479. if (!tg->se[0])
  4480. return -EINVAL;
  4481. shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
  4482. mutex_lock(&shares_mutex);
  4483. if (tg->shares == shares)
  4484. goto done;
  4485. tg->shares = shares;
  4486. for_each_possible_cpu(i) {
  4487. struct rq *rq = cpu_rq(i);
  4488. struct sched_entity *se;
  4489. se = tg->se[i];
  4490. /* Propagate contribution to hierarchy */
  4491. raw_spin_lock_irqsave(&rq->lock, flags);
  4492. for_each_sched_entity(se)
  4493. update_cfs_shares(group_cfs_rq(se));
  4494. raw_spin_unlock_irqrestore(&rq->lock, flags);
  4495. }
  4496. done:
  4497. mutex_unlock(&shares_mutex);
  4498. return 0;
  4499. }
  4500. #else /* CONFIG_FAIR_GROUP_SCHED */
  4501. void free_fair_sched_group(struct task_group *tg) { }
  4502. int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
  4503. {
  4504. return 1;
  4505. }
  4506. void unregister_fair_sched_group(struct task_group *tg, int cpu) { }
  4507. #endif /* CONFIG_FAIR_GROUP_SCHED */
  4508. static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task)
  4509. {
  4510. struct sched_entity *se = &task->se;
  4511. unsigned int rr_interval = 0;
  4512. /*
  4513. * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
  4514. * idle runqueue:
  4515. */
  4516. if (rq->cfs.load.weight)
  4517. rr_interval = NS_TO_JIFFIES(sched_slice(&rq->cfs, se));
  4518. return rr_interval;
  4519. }
  4520. /*
  4521. * All the scheduling class methods:
  4522. */
  4523. const struct sched_class fair_sched_class = {
  4524. .next = &idle_sched_class,
  4525. .enqueue_task = enqueue_task_fair,
  4526. .dequeue_task = dequeue_task_fair,
  4527. .yield_task = yield_task_fair,
  4528. .yield_to_task = yield_to_task_fair,
  4529. .check_preempt_curr = check_preempt_wakeup,
  4530. .pick_next_task = pick_next_task_fair,
  4531. .put_prev_task = put_prev_task_fair,
  4532. #ifdef CONFIG_SMP
  4533. .select_task_rq = select_task_rq_fair,
  4534. .rq_online = rq_online_fair,
  4535. .rq_offline = rq_offline_fair,
  4536. .task_waking = task_waking_fair,
  4537. #endif
  4538. .set_curr_task = set_curr_task_fair,
  4539. .task_tick = task_tick_fair,
  4540. .task_fork = task_fork_fair,
  4541. .prio_changed = prio_changed_fair,
  4542. .switched_from = switched_from_fair,
  4543. .switched_to = switched_to_fair,
  4544. .get_rr_interval = get_rr_interval_fair,
  4545. #ifdef CONFIG_FAIR_GROUP_SCHED
  4546. .task_move_group = task_move_group_fair,
  4547. #endif
  4548. };
  4549. #ifdef CONFIG_SCHED_DEBUG
  4550. void print_cfs_stats(struct seq_file *m, int cpu)
  4551. {
  4552. struct cfs_rq *cfs_rq;
  4553. rcu_read_lock();
  4554. for_each_leaf_cfs_rq(cpu_rq(cpu), cfs_rq)
  4555. print_cfs_rq(m, cpu, cfs_rq);
  4556. rcu_read_unlock();
  4557. }
  4558. #endif
  4559. __init void init_sched_fair_class(void)
  4560. {
  4561. #ifdef CONFIG_SMP
  4562. open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
  4563. #ifdef CONFIG_NO_HZ
  4564. nohz.next_balance = jiffies;
  4565. zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);
  4566. cpu_notifier(sched_ilb_notifier, 0);
  4567. #endif
  4568. #endif /* SMP */
  4569. }