fair.c 174 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772
  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/migrate.h>
  30. #include <linux/task_work.h>
  31. #include <trace/events/sched.h>
  32. #include "sched.h"
  33. /*
  34. * Targeted preemption latency for CPU-bound tasks:
  35. * (default: 6ms * (1 + ilog(ncpus)), units: nanoseconds)
  36. *
  37. * NOTE: this latency value is not the same as the concept of
  38. * 'timeslice length' - timeslices in CFS are of variable length
  39. * and have no persistent notion like in traditional, time-slice
  40. * based scheduling concepts.
  41. *
  42. * (to see the precise effective timeslice length of your workload,
  43. * run vmstat and monitor the context-switches (cs) field)
  44. */
  45. unsigned int sysctl_sched_latency = 6000000ULL;
  46. unsigned int normalized_sysctl_sched_latency = 6000000ULL;
  47. /*
  48. * The initial- and re-scaling of tunables is configurable
  49. * (default SCHED_TUNABLESCALING_LOG = *(1+ilog(ncpus))
  50. *
  51. * Options are:
  52. * SCHED_TUNABLESCALING_NONE - unscaled, always *1
  53. * SCHED_TUNABLESCALING_LOG - scaled logarithmical, *1+ilog(ncpus)
  54. * SCHED_TUNABLESCALING_LINEAR - scaled linear, *ncpus
  55. */
  56. enum sched_tunable_scaling sysctl_sched_tunable_scaling
  57. = SCHED_TUNABLESCALING_LOG;
  58. /*
  59. * Minimal preemption granularity for CPU-bound tasks:
  60. * (default: 0.75 msec * (1 + ilog(ncpus)), units: nanoseconds)
  61. */
  62. unsigned int sysctl_sched_min_granularity = 750000ULL;
  63. unsigned int normalized_sysctl_sched_min_granularity = 750000ULL;
  64. /*
  65. * is kept at sysctl_sched_latency / sysctl_sched_min_granularity
  66. */
  67. static unsigned int sched_nr_latency = 8;
  68. /*
  69. * After fork, child runs first. If set to 0 (default) then
  70. * parent will (try to) run first.
  71. */
  72. unsigned int sysctl_sched_child_runs_first __read_mostly;
  73. /*
  74. * SCHED_OTHER wake-up granularity.
  75. * (default: 1 msec * (1 + ilog(ncpus)), units: nanoseconds)
  76. *
  77. * This option delays the preemption effects of decoupled workloads
  78. * and reduces their over-scheduling. Synchronous workloads will still
  79. * have immediate wakeup/sleep latencies.
  80. */
  81. unsigned int sysctl_sched_wakeup_granularity = 1000000UL;
  82. unsigned int normalized_sysctl_sched_wakeup_granularity = 1000000UL;
  83. const_debug unsigned int sysctl_sched_migration_cost = 500000UL;
  84. /*
  85. * The exponential sliding window over which load is averaged for shares
  86. * distribution.
  87. * (default: 10msec)
  88. */
  89. unsigned int __read_mostly sysctl_sched_shares_window = 10000000UL;
  90. #ifdef CONFIG_CFS_BANDWIDTH
  91. /*
  92. * Amount of runtime to allocate from global (tg) to local (per-cfs_rq) pool
  93. * each time a cfs_rq requests quota.
  94. *
  95. * Note: in the case that the slice exceeds the runtime remaining (either due
  96. * to consumption or the quota being specified to be smaller than the slice)
  97. * we will always only issue the remaining available time.
  98. *
  99. * default: 5 msec, units: microseconds
  100. */
  101. unsigned int sysctl_sched_cfs_bandwidth_slice = 5000UL;
  102. #endif
  103. static inline void update_load_add(struct load_weight *lw, unsigned long inc)
  104. {
  105. lw->weight += inc;
  106. lw->inv_weight = 0;
  107. }
  108. static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
  109. {
  110. lw->weight -= dec;
  111. lw->inv_weight = 0;
  112. }
  113. static inline void update_load_set(struct load_weight *lw, unsigned long w)
  114. {
  115. lw->weight = w;
  116. lw->inv_weight = 0;
  117. }
  118. /*
  119. * Increase the granularity value when there are more CPUs,
  120. * because with more CPUs the 'effective latency' as visible
  121. * to users decreases. But the relationship is not linear,
  122. * so pick a second-best guess by going with the log2 of the
  123. * number of CPUs.
  124. *
  125. * This idea comes from the SD scheduler of Con Kolivas:
  126. */
  127. static int get_update_sysctl_factor(void)
  128. {
  129. unsigned int cpus = min_t(int, num_online_cpus(), 8);
  130. unsigned int factor;
  131. switch (sysctl_sched_tunable_scaling) {
  132. case SCHED_TUNABLESCALING_NONE:
  133. factor = 1;
  134. break;
  135. case SCHED_TUNABLESCALING_LINEAR:
  136. factor = cpus;
  137. break;
  138. case SCHED_TUNABLESCALING_LOG:
  139. default:
  140. factor = 1 + ilog2(cpus);
  141. break;
  142. }
  143. return factor;
  144. }
  145. static void update_sysctl(void)
  146. {
  147. unsigned int factor = get_update_sysctl_factor();
  148. #define SET_SYSCTL(name) \
  149. (sysctl_##name = (factor) * normalized_sysctl_##name)
  150. SET_SYSCTL(sched_min_granularity);
  151. SET_SYSCTL(sched_latency);
  152. SET_SYSCTL(sched_wakeup_granularity);
  153. #undef SET_SYSCTL
  154. }
  155. void sched_init_granularity(void)
  156. {
  157. update_sysctl();
  158. }
  159. #if BITS_PER_LONG == 32
  160. # define WMULT_CONST (~0UL)
  161. #else
  162. # define WMULT_CONST (1UL << 32)
  163. #endif
  164. #define WMULT_SHIFT 32
  165. /*
  166. * Shift right and round:
  167. */
  168. #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
  169. /*
  170. * delta *= weight / lw
  171. */
  172. static unsigned long
  173. calc_delta_mine(unsigned long delta_exec, unsigned long weight,
  174. struct load_weight *lw)
  175. {
  176. u64 tmp;
  177. /*
  178. * weight can be less than 2^SCHED_LOAD_RESOLUTION for task group sched
  179. * entities since MIN_SHARES = 2. Treat weight as 1 if less than
  180. * 2^SCHED_LOAD_RESOLUTION.
  181. */
  182. if (likely(weight > (1UL << SCHED_LOAD_RESOLUTION)))
  183. tmp = (u64)delta_exec * scale_load_down(weight);
  184. else
  185. tmp = (u64)delta_exec;
  186. if (!lw->inv_weight) {
  187. unsigned long w = scale_load_down(lw->weight);
  188. if (BITS_PER_LONG > 32 && unlikely(w >= WMULT_CONST))
  189. lw->inv_weight = 1;
  190. else if (unlikely(!w))
  191. lw->inv_weight = WMULT_CONST;
  192. else
  193. lw->inv_weight = WMULT_CONST / w;
  194. }
  195. /*
  196. * Check whether we'd overflow the 64-bit multiplication:
  197. */
  198. if (unlikely(tmp > WMULT_CONST))
  199. tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
  200. WMULT_SHIFT/2);
  201. else
  202. tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);
  203. return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);
  204. }
  205. const struct sched_class fair_sched_class;
  206. /**************************************************************
  207. * CFS operations on generic schedulable entities:
  208. */
  209. #ifdef CONFIG_FAIR_GROUP_SCHED
  210. /* cpu runqueue to which this cfs_rq is attached */
  211. static inline struct rq *rq_of(struct cfs_rq *cfs_rq)
  212. {
  213. return cfs_rq->rq;
  214. }
  215. /* An entity is a task if it doesn't "own" a runqueue */
  216. #define entity_is_task(se) (!se->my_q)
  217. static inline struct task_struct *task_of(struct sched_entity *se)
  218. {
  219. #ifdef CONFIG_SCHED_DEBUG
  220. WARN_ON_ONCE(!entity_is_task(se));
  221. #endif
  222. return container_of(se, struct task_struct, se);
  223. }
  224. /* Walk up scheduling entities hierarchy */
  225. #define for_each_sched_entity(se) \
  226. for (; se; se = se->parent)
  227. static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
  228. {
  229. return p->se.cfs_rq;
  230. }
  231. /* runqueue on which this entity is (to be) queued */
  232. static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se)
  233. {
  234. return se->cfs_rq;
  235. }
  236. /* runqueue "owned" by this group */
  237. static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
  238. {
  239. return grp->my_q;
  240. }
  241. static void update_cfs_rq_blocked_load(struct cfs_rq *cfs_rq,
  242. int force_update);
  243. static inline void list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
  244. {
  245. if (!cfs_rq->on_list) {
  246. /*
  247. * Ensure we either appear before our parent (if already
  248. * enqueued) or force our parent to appear after us when it is
  249. * enqueued. The fact that we always enqueue bottom-up
  250. * reduces this to two cases.
  251. */
  252. if (cfs_rq->tg->parent &&
  253. cfs_rq->tg->parent->cfs_rq[cpu_of(rq_of(cfs_rq))]->on_list) {
  254. list_add_rcu(&cfs_rq->leaf_cfs_rq_list,
  255. &rq_of(cfs_rq)->leaf_cfs_rq_list);
  256. } else {
  257. list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
  258. &rq_of(cfs_rq)->leaf_cfs_rq_list);
  259. }
  260. cfs_rq->on_list = 1;
  261. /* We should have no load, but we need to update last_decay. */
  262. update_cfs_rq_blocked_load(cfs_rq, 0);
  263. }
  264. }
  265. static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
  266. {
  267. if (cfs_rq->on_list) {
  268. list_del_rcu(&cfs_rq->leaf_cfs_rq_list);
  269. cfs_rq->on_list = 0;
  270. }
  271. }
  272. /* Iterate thr' all leaf cfs_rq's on a runqueue */
  273. #define for_each_leaf_cfs_rq(rq, cfs_rq) \
  274. list_for_each_entry_rcu(cfs_rq, &rq->leaf_cfs_rq_list, leaf_cfs_rq_list)
  275. /* Do the two (enqueued) entities belong to the same group ? */
  276. static inline int
  277. is_same_group(struct sched_entity *se, struct sched_entity *pse)
  278. {
  279. if (se->cfs_rq == pse->cfs_rq)
  280. return 1;
  281. return 0;
  282. }
  283. static inline struct sched_entity *parent_entity(struct sched_entity *se)
  284. {
  285. return se->parent;
  286. }
  287. /* return depth at which a sched entity is present in the hierarchy */
  288. static inline int depth_se(struct sched_entity *se)
  289. {
  290. int depth = 0;
  291. for_each_sched_entity(se)
  292. depth++;
  293. return depth;
  294. }
  295. static void
  296. find_matching_se(struct sched_entity **se, struct sched_entity **pse)
  297. {
  298. int se_depth, pse_depth;
  299. /*
  300. * preemption test can be made between sibling entities who are in the
  301. * same cfs_rq i.e who have a common parent. Walk up the hierarchy of
  302. * both tasks until we find their ancestors who are siblings of common
  303. * parent.
  304. */
  305. /* First walk up until both entities are at same depth */
  306. se_depth = depth_se(*se);
  307. pse_depth = depth_se(*pse);
  308. while (se_depth > pse_depth) {
  309. se_depth--;
  310. *se = parent_entity(*se);
  311. }
  312. while (pse_depth > se_depth) {
  313. pse_depth--;
  314. *pse = parent_entity(*pse);
  315. }
  316. while (!is_same_group(*se, *pse)) {
  317. *se = parent_entity(*se);
  318. *pse = parent_entity(*pse);
  319. }
  320. }
  321. #else /* !CONFIG_FAIR_GROUP_SCHED */
  322. static inline struct task_struct *task_of(struct sched_entity *se)
  323. {
  324. return container_of(se, struct task_struct, se);
  325. }
  326. static inline struct rq *rq_of(struct cfs_rq *cfs_rq)
  327. {
  328. return container_of(cfs_rq, struct rq, cfs);
  329. }
  330. #define entity_is_task(se) 1
  331. #define for_each_sched_entity(se) \
  332. for (; se; se = NULL)
  333. static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
  334. {
  335. return &task_rq(p)->cfs;
  336. }
  337. static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se)
  338. {
  339. struct task_struct *p = task_of(se);
  340. struct rq *rq = task_rq(p);
  341. return &rq->cfs;
  342. }
  343. /* runqueue "owned" by this group */
  344. static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
  345. {
  346. return NULL;
  347. }
  348. static inline void list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
  349. {
  350. }
  351. static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
  352. {
  353. }
  354. #define for_each_leaf_cfs_rq(rq, cfs_rq) \
  355. for (cfs_rq = &rq->cfs; cfs_rq; cfs_rq = NULL)
  356. static inline int
  357. is_same_group(struct sched_entity *se, struct sched_entity *pse)
  358. {
  359. return 1;
  360. }
  361. static inline struct sched_entity *parent_entity(struct sched_entity *se)
  362. {
  363. return NULL;
  364. }
  365. static inline void
  366. find_matching_se(struct sched_entity **se, struct sched_entity **pse)
  367. {
  368. }
  369. #endif /* CONFIG_FAIR_GROUP_SCHED */
  370. static __always_inline
  371. void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, unsigned long delta_exec);
  372. /**************************************************************
  373. * Scheduling class tree data structure manipulation methods:
  374. */
  375. static inline u64 max_vruntime(u64 max_vruntime, u64 vruntime)
  376. {
  377. s64 delta = (s64)(vruntime - max_vruntime);
  378. if (delta > 0)
  379. max_vruntime = vruntime;
  380. return max_vruntime;
  381. }
  382. static inline u64 min_vruntime(u64 min_vruntime, u64 vruntime)
  383. {
  384. s64 delta = (s64)(vruntime - min_vruntime);
  385. if (delta < 0)
  386. min_vruntime = vruntime;
  387. return min_vruntime;
  388. }
  389. static inline int entity_before(struct sched_entity *a,
  390. struct sched_entity *b)
  391. {
  392. return (s64)(a->vruntime - b->vruntime) < 0;
  393. }
  394. static void update_min_vruntime(struct cfs_rq *cfs_rq)
  395. {
  396. u64 vruntime = cfs_rq->min_vruntime;
  397. if (cfs_rq->curr)
  398. vruntime = cfs_rq->curr->vruntime;
  399. if (cfs_rq->rb_leftmost) {
  400. struct sched_entity *se = rb_entry(cfs_rq->rb_leftmost,
  401. struct sched_entity,
  402. run_node);
  403. if (!cfs_rq->curr)
  404. vruntime = se->vruntime;
  405. else
  406. vruntime = min_vruntime(vruntime, se->vruntime);
  407. }
  408. /* ensure we never gain time by being placed backwards. */
  409. cfs_rq->min_vruntime = max_vruntime(cfs_rq->min_vruntime, vruntime);
  410. #ifndef CONFIG_64BIT
  411. smp_wmb();
  412. cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
  413. #endif
  414. }
  415. /*
  416. * Enqueue an entity into the rb-tree:
  417. */
  418. static void __enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
  419. {
  420. struct rb_node **link = &cfs_rq->tasks_timeline.rb_node;
  421. struct rb_node *parent = NULL;
  422. struct sched_entity *entry;
  423. int leftmost = 1;
  424. /*
  425. * Find the right place in the rbtree:
  426. */
  427. while (*link) {
  428. parent = *link;
  429. entry = rb_entry(parent, struct sched_entity, run_node);
  430. /*
  431. * We dont care about collisions. Nodes with
  432. * the same key stay together.
  433. */
  434. if (entity_before(se, entry)) {
  435. link = &parent->rb_left;
  436. } else {
  437. link = &parent->rb_right;
  438. leftmost = 0;
  439. }
  440. }
  441. /*
  442. * Maintain a cache of leftmost tree entries (it is frequently
  443. * used):
  444. */
  445. if (leftmost)
  446. cfs_rq->rb_leftmost = &se->run_node;
  447. rb_link_node(&se->run_node, parent, link);
  448. rb_insert_color(&se->run_node, &cfs_rq->tasks_timeline);
  449. }
  450. static void __dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
  451. {
  452. if (cfs_rq->rb_leftmost == &se->run_node) {
  453. struct rb_node *next_node;
  454. next_node = rb_next(&se->run_node);
  455. cfs_rq->rb_leftmost = next_node;
  456. }
  457. rb_erase(&se->run_node, &cfs_rq->tasks_timeline);
  458. }
  459. struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq)
  460. {
  461. struct rb_node *left = cfs_rq->rb_leftmost;
  462. if (!left)
  463. return NULL;
  464. return rb_entry(left, struct sched_entity, run_node);
  465. }
  466. static struct sched_entity *__pick_next_entity(struct sched_entity *se)
  467. {
  468. struct rb_node *next = rb_next(&se->run_node);
  469. if (!next)
  470. return NULL;
  471. return rb_entry(next, struct sched_entity, run_node);
  472. }
  473. #ifdef CONFIG_SCHED_DEBUG
  474. struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq)
  475. {
  476. struct rb_node *last = rb_last(&cfs_rq->tasks_timeline);
  477. if (!last)
  478. return NULL;
  479. return rb_entry(last, struct sched_entity, run_node);
  480. }
  481. /**************************************************************
  482. * Scheduling class statistics methods:
  483. */
  484. int sched_proc_update_handler(struct ctl_table *table, int write,
  485. void __user *buffer, size_t *lenp,
  486. loff_t *ppos)
  487. {
  488. int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
  489. int factor = get_update_sysctl_factor();
  490. if (ret || !write)
  491. return ret;
  492. sched_nr_latency = DIV_ROUND_UP(sysctl_sched_latency,
  493. sysctl_sched_min_granularity);
  494. #define WRT_SYSCTL(name) \
  495. (normalized_sysctl_##name = sysctl_##name / (factor))
  496. WRT_SYSCTL(sched_min_granularity);
  497. WRT_SYSCTL(sched_latency);
  498. WRT_SYSCTL(sched_wakeup_granularity);
  499. #undef WRT_SYSCTL
  500. return 0;
  501. }
  502. #endif
  503. /*
  504. * delta /= w
  505. */
  506. static inline unsigned long
  507. calc_delta_fair(unsigned long delta, struct sched_entity *se)
  508. {
  509. if (unlikely(se->load.weight != NICE_0_LOAD))
  510. delta = calc_delta_mine(delta, NICE_0_LOAD, &se->load);
  511. return delta;
  512. }
  513. /*
  514. * The idea is to set a period in which each task runs once.
  515. *
  516. * When there are too many tasks (sched_nr_latency) we have to stretch
  517. * this period because otherwise the slices get too small.
  518. *
  519. * p = (nr <= nl) ? l : l*nr/nl
  520. */
  521. static u64 __sched_period(unsigned long nr_running)
  522. {
  523. u64 period = sysctl_sched_latency;
  524. unsigned long nr_latency = sched_nr_latency;
  525. if (unlikely(nr_running > nr_latency)) {
  526. period = sysctl_sched_min_granularity;
  527. period *= nr_running;
  528. }
  529. return period;
  530. }
  531. /*
  532. * We calculate the wall-time slice from the period by taking a part
  533. * proportional to the weight.
  534. *
  535. * s = p*P[w/rw]
  536. */
  537. static u64 sched_slice(struct cfs_rq *cfs_rq, struct sched_entity *se)
  538. {
  539. u64 slice = __sched_period(cfs_rq->nr_running + !se->on_rq);
  540. for_each_sched_entity(se) {
  541. struct load_weight *load;
  542. struct load_weight lw;
  543. cfs_rq = cfs_rq_of(se);
  544. load = &cfs_rq->load;
  545. if (unlikely(!se->on_rq)) {
  546. lw = cfs_rq->load;
  547. update_load_add(&lw, se->load.weight);
  548. load = &lw;
  549. }
  550. slice = calc_delta_mine(slice, se->load.weight, load);
  551. }
  552. return slice;
  553. }
  554. /*
  555. * We calculate the vruntime slice of a to-be-inserted task.
  556. *
  557. * vs = s/w
  558. */
  559. static u64 sched_vslice(struct cfs_rq *cfs_rq, struct sched_entity *se)
  560. {
  561. return calc_delta_fair(sched_slice(cfs_rq, se), se);
  562. }
  563. #ifdef CONFIG_SMP
  564. static inline void __update_task_entity_contrib(struct sched_entity *se);
  565. /* Give new task start runnable values to heavy its load in infant time */
  566. void init_task_runnable_average(struct task_struct *p)
  567. {
  568. u32 slice;
  569. p->se.avg.decay_count = 0;
  570. slice = sched_slice(task_cfs_rq(p), &p->se) >> 10;
  571. p->se.avg.runnable_avg_sum = slice;
  572. p->se.avg.runnable_avg_period = slice;
  573. __update_task_entity_contrib(&p->se);
  574. }
  575. #else
  576. void init_task_runnable_average(struct task_struct *p)
  577. {
  578. }
  579. #endif
  580. /*
  581. * Update the current task's runtime statistics. Skip current tasks that
  582. * are not in our scheduling class.
  583. */
  584. static inline void
  585. __update_curr(struct cfs_rq *cfs_rq, struct sched_entity *curr,
  586. unsigned long delta_exec)
  587. {
  588. unsigned long delta_exec_weighted;
  589. schedstat_set(curr->statistics.exec_max,
  590. max((u64)delta_exec, curr->statistics.exec_max));
  591. curr->sum_exec_runtime += delta_exec;
  592. schedstat_add(cfs_rq, exec_clock, delta_exec);
  593. delta_exec_weighted = calc_delta_fair(delta_exec, curr);
  594. curr->vruntime += delta_exec_weighted;
  595. update_min_vruntime(cfs_rq);
  596. }
  597. static void update_curr(struct cfs_rq *cfs_rq)
  598. {
  599. struct sched_entity *curr = cfs_rq->curr;
  600. u64 now = rq_clock_task(rq_of(cfs_rq));
  601. unsigned long delta_exec;
  602. if (unlikely(!curr))
  603. return;
  604. /*
  605. * Get the amount of time the current task was running
  606. * since the last time we changed load (this cannot
  607. * overflow on 32 bits):
  608. */
  609. delta_exec = (unsigned long)(now - curr->exec_start);
  610. if (!delta_exec)
  611. return;
  612. __update_curr(cfs_rq, curr, delta_exec);
  613. curr->exec_start = now;
  614. if (entity_is_task(curr)) {
  615. struct task_struct *curtask = task_of(curr);
  616. trace_sched_stat_runtime(curtask, delta_exec, curr->vruntime);
  617. cpuacct_charge(curtask, delta_exec);
  618. account_group_exec_runtime(curtask, delta_exec);
  619. }
  620. account_cfs_rq_runtime(cfs_rq, delta_exec);
  621. }
  622. static inline void
  623. update_stats_wait_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
  624. {
  625. schedstat_set(se->statistics.wait_start, rq_clock(rq_of(cfs_rq)));
  626. }
  627. /*
  628. * Task is being enqueued - update stats:
  629. */
  630. static void update_stats_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
  631. {
  632. /*
  633. * Are we enqueueing a waiting task? (for current tasks
  634. * a dequeue/enqueue event is a NOP)
  635. */
  636. if (se != cfs_rq->curr)
  637. update_stats_wait_start(cfs_rq, se);
  638. }
  639. static void
  640. update_stats_wait_end(struct cfs_rq *cfs_rq, struct sched_entity *se)
  641. {
  642. schedstat_set(se->statistics.wait_max, max(se->statistics.wait_max,
  643. rq_clock(rq_of(cfs_rq)) - se->statistics.wait_start));
  644. schedstat_set(se->statistics.wait_count, se->statistics.wait_count + 1);
  645. schedstat_set(se->statistics.wait_sum, se->statistics.wait_sum +
  646. rq_clock(rq_of(cfs_rq)) - se->statistics.wait_start);
  647. #ifdef CONFIG_SCHEDSTATS
  648. if (entity_is_task(se)) {
  649. trace_sched_stat_wait(task_of(se),
  650. rq_clock(rq_of(cfs_rq)) - se->statistics.wait_start);
  651. }
  652. #endif
  653. schedstat_set(se->statistics.wait_start, 0);
  654. }
  655. static inline void
  656. update_stats_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
  657. {
  658. /*
  659. * Mark the end of the wait period if dequeueing a
  660. * waiting task:
  661. */
  662. if (se != cfs_rq->curr)
  663. update_stats_wait_end(cfs_rq, se);
  664. }
  665. /*
  666. * We are picking a new current task - update its stats:
  667. */
  668. static inline void
  669. update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
  670. {
  671. /*
  672. * We are starting a new run period:
  673. */
  674. se->exec_start = rq_clock_task(rq_of(cfs_rq));
  675. }
  676. /**************************************************
  677. * Scheduling class queueing methods:
  678. */
  679. #ifdef CONFIG_NUMA_BALANCING
  680. /*
  681. * Approximate time to scan a full NUMA task in ms. The task scan period is
  682. * calculated based on the tasks virtual memory size and
  683. * numa_balancing_scan_size.
  684. */
  685. unsigned int sysctl_numa_balancing_scan_period_min = 1000;
  686. unsigned int sysctl_numa_balancing_scan_period_max = 60000;
  687. unsigned int sysctl_numa_balancing_scan_period_reset = 60000;
  688. /* Portion of address space to scan in MB */
  689. unsigned int sysctl_numa_balancing_scan_size = 256;
  690. /* Scan @scan_size MB every @scan_period after an initial @scan_delay in ms */
  691. unsigned int sysctl_numa_balancing_scan_delay = 1000;
  692. static unsigned int task_nr_scan_windows(struct task_struct *p)
  693. {
  694. unsigned long rss = 0;
  695. unsigned long nr_scan_pages;
  696. /*
  697. * Calculations based on RSS as non-present and empty pages are skipped
  698. * by the PTE scanner and NUMA hinting faults should be trapped based
  699. * on resident pages
  700. */
  701. nr_scan_pages = sysctl_numa_balancing_scan_size << (20 - PAGE_SHIFT);
  702. rss = get_mm_rss(p->mm);
  703. if (!rss)
  704. rss = nr_scan_pages;
  705. rss = round_up(rss, nr_scan_pages);
  706. return rss / nr_scan_pages;
  707. }
  708. /* For sanitys sake, never scan more PTEs than MAX_SCAN_WINDOW MB/sec. */
  709. #define MAX_SCAN_WINDOW 2560
  710. static unsigned int task_scan_min(struct task_struct *p)
  711. {
  712. unsigned int scan, floor;
  713. unsigned int windows = 1;
  714. if (sysctl_numa_balancing_scan_size < MAX_SCAN_WINDOW)
  715. windows = MAX_SCAN_WINDOW / sysctl_numa_balancing_scan_size;
  716. floor = 1000 / windows;
  717. scan = sysctl_numa_balancing_scan_period_min / task_nr_scan_windows(p);
  718. return max_t(unsigned int, floor, scan);
  719. }
  720. static unsigned int task_scan_max(struct task_struct *p)
  721. {
  722. unsigned int smin = task_scan_min(p);
  723. unsigned int smax;
  724. /* Watch for min being lower than max due to floor calculations */
  725. smax = sysctl_numa_balancing_scan_period_max / task_nr_scan_windows(p);
  726. return max(smin, smax);
  727. }
  728. /*
  729. * Once a preferred node is selected the scheduler balancer will prefer moving
  730. * a task to that node for sysctl_numa_balancing_settle_count number of PTE
  731. * scans. This will give the process the chance to accumulate more faults on
  732. * the preferred node but still allow the scheduler to move the task again if
  733. * the nodes CPUs are overloaded.
  734. */
  735. unsigned int sysctl_numa_balancing_settle_count __read_mostly = 4;
  736. static inline int task_faults_idx(int nid, int priv)
  737. {
  738. return 2 * nid + priv;
  739. }
  740. static inline unsigned long task_faults(struct task_struct *p, int nid)
  741. {
  742. if (!p->numa_faults)
  743. return 0;
  744. return p->numa_faults[task_faults_idx(nid, 0)] +
  745. p->numa_faults[task_faults_idx(nid, 1)];
  746. }
  747. static unsigned long weighted_cpuload(const int cpu);
  748. static unsigned long source_load(int cpu, int type);
  749. static unsigned long target_load(int cpu, int type);
  750. static unsigned long power_of(int cpu);
  751. static long effective_load(struct task_group *tg, int cpu, long wl, long wg);
  752. struct numa_stats {
  753. unsigned long load;
  754. s64 eff_load;
  755. unsigned long faults;
  756. };
  757. struct task_numa_env {
  758. struct task_struct *p;
  759. int src_cpu, src_nid;
  760. int dst_cpu, dst_nid;
  761. struct numa_stats src_stats, dst_stats;
  762. unsigned long best_load;
  763. int best_cpu;
  764. };
  765. static int task_numa_migrate(struct task_struct *p)
  766. {
  767. int node_cpu = cpumask_first(cpumask_of_node(p->numa_preferred_nid));
  768. struct task_numa_env env = {
  769. .p = p,
  770. .src_cpu = task_cpu(p),
  771. .src_nid = cpu_to_node(task_cpu(p)),
  772. .dst_cpu = node_cpu,
  773. .dst_nid = p->numa_preferred_nid,
  774. .best_load = ULONG_MAX,
  775. .best_cpu = task_cpu(p),
  776. };
  777. struct sched_domain *sd;
  778. int cpu;
  779. struct task_group *tg = task_group(p);
  780. unsigned long weight;
  781. bool balanced;
  782. int imbalance_pct, idx = -1;
  783. /*
  784. * Find the lowest common scheduling domain covering the nodes of both
  785. * the CPU the task is currently running on and the target NUMA node.
  786. */
  787. rcu_read_lock();
  788. for_each_domain(env.src_cpu, sd) {
  789. if (cpumask_test_cpu(node_cpu, sched_domain_span(sd))) {
  790. /*
  791. * busy_idx is used for the load decision as it is the
  792. * same index used by the regular load balancer for an
  793. * active cpu.
  794. */
  795. idx = sd->busy_idx;
  796. imbalance_pct = sd->imbalance_pct;
  797. break;
  798. }
  799. }
  800. rcu_read_unlock();
  801. if (WARN_ON_ONCE(idx == -1))
  802. return 0;
  803. /*
  804. * XXX the below is mostly nicked from wake_affine(); we should
  805. * see about sharing a bit if at all possible; also it might want
  806. * some per entity weight love.
  807. */
  808. weight = p->se.load.weight;
  809. env.src_stats.load = source_load(env.src_cpu, idx);
  810. env.src_stats.eff_load = 100 + (imbalance_pct - 100) / 2;
  811. env.src_stats.eff_load *= power_of(env.src_cpu);
  812. env.src_stats.eff_load *= env.src_stats.load + effective_load(tg, env.src_cpu, -weight, -weight);
  813. for_each_cpu(cpu, cpumask_of_node(env.dst_nid)) {
  814. env.dst_cpu = cpu;
  815. env.dst_stats.load = target_load(cpu, idx);
  816. /* If the CPU is idle, use it */
  817. if (!env.dst_stats.load) {
  818. env.best_cpu = cpu;
  819. goto migrate;
  820. }
  821. /* Otherwise check the target CPU load */
  822. env.dst_stats.eff_load = 100;
  823. env.dst_stats.eff_load *= power_of(cpu);
  824. env.dst_stats.eff_load *= env.dst_stats.load + effective_load(tg, cpu, weight, weight);
  825. /*
  826. * Destination is considered balanced if the destination CPU is
  827. * less loaded than the source CPU. Unfortunately there is a
  828. * risk that a task running on a lightly loaded CPU will not
  829. * migrate to its preferred node due to load imbalances.
  830. */
  831. balanced = (env.dst_stats.eff_load <= env.src_stats.eff_load);
  832. if (!balanced)
  833. continue;
  834. if (env.dst_stats.eff_load < env.best_load) {
  835. env.best_load = env.dst_stats.eff_load;
  836. env.best_cpu = cpu;
  837. }
  838. }
  839. migrate:
  840. return migrate_task_to(p, env.best_cpu);
  841. }
  842. /* Attempt to migrate a task to a CPU on the preferred node. */
  843. static void numa_migrate_preferred(struct task_struct *p)
  844. {
  845. /* Success if task is already running on preferred CPU */
  846. p->numa_migrate_retry = 0;
  847. if (cpu_to_node(task_cpu(p)) == p->numa_preferred_nid) {
  848. /*
  849. * If migration is temporarily disabled due to a task migration
  850. * then re-enable it now as the task is running on its
  851. * preferred node and memory should migrate locally
  852. */
  853. if (!p->numa_migrate_seq)
  854. p->numa_migrate_seq++;
  855. return;
  856. }
  857. /* This task has no NUMA fault statistics yet */
  858. if (unlikely(p->numa_preferred_nid == -1))
  859. return;
  860. /* Otherwise, try migrate to a CPU on the preferred node */
  861. if (task_numa_migrate(p) != 0)
  862. p->numa_migrate_retry = jiffies + HZ*5;
  863. }
  864. static void task_numa_placement(struct task_struct *p)
  865. {
  866. int seq, nid, max_nid = -1;
  867. unsigned long max_faults = 0;
  868. seq = ACCESS_ONCE(p->mm->numa_scan_seq);
  869. if (p->numa_scan_seq == seq)
  870. return;
  871. p->numa_scan_seq = seq;
  872. p->numa_migrate_seq++;
  873. p->numa_scan_period_max = task_scan_max(p);
  874. /* Find the node with the highest number of faults */
  875. for_each_online_node(nid) {
  876. unsigned long faults;
  877. int priv, i;
  878. for (priv = 0; priv < 2; priv++) {
  879. i = task_faults_idx(nid, priv);
  880. /* Decay existing window, copy faults since last scan */
  881. p->numa_faults[i] >>= 1;
  882. p->numa_faults[i] += p->numa_faults_buffer[i];
  883. p->numa_faults_buffer[i] = 0;
  884. }
  885. /* Find maximum private faults */
  886. faults = p->numa_faults[task_faults_idx(nid, 1)];
  887. if (faults > max_faults) {
  888. max_faults = faults;
  889. max_nid = nid;
  890. }
  891. }
  892. /* Preferred node as the node with the most faults */
  893. if (max_faults && max_nid != p->numa_preferred_nid) {
  894. /* Update the preferred nid and migrate task if possible */
  895. p->numa_preferred_nid = max_nid;
  896. p->numa_migrate_seq = 1;
  897. numa_migrate_preferred(p);
  898. }
  899. }
  900. /*
  901. * Got a PROT_NONE fault for a page on @node.
  902. */
  903. void task_numa_fault(int last_nidpid, int node, int pages, bool migrated)
  904. {
  905. struct task_struct *p = current;
  906. int priv;
  907. if (!numabalancing_enabled)
  908. return;
  909. /* for example, ksmd faulting in a user's mm */
  910. if (!p->mm)
  911. return;
  912. /*
  913. * First accesses are treated as private, otherwise consider accesses
  914. * to be private if the accessing pid has not changed
  915. */
  916. if (!nidpid_pid_unset(last_nidpid))
  917. priv = ((p->pid & LAST__PID_MASK) == nidpid_to_pid(last_nidpid));
  918. else
  919. priv = 1;
  920. /* Allocate buffer to track faults on a per-node basis */
  921. if (unlikely(!p->numa_faults)) {
  922. int size = sizeof(*p->numa_faults) * 2 * nr_node_ids;
  923. /* numa_faults and numa_faults_buffer share the allocation */
  924. p->numa_faults = kzalloc(size * 2, GFP_KERNEL|__GFP_NOWARN);
  925. if (!p->numa_faults)
  926. return;
  927. BUG_ON(p->numa_faults_buffer);
  928. p->numa_faults_buffer = p->numa_faults + (2 * nr_node_ids);
  929. }
  930. /*
  931. * If pages are properly placed (did not migrate) then scan slower.
  932. * This is reset periodically in case of phase changes
  933. */
  934. if (!migrated) {
  935. /* Initialise if necessary */
  936. if (!p->numa_scan_period_max)
  937. p->numa_scan_period_max = task_scan_max(p);
  938. p->numa_scan_period = min(p->numa_scan_period_max,
  939. p->numa_scan_period + 10);
  940. }
  941. task_numa_placement(p);
  942. /* Retry task to preferred node migration if it previously failed */
  943. if (p->numa_migrate_retry && time_after(jiffies, p->numa_migrate_retry))
  944. numa_migrate_preferred(p);
  945. p->numa_faults_buffer[task_faults_idx(node, priv)] += pages;
  946. }
  947. static void reset_ptenuma_scan(struct task_struct *p)
  948. {
  949. ACCESS_ONCE(p->mm->numa_scan_seq)++;
  950. p->mm->numa_scan_offset = 0;
  951. }
  952. /*
  953. * The expensive part of numa migration is done from task_work context.
  954. * Triggered from task_tick_numa().
  955. */
  956. void task_numa_work(struct callback_head *work)
  957. {
  958. unsigned long migrate, next_scan, now = jiffies;
  959. struct task_struct *p = current;
  960. struct mm_struct *mm = p->mm;
  961. struct vm_area_struct *vma;
  962. unsigned long start, end;
  963. unsigned long nr_pte_updates = 0;
  964. long pages;
  965. WARN_ON_ONCE(p != container_of(work, struct task_struct, numa_work));
  966. work->next = work; /* protect against double add */
  967. /*
  968. * Who cares about NUMA placement when they're dying.
  969. *
  970. * NOTE: make sure not to dereference p->mm before this check,
  971. * exit_task_work() happens _after_ exit_mm() so we could be called
  972. * without p->mm even though we still had it when we enqueued this
  973. * work.
  974. */
  975. if (p->flags & PF_EXITING)
  976. return;
  977. if (!mm->numa_next_reset || !mm->numa_next_scan) {
  978. mm->numa_next_scan = now +
  979. msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
  980. mm->numa_next_reset = now +
  981. msecs_to_jiffies(sysctl_numa_balancing_scan_period_reset);
  982. }
  983. /*
  984. * Reset the scan period if enough time has gone by. Objective is that
  985. * scanning will be reduced if pages are properly placed. As tasks
  986. * can enter different phases this needs to be re-examined. Lacking
  987. * proper tracking of reference behaviour, this blunt hammer is used.
  988. */
  989. migrate = mm->numa_next_reset;
  990. if (time_after(now, migrate)) {
  991. p->numa_scan_period = task_scan_min(p);
  992. next_scan = now + msecs_to_jiffies(sysctl_numa_balancing_scan_period_reset);
  993. xchg(&mm->numa_next_reset, next_scan);
  994. }
  995. /*
  996. * Enforce maximal scan/migration frequency..
  997. */
  998. migrate = mm->numa_next_scan;
  999. if (time_before(now, migrate))
  1000. return;
  1001. if (p->numa_scan_period == 0) {
  1002. p->numa_scan_period_max = task_scan_max(p);
  1003. p->numa_scan_period = task_scan_min(p);
  1004. }
  1005. next_scan = now + msecs_to_jiffies(p->numa_scan_period);
  1006. if (cmpxchg(&mm->numa_next_scan, migrate, next_scan) != migrate)
  1007. return;
  1008. /*
  1009. * Delay this task enough that another task of this mm will likely win
  1010. * the next time around.
  1011. */
  1012. p->node_stamp += 2 * TICK_NSEC;
  1013. start = mm->numa_scan_offset;
  1014. pages = sysctl_numa_balancing_scan_size;
  1015. pages <<= 20 - PAGE_SHIFT; /* MB in pages */
  1016. if (!pages)
  1017. return;
  1018. down_read(&mm->mmap_sem);
  1019. vma = find_vma(mm, start);
  1020. if (!vma) {
  1021. reset_ptenuma_scan(p);
  1022. start = 0;
  1023. vma = mm->mmap;
  1024. }
  1025. for (; vma; vma = vma->vm_next) {
  1026. if (!vma_migratable(vma) || !vma_policy_mof(p, vma))
  1027. continue;
  1028. /*
  1029. * Shared library pages mapped by multiple processes are not
  1030. * migrated as it is expected they are cache replicated. Avoid
  1031. * hinting faults in read-only file-backed mappings or the vdso
  1032. * as migrating the pages will be of marginal benefit.
  1033. */
  1034. if (!vma->vm_mm ||
  1035. (vma->vm_file && (vma->vm_flags & (VM_READ|VM_WRITE)) == (VM_READ)))
  1036. continue;
  1037. do {
  1038. start = max(start, vma->vm_start);
  1039. end = ALIGN(start + (pages << PAGE_SHIFT), HPAGE_SIZE);
  1040. end = min(end, vma->vm_end);
  1041. nr_pte_updates += change_prot_numa(vma, start, end);
  1042. /*
  1043. * Scan sysctl_numa_balancing_scan_size but ensure that
  1044. * at least one PTE is updated so that unused virtual
  1045. * address space is quickly skipped.
  1046. */
  1047. if (nr_pte_updates)
  1048. pages -= (end - start) >> PAGE_SHIFT;
  1049. start = end;
  1050. if (pages <= 0)
  1051. goto out;
  1052. } while (end != vma->vm_end);
  1053. }
  1054. out:
  1055. /*
  1056. * If the whole process was scanned without updates then no NUMA
  1057. * hinting faults are being recorded and scan rate should be lower.
  1058. */
  1059. if (mm->numa_scan_offset == 0 && !nr_pte_updates) {
  1060. p->numa_scan_period = min(p->numa_scan_period_max,
  1061. p->numa_scan_period << 1);
  1062. next_scan = now + msecs_to_jiffies(p->numa_scan_period);
  1063. mm->numa_next_scan = next_scan;
  1064. }
  1065. /*
  1066. * It is possible to reach the end of the VMA list but the last few
  1067. * VMAs are not guaranteed to the vma_migratable. If they are not, we
  1068. * would find the !migratable VMA on the next scan but not reset the
  1069. * scanner to the start so check it now.
  1070. */
  1071. if (vma)
  1072. mm->numa_scan_offset = start;
  1073. else
  1074. reset_ptenuma_scan(p);
  1075. up_read(&mm->mmap_sem);
  1076. }
  1077. /*
  1078. * Drive the periodic memory faults..
  1079. */
  1080. void task_tick_numa(struct rq *rq, struct task_struct *curr)
  1081. {
  1082. struct callback_head *work = &curr->numa_work;
  1083. u64 period, now;
  1084. /*
  1085. * We don't care about NUMA placement if we don't have memory.
  1086. */
  1087. if (!curr->mm || (curr->flags & PF_EXITING) || work->next != work)
  1088. return;
  1089. /*
  1090. * Using runtime rather than walltime has the dual advantage that
  1091. * we (mostly) drive the selection from busy threads and that the
  1092. * task needs to have done some actual work before we bother with
  1093. * NUMA placement.
  1094. */
  1095. now = curr->se.sum_exec_runtime;
  1096. period = (u64)curr->numa_scan_period * NSEC_PER_MSEC;
  1097. if (now - curr->node_stamp > period) {
  1098. if (!curr->node_stamp)
  1099. curr->numa_scan_period = task_scan_min(curr);
  1100. curr->node_stamp += period;
  1101. if (!time_before(jiffies, curr->mm->numa_next_scan)) {
  1102. init_task_work(work, task_numa_work); /* TODO: move this into sched_fork() */
  1103. task_work_add(curr, work, true);
  1104. }
  1105. }
  1106. }
  1107. #else
  1108. static void task_tick_numa(struct rq *rq, struct task_struct *curr)
  1109. {
  1110. }
  1111. #endif /* CONFIG_NUMA_BALANCING */
  1112. static void
  1113. account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
  1114. {
  1115. update_load_add(&cfs_rq->load, se->load.weight);
  1116. if (!parent_entity(se))
  1117. update_load_add(&rq_of(cfs_rq)->load, se->load.weight);
  1118. #ifdef CONFIG_SMP
  1119. if (entity_is_task(se))
  1120. list_add(&se->group_node, &rq_of(cfs_rq)->cfs_tasks);
  1121. #endif
  1122. cfs_rq->nr_running++;
  1123. }
  1124. static void
  1125. account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
  1126. {
  1127. update_load_sub(&cfs_rq->load, se->load.weight);
  1128. if (!parent_entity(se))
  1129. update_load_sub(&rq_of(cfs_rq)->load, se->load.weight);
  1130. if (entity_is_task(se))
  1131. list_del_init(&se->group_node);
  1132. cfs_rq->nr_running--;
  1133. }
  1134. #ifdef CONFIG_FAIR_GROUP_SCHED
  1135. # ifdef CONFIG_SMP
  1136. static inline long calc_tg_weight(struct task_group *tg, struct cfs_rq *cfs_rq)
  1137. {
  1138. long tg_weight;
  1139. /*
  1140. * Use this CPU's actual weight instead of the last load_contribution
  1141. * to gain a more accurate current total weight. See
  1142. * update_cfs_rq_load_contribution().
  1143. */
  1144. tg_weight = atomic_long_read(&tg->load_avg);
  1145. tg_weight -= cfs_rq->tg_load_contrib;
  1146. tg_weight += cfs_rq->load.weight;
  1147. return tg_weight;
  1148. }
  1149. static long calc_cfs_shares(struct cfs_rq *cfs_rq, struct task_group *tg)
  1150. {
  1151. long tg_weight, load, shares;
  1152. tg_weight = calc_tg_weight(tg, cfs_rq);
  1153. load = cfs_rq->load.weight;
  1154. shares = (tg->shares * load);
  1155. if (tg_weight)
  1156. shares /= tg_weight;
  1157. if (shares < MIN_SHARES)
  1158. shares = MIN_SHARES;
  1159. if (shares > tg->shares)
  1160. shares = tg->shares;
  1161. return shares;
  1162. }
  1163. # else /* CONFIG_SMP */
  1164. static inline long calc_cfs_shares(struct cfs_rq *cfs_rq, struct task_group *tg)
  1165. {
  1166. return tg->shares;
  1167. }
  1168. # endif /* CONFIG_SMP */
  1169. static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se,
  1170. unsigned long weight)
  1171. {
  1172. if (se->on_rq) {
  1173. /* commit outstanding execution time */
  1174. if (cfs_rq->curr == se)
  1175. update_curr(cfs_rq);
  1176. account_entity_dequeue(cfs_rq, se);
  1177. }
  1178. update_load_set(&se->load, weight);
  1179. if (se->on_rq)
  1180. account_entity_enqueue(cfs_rq, se);
  1181. }
  1182. static inline int throttled_hierarchy(struct cfs_rq *cfs_rq);
  1183. static void update_cfs_shares(struct cfs_rq *cfs_rq)
  1184. {
  1185. struct task_group *tg;
  1186. struct sched_entity *se;
  1187. long shares;
  1188. tg = cfs_rq->tg;
  1189. se = tg->se[cpu_of(rq_of(cfs_rq))];
  1190. if (!se || throttled_hierarchy(cfs_rq))
  1191. return;
  1192. #ifndef CONFIG_SMP
  1193. if (likely(se->load.weight == tg->shares))
  1194. return;
  1195. #endif
  1196. shares = calc_cfs_shares(cfs_rq, tg);
  1197. reweight_entity(cfs_rq_of(se), se, shares);
  1198. }
  1199. #else /* CONFIG_FAIR_GROUP_SCHED */
  1200. static inline void update_cfs_shares(struct cfs_rq *cfs_rq)
  1201. {
  1202. }
  1203. #endif /* CONFIG_FAIR_GROUP_SCHED */
  1204. #ifdef CONFIG_SMP
  1205. /*
  1206. * We choose a half-life close to 1 scheduling period.
  1207. * Note: The tables below are dependent on this value.
  1208. */
  1209. #define LOAD_AVG_PERIOD 32
  1210. #define LOAD_AVG_MAX 47742 /* maximum possible load avg */
  1211. #define LOAD_AVG_MAX_N 345 /* number of full periods to produce LOAD_MAX_AVG */
  1212. /* Precomputed fixed inverse multiplies for multiplication by y^n */
  1213. static const u32 runnable_avg_yN_inv[] = {
  1214. 0xffffffff, 0xfa83b2da, 0xf5257d14, 0xefe4b99a, 0xeac0c6e6, 0xe5b906e6,
  1215. 0xe0ccdeeb, 0xdbfbb796, 0xd744fcc9, 0xd2a81d91, 0xce248c14, 0xc9b9bd85,
  1216. 0xc5672a10, 0xc12c4cc9, 0xbd08a39e, 0xb8fbaf46, 0xb504f333, 0xb123f581,
  1217. 0xad583ee9, 0xa9a15ab4, 0xa5fed6a9, 0xa2704302, 0x9ef5325f, 0x9b8d39b9,
  1218. 0x9837f050, 0x94f4efa8, 0x91c3d373, 0x8ea4398a, 0x8b95c1e3, 0x88980e80,
  1219. 0x85aac367, 0x82cd8698,
  1220. };
  1221. /*
  1222. * Precomputed \Sum y^k { 1<=k<=n }. These are floor(true_value) to prevent
  1223. * over-estimates when re-combining.
  1224. */
  1225. static const u32 runnable_avg_yN_sum[] = {
  1226. 0, 1002, 1982, 2941, 3880, 4798, 5697, 6576, 7437, 8279, 9103,
  1227. 9909,10698,11470,12226,12966,13690,14398,15091,15769,16433,17082,
  1228. 17718,18340,18949,19545,20128,20698,21256,21802,22336,22859,23371,
  1229. };
  1230. /*
  1231. * Approximate:
  1232. * val * y^n, where y^32 ~= 0.5 (~1 scheduling period)
  1233. */
  1234. static __always_inline u64 decay_load(u64 val, u64 n)
  1235. {
  1236. unsigned int local_n;
  1237. if (!n)
  1238. return val;
  1239. else if (unlikely(n > LOAD_AVG_PERIOD * 63))
  1240. return 0;
  1241. /* after bounds checking we can collapse to 32-bit */
  1242. local_n = n;
  1243. /*
  1244. * As y^PERIOD = 1/2, we can combine
  1245. * y^n = 1/2^(n/PERIOD) * k^(n%PERIOD)
  1246. * With a look-up table which covers k^n (n<PERIOD)
  1247. *
  1248. * To achieve constant time decay_load.
  1249. */
  1250. if (unlikely(local_n >= LOAD_AVG_PERIOD)) {
  1251. val >>= local_n / LOAD_AVG_PERIOD;
  1252. local_n %= LOAD_AVG_PERIOD;
  1253. }
  1254. val *= runnable_avg_yN_inv[local_n];
  1255. /* We don't use SRR here since we always want to round down. */
  1256. return val >> 32;
  1257. }
  1258. /*
  1259. * For updates fully spanning n periods, the contribution to runnable
  1260. * average will be: \Sum 1024*y^n
  1261. *
  1262. * We can compute this reasonably efficiently by combining:
  1263. * y^PERIOD = 1/2 with precomputed \Sum 1024*y^n {for n <PERIOD}
  1264. */
  1265. static u32 __compute_runnable_contrib(u64 n)
  1266. {
  1267. u32 contrib = 0;
  1268. if (likely(n <= LOAD_AVG_PERIOD))
  1269. return runnable_avg_yN_sum[n];
  1270. else if (unlikely(n >= LOAD_AVG_MAX_N))
  1271. return LOAD_AVG_MAX;
  1272. /* Compute \Sum k^n combining precomputed values for k^i, \Sum k^j */
  1273. do {
  1274. contrib /= 2; /* y^LOAD_AVG_PERIOD = 1/2 */
  1275. contrib += runnable_avg_yN_sum[LOAD_AVG_PERIOD];
  1276. n -= LOAD_AVG_PERIOD;
  1277. } while (n > LOAD_AVG_PERIOD);
  1278. contrib = decay_load(contrib, n);
  1279. return contrib + runnable_avg_yN_sum[n];
  1280. }
  1281. /*
  1282. * We can represent the historical contribution to runnable average as the
  1283. * coefficients of a geometric series. To do this we sub-divide our runnable
  1284. * history into segments of approximately 1ms (1024us); label the segment that
  1285. * occurred N-ms ago p_N, with p_0 corresponding to the current period, e.g.
  1286. *
  1287. * [<- 1024us ->|<- 1024us ->|<- 1024us ->| ...
  1288. * p0 p1 p2
  1289. * (now) (~1ms ago) (~2ms ago)
  1290. *
  1291. * Let u_i denote the fraction of p_i that the entity was runnable.
  1292. *
  1293. * We then designate the fractions u_i as our co-efficients, yielding the
  1294. * following representation of historical load:
  1295. * u_0 + u_1*y + u_2*y^2 + u_3*y^3 + ...
  1296. *
  1297. * We choose y based on the with of a reasonably scheduling period, fixing:
  1298. * y^32 = 0.5
  1299. *
  1300. * This means that the contribution to load ~32ms ago (u_32) will be weighted
  1301. * approximately half as much as the contribution to load within the last ms
  1302. * (u_0).
  1303. *
  1304. * When a period "rolls over" and we have new u_0`, multiplying the previous
  1305. * sum again by y is sufficient to update:
  1306. * load_avg = u_0` + y*(u_0 + u_1*y + u_2*y^2 + ... )
  1307. * = u_0 + u_1*y + u_2*y^2 + ... [re-labeling u_i --> u_{i+1}]
  1308. */
  1309. static __always_inline int __update_entity_runnable_avg(u64 now,
  1310. struct sched_avg *sa,
  1311. int runnable)
  1312. {
  1313. u64 delta, periods;
  1314. u32 runnable_contrib;
  1315. int delta_w, decayed = 0;
  1316. delta = now - sa->last_runnable_update;
  1317. /*
  1318. * This should only happen when time goes backwards, which it
  1319. * unfortunately does during sched clock init when we swap over to TSC.
  1320. */
  1321. if ((s64)delta < 0) {
  1322. sa->last_runnable_update = now;
  1323. return 0;
  1324. }
  1325. /*
  1326. * Use 1024ns as the unit of measurement since it's a reasonable
  1327. * approximation of 1us and fast to compute.
  1328. */
  1329. delta >>= 10;
  1330. if (!delta)
  1331. return 0;
  1332. sa->last_runnable_update = now;
  1333. /* delta_w is the amount already accumulated against our next period */
  1334. delta_w = sa->runnable_avg_period % 1024;
  1335. if (delta + delta_w >= 1024) {
  1336. /* period roll-over */
  1337. decayed = 1;
  1338. /*
  1339. * Now that we know we're crossing a period boundary, figure
  1340. * out how much from delta we need to complete the current
  1341. * period and accrue it.
  1342. */
  1343. delta_w = 1024 - delta_w;
  1344. if (runnable)
  1345. sa->runnable_avg_sum += delta_w;
  1346. sa->runnable_avg_period += delta_w;
  1347. delta -= delta_w;
  1348. /* Figure out how many additional periods this update spans */
  1349. periods = delta / 1024;
  1350. delta %= 1024;
  1351. sa->runnable_avg_sum = decay_load(sa->runnable_avg_sum,
  1352. periods + 1);
  1353. sa->runnable_avg_period = decay_load(sa->runnable_avg_period,
  1354. periods + 1);
  1355. /* Efficiently calculate \sum (1..n_period) 1024*y^i */
  1356. runnable_contrib = __compute_runnable_contrib(periods);
  1357. if (runnable)
  1358. sa->runnable_avg_sum += runnable_contrib;
  1359. sa->runnable_avg_period += runnable_contrib;
  1360. }
  1361. /* Remainder of delta accrued against u_0` */
  1362. if (runnable)
  1363. sa->runnable_avg_sum += delta;
  1364. sa->runnable_avg_period += delta;
  1365. return decayed;
  1366. }
  1367. /* Synchronize an entity's decay with its parenting cfs_rq.*/
  1368. static inline u64 __synchronize_entity_decay(struct sched_entity *se)
  1369. {
  1370. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  1371. u64 decays = atomic64_read(&cfs_rq->decay_counter);
  1372. decays -= se->avg.decay_count;
  1373. if (!decays)
  1374. return 0;
  1375. se->avg.load_avg_contrib = decay_load(se->avg.load_avg_contrib, decays);
  1376. se->avg.decay_count = 0;
  1377. return decays;
  1378. }
  1379. #ifdef CONFIG_FAIR_GROUP_SCHED
  1380. static inline void __update_cfs_rq_tg_load_contrib(struct cfs_rq *cfs_rq,
  1381. int force_update)
  1382. {
  1383. struct task_group *tg = cfs_rq->tg;
  1384. long tg_contrib;
  1385. tg_contrib = cfs_rq->runnable_load_avg + cfs_rq->blocked_load_avg;
  1386. tg_contrib -= cfs_rq->tg_load_contrib;
  1387. if (force_update || abs(tg_contrib) > cfs_rq->tg_load_contrib / 8) {
  1388. atomic_long_add(tg_contrib, &tg->load_avg);
  1389. cfs_rq->tg_load_contrib += tg_contrib;
  1390. }
  1391. }
  1392. /*
  1393. * Aggregate cfs_rq runnable averages into an equivalent task_group
  1394. * representation for computing load contributions.
  1395. */
  1396. static inline void __update_tg_runnable_avg(struct sched_avg *sa,
  1397. struct cfs_rq *cfs_rq)
  1398. {
  1399. struct task_group *tg = cfs_rq->tg;
  1400. long contrib;
  1401. /* The fraction of a cpu used by this cfs_rq */
  1402. contrib = div_u64(sa->runnable_avg_sum << NICE_0_SHIFT,
  1403. sa->runnable_avg_period + 1);
  1404. contrib -= cfs_rq->tg_runnable_contrib;
  1405. if (abs(contrib) > cfs_rq->tg_runnable_contrib / 64) {
  1406. atomic_add(contrib, &tg->runnable_avg);
  1407. cfs_rq->tg_runnable_contrib += contrib;
  1408. }
  1409. }
  1410. static inline void __update_group_entity_contrib(struct sched_entity *se)
  1411. {
  1412. struct cfs_rq *cfs_rq = group_cfs_rq(se);
  1413. struct task_group *tg = cfs_rq->tg;
  1414. int runnable_avg;
  1415. u64 contrib;
  1416. contrib = cfs_rq->tg_load_contrib * tg->shares;
  1417. se->avg.load_avg_contrib = div_u64(contrib,
  1418. atomic_long_read(&tg->load_avg) + 1);
  1419. /*
  1420. * For group entities we need to compute a correction term in the case
  1421. * that they are consuming <1 cpu so that we would contribute the same
  1422. * load as a task of equal weight.
  1423. *
  1424. * Explicitly co-ordinating this measurement would be expensive, but
  1425. * fortunately the sum of each cpus contribution forms a usable
  1426. * lower-bound on the true value.
  1427. *
  1428. * Consider the aggregate of 2 contributions. Either they are disjoint
  1429. * (and the sum represents true value) or they are disjoint and we are
  1430. * understating by the aggregate of their overlap.
  1431. *
  1432. * Extending this to N cpus, for a given overlap, the maximum amount we
  1433. * understand is then n_i(n_i+1)/2 * w_i where n_i is the number of
  1434. * cpus that overlap for this interval and w_i is the interval width.
  1435. *
  1436. * On a small machine; the first term is well-bounded which bounds the
  1437. * total error since w_i is a subset of the period. Whereas on a
  1438. * larger machine, while this first term can be larger, if w_i is the
  1439. * of consequential size guaranteed to see n_i*w_i quickly converge to
  1440. * our upper bound of 1-cpu.
  1441. */
  1442. runnable_avg = atomic_read(&tg->runnable_avg);
  1443. if (runnable_avg < NICE_0_LOAD) {
  1444. se->avg.load_avg_contrib *= runnable_avg;
  1445. se->avg.load_avg_contrib >>= NICE_0_SHIFT;
  1446. }
  1447. }
  1448. #else
  1449. static inline void __update_cfs_rq_tg_load_contrib(struct cfs_rq *cfs_rq,
  1450. int force_update) {}
  1451. static inline void __update_tg_runnable_avg(struct sched_avg *sa,
  1452. struct cfs_rq *cfs_rq) {}
  1453. static inline void __update_group_entity_contrib(struct sched_entity *se) {}
  1454. #endif
  1455. static inline void __update_task_entity_contrib(struct sched_entity *se)
  1456. {
  1457. u32 contrib;
  1458. /* avoid overflowing a 32-bit type w/ SCHED_LOAD_SCALE */
  1459. contrib = se->avg.runnable_avg_sum * scale_load_down(se->load.weight);
  1460. contrib /= (se->avg.runnable_avg_period + 1);
  1461. se->avg.load_avg_contrib = scale_load(contrib);
  1462. }
  1463. /* Compute the current contribution to load_avg by se, return any delta */
  1464. static long __update_entity_load_avg_contrib(struct sched_entity *se)
  1465. {
  1466. long old_contrib = se->avg.load_avg_contrib;
  1467. if (entity_is_task(se)) {
  1468. __update_task_entity_contrib(se);
  1469. } else {
  1470. __update_tg_runnable_avg(&se->avg, group_cfs_rq(se));
  1471. __update_group_entity_contrib(se);
  1472. }
  1473. return se->avg.load_avg_contrib - old_contrib;
  1474. }
  1475. static inline void subtract_blocked_load_contrib(struct cfs_rq *cfs_rq,
  1476. long load_contrib)
  1477. {
  1478. if (likely(load_contrib < cfs_rq->blocked_load_avg))
  1479. cfs_rq->blocked_load_avg -= load_contrib;
  1480. else
  1481. cfs_rq->blocked_load_avg = 0;
  1482. }
  1483. static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq);
  1484. /* Update a sched_entity's runnable average */
  1485. static inline void update_entity_load_avg(struct sched_entity *se,
  1486. int update_cfs_rq)
  1487. {
  1488. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  1489. long contrib_delta;
  1490. u64 now;
  1491. /*
  1492. * For a group entity we need to use their owned cfs_rq_clock_task() in
  1493. * case they are the parent of a throttled hierarchy.
  1494. */
  1495. if (entity_is_task(se))
  1496. now = cfs_rq_clock_task(cfs_rq);
  1497. else
  1498. now = cfs_rq_clock_task(group_cfs_rq(se));
  1499. if (!__update_entity_runnable_avg(now, &se->avg, se->on_rq))
  1500. return;
  1501. contrib_delta = __update_entity_load_avg_contrib(se);
  1502. if (!update_cfs_rq)
  1503. return;
  1504. if (se->on_rq)
  1505. cfs_rq->runnable_load_avg += contrib_delta;
  1506. else
  1507. subtract_blocked_load_contrib(cfs_rq, -contrib_delta);
  1508. }
  1509. /*
  1510. * Decay the load contributed by all blocked children and account this so that
  1511. * their contribution may appropriately discounted when they wake up.
  1512. */
  1513. static void update_cfs_rq_blocked_load(struct cfs_rq *cfs_rq, int force_update)
  1514. {
  1515. u64 now = cfs_rq_clock_task(cfs_rq) >> 20;
  1516. u64 decays;
  1517. decays = now - cfs_rq->last_decay;
  1518. if (!decays && !force_update)
  1519. return;
  1520. if (atomic_long_read(&cfs_rq->removed_load)) {
  1521. unsigned long removed_load;
  1522. removed_load = atomic_long_xchg(&cfs_rq->removed_load, 0);
  1523. subtract_blocked_load_contrib(cfs_rq, removed_load);
  1524. }
  1525. if (decays) {
  1526. cfs_rq->blocked_load_avg = decay_load(cfs_rq->blocked_load_avg,
  1527. decays);
  1528. atomic64_add(decays, &cfs_rq->decay_counter);
  1529. cfs_rq->last_decay = now;
  1530. }
  1531. __update_cfs_rq_tg_load_contrib(cfs_rq, force_update);
  1532. }
  1533. static inline void update_rq_runnable_avg(struct rq *rq, int runnable)
  1534. {
  1535. __update_entity_runnable_avg(rq_clock_task(rq), &rq->avg, runnable);
  1536. __update_tg_runnable_avg(&rq->avg, &rq->cfs);
  1537. }
  1538. /* Add the load generated by se into cfs_rq's child load-average */
  1539. static inline void enqueue_entity_load_avg(struct cfs_rq *cfs_rq,
  1540. struct sched_entity *se,
  1541. int wakeup)
  1542. {
  1543. /*
  1544. * We track migrations using entity decay_count <= 0, on a wake-up
  1545. * migration we use a negative decay count to track the remote decays
  1546. * accumulated while sleeping.
  1547. *
  1548. * Newly forked tasks are enqueued with se->avg.decay_count == 0, they
  1549. * are seen by enqueue_entity_load_avg() as a migration with an already
  1550. * constructed load_avg_contrib.
  1551. */
  1552. if (unlikely(se->avg.decay_count <= 0)) {
  1553. se->avg.last_runnable_update = rq_clock_task(rq_of(cfs_rq));
  1554. if (se->avg.decay_count) {
  1555. /*
  1556. * In a wake-up migration we have to approximate the
  1557. * time sleeping. This is because we can't synchronize
  1558. * clock_task between the two cpus, and it is not
  1559. * guaranteed to be read-safe. Instead, we can
  1560. * approximate this using our carried decays, which are
  1561. * explicitly atomically readable.
  1562. */
  1563. se->avg.last_runnable_update -= (-se->avg.decay_count)
  1564. << 20;
  1565. update_entity_load_avg(se, 0);
  1566. /* Indicate that we're now synchronized and on-rq */
  1567. se->avg.decay_count = 0;
  1568. }
  1569. wakeup = 0;
  1570. } else {
  1571. /*
  1572. * Task re-woke on same cpu (or else migrate_task_rq_fair()
  1573. * would have made count negative); we must be careful to avoid
  1574. * double-accounting blocked time after synchronizing decays.
  1575. */
  1576. se->avg.last_runnable_update += __synchronize_entity_decay(se)
  1577. << 20;
  1578. }
  1579. /* migrated tasks did not contribute to our blocked load */
  1580. if (wakeup) {
  1581. subtract_blocked_load_contrib(cfs_rq, se->avg.load_avg_contrib);
  1582. update_entity_load_avg(se, 0);
  1583. }
  1584. cfs_rq->runnable_load_avg += se->avg.load_avg_contrib;
  1585. /* we force update consideration on load-balancer moves */
  1586. update_cfs_rq_blocked_load(cfs_rq, !wakeup);
  1587. }
  1588. /*
  1589. * Remove se's load from this cfs_rq child load-average, if the entity is
  1590. * transitioning to a blocked state we track its projected decay using
  1591. * blocked_load_avg.
  1592. */
  1593. static inline void dequeue_entity_load_avg(struct cfs_rq *cfs_rq,
  1594. struct sched_entity *se,
  1595. int sleep)
  1596. {
  1597. update_entity_load_avg(se, 1);
  1598. /* we force update consideration on load-balancer moves */
  1599. update_cfs_rq_blocked_load(cfs_rq, !sleep);
  1600. cfs_rq->runnable_load_avg -= se->avg.load_avg_contrib;
  1601. if (sleep) {
  1602. cfs_rq->blocked_load_avg += se->avg.load_avg_contrib;
  1603. se->avg.decay_count = atomic64_read(&cfs_rq->decay_counter);
  1604. } /* migrations, e.g. sleep=0 leave decay_count == 0 */
  1605. }
  1606. /*
  1607. * Update the rq's load with the elapsed running time before entering
  1608. * idle. if the last scheduled task is not a CFS task, idle_enter will
  1609. * be the only way to update the runnable statistic.
  1610. */
  1611. void idle_enter_fair(struct rq *this_rq)
  1612. {
  1613. update_rq_runnable_avg(this_rq, 1);
  1614. }
  1615. /*
  1616. * Update the rq's load with the elapsed idle time before a task is
  1617. * scheduled. if the newly scheduled task is not a CFS task, idle_exit will
  1618. * be the only way to update the runnable statistic.
  1619. */
  1620. void idle_exit_fair(struct rq *this_rq)
  1621. {
  1622. update_rq_runnable_avg(this_rq, 0);
  1623. }
  1624. #else
  1625. static inline void update_entity_load_avg(struct sched_entity *se,
  1626. int update_cfs_rq) {}
  1627. static inline void update_rq_runnable_avg(struct rq *rq, int runnable) {}
  1628. static inline void enqueue_entity_load_avg(struct cfs_rq *cfs_rq,
  1629. struct sched_entity *se,
  1630. int wakeup) {}
  1631. static inline void dequeue_entity_load_avg(struct cfs_rq *cfs_rq,
  1632. struct sched_entity *se,
  1633. int sleep) {}
  1634. static inline void update_cfs_rq_blocked_load(struct cfs_rq *cfs_rq,
  1635. int force_update) {}
  1636. #endif
  1637. static void enqueue_sleeper(struct cfs_rq *cfs_rq, struct sched_entity *se)
  1638. {
  1639. #ifdef CONFIG_SCHEDSTATS
  1640. struct task_struct *tsk = NULL;
  1641. if (entity_is_task(se))
  1642. tsk = task_of(se);
  1643. if (se->statistics.sleep_start) {
  1644. u64 delta = rq_clock(rq_of(cfs_rq)) - se->statistics.sleep_start;
  1645. if ((s64)delta < 0)
  1646. delta = 0;
  1647. if (unlikely(delta > se->statistics.sleep_max))
  1648. se->statistics.sleep_max = delta;
  1649. se->statistics.sleep_start = 0;
  1650. se->statistics.sum_sleep_runtime += delta;
  1651. if (tsk) {
  1652. account_scheduler_latency(tsk, delta >> 10, 1);
  1653. trace_sched_stat_sleep(tsk, delta);
  1654. }
  1655. }
  1656. if (se->statistics.block_start) {
  1657. u64 delta = rq_clock(rq_of(cfs_rq)) - se->statistics.block_start;
  1658. if ((s64)delta < 0)
  1659. delta = 0;
  1660. if (unlikely(delta > se->statistics.block_max))
  1661. se->statistics.block_max = delta;
  1662. se->statistics.block_start = 0;
  1663. se->statistics.sum_sleep_runtime += delta;
  1664. if (tsk) {
  1665. if (tsk->in_iowait) {
  1666. se->statistics.iowait_sum += delta;
  1667. se->statistics.iowait_count++;
  1668. trace_sched_stat_iowait(tsk, delta);
  1669. }
  1670. trace_sched_stat_blocked(tsk, delta);
  1671. /*
  1672. * Blocking time is in units of nanosecs, so shift by
  1673. * 20 to get a milliseconds-range estimation of the
  1674. * amount of time that the task spent sleeping:
  1675. */
  1676. if (unlikely(prof_on == SLEEP_PROFILING)) {
  1677. profile_hits(SLEEP_PROFILING,
  1678. (void *)get_wchan(tsk),
  1679. delta >> 20);
  1680. }
  1681. account_scheduler_latency(tsk, delta >> 10, 0);
  1682. }
  1683. }
  1684. #endif
  1685. }
  1686. static void check_spread(struct cfs_rq *cfs_rq, struct sched_entity *se)
  1687. {
  1688. #ifdef CONFIG_SCHED_DEBUG
  1689. s64 d = se->vruntime - cfs_rq->min_vruntime;
  1690. if (d < 0)
  1691. d = -d;
  1692. if (d > 3*sysctl_sched_latency)
  1693. schedstat_inc(cfs_rq, nr_spread_over);
  1694. #endif
  1695. }
  1696. static void
  1697. place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int initial)
  1698. {
  1699. u64 vruntime = cfs_rq->min_vruntime;
  1700. /*
  1701. * The 'current' period is already promised to the current tasks,
  1702. * however the extra weight of the new task will slow them down a
  1703. * little, place the new task so that it fits in the slot that
  1704. * stays open at the end.
  1705. */
  1706. if (initial && sched_feat(START_DEBIT))
  1707. vruntime += sched_vslice(cfs_rq, se);
  1708. /* sleeps up to a single latency don't count. */
  1709. if (!initial) {
  1710. unsigned long thresh = sysctl_sched_latency;
  1711. /*
  1712. * Halve their sleep time's effect, to allow
  1713. * for a gentler effect of sleepers:
  1714. */
  1715. if (sched_feat(GENTLE_FAIR_SLEEPERS))
  1716. thresh >>= 1;
  1717. vruntime -= thresh;
  1718. }
  1719. /* ensure we never gain time by being placed backwards. */
  1720. se->vruntime = max_vruntime(se->vruntime, vruntime);
  1721. }
  1722. static void check_enqueue_throttle(struct cfs_rq *cfs_rq);
  1723. static void
  1724. enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
  1725. {
  1726. /*
  1727. * Update the normalized vruntime before updating min_vruntime
  1728. * through calling update_curr().
  1729. */
  1730. if (!(flags & ENQUEUE_WAKEUP) || (flags & ENQUEUE_WAKING))
  1731. se->vruntime += cfs_rq->min_vruntime;
  1732. /*
  1733. * Update run-time statistics of the 'current'.
  1734. */
  1735. update_curr(cfs_rq);
  1736. enqueue_entity_load_avg(cfs_rq, se, flags & ENQUEUE_WAKEUP);
  1737. account_entity_enqueue(cfs_rq, se);
  1738. update_cfs_shares(cfs_rq);
  1739. if (flags & ENQUEUE_WAKEUP) {
  1740. place_entity(cfs_rq, se, 0);
  1741. enqueue_sleeper(cfs_rq, se);
  1742. }
  1743. update_stats_enqueue(cfs_rq, se);
  1744. check_spread(cfs_rq, se);
  1745. if (se != cfs_rq->curr)
  1746. __enqueue_entity(cfs_rq, se);
  1747. se->on_rq = 1;
  1748. if (cfs_rq->nr_running == 1) {
  1749. list_add_leaf_cfs_rq(cfs_rq);
  1750. check_enqueue_throttle(cfs_rq);
  1751. }
  1752. }
  1753. static void __clear_buddies_last(struct sched_entity *se)
  1754. {
  1755. for_each_sched_entity(se) {
  1756. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  1757. if (cfs_rq->last == se)
  1758. cfs_rq->last = NULL;
  1759. else
  1760. break;
  1761. }
  1762. }
  1763. static void __clear_buddies_next(struct sched_entity *se)
  1764. {
  1765. for_each_sched_entity(se) {
  1766. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  1767. if (cfs_rq->next == se)
  1768. cfs_rq->next = NULL;
  1769. else
  1770. break;
  1771. }
  1772. }
  1773. static void __clear_buddies_skip(struct sched_entity *se)
  1774. {
  1775. for_each_sched_entity(se) {
  1776. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  1777. if (cfs_rq->skip == se)
  1778. cfs_rq->skip = NULL;
  1779. else
  1780. break;
  1781. }
  1782. }
  1783. static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
  1784. {
  1785. if (cfs_rq->last == se)
  1786. __clear_buddies_last(se);
  1787. if (cfs_rq->next == se)
  1788. __clear_buddies_next(se);
  1789. if (cfs_rq->skip == se)
  1790. __clear_buddies_skip(se);
  1791. }
  1792. static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq);
  1793. static void
  1794. dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
  1795. {
  1796. /*
  1797. * Update run-time statistics of the 'current'.
  1798. */
  1799. update_curr(cfs_rq);
  1800. dequeue_entity_load_avg(cfs_rq, se, flags & DEQUEUE_SLEEP);
  1801. update_stats_dequeue(cfs_rq, se);
  1802. if (flags & DEQUEUE_SLEEP) {
  1803. #ifdef CONFIG_SCHEDSTATS
  1804. if (entity_is_task(se)) {
  1805. struct task_struct *tsk = task_of(se);
  1806. if (tsk->state & TASK_INTERRUPTIBLE)
  1807. se->statistics.sleep_start = rq_clock(rq_of(cfs_rq));
  1808. if (tsk->state & TASK_UNINTERRUPTIBLE)
  1809. se->statistics.block_start = rq_clock(rq_of(cfs_rq));
  1810. }
  1811. #endif
  1812. }
  1813. clear_buddies(cfs_rq, se);
  1814. if (se != cfs_rq->curr)
  1815. __dequeue_entity(cfs_rq, se);
  1816. se->on_rq = 0;
  1817. account_entity_dequeue(cfs_rq, se);
  1818. /*
  1819. * Normalize the entity after updating the min_vruntime because the
  1820. * update can refer to the ->curr item and we need to reflect this
  1821. * movement in our normalized position.
  1822. */
  1823. if (!(flags & DEQUEUE_SLEEP))
  1824. se->vruntime -= cfs_rq->min_vruntime;
  1825. /* return excess runtime on last dequeue */
  1826. return_cfs_rq_runtime(cfs_rq);
  1827. update_min_vruntime(cfs_rq);
  1828. update_cfs_shares(cfs_rq);
  1829. }
  1830. /*
  1831. * Preempt the current task with a newly woken task if needed:
  1832. */
  1833. static void
  1834. check_preempt_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr)
  1835. {
  1836. unsigned long ideal_runtime, delta_exec;
  1837. struct sched_entity *se;
  1838. s64 delta;
  1839. ideal_runtime = sched_slice(cfs_rq, curr);
  1840. delta_exec = curr->sum_exec_runtime - curr->prev_sum_exec_runtime;
  1841. if (delta_exec > ideal_runtime) {
  1842. resched_task(rq_of(cfs_rq)->curr);
  1843. /*
  1844. * The current task ran long enough, ensure it doesn't get
  1845. * re-elected due to buddy favours.
  1846. */
  1847. clear_buddies(cfs_rq, curr);
  1848. return;
  1849. }
  1850. /*
  1851. * Ensure that a task that missed wakeup preemption by a
  1852. * narrow margin doesn't have to wait for a full slice.
  1853. * This also mitigates buddy induced latencies under load.
  1854. */
  1855. if (delta_exec < sysctl_sched_min_granularity)
  1856. return;
  1857. se = __pick_first_entity(cfs_rq);
  1858. delta = curr->vruntime - se->vruntime;
  1859. if (delta < 0)
  1860. return;
  1861. if (delta > ideal_runtime)
  1862. resched_task(rq_of(cfs_rq)->curr);
  1863. }
  1864. static void
  1865. set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
  1866. {
  1867. /* 'current' is not kept within the tree. */
  1868. if (se->on_rq) {
  1869. /*
  1870. * Any task has to be enqueued before it get to execute on
  1871. * a CPU. So account for the time it spent waiting on the
  1872. * runqueue.
  1873. */
  1874. update_stats_wait_end(cfs_rq, se);
  1875. __dequeue_entity(cfs_rq, se);
  1876. }
  1877. update_stats_curr_start(cfs_rq, se);
  1878. cfs_rq->curr = se;
  1879. #ifdef CONFIG_SCHEDSTATS
  1880. /*
  1881. * Track our maximum slice length, if the CPU's load is at
  1882. * least twice that of our own weight (i.e. dont track it
  1883. * when there are only lesser-weight tasks around):
  1884. */
  1885. if (rq_of(cfs_rq)->load.weight >= 2*se->load.weight) {
  1886. se->statistics.slice_max = max(se->statistics.slice_max,
  1887. se->sum_exec_runtime - se->prev_sum_exec_runtime);
  1888. }
  1889. #endif
  1890. se->prev_sum_exec_runtime = se->sum_exec_runtime;
  1891. }
  1892. static int
  1893. wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se);
  1894. /*
  1895. * Pick the next process, keeping these things in mind, in this order:
  1896. * 1) keep things fair between processes/task groups
  1897. * 2) pick the "next" process, since someone really wants that to run
  1898. * 3) pick the "last" process, for cache locality
  1899. * 4) do not run the "skip" process, if something else is available
  1900. */
  1901. static struct sched_entity *pick_next_entity(struct cfs_rq *cfs_rq)
  1902. {
  1903. struct sched_entity *se = __pick_first_entity(cfs_rq);
  1904. struct sched_entity *left = se;
  1905. /*
  1906. * Avoid running the skip buddy, if running something else can
  1907. * be done without getting too unfair.
  1908. */
  1909. if (cfs_rq->skip == se) {
  1910. struct sched_entity *second = __pick_next_entity(se);
  1911. if (second && wakeup_preempt_entity(second, left) < 1)
  1912. se = second;
  1913. }
  1914. /*
  1915. * Prefer last buddy, try to return the CPU to a preempted task.
  1916. */
  1917. if (cfs_rq->last && wakeup_preempt_entity(cfs_rq->last, left) < 1)
  1918. se = cfs_rq->last;
  1919. /*
  1920. * Someone really wants this to run. If it's not unfair, run it.
  1921. */
  1922. if (cfs_rq->next && wakeup_preempt_entity(cfs_rq->next, left) < 1)
  1923. se = cfs_rq->next;
  1924. clear_buddies(cfs_rq, se);
  1925. return se;
  1926. }
  1927. static void check_cfs_rq_runtime(struct cfs_rq *cfs_rq);
  1928. static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
  1929. {
  1930. /*
  1931. * If still on the runqueue then deactivate_task()
  1932. * was not called and update_curr() has to be done:
  1933. */
  1934. if (prev->on_rq)
  1935. update_curr(cfs_rq);
  1936. /* throttle cfs_rqs exceeding runtime */
  1937. check_cfs_rq_runtime(cfs_rq);
  1938. check_spread(cfs_rq, prev);
  1939. if (prev->on_rq) {
  1940. update_stats_wait_start(cfs_rq, prev);
  1941. /* Put 'current' back into the tree. */
  1942. __enqueue_entity(cfs_rq, prev);
  1943. /* in !on_rq case, update occurred at dequeue */
  1944. update_entity_load_avg(prev, 1);
  1945. }
  1946. cfs_rq->curr = NULL;
  1947. }
  1948. static void
  1949. entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
  1950. {
  1951. /*
  1952. * Update run-time statistics of the 'current'.
  1953. */
  1954. update_curr(cfs_rq);
  1955. /*
  1956. * Ensure that runnable average is periodically updated.
  1957. */
  1958. update_entity_load_avg(curr, 1);
  1959. update_cfs_rq_blocked_load(cfs_rq, 1);
  1960. update_cfs_shares(cfs_rq);
  1961. #ifdef CONFIG_SCHED_HRTICK
  1962. /*
  1963. * queued ticks are scheduled to match the slice, so don't bother
  1964. * validating it and just reschedule.
  1965. */
  1966. if (queued) {
  1967. resched_task(rq_of(cfs_rq)->curr);
  1968. return;
  1969. }
  1970. /*
  1971. * don't let the period tick interfere with the hrtick preemption
  1972. */
  1973. if (!sched_feat(DOUBLE_TICK) &&
  1974. hrtimer_active(&rq_of(cfs_rq)->hrtick_timer))
  1975. return;
  1976. #endif
  1977. if (cfs_rq->nr_running > 1)
  1978. check_preempt_tick(cfs_rq, curr);
  1979. }
  1980. /**************************************************
  1981. * CFS bandwidth control machinery
  1982. */
  1983. #ifdef CONFIG_CFS_BANDWIDTH
  1984. #ifdef HAVE_JUMP_LABEL
  1985. static struct static_key __cfs_bandwidth_used;
  1986. static inline bool cfs_bandwidth_used(void)
  1987. {
  1988. return static_key_false(&__cfs_bandwidth_used);
  1989. }
  1990. void account_cfs_bandwidth_used(int enabled, int was_enabled)
  1991. {
  1992. /* only need to count groups transitioning between enabled/!enabled */
  1993. if (enabled && !was_enabled)
  1994. static_key_slow_inc(&__cfs_bandwidth_used);
  1995. else if (!enabled && was_enabled)
  1996. static_key_slow_dec(&__cfs_bandwidth_used);
  1997. }
  1998. #else /* HAVE_JUMP_LABEL */
  1999. static bool cfs_bandwidth_used(void)
  2000. {
  2001. return true;
  2002. }
  2003. void account_cfs_bandwidth_used(int enabled, int was_enabled) {}
  2004. #endif /* HAVE_JUMP_LABEL */
  2005. /*
  2006. * default period for cfs group bandwidth.
  2007. * default: 0.1s, units: nanoseconds
  2008. */
  2009. static inline u64 default_cfs_period(void)
  2010. {
  2011. return 100000000ULL;
  2012. }
  2013. static inline u64 sched_cfs_bandwidth_slice(void)
  2014. {
  2015. return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC;
  2016. }
  2017. /*
  2018. * Replenish runtime according to assigned quota and update expiration time.
  2019. * We use sched_clock_cpu directly instead of rq->clock to avoid adding
  2020. * additional synchronization around rq->lock.
  2021. *
  2022. * requires cfs_b->lock
  2023. */
  2024. void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
  2025. {
  2026. u64 now;
  2027. if (cfs_b->quota == RUNTIME_INF)
  2028. return;
  2029. now = sched_clock_cpu(smp_processor_id());
  2030. cfs_b->runtime = cfs_b->quota;
  2031. cfs_b->runtime_expires = now + ktime_to_ns(cfs_b->period);
  2032. }
  2033. static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
  2034. {
  2035. return &tg->cfs_bandwidth;
  2036. }
  2037. /* rq->task_clock normalized against any time this cfs_rq has spent throttled */
  2038. static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq)
  2039. {
  2040. if (unlikely(cfs_rq->throttle_count))
  2041. return cfs_rq->throttled_clock_task;
  2042. return rq_clock_task(rq_of(cfs_rq)) - cfs_rq->throttled_clock_task_time;
  2043. }
  2044. /* returns 0 on failure to allocate runtime */
  2045. static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  2046. {
  2047. struct task_group *tg = cfs_rq->tg;
  2048. struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(tg);
  2049. u64 amount = 0, min_amount, expires;
  2050. /* note: this is a positive sum as runtime_remaining <= 0 */
  2051. min_amount = sched_cfs_bandwidth_slice() - cfs_rq->runtime_remaining;
  2052. raw_spin_lock(&cfs_b->lock);
  2053. if (cfs_b->quota == RUNTIME_INF)
  2054. amount = min_amount;
  2055. else {
  2056. /*
  2057. * If the bandwidth pool has become inactive, then at least one
  2058. * period must have elapsed since the last consumption.
  2059. * Refresh the global state and ensure bandwidth timer becomes
  2060. * active.
  2061. */
  2062. if (!cfs_b->timer_active) {
  2063. __refill_cfs_bandwidth_runtime(cfs_b);
  2064. __start_cfs_bandwidth(cfs_b);
  2065. }
  2066. if (cfs_b->runtime > 0) {
  2067. amount = min(cfs_b->runtime, min_amount);
  2068. cfs_b->runtime -= amount;
  2069. cfs_b->idle = 0;
  2070. }
  2071. }
  2072. expires = cfs_b->runtime_expires;
  2073. raw_spin_unlock(&cfs_b->lock);
  2074. cfs_rq->runtime_remaining += amount;
  2075. /*
  2076. * we may have advanced our local expiration to account for allowed
  2077. * spread between our sched_clock and the one on which runtime was
  2078. * issued.
  2079. */
  2080. if ((s64)(expires - cfs_rq->runtime_expires) > 0)
  2081. cfs_rq->runtime_expires = expires;
  2082. return cfs_rq->runtime_remaining > 0;
  2083. }
  2084. /*
  2085. * Note: This depends on the synchronization provided by sched_clock and the
  2086. * fact that rq->clock snapshots this value.
  2087. */
  2088. static void expire_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  2089. {
  2090. struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
  2091. /* if the deadline is ahead of our clock, nothing to do */
  2092. if (likely((s64)(rq_clock(rq_of(cfs_rq)) - cfs_rq->runtime_expires) < 0))
  2093. return;
  2094. if (cfs_rq->runtime_remaining < 0)
  2095. return;
  2096. /*
  2097. * If the local deadline has passed we have to consider the
  2098. * possibility that our sched_clock is 'fast' and the global deadline
  2099. * has not truly expired.
  2100. *
  2101. * Fortunately we can check determine whether this the case by checking
  2102. * whether the global deadline has advanced.
  2103. */
  2104. if ((s64)(cfs_rq->runtime_expires - cfs_b->runtime_expires) >= 0) {
  2105. /* extend local deadline, drift is bounded above by 2 ticks */
  2106. cfs_rq->runtime_expires += TICK_NSEC;
  2107. } else {
  2108. /* global deadline is ahead, expiration has passed */
  2109. cfs_rq->runtime_remaining = 0;
  2110. }
  2111. }
  2112. static void __account_cfs_rq_runtime(struct cfs_rq *cfs_rq,
  2113. unsigned long delta_exec)
  2114. {
  2115. /* dock delta_exec before expiring quota (as it could span periods) */
  2116. cfs_rq->runtime_remaining -= delta_exec;
  2117. expire_cfs_rq_runtime(cfs_rq);
  2118. if (likely(cfs_rq->runtime_remaining > 0))
  2119. return;
  2120. /*
  2121. * if we're unable to extend our runtime we resched so that the active
  2122. * hierarchy can be throttled
  2123. */
  2124. if (!assign_cfs_rq_runtime(cfs_rq) && likely(cfs_rq->curr))
  2125. resched_task(rq_of(cfs_rq)->curr);
  2126. }
  2127. static __always_inline
  2128. void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, unsigned long delta_exec)
  2129. {
  2130. if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled)
  2131. return;
  2132. __account_cfs_rq_runtime(cfs_rq, delta_exec);
  2133. }
  2134. static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
  2135. {
  2136. return cfs_bandwidth_used() && cfs_rq->throttled;
  2137. }
  2138. /* check whether cfs_rq, or any parent, is throttled */
  2139. static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
  2140. {
  2141. return cfs_bandwidth_used() && cfs_rq->throttle_count;
  2142. }
  2143. /*
  2144. * Ensure that neither of the group entities corresponding to src_cpu or
  2145. * dest_cpu are members of a throttled hierarchy when performing group
  2146. * load-balance operations.
  2147. */
  2148. static inline int throttled_lb_pair(struct task_group *tg,
  2149. int src_cpu, int dest_cpu)
  2150. {
  2151. struct cfs_rq *src_cfs_rq, *dest_cfs_rq;
  2152. src_cfs_rq = tg->cfs_rq[src_cpu];
  2153. dest_cfs_rq = tg->cfs_rq[dest_cpu];
  2154. return throttled_hierarchy(src_cfs_rq) ||
  2155. throttled_hierarchy(dest_cfs_rq);
  2156. }
  2157. /* updated child weight may affect parent so we have to do this bottom up */
  2158. static int tg_unthrottle_up(struct task_group *tg, void *data)
  2159. {
  2160. struct rq *rq = data;
  2161. struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
  2162. cfs_rq->throttle_count--;
  2163. #ifdef CONFIG_SMP
  2164. if (!cfs_rq->throttle_count) {
  2165. /* adjust cfs_rq_clock_task() */
  2166. cfs_rq->throttled_clock_task_time += rq_clock_task(rq) -
  2167. cfs_rq->throttled_clock_task;
  2168. }
  2169. #endif
  2170. return 0;
  2171. }
  2172. static int tg_throttle_down(struct task_group *tg, void *data)
  2173. {
  2174. struct rq *rq = data;
  2175. struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
  2176. /* group is entering throttled state, stop time */
  2177. if (!cfs_rq->throttle_count)
  2178. cfs_rq->throttled_clock_task = rq_clock_task(rq);
  2179. cfs_rq->throttle_count++;
  2180. return 0;
  2181. }
  2182. static void throttle_cfs_rq(struct cfs_rq *cfs_rq)
  2183. {
  2184. struct rq *rq = rq_of(cfs_rq);
  2185. struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
  2186. struct sched_entity *se;
  2187. long task_delta, dequeue = 1;
  2188. se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))];
  2189. /* freeze hierarchy runnable averages while throttled */
  2190. rcu_read_lock();
  2191. walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq);
  2192. rcu_read_unlock();
  2193. task_delta = cfs_rq->h_nr_running;
  2194. for_each_sched_entity(se) {
  2195. struct cfs_rq *qcfs_rq = cfs_rq_of(se);
  2196. /* throttled entity or throttle-on-deactivate */
  2197. if (!se->on_rq)
  2198. break;
  2199. if (dequeue)
  2200. dequeue_entity(qcfs_rq, se, DEQUEUE_SLEEP);
  2201. qcfs_rq->h_nr_running -= task_delta;
  2202. if (qcfs_rq->load.weight)
  2203. dequeue = 0;
  2204. }
  2205. if (!se)
  2206. rq->nr_running -= task_delta;
  2207. cfs_rq->throttled = 1;
  2208. cfs_rq->throttled_clock = rq_clock(rq);
  2209. raw_spin_lock(&cfs_b->lock);
  2210. list_add_tail_rcu(&cfs_rq->throttled_list, &cfs_b->throttled_cfs_rq);
  2211. raw_spin_unlock(&cfs_b->lock);
  2212. }
  2213. void unthrottle_cfs_rq(struct cfs_rq *cfs_rq)
  2214. {
  2215. struct rq *rq = rq_of(cfs_rq);
  2216. struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
  2217. struct sched_entity *se;
  2218. int enqueue = 1;
  2219. long task_delta;
  2220. se = cfs_rq->tg->se[cpu_of(rq)];
  2221. cfs_rq->throttled = 0;
  2222. update_rq_clock(rq);
  2223. raw_spin_lock(&cfs_b->lock);
  2224. cfs_b->throttled_time += rq_clock(rq) - cfs_rq->throttled_clock;
  2225. list_del_rcu(&cfs_rq->throttled_list);
  2226. raw_spin_unlock(&cfs_b->lock);
  2227. /* update hierarchical throttle state */
  2228. walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq);
  2229. if (!cfs_rq->load.weight)
  2230. return;
  2231. task_delta = cfs_rq->h_nr_running;
  2232. for_each_sched_entity(se) {
  2233. if (se->on_rq)
  2234. enqueue = 0;
  2235. cfs_rq = cfs_rq_of(se);
  2236. if (enqueue)
  2237. enqueue_entity(cfs_rq, se, ENQUEUE_WAKEUP);
  2238. cfs_rq->h_nr_running += task_delta;
  2239. if (cfs_rq_throttled(cfs_rq))
  2240. break;
  2241. }
  2242. if (!se)
  2243. rq->nr_running += task_delta;
  2244. /* determine whether we need to wake up potentially idle cpu */
  2245. if (rq->curr == rq->idle && rq->cfs.nr_running)
  2246. resched_task(rq->curr);
  2247. }
  2248. static u64 distribute_cfs_runtime(struct cfs_bandwidth *cfs_b,
  2249. u64 remaining, u64 expires)
  2250. {
  2251. struct cfs_rq *cfs_rq;
  2252. u64 runtime = remaining;
  2253. rcu_read_lock();
  2254. list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
  2255. throttled_list) {
  2256. struct rq *rq = rq_of(cfs_rq);
  2257. raw_spin_lock(&rq->lock);
  2258. if (!cfs_rq_throttled(cfs_rq))
  2259. goto next;
  2260. runtime = -cfs_rq->runtime_remaining + 1;
  2261. if (runtime > remaining)
  2262. runtime = remaining;
  2263. remaining -= runtime;
  2264. cfs_rq->runtime_remaining += runtime;
  2265. cfs_rq->runtime_expires = expires;
  2266. /* we check whether we're throttled above */
  2267. if (cfs_rq->runtime_remaining > 0)
  2268. unthrottle_cfs_rq(cfs_rq);
  2269. next:
  2270. raw_spin_unlock(&rq->lock);
  2271. if (!remaining)
  2272. break;
  2273. }
  2274. rcu_read_unlock();
  2275. return remaining;
  2276. }
  2277. /*
  2278. * Responsible for refilling a task_group's bandwidth and unthrottling its
  2279. * cfs_rqs as appropriate. If there has been no activity within the last
  2280. * period the timer is deactivated until scheduling resumes; cfs_b->idle is
  2281. * used to track this state.
  2282. */
  2283. static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun)
  2284. {
  2285. u64 runtime, runtime_expires;
  2286. int idle = 1, throttled;
  2287. raw_spin_lock(&cfs_b->lock);
  2288. /* no need to continue the timer with no bandwidth constraint */
  2289. if (cfs_b->quota == RUNTIME_INF)
  2290. goto out_unlock;
  2291. throttled = !list_empty(&cfs_b->throttled_cfs_rq);
  2292. /* idle depends on !throttled (for the case of a large deficit) */
  2293. idle = cfs_b->idle && !throttled;
  2294. cfs_b->nr_periods += overrun;
  2295. /* if we're going inactive then everything else can be deferred */
  2296. if (idle)
  2297. goto out_unlock;
  2298. __refill_cfs_bandwidth_runtime(cfs_b);
  2299. if (!throttled) {
  2300. /* mark as potentially idle for the upcoming period */
  2301. cfs_b->idle = 1;
  2302. goto out_unlock;
  2303. }
  2304. /* account preceding periods in which throttling occurred */
  2305. cfs_b->nr_throttled += overrun;
  2306. /*
  2307. * There are throttled entities so we must first use the new bandwidth
  2308. * to unthrottle them before making it generally available. This
  2309. * ensures that all existing debts will be paid before a new cfs_rq is
  2310. * allowed to run.
  2311. */
  2312. runtime = cfs_b->runtime;
  2313. runtime_expires = cfs_b->runtime_expires;
  2314. cfs_b->runtime = 0;
  2315. /*
  2316. * This check is repeated as we are holding onto the new bandwidth
  2317. * while we unthrottle. This can potentially race with an unthrottled
  2318. * group trying to acquire new bandwidth from the global pool.
  2319. */
  2320. while (throttled && runtime > 0) {
  2321. raw_spin_unlock(&cfs_b->lock);
  2322. /* we can't nest cfs_b->lock while distributing bandwidth */
  2323. runtime = distribute_cfs_runtime(cfs_b, runtime,
  2324. runtime_expires);
  2325. raw_spin_lock(&cfs_b->lock);
  2326. throttled = !list_empty(&cfs_b->throttled_cfs_rq);
  2327. }
  2328. /* return (any) remaining runtime */
  2329. cfs_b->runtime = runtime;
  2330. /*
  2331. * While we are ensured activity in the period following an
  2332. * unthrottle, this also covers the case in which the new bandwidth is
  2333. * insufficient to cover the existing bandwidth deficit. (Forcing the
  2334. * timer to remain active while there are any throttled entities.)
  2335. */
  2336. cfs_b->idle = 0;
  2337. out_unlock:
  2338. if (idle)
  2339. cfs_b->timer_active = 0;
  2340. raw_spin_unlock(&cfs_b->lock);
  2341. return idle;
  2342. }
  2343. /* a cfs_rq won't donate quota below this amount */
  2344. static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC;
  2345. /* minimum remaining period time to redistribute slack quota */
  2346. static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC;
  2347. /* how long we wait to gather additional slack before distributing */
  2348. static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC;
  2349. /* are we near the end of the current quota period? */
  2350. static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire)
  2351. {
  2352. struct hrtimer *refresh_timer = &cfs_b->period_timer;
  2353. u64 remaining;
  2354. /* if the call-back is running a quota refresh is already occurring */
  2355. if (hrtimer_callback_running(refresh_timer))
  2356. return 1;
  2357. /* is a quota refresh about to occur? */
  2358. remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer));
  2359. if (remaining < min_expire)
  2360. return 1;
  2361. return 0;
  2362. }
  2363. static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b)
  2364. {
  2365. u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration;
  2366. /* if there's a quota refresh soon don't bother with slack */
  2367. if (runtime_refresh_within(cfs_b, min_left))
  2368. return;
  2369. start_bandwidth_timer(&cfs_b->slack_timer,
  2370. ns_to_ktime(cfs_bandwidth_slack_period));
  2371. }
  2372. /* we know any runtime found here is valid as update_curr() precedes return */
  2373. static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  2374. {
  2375. struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
  2376. s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;
  2377. if (slack_runtime <= 0)
  2378. return;
  2379. raw_spin_lock(&cfs_b->lock);
  2380. if (cfs_b->quota != RUNTIME_INF &&
  2381. cfs_rq->runtime_expires == cfs_b->runtime_expires) {
  2382. cfs_b->runtime += slack_runtime;
  2383. /* we are under rq->lock, defer unthrottling using a timer */
  2384. if (cfs_b->runtime > sched_cfs_bandwidth_slice() &&
  2385. !list_empty(&cfs_b->throttled_cfs_rq))
  2386. start_cfs_slack_bandwidth(cfs_b);
  2387. }
  2388. raw_spin_unlock(&cfs_b->lock);
  2389. /* even if it's not valid for return we don't want to try again */
  2390. cfs_rq->runtime_remaining -= slack_runtime;
  2391. }
  2392. static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  2393. {
  2394. if (!cfs_bandwidth_used())
  2395. return;
  2396. if (!cfs_rq->runtime_enabled || cfs_rq->nr_running)
  2397. return;
  2398. __return_cfs_rq_runtime(cfs_rq);
  2399. }
  2400. /*
  2401. * This is done with a timer (instead of inline with bandwidth return) since
  2402. * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
  2403. */
  2404. static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)
  2405. {
  2406. u64 runtime = 0, slice = sched_cfs_bandwidth_slice();
  2407. u64 expires;
  2408. /* confirm we're still not at a refresh boundary */
  2409. if (runtime_refresh_within(cfs_b, min_bandwidth_expiration))
  2410. return;
  2411. raw_spin_lock(&cfs_b->lock);
  2412. if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice) {
  2413. runtime = cfs_b->runtime;
  2414. cfs_b->runtime = 0;
  2415. }
  2416. expires = cfs_b->runtime_expires;
  2417. raw_spin_unlock(&cfs_b->lock);
  2418. if (!runtime)
  2419. return;
  2420. runtime = distribute_cfs_runtime(cfs_b, runtime, expires);
  2421. raw_spin_lock(&cfs_b->lock);
  2422. if (expires == cfs_b->runtime_expires)
  2423. cfs_b->runtime = runtime;
  2424. raw_spin_unlock(&cfs_b->lock);
  2425. }
  2426. /*
  2427. * When a group wakes up we want to make sure that its quota is not already
  2428. * expired/exceeded, otherwise it may be allowed to steal additional ticks of
  2429. * runtime as update_curr() throttling can not not trigger until it's on-rq.
  2430. */
  2431. static void check_enqueue_throttle(struct cfs_rq *cfs_rq)
  2432. {
  2433. if (!cfs_bandwidth_used())
  2434. return;
  2435. /* an active group must be handled by the update_curr()->put() path */
  2436. if (!cfs_rq->runtime_enabled || cfs_rq->curr)
  2437. return;
  2438. /* ensure the group is not already throttled */
  2439. if (cfs_rq_throttled(cfs_rq))
  2440. return;
  2441. /* update runtime allocation */
  2442. account_cfs_rq_runtime(cfs_rq, 0);
  2443. if (cfs_rq->runtime_remaining <= 0)
  2444. throttle_cfs_rq(cfs_rq);
  2445. }
  2446. /* conditionally throttle active cfs_rq's from put_prev_entity() */
  2447. static void check_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  2448. {
  2449. if (!cfs_bandwidth_used())
  2450. return;
  2451. if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0))
  2452. return;
  2453. /*
  2454. * it's possible for a throttled entity to be forced into a running
  2455. * state (e.g. set_curr_task), in this case we're finished.
  2456. */
  2457. if (cfs_rq_throttled(cfs_rq))
  2458. return;
  2459. throttle_cfs_rq(cfs_rq);
  2460. }
  2461. static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer)
  2462. {
  2463. struct cfs_bandwidth *cfs_b =
  2464. container_of(timer, struct cfs_bandwidth, slack_timer);
  2465. do_sched_cfs_slack_timer(cfs_b);
  2466. return HRTIMER_NORESTART;
  2467. }
  2468. static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)
  2469. {
  2470. struct cfs_bandwidth *cfs_b =
  2471. container_of(timer, struct cfs_bandwidth, period_timer);
  2472. ktime_t now;
  2473. int overrun;
  2474. int idle = 0;
  2475. for (;;) {
  2476. now = hrtimer_cb_get_time(timer);
  2477. overrun = hrtimer_forward(timer, now, cfs_b->period);
  2478. if (!overrun)
  2479. break;
  2480. idle = do_sched_cfs_period_timer(cfs_b, overrun);
  2481. }
  2482. return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
  2483. }
  2484. void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
  2485. {
  2486. raw_spin_lock_init(&cfs_b->lock);
  2487. cfs_b->runtime = 0;
  2488. cfs_b->quota = RUNTIME_INF;
  2489. cfs_b->period = ns_to_ktime(default_cfs_period());
  2490. INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq);
  2491. hrtimer_init(&cfs_b->period_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
  2492. cfs_b->period_timer.function = sched_cfs_period_timer;
  2493. hrtimer_init(&cfs_b->slack_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
  2494. cfs_b->slack_timer.function = sched_cfs_slack_timer;
  2495. }
  2496. static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  2497. {
  2498. cfs_rq->runtime_enabled = 0;
  2499. INIT_LIST_HEAD(&cfs_rq->throttled_list);
  2500. }
  2501. /* requires cfs_b->lock, may release to reprogram timer */
  2502. void __start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
  2503. {
  2504. /*
  2505. * The timer may be active because we're trying to set a new bandwidth
  2506. * period or because we're racing with the tear-down path
  2507. * (timer_active==0 becomes visible before the hrtimer call-back
  2508. * terminates). In either case we ensure that it's re-programmed
  2509. */
  2510. while (unlikely(hrtimer_active(&cfs_b->period_timer))) {
  2511. raw_spin_unlock(&cfs_b->lock);
  2512. /* ensure cfs_b->lock is available while we wait */
  2513. hrtimer_cancel(&cfs_b->period_timer);
  2514. raw_spin_lock(&cfs_b->lock);
  2515. /* if someone else restarted the timer then we're done */
  2516. if (cfs_b->timer_active)
  2517. return;
  2518. }
  2519. cfs_b->timer_active = 1;
  2520. start_bandwidth_timer(&cfs_b->period_timer, cfs_b->period);
  2521. }
  2522. static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
  2523. {
  2524. hrtimer_cancel(&cfs_b->period_timer);
  2525. hrtimer_cancel(&cfs_b->slack_timer);
  2526. }
  2527. static void __maybe_unused unthrottle_offline_cfs_rqs(struct rq *rq)
  2528. {
  2529. struct cfs_rq *cfs_rq;
  2530. for_each_leaf_cfs_rq(rq, cfs_rq) {
  2531. struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
  2532. if (!cfs_rq->runtime_enabled)
  2533. continue;
  2534. /*
  2535. * clock_task is not advancing so we just need to make sure
  2536. * there's some valid quota amount
  2537. */
  2538. cfs_rq->runtime_remaining = cfs_b->quota;
  2539. if (cfs_rq_throttled(cfs_rq))
  2540. unthrottle_cfs_rq(cfs_rq);
  2541. }
  2542. }
  2543. #else /* CONFIG_CFS_BANDWIDTH */
  2544. static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq)
  2545. {
  2546. return rq_clock_task(rq_of(cfs_rq));
  2547. }
  2548. static void account_cfs_rq_runtime(struct cfs_rq *cfs_rq,
  2549. unsigned long delta_exec) {}
  2550. static void check_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
  2551. static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {}
  2552. static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
  2553. static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
  2554. {
  2555. return 0;
  2556. }
  2557. static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
  2558. {
  2559. return 0;
  2560. }
  2561. static inline int throttled_lb_pair(struct task_group *tg,
  2562. int src_cpu, int dest_cpu)
  2563. {
  2564. return 0;
  2565. }
  2566. void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
  2567. #ifdef CONFIG_FAIR_GROUP_SCHED
  2568. static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
  2569. #endif
  2570. static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
  2571. {
  2572. return NULL;
  2573. }
  2574. static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
  2575. static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {}
  2576. #endif /* CONFIG_CFS_BANDWIDTH */
  2577. /**************************************************
  2578. * CFS operations on tasks:
  2579. */
  2580. #ifdef CONFIG_SCHED_HRTICK
  2581. static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
  2582. {
  2583. struct sched_entity *se = &p->se;
  2584. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  2585. WARN_ON(task_rq(p) != rq);
  2586. if (cfs_rq->nr_running > 1) {
  2587. u64 slice = sched_slice(cfs_rq, se);
  2588. u64 ran = se->sum_exec_runtime - se->prev_sum_exec_runtime;
  2589. s64 delta = slice - ran;
  2590. if (delta < 0) {
  2591. if (rq->curr == p)
  2592. resched_task(p);
  2593. return;
  2594. }
  2595. /*
  2596. * Don't schedule slices shorter than 10000ns, that just
  2597. * doesn't make sense. Rely on vruntime for fairness.
  2598. */
  2599. if (rq->curr != p)
  2600. delta = max_t(s64, 10000LL, delta);
  2601. hrtick_start(rq, delta);
  2602. }
  2603. }
  2604. /*
  2605. * called from enqueue/dequeue and updates the hrtick when the
  2606. * current task is from our class and nr_running is low enough
  2607. * to matter.
  2608. */
  2609. static void hrtick_update(struct rq *rq)
  2610. {
  2611. struct task_struct *curr = rq->curr;
  2612. if (!hrtick_enabled(rq) || curr->sched_class != &fair_sched_class)
  2613. return;
  2614. if (cfs_rq_of(&curr->se)->nr_running < sched_nr_latency)
  2615. hrtick_start_fair(rq, curr);
  2616. }
  2617. #else /* !CONFIG_SCHED_HRTICK */
  2618. static inline void
  2619. hrtick_start_fair(struct rq *rq, struct task_struct *p)
  2620. {
  2621. }
  2622. static inline void hrtick_update(struct rq *rq)
  2623. {
  2624. }
  2625. #endif
  2626. /*
  2627. * The enqueue_task method is called before nr_running is
  2628. * increased. Here we update the fair scheduling stats and
  2629. * then put the task into the rbtree:
  2630. */
  2631. static void
  2632. enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
  2633. {
  2634. struct cfs_rq *cfs_rq;
  2635. struct sched_entity *se = &p->se;
  2636. for_each_sched_entity(se) {
  2637. if (se->on_rq)
  2638. break;
  2639. cfs_rq = cfs_rq_of(se);
  2640. enqueue_entity(cfs_rq, se, flags);
  2641. /*
  2642. * end evaluation on encountering a throttled cfs_rq
  2643. *
  2644. * note: in the case of encountering a throttled cfs_rq we will
  2645. * post the final h_nr_running increment below.
  2646. */
  2647. if (cfs_rq_throttled(cfs_rq))
  2648. break;
  2649. cfs_rq->h_nr_running++;
  2650. flags = ENQUEUE_WAKEUP;
  2651. }
  2652. for_each_sched_entity(se) {
  2653. cfs_rq = cfs_rq_of(se);
  2654. cfs_rq->h_nr_running++;
  2655. if (cfs_rq_throttled(cfs_rq))
  2656. break;
  2657. update_cfs_shares(cfs_rq);
  2658. update_entity_load_avg(se, 1);
  2659. }
  2660. if (!se) {
  2661. update_rq_runnable_avg(rq, rq->nr_running);
  2662. inc_nr_running(rq);
  2663. }
  2664. hrtick_update(rq);
  2665. }
  2666. static void set_next_buddy(struct sched_entity *se);
  2667. /*
  2668. * The dequeue_task method is called before nr_running is
  2669. * decreased. We remove the task from the rbtree and
  2670. * update the fair scheduling stats:
  2671. */
  2672. static void dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
  2673. {
  2674. struct cfs_rq *cfs_rq;
  2675. struct sched_entity *se = &p->se;
  2676. int task_sleep = flags & DEQUEUE_SLEEP;
  2677. for_each_sched_entity(se) {
  2678. cfs_rq = cfs_rq_of(se);
  2679. dequeue_entity(cfs_rq, se, flags);
  2680. /*
  2681. * end evaluation on encountering a throttled cfs_rq
  2682. *
  2683. * note: in the case of encountering a throttled cfs_rq we will
  2684. * post the final h_nr_running decrement below.
  2685. */
  2686. if (cfs_rq_throttled(cfs_rq))
  2687. break;
  2688. cfs_rq->h_nr_running--;
  2689. /* Don't dequeue parent if it has other entities besides us */
  2690. if (cfs_rq->load.weight) {
  2691. /*
  2692. * Bias pick_next to pick a task from this cfs_rq, as
  2693. * p is sleeping when it is within its sched_slice.
  2694. */
  2695. if (task_sleep && parent_entity(se))
  2696. set_next_buddy(parent_entity(se));
  2697. /* avoid re-evaluating load for this entity */
  2698. se = parent_entity(se);
  2699. break;
  2700. }
  2701. flags |= DEQUEUE_SLEEP;
  2702. }
  2703. for_each_sched_entity(se) {
  2704. cfs_rq = cfs_rq_of(se);
  2705. cfs_rq->h_nr_running--;
  2706. if (cfs_rq_throttled(cfs_rq))
  2707. break;
  2708. update_cfs_shares(cfs_rq);
  2709. update_entity_load_avg(se, 1);
  2710. }
  2711. if (!se) {
  2712. dec_nr_running(rq);
  2713. update_rq_runnable_avg(rq, 1);
  2714. }
  2715. hrtick_update(rq);
  2716. }
  2717. #ifdef CONFIG_SMP
  2718. /* Used instead of source_load when we know the type == 0 */
  2719. static unsigned long weighted_cpuload(const int cpu)
  2720. {
  2721. return cpu_rq(cpu)->cfs.runnable_load_avg;
  2722. }
  2723. /*
  2724. * Return a low guess at the load of a migration-source cpu weighted
  2725. * according to the scheduling class and "nice" value.
  2726. *
  2727. * We want to under-estimate the load of migration sources, to
  2728. * balance conservatively.
  2729. */
  2730. static unsigned long source_load(int cpu, int type)
  2731. {
  2732. struct rq *rq = cpu_rq(cpu);
  2733. unsigned long total = weighted_cpuload(cpu);
  2734. if (type == 0 || !sched_feat(LB_BIAS))
  2735. return total;
  2736. return min(rq->cpu_load[type-1], total);
  2737. }
  2738. /*
  2739. * Return a high guess at the load of a migration-target cpu weighted
  2740. * according to the scheduling class and "nice" value.
  2741. */
  2742. static unsigned long target_load(int cpu, int type)
  2743. {
  2744. struct rq *rq = cpu_rq(cpu);
  2745. unsigned long total = weighted_cpuload(cpu);
  2746. if (type == 0 || !sched_feat(LB_BIAS))
  2747. return total;
  2748. return max(rq->cpu_load[type-1], total);
  2749. }
  2750. static unsigned long power_of(int cpu)
  2751. {
  2752. return cpu_rq(cpu)->cpu_power;
  2753. }
  2754. static unsigned long cpu_avg_load_per_task(int cpu)
  2755. {
  2756. struct rq *rq = cpu_rq(cpu);
  2757. unsigned long nr_running = ACCESS_ONCE(rq->nr_running);
  2758. unsigned long load_avg = rq->cfs.runnable_load_avg;
  2759. if (nr_running)
  2760. return load_avg / nr_running;
  2761. return 0;
  2762. }
  2763. static void record_wakee(struct task_struct *p)
  2764. {
  2765. /*
  2766. * Rough decay (wiping) for cost saving, don't worry
  2767. * about the boundary, really active task won't care
  2768. * about the loss.
  2769. */
  2770. if (jiffies > current->wakee_flip_decay_ts + HZ) {
  2771. current->wakee_flips = 0;
  2772. current->wakee_flip_decay_ts = jiffies;
  2773. }
  2774. if (current->last_wakee != p) {
  2775. current->last_wakee = p;
  2776. current->wakee_flips++;
  2777. }
  2778. }
  2779. static void task_waking_fair(struct task_struct *p)
  2780. {
  2781. struct sched_entity *se = &p->se;
  2782. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  2783. u64 min_vruntime;
  2784. #ifndef CONFIG_64BIT
  2785. u64 min_vruntime_copy;
  2786. do {
  2787. min_vruntime_copy = cfs_rq->min_vruntime_copy;
  2788. smp_rmb();
  2789. min_vruntime = cfs_rq->min_vruntime;
  2790. } while (min_vruntime != min_vruntime_copy);
  2791. #else
  2792. min_vruntime = cfs_rq->min_vruntime;
  2793. #endif
  2794. se->vruntime -= min_vruntime;
  2795. record_wakee(p);
  2796. }
  2797. #ifdef CONFIG_FAIR_GROUP_SCHED
  2798. /*
  2799. * effective_load() calculates the load change as seen from the root_task_group
  2800. *
  2801. * Adding load to a group doesn't make a group heavier, but can cause movement
  2802. * of group shares between cpus. Assuming the shares were perfectly aligned one
  2803. * can calculate the shift in shares.
  2804. *
  2805. * Calculate the effective load difference if @wl is added (subtracted) to @tg
  2806. * on this @cpu and results in a total addition (subtraction) of @wg to the
  2807. * total group weight.
  2808. *
  2809. * Given a runqueue weight distribution (rw_i) we can compute a shares
  2810. * distribution (s_i) using:
  2811. *
  2812. * s_i = rw_i / \Sum rw_j (1)
  2813. *
  2814. * Suppose we have 4 CPUs and our @tg is a direct child of the root group and
  2815. * has 7 equal weight tasks, distributed as below (rw_i), with the resulting
  2816. * shares distribution (s_i):
  2817. *
  2818. * rw_i = { 2, 4, 1, 0 }
  2819. * s_i = { 2/7, 4/7, 1/7, 0 }
  2820. *
  2821. * As per wake_affine() we're interested in the load of two CPUs (the CPU the
  2822. * task used to run on and the CPU the waker is running on), we need to
  2823. * compute the effect of waking a task on either CPU and, in case of a sync
  2824. * wakeup, compute the effect of the current task going to sleep.
  2825. *
  2826. * So for a change of @wl to the local @cpu with an overall group weight change
  2827. * of @wl we can compute the new shares distribution (s'_i) using:
  2828. *
  2829. * s'_i = (rw_i + @wl) / (@wg + \Sum rw_j) (2)
  2830. *
  2831. * Suppose we're interested in CPUs 0 and 1, and want to compute the load
  2832. * differences in waking a task to CPU 0. The additional task changes the
  2833. * weight and shares distributions like:
  2834. *
  2835. * rw'_i = { 3, 4, 1, 0 }
  2836. * s'_i = { 3/8, 4/8, 1/8, 0 }
  2837. *
  2838. * We can then compute the difference in effective weight by using:
  2839. *
  2840. * dw_i = S * (s'_i - s_i) (3)
  2841. *
  2842. * Where 'S' is the group weight as seen by its parent.
  2843. *
  2844. * Therefore the effective change in loads on CPU 0 would be 5/56 (3/8 - 2/7)
  2845. * times the weight of the group. The effect on CPU 1 would be -4/56 (4/8 -
  2846. * 4/7) times the weight of the group.
  2847. */
  2848. static long effective_load(struct task_group *tg, int cpu, long wl, long wg)
  2849. {
  2850. struct sched_entity *se = tg->se[cpu];
  2851. if (!tg->parent || !wl) /* the trivial, non-cgroup case */
  2852. return wl;
  2853. for_each_sched_entity(se) {
  2854. long w, W;
  2855. tg = se->my_q->tg;
  2856. /*
  2857. * W = @wg + \Sum rw_j
  2858. */
  2859. W = wg + calc_tg_weight(tg, se->my_q);
  2860. /*
  2861. * w = rw_i + @wl
  2862. */
  2863. w = se->my_q->load.weight + wl;
  2864. /*
  2865. * wl = S * s'_i; see (2)
  2866. */
  2867. if (W > 0 && w < W)
  2868. wl = (w * tg->shares) / W;
  2869. else
  2870. wl = tg->shares;
  2871. /*
  2872. * Per the above, wl is the new se->load.weight value; since
  2873. * those are clipped to [MIN_SHARES, ...) do so now. See
  2874. * calc_cfs_shares().
  2875. */
  2876. if (wl < MIN_SHARES)
  2877. wl = MIN_SHARES;
  2878. /*
  2879. * wl = dw_i = S * (s'_i - s_i); see (3)
  2880. */
  2881. wl -= se->load.weight;
  2882. /*
  2883. * Recursively apply this logic to all parent groups to compute
  2884. * the final effective load change on the root group. Since
  2885. * only the @tg group gets extra weight, all parent groups can
  2886. * only redistribute existing shares. @wl is the shift in shares
  2887. * resulting from this level per the above.
  2888. */
  2889. wg = 0;
  2890. }
  2891. return wl;
  2892. }
  2893. #else
  2894. static long effective_load(struct task_group *tg, int cpu, long wl, long wg)
  2895. {
  2896. return wl;
  2897. }
  2898. #endif
  2899. static int wake_wide(struct task_struct *p)
  2900. {
  2901. int factor = this_cpu_read(sd_llc_size);
  2902. /*
  2903. * Yeah, it's the switching-frequency, could means many wakee or
  2904. * rapidly switch, use factor here will just help to automatically
  2905. * adjust the loose-degree, so bigger node will lead to more pull.
  2906. */
  2907. if (p->wakee_flips > factor) {
  2908. /*
  2909. * wakee is somewhat hot, it needs certain amount of cpu
  2910. * resource, so if waker is far more hot, prefer to leave
  2911. * it alone.
  2912. */
  2913. if (current->wakee_flips > (factor * p->wakee_flips))
  2914. return 1;
  2915. }
  2916. return 0;
  2917. }
  2918. static int wake_affine(struct sched_domain *sd, struct task_struct *p, int sync)
  2919. {
  2920. s64 this_load, load;
  2921. int idx, this_cpu, prev_cpu;
  2922. unsigned long tl_per_task;
  2923. struct task_group *tg;
  2924. unsigned long weight;
  2925. int balanced;
  2926. /*
  2927. * If we wake multiple tasks be careful to not bounce
  2928. * ourselves around too much.
  2929. */
  2930. if (wake_wide(p))
  2931. return 0;
  2932. idx = sd->wake_idx;
  2933. this_cpu = smp_processor_id();
  2934. prev_cpu = task_cpu(p);
  2935. load = source_load(prev_cpu, idx);
  2936. this_load = target_load(this_cpu, idx);
  2937. /*
  2938. * If sync wakeup then subtract the (maximum possible)
  2939. * effect of the currently running task from the load
  2940. * of the current CPU:
  2941. */
  2942. if (sync) {
  2943. tg = task_group(current);
  2944. weight = current->se.load.weight;
  2945. this_load += effective_load(tg, this_cpu, -weight, -weight);
  2946. load += effective_load(tg, prev_cpu, 0, -weight);
  2947. }
  2948. tg = task_group(p);
  2949. weight = p->se.load.weight;
  2950. /*
  2951. * In low-load situations, where prev_cpu is idle and this_cpu is idle
  2952. * due to the sync cause above having dropped this_load to 0, we'll
  2953. * always have an imbalance, but there's really nothing you can do
  2954. * about that, so that's good too.
  2955. *
  2956. * Otherwise check if either cpus are near enough in load to allow this
  2957. * task to be woken on this_cpu.
  2958. */
  2959. if (this_load > 0) {
  2960. s64 this_eff_load, prev_eff_load;
  2961. this_eff_load = 100;
  2962. this_eff_load *= power_of(prev_cpu);
  2963. this_eff_load *= this_load +
  2964. effective_load(tg, this_cpu, weight, weight);
  2965. prev_eff_load = 100 + (sd->imbalance_pct - 100) / 2;
  2966. prev_eff_load *= power_of(this_cpu);
  2967. prev_eff_load *= load + effective_load(tg, prev_cpu, 0, weight);
  2968. balanced = this_eff_load <= prev_eff_load;
  2969. } else
  2970. balanced = true;
  2971. /*
  2972. * If the currently running task will sleep within
  2973. * a reasonable amount of time then attract this newly
  2974. * woken task:
  2975. */
  2976. if (sync && balanced)
  2977. return 1;
  2978. schedstat_inc(p, se.statistics.nr_wakeups_affine_attempts);
  2979. tl_per_task = cpu_avg_load_per_task(this_cpu);
  2980. if (balanced ||
  2981. (this_load <= load &&
  2982. this_load + target_load(prev_cpu, idx) <= tl_per_task)) {
  2983. /*
  2984. * This domain has SD_WAKE_AFFINE and
  2985. * p is cache cold in this domain, and
  2986. * there is no bad imbalance.
  2987. */
  2988. schedstat_inc(sd, ttwu_move_affine);
  2989. schedstat_inc(p, se.statistics.nr_wakeups_affine);
  2990. return 1;
  2991. }
  2992. return 0;
  2993. }
  2994. /*
  2995. * find_idlest_group finds and returns the least busy CPU group within the
  2996. * domain.
  2997. */
  2998. static struct sched_group *
  2999. find_idlest_group(struct sched_domain *sd, struct task_struct *p,
  3000. int this_cpu, int load_idx)
  3001. {
  3002. struct sched_group *idlest = NULL, *group = sd->groups;
  3003. unsigned long min_load = ULONG_MAX, this_load = 0;
  3004. int imbalance = 100 + (sd->imbalance_pct-100)/2;
  3005. do {
  3006. unsigned long load, avg_load;
  3007. int local_group;
  3008. int i;
  3009. /* Skip over this group if it has no CPUs allowed */
  3010. if (!cpumask_intersects(sched_group_cpus(group),
  3011. tsk_cpus_allowed(p)))
  3012. continue;
  3013. local_group = cpumask_test_cpu(this_cpu,
  3014. sched_group_cpus(group));
  3015. /* Tally up the load of all CPUs in the group */
  3016. avg_load = 0;
  3017. for_each_cpu(i, sched_group_cpus(group)) {
  3018. /* Bias balancing toward cpus of our domain */
  3019. if (local_group)
  3020. load = source_load(i, load_idx);
  3021. else
  3022. load = target_load(i, load_idx);
  3023. avg_load += load;
  3024. }
  3025. /* Adjust by relative CPU power of the group */
  3026. avg_load = (avg_load * SCHED_POWER_SCALE) / group->sgp->power;
  3027. if (local_group) {
  3028. this_load = avg_load;
  3029. } else if (avg_load < min_load) {
  3030. min_load = avg_load;
  3031. idlest = group;
  3032. }
  3033. } while (group = group->next, group != sd->groups);
  3034. if (!idlest || 100*this_load < imbalance*min_load)
  3035. return NULL;
  3036. return idlest;
  3037. }
  3038. /*
  3039. * find_idlest_cpu - find the idlest cpu among the cpus in group.
  3040. */
  3041. static int
  3042. find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
  3043. {
  3044. unsigned long load, min_load = ULONG_MAX;
  3045. int idlest = -1;
  3046. int i;
  3047. /* Traverse only the allowed CPUs */
  3048. for_each_cpu_and(i, sched_group_cpus(group), tsk_cpus_allowed(p)) {
  3049. load = weighted_cpuload(i);
  3050. if (load < min_load || (load == min_load && i == this_cpu)) {
  3051. min_load = load;
  3052. idlest = i;
  3053. }
  3054. }
  3055. return idlest;
  3056. }
  3057. /*
  3058. * Try and locate an idle CPU in the sched_domain.
  3059. */
  3060. static int select_idle_sibling(struct task_struct *p, int target)
  3061. {
  3062. struct sched_domain *sd;
  3063. struct sched_group *sg;
  3064. int i = task_cpu(p);
  3065. if (idle_cpu(target))
  3066. return target;
  3067. /*
  3068. * If the prevous cpu is cache affine and idle, don't be stupid.
  3069. */
  3070. if (i != target && cpus_share_cache(i, target) && idle_cpu(i))
  3071. return i;
  3072. /*
  3073. * Otherwise, iterate the domains and find an elegible idle cpu.
  3074. */
  3075. sd = rcu_dereference(per_cpu(sd_llc, target));
  3076. for_each_lower_domain(sd) {
  3077. sg = sd->groups;
  3078. do {
  3079. if (!cpumask_intersects(sched_group_cpus(sg),
  3080. tsk_cpus_allowed(p)))
  3081. goto next;
  3082. for_each_cpu(i, sched_group_cpus(sg)) {
  3083. if (i == target || !idle_cpu(i))
  3084. goto next;
  3085. }
  3086. target = cpumask_first_and(sched_group_cpus(sg),
  3087. tsk_cpus_allowed(p));
  3088. goto done;
  3089. next:
  3090. sg = sg->next;
  3091. } while (sg != sd->groups);
  3092. }
  3093. done:
  3094. return target;
  3095. }
  3096. /*
  3097. * sched_balance_self: balance the current task (running on cpu) in domains
  3098. * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
  3099. * SD_BALANCE_EXEC.
  3100. *
  3101. * Balance, ie. select the least loaded group.
  3102. *
  3103. * Returns the target CPU number, or the same CPU if no balancing is needed.
  3104. *
  3105. * preempt must be disabled.
  3106. */
  3107. static int
  3108. select_task_rq_fair(struct task_struct *p, int sd_flag, int wake_flags)
  3109. {
  3110. struct sched_domain *tmp, *affine_sd = NULL, *sd = NULL;
  3111. int cpu = smp_processor_id();
  3112. int prev_cpu = task_cpu(p);
  3113. int new_cpu = cpu;
  3114. int want_affine = 0;
  3115. int sync = wake_flags & WF_SYNC;
  3116. if (p->nr_cpus_allowed == 1)
  3117. return prev_cpu;
  3118. if (sd_flag & SD_BALANCE_WAKE) {
  3119. if (cpumask_test_cpu(cpu, tsk_cpus_allowed(p)))
  3120. want_affine = 1;
  3121. new_cpu = prev_cpu;
  3122. }
  3123. rcu_read_lock();
  3124. for_each_domain(cpu, tmp) {
  3125. if (!(tmp->flags & SD_LOAD_BALANCE))
  3126. continue;
  3127. /*
  3128. * If both cpu and prev_cpu are part of this domain,
  3129. * cpu is a valid SD_WAKE_AFFINE target.
  3130. */
  3131. if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
  3132. cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
  3133. affine_sd = tmp;
  3134. break;
  3135. }
  3136. if (tmp->flags & sd_flag)
  3137. sd = tmp;
  3138. }
  3139. if (affine_sd) {
  3140. if (cpu != prev_cpu && wake_affine(affine_sd, p, sync))
  3141. prev_cpu = cpu;
  3142. new_cpu = select_idle_sibling(p, prev_cpu);
  3143. goto unlock;
  3144. }
  3145. while (sd) {
  3146. int load_idx = sd->forkexec_idx;
  3147. struct sched_group *group;
  3148. int weight;
  3149. if (!(sd->flags & sd_flag)) {
  3150. sd = sd->child;
  3151. continue;
  3152. }
  3153. if (sd_flag & SD_BALANCE_WAKE)
  3154. load_idx = sd->wake_idx;
  3155. group = find_idlest_group(sd, p, cpu, load_idx);
  3156. if (!group) {
  3157. sd = sd->child;
  3158. continue;
  3159. }
  3160. new_cpu = find_idlest_cpu(group, p, cpu);
  3161. if (new_cpu == -1 || new_cpu == cpu) {
  3162. /* Now try balancing at a lower domain level of cpu */
  3163. sd = sd->child;
  3164. continue;
  3165. }
  3166. /* Now try balancing at a lower domain level of new_cpu */
  3167. cpu = new_cpu;
  3168. weight = sd->span_weight;
  3169. sd = NULL;
  3170. for_each_domain(cpu, tmp) {
  3171. if (weight <= tmp->span_weight)
  3172. break;
  3173. if (tmp->flags & sd_flag)
  3174. sd = tmp;
  3175. }
  3176. /* while loop will break here if sd == NULL */
  3177. }
  3178. unlock:
  3179. rcu_read_unlock();
  3180. return new_cpu;
  3181. }
  3182. /*
  3183. * Called immediately before a task is migrated to a new cpu; task_cpu(p) and
  3184. * cfs_rq_of(p) references at time of call are still valid and identify the
  3185. * previous cpu. However, the caller only guarantees p->pi_lock is held; no
  3186. * other assumptions, including the state of rq->lock, should be made.
  3187. */
  3188. static void
  3189. migrate_task_rq_fair(struct task_struct *p, int next_cpu)
  3190. {
  3191. struct sched_entity *se = &p->se;
  3192. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  3193. /*
  3194. * Load tracking: accumulate removed load so that it can be processed
  3195. * when we next update owning cfs_rq under rq->lock. Tasks contribute
  3196. * to blocked load iff they have a positive decay-count. It can never
  3197. * be negative here since on-rq tasks have decay-count == 0.
  3198. */
  3199. if (se->avg.decay_count) {
  3200. se->avg.decay_count = -__synchronize_entity_decay(se);
  3201. atomic_long_add(se->avg.load_avg_contrib,
  3202. &cfs_rq->removed_load);
  3203. }
  3204. }
  3205. #endif /* CONFIG_SMP */
  3206. static unsigned long
  3207. wakeup_gran(struct sched_entity *curr, struct sched_entity *se)
  3208. {
  3209. unsigned long gran = sysctl_sched_wakeup_granularity;
  3210. /*
  3211. * Since its curr running now, convert the gran from real-time
  3212. * to virtual-time in his units.
  3213. *
  3214. * By using 'se' instead of 'curr' we penalize light tasks, so
  3215. * they get preempted easier. That is, if 'se' < 'curr' then
  3216. * the resulting gran will be larger, therefore penalizing the
  3217. * lighter, if otoh 'se' > 'curr' then the resulting gran will
  3218. * be smaller, again penalizing the lighter task.
  3219. *
  3220. * This is especially important for buddies when the leftmost
  3221. * task is higher priority than the buddy.
  3222. */
  3223. return calc_delta_fair(gran, se);
  3224. }
  3225. /*
  3226. * Should 'se' preempt 'curr'.
  3227. *
  3228. * |s1
  3229. * |s2
  3230. * |s3
  3231. * g
  3232. * |<--->|c
  3233. *
  3234. * w(c, s1) = -1
  3235. * w(c, s2) = 0
  3236. * w(c, s3) = 1
  3237. *
  3238. */
  3239. static int
  3240. wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se)
  3241. {
  3242. s64 gran, vdiff = curr->vruntime - se->vruntime;
  3243. if (vdiff <= 0)
  3244. return -1;
  3245. gran = wakeup_gran(curr, se);
  3246. if (vdiff > gran)
  3247. return 1;
  3248. return 0;
  3249. }
  3250. static void set_last_buddy(struct sched_entity *se)
  3251. {
  3252. if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE))
  3253. return;
  3254. for_each_sched_entity(se)
  3255. cfs_rq_of(se)->last = se;
  3256. }
  3257. static void set_next_buddy(struct sched_entity *se)
  3258. {
  3259. if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE))
  3260. return;
  3261. for_each_sched_entity(se)
  3262. cfs_rq_of(se)->next = se;
  3263. }
  3264. static void set_skip_buddy(struct sched_entity *se)
  3265. {
  3266. for_each_sched_entity(se)
  3267. cfs_rq_of(se)->skip = se;
  3268. }
  3269. /*
  3270. * Preempt the current task with a newly woken task if needed:
  3271. */
  3272. static void check_preempt_wakeup(struct rq *rq, struct task_struct *p, int wake_flags)
  3273. {
  3274. struct task_struct *curr = rq->curr;
  3275. struct sched_entity *se = &curr->se, *pse = &p->se;
  3276. struct cfs_rq *cfs_rq = task_cfs_rq(curr);
  3277. int scale = cfs_rq->nr_running >= sched_nr_latency;
  3278. int next_buddy_marked = 0;
  3279. if (unlikely(se == pse))
  3280. return;
  3281. /*
  3282. * This is possible from callers such as move_task(), in which we
  3283. * unconditionally check_prempt_curr() after an enqueue (which may have
  3284. * lead to a throttle). This both saves work and prevents false
  3285. * next-buddy nomination below.
  3286. */
  3287. if (unlikely(throttled_hierarchy(cfs_rq_of(pse))))
  3288. return;
  3289. if (sched_feat(NEXT_BUDDY) && scale && !(wake_flags & WF_FORK)) {
  3290. set_next_buddy(pse);
  3291. next_buddy_marked = 1;
  3292. }
  3293. /*
  3294. * We can come here with TIF_NEED_RESCHED already set from new task
  3295. * wake up path.
  3296. *
  3297. * Note: this also catches the edge-case of curr being in a throttled
  3298. * group (e.g. via set_curr_task), since update_curr() (in the
  3299. * enqueue of curr) will have resulted in resched being set. This
  3300. * prevents us from potentially nominating it as a false LAST_BUDDY
  3301. * below.
  3302. */
  3303. if (test_tsk_need_resched(curr))
  3304. return;
  3305. /* Idle tasks are by definition preempted by non-idle tasks. */
  3306. if (unlikely(curr->policy == SCHED_IDLE) &&
  3307. likely(p->policy != SCHED_IDLE))
  3308. goto preempt;
  3309. /*
  3310. * Batch and idle tasks do not preempt non-idle tasks (their preemption
  3311. * is driven by the tick):
  3312. */
  3313. if (unlikely(p->policy != SCHED_NORMAL) || !sched_feat(WAKEUP_PREEMPTION))
  3314. return;
  3315. find_matching_se(&se, &pse);
  3316. update_curr(cfs_rq_of(se));
  3317. BUG_ON(!pse);
  3318. if (wakeup_preempt_entity(se, pse) == 1) {
  3319. /*
  3320. * Bias pick_next to pick the sched entity that is
  3321. * triggering this preemption.
  3322. */
  3323. if (!next_buddy_marked)
  3324. set_next_buddy(pse);
  3325. goto preempt;
  3326. }
  3327. return;
  3328. preempt:
  3329. resched_task(curr);
  3330. /*
  3331. * Only set the backward buddy when the current task is still
  3332. * on the rq. This can happen when a wakeup gets interleaved
  3333. * with schedule on the ->pre_schedule() or idle_balance()
  3334. * point, either of which can * drop the rq lock.
  3335. *
  3336. * Also, during early boot the idle thread is in the fair class,
  3337. * for obvious reasons its a bad idea to schedule back to it.
  3338. */
  3339. if (unlikely(!se->on_rq || curr == rq->idle))
  3340. return;
  3341. if (sched_feat(LAST_BUDDY) && scale && entity_is_task(se))
  3342. set_last_buddy(se);
  3343. }
  3344. static struct task_struct *pick_next_task_fair(struct rq *rq)
  3345. {
  3346. struct task_struct *p;
  3347. struct cfs_rq *cfs_rq = &rq->cfs;
  3348. struct sched_entity *se;
  3349. if (!cfs_rq->nr_running)
  3350. return NULL;
  3351. do {
  3352. se = pick_next_entity(cfs_rq);
  3353. set_next_entity(cfs_rq, se);
  3354. cfs_rq = group_cfs_rq(se);
  3355. } while (cfs_rq);
  3356. p = task_of(se);
  3357. if (hrtick_enabled(rq))
  3358. hrtick_start_fair(rq, p);
  3359. return p;
  3360. }
  3361. /*
  3362. * Account for a descheduled task:
  3363. */
  3364. static void put_prev_task_fair(struct rq *rq, struct task_struct *prev)
  3365. {
  3366. struct sched_entity *se = &prev->se;
  3367. struct cfs_rq *cfs_rq;
  3368. for_each_sched_entity(se) {
  3369. cfs_rq = cfs_rq_of(se);
  3370. put_prev_entity(cfs_rq, se);
  3371. }
  3372. }
  3373. /*
  3374. * sched_yield() is very simple
  3375. *
  3376. * The magic of dealing with the ->skip buddy is in pick_next_entity.
  3377. */
  3378. static void yield_task_fair(struct rq *rq)
  3379. {
  3380. struct task_struct *curr = rq->curr;
  3381. struct cfs_rq *cfs_rq = task_cfs_rq(curr);
  3382. struct sched_entity *se = &curr->se;
  3383. /*
  3384. * Are we the only task in the tree?
  3385. */
  3386. if (unlikely(rq->nr_running == 1))
  3387. return;
  3388. clear_buddies(cfs_rq, se);
  3389. if (curr->policy != SCHED_BATCH) {
  3390. update_rq_clock(rq);
  3391. /*
  3392. * Update run-time statistics of the 'current'.
  3393. */
  3394. update_curr(cfs_rq);
  3395. /*
  3396. * Tell update_rq_clock() that we've just updated,
  3397. * so we don't do microscopic update in schedule()
  3398. * and double the fastpath cost.
  3399. */
  3400. rq->skip_clock_update = 1;
  3401. }
  3402. set_skip_buddy(se);
  3403. }
  3404. static bool yield_to_task_fair(struct rq *rq, struct task_struct *p, bool preempt)
  3405. {
  3406. struct sched_entity *se = &p->se;
  3407. /* throttled hierarchies are not runnable */
  3408. if (!se->on_rq || throttled_hierarchy(cfs_rq_of(se)))
  3409. return false;
  3410. /* Tell the scheduler that we'd really like pse to run next. */
  3411. set_next_buddy(se);
  3412. yield_task_fair(rq);
  3413. return true;
  3414. }
  3415. #ifdef CONFIG_SMP
  3416. /**************************************************
  3417. * Fair scheduling class load-balancing methods.
  3418. *
  3419. * BASICS
  3420. *
  3421. * The purpose of load-balancing is to achieve the same basic fairness the
  3422. * per-cpu scheduler provides, namely provide a proportional amount of compute
  3423. * time to each task. This is expressed in the following equation:
  3424. *
  3425. * W_i,n/P_i == W_j,n/P_j for all i,j (1)
  3426. *
  3427. * Where W_i,n is the n-th weight average for cpu i. The instantaneous weight
  3428. * W_i,0 is defined as:
  3429. *
  3430. * W_i,0 = \Sum_j w_i,j (2)
  3431. *
  3432. * Where w_i,j is the weight of the j-th runnable task on cpu i. This weight
  3433. * is derived from the nice value as per prio_to_weight[].
  3434. *
  3435. * The weight average is an exponential decay average of the instantaneous
  3436. * weight:
  3437. *
  3438. * W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0 (3)
  3439. *
  3440. * P_i is the cpu power (or compute capacity) of cpu i, typically it is the
  3441. * fraction of 'recent' time available for SCHED_OTHER task execution. But it
  3442. * can also include other factors [XXX].
  3443. *
  3444. * To achieve this balance we define a measure of imbalance which follows
  3445. * directly from (1):
  3446. *
  3447. * imb_i,j = max{ avg(W/P), W_i/P_i } - min{ avg(W/P), W_j/P_j } (4)
  3448. *
  3449. * We them move tasks around to minimize the imbalance. In the continuous
  3450. * function space it is obvious this converges, in the discrete case we get
  3451. * a few fun cases generally called infeasible weight scenarios.
  3452. *
  3453. * [XXX expand on:
  3454. * - infeasible weights;
  3455. * - local vs global optima in the discrete case. ]
  3456. *
  3457. *
  3458. * SCHED DOMAINS
  3459. *
  3460. * In order to solve the imbalance equation (4), and avoid the obvious O(n^2)
  3461. * for all i,j solution, we create a tree of cpus that follows the hardware
  3462. * topology where each level pairs two lower groups (or better). This results
  3463. * in O(log n) layers. Furthermore we reduce the number of cpus going up the
  3464. * tree to only the first of the previous level and we decrease the frequency
  3465. * of load-balance at each level inv. proportional to the number of cpus in
  3466. * the groups.
  3467. *
  3468. * This yields:
  3469. *
  3470. * log_2 n 1 n
  3471. * \Sum { --- * --- * 2^i } = O(n) (5)
  3472. * i = 0 2^i 2^i
  3473. * `- size of each group
  3474. * | | `- number of cpus doing load-balance
  3475. * | `- freq
  3476. * `- sum over all levels
  3477. *
  3478. * Coupled with a limit on how many tasks we can migrate every balance pass,
  3479. * this makes (5) the runtime complexity of the balancer.
  3480. *
  3481. * An important property here is that each CPU is still (indirectly) connected
  3482. * to every other cpu in at most O(log n) steps:
  3483. *
  3484. * The adjacency matrix of the resulting graph is given by:
  3485. *
  3486. * log_2 n
  3487. * A_i,j = \Union (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1) (6)
  3488. * k = 0
  3489. *
  3490. * And you'll find that:
  3491. *
  3492. * A^(log_2 n)_i,j != 0 for all i,j (7)
  3493. *
  3494. * Showing there's indeed a path between every cpu in at most O(log n) steps.
  3495. * The task movement gives a factor of O(m), giving a convergence complexity
  3496. * of:
  3497. *
  3498. * O(nm log n), n := nr_cpus, m := nr_tasks (8)
  3499. *
  3500. *
  3501. * WORK CONSERVING
  3502. *
  3503. * In order to avoid CPUs going idle while there's still work to do, new idle
  3504. * balancing is more aggressive and has the newly idle cpu iterate up the domain
  3505. * tree itself instead of relying on other CPUs to bring it work.
  3506. *
  3507. * This adds some complexity to both (5) and (8) but it reduces the total idle
  3508. * time.
  3509. *
  3510. * [XXX more?]
  3511. *
  3512. *
  3513. * CGROUPS
  3514. *
  3515. * Cgroups make a horror show out of (2), instead of a simple sum we get:
  3516. *
  3517. * s_k,i
  3518. * W_i,0 = \Sum_j \Prod_k w_k * ----- (9)
  3519. * S_k
  3520. *
  3521. * Where
  3522. *
  3523. * s_k,i = \Sum_j w_i,j,k and S_k = \Sum_i s_k,i (10)
  3524. *
  3525. * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on cpu i.
  3526. *
  3527. * The big problem is S_k, its a global sum needed to compute a local (W_i)
  3528. * property.
  3529. *
  3530. * [XXX write more on how we solve this.. _after_ merging pjt's patches that
  3531. * rewrite all of this once again.]
  3532. */
  3533. static unsigned long __read_mostly max_load_balance_interval = HZ/10;
  3534. #define LBF_ALL_PINNED 0x01
  3535. #define LBF_NEED_BREAK 0x02
  3536. #define LBF_DST_PINNED 0x04
  3537. #define LBF_SOME_PINNED 0x08
  3538. struct lb_env {
  3539. struct sched_domain *sd;
  3540. struct rq *src_rq;
  3541. int src_cpu;
  3542. int dst_cpu;
  3543. struct rq *dst_rq;
  3544. struct cpumask *dst_grpmask;
  3545. int new_dst_cpu;
  3546. enum cpu_idle_type idle;
  3547. long imbalance;
  3548. /* The set of CPUs under consideration for load-balancing */
  3549. struct cpumask *cpus;
  3550. unsigned int flags;
  3551. unsigned int loop;
  3552. unsigned int loop_break;
  3553. unsigned int loop_max;
  3554. };
  3555. /*
  3556. * move_task - move a task from one runqueue to another runqueue.
  3557. * Both runqueues must be locked.
  3558. */
  3559. static void move_task(struct task_struct *p, struct lb_env *env)
  3560. {
  3561. deactivate_task(env->src_rq, p, 0);
  3562. set_task_cpu(p, env->dst_cpu);
  3563. activate_task(env->dst_rq, p, 0);
  3564. check_preempt_curr(env->dst_rq, p, 0);
  3565. #ifdef CONFIG_NUMA_BALANCING
  3566. if (p->numa_preferred_nid != -1) {
  3567. int src_nid = cpu_to_node(env->src_cpu);
  3568. int dst_nid = cpu_to_node(env->dst_cpu);
  3569. /*
  3570. * If the load balancer has moved the task then limit
  3571. * migrations from taking place in the short term in
  3572. * case this is a short-lived migration.
  3573. */
  3574. if (src_nid != dst_nid && dst_nid != p->numa_preferred_nid)
  3575. p->numa_migrate_seq = 0;
  3576. }
  3577. #endif
  3578. }
  3579. /*
  3580. * Is this task likely cache-hot:
  3581. */
  3582. static int
  3583. task_hot(struct task_struct *p, u64 now, struct sched_domain *sd)
  3584. {
  3585. s64 delta;
  3586. if (p->sched_class != &fair_sched_class)
  3587. return 0;
  3588. if (unlikely(p->policy == SCHED_IDLE))
  3589. return 0;
  3590. /*
  3591. * Buddy candidates are cache hot:
  3592. */
  3593. if (sched_feat(CACHE_HOT_BUDDY) && this_rq()->nr_running &&
  3594. (&p->se == cfs_rq_of(&p->se)->next ||
  3595. &p->se == cfs_rq_of(&p->se)->last))
  3596. return 1;
  3597. if (sysctl_sched_migration_cost == -1)
  3598. return 1;
  3599. if (sysctl_sched_migration_cost == 0)
  3600. return 0;
  3601. delta = now - p->se.exec_start;
  3602. return delta < (s64)sysctl_sched_migration_cost;
  3603. }
  3604. #ifdef CONFIG_NUMA_BALANCING
  3605. /* Returns true if the destination node has incurred more faults */
  3606. static bool migrate_improves_locality(struct task_struct *p, struct lb_env *env)
  3607. {
  3608. int src_nid, dst_nid;
  3609. if (!sched_feat(NUMA_FAVOUR_HIGHER) || !p->numa_faults ||
  3610. !(env->sd->flags & SD_NUMA)) {
  3611. return false;
  3612. }
  3613. src_nid = cpu_to_node(env->src_cpu);
  3614. dst_nid = cpu_to_node(env->dst_cpu);
  3615. if (src_nid == dst_nid ||
  3616. p->numa_migrate_seq >= sysctl_numa_balancing_settle_count)
  3617. return false;
  3618. if (dst_nid == p->numa_preferred_nid ||
  3619. task_faults(p, dst_nid) > task_faults(p, src_nid))
  3620. return true;
  3621. return false;
  3622. }
  3623. static bool migrate_degrades_locality(struct task_struct *p, struct lb_env *env)
  3624. {
  3625. int src_nid, dst_nid;
  3626. if (!sched_feat(NUMA) || !sched_feat(NUMA_RESIST_LOWER))
  3627. return false;
  3628. if (!p->numa_faults || !(env->sd->flags & SD_NUMA))
  3629. return false;
  3630. src_nid = cpu_to_node(env->src_cpu);
  3631. dst_nid = cpu_to_node(env->dst_cpu);
  3632. if (src_nid == dst_nid ||
  3633. p->numa_migrate_seq >= sysctl_numa_balancing_settle_count)
  3634. return false;
  3635. if (task_faults(p, dst_nid) < task_faults(p, src_nid))
  3636. return true;
  3637. return false;
  3638. }
  3639. #else
  3640. static inline bool migrate_improves_locality(struct task_struct *p,
  3641. struct lb_env *env)
  3642. {
  3643. return false;
  3644. }
  3645. static inline bool migrate_degrades_locality(struct task_struct *p,
  3646. struct lb_env *env)
  3647. {
  3648. return false;
  3649. }
  3650. #endif
  3651. /*
  3652. * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
  3653. */
  3654. static
  3655. int can_migrate_task(struct task_struct *p, struct lb_env *env)
  3656. {
  3657. int tsk_cache_hot = 0;
  3658. /*
  3659. * We do not migrate tasks that are:
  3660. * 1) throttled_lb_pair, or
  3661. * 2) cannot be migrated to this CPU due to cpus_allowed, or
  3662. * 3) running (obviously), or
  3663. * 4) are cache-hot on their current CPU.
  3664. */
  3665. if (throttled_lb_pair(task_group(p), env->src_cpu, env->dst_cpu))
  3666. return 0;
  3667. if (!cpumask_test_cpu(env->dst_cpu, tsk_cpus_allowed(p))) {
  3668. int cpu;
  3669. schedstat_inc(p, se.statistics.nr_failed_migrations_affine);
  3670. env->flags |= LBF_SOME_PINNED;
  3671. /*
  3672. * Remember if this task can be migrated to any other cpu in
  3673. * our sched_group. We may want to revisit it if we couldn't
  3674. * meet load balance goals by pulling other tasks on src_cpu.
  3675. *
  3676. * Also avoid computing new_dst_cpu if we have already computed
  3677. * one in current iteration.
  3678. */
  3679. if (!env->dst_grpmask || (env->flags & LBF_DST_PINNED))
  3680. return 0;
  3681. /* Prevent to re-select dst_cpu via env's cpus */
  3682. for_each_cpu_and(cpu, env->dst_grpmask, env->cpus) {
  3683. if (cpumask_test_cpu(cpu, tsk_cpus_allowed(p))) {
  3684. env->flags |= LBF_DST_PINNED;
  3685. env->new_dst_cpu = cpu;
  3686. break;
  3687. }
  3688. }
  3689. return 0;
  3690. }
  3691. /* Record that we found atleast one task that could run on dst_cpu */
  3692. env->flags &= ~LBF_ALL_PINNED;
  3693. if (task_running(env->src_rq, p)) {
  3694. schedstat_inc(p, se.statistics.nr_failed_migrations_running);
  3695. return 0;
  3696. }
  3697. /*
  3698. * Aggressive migration if:
  3699. * 1) destination numa is preferred
  3700. * 2) task is cache cold, or
  3701. * 3) too many balance attempts have failed.
  3702. */
  3703. tsk_cache_hot = task_hot(p, rq_clock_task(env->src_rq), env->sd);
  3704. if (!tsk_cache_hot)
  3705. tsk_cache_hot = migrate_degrades_locality(p, env);
  3706. if (migrate_improves_locality(p, env)) {
  3707. #ifdef CONFIG_SCHEDSTATS
  3708. if (tsk_cache_hot) {
  3709. schedstat_inc(env->sd, lb_hot_gained[env->idle]);
  3710. schedstat_inc(p, se.statistics.nr_forced_migrations);
  3711. }
  3712. #endif
  3713. return 1;
  3714. }
  3715. if (!tsk_cache_hot ||
  3716. env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
  3717. if (tsk_cache_hot) {
  3718. schedstat_inc(env->sd, lb_hot_gained[env->idle]);
  3719. schedstat_inc(p, se.statistics.nr_forced_migrations);
  3720. }
  3721. return 1;
  3722. }
  3723. schedstat_inc(p, se.statistics.nr_failed_migrations_hot);
  3724. return 0;
  3725. }
  3726. /*
  3727. * move_one_task tries to move exactly one task from busiest to this_rq, as
  3728. * part of active balancing operations within "domain".
  3729. * Returns 1 if successful and 0 otherwise.
  3730. *
  3731. * Called with both runqueues locked.
  3732. */
  3733. static int move_one_task(struct lb_env *env)
  3734. {
  3735. struct task_struct *p, *n;
  3736. list_for_each_entry_safe(p, n, &env->src_rq->cfs_tasks, se.group_node) {
  3737. if (!can_migrate_task(p, env))
  3738. continue;
  3739. move_task(p, env);
  3740. /*
  3741. * Right now, this is only the second place move_task()
  3742. * is called, so we can safely collect move_task()
  3743. * stats here rather than inside move_task().
  3744. */
  3745. schedstat_inc(env->sd, lb_gained[env->idle]);
  3746. return 1;
  3747. }
  3748. return 0;
  3749. }
  3750. static unsigned long task_h_load(struct task_struct *p);
  3751. static const unsigned int sched_nr_migrate_break = 32;
  3752. /*
  3753. * move_tasks tries to move up to imbalance weighted load from busiest to
  3754. * this_rq, as part of a balancing operation within domain "sd".
  3755. * Returns 1 if successful and 0 otherwise.
  3756. *
  3757. * Called with both runqueues locked.
  3758. */
  3759. static int move_tasks(struct lb_env *env)
  3760. {
  3761. struct list_head *tasks = &env->src_rq->cfs_tasks;
  3762. struct task_struct *p;
  3763. unsigned long load;
  3764. int pulled = 0;
  3765. if (env->imbalance <= 0)
  3766. return 0;
  3767. while (!list_empty(tasks)) {
  3768. p = list_first_entry(tasks, struct task_struct, se.group_node);
  3769. env->loop++;
  3770. /* We've more or less seen every task there is, call it quits */
  3771. if (env->loop > env->loop_max)
  3772. break;
  3773. /* take a breather every nr_migrate tasks */
  3774. if (env->loop > env->loop_break) {
  3775. env->loop_break += sched_nr_migrate_break;
  3776. env->flags |= LBF_NEED_BREAK;
  3777. break;
  3778. }
  3779. if (!can_migrate_task(p, env))
  3780. goto next;
  3781. load = task_h_load(p);
  3782. if (sched_feat(LB_MIN) && load < 16 && !env->sd->nr_balance_failed)
  3783. goto next;
  3784. if ((load / 2) > env->imbalance)
  3785. goto next;
  3786. move_task(p, env);
  3787. pulled++;
  3788. env->imbalance -= load;
  3789. #ifdef CONFIG_PREEMPT
  3790. /*
  3791. * NEWIDLE balancing is a source of latency, so preemptible
  3792. * kernels will stop after the first task is pulled to minimize
  3793. * the critical section.
  3794. */
  3795. if (env->idle == CPU_NEWLY_IDLE)
  3796. break;
  3797. #endif
  3798. /*
  3799. * We only want to steal up to the prescribed amount of
  3800. * weighted load.
  3801. */
  3802. if (env->imbalance <= 0)
  3803. break;
  3804. continue;
  3805. next:
  3806. list_move_tail(&p->se.group_node, tasks);
  3807. }
  3808. /*
  3809. * Right now, this is one of only two places move_task() is called,
  3810. * so we can safely collect move_task() stats here rather than
  3811. * inside move_task().
  3812. */
  3813. schedstat_add(env->sd, lb_gained[env->idle], pulled);
  3814. return pulled;
  3815. }
  3816. #ifdef CONFIG_FAIR_GROUP_SCHED
  3817. /*
  3818. * update tg->load_weight by folding this cpu's load_avg
  3819. */
  3820. static void __update_blocked_averages_cpu(struct task_group *tg, int cpu)
  3821. {
  3822. struct sched_entity *se = tg->se[cpu];
  3823. struct cfs_rq *cfs_rq = tg->cfs_rq[cpu];
  3824. /* throttled entities do not contribute to load */
  3825. if (throttled_hierarchy(cfs_rq))
  3826. return;
  3827. update_cfs_rq_blocked_load(cfs_rq, 1);
  3828. if (se) {
  3829. update_entity_load_avg(se, 1);
  3830. /*
  3831. * We pivot on our runnable average having decayed to zero for
  3832. * list removal. This generally implies that all our children
  3833. * have also been removed (modulo rounding error or bandwidth
  3834. * control); however, such cases are rare and we can fix these
  3835. * at enqueue.
  3836. *
  3837. * TODO: fix up out-of-order children on enqueue.
  3838. */
  3839. if (!se->avg.runnable_avg_sum && !cfs_rq->nr_running)
  3840. list_del_leaf_cfs_rq(cfs_rq);
  3841. } else {
  3842. struct rq *rq = rq_of(cfs_rq);
  3843. update_rq_runnable_avg(rq, rq->nr_running);
  3844. }
  3845. }
  3846. static void update_blocked_averages(int cpu)
  3847. {
  3848. struct rq *rq = cpu_rq(cpu);
  3849. struct cfs_rq *cfs_rq;
  3850. unsigned long flags;
  3851. raw_spin_lock_irqsave(&rq->lock, flags);
  3852. update_rq_clock(rq);
  3853. /*
  3854. * Iterates the task_group tree in a bottom up fashion, see
  3855. * list_add_leaf_cfs_rq() for details.
  3856. */
  3857. for_each_leaf_cfs_rq(rq, cfs_rq) {
  3858. /*
  3859. * Note: We may want to consider periodically releasing
  3860. * rq->lock about these updates so that creating many task
  3861. * groups does not result in continually extending hold time.
  3862. */
  3863. __update_blocked_averages_cpu(cfs_rq->tg, rq->cpu);
  3864. }
  3865. raw_spin_unlock_irqrestore(&rq->lock, flags);
  3866. }
  3867. /*
  3868. * Compute the hierarchical load factor for cfs_rq and all its ascendants.
  3869. * This needs to be done in a top-down fashion because the load of a child
  3870. * group is a fraction of its parents load.
  3871. */
  3872. static void update_cfs_rq_h_load(struct cfs_rq *cfs_rq)
  3873. {
  3874. struct rq *rq = rq_of(cfs_rq);
  3875. struct sched_entity *se = cfs_rq->tg->se[cpu_of(rq)];
  3876. unsigned long now = jiffies;
  3877. unsigned long load;
  3878. if (cfs_rq->last_h_load_update == now)
  3879. return;
  3880. cfs_rq->h_load_next = NULL;
  3881. for_each_sched_entity(se) {
  3882. cfs_rq = cfs_rq_of(se);
  3883. cfs_rq->h_load_next = se;
  3884. if (cfs_rq->last_h_load_update == now)
  3885. break;
  3886. }
  3887. if (!se) {
  3888. cfs_rq->h_load = cfs_rq->runnable_load_avg;
  3889. cfs_rq->last_h_load_update = now;
  3890. }
  3891. while ((se = cfs_rq->h_load_next) != NULL) {
  3892. load = cfs_rq->h_load;
  3893. load = div64_ul(load * se->avg.load_avg_contrib,
  3894. cfs_rq->runnable_load_avg + 1);
  3895. cfs_rq = group_cfs_rq(se);
  3896. cfs_rq->h_load = load;
  3897. cfs_rq->last_h_load_update = now;
  3898. }
  3899. }
  3900. static unsigned long task_h_load(struct task_struct *p)
  3901. {
  3902. struct cfs_rq *cfs_rq = task_cfs_rq(p);
  3903. update_cfs_rq_h_load(cfs_rq);
  3904. return div64_ul(p->se.avg.load_avg_contrib * cfs_rq->h_load,
  3905. cfs_rq->runnable_load_avg + 1);
  3906. }
  3907. #else
  3908. static inline void update_blocked_averages(int cpu)
  3909. {
  3910. }
  3911. static unsigned long task_h_load(struct task_struct *p)
  3912. {
  3913. return p->se.avg.load_avg_contrib;
  3914. }
  3915. #endif
  3916. /********** Helpers for find_busiest_group ************************/
  3917. /*
  3918. * sg_lb_stats - stats of a sched_group required for load_balancing
  3919. */
  3920. struct sg_lb_stats {
  3921. unsigned long avg_load; /*Avg load across the CPUs of the group */
  3922. unsigned long group_load; /* Total load over the CPUs of the group */
  3923. unsigned long sum_weighted_load; /* Weighted load of group's tasks */
  3924. unsigned long load_per_task;
  3925. unsigned long group_power;
  3926. unsigned int sum_nr_running; /* Nr tasks running in the group */
  3927. unsigned int group_capacity;
  3928. unsigned int idle_cpus;
  3929. unsigned int group_weight;
  3930. int group_imb; /* Is there an imbalance in the group ? */
  3931. int group_has_capacity; /* Is there extra capacity in the group? */
  3932. };
  3933. /*
  3934. * sd_lb_stats - Structure to store the statistics of a sched_domain
  3935. * during load balancing.
  3936. */
  3937. struct sd_lb_stats {
  3938. struct sched_group *busiest; /* Busiest group in this sd */
  3939. struct sched_group *local; /* Local group in this sd */
  3940. unsigned long total_load; /* Total load of all groups in sd */
  3941. unsigned long total_pwr; /* Total power of all groups in sd */
  3942. unsigned long avg_load; /* Average load across all groups in sd */
  3943. struct sg_lb_stats busiest_stat;/* Statistics of the busiest group */
  3944. struct sg_lb_stats local_stat; /* Statistics of the local group */
  3945. };
  3946. static inline void init_sd_lb_stats(struct sd_lb_stats *sds)
  3947. {
  3948. /*
  3949. * Skimp on the clearing to avoid duplicate work. We can avoid clearing
  3950. * local_stat because update_sg_lb_stats() does a full clear/assignment.
  3951. * We must however clear busiest_stat::avg_load because
  3952. * update_sd_pick_busiest() reads this before assignment.
  3953. */
  3954. *sds = (struct sd_lb_stats){
  3955. .busiest = NULL,
  3956. .local = NULL,
  3957. .total_load = 0UL,
  3958. .total_pwr = 0UL,
  3959. .busiest_stat = {
  3960. .avg_load = 0UL,
  3961. },
  3962. };
  3963. }
  3964. /**
  3965. * get_sd_load_idx - Obtain the load index for a given sched domain.
  3966. * @sd: The sched_domain whose load_idx is to be obtained.
  3967. * @idle: The Idle status of the CPU for whose sd load_icx is obtained.
  3968. *
  3969. * Return: The load index.
  3970. */
  3971. static inline int get_sd_load_idx(struct sched_domain *sd,
  3972. enum cpu_idle_type idle)
  3973. {
  3974. int load_idx;
  3975. switch (idle) {
  3976. case CPU_NOT_IDLE:
  3977. load_idx = sd->busy_idx;
  3978. break;
  3979. case CPU_NEWLY_IDLE:
  3980. load_idx = sd->newidle_idx;
  3981. break;
  3982. default:
  3983. load_idx = sd->idle_idx;
  3984. break;
  3985. }
  3986. return load_idx;
  3987. }
  3988. static unsigned long default_scale_freq_power(struct sched_domain *sd, int cpu)
  3989. {
  3990. return SCHED_POWER_SCALE;
  3991. }
  3992. unsigned long __weak arch_scale_freq_power(struct sched_domain *sd, int cpu)
  3993. {
  3994. return default_scale_freq_power(sd, cpu);
  3995. }
  3996. static unsigned long default_scale_smt_power(struct sched_domain *sd, int cpu)
  3997. {
  3998. unsigned long weight = sd->span_weight;
  3999. unsigned long smt_gain = sd->smt_gain;
  4000. smt_gain /= weight;
  4001. return smt_gain;
  4002. }
  4003. unsigned long __weak arch_scale_smt_power(struct sched_domain *sd, int cpu)
  4004. {
  4005. return default_scale_smt_power(sd, cpu);
  4006. }
  4007. static unsigned long scale_rt_power(int cpu)
  4008. {
  4009. struct rq *rq = cpu_rq(cpu);
  4010. u64 total, available, age_stamp, avg;
  4011. /*
  4012. * Since we're reading these variables without serialization make sure
  4013. * we read them once before doing sanity checks on them.
  4014. */
  4015. age_stamp = ACCESS_ONCE(rq->age_stamp);
  4016. avg = ACCESS_ONCE(rq->rt_avg);
  4017. total = sched_avg_period() + (rq_clock(rq) - age_stamp);
  4018. if (unlikely(total < avg)) {
  4019. /* Ensures that power won't end up being negative */
  4020. available = 0;
  4021. } else {
  4022. available = total - avg;
  4023. }
  4024. if (unlikely((s64)total < SCHED_POWER_SCALE))
  4025. total = SCHED_POWER_SCALE;
  4026. total >>= SCHED_POWER_SHIFT;
  4027. return div_u64(available, total);
  4028. }
  4029. static void update_cpu_power(struct sched_domain *sd, int cpu)
  4030. {
  4031. unsigned long weight = sd->span_weight;
  4032. unsigned long power = SCHED_POWER_SCALE;
  4033. struct sched_group *sdg = sd->groups;
  4034. if ((sd->flags & SD_SHARE_CPUPOWER) && weight > 1) {
  4035. if (sched_feat(ARCH_POWER))
  4036. power *= arch_scale_smt_power(sd, cpu);
  4037. else
  4038. power *= default_scale_smt_power(sd, cpu);
  4039. power >>= SCHED_POWER_SHIFT;
  4040. }
  4041. sdg->sgp->power_orig = power;
  4042. if (sched_feat(ARCH_POWER))
  4043. power *= arch_scale_freq_power(sd, cpu);
  4044. else
  4045. power *= default_scale_freq_power(sd, cpu);
  4046. power >>= SCHED_POWER_SHIFT;
  4047. power *= scale_rt_power(cpu);
  4048. power >>= SCHED_POWER_SHIFT;
  4049. if (!power)
  4050. power = 1;
  4051. cpu_rq(cpu)->cpu_power = power;
  4052. sdg->sgp->power = power;
  4053. }
  4054. void update_group_power(struct sched_domain *sd, int cpu)
  4055. {
  4056. struct sched_domain *child = sd->child;
  4057. struct sched_group *group, *sdg = sd->groups;
  4058. unsigned long power, power_orig;
  4059. unsigned long interval;
  4060. interval = msecs_to_jiffies(sd->balance_interval);
  4061. interval = clamp(interval, 1UL, max_load_balance_interval);
  4062. sdg->sgp->next_update = jiffies + interval;
  4063. if (!child) {
  4064. update_cpu_power(sd, cpu);
  4065. return;
  4066. }
  4067. power_orig = power = 0;
  4068. if (child->flags & SD_OVERLAP) {
  4069. /*
  4070. * SD_OVERLAP domains cannot assume that child groups
  4071. * span the current group.
  4072. */
  4073. for_each_cpu(cpu, sched_group_cpus(sdg)) {
  4074. struct sched_group *sg = cpu_rq(cpu)->sd->groups;
  4075. power_orig += sg->sgp->power_orig;
  4076. power += sg->sgp->power;
  4077. }
  4078. } else {
  4079. /*
  4080. * !SD_OVERLAP domains can assume that child groups
  4081. * span the current group.
  4082. */
  4083. group = child->groups;
  4084. do {
  4085. power_orig += group->sgp->power_orig;
  4086. power += group->sgp->power;
  4087. group = group->next;
  4088. } while (group != child->groups);
  4089. }
  4090. sdg->sgp->power_orig = power_orig;
  4091. sdg->sgp->power = power;
  4092. }
  4093. /*
  4094. * Try and fix up capacity for tiny siblings, this is needed when
  4095. * things like SD_ASYM_PACKING need f_b_g to select another sibling
  4096. * which on its own isn't powerful enough.
  4097. *
  4098. * See update_sd_pick_busiest() and check_asym_packing().
  4099. */
  4100. static inline int
  4101. fix_small_capacity(struct sched_domain *sd, struct sched_group *group)
  4102. {
  4103. /*
  4104. * Only siblings can have significantly less than SCHED_POWER_SCALE
  4105. */
  4106. if (!(sd->flags & SD_SHARE_CPUPOWER))
  4107. return 0;
  4108. /*
  4109. * If ~90% of the cpu_power is still there, we're good.
  4110. */
  4111. if (group->sgp->power * 32 > group->sgp->power_orig * 29)
  4112. return 1;
  4113. return 0;
  4114. }
  4115. /*
  4116. * Group imbalance indicates (and tries to solve) the problem where balancing
  4117. * groups is inadequate due to tsk_cpus_allowed() constraints.
  4118. *
  4119. * Imagine a situation of two groups of 4 cpus each and 4 tasks each with a
  4120. * cpumask covering 1 cpu of the first group and 3 cpus of the second group.
  4121. * Something like:
  4122. *
  4123. * { 0 1 2 3 } { 4 5 6 7 }
  4124. * * * * *
  4125. *
  4126. * If we were to balance group-wise we'd place two tasks in the first group and
  4127. * two tasks in the second group. Clearly this is undesired as it will overload
  4128. * cpu 3 and leave one of the cpus in the second group unused.
  4129. *
  4130. * The current solution to this issue is detecting the skew in the first group
  4131. * by noticing the lower domain failed to reach balance and had difficulty
  4132. * moving tasks due to affinity constraints.
  4133. *
  4134. * When this is so detected; this group becomes a candidate for busiest; see
  4135. * update_sd_pick_busiest(). And calculcate_imbalance() and
  4136. * find_busiest_group() avoid some of the usual balance conditions to allow it
  4137. * to create an effective group imbalance.
  4138. *
  4139. * This is a somewhat tricky proposition since the next run might not find the
  4140. * group imbalance and decide the groups need to be balanced again. A most
  4141. * subtle and fragile situation.
  4142. */
  4143. static inline int sg_imbalanced(struct sched_group *group)
  4144. {
  4145. return group->sgp->imbalance;
  4146. }
  4147. /*
  4148. * Compute the group capacity.
  4149. *
  4150. * Avoid the issue where N*frac(smt_power) >= 1 creates 'phantom' cores by
  4151. * first dividing out the smt factor and computing the actual number of cores
  4152. * and limit power unit capacity with that.
  4153. */
  4154. static inline int sg_capacity(struct lb_env *env, struct sched_group *group)
  4155. {
  4156. unsigned int capacity, smt, cpus;
  4157. unsigned int power, power_orig;
  4158. power = group->sgp->power;
  4159. power_orig = group->sgp->power_orig;
  4160. cpus = group->group_weight;
  4161. /* smt := ceil(cpus / power), assumes: 1 < smt_power < 2 */
  4162. smt = DIV_ROUND_UP(SCHED_POWER_SCALE * cpus, power_orig);
  4163. capacity = cpus / smt; /* cores */
  4164. capacity = min_t(unsigned, capacity, DIV_ROUND_CLOSEST(power, SCHED_POWER_SCALE));
  4165. if (!capacity)
  4166. capacity = fix_small_capacity(env->sd, group);
  4167. return capacity;
  4168. }
  4169. /**
  4170. * update_sg_lb_stats - Update sched_group's statistics for load balancing.
  4171. * @env: The load balancing environment.
  4172. * @group: sched_group whose statistics are to be updated.
  4173. * @load_idx: Load index of sched_domain of this_cpu for load calc.
  4174. * @local_group: Does group contain this_cpu.
  4175. * @sgs: variable to hold the statistics for this group.
  4176. */
  4177. static inline void update_sg_lb_stats(struct lb_env *env,
  4178. struct sched_group *group, int load_idx,
  4179. int local_group, struct sg_lb_stats *sgs)
  4180. {
  4181. unsigned long nr_running;
  4182. unsigned long load;
  4183. int i;
  4184. memset(sgs, 0, sizeof(*sgs));
  4185. for_each_cpu_and(i, sched_group_cpus(group), env->cpus) {
  4186. struct rq *rq = cpu_rq(i);
  4187. nr_running = rq->nr_running;
  4188. /* Bias balancing toward cpus of our domain */
  4189. if (local_group)
  4190. load = target_load(i, load_idx);
  4191. else
  4192. load = source_load(i, load_idx);
  4193. sgs->group_load += load;
  4194. sgs->sum_nr_running += nr_running;
  4195. sgs->sum_weighted_load += weighted_cpuload(i);
  4196. if (idle_cpu(i))
  4197. sgs->idle_cpus++;
  4198. }
  4199. /* Adjust by relative CPU power of the group */
  4200. sgs->group_power = group->sgp->power;
  4201. sgs->avg_load = (sgs->group_load*SCHED_POWER_SCALE) / sgs->group_power;
  4202. if (sgs->sum_nr_running)
  4203. sgs->load_per_task = sgs->sum_weighted_load / sgs->sum_nr_running;
  4204. sgs->group_weight = group->group_weight;
  4205. sgs->group_imb = sg_imbalanced(group);
  4206. sgs->group_capacity = sg_capacity(env, group);
  4207. if (sgs->group_capacity > sgs->sum_nr_running)
  4208. sgs->group_has_capacity = 1;
  4209. }
  4210. /**
  4211. * update_sd_pick_busiest - return 1 on busiest group
  4212. * @env: The load balancing environment.
  4213. * @sds: sched_domain statistics
  4214. * @sg: sched_group candidate to be checked for being the busiest
  4215. * @sgs: sched_group statistics
  4216. *
  4217. * Determine if @sg is a busier group than the previously selected
  4218. * busiest group.
  4219. *
  4220. * Return: %true if @sg is a busier group than the previously selected
  4221. * busiest group. %false otherwise.
  4222. */
  4223. static bool update_sd_pick_busiest(struct lb_env *env,
  4224. struct sd_lb_stats *sds,
  4225. struct sched_group *sg,
  4226. struct sg_lb_stats *sgs)
  4227. {
  4228. if (sgs->avg_load <= sds->busiest_stat.avg_load)
  4229. return false;
  4230. if (sgs->sum_nr_running > sgs->group_capacity)
  4231. return true;
  4232. if (sgs->group_imb)
  4233. return true;
  4234. /*
  4235. * ASYM_PACKING needs to move all the work to the lowest
  4236. * numbered CPUs in the group, therefore mark all groups
  4237. * higher than ourself as busy.
  4238. */
  4239. if ((env->sd->flags & SD_ASYM_PACKING) && sgs->sum_nr_running &&
  4240. env->dst_cpu < group_first_cpu(sg)) {
  4241. if (!sds->busiest)
  4242. return true;
  4243. if (group_first_cpu(sds->busiest) > group_first_cpu(sg))
  4244. return true;
  4245. }
  4246. return false;
  4247. }
  4248. /**
  4249. * update_sd_lb_stats - Update sched_domain's statistics for load balancing.
  4250. * @env: The load balancing environment.
  4251. * @balance: Should we balance.
  4252. * @sds: variable to hold the statistics for this sched_domain.
  4253. */
  4254. static inline void update_sd_lb_stats(struct lb_env *env,
  4255. struct sd_lb_stats *sds)
  4256. {
  4257. struct sched_domain *child = env->sd->child;
  4258. struct sched_group *sg = env->sd->groups;
  4259. struct sg_lb_stats tmp_sgs;
  4260. int load_idx, prefer_sibling = 0;
  4261. if (child && child->flags & SD_PREFER_SIBLING)
  4262. prefer_sibling = 1;
  4263. load_idx = get_sd_load_idx(env->sd, env->idle);
  4264. do {
  4265. struct sg_lb_stats *sgs = &tmp_sgs;
  4266. int local_group;
  4267. local_group = cpumask_test_cpu(env->dst_cpu, sched_group_cpus(sg));
  4268. if (local_group) {
  4269. sds->local = sg;
  4270. sgs = &sds->local_stat;
  4271. if (env->idle != CPU_NEWLY_IDLE ||
  4272. time_after_eq(jiffies, sg->sgp->next_update))
  4273. update_group_power(env->sd, env->dst_cpu);
  4274. }
  4275. update_sg_lb_stats(env, sg, load_idx, local_group, sgs);
  4276. if (local_group)
  4277. goto next_group;
  4278. /*
  4279. * In case the child domain prefers tasks go to siblings
  4280. * first, lower the sg capacity to one so that we'll try
  4281. * and move all the excess tasks away. We lower the capacity
  4282. * of a group only if the local group has the capacity to fit
  4283. * these excess tasks, i.e. nr_running < group_capacity. The
  4284. * extra check prevents the case where you always pull from the
  4285. * heaviest group when it is already under-utilized (possible
  4286. * with a large weight task outweighs the tasks on the system).
  4287. */
  4288. if (prefer_sibling && sds->local &&
  4289. sds->local_stat.group_has_capacity)
  4290. sgs->group_capacity = min(sgs->group_capacity, 1U);
  4291. if (update_sd_pick_busiest(env, sds, sg, sgs)) {
  4292. sds->busiest = sg;
  4293. sds->busiest_stat = *sgs;
  4294. }
  4295. next_group:
  4296. /* Now, start updating sd_lb_stats */
  4297. sds->total_load += sgs->group_load;
  4298. sds->total_pwr += sgs->group_power;
  4299. sg = sg->next;
  4300. } while (sg != env->sd->groups);
  4301. }
  4302. /**
  4303. * check_asym_packing - Check to see if the group is packed into the
  4304. * sched doman.
  4305. *
  4306. * This is primarily intended to used at the sibling level. Some
  4307. * cores like POWER7 prefer to use lower numbered SMT threads. In the
  4308. * case of POWER7, it can move to lower SMT modes only when higher
  4309. * threads are idle. When in lower SMT modes, the threads will
  4310. * perform better since they share less core resources. Hence when we
  4311. * have idle threads, we want them to be the higher ones.
  4312. *
  4313. * This packing function is run on idle threads. It checks to see if
  4314. * the busiest CPU in this domain (core in the P7 case) has a higher
  4315. * CPU number than the packing function is being run on. Here we are
  4316. * assuming lower CPU number will be equivalent to lower a SMT thread
  4317. * number.
  4318. *
  4319. * Return: 1 when packing is required and a task should be moved to
  4320. * this CPU. The amount of the imbalance is returned in *imbalance.
  4321. *
  4322. * @env: The load balancing environment.
  4323. * @sds: Statistics of the sched_domain which is to be packed
  4324. */
  4325. static int check_asym_packing(struct lb_env *env, struct sd_lb_stats *sds)
  4326. {
  4327. int busiest_cpu;
  4328. if (!(env->sd->flags & SD_ASYM_PACKING))
  4329. return 0;
  4330. if (!sds->busiest)
  4331. return 0;
  4332. busiest_cpu = group_first_cpu(sds->busiest);
  4333. if (env->dst_cpu > busiest_cpu)
  4334. return 0;
  4335. env->imbalance = DIV_ROUND_CLOSEST(
  4336. sds->busiest_stat.avg_load * sds->busiest_stat.group_power,
  4337. SCHED_POWER_SCALE);
  4338. return 1;
  4339. }
  4340. /**
  4341. * fix_small_imbalance - Calculate the minor imbalance that exists
  4342. * amongst the groups of a sched_domain, during
  4343. * load balancing.
  4344. * @env: The load balancing environment.
  4345. * @sds: Statistics of the sched_domain whose imbalance is to be calculated.
  4346. */
  4347. static inline
  4348. void fix_small_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
  4349. {
  4350. unsigned long tmp, pwr_now = 0, pwr_move = 0;
  4351. unsigned int imbn = 2;
  4352. unsigned long scaled_busy_load_per_task;
  4353. struct sg_lb_stats *local, *busiest;
  4354. local = &sds->local_stat;
  4355. busiest = &sds->busiest_stat;
  4356. if (!local->sum_nr_running)
  4357. local->load_per_task = cpu_avg_load_per_task(env->dst_cpu);
  4358. else if (busiest->load_per_task > local->load_per_task)
  4359. imbn = 1;
  4360. scaled_busy_load_per_task =
  4361. (busiest->load_per_task * SCHED_POWER_SCALE) /
  4362. busiest->group_power;
  4363. if (busiest->avg_load + scaled_busy_load_per_task >=
  4364. local->avg_load + (scaled_busy_load_per_task * imbn)) {
  4365. env->imbalance = busiest->load_per_task;
  4366. return;
  4367. }
  4368. /*
  4369. * OK, we don't have enough imbalance to justify moving tasks,
  4370. * however we may be able to increase total CPU power used by
  4371. * moving them.
  4372. */
  4373. pwr_now += busiest->group_power *
  4374. min(busiest->load_per_task, busiest->avg_load);
  4375. pwr_now += local->group_power *
  4376. min(local->load_per_task, local->avg_load);
  4377. pwr_now /= SCHED_POWER_SCALE;
  4378. /* Amount of load we'd subtract */
  4379. tmp = (busiest->load_per_task * SCHED_POWER_SCALE) /
  4380. busiest->group_power;
  4381. if (busiest->avg_load > tmp) {
  4382. pwr_move += busiest->group_power *
  4383. min(busiest->load_per_task,
  4384. busiest->avg_load - tmp);
  4385. }
  4386. /* Amount of load we'd add */
  4387. if (busiest->avg_load * busiest->group_power <
  4388. busiest->load_per_task * SCHED_POWER_SCALE) {
  4389. tmp = (busiest->avg_load * busiest->group_power) /
  4390. local->group_power;
  4391. } else {
  4392. tmp = (busiest->load_per_task * SCHED_POWER_SCALE) /
  4393. local->group_power;
  4394. }
  4395. pwr_move += local->group_power *
  4396. min(local->load_per_task, local->avg_load + tmp);
  4397. pwr_move /= SCHED_POWER_SCALE;
  4398. /* Move if we gain throughput */
  4399. if (pwr_move > pwr_now)
  4400. env->imbalance = busiest->load_per_task;
  4401. }
  4402. /**
  4403. * calculate_imbalance - Calculate the amount of imbalance present within the
  4404. * groups of a given sched_domain during load balance.
  4405. * @env: load balance environment
  4406. * @sds: statistics of the sched_domain whose imbalance is to be calculated.
  4407. */
  4408. static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
  4409. {
  4410. unsigned long max_pull, load_above_capacity = ~0UL;
  4411. struct sg_lb_stats *local, *busiest;
  4412. local = &sds->local_stat;
  4413. busiest = &sds->busiest_stat;
  4414. if (busiest->group_imb) {
  4415. /*
  4416. * In the group_imb case we cannot rely on group-wide averages
  4417. * to ensure cpu-load equilibrium, look at wider averages. XXX
  4418. */
  4419. busiest->load_per_task =
  4420. min(busiest->load_per_task, sds->avg_load);
  4421. }
  4422. /*
  4423. * In the presence of smp nice balancing, certain scenarios can have
  4424. * max load less than avg load(as we skip the groups at or below
  4425. * its cpu_power, while calculating max_load..)
  4426. */
  4427. if (busiest->avg_load <= sds->avg_load ||
  4428. local->avg_load >= sds->avg_load) {
  4429. env->imbalance = 0;
  4430. return fix_small_imbalance(env, sds);
  4431. }
  4432. if (!busiest->group_imb) {
  4433. /*
  4434. * Don't want to pull so many tasks that a group would go idle.
  4435. * Except of course for the group_imb case, since then we might
  4436. * have to drop below capacity to reach cpu-load equilibrium.
  4437. */
  4438. load_above_capacity =
  4439. (busiest->sum_nr_running - busiest->group_capacity);
  4440. load_above_capacity *= (SCHED_LOAD_SCALE * SCHED_POWER_SCALE);
  4441. load_above_capacity /= busiest->group_power;
  4442. }
  4443. /*
  4444. * We're trying to get all the cpus to the average_load, so we don't
  4445. * want to push ourselves above the average load, nor do we wish to
  4446. * reduce the max loaded cpu below the average load. At the same time,
  4447. * we also don't want to reduce the group load below the group capacity
  4448. * (so that we can implement power-savings policies etc). Thus we look
  4449. * for the minimum possible imbalance.
  4450. */
  4451. max_pull = min(busiest->avg_load - sds->avg_load, load_above_capacity);
  4452. /* How much load to actually move to equalise the imbalance */
  4453. env->imbalance = min(
  4454. max_pull * busiest->group_power,
  4455. (sds->avg_load - local->avg_load) * local->group_power
  4456. ) / SCHED_POWER_SCALE;
  4457. /*
  4458. * if *imbalance is less than the average load per runnable task
  4459. * there is no guarantee that any tasks will be moved so we'll have
  4460. * a think about bumping its value to force at least one task to be
  4461. * moved
  4462. */
  4463. if (env->imbalance < busiest->load_per_task)
  4464. return fix_small_imbalance(env, sds);
  4465. }
  4466. /******* find_busiest_group() helpers end here *********************/
  4467. /**
  4468. * find_busiest_group - Returns the busiest group within the sched_domain
  4469. * if there is an imbalance. If there isn't an imbalance, and
  4470. * the user has opted for power-savings, it returns a group whose
  4471. * CPUs can be put to idle by rebalancing those tasks elsewhere, if
  4472. * such a group exists.
  4473. *
  4474. * Also calculates the amount of weighted load which should be moved
  4475. * to restore balance.
  4476. *
  4477. * @env: The load balancing environment.
  4478. *
  4479. * Return: - The busiest group if imbalance exists.
  4480. * - If no imbalance and user has opted for power-savings balance,
  4481. * return the least loaded group whose CPUs can be
  4482. * put to idle by rebalancing its tasks onto our group.
  4483. */
  4484. static struct sched_group *find_busiest_group(struct lb_env *env)
  4485. {
  4486. struct sg_lb_stats *local, *busiest;
  4487. struct sd_lb_stats sds;
  4488. init_sd_lb_stats(&sds);
  4489. /*
  4490. * Compute the various statistics relavent for load balancing at
  4491. * this level.
  4492. */
  4493. update_sd_lb_stats(env, &sds);
  4494. local = &sds.local_stat;
  4495. busiest = &sds.busiest_stat;
  4496. if ((env->idle == CPU_IDLE || env->idle == CPU_NEWLY_IDLE) &&
  4497. check_asym_packing(env, &sds))
  4498. return sds.busiest;
  4499. /* There is no busy sibling group to pull tasks from */
  4500. if (!sds.busiest || busiest->sum_nr_running == 0)
  4501. goto out_balanced;
  4502. sds.avg_load = (SCHED_POWER_SCALE * sds.total_load) / sds.total_pwr;
  4503. /*
  4504. * If the busiest group is imbalanced the below checks don't
  4505. * work because they assume all things are equal, which typically
  4506. * isn't true due to cpus_allowed constraints and the like.
  4507. */
  4508. if (busiest->group_imb)
  4509. goto force_balance;
  4510. /* SD_BALANCE_NEWIDLE trumps SMP nice when underutilized */
  4511. if (env->idle == CPU_NEWLY_IDLE && local->group_has_capacity &&
  4512. !busiest->group_has_capacity)
  4513. goto force_balance;
  4514. /*
  4515. * If the local group is more busy than the selected busiest group
  4516. * don't try and pull any tasks.
  4517. */
  4518. if (local->avg_load >= busiest->avg_load)
  4519. goto out_balanced;
  4520. /*
  4521. * Don't pull any tasks if this group is already above the domain
  4522. * average load.
  4523. */
  4524. if (local->avg_load >= sds.avg_load)
  4525. goto out_balanced;
  4526. if (env->idle == CPU_IDLE) {
  4527. /*
  4528. * This cpu is idle. If the busiest group load doesn't
  4529. * have more tasks than the number of available cpu's and
  4530. * there is no imbalance between this and busiest group
  4531. * wrt to idle cpu's, it is balanced.
  4532. */
  4533. if ((local->idle_cpus < busiest->idle_cpus) &&
  4534. busiest->sum_nr_running <= busiest->group_weight)
  4535. goto out_balanced;
  4536. } else {
  4537. /*
  4538. * In the CPU_NEWLY_IDLE, CPU_NOT_IDLE cases, use
  4539. * imbalance_pct to be conservative.
  4540. */
  4541. if (100 * busiest->avg_load <=
  4542. env->sd->imbalance_pct * local->avg_load)
  4543. goto out_balanced;
  4544. }
  4545. force_balance:
  4546. /* Looks like there is an imbalance. Compute it */
  4547. calculate_imbalance(env, &sds);
  4548. return sds.busiest;
  4549. out_balanced:
  4550. env->imbalance = 0;
  4551. return NULL;
  4552. }
  4553. /*
  4554. * find_busiest_queue - find the busiest runqueue among the cpus in group.
  4555. */
  4556. static struct rq *find_busiest_queue(struct lb_env *env,
  4557. struct sched_group *group)
  4558. {
  4559. struct rq *busiest = NULL, *rq;
  4560. unsigned long busiest_load = 0, busiest_power = 1;
  4561. int i;
  4562. for_each_cpu_and(i, sched_group_cpus(group), env->cpus) {
  4563. unsigned long power = power_of(i);
  4564. unsigned long capacity = DIV_ROUND_CLOSEST(power,
  4565. SCHED_POWER_SCALE);
  4566. unsigned long wl;
  4567. if (!capacity)
  4568. capacity = fix_small_capacity(env->sd, group);
  4569. rq = cpu_rq(i);
  4570. wl = weighted_cpuload(i);
  4571. /*
  4572. * When comparing with imbalance, use weighted_cpuload()
  4573. * which is not scaled with the cpu power.
  4574. */
  4575. if (capacity && rq->nr_running == 1 && wl > env->imbalance)
  4576. continue;
  4577. /*
  4578. * For the load comparisons with the other cpu's, consider
  4579. * the weighted_cpuload() scaled with the cpu power, so that
  4580. * the load can be moved away from the cpu that is potentially
  4581. * running at a lower capacity.
  4582. *
  4583. * Thus we're looking for max(wl_i / power_i), crosswise
  4584. * multiplication to rid ourselves of the division works out
  4585. * to: wl_i * power_j > wl_j * power_i; where j is our
  4586. * previous maximum.
  4587. */
  4588. if (wl * busiest_power > busiest_load * power) {
  4589. busiest_load = wl;
  4590. busiest_power = power;
  4591. busiest = rq;
  4592. }
  4593. }
  4594. return busiest;
  4595. }
  4596. /*
  4597. * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
  4598. * so long as it is large enough.
  4599. */
  4600. #define MAX_PINNED_INTERVAL 512
  4601. /* Working cpumask for load_balance and load_balance_newidle. */
  4602. DEFINE_PER_CPU(cpumask_var_t, load_balance_mask);
  4603. static int need_active_balance(struct lb_env *env)
  4604. {
  4605. struct sched_domain *sd = env->sd;
  4606. if (env->idle == CPU_NEWLY_IDLE) {
  4607. /*
  4608. * ASYM_PACKING needs to force migrate tasks from busy but
  4609. * higher numbered CPUs in order to pack all tasks in the
  4610. * lowest numbered CPUs.
  4611. */
  4612. if ((sd->flags & SD_ASYM_PACKING) && env->src_cpu > env->dst_cpu)
  4613. return 1;
  4614. }
  4615. return unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2);
  4616. }
  4617. static int active_load_balance_cpu_stop(void *data);
  4618. static int should_we_balance(struct lb_env *env)
  4619. {
  4620. struct sched_group *sg = env->sd->groups;
  4621. struct cpumask *sg_cpus, *sg_mask;
  4622. int cpu, balance_cpu = -1;
  4623. /*
  4624. * In the newly idle case, we will allow all the cpu's
  4625. * to do the newly idle load balance.
  4626. */
  4627. if (env->idle == CPU_NEWLY_IDLE)
  4628. return 1;
  4629. sg_cpus = sched_group_cpus(sg);
  4630. sg_mask = sched_group_mask(sg);
  4631. /* Try to find first idle cpu */
  4632. for_each_cpu_and(cpu, sg_cpus, env->cpus) {
  4633. if (!cpumask_test_cpu(cpu, sg_mask) || !idle_cpu(cpu))
  4634. continue;
  4635. balance_cpu = cpu;
  4636. break;
  4637. }
  4638. if (balance_cpu == -1)
  4639. balance_cpu = group_balance_cpu(sg);
  4640. /*
  4641. * First idle cpu or the first cpu(busiest) in this sched group
  4642. * is eligible for doing load balancing at this and above domains.
  4643. */
  4644. return balance_cpu == env->dst_cpu;
  4645. }
  4646. /*
  4647. * Check this_cpu to ensure it is balanced within domain. Attempt to move
  4648. * tasks if there is an imbalance.
  4649. */
  4650. static int load_balance(int this_cpu, struct rq *this_rq,
  4651. struct sched_domain *sd, enum cpu_idle_type idle,
  4652. int *continue_balancing)
  4653. {
  4654. int ld_moved, cur_ld_moved, active_balance = 0;
  4655. struct sched_domain *sd_parent = sd->parent;
  4656. struct sched_group *group;
  4657. struct rq *busiest;
  4658. unsigned long flags;
  4659. struct cpumask *cpus = __get_cpu_var(load_balance_mask);
  4660. struct lb_env env = {
  4661. .sd = sd,
  4662. .dst_cpu = this_cpu,
  4663. .dst_rq = this_rq,
  4664. .dst_grpmask = sched_group_cpus(sd->groups),
  4665. .idle = idle,
  4666. .loop_break = sched_nr_migrate_break,
  4667. .cpus = cpus,
  4668. };
  4669. /*
  4670. * For NEWLY_IDLE load_balancing, we don't need to consider
  4671. * other cpus in our group
  4672. */
  4673. if (idle == CPU_NEWLY_IDLE)
  4674. env.dst_grpmask = NULL;
  4675. cpumask_copy(cpus, cpu_active_mask);
  4676. schedstat_inc(sd, lb_count[idle]);
  4677. redo:
  4678. if (!should_we_balance(&env)) {
  4679. *continue_balancing = 0;
  4680. goto out_balanced;
  4681. }
  4682. group = find_busiest_group(&env);
  4683. if (!group) {
  4684. schedstat_inc(sd, lb_nobusyg[idle]);
  4685. goto out_balanced;
  4686. }
  4687. busiest = find_busiest_queue(&env, group);
  4688. if (!busiest) {
  4689. schedstat_inc(sd, lb_nobusyq[idle]);
  4690. goto out_balanced;
  4691. }
  4692. BUG_ON(busiest == env.dst_rq);
  4693. schedstat_add(sd, lb_imbalance[idle], env.imbalance);
  4694. ld_moved = 0;
  4695. if (busiest->nr_running > 1) {
  4696. /*
  4697. * Attempt to move tasks. If find_busiest_group has found
  4698. * an imbalance but busiest->nr_running <= 1, the group is
  4699. * still unbalanced. ld_moved simply stays zero, so it is
  4700. * correctly treated as an imbalance.
  4701. */
  4702. env.flags |= LBF_ALL_PINNED;
  4703. env.src_cpu = busiest->cpu;
  4704. env.src_rq = busiest;
  4705. env.loop_max = min(sysctl_sched_nr_migrate, busiest->nr_running);
  4706. more_balance:
  4707. local_irq_save(flags);
  4708. double_rq_lock(env.dst_rq, busiest);
  4709. /*
  4710. * cur_ld_moved - load moved in current iteration
  4711. * ld_moved - cumulative load moved across iterations
  4712. */
  4713. cur_ld_moved = move_tasks(&env);
  4714. ld_moved += cur_ld_moved;
  4715. double_rq_unlock(env.dst_rq, busiest);
  4716. local_irq_restore(flags);
  4717. /*
  4718. * some other cpu did the load balance for us.
  4719. */
  4720. if (cur_ld_moved && env.dst_cpu != smp_processor_id())
  4721. resched_cpu(env.dst_cpu);
  4722. if (env.flags & LBF_NEED_BREAK) {
  4723. env.flags &= ~LBF_NEED_BREAK;
  4724. goto more_balance;
  4725. }
  4726. /*
  4727. * Revisit (affine) tasks on src_cpu that couldn't be moved to
  4728. * us and move them to an alternate dst_cpu in our sched_group
  4729. * where they can run. The upper limit on how many times we
  4730. * iterate on same src_cpu is dependent on number of cpus in our
  4731. * sched_group.
  4732. *
  4733. * This changes load balance semantics a bit on who can move
  4734. * load to a given_cpu. In addition to the given_cpu itself
  4735. * (or a ilb_cpu acting on its behalf where given_cpu is
  4736. * nohz-idle), we now have balance_cpu in a position to move
  4737. * load to given_cpu. In rare situations, this may cause
  4738. * conflicts (balance_cpu and given_cpu/ilb_cpu deciding
  4739. * _independently_ and at _same_ time to move some load to
  4740. * given_cpu) causing exceess load to be moved to given_cpu.
  4741. * This however should not happen so much in practice and
  4742. * moreover subsequent load balance cycles should correct the
  4743. * excess load moved.
  4744. */
  4745. if ((env.flags & LBF_DST_PINNED) && env.imbalance > 0) {
  4746. /* Prevent to re-select dst_cpu via env's cpus */
  4747. cpumask_clear_cpu(env.dst_cpu, env.cpus);
  4748. env.dst_rq = cpu_rq(env.new_dst_cpu);
  4749. env.dst_cpu = env.new_dst_cpu;
  4750. env.flags &= ~LBF_DST_PINNED;
  4751. env.loop = 0;
  4752. env.loop_break = sched_nr_migrate_break;
  4753. /*
  4754. * Go back to "more_balance" rather than "redo" since we
  4755. * need to continue with same src_cpu.
  4756. */
  4757. goto more_balance;
  4758. }
  4759. /*
  4760. * We failed to reach balance because of affinity.
  4761. */
  4762. if (sd_parent) {
  4763. int *group_imbalance = &sd_parent->groups->sgp->imbalance;
  4764. if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0) {
  4765. *group_imbalance = 1;
  4766. } else if (*group_imbalance)
  4767. *group_imbalance = 0;
  4768. }
  4769. /* All tasks on this runqueue were pinned by CPU affinity */
  4770. if (unlikely(env.flags & LBF_ALL_PINNED)) {
  4771. cpumask_clear_cpu(cpu_of(busiest), cpus);
  4772. if (!cpumask_empty(cpus)) {
  4773. env.loop = 0;
  4774. env.loop_break = sched_nr_migrate_break;
  4775. goto redo;
  4776. }
  4777. goto out_balanced;
  4778. }
  4779. }
  4780. if (!ld_moved) {
  4781. schedstat_inc(sd, lb_failed[idle]);
  4782. /*
  4783. * Increment the failure counter only on periodic balance.
  4784. * We do not want newidle balance, which can be very
  4785. * frequent, pollute the failure counter causing
  4786. * excessive cache_hot migrations and active balances.
  4787. */
  4788. if (idle != CPU_NEWLY_IDLE)
  4789. sd->nr_balance_failed++;
  4790. if (need_active_balance(&env)) {
  4791. raw_spin_lock_irqsave(&busiest->lock, flags);
  4792. /* don't kick the active_load_balance_cpu_stop,
  4793. * if the curr task on busiest cpu can't be
  4794. * moved to this_cpu
  4795. */
  4796. if (!cpumask_test_cpu(this_cpu,
  4797. tsk_cpus_allowed(busiest->curr))) {
  4798. raw_spin_unlock_irqrestore(&busiest->lock,
  4799. flags);
  4800. env.flags |= LBF_ALL_PINNED;
  4801. goto out_one_pinned;
  4802. }
  4803. /*
  4804. * ->active_balance synchronizes accesses to
  4805. * ->active_balance_work. Once set, it's cleared
  4806. * only after active load balance is finished.
  4807. */
  4808. if (!busiest->active_balance) {
  4809. busiest->active_balance = 1;
  4810. busiest->push_cpu = this_cpu;
  4811. active_balance = 1;
  4812. }
  4813. raw_spin_unlock_irqrestore(&busiest->lock, flags);
  4814. if (active_balance) {
  4815. stop_one_cpu_nowait(cpu_of(busiest),
  4816. active_load_balance_cpu_stop, busiest,
  4817. &busiest->active_balance_work);
  4818. }
  4819. /*
  4820. * We've kicked active balancing, reset the failure
  4821. * counter.
  4822. */
  4823. sd->nr_balance_failed = sd->cache_nice_tries+1;
  4824. }
  4825. } else
  4826. sd->nr_balance_failed = 0;
  4827. if (likely(!active_balance)) {
  4828. /* We were unbalanced, so reset the balancing interval */
  4829. sd->balance_interval = sd->min_interval;
  4830. } else {
  4831. /*
  4832. * If we've begun active balancing, start to back off. This
  4833. * case may not be covered by the all_pinned logic if there
  4834. * is only 1 task on the busy runqueue (because we don't call
  4835. * move_tasks).
  4836. */
  4837. if (sd->balance_interval < sd->max_interval)
  4838. sd->balance_interval *= 2;
  4839. }
  4840. goto out;
  4841. out_balanced:
  4842. schedstat_inc(sd, lb_balanced[idle]);
  4843. sd->nr_balance_failed = 0;
  4844. out_one_pinned:
  4845. /* tune up the balancing interval */
  4846. if (((env.flags & LBF_ALL_PINNED) &&
  4847. sd->balance_interval < MAX_PINNED_INTERVAL) ||
  4848. (sd->balance_interval < sd->max_interval))
  4849. sd->balance_interval *= 2;
  4850. ld_moved = 0;
  4851. out:
  4852. return ld_moved;
  4853. }
  4854. /*
  4855. * idle_balance is called by schedule() if this_cpu is about to become
  4856. * idle. Attempts to pull tasks from other CPUs.
  4857. */
  4858. void idle_balance(int this_cpu, struct rq *this_rq)
  4859. {
  4860. struct sched_domain *sd;
  4861. int pulled_task = 0;
  4862. unsigned long next_balance = jiffies + HZ;
  4863. u64 curr_cost = 0;
  4864. this_rq->idle_stamp = rq_clock(this_rq);
  4865. if (this_rq->avg_idle < sysctl_sched_migration_cost)
  4866. return;
  4867. /*
  4868. * Drop the rq->lock, but keep IRQ/preempt disabled.
  4869. */
  4870. raw_spin_unlock(&this_rq->lock);
  4871. update_blocked_averages(this_cpu);
  4872. rcu_read_lock();
  4873. for_each_domain(this_cpu, sd) {
  4874. unsigned long interval;
  4875. int continue_balancing = 1;
  4876. u64 t0, domain_cost;
  4877. if (!(sd->flags & SD_LOAD_BALANCE))
  4878. continue;
  4879. if (this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost)
  4880. break;
  4881. if (sd->flags & SD_BALANCE_NEWIDLE) {
  4882. t0 = sched_clock_cpu(this_cpu);
  4883. /* If we've pulled tasks over stop searching: */
  4884. pulled_task = load_balance(this_cpu, this_rq,
  4885. sd, CPU_NEWLY_IDLE,
  4886. &continue_balancing);
  4887. domain_cost = sched_clock_cpu(this_cpu) - t0;
  4888. if (domain_cost > sd->max_newidle_lb_cost)
  4889. sd->max_newidle_lb_cost = domain_cost;
  4890. curr_cost += domain_cost;
  4891. }
  4892. interval = msecs_to_jiffies(sd->balance_interval);
  4893. if (time_after(next_balance, sd->last_balance + interval))
  4894. next_balance = sd->last_balance + interval;
  4895. if (pulled_task) {
  4896. this_rq->idle_stamp = 0;
  4897. break;
  4898. }
  4899. }
  4900. rcu_read_unlock();
  4901. raw_spin_lock(&this_rq->lock);
  4902. if (pulled_task || time_after(jiffies, this_rq->next_balance)) {
  4903. /*
  4904. * We are going idle. next_balance may be set based on
  4905. * a busy processor. So reset next_balance.
  4906. */
  4907. this_rq->next_balance = next_balance;
  4908. }
  4909. if (curr_cost > this_rq->max_idle_balance_cost)
  4910. this_rq->max_idle_balance_cost = curr_cost;
  4911. }
  4912. /*
  4913. * active_load_balance_cpu_stop is run by cpu stopper. It pushes
  4914. * running tasks off the busiest CPU onto idle CPUs. It requires at
  4915. * least 1 task to be running on each physical CPU where possible, and
  4916. * avoids physical / logical imbalances.
  4917. */
  4918. static int active_load_balance_cpu_stop(void *data)
  4919. {
  4920. struct rq *busiest_rq = data;
  4921. int busiest_cpu = cpu_of(busiest_rq);
  4922. int target_cpu = busiest_rq->push_cpu;
  4923. struct rq *target_rq = cpu_rq(target_cpu);
  4924. struct sched_domain *sd;
  4925. raw_spin_lock_irq(&busiest_rq->lock);
  4926. /* make sure the requested cpu hasn't gone down in the meantime */
  4927. if (unlikely(busiest_cpu != smp_processor_id() ||
  4928. !busiest_rq->active_balance))
  4929. goto out_unlock;
  4930. /* Is there any task to move? */
  4931. if (busiest_rq->nr_running <= 1)
  4932. goto out_unlock;
  4933. /*
  4934. * This condition is "impossible", if it occurs
  4935. * we need to fix it. Originally reported by
  4936. * Bjorn Helgaas on a 128-cpu setup.
  4937. */
  4938. BUG_ON(busiest_rq == target_rq);
  4939. /* move a task from busiest_rq to target_rq */
  4940. double_lock_balance(busiest_rq, target_rq);
  4941. /* Search for an sd spanning us and the target CPU. */
  4942. rcu_read_lock();
  4943. for_each_domain(target_cpu, sd) {
  4944. if ((sd->flags & SD_LOAD_BALANCE) &&
  4945. cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
  4946. break;
  4947. }
  4948. if (likely(sd)) {
  4949. struct lb_env env = {
  4950. .sd = sd,
  4951. .dst_cpu = target_cpu,
  4952. .dst_rq = target_rq,
  4953. .src_cpu = busiest_rq->cpu,
  4954. .src_rq = busiest_rq,
  4955. .idle = CPU_IDLE,
  4956. };
  4957. schedstat_inc(sd, alb_count);
  4958. if (move_one_task(&env))
  4959. schedstat_inc(sd, alb_pushed);
  4960. else
  4961. schedstat_inc(sd, alb_failed);
  4962. }
  4963. rcu_read_unlock();
  4964. double_unlock_balance(busiest_rq, target_rq);
  4965. out_unlock:
  4966. busiest_rq->active_balance = 0;
  4967. raw_spin_unlock_irq(&busiest_rq->lock);
  4968. return 0;
  4969. }
  4970. #ifdef CONFIG_NO_HZ_COMMON
  4971. /*
  4972. * idle load balancing details
  4973. * - When one of the busy CPUs notice that there may be an idle rebalancing
  4974. * needed, they will kick the idle load balancer, which then does idle
  4975. * load balancing for all the idle CPUs.
  4976. */
  4977. static struct {
  4978. cpumask_var_t idle_cpus_mask;
  4979. atomic_t nr_cpus;
  4980. unsigned long next_balance; /* in jiffy units */
  4981. } nohz ____cacheline_aligned;
  4982. static inline int find_new_ilb(int call_cpu)
  4983. {
  4984. int ilb = cpumask_first(nohz.idle_cpus_mask);
  4985. if (ilb < nr_cpu_ids && idle_cpu(ilb))
  4986. return ilb;
  4987. return nr_cpu_ids;
  4988. }
  4989. /*
  4990. * Kick a CPU to do the nohz balancing, if it is time for it. We pick the
  4991. * nohz_load_balancer CPU (if there is one) otherwise fallback to any idle
  4992. * CPU (if there is one).
  4993. */
  4994. static void nohz_balancer_kick(int cpu)
  4995. {
  4996. int ilb_cpu;
  4997. nohz.next_balance++;
  4998. ilb_cpu = find_new_ilb(cpu);
  4999. if (ilb_cpu >= nr_cpu_ids)
  5000. return;
  5001. if (test_and_set_bit(NOHZ_BALANCE_KICK, nohz_flags(ilb_cpu)))
  5002. return;
  5003. /*
  5004. * Use smp_send_reschedule() instead of resched_cpu().
  5005. * This way we generate a sched IPI on the target cpu which
  5006. * is idle. And the softirq performing nohz idle load balance
  5007. * will be run before returning from the IPI.
  5008. */
  5009. smp_send_reschedule(ilb_cpu);
  5010. return;
  5011. }
  5012. static inline void nohz_balance_exit_idle(int cpu)
  5013. {
  5014. if (unlikely(test_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu)))) {
  5015. cpumask_clear_cpu(cpu, nohz.idle_cpus_mask);
  5016. atomic_dec(&nohz.nr_cpus);
  5017. clear_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu));
  5018. }
  5019. }
  5020. static inline void set_cpu_sd_state_busy(void)
  5021. {
  5022. struct sched_domain *sd;
  5023. rcu_read_lock();
  5024. sd = rcu_dereference_check_sched_domain(this_rq()->sd);
  5025. if (!sd || !sd->nohz_idle)
  5026. goto unlock;
  5027. sd->nohz_idle = 0;
  5028. for (; sd; sd = sd->parent)
  5029. atomic_inc(&sd->groups->sgp->nr_busy_cpus);
  5030. unlock:
  5031. rcu_read_unlock();
  5032. }
  5033. void set_cpu_sd_state_idle(void)
  5034. {
  5035. struct sched_domain *sd;
  5036. rcu_read_lock();
  5037. sd = rcu_dereference_check_sched_domain(this_rq()->sd);
  5038. if (!sd || sd->nohz_idle)
  5039. goto unlock;
  5040. sd->nohz_idle = 1;
  5041. for (; sd; sd = sd->parent)
  5042. atomic_dec(&sd->groups->sgp->nr_busy_cpus);
  5043. unlock:
  5044. rcu_read_unlock();
  5045. }
  5046. /*
  5047. * This routine will record that the cpu is going idle with tick stopped.
  5048. * This info will be used in performing idle load balancing in the future.
  5049. */
  5050. void nohz_balance_enter_idle(int cpu)
  5051. {
  5052. /*
  5053. * If this cpu is going down, then nothing needs to be done.
  5054. */
  5055. if (!cpu_active(cpu))
  5056. return;
  5057. if (test_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu)))
  5058. return;
  5059. cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
  5060. atomic_inc(&nohz.nr_cpus);
  5061. set_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu));
  5062. }
  5063. static int sched_ilb_notifier(struct notifier_block *nfb,
  5064. unsigned long action, void *hcpu)
  5065. {
  5066. switch (action & ~CPU_TASKS_FROZEN) {
  5067. case CPU_DYING:
  5068. nohz_balance_exit_idle(smp_processor_id());
  5069. return NOTIFY_OK;
  5070. default:
  5071. return NOTIFY_DONE;
  5072. }
  5073. }
  5074. #endif
  5075. static DEFINE_SPINLOCK(balancing);
  5076. /*
  5077. * Scale the max load_balance interval with the number of CPUs in the system.
  5078. * This trades load-balance latency on larger machines for less cross talk.
  5079. */
  5080. void update_max_interval(void)
  5081. {
  5082. max_load_balance_interval = HZ*num_online_cpus()/10;
  5083. }
  5084. /*
  5085. * It checks each scheduling domain to see if it is due to be balanced,
  5086. * and initiates a balancing operation if so.
  5087. *
  5088. * Balancing parameters are set up in init_sched_domains.
  5089. */
  5090. static void rebalance_domains(int cpu, enum cpu_idle_type idle)
  5091. {
  5092. int continue_balancing = 1;
  5093. struct rq *rq = cpu_rq(cpu);
  5094. unsigned long interval;
  5095. struct sched_domain *sd;
  5096. /* Earliest time when we have to do rebalance again */
  5097. unsigned long next_balance = jiffies + 60*HZ;
  5098. int update_next_balance = 0;
  5099. int need_serialize, need_decay = 0;
  5100. u64 max_cost = 0;
  5101. update_blocked_averages(cpu);
  5102. rcu_read_lock();
  5103. for_each_domain(cpu, sd) {
  5104. /*
  5105. * Decay the newidle max times here because this is a regular
  5106. * visit to all the domains. Decay ~1% per second.
  5107. */
  5108. if (time_after(jiffies, sd->next_decay_max_lb_cost)) {
  5109. sd->max_newidle_lb_cost =
  5110. (sd->max_newidle_lb_cost * 253) / 256;
  5111. sd->next_decay_max_lb_cost = jiffies + HZ;
  5112. need_decay = 1;
  5113. }
  5114. max_cost += sd->max_newidle_lb_cost;
  5115. if (!(sd->flags & SD_LOAD_BALANCE))
  5116. continue;
  5117. /*
  5118. * Stop the load balance at this level. There is another
  5119. * CPU in our sched group which is doing load balancing more
  5120. * actively.
  5121. */
  5122. if (!continue_balancing) {
  5123. if (need_decay)
  5124. continue;
  5125. break;
  5126. }
  5127. interval = sd->balance_interval;
  5128. if (idle != CPU_IDLE)
  5129. interval *= sd->busy_factor;
  5130. /* scale ms to jiffies */
  5131. interval = msecs_to_jiffies(interval);
  5132. interval = clamp(interval, 1UL, max_load_balance_interval);
  5133. need_serialize = sd->flags & SD_SERIALIZE;
  5134. if (need_serialize) {
  5135. if (!spin_trylock(&balancing))
  5136. goto out;
  5137. }
  5138. if (time_after_eq(jiffies, sd->last_balance + interval)) {
  5139. if (load_balance(cpu, rq, sd, idle, &continue_balancing)) {
  5140. /*
  5141. * The LBF_DST_PINNED logic could have changed
  5142. * env->dst_cpu, so we can't know our idle
  5143. * state even if we migrated tasks. Update it.
  5144. */
  5145. idle = idle_cpu(cpu) ? CPU_IDLE : CPU_NOT_IDLE;
  5146. }
  5147. sd->last_balance = jiffies;
  5148. }
  5149. if (need_serialize)
  5150. spin_unlock(&balancing);
  5151. out:
  5152. if (time_after(next_balance, sd->last_balance + interval)) {
  5153. next_balance = sd->last_balance + interval;
  5154. update_next_balance = 1;
  5155. }
  5156. }
  5157. if (need_decay) {
  5158. /*
  5159. * Ensure the rq-wide value also decays but keep it at a
  5160. * reasonable floor to avoid funnies with rq->avg_idle.
  5161. */
  5162. rq->max_idle_balance_cost =
  5163. max((u64)sysctl_sched_migration_cost, max_cost);
  5164. }
  5165. rcu_read_unlock();
  5166. /*
  5167. * next_balance will be updated only when there is a need.
  5168. * When the cpu is attached to null domain for ex, it will not be
  5169. * updated.
  5170. */
  5171. if (likely(update_next_balance))
  5172. rq->next_balance = next_balance;
  5173. }
  5174. #ifdef CONFIG_NO_HZ_COMMON
  5175. /*
  5176. * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the
  5177. * rebalancing for all the cpus for whom scheduler ticks are stopped.
  5178. */
  5179. static void nohz_idle_balance(int this_cpu, enum cpu_idle_type idle)
  5180. {
  5181. struct rq *this_rq = cpu_rq(this_cpu);
  5182. struct rq *rq;
  5183. int balance_cpu;
  5184. if (idle != CPU_IDLE ||
  5185. !test_bit(NOHZ_BALANCE_KICK, nohz_flags(this_cpu)))
  5186. goto end;
  5187. for_each_cpu(balance_cpu, nohz.idle_cpus_mask) {
  5188. if (balance_cpu == this_cpu || !idle_cpu(balance_cpu))
  5189. continue;
  5190. /*
  5191. * If this cpu gets work to do, stop the load balancing
  5192. * work being done for other cpus. Next load
  5193. * balancing owner will pick it up.
  5194. */
  5195. if (need_resched())
  5196. break;
  5197. rq = cpu_rq(balance_cpu);
  5198. raw_spin_lock_irq(&rq->lock);
  5199. update_rq_clock(rq);
  5200. update_idle_cpu_load(rq);
  5201. raw_spin_unlock_irq(&rq->lock);
  5202. rebalance_domains(balance_cpu, CPU_IDLE);
  5203. if (time_after(this_rq->next_balance, rq->next_balance))
  5204. this_rq->next_balance = rq->next_balance;
  5205. }
  5206. nohz.next_balance = this_rq->next_balance;
  5207. end:
  5208. clear_bit(NOHZ_BALANCE_KICK, nohz_flags(this_cpu));
  5209. }
  5210. /*
  5211. * Current heuristic for kicking the idle load balancer in the presence
  5212. * of an idle cpu is the system.
  5213. * - This rq has more than one task.
  5214. * - At any scheduler domain level, this cpu's scheduler group has multiple
  5215. * busy cpu's exceeding the group's power.
  5216. * - For SD_ASYM_PACKING, if the lower numbered cpu's in the scheduler
  5217. * domain span are idle.
  5218. */
  5219. static inline int nohz_kick_needed(struct rq *rq, int cpu)
  5220. {
  5221. unsigned long now = jiffies;
  5222. struct sched_domain *sd;
  5223. if (unlikely(idle_cpu(cpu)))
  5224. return 0;
  5225. /*
  5226. * We may be recently in ticked or tickless idle mode. At the first
  5227. * busy tick after returning from idle, we will update the busy stats.
  5228. */
  5229. set_cpu_sd_state_busy();
  5230. nohz_balance_exit_idle(cpu);
  5231. /*
  5232. * None are in tickless mode and hence no need for NOHZ idle load
  5233. * balancing.
  5234. */
  5235. if (likely(!atomic_read(&nohz.nr_cpus)))
  5236. return 0;
  5237. if (time_before(now, nohz.next_balance))
  5238. return 0;
  5239. if (rq->nr_running >= 2)
  5240. goto need_kick;
  5241. rcu_read_lock();
  5242. for_each_domain(cpu, sd) {
  5243. struct sched_group *sg = sd->groups;
  5244. struct sched_group_power *sgp = sg->sgp;
  5245. int nr_busy = atomic_read(&sgp->nr_busy_cpus);
  5246. if (sd->flags & SD_SHARE_PKG_RESOURCES && nr_busy > 1)
  5247. goto need_kick_unlock;
  5248. if (sd->flags & SD_ASYM_PACKING && nr_busy != sg->group_weight
  5249. && (cpumask_first_and(nohz.idle_cpus_mask,
  5250. sched_domain_span(sd)) < cpu))
  5251. goto need_kick_unlock;
  5252. if (!(sd->flags & (SD_SHARE_PKG_RESOURCES | SD_ASYM_PACKING)))
  5253. break;
  5254. }
  5255. rcu_read_unlock();
  5256. return 0;
  5257. need_kick_unlock:
  5258. rcu_read_unlock();
  5259. need_kick:
  5260. return 1;
  5261. }
  5262. #else
  5263. static void nohz_idle_balance(int this_cpu, enum cpu_idle_type idle) { }
  5264. #endif
  5265. /*
  5266. * run_rebalance_domains is triggered when needed from the scheduler tick.
  5267. * Also triggered for nohz idle balancing (with nohz_balancing_kick set).
  5268. */
  5269. static void run_rebalance_domains(struct softirq_action *h)
  5270. {
  5271. int this_cpu = smp_processor_id();
  5272. struct rq *this_rq = cpu_rq(this_cpu);
  5273. enum cpu_idle_type idle = this_rq->idle_balance ?
  5274. CPU_IDLE : CPU_NOT_IDLE;
  5275. rebalance_domains(this_cpu, idle);
  5276. /*
  5277. * If this cpu has a pending nohz_balance_kick, then do the
  5278. * balancing on behalf of the other idle cpus whose ticks are
  5279. * stopped.
  5280. */
  5281. nohz_idle_balance(this_cpu, idle);
  5282. }
  5283. static inline int on_null_domain(int cpu)
  5284. {
  5285. return !rcu_dereference_sched(cpu_rq(cpu)->sd);
  5286. }
  5287. /*
  5288. * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
  5289. */
  5290. void trigger_load_balance(struct rq *rq, int cpu)
  5291. {
  5292. /* Don't need to rebalance while attached to NULL domain */
  5293. if (time_after_eq(jiffies, rq->next_balance) &&
  5294. likely(!on_null_domain(cpu)))
  5295. raise_softirq(SCHED_SOFTIRQ);
  5296. #ifdef CONFIG_NO_HZ_COMMON
  5297. if (nohz_kick_needed(rq, cpu) && likely(!on_null_domain(cpu)))
  5298. nohz_balancer_kick(cpu);
  5299. #endif
  5300. }
  5301. static void rq_online_fair(struct rq *rq)
  5302. {
  5303. update_sysctl();
  5304. }
  5305. static void rq_offline_fair(struct rq *rq)
  5306. {
  5307. update_sysctl();
  5308. /* Ensure any throttled groups are reachable by pick_next_task */
  5309. unthrottle_offline_cfs_rqs(rq);
  5310. }
  5311. #endif /* CONFIG_SMP */
  5312. /*
  5313. * scheduler tick hitting a task of our scheduling class:
  5314. */
  5315. static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)
  5316. {
  5317. struct cfs_rq *cfs_rq;
  5318. struct sched_entity *se = &curr->se;
  5319. for_each_sched_entity(se) {
  5320. cfs_rq = cfs_rq_of(se);
  5321. entity_tick(cfs_rq, se, queued);
  5322. }
  5323. if (numabalancing_enabled)
  5324. task_tick_numa(rq, curr);
  5325. update_rq_runnable_avg(rq, 1);
  5326. }
  5327. /*
  5328. * called on fork with the child task as argument from the parent's context
  5329. * - child not yet on the tasklist
  5330. * - preemption disabled
  5331. */
  5332. static void task_fork_fair(struct task_struct *p)
  5333. {
  5334. struct cfs_rq *cfs_rq;
  5335. struct sched_entity *se = &p->se, *curr;
  5336. int this_cpu = smp_processor_id();
  5337. struct rq *rq = this_rq();
  5338. unsigned long flags;
  5339. raw_spin_lock_irqsave(&rq->lock, flags);
  5340. update_rq_clock(rq);
  5341. cfs_rq = task_cfs_rq(current);
  5342. curr = cfs_rq->curr;
  5343. /*
  5344. * Not only the cpu but also the task_group of the parent might have
  5345. * been changed after parent->se.parent,cfs_rq were copied to
  5346. * child->se.parent,cfs_rq. So call __set_task_cpu() to make those
  5347. * of child point to valid ones.
  5348. */
  5349. rcu_read_lock();
  5350. __set_task_cpu(p, this_cpu);
  5351. rcu_read_unlock();
  5352. update_curr(cfs_rq);
  5353. if (curr)
  5354. se->vruntime = curr->vruntime;
  5355. place_entity(cfs_rq, se, 1);
  5356. if (sysctl_sched_child_runs_first && curr && entity_before(curr, se)) {
  5357. /*
  5358. * Upon rescheduling, sched_class::put_prev_task() will place
  5359. * 'current' within the tree based on its new key value.
  5360. */
  5361. swap(curr->vruntime, se->vruntime);
  5362. resched_task(rq->curr);
  5363. }
  5364. se->vruntime -= cfs_rq->min_vruntime;
  5365. raw_spin_unlock_irqrestore(&rq->lock, flags);
  5366. }
  5367. /*
  5368. * Priority of the task has changed. Check to see if we preempt
  5369. * the current task.
  5370. */
  5371. static void
  5372. prio_changed_fair(struct rq *rq, struct task_struct *p, int oldprio)
  5373. {
  5374. if (!p->se.on_rq)
  5375. return;
  5376. /*
  5377. * Reschedule if we are currently running on this runqueue and
  5378. * our priority decreased, or if we are not currently running on
  5379. * this runqueue and our priority is higher than the current's
  5380. */
  5381. if (rq->curr == p) {
  5382. if (p->prio > oldprio)
  5383. resched_task(rq->curr);
  5384. } else
  5385. check_preempt_curr(rq, p, 0);
  5386. }
  5387. static void switched_from_fair(struct rq *rq, struct task_struct *p)
  5388. {
  5389. struct sched_entity *se = &p->se;
  5390. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  5391. /*
  5392. * Ensure the task's vruntime is normalized, so that when its
  5393. * switched back to the fair class the enqueue_entity(.flags=0) will
  5394. * do the right thing.
  5395. *
  5396. * If it was on_rq, then the dequeue_entity(.flags=0) will already
  5397. * have normalized the vruntime, if it was !on_rq, then only when
  5398. * the task is sleeping will it still have non-normalized vruntime.
  5399. */
  5400. if (!se->on_rq && p->state != TASK_RUNNING) {
  5401. /*
  5402. * Fix up our vruntime so that the current sleep doesn't
  5403. * cause 'unlimited' sleep bonus.
  5404. */
  5405. place_entity(cfs_rq, se, 0);
  5406. se->vruntime -= cfs_rq->min_vruntime;
  5407. }
  5408. #ifdef CONFIG_SMP
  5409. /*
  5410. * Remove our load from contribution when we leave sched_fair
  5411. * and ensure we don't carry in an old decay_count if we
  5412. * switch back.
  5413. */
  5414. if (se->avg.decay_count) {
  5415. __synchronize_entity_decay(se);
  5416. subtract_blocked_load_contrib(cfs_rq, se->avg.load_avg_contrib);
  5417. }
  5418. #endif
  5419. }
  5420. /*
  5421. * We switched to the sched_fair class.
  5422. */
  5423. static void switched_to_fair(struct rq *rq, struct task_struct *p)
  5424. {
  5425. if (!p->se.on_rq)
  5426. return;
  5427. /*
  5428. * We were most likely switched from sched_rt, so
  5429. * kick off the schedule if running, otherwise just see
  5430. * if we can still preempt the current task.
  5431. */
  5432. if (rq->curr == p)
  5433. resched_task(rq->curr);
  5434. else
  5435. check_preempt_curr(rq, p, 0);
  5436. }
  5437. /* Account for a task changing its policy or group.
  5438. *
  5439. * This routine is mostly called to set cfs_rq->curr field when a task
  5440. * migrates between groups/classes.
  5441. */
  5442. static void set_curr_task_fair(struct rq *rq)
  5443. {
  5444. struct sched_entity *se = &rq->curr->se;
  5445. for_each_sched_entity(se) {
  5446. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  5447. set_next_entity(cfs_rq, se);
  5448. /* ensure bandwidth has been allocated on our new cfs_rq */
  5449. account_cfs_rq_runtime(cfs_rq, 0);
  5450. }
  5451. }
  5452. void init_cfs_rq(struct cfs_rq *cfs_rq)
  5453. {
  5454. cfs_rq->tasks_timeline = RB_ROOT;
  5455. cfs_rq->min_vruntime = (u64)(-(1LL << 20));
  5456. #ifndef CONFIG_64BIT
  5457. cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
  5458. #endif
  5459. #ifdef CONFIG_SMP
  5460. atomic64_set(&cfs_rq->decay_counter, 1);
  5461. atomic_long_set(&cfs_rq->removed_load, 0);
  5462. #endif
  5463. }
  5464. #ifdef CONFIG_FAIR_GROUP_SCHED
  5465. static void task_move_group_fair(struct task_struct *p, int on_rq)
  5466. {
  5467. struct cfs_rq *cfs_rq;
  5468. /*
  5469. * If the task was not on the rq at the time of this cgroup movement
  5470. * it must have been asleep, sleeping tasks keep their ->vruntime
  5471. * absolute on their old rq until wakeup (needed for the fair sleeper
  5472. * bonus in place_entity()).
  5473. *
  5474. * If it was on the rq, we've just 'preempted' it, which does convert
  5475. * ->vruntime to a relative base.
  5476. *
  5477. * Make sure both cases convert their relative position when migrating
  5478. * to another cgroup's rq. This does somewhat interfere with the
  5479. * fair sleeper stuff for the first placement, but who cares.
  5480. */
  5481. /*
  5482. * When !on_rq, vruntime of the task has usually NOT been normalized.
  5483. * But there are some cases where it has already been normalized:
  5484. *
  5485. * - Moving a forked child which is waiting for being woken up by
  5486. * wake_up_new_task().
  5487. * - Moving a task which has been woken up by try_to_wake_up() and
  5488. * waiting for actually being woken up by sched_ttwu_pending().
  5489. *
  5490. * To prevent boost or penalty in the new cfs_rq caused by delta
  5491. * min_vruntime between the two cfs_rqs, we skip vruntime adjustment.
  5492. */
  5493. if (!on_rq && (!p->se.sum_exec_runtime || p->state == TASK_WAKING))
  5494. on_rq = 1;
  5495. if (!on_rq)
  5496. p->se.vruntime -= cfs_rq_of(&p->se)->min_vruntime;
  5497. set_task_rq(p, task_cpu(p));
  5498. if (!on_rq) {
  5499. cfs_rq = cfs_rq_of(&p->se);
  5500. p->se.vruntime += cfs_rq->min_vruntime;
  5501. #ifdef CONFIG_SMP
  5502. /*
  5503. * migrate_task_rq_fair() will have removed our previous
  5504. * contribution, but we must synchronize for ongoing future
  5505. * decay.
  5506. */
  5507. p->se.avg.decay_count = atomic64_read(&cfs_rq->decay_counter);
  5508. cfs_rq->blocked_load_avg += p->se.avg.load_avg_contrib;
  5509. #endif
  5510. }
  5511. }
  5512. void free_fair_sched_group(struct task_group *tg)
  5513. {
  5514. int i;
  5515. destroy_cfs_bandwidth(tg_cfs_bandwidth(tg));
  5516. for_each_possible_cpu(i) {
  5517. if (tg->cfs_rq)
  5518. kfree(tg->cfs_rq[i]);
  5519. if (tg->se)
  5520. kfree(tg->se[i]);
  5521. }
  5522. kfree(tg->cfs_rq);
  5523. kfree(tg->se);
  5524. }
  5525. int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
  5526. {
  5527. struct cfs_rq *cfs_rq;
  5528. struct sched_entity *se;
  5529. int i;
  5530. tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL);
  5531. if (!tg->cfs_rq)
  5532. goto err;
  5533. tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL);
  5534. if (!tg->se)
  5535. goto err;
  5536. tg->shares = NICE_0_LOAD;
  5537. init_cfs_bandwidth(tg_cfs_bandwidth(tg));
  5538. for_each_possible_cpu(i) {
  5539. cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
  5540. GFP_KERNEL, cpu_to_node(i));
  5541. if (!cfs_rq)
  5542. goto err;
  5543. se = kzalloc_node(sizeof(struct sched_entity),
  5544. GFP_KERNEL, cpu_to_node(i));
  5545. if (!se)
  5546. goto err_free_rq;
  5547. init_cfs_rq(cfs_rq);
  5548. init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
  5549. }
  5550. return 1;
  5551. err_free_rq:
  5552. kfree(cfs_rq);
  5553. err:
  5554. return 0;
  5555. }
  5556. void unregister_fair_sched_group(struct task_group *tg, int cpu)
  5557. {
  5558. struct rq *rq = cpu_rq(cpu);
  5559. unsigned long flags;
  5560. /*
  5561. * Only empty task groups can be destroyed; so we can speculatively
  5562. * check on_list without danger of it being re-added.
  5563. */
  5564. if (!tg->cfs_rq[cpu]->on_list)
  5565. return;
  5566. raw_spin_lock_irqsave(&rq->lock, flags);
  5567. list_del_leaf_cfs_rq(tg->cfs_rq[cpu]);
  5568. raw_spin_unlock_irqrestore(&rq->lock, flags);
  5569. }
  5570. void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
  5571. struct sched_entity *se, int cpu,
  5572. struct sched_entity *parent)
  5573. {
  5574. struct rq *rq = cpu_rq(cpu);
  5575. cfs_rq->tg = tg;
  5576. cfs_rq->rq = rq;
  5577. init_cfs_rq_runtime(cfs_rq);
  5578. tg->cfs_rq[cpu] = cfs_rq;
  5579. tg->se[cpu] = se;
  5580. /* se could be NULL for root_task_group */
  5581. if (!se)
  5582. return;
  5583. if (!parent)
  5584. se->cfs_rq = &rq->cfs;
  5585. else
  5586. se->cfs_rq = parent->my_q;
  5587. se->my_q = cfs_rq;
  5588. update_load_set(&se->load, 0);
  5589. se->parent = parent;
  5590. }
  5591. static DEFINE_MUTEX(shares_mutex);
  5592. int sched_group_set_shares(struct task_group *tg, unsigned long shares)
  5593. {
  5594. int i;
  5595. unsigned long flags;
  5596. /*
  5597. * We can't change the weight of the root cgroup.
  5598. */
  5599. if (!tg->se[0])
  5600. return -EINVAL;
  5601. shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
  5602. mutex_lock(&shares_mutex);
  5603. if (tg->shares == shares)
  5604. goto done;
  5605. tg->shares = shares;
  5606. for_each_possible_cpu(i) {
  5607. struct rq *rq = cpu_rq(i);
  5608. struct sched_entity *se;
  5609. se = tg->se[i];
  5610. /* Propagate contribution to hierarchy */
  5611. raw_spin_lock_irqsave(&rq->lock, flags);
  5612. /* Possible calls to update_curr() need rq clock */
  5613. update_rq_clock(rq);
  5614. for_each_sched_entity(se)
  5615. update_cfs_shares(group_cfs_rq(se));
  5616. raw_spin_unlock_irqrestore(&rq->lock, flags);
  5617. }
  5618. done:
  5619. mutex_unlock(&shares_mutex);
  5620. return 0;
  5621. }
  5622. #else /* CONFIG_FAIR_GROUP_SCHED */
  5623. void free_fair_sched_group(struct task_group *tg) { }
  5624. int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
  5625. {
  5626. return 1;
  5627. }
  5628. void unregister_fair_sched_group(struct task_group *tg, int cpu) { }
  5629. #endif /* CONFIG_FAIR_GROUP_SCHED */
  5630. static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task)
  5631. {
  5632. struct sched_entity *se = &task->se;
  5633. unsigned int rr_interval = 0;
  5634. /*
  5635. * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
  5636. * idle runqueue:
  5637. */
  5638. if (rq->cfs.load.weight)
  5639. rr_interval = NS_TO_JIFFIES(sched_slice(cfs_rq_of(se), se));
  5640. return rr_interval;
  5641. }
  5642. /*
  5643. * All the scheduling class methods:
  5644. */
  5645. const struct sched_class fair_sched_class = {
  5646. .next = &idle_sched_class,
  5647. .enqueue_task = enqueue_task_fair,
  5648. .dequeue_task = dequeue_task_fair,
  5649. .yield_task = yield_task_fair,
  5650. .yield_to_task = yield_to_task_fair,
  5651. .check_preempt_curr = check_preempt_wakeup,
  5652. .pick_next_task = pick_next_task_fair,
  5653. .put_prev_task = put_prev_task_fair,
  5654. #ifdef CONFIG_SMP
  5655. .select_task_rq = select_task_rq_fair,
  5656. .migrate_task_rq = migrate_task_rq_fair,
  5657. .rq_online = rq_online_fair,
  5658. .rq_offline = rq_offline_fair,
  5659. .task_waking = task_waking_fair,
  5660. #endif
  5661. .set_curr_task = set_curr_task_fair,
  5662. .task_tick = task_tick_fair,
  5663. .task_fork = task_fork_fair,
  5664. .prio_changed = prio_changed_fair,
  5665. .switched_from = switched_from_fair,
  5666. .switched_to = switched_to_fair,
  5667. .get_rr_interval = get_rr_interval_fair,
  5668. #ifdef CONFIG_FAIR_GROUP_SCHED
  5669. .task_move_group = task_move_group_fair,
  5670. #endif
  5671. };
  5672. #ifdef CONFIG_SCHED_DEBUG
  5673. void print_cfs_stats(struct seq_file *m, int cpu)
  5674. {
  5675. struct cfs_rq *cfs_rq;
  5676. rcu_read_lock();
  5677. for_each_leaf_cfs_rq(cpu_rq(cpu), cfs_rq)
  5678. print_cfs_rq(m, cpu, cfs_rq);
  5679. rcu_read_unlock();
  5680. }
  5681. #endif
  5682. __init void init_sched_fair_class(void)
  5683. {
  5684. #ifdef CONFIG_SMP
  5685. open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
  5686. #ifdef CONFIG_NO_HZ_COMMON
  5687. nohz.next_balance = jiffies;
  5688. zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);
  5689. cpu_notifier(sched_ilb_notifier, 0);
  5690. #endif
  5691. #endif /* SMP */
  5692. }