fair.c 274 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Completely Fair Scheduling (CFS) Class (SCHED_NORMAL/SCHED_BATCH)
  4. *
  5. * Copyright (C) 2007 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
  6. *
  7. * Interactivity improvements by Mike Galbraith
  8. * (C) 2007 Mike Galbraith <efault@gmx.de>
  9. *
  10. * Various enhancements by Dmitry Adamushko.
  11. * (C) 2007 Dmitry Adamushko <dmitry.adamushko@gmail.com>
  12. *
  13. * Group scheduling enhancements by Srivatsa Vaddagiri
  14. * Copyright IBM Corporation, 2007
  15. * Author: Srivatsa Vaddagiri <vatsa@linux.vnet.ibm.com>
  16. *
  17. * Scaled math optimizations by Thomas Gleixner
  18. * Copyright (C) 2007, Thomas Gleixner <tglx@linutronix.de>
  19. *
  20. * Adaptive scheduling granularity, math enhancements by Peter Zijlstra
  21. * Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra
  22. */
  23. #include "sched.h"
  24. #include <trace/events/sched.h>
  25. /*
  26. * Targeted preemption latency for CPU-bound tasks:
  27. *
  28. * NOTE: this latency value is not the same as the concept of
  29. * 'timeslice length' - timeslices in CFS are of variable length
  30. * and have no persistent notion like in traditional, time-slice
  31. * based scheduling concepts.
  32. *
  33. * (to see the precise effective timeslice length of your workload,
  34. * run vmstat and monitor the context-switches (cs) field)
  35. *
  36. * (default: 6ms * (1 + ilog(ncpus)), units: nanoseconds)
  37. */
  38. unsigned int sysctl_sched_latency = 6000000ULL;
  39. unsigned int normalized_sysctl_sched_latency = 6000000ULL;
  40. /*
  41. * The initial- and re-scaling of tunables is configurable
  42. *
  43. * Options are:
  44. *
  45. * SCHED_TUNABLESCALING_NONE - unscaled, always *1
  46. * SCHED_TUNABLESCALING_LOG - scaled logarithmical, *1+ilog(ncpus)
  47. * SCHED_TUNABLESCALING_LINEAR - scaled linear, *ncpus
  48. *
  49. * (default SCHED_TUNABLESCALING_LOG = *(1+ilog(ncpus))
  50. */
  51. enum sched_tunable_scaling sysctl_sched_tunable_scaling = SCHED_TUNABLESCALING_LOG;
  52. /*
  53. * Minimal preemption granularity for CPU-bound tasks:
  54. *
  55. * (default: 0.75 msec * (1 + ilog(ncpus)), units: nanoseconds)
  56. */
  57. unsigned int sysctl_sched_min_granularity = 750000ULL;
  58. unsigned int normalized_sysctl_sched_min_granularity = 750000ULL;
  59. /*
  60. * This value is kept at sysctl_sched_latency/sysctl_sched_min_granularity
  61. */
  62. static unsigned int sched_nr_latency = 8;
  63. /*
  64. * After fork, child runs first. If set to 0 (default) then
  65. * parent will (try to) run first.
  66. */
  67. unsigned int sysctl_sched_child_runs_first __read_mostly;
  68. /*
  69. * SCHED_OTHER wake-up granularity.
  70. *
  71. * This option delays the preemption effects of decoupled workloads
  72. * and reduces their over-scheduling. Synchronous workloads will still
  73. * have immediate wakeup/sleep latencies.
  74. *
  75. * (default: 1 msec * (1 + ilog(ncpus)), units: nanoseconds)
  76. */
  77. unsigned int sysctl_sched_wakeup_granularity = 1000000UL;
  78. unsigned int normalized_sysctl_sched_wakeup_granularity = 1000000UL;
  79. const_debug unsigned int sysctl_sched_migration_cost = 500000UL;
  80. #ifdef CONFIG_SMP
  81. /*
  82. * For asym packing, by default the lower numbered CPU has higher priority.
  83. */
  84. int __weak arch_asym_cpu_priority(int cpu)
  85. {
  86. return -cpu;
  87. }
  88. #endif
  89. #ifdef CONFIG_CFS_BANDWIDTH
  90. /*
  91. * Amount of runtime to allocate from global (tg) to local (per-cfs_rq) pool
  92. * each time a cfs_rq requests quota.
  93. *
  94. * Note: in the case that the slice exceeds the runtime remaining (either due
  95. * to consumption or the quota being specified to be smaller than the slice)
  96. * we will always only issue the remaining available time.
  97. *
  98. * (default: 5 msec, units: microseconds)
  99. */
  100. unsigned int sysctl_sched_cfs_bandwidth_slice = 5000UL;
  101. #endif
  102. /*
  103. * The margin used when comparing utilization with CPU capacity:
  104. * util * margin < capacity * 1024
  105. *
  106. * (default: ~20%)
  107. */
  108. unsigned int capacity_margin = 1280;
  109. static inline void update_load_add(struct load_weight *lw, unsigned long inc)
  110. {
  111. lw->weight += inc;
  112. lw->inv_weight = 0;
  113. }
  114. static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
  115. {
  116. lw->weight -= dec;
  117. lw->inv_weight = 0;
  118. }
  119. static inline void update_load_set(struct load_weight *lw, unsigned long w)
  120. {
  121. lw->weight = w;
  122. lw->inv_weight = 0;
  123. }
  124. /*
  125. * Increase the granularity value when there are more CPUs,
  126. * because with more CPUs the 'effective latency' as visible
  127. * to users decreases. But the relationship is not linear,
  128. * so pick a second-best guess by going with the log2 of the
  129. * number of CPUs.
  130. *
  131. * This idea comes from the SD scheduler of Con Kolivas:
  132. */
  133. static unsigned int get_update_sysctl_factor(void)
  134. {
  135. unsigned int cpus = min_t(unsigned int, num_online_cpus(), 8);
  136. unsigned int factor;
  137. switch (sysctl_sched_tunable_scaling) {
  138. case SCHED_TUNABLESCALING_NONE:
  139. factor = 1;
  140. break;
  141. case SCHED_TUNABLESCALING_LINEAR:
  142. factor = cpus;
  143. break;
  144. case SCHED_TUNABLESCALING_LOG:
  145. default:
  146. factor = 1 + ilog2(cpus);
  147. break;
  148. }
  149. return factor;
  150. }
  151. static void update_sysctl(void)
  152. {
  153. unsigned int factor = get_update_sysctl_factor();
  154. #define SET_SYSCTL(name) \
  155. (sysctl_##name = (factor) * normalized_sysctl_##name)
  156. SET_SYSCTL(sched_min_granularity);
  157. SET_SYSCTL(sched_latency);
  158. SET_SYSCTL(sched_wakeup_granularity);
  159. #undef SET_SYSCTL
  160. }
  161. void sched_init_granularity(void)
  162. {
  163. update_sysctl();
  164. }
  165. #define WMULT_CONST (~0U)
  166. #define WMULT_SHIFT 32
  167. static void __update_inv_weight(struct load_weight *lw)
  168. {
  169. unsigned long w;
  170. if (likely(lw->inv_weight))
  171. return;
  172. w = scale_load_down(lw->weight);
  173. if (BITS_PER_LONG > 32 && unlikely(w >= WMULT_CONST))
  174. lw->inv_weight = 1;
  175. else if (unlikely(!w))
  176. lw->inv_weight = WMULT_CONST;
  177. else
  178. lw->inv_weight = WMULT_CONST / w;
  179. }
  180. /*
  181. * delta_exec * weight / lw.weight
  182. * OR
  183. * (delta_exec * (weight * lw->inv_weight)) >> WMULT_SHIFT
  184. *
  185. * Either weight := NICE_0_LOAD and lw \e sched_prio_to_wmult[], in which case
  186. * we're guaranteed shift stays positive because inv_weight is guaranteed to
  187. * fit 32 bits, and NICE_0_LOAD gives another 10 bits; therefore shift >= 22.
  188. *
  189. * Or, weight =< lw.weight (because lw.weight is the runqueue weight), thus
  190. * weight/lw.weight <= 1, and therefore our shift will also be positive.
  191. */
  192. static u64 __calc_delta(u64 delta_exec, unsigned long weight, struct load_weight *lw)
  193. {
  194. u64 fact = scale_load_down(weight);
  195. int shift = WMULT_SHIFT;
  196. __update_inv_weight(lw);
  197. if (unlikely(fact >> 32)) {
  198. while (fact >> 32) {
  199. fact >>= 1;
  200. shift--;
  201. }
  202. }
  203. /* hint to use a 32x32->64 mul */
  204. fact = (u64)(u32)fact * lw->inv_weight;
  205. while (fact >> 32) {
  206. fact >>= 1;
  207. shift--;
  208. }
  209. return mul_u64_u32_shr(delta_exec, fact, shift);
  210. }
  211. const struct sched_class fair_sched_class;
  212. /**************************************************************
  213. * CFS operations on generic schedulable entities:
  214. */
  215. #ifdef CONFIG_FAIR_GROUP_SCHED
  216. /* cpu runqueue to which this cfs_rq is attached */
  217. static inline struct rq *rq_of(struct cfs_rq *cfs_rq)
  218. {
  219. return cfs_rq->rq;
  220. }
  221. /* An entity is a task if it doesn't "own" a runqueue */
  222. #define entity_is_task(se) (!se->my_q)
  223. static inline struct task_struct *task_of(struct sched_entity *se)
  224. {
  225. SCHED_WARN_ON(!entity_is_task(se));
  226. return container_of(se, struct task_struct, se);
  227. }
  228. /* Walk up scheduling entities hierarchy */
  229. #define for_each_sched_entity(se) \
  230. for (; se; se = se->parent)
  231. static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
  232. {
  233. return p->se.cfs_rq;
  234. }
  235. /* runqueue on which this entity is (to be) queued */
  236. static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se)
  237. {
  238. return se->cfs_rq;
  239. }
  240. /* runqueue "owned" by this group */
  241. static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
  242. {
  243. return grp->my_q;
  244. }
  245. static inline void list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
  246. {
  247. if (!cfs_rq->on_list) {
  248. struct rq *rq = rq_of(cfs_rq);
  249. int cpu = cpu_of(rq);
  250. /*
  251. * Ensure we either appear before our parent (if already
  252. * enqueued) or force our parent to appear after us when it is
  253. * enqueued. The fact that we always enqueue bottom-up
  254. * reduces this to two cases and a special case for the root
  255. * cfs_rq. Furthermore, it also means that we will always reset
  256. * tmp_alone_branch either when the branch is connected
  257. * to a tree or when we reach the beg of the tree
  258. */
  259. if (cfs_rq->tg->parent &&
  260. cfs_rq->tg->parent->cfs_rq[cpu]->on_list) {
  261. /*
  262. * If parent is already on the list, we add the child
  263. * just before. Thanks to circular linked property of
  264. * the list, this means to put the child at the tail
  265. * of the list that starts by parent.
  266. */
  267. list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
  268. &(cfs_rq->tg->parent->cfs_rq[cpu]->leaf_cfs_rq_list));
  269. /*
  270. * The branch is now connected to its tree so we can
  271. * reset tmp_alone_branch to the beginning of the
  272. * list.
  273. */
  274. rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
  275. } else if (!cfs_rq->tg->parent) {
  276. /*
  277. * cfs rq without parent should be put
  278. * at the tail of the list.
  279. */
  280. list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
  281. &rq->leaf_cfs_rq_list);
  282. /*
  283. * We have reach the beg of a tree so we can reset
  284. * tmp_alone_branch to the beginning of the list.
  285. */
  286. rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
  287. } else {
  288. /*
  289. * The parent has not already been added so we want to
  290. * make sure that it will be put after us.
  291. * tmp_alone_branch points to the beg of the branch
  292. * where we will add parent.
  293. */
  294. list_add_rcu(&cfs_rq->leaf_cfs_rq_list,
  295. rq->tmp_alone_branch);
  296. /*
  297. * update tmp_alone_branch to points to the new beg
  298. * of the branch
  299. */
  300. rq->tmp_alone_branch = &cfs_rq->leaf_cfs_rq_list;
  301. }
  302. cfs_rq->on_list = 1;
  303. }
  304. }
  305. static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
  306. {
  307. if (cfs_rq->on_list) {
  308. list_del_rcu(&cfs_rq->leaf_cfs_rq_list);
  309. cfs_rq->on_list = 0;
  310. }
  311. }
  312. /* Iterate thr' all leaf cfs_rq's on a runqueue */
  313. #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) \
  314. list_for_each_entry_safe(cfs_rq, pos, &rq->leaf_cfs_rq_list, \
  315. leaf_cfs_rq_list)
  316. /* Do the two (enqueued) entities belong to the same group ? */
  317. static inline struct cfs_rq *
  318. is_same_group(struct sched_entity *se, struct sched_entity *pse)
  319. {
  320. if (se->cfs_rq == pse->cfs_rq)
  321. return se->cfs_rq;
  322. return NULL;
  323. }
  324. static inline struct sched_entity *parent_entity(struct sched_entity *se)
  325. {
  326. return se->parent;
  327. }
  328. static void
  329. find_matching_se(struct sched_entity **se, struct sched_entity **pse)
  330. {
  331. int se_depth, pse_depth;
  332. /*
  333. * preemption test can be made between sibling entities who are in the
  334. * same cfs_rq i.e who have a common parent. Walk up the hierarchy of
  335. * both tasks until we find their ancestors who are siblings of common
  336. * parent.
  337. */
  338. /* First walk up until both entities are at same depth */
  339. se_depth = (*se)->depth;
  340. pse_depth = (*pse)->depth;
  341. while (se_depth > pse_depth) {
  342. se_depth--;
  343. *se = parent_entity(*se);
  344. }
  345. while (pse_depth > se_depth) {
  346. pse_depth--;
  347. *pse = parent_entity(*pse);
  348. }
  349. while (!is_same_group(*se, *pse)) {
  350. *se = parent_entity(*se);
  351. *pse = parent_entity(*pse);
  352. }
  353. }
  354. #else /* !CONFIG_FAIR_GROUP_SCHED */
  355. static inline struct task_struct *task_of(struct sched_entity *se)
  356. {
  357. return container_of(se, struct task_struct, se);
  358. }
  359. static inline struct rq *rq_of(struct cfs_rq *cfs_rq)
  360. {
  361. return container_of(cfs_rq, struct rq, cfs);
  362. }
  363. #define entity_is_task(se) 1
  364. #define for_each_sched_entity(se) \
  365. for (; se; se = NULL)
  366. static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
  367. {
  368. return &task_rq(p)->cfs;
  369. }
  370. static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se)
  371. {
  372. struct task_struct *p = task_of(se);
  373. struct rq *rq = task_rq(p);
  374. return &rq->cfs;
  375. }
  376. /* runqueue "owned" by this group */
  377. static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
  378. {
  379. return NULL;
  380. }
  381. static inline void list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
  382. {
  383. }
  384. static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
  385. {
  386. }
  387. #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) \
  388. for (cfs_rq = &rq->cfs, pos = NULL; cfs_rq; cfs_rq = pos)
  389. static inline struct sched_entity *parent_entity(struct sched_entity *se)
  390. {
  391. return NULL;
  392. }
  393. static inline void
  394. find_matching_se(struct sched_entity **se, struct sched_entity **pse)
  395. {
  396. }
  397. #endif /* CONFIG_FAIR_GROUP_SCHED */
  398. static __always_inline
  399. void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec);
  400. /**************************************************************
  401. * Scheduling class tree data structure manipulation methods:
  402. */
  403. static inline u64 max_vruntime(u64 max_vruntime, u64 vruntime)
  404. {
  405. s64 delta = (s64)(vruntime - max_vruntime);
  406. if (delta > 0)
  407. max_vruntime = vruntime;
  408. return max_vruntime;
  409. }
  410. static inline u64 min_vruntime(u64 min_vruntime, u64 vruntime)
  411. {
  412. s64 delta = (s64)(vruntime - min_vruntime);
  413. if (delta < 0)
  414. min_vruntime = vruntime;
  415. return min_vruntime;
  416. }
  417. static inline int entity_before(struct sched_entity *a,
  418. struct sched_entity *b)
  419. {
  420. return (s64)(a->vruntime - b->vruntime) < 0;
  421. }
  422. static void update_min_vruntime(struct cfs_rq *cfs_rq)
  423. {
  424. struct sched_entity *curr = cfs_rq->curr;
  425. struct rb_node *leftmost = rb_first_cached(&cfs_rq->tasks_timeline);
  426. u64 vruntime = cfs_rq->min_vruntime;
  427. if (curr) {
  428. if (curr->on_rq)
  429. vruntime = curr->vruntime;
  430. else
  431. curr = NULL;
  432. }
  433. if (leftmost) { /* non-empty tree */
  434. struct sched_entity *se;
  435. se = rb_entry(leftmost, struct sched_entity, run_node);
  436. if (!curr)
  437. vruntime = se->vruntime;
  438. else
  439. vruntime = min_vruntime(vruntime, se->vruntime);
  440. }
  441. /* ensure we never gain time by being placed backwards. */
  442. cfs_rq->min_vruntime = max_vruntime(cfs_rq->min_vruntime, vruntime);
  443. #ifndef CONFIG_64BIT
  444. smp_wmb();
  445. cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
  446. #endif
  447. }
  448. /*
  449. * Enqueue an entity into the rb-tree:
  450. */
  451. static void __enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
  452. {
  453. struct rb_node **link = &cfs_rq->tasks_timeline.rb_root.rb_node;
  454. struct rb_node *parent = NULL;
  455. struct sched_entity *entry;
  456. bool leftmost = true;
  457. /*
  458. * Find the right place in the rbtree:
  459. */
  460. while (*link) {
  461. parent = *link;
  462. entry = rb_entry(parent, struct sched_entity, run_node);
  463. /*
  464. * We dont care about collisions. Nodes with
  465. * the same key stay together.
  466. */
  467. if (entity_before(se, entry)) {
  468. link = &parent->rb_left;
  469. } else {
  470. link = &parent->rb_right;
  471. leftmost = false;
  472. }
  473. }
  474. rb_link_node(&se->run_node, parent, link);
  475. rb_insert_color_cached(&se->run_node,
  476. &cfs_rq->tasks_timeline, leftmost);
  477. }
  478. static void __dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
  479. {
  480. rb_erase_cached(&se->run_node, &cfs_rq->tasks_timeline);
  481. }
  482. struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq)
  483. {
  484. struct rb_node *left = rb_first_cached(&cfs_rq->tasks_timeline);
  485. if (!left)
  486. return NULL;
  487. return rb_entry(left, struct sched_entity, run_node);
  488. }
  489. static struct sched_entity *__pick_next_entity(struct sched_entity *se)
  490. {
  491. struct rb_node *next = rb_next(&se->run_node);
  492. if (!next)
  493. return NULL;
  494. return rb_entry(next, struct sched_entity, run_node);
  495. }
  496. #ifdef CONFIG_SCHED_DEBUG
  497. struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq)
  498. {
  499. struct rb_node *last = rb_last(&cfs_rq->tasks_timeline.rb_root);
  500. if (!last)
  501. return NULL;
  502. return rb_entry(last, struct sched_entity, run_node);
  503. }
  504. /**************************************************************
  505. * Scheduling class statistics methods:
  506. */
  507. int sched_proc_update_handler(struct ctl_table *table, int write,
  508. void __user *buffer, size_t *lenp,
  509. loff_t *ppos)
  510. {
  511. int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
  512. unsigned int factor = get_update_sysctl_factor();
  513. if (ret || !write)
  514. return ret;
  515. sched_nr_latency = DIV_ROUND_UP(sysctl_sched_latency,
  516. sysctl_sched_min_granularity);
  517. #define WRT_SYSCTL(name) \
  518. (normalized_sysctl_##name = sysctl_##name / (factor))
  519. WRT_SYSCTL(sched_min_granularity);
  520. WRT_SYSCTL(sched_latency);
  521. WRT_SYSCTL(sched_wakeup_granularity);
  522. #undef WRT_SYSCTL
  523. return 0;
  524. }
  525. #endif
  526. /*
  527. * delta /= w
  528. */
  529. static inline u64 calc_delta_fair(u64 delta, struct sched_entity *se)
  530. {
  531. if (unlikely(se->load.weight != NICE_0_LOAD))
  532. delta = __calc_delta(delta, NICE_0_LOAD, &se->load);
  533. return delta;
  534. }
  535. /*
  536. * The idea is to set a period in which each task runs once.
  537. *
  538. * When there are too many tasks (sched_nr_latency) we have to stretch
  539. * this period because otherwise the slices get too small.
  540. *
  541. * p = (nr <= nl) ? l : l*nr/nl
  542. */
  543. static u64 __sched_period(unsigned long nr_running)
  544. {
  545. if (unlikely(nr_running > sched_nr_latency))
  546. return nr_running * sysctl_sched_min_granularity;
  547. else
  548. return sysctl_sched_latency;
  549. }
  550. /*
  551. * We calculate the wall-time slice from the period by taking a part
  552. * proportional to the weight.
  553. *
  554. * s = p*P[w/rw]
  555. */
  556. static u64 sched_slice(struct cfs_rq *cfs_rq, struct sched_entity *se)
  557. {
  558. u64 slice = __sched_period(cfs_rq->nr_running + !se->on_rq);
  559. for_each_sched_entity(se) {
  560. struct load_weight *load;
  561. struct load_weight lw;
  562. cfs_rq = cfs_rq_of(se);
  563. load = &cfs_rq->load;
  564. if (unlikely(!se->on_rq)) {
  565. lw = cfs_rq->load;
  566. update_load_add(&lw, se->load.weight);
  567. load = &lw;
  568. }
  569. slice = __calc_delta(slice, se->load.weight, load);
  570. }
  571. return slice;
  572. }
  573. /*
  574. * We calculate the vruntime slice of a to-be-inserted task.
  575. *
  576. * vs = s/w
  577. */
  578. static u64 sched_vslice(struct cfs_rq *cfs_rq, struct sched_entity *se)
  579. {
  580. return calc_delta_fair(sched_slice(cfs_rq, se), se);
  581. }
  582. #ifdef CONFIG_SMP
  583. #include "sched-pelt.h"
  584. static int select_idle_sibling(struct task_struct *p, int prev_cpu, int cpu);
  585. static unsigned long task_h_load(struct task_struct *p);
  586. /* Give new sched_entity start runnable values to heavy its load in infant time */
  587. void init_entity_runnable_average(struct sched_entity *se)
  588. {
  589. struct sched_avg *sa = &se->avg;
  590. memset(sa, 0, sizeof(*sa));
  591. /*
  592. * Tasks are intialized with full load to be seen as heavy tasks until
  593. * they get a chance to stabilize to their real load level.
  594. * Group entities are intialized with zero load to reflect the fact that
  595. * nothing has been attached to the task group yet.
  596. */
  597. if (entity_is_task(se))
  598. sa->runnable_load_avg = sa->load_avg = scale_load_down(se->load.weight);
  599. se->runnable_weight = se->load.weight;
  600. /* when this task enqueue'ed, it will contribute to its cfs_rq's load_avg */
  601. }
  602. static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq);
  603. static void attach_entity_cfs_rq(struct sched_entity *se);
  604. /*
  605. * With new tasks being created, their initial util_avgs are extrapolated
  606. * based on the cfs_rq's current util_avg:
  607. *
  608. * util_avg = cfs_rq->util_avg / (cfs_rq->load_avg + 1) * se.load.weight
  609. *
  610. * However, in many cases, the above util_avg does not give a desired
  611. * value. Moreover, the sum of the util_avgs may be divergent, such
  612. * as when the series is a harmonic series.
  613. *
  614. * To solve this problem, we also cap the util_avg of successive tasks to
  615. * only 1/2 of the left utilization budget:
  616. *
  617. * util_avg_cap = (1024 - cfs_rq->avg.util_avg) / 2^n
  618. *
  619. * where n denotes the nth task.
  620. *
  621. * For example, a simplest series from the beginning would be like:
  622. *
  623. * task util_avg: 512, 256, 128, 64, 32, 16, 8, ...
  624. * cfs_rq util_avg: 512, 768, 896, 960, 992, 1008, 1016, ...
  625. *
  626. * Finally, that extrapolated util_avg is clamped to the cap (util_avg_cap)
  627. * if util_avg > util_avg_cap.
  628. */
  629. void post_init_entity_util_avg(struct sched_entity *se)
  630. {
  631. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  632. struct sched_avg *sa = &se->avg;
  633. long cap = (long)(SCHED_CAPACITY_SCALE - cfs_rq->avg.util_avg) / 2;
  634. if (cap > 0) {
  635. if (cfs_rq->avg.util_avg != 0) {
  636. sa->util_avg = cfs_rq->avg.util_avg * se->load.weight;
  637. sa->util_avg /= (cfs_rq->avg.load_avg + 1);
  638. if (sa->util_avg > cap)
  639. sa->util_avg = cap;
  640. } else {
  641. sa->util_avg = cap;
  642. }
  643. }
  644. if (entity_is_task(se)) {
  645. struct task_struct *p = task_of(se);
  646. if (p->sched_class != &fair_sched_class) {
  647. /*
  648. * For !fair tasks do:
  649. *
  650. update_cfs_rq_load_avg(now, cfs_rq);
  651. attach_entity_load_avg(cfs_rq, se, 0);
  652. switched_from_fair(rq, p);
  653. *
  654. * such that the next switched_to_fair() has the
  655. * expected state.
  656. */
  657. se->avg.last_update_time = cfs_rq_clock_task(cfs_rq);
  658. return;
  659. }
  660. }
  661. attach_entity_cfs_rq(se);
  662. }
  663. #else /* !CONFIG_SMP */
  664. void init_entity_runnable_average(struct sched_entity *se)
  665. {
  666. }
  667. void post_init_entity_util_avg(struct sched_entity *se)
  668. {
  669. }
  670. static void update_tg_load_avg(struct cfs_rq *cfs_rq, int force)
  671. {
  672. }
  673. #endif /* CONFIG_SMP */
  674. /*
  675. * Update the current task's runtime statistics.
  676. */
  677. static void update_curr(struct cfs_rq *cfs_rq)
  678. {
  679. struct sched_entity *curr = cfs_rq->curr;
  680. u64 now = rq_clock_task(rq_of(cfs_rq));
  681. u64 delta_exec;
  682. if (unlikely(!curr))
  683. return;
  684. delta_exec = now - curr->exec_start;
  685. if (unlikely((s64)delta_exec <= 0))
  686. return;
  687. curr->exec_start = now;
  688. schedstat_set(curr->statistics.exec_max,
  689. max(delta_exec, curr->statistics.exec_max));
  690. curr->sum_exec_runtime += delta_exec;
  691. schedstat_add(cfs_rq->exec_clock, delta_exec);
  692. curr->vruntime += calc_delta_fair(delta_exec, curr);
  693. update_min_vruntime(cfs_rq);
  694. if (entity_is_task(curr)) {
  695. struct task_struct *curtask = task_of(curr);
  696. trace_sched_stat_runtime(curtask, delta_exec, curr->vruntime);
  697. cgroup_account_cputime(curtask, delta_exec);
  698. account_group_exec_runtime(curtask, delta_exec);
  699. }
  700. account_cfs_rq_runtime(cfs_rq, delta_exec);
  701. }
  702. static void update_curr_fair(struct rq *rq)
  703. {
  704. update_curr(cfs_rq_of(&rq->curr->se));
  705. }
  706. static inline void
  707. update_stats_wait_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
  708. {
  709. u64 wait_start, prev_wait_start;
  710. if (!schedstat_enabled())
  711. return;
  712. wait_start = rq_clock(rq_of(cfs_rq));
  713. prev_wait_start = schedstat_val(se->statistics.wait_start);
  714. if (entity_is_task(se) && task_on_rq_migrating(task_of(se)) &&
  715. likely(wait_start > prev_wait_start))
  716. wait_start -= prev_wait_start;
  717. __schedstat_set(se->statistics.wait_start, wait_start);
  718. }
  719. static inline void
  720. update_stats_wait_end(struct cfs_rq *cfs_rq, struct sched_entity *se)
  721. {
  722. struct task_struct *p;
  723. u64 delta;
  724. if (!schedstat_enabled())
  725. return;
  726. delta = rq_clock(rq_of(cfs_rq)) - schedstat_val(se->statistics.wait_start);
  727. if (entity_is_task(se)) {
  728. p = task_of(se);
  729. if (task_on_rq_migrating(p)) {
  730. /*
  731. * Preserve migrating task's wait time so wait_start
  732. * time stamp can be adjusted to accumulate wait time
  733. * prior to migration.
  734. */
  735. __schedstat_set(se->statistics.wait_start, delta);
  736. return;
  737. }
  738. trace_sched_stat_wait(p, delta);
  739. }
  740. __schedstat_set(se->statistics.wait_max,
  741. max(schedstat_val(se->statistics.wait_max), delta));
  742. __schedstat_inc(se->statistics.wait_count);
  743. __schedstat_add(se->statistics.wait_sum, delta);
  744. __schedstat_set(se->statistics.wait_start, 0);
  745. }
  746. static inline void
  747. update_stats_enqueue_sleeper(struct cfs_rq *cfs_rq, struct sched_entity *se)
  748. {
  749. struct task_struct *tsk = NULL;
  750. u64 sleep_start, block_start;
  751. if (!schedstat_enabled())
  752. return;
  753. sleep_start = schedstat_val(se->statistics.sleep_start);
  754. block_start = schedstat_val(se->statistics.block_start);
  755. if (entity_is_task(se))
  756. tsk = task_of(se);
  757. if (sleep_start) {
  758. u64 delta = rq_clock(rq_of(cfs_rq)) - sleep_start;
  759. if ((s64)delta < 0)
  760. delta = 0;
  761. if (unlikely(delta > schedstat_val(se->statistics.sleep_max)))
  762. __schedstat_set(se->statistics.sleep_max, delta);
  763. __schedstat_set(se->statistics.sleep_start, 0);
  764. __schedstat_add(se->statistics.sum_sleep_runtime, delta);
  765. if (tsk) {
  766. account_scheduler_latency(tsk, delta >> 10, 1);
  767. trace_sched_stat_sleep(tsk, delta);
  768. }
  769. }
  770. if (block_start) {
  771. u64 delta = rq_clock(rq_of(cfs_rq)) - block_start;
  772. if ((s64)delta < 0)
  773. delta = 0;
  774. if (unlikely(delta > schedstat_val(se->statistics.block_max)))
  775. __schedstat_set(se->statistics.block_max, delta);
  776. __schedstat_set(se->statistics.block_start, 0);
  777. __schedstat_add(se->statistics.sum_sleep_runtime, delta);
  778. if (tsk) {
  779. if (tsk->in_iowait) {
  780. __schedstat_add(se->statistics.iowait_sum, delta);
  781. __schedstat_inc(se->statistics.iowait_count);
  782. trace_sched_stat_iowait(tsk, delta);
  783. }
  784. trace_sched_stat_blocked(tsk, delta);
  785. /*
  786. * Blocking time is in units of nanosecs, so shift by
  787. * 20 to get a milliseconds-range estimation of the
  788. * amount of time that the task spent sleeping:
  789. */
  790. if (unlikely(prof_on == SLEEP_PROFILING)) {
  791. profile_hits(SLEEP_PROFILING,
  792. (void *)get_wchan(tsk),
  793. delta >> 20);
  794. }
  795. account_scheduler_latency(tsk, delta >> 10, 0);
  796. }
  797. }
  798. }
  799. /*
  800. * Task is being enqueued - update stats:
  801. */
  802. static inline void
  803. update_stats_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
  804. {
  805. if (!schedstat_enabled())
  806. return;
  807. /*
  808. * Are we enqueueing a waiting task? (for current tasks
  809. * a dequeue/enqueue event is a NOP)
  810. */
  811. if (se != cfs_rq->curr)
  812. update_stats_wait_start(cfs_rq, se);
  813. if (flags & ENQUEUE_WAKEUP)
  814. update_stats_enqueue_sleeper(cfs_rq, se);
  815. }
  816. static inline void
  817. update_stats_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
  818. {
  819. if (!schedstat_enabled())
  820. return;
  821. /*
  822. * Mark the end of the wait period if dequeueing a
  823. * waiting task:
  824. */
  825. if (se != cfs_rq->curr)
  826. update_stats_wait_end(cfs_rq, se);
  827. if ((flags & DEQUEUE_SLEEP) && entity_is_task(se)) {
  828. struct task_struct *tsk = task_of(se);
  829. if (tsk->state & TASK_INTERRUPTIBLE)
  830. __schedstat_set(se->statistics.sleep_start,
  831. rq_clock(rq_of(cfs_rq)));
  832. if (tsk->state & TASK_UNINTERRUPTIBLE)
  833. __schedstat_set(se->statistics.block_start,
  834. rq_clock(rq_of(cfs_rq)));
  835. }
  836. }
  837. /*
  838. * We are picking a new current task - update its stats:
  839. */
  840. static inline void
  841. update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
  842. {
  843. /*
  844. * We are starting a new run period:
  845. */
  846. se->exec_start = rq_clock_task(rq_of(cfs_rq));
  847. }
  848. /**************************************************
  849. * Scheduling class queueing methods:
  850. */
  851. #ifdef CONFIG_NUMA_BALANCING
  852. /*
  853. * Approximate time to scan a full NUMA task in ms. The task scan period is
  854. * calculated based on the tasks virtual memory size and
  855. * numa_balancing_scan_size.
  856. */
  857. unsigned int sysctl_numa_balancing_scan_period_min = 1000;
  858. unsigned int sysctl_numa_balancing_scan_period_max = 60000;
  859. /* Portion of address space to scan in MB */
  860. unsigned int sysctl_numa_balancing_scan_size = 256;
  861. /* Scan @scan_size MB every @scan_period after an initial @scan_delay in ms */
  862. unsigned int sysctl_numa_balancing_scan_delay = 1000;
  863. struct numa_group {
  864. atomic_t refcount;
  865. spinlock_t lock; /* nr_tasks, tasks */
  866. int nr_tasks;
  867. pid_t gid;
  868. int active_nodes;
  869. struct rcu_head rcu;
  870. unsigned long total_faults;
  871. unsigned long max_faults_cpu;
  872. /*
  873. * Faults_cpu is used to decide whether memory should move
  874. * towards the CPU. As a consequence, these stats are weighted
  875. * more by CPU use than by memory faults.
  876. */
  877. unsigned long *faults_cpu;
  878. unsigned long faults[0];
  879. };
  880. static inline unsigned long group_faults_priv(struct numa_group *ng);
  881. static inline unsigned long group_faults_shared(struct numa_group *ng);
  882. static unsigned int task_nr_scan_windows(struct task_struct *p)
  883. {
  884. unsigned long rss = 0;
  885. unsigned long nr_scan_pages;
  886. /*
  887. * Calculations based on RSS as non-present and empty pages are skipped
  888. * by the PTE scanner and NUMA hinting faults should be trapped based
  889. * on resident pages
  890. */
  891. nr_scan_pages = sysctl_numa_balancing_scan_size << (20 - PAGE_SHIFT);
  892. rss = get_mm_rss(p->mm);
  893. if (!rss)
  894. rss = nr_scan_pages;
  895. rss = round_up(rss, nr_scan_pages);
  896. return rss / nr_scan_pages;
  897. }
  898. /* For sanitys sake, never scan more PTEs than MAX_SCAN_WINDOW MB/sec. */
  899. #define MAX_SCAN_WINDOW 2560
  900. static unsigned int task_scan_min(struct task_struct *p)
  901. {
  902. unsigned int scan_size = READ_ONCE(sysctl_numa_balancing_scan_size);
  903. unsigned int scan, floor;
  904. unsigned int windows = 1;
  905. if (scan_size < MAX_SCAN_WINDOW)
  906. windows = MAX_SCAN_WINDOW / scan_size;
  907. floor = 1000 / windows;
  908. scan = sysctl_numa_balancing_scan_period_min / task_nr_scan_windows(p);
  909. return max_t(unsigned int, floor, scan);
  910. }
  911. static unsigned int task_scan_start(struct task_struct *p)
  912. {
  913. unsigned long smin = task_scan_min(p);
  914. unsigned long period = smin;
  915. /* Scale the maximum scan period with the amount of shared memory. */
  916. if (p->numa_group) {
  917. struct numa_group *ng = p->numa_group;
  918. unsigned long shared = group_faults_shared(ng);
  919. unsigned long private = group_faults_priv(ng);
  920. period *= atomic_read(&ng->refcount);
  921. period *= shared + 1;
  922. period /= private + shared + 1;
  923. }
  924. return max(smin, period);
  925. }
  926. static unsigned int task_scan_max(struct task_struct *p)
  927. {
  928. unsigned long smin = task_scan_min(p);
  929. unsigned long smax;
  930. /* Watch for min being lower than max due to floor calculations */
  931. smax = sysctl_numa_balancing_scan_period_max / task_nr_scan_windows(p);
  932. /* Scale the maximum scan period with the amount of shared memory. */
  933. if (p->numa_group) {
  934. struct numa_group *ng = p->numa_group;
  935. unsigned long shared = group_faults_shared(ng);
  936. unsigned long private = group_faults_priv(ng);
  937. unsigned long period = smax;
  938. period *= atomic_read(&ng->refcount);
  939. period *= shared + 1;
  940. period /= private + shared + 1;
  941. smax = max(smax, period);
  942. }
  943. return max(smin, smax);
  944. }
  945. static void account_numa_enqueue(struct rq *rq, struct task_struct *p)
  946. {
  947. rq->nr_numa_running += (p->numa_preferred_nid != -1);
  948. rq->nr_preferred_running += (p->numa_preferred_nid == task_node(p));
  949. }
  950. static void account_numa_dequeue(struct rq *rq, struct task_struct *p)
  951. {
  952. rq->nr_numa_running -= (p->numa_preferred_nid != -1);
  953. rq->nr_preferred_running -= (p->numa_preferred_nid == task_node(p));
  954. }
  955. /* Shared or private faults. */
  956. #define NR_NUMA_HINT_FAULT_TYPES 2
  957. /* Memory and CPU locality */
  958. #define NR_NUMA_HINT_FAULT_STATS (NR_NUMA_HINT_FAULT_TYPES * 2)
  959. /* Averaged statistics, and temporary buffers. */
  960. #define NR_NUMA_HINT_FAULT_BUCKETS (NR_NUMA_HINT_FAULT_STATS * 2)
  961. pid_t task_numa_group_id(struct task_struct *p)
  962. {
  963. return p->numa_group ? p->numa_group->gid : 0;
  964. }
  965. /*
  966. * The averaged statistics, shared & private, memory & CPU,
  967. * occupy the first half of the array. The second half of the
  968. * array is for current counters, which are averaged into the
  969. * first set by task_numa_placement.
  970. */
  971. static inline int task_faults_idx(enum numa_faults_stats s, int nid, int priv)
  972. {
  973. return NR_NUMA_HINT_FAULT_TYPES * (s * nr_node_ids + nid) + priv;
  974. }
  975. static inline unsigned long task_faults(struct task_struct *p, int nid)
  976. {
  977. if (!p->numa_faults)
  978. return 0;
  979. return p->numa_faults[task_faults_idx(NUMA_MEM, nid, 0)] +
  980. p->numa_faults[task_faults_idx(NUMA_MEM, nid, 1)];
  981. }
  982. static inline unsigned long group_faults(struct task_struct *p, int nid)
  983. {
  984. if (!p->numa_group)
  985. return 0;
  986. return p->numa_group->faults[task_faults_idx(NUMA_MEM, nid, 0)] +
  987. p->numa_group->faults[task_faults_idx(NUMA_MEM, nid, 1)];
  988. }
  989. static inline unsigned long group_faults_cpu(struct numa_group *group, int nid)
  990. {
  991. return group->faults_cpu[task_faults_idx(NUMA_MEM, nid, 0)] +
  992. group->faults_cpu[task_faults_idx(NUMA_MEM, nid, 1)];
  993. }
  994. static inline unsigned long group_faults_priv(struct numa_group *ng)
  995. {
  996. unsigned long faults = 0;
  997. int node;
  998. for_each_online_node(node) {
  999. faults += ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
  1000. }
  1001. return faults;
  1002. }
  1003. static inline unsigned long group_faults_shared(struct numa_group *ng)
  1004. {
  1005. unsigned long faults = 0;
  1006. int node;
  1007. for_each_online_node(node) {
  1008. faults += ng->faults[task_faults_idx(NUMA_MEM, node, 0)];
  1009. }
  1010. return faults;
  1011. }
  1012. /*
  1013. * A node triggering more than 1/3 as many NUMA faults as the maximum is
  1014. * considered part of a numa group's pseudo-interleaving set. Migrations
  1015. * between these nodes are slowed down, to allow things to settle down.
  1016. */
  1017. #define ACTIVE_NODE_FRACTION 3
  1018. static bool numa_is_active_node(int nid, struct numa_group *ng)
  1019. {
  1020. return group_faults_cpu(ng, nid) * ACTIVE_NODE_FRACTION > ng->max_faults_cpu;
  1021. }
  1022. /* Handle placement on systems where not all nodes are directly connected. */
  1023. static unsigned long score_nearby_nodes(struct task_struct *p, int nid,
  1024. int maxdist, bool task)
  1025. {
  1026. unsigned long score = 0;
  1027. int node;
  1028. /*
  1029. * All nodes are directly connected, and the same distance
  1030. * from each other. No need for fancy placement algorithms.
  1031. */
  1032. if (sched_numa_topology_type == NUMA_DIRECT)
  1033. return 0;
  1034. /*
  1035. * This code is called for each node, introducing N^2 complexity,
  1036. * which should be ok given the number of nodes rarely exceeds 8.
  1037. */
  1038. for_each_online_node(node) {
  1039. unsigned long faults;
  1040. int dist = node_distance(nid, node);
  1041. /*
  1042. * The furthest away nodes in the system are not interesting
  1043. * for placement; nid was already counted.
  1044. */
  1045. if (dist == sched_max_numa_distance || node == nid)
  1046. continue;
  1047. /*
  1048. * On systems with a backplane NUMA topology, compare groups
  1049. * of nodes, and move tasks towards the group with the most
  1050. * memory accesses. When comparing two nodes at distance
  1051. * "hoplimit", only nodes closer by than "hoplimit" are part
  1052. * of each group. Skip other nodes.
  1053. */
  1054. if (sched_numa_topology_type == NUMA_BACKPLANE &&
  1055. dist > maxdist)
  1056. continue;
  1057. /* Add up the faults from nearby nodes. */
  1058. if (task)
  1059. faults = task_faults(p, node);
  1060. else
  1061. faults = group_faults(p, node);
  1062. /*
  1063. * On systems with a glueless mesh NUMA topology, there are
  1064. * no fixed "groups of nodes". Instead, nodes that are not
  1065. * directly connected bounce traffic through intermediate
  1066. * nodes; a numa_group can occupy any set of nodes.
  1067. * The further away a node is, the less the faults count.
  1068. * This seems to result in good task placement.
  1069. */
  1070. if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
  1071. faults *= (sched_max_numa_distance - dist);
  1072. faults /= (sched_max_numa_distance - LOCAL_DISTANCE);
  1073. }
  1074. score += faults;
  1075. }
  1076. return score;
  1077. }
  1078. /*
  1079. * These return the fraction of accesses done by a particular task, or
  1080. * task group, on a particular numa node. The group weight is given a
  1081. * larger multiplier, in order to group tasks together that are almost
  1082. * evenly spread out between numa nodes.
  1083. */
  1084. static inline unsigned long task_weight(struct task_struct *p, int nid,
  1085. int dist)
  1086. {
  1087. unsigned long faults, total_faults;
  1088. if (!p->numa_faults)
  1089. return 0;
  1090. total_faults = p->total_numa_faults;
  1091. if (!total_faults)
  1092. return 0;
  1093. faults = task_faults(p, nid);
  1094. faults += score_nearby_nodes(p, nid, dist, true);
  1095. return 1000 * faults / total_faults;
  1096. }
  1097. static inline unsigned long group_weight(struct task_struct *p, int nid,
  1098. int dist)
  1099. {
  1100. unsigned long faults, total_faults;
  1101. if (!p->numa_group)
  1102. return 0;
  1103. total_faults = p->numa_group->total_faults;
  1104. if (!total_faults)
  1105. return 0;
  1106. faults = group_faults(p, nid);
  1107. faults += score_nearby_nodes(p, nid, dist, false);
  1108. return 1000 * faults / total_faults;
  1109. }
  1110. bool should_numa_migrate_memory(struct task_struct *p, struct page * page,
  1111. int src_nid, int dst_cpu)
  1112. {
  1113. struct numa_group *ng = p->numa_group;
  1114. int dst_nid = cpu_to_node(dst_cpu);
  1115. int last_cpupid, this_cpupid;
  1116. this_cpupid = cpu_pid_to_cpupid(dst_cpu, current->pid);
  1117. /*
  1118. * Multi-stage node selection is used in conjunction with a periodic
  1119. * migration fault to build a temporal task<->page relation. By using
  1120. * a two-stage filter we remove short/unlikely relations.
  1121. *
  1122. * Using P(p) ~ n_p / n_t as per frequentist probability, we can equate
  1123. * a task's usage of a particular page (n_p) per total usage of this
  1124. * page (n_t) (in a given time-span) to a probability.
  1125. *
  1126. * Our periodic faults will sample this probability and getting the
  1127. * same result twice in a row, given these samples are fully
  1128. * independent, is then given by P(n)^2, provided our sample period
  1129. * is sufficiently short compared to the usage pattern.
  1130. *
  1131. * This quadric squishes small probabilities, making it less likely we
  1132. * act on an unlikely task<->page relation.
  1133. */
  1134. last_cpupid = page_cpupid_xchg_last(page, this_cpupid);
  1135. if (!cpupid_pid_unset(last_cpupid) &&
  1136. cpupid_to_nid(last_cpupid) != dst_nid)
  1137. return false;
  1138. /* Always allow migrate on private faults */
  1139. if (cpupid_match_pid(p, last_cpupid))
  1140. return true;
  1141. /* A shared fault, but p->numa_group has not been set up yet. */
  1142. if (!ng)
  1143. return true;
  1144. /*
  1145. * Destination node is much more heavily used than the source
  1146. * node? Allow migration.
  1147. */
  1148. if (group_faults_cpu(ng, dst_nid) > group_faults_cpu(ng, src_nid) *
  1149. ACTIVE_NODE_FRACTION)
  1150. return true;
  1151. /*
  1152. * Distribute memory according to CPU & memory use on each node,
  1153. * with 3/4 hysteresis to avoid unnecessary memory migrations:
  1154. *
  1155. * faults_cpu(dst) 3 faults_cpu(src)
  1156. * --------------- * - > ---------------
  1157. * faults_mem(dst) 4 faults_mem(src)
  1158. */
  1159. return group_faults_cpu(ng, dst_nid) * group_faults(p, src_nid) * 3 >
  1160. group_faults_cpu(ng, src_nid) * group_faults(p, dst_nid) * 4;
  1161. }
  1162. static unsigned long weighted_cpuload(struct rq *rq);
  1163. static unsigned long source_load(int cpu, int type);
  1164. static unsigned long target_load(int cpu, int type);
  1165. static unsigned long capacity_of(int cpu);
  1166. /* Cached statistics for all CPUs within a node */
  1167. struct numa_stats {
  1168. unsigned long nr_running;
  1169. unsigned long load;
  1170. /* Total compute capacity of CPUs on a node */
  1171. unsigned long compute_capacity;
  1172. /* Approximate capacity in terms of runnable tasks on a node */
  1173. unsigned long task_capacity;
  1174. int has_free_capacity;
  1175. };
  1176. /*
  1177. * XXX borrowed from update_sg_lb_stats
  1178. */
  1179. static void update_numa_stats(struct numa_stats *ns, int nid)
  1180. {
  1181. int smt, cpu, cpus = 0;
  1182. unsigned long capacity;
  1183. memset(ns, 0, sizeof(*ns));
  1184. for_each_cpu(cpu, cpumask_of_node(nid)) {
  1185. struct rq *rq = cpu_rq(cpu);
  1186. ns->nr_running += rq->nr_running;
  1187. ns->load += weighted_cpuload(rq);
  1188. ns->compute_capacity += capacity_of(cpu);
  1189. cpus++;
  1190. }
  1191. /*
  1192. * If we raced with hotplug and there are no CPUs left in our mask
  1193. * the @ns structure is NULL'ed and task_numa_compare() will
  1194. * not find this node attractive.
  1195. *
  1196. * We'll either bail at !has_free_capacity, or we'll detect a huge
  1197. * imbalance and bail there.
  1198. */
  1199. if (!cpus)
  1200. return;
  1201. /* smt := ceil(cpus / capacity), assumes: 1 < smt_power < 2 */
  1202. smt = DIV_ROUND_UP(SCHED_CAPACITY_SCALE * cpus, ns->compute_capacity);
  1203. capacity = cpus / smt; /* cores */
  1204. ns->task_capacity = min_t(unsigned, capacity,
  1205. DIV_ROUND_CLOSEST(ns->compute_capacity, SCHED_CAPACITY_SCALE));
  1206. ns->has_free_capacity = (ns->nr_running < ns->task_capacity);
  1207. }
  1208. struct task_numa_env {
  1209. struct task_struct *p;
  1210. int src_cpu, src_nid;
  1211. int dst_cpu, dst_nid;
  1212. struct numa_stats src_stats, dst_stats;
  1213. int imbalance_pct;
  1214. int dist;
  1215. struct task_struct *best_task;
  1216. long best_imp;
  1217. int best_cpu;
  1218. };
  1219. static void task_numa_assign(struct task_numa_env *env,
  1220. struct task_struct *p, long imp)
  1221. {
  1222. if (env->best_task)
  1223. put_task_struct(env->best_task);
  1224. if (p)
  1225. get_task_struct(p);
  1226. env->best_task = p;
  1227. env->best_imp = imp;
  1228. env->best_cpu = env->dst_cpu;
  1229. }
  1230. static bool load_too_imbalanced(long src_load, long dst_load,
  1231. struct task_numa_env *env)
  1232. {
  1233. long imb, old_imb;
  1234. long orig_src_load, orig_dst_load;
  1235. long src_capacity, dst_capacity;
  1236. /*
  1237. * The load is corrected for the CPU capacity available on each node.
  1238. *
  1239. * src_load dst_load
  1240. * ------------ vs ---------
  1241. * src_capacity dst_capacity
  1242. */
  1243. src_capacity = env->src_stats.compute_capacity;
  1244. dst_capacity = env->dst_stats.compute_capacity;
  1245. /* We care about the slope of the imbalance, not the direction. */
  1246. if (dst_load < src_load)
  1247. swap(dst_load, src_load);
  1248. /* Is the difference below the threshold? */
  1249. imb = dst_load * src_capacity * 100 -
  1250. src_load * dst_capacity * env->imbalance_pct;
  1251. if (imb <= 0)
  1252. return false;
  1253. /*
  1254. * The imbalance is above the allowed threshold.
  1255. * Compare it with the old imbalance.
  1256. */
  1257. orig_src_load = env->src_stats.load;
  1258. orig_dst_load = env->dst_stats.load;
  1259. if (orig_dst_load < orig_src_load)
  1260. swap(orig_dst_load, orig_src_load);
  1261. old_imb = orig_dst_load * src_capacity * 100 -
  1262. orig_src_load * dst_capacity * env->imbalance_pct;
  1263. /* Would this change make things worse? */
  1264. return (imb > old_imb);
  1265. }
  1266. /*
  1267. * This checks if the overall compute and NUMA accesses of the system would
  1268. * be improved if the source tasks was migrated to the target dst_cpu taking
  1269. * into account that it might be best if task running on the dst_cpu should
  1270. * be exchanged with the source task
  1271. */
  1272. static void task_numa_compare(struct task_numa_env *env,
  1273. long taskimp, long groupimp)
  1274. {
  1275. struct rq *src_rq = cpu_rq(env->src_cpu);
  1276. struct rq *dst_rq = cpu_rq(env->dst_cpu);
  1277. struct task_struct *cur;
  1278. long src_load, dst_load;
  1279. long load;
  1280. long imp = env->p->numa_group ? groupimp : taskimp;
  1281. long moveimp = imp;
  1282. int dist = env->dist;
  1283. rcu_read_lock();
  1284. cur = task_rcu_dereference(&dst_rq->curr);
  1285. if (cur && ((cur->flags & PF_EXITING) || is_idle_task(cur)))
  1286. cur = NULL;
  1287. /*
  1288. * Because we have preemption enabled we can get migrated around and
  1289. * end try selecting ourselves (current == env->p) as a swap candidate.
  1290. */
  1291. if (cur == env->p)
  1292. goto unlock;
  1293. /*
  1294. * "imp" is the fault differential for the source task between the
  1295. * source and destination node. Calculate the total differential for
  1296. * the source task and potential destination task. The more negative
  1297. * the value is, the more rmeote accesses that would be expected to
  1298. * be incurred if the tasks were swapped.
  1299. */
  1300. if (cur) {
  1301. /* Skip this swap candidate if cannot move to the source CPU: */
  1302. if (!cpumask_test_cpu(env->src_cpu, &cur->cpus_allowed))
  1303. goto unlock;
  1304. /*
  1305. * If dst and source tasks are in the same NUMA group, or not
  1306. * in any group then look only at task weights.
  1307. */
  1308. if (cur->numa_group == env->p->numa_group) {
  1309. imp = taskimp + task_weight(cur, env->src_nid, dist) -
  1310. task_weight(cur, env->dst_nid, dist);
  1311. /*
  1312. * Add some hysteresis to prevent swapping the
  1313. * tasks within a group over tiny differences.
  1314. */
  1315. if (cur->numa_group)
  1316. imp -= imp/16;
  1317. } else {
  1318. /*
  1319. * Compare the group weights. If a task is all by
  1320. * itself (not part of a group), use the task weight
  1321. * instead.
  1322. */
  1323. if (cur->numa_group)
  1324. imp += group_weight(cur, env->src_nid, dist) -
  1325. group_weight(cur, env->dst_nid, dist);
  1326. else
  1327. imp += task_weight(cur, env->src_nid, dist) -
  1328. task_weight(cur, env->dst_nid, dist);
  1329. }
  1330. }
  1331. if (imp <= env->best_imp && moveimp <= env->best_imp)
  1332. goto unlock;
  1333. if (!cur) {
  1334. /* Is there capacity at our destination? */
  1335. if (env->src_stats.nr_running <= env->src_stats.task_capacity &&
  1336. !env->dst_stats.has_free_capacity)
  1337. goto unlock;
  1338. goto balance;
  1339. }
  1340. /* Balance doesn't matter much if we're running a task per CPU: */
  1341. if (imp > env->best_imp && src_rq->nr_running == 1 &&
  1342. dst_rq->nr_running == 1)
  1343. goto assign;
  1344. /*
  1345. * In the overloaded case, try and keep the load balanced.
  1346. */
  1347. balance:
  1348. load = task_h_load(env->p);
  1349. dst_load = env->dst_stats.load + load;
  1350. src_load = env->src_stats.load - load;
  1351. if (moveimp > imp && moveimp > env->best_imp) {
  1352. /*
  1353. * If the improvement from just moving env->p direction is
  1354. * better than swapping tasks around, check if a move is
  1355. * possible. Store a slightly smaller score than moveimp,
  1356. * so an actually idle CPU will win.
  1357. */
  1358. if (!load_too_imbalanced(src_load, dst_load, env)) {
  1359. imp = moveimp - 1;
  1360. cur = NULL;
  1361. goto assign;
  1362. }
  1363. }
  1364. if (imp <= env->best_imp)
  1365. goto unlock;
  1366. if (cur) {
  1367. load = task_h_load(cur);
  1368. dst_load -= load;
  1369. src_load += load;
  1370. }
  1371. if (load_too_imbalanced(src_load, dst_load, env))
  1372. goto unlock;
  1373. /*
  1374. * One idle CPU per node is evaluated for a task numa move.
  1375. * Call select_idle_sibling to maybe find a better one.
  1376. */
  1377. if (!cur) {
  1378. /*
  1379. * select_idle_siblings() uses an per-CPU cpumask that
  1380. * can be used from IRQ context.
  1381. */
  1382. local_irq_disable();
  1383. env->dst_cpu = select_idle_sibling(env->p, env->src_cpu,
  1384. env->dst_cpu);
  1385. local_irq_enable();
  1386. }
  1387. assign:
  1388. task_numa_assign(env, cur, imp);
  1389. unlock:
  1390. rcu_read_unlock();
  1391. }
  1392. static void task_numa_find_cpu(struct task_numa_env *env,
  1393. long taskimp, long groupimp)
  1394. {
  1395. int cpu;
  1396. for_each_cpu(cpu, cpumask_of_node(env->dst_nid)) {
  1397. /* Skip this CPU if the source task cannot migrate */
  1398. if (!cpumask_test_cpu(cpu, &env->p->cpus_allowed))
  1399. continue;
  1400. env->dst_cpu = cpu;
  1401. task_numa_compare(env, taskimp, groupimp);
  1402. }
  1403. }
  1404. /* Only move tasks to a NUMA node less busy than the current node. */
  1405. static bool numa_has_capacity(struct task_numa_env *env)
  1406. {
  1407. struct numa_stats *src = &env->src_stats;
  1408. struct numa_stats *dst = &env->dst_stats;
  1409. if (src->has_free_capacity && !dst->has_free_capacity)
  1410. return false;
  1411. /*
  1412. * Only consider a task move if the source has a higher load
  1413. * than the destination, corrected for CPU capacity on each node.
  1414. *
  1415. * src->load dst->load
  1416. * --------------------- vs ---------------------
  1417. * src->compute_capacity dst->compute_capacity
  1418. */
  1419. if (src->load * dst->compute_capacity * env->imbalance_pct >
  1420. dst->load * src->compute_capacity * 100)
  1421. return true;
  1422. return false;
  1423. }
  1424. static int task_numa_migrate(struct task_struct *p)
  1425. {
  1426. struct task_numa_env env = {
  1427. .p = p,
  1428. .src_cpu = task_cpu(p),
  1429. .src_nid = task_node(p),
  1430. .imbalance_pct = 112,
  1431. .best_task = NULL,
  1432. .best_imp = 0,
  1433. .best_cpu = -1,
  1434. };
  1435. struct sched_domain *sd;
  1436. unsigned long taskweight, groupweight;
  1437. int nid, ret, dist;
  1438. long taskimp, groupimp;
  1439. /*
  1440. * Pick the lowest SD_NUMA domain, as that would have the smallest
  1441. * imbalance and would be the first to start moving tasks about.
  1442. *
  1443. * And we want to avoid any moving of tasks about, as that would create
  1444. * random movement of tasks -- counter the numa conditions we're trying
  1445. * to satisfy here.
  1446. */
  1447. rcu_read_lock();
  1448. sd = rcu_dereference(per_cpu(sd_numa, env.src_cpu));
  1449. if (sd)
  1450. env.imbalance_pct = 100 + (sd->imbalance_pct - 100) / 2;
  1451. rcu_read_unlock();
  1452. /*
  1453. * Cpusets can break the scheduler domain tree into smaller
  1454. * balance domains, some of which do not cross NUMA boundaries.
  1455. * Tasks that are "trapped" in such domains cannot be migrated
  1456. * elsewhere, so there is no point in (re)trying.
  1457. */
  1458. if (unlikely(!sd)) {
  1459. p->numa_preferred_nid = task_node(p);
  1460. return -EINVAL;
  1461. }
  1462. env.dst_nid = p->numa_preferred_nid;
  1463. dist = env.dist = node_distance(env.src_nid, env.dst_nid);
  1464. taskweight = task_weight(p, env.src_nid, dist);
  1465. groupweight = group_weight(p, env.src_nid, dist);
  1466. update_numa_stats(&env.src_stats, env.src_nid);
  1467. taskimp = task_weight(p, env.dst_nid, dist) - taskweight;
  1468. groupimp = group_weight(p, env.dst_nid, dist) - groupweight;
  1469. update_numa_stats(&env.dst_stats, env.dst_nid);
  1470. /* Try to find a spot on the preferred nid. */
  1471. if (numa_has_capacity(&env))
  1472. task_numa_find_cpu(&env, taskimp, groupimp);
  1473. /*
  1474. * Look at other nodes in these cases:
  1475. * - there is no space available on the preferred_nid
  1476. * - the task is part of a numa_group that is interleaved across
  1477. * multiple NUMA nodes; in order to better consolidate the group,
  1478. * we need to check other locations.
  1479. */
  1480. if (env.best_cpu == -1 || (p->numa_group && p->numa_group->active_nodes > 1)) {
  1481. for_each_online_node(nid) {
  1482. if (nid == env.src_nid || nid == p->numa_preferred_nid)
  1483. continue;
  1484. dist = node_distance(env.src_nid, env.dst_nid);
  1485. if (sched_numa_topology_type == NUMA_BACKPLANE &&
  1486. dist != env.dist) {
  1487. taskweight = task_weight(p, env.src_nid, dist);
  1488. groupweight = group_weight(p, env.src_nid, dist);
  1489. }
  1490. /* Only consider nodes where both task and groups benefit */
  1491. taskimp = task_weight(p, nid, dist) - taskweight;
  1492. groupimp = group_weight(p, nid, dist) - groupweight;
  1493. if (taskimp < 0 && groupimp < 0)
  1494. continue;
  1495. env.dist = dist;
  1496. env.dst_nid = nid;
  1497. update_numa_stats(&env.dst_stats, env.dst_nid);
  1498. if (numa_has_capacity(&env))
  1499. task_numa_find_cpu(&env, taskimp, groupimp);
  1500. }
  1501. }
  1502. /*
  1503. * If the task is part of a workload that spans multiple NUMA nodes,
  1504. * and is migrating into one of the workload's active nodes, remember
  1505. * this node as the task's preferred numa node, so the workload can
  1506. * settle down.
  1507. * A task that migrated to a second choice node will be better off
  1508. * trying for a better one later. Do not set the preferred node here.
  1509. */
  1510. if (p->numa_group) {
  1511. struct numa_group *ng = p->numa_group;
  1512. if (env.best_cpu == -1)
  1513. nid = env.src_nid;
  1514. else
  1515. nid = env.dst_nid;
  1516. if (ng->active_nodes > 1 && numa_is_active_node(env.dst_nid, ng))
  1517. sched_setnuma(p, env.dst_nid);
  1518. }
  1519. /* No better CPU than the current one was found. */
  1520. if (env.best_cpu == -1)
  1521. return -EAGAIN;
  1522. /*
  1523. * Reset the scan period if the task is being rescheduled on an
  1524. * alternative node to recheck if the tasks is now properly placed.
  1525. */
  1526. p->numa_scan_period = task_scan_start(p);
  1527. if (env.best_task == NULL) {
  1528. ret = migrate_task_to(p, env.best_cpu);
  1529. if (ret != 0)
  1530. trace_sched_stick_numa(p, env.src_cpu, env.best_cpu);
  1531. return ret;
  1532. }
  1533. ret = migrate_swap(p, env.best_task);
  1534. if (ret != 0)
  1535. trace_sched_stick_numa(p, env.src_cpu, task_cpu(env.best_task));
  1536. put_task_struct(env.best_task);
  1537. return ret;
  1538. }
  1539. /* Attempt to migrate a task to a CPU on the preferred node. */
  1540. static void numa_migrate_preferred(struct task_struct *p)
  1541. {
  1542. unsigned long interval = HZ;
  1543. /* This task has no NUMA fault statistics yet */
  1544. if (unlikely(p->numa_preferred_nid == -1 || !p->numa_faults))
  1545. return;
  1546. /* Periodically retry migrating the task to the preferred node */
  1547. interval = min(interval, msecs_to_jiffies(p->numa_scan_period) / 16);
  1548. p->numa_migrate_retry = jiffies + interval;
  1549. /* Success if task is already running on preferred CPU */
  1550. if (task_node(p) == p->numa_preferred_nid)
  1551. return;
  1552. /* Otherwise, try migrate to a CPU on the preferred node */
  1553. task_numa_migrate(p);
  1554. }
  1555. /*
  1556. * Find out how many nodes on the workload is actively running on. Do this by
  1557. * tracking the nodes from which NUMA hinting faults are triggered. This can
  1558. * be different from the set of nodes where the workload's memory is currently
  1559. * located.
  1560. */
  1561. static void numa_group_count_active_nodes(struct numa_group *numa_group)
  1562. {
  1563. unsigned long faults, max_faults = 0;
  1564. int nid, active_nodes = 0;
  1565. for_each_online_node(nid) {
  1566. faults = group_faults_cpu(numa_group, nid);
  1567. if (faults > max_faults)
  1568. max_faults = faults;
  1569. }
  1570. for_each_online_node(nid) {
  1571. faults = group_faults_cpu(numa_group, nid);
  1572. if (faults * ACTIVE_NODE_FRACTION > max_faults)
  1573. active_nodes++;
  1574. }
  1575. numa_group->max_faults_cpu = max_faults;
  1576. numa_group->active_nodes = active_nodes;
  1577. }
  1578. /*
  1579. * When adapting the scan rate, the period is divided into NUMA_PERIOD_SLOTS
  1580. * increments. The more local the fault statistics are, the higher the scan
  1581. * period will be for the next scan window. If local/(local+remote) ratio is
  1582. * below NUMA_PERIOD_THRESHOLD (where range of ratio is 1..NUMA_PERIOD_SLOTS)
  1583. * the scan period will decrease. Aim for 70% local accesses.
  1584. */
  1585. #define NUMA_PERIOD_SLOTS 10
  1586. #define NUMA_PERIOD_THRESHOLD 7
  1587. /*
  1588. * Increase the scan period (slow down scanning) if the majority of
  1589. * our memory is already on our local node, or if the majority of
  1590. * the page accesses are shared with other processes.
  1591. * Otherwise, decrease the scan period.
  1592. */
  1593. static void update_task_scan_period(struct task_struct *p,
  1594. unsigned long shared, unsigned long private)
  1595. {
  1596. unsigned int period_slot;
  1597. int lr_ratio, ps_ratio;
  1598. int diff;
  1599. unsigned long remote = p->numa_faults_locality[0];
  1600. unsigned long local = p->numa_faults_locality[1];
  1601. /*
  1602. * If there were no record hinting faults then either the task is
  1603. * completely idle or all activity is areas that are not of interest
  1604. * to automatic numa balancing. Related to that, if there were failed
  1605. * migration then it implies we are migrating too quickly or the local
  1606. * node is overloaded. In either case, scan slower
  1607. */
  1608. if (local + shared == 0 || p->numa_faults_locality[2]) {
  1609. p->numa_scan_period = min(p->numa_scan_period_max,
  1610. p->numa_scan_period << 1);
  1611. p->mm->numa_next_scan = jiffies +
  1612. msecs_to_jiffies(p->numa_scan_period);
  1613. return;
  1614. }
  1615. /*
  1616. * Prepare to scale scan period relative to the current period.
  1617. * == NUMA_PERIOD_THRESHOLD scan period stays the same
  1618. * < NUMA_PERIOD_THRESHOLD scan period decreases (scan faster)
  1619. * >= NUMA_PERIOD_THRESHOLD scan period increases (scan slower)
  1620. */
  1621. period_slot = DIV_ROUND_UP(p->numa_scan_period, NUMA_PERIOD_SLOTS);
  1622. lr_ratio = (local * NUMA_PERIOD_SLOTS) / (local + remote);
  1623. ps_ratio = (private * NUMA_PERIOD_SLOTS) / (private + shared);
  1624. if (ps_ratio >= NUMA_PERIOD_THRESHOLD) {
  1625. /*
  1626. * Most memory accesses are local. There is no need to
  1627. * do fast NUMA scanning, since memory is already local.
  1628. */
  1629. int slot = ps_ratio - NUMA_PERIOD_THRESHOLD;
  1630. if (!slot)
  1631. slot = 1;
  1632. diff = slot * period_slot;
  1633. } else if (lr_ratio >= NUMA_PERIOD_THRESHOLD) {
  1634. /*
  1635. * Most memory accesses are shared with other tasks.
  1636. * There is no point in continuing fast NUMA scanning,
  1637. * since other tasks may just move the memory elsewhere.
  1638. */
  1639. int slot = lr_ratio - NUMA_PERIOD_THRESHOLD;
  1640. if (!slot)
  1641. slot = 1;
  1642. diff = slot * period_slot;
  1643. } else {
  1644. /*
  1645. * Private memory faults exceed (SLOTS-THRESHOLD)/SLOTS,
  1646. * yet they are not on the local NUMA node. Speed up
  1647. * NUMA scanning to get the memory moved over.
  1648. */
  1649. int ratio = max(lr_ratio, ps_ratio);
  1650. diff = -(NUMA_PERIOD_THRESHOLD - ratio) * period_slot;
  1651. }
  1652. p->numa_scan_period = clamp(p->numa_scan_period + diff,
  1653. task_scan_min(p), task_scan_max(p));
  1654. memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
  1655. }
  1656. /*
  1657. * Get the fraction of time the task has been running since the last
  1658. * NUMA placement cycle. The scheduler keeps similar statistics, but
  1659. * decays those on a 32ms period, which is orders of magnitude off
  1660. * from the dozens-of-seconds NUMA balancing period. Use the scheduler
  1661. * stats only if the task is so new there are no NUMA statistics yet.
  1662. */
  1663. static u64 numa_get_avg_runtime(struct task_struct *p, u64 *period)
  1664. {
  1665. u64 runtime, delta, now;
  1666. /* Use the start of this time slice to avoid calculations. */
  1667. now = p->se.exec_start;
  1668. runtime = p->se.sum_exec_runtime;
  1669. if (p->last_task_numa_placement) {
  1670. delta = runtime - p->last_sum_exec_runtime;
  1671. *period = now - p->last_task_numa_placement;
  1672. } else {
  1673. delta = p->se.avg.load_sum;
  1674. *period = LOAD_AVG_MAX;
  1675. }
  1676. p->last_sum_exec_runtime = runtime;
  1677. p->last_task_numa_placement = now;
  1678. return delta;
  1679. }
  1680. /*
  1681. * Determine the preferred nid for a task in a numa_group. This needs to
  1682. * be done in a way that produces consistent results with group_weight,
  1683. * otherwise workloads might not converge.
  1684. */
  1685. static int preferred_group_nid(struct task_struct *p, int nid)
  1686. {
  1687. nodemask_t nodes;
  1688. int dist;
  1689. /* Direct connections between all NUMA nodes. */
  1690. if (sched_numa_topology_type == NUMA_DIRECT)
  1691. return nid;
  1692. /*
  1693. * On a system with glueless mesh NUMA topology, group_weight
  1694. * scores nodes according to the number of NUMA hinting faults on
  1695. * both the node itself, and on nearby nodes.
  1696. */
  1697. if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
  1698. unsigned long score, max_score = 0;
  1699. int node, max_node = nid;
  1700. dist = sched_max_numa_distance;
  1701. for_each_online_node(node) {
  1702. score = group_weight(p, node, dist);
  1703. if (score > max_score) {
  1704. max_score = score;
  1705. max_node = node;
  1706. }
  1707. }
  1708. return max_node;
  1709. }
  1710. /*
  1711. * Finding the preferred nid in a system with NUMA backplane
  1712. * interconnect topology is more involved. The goal is to locate
  1713. * tasks from numa_groups near each other in the system, and
  1714. * untangle workloads from different sides of the system. This requires
  1715. * searching down the hierarchy of node groups, recursively searching
  1716. * inside the highest scoring group of nodes. The nodemask tricks
  1717. * keep the complexity of the search down.
  1718. */
  1719. nodes = node_online_map;
  1720. for (dist = sched_max_numa_distance; dist > LOCAL_DISTANCE; dist--) {
  1721. unsigned long max_faults = 0;
  1722. nodemask_t max_group = NODE_MASK_NONE;
  1723. int a, b;
  1724. /* Are there nodes at this distance from each other? */
  1725. if (!find_numa_distance(dist))
  1726. continue;
  1727. for_each_node_mask(a, nodes) {
  1728. unsigned long faults = 0;
  1729. nodemask_t this_group;
  1730. nodes_clear(this_group);
  1731. /* Sum group's NUMA faults; includes a==b case. */
  1732. for_each_node_mask(b, nodes) {
  1733. if (node_distance(a, b) < dist) {
  1734. faults += group_faults(p, b);
  1735. node_set(b, this_group);
  1736. node_clear(b, nodes);
  1737. }
  1738. }
  1739. /* Remember the top group. */
  1740. if (faults > max_faults) {
  1741. max_faults = faults;
  1742. max_group = this_group;
  1743. /*
  1744. * subtle: at the smallest distance there is
  1745. * just one node left in each "group", the
  1746. * winner is the preferred nid.
  1747. */
  1748. nid = a;
  1749. }
  1750. }
  1751. /* Next round, evaluate the nodes within max_group. */
  1752. if (!max_faults)
  1753. break;
  1754. nodes = max_group;
  1755. }
  1756. return nid;
  1757. }
  1758. static void task_numa_placement(struct task_struct *p)
  1759. {
  1760. int seq, nid, max_nid = -1, max_group_nid = -1;
  1761. unsigned long max_faults = 0, max_group_faults = 0;
  1762. unsigned long fault_types[2] = { 0, 0 };
  1763. unsigned long total_faults;
  1764. u64 runtime, period;
  1765. spinlock_t *group_lock = NULL;
  1766. /*
  1767. * The p->mm->numa_scan_seq field gets updated without
  1768. * exclusive access. Use READ_ONCE() here to ensure
  1769. * that the field is read in a single access:
  1770. */
  1771. seq = READ_ONCE(p->mm->numa_scan_seq);
  1772. if (p->numa_scan_seq == seq)
  1773. return;
  1774. p->numa_scan_seq = seq;
  1775. p->numa_scan_period_max = task_scan_max(p);
  1776. total_faults = p->numa_faults_locality[0] +
  1777. p->numa_faults_locality[1];
  1778. runtime = numa_get_avg_runtime(p, &period);
  1779. /* If the task is part of a group prevent parallel updates to group stats */
  1780. if (p->numa_group) {
  1781. group_lock = &p->numa_group->lock;
  1782. spin_lock_irq(group_lock);
  1783. }
  1784. /* Find the node with the highest number of faults */
  1785. for_each_online_node(nid) {
  1786. /* Keep track of the offsets in numa_faults array */
  1787. int mem_idx, membuf_idx, cpu_idx, cpubuf_idx;
  1788. unsigned long faults = 0, group_faults = 0;
  1789. int priv;
  1790. for (priv = 0; priv < NR_NUMA_HINT_FAULT_TYPES; priv++) {
  1791. long diff, f_diff, f_weight;
  1792. mem_idx = task_faults_idx(NUMA_MEM, nid, priv);
  1793. membuf_idx = task_faults_idx(NUMA_MEMBUF, nid, priv);
  1794. cpu_idx = task_faults_idx(NUMA_CPU, nid, priv);
  1795. cpubuf_idx = task_faults_idx(NUMA_CPUBUF, nid, priv);
  1796. /* Decay existing window, copy faults since last scan */
  1797. diff = p->numa_faults[membuf_idx] - p->numa_faults[mem_idx] / 2;
  1798. fault_types[priv] += p->numa_faults[membuf_idx];
  1799. p->numa_faults[membuf_idx] = 0;
  1800. /*
  1801. * Normalize the faults_from, so all tasks in a group
  1802. * count according to CPU use, instead of by the raw
  1803. * number of faults. Tasks with little runtime have
  1804. * little over-all impact on throughput, and thus their
  1805. * faults are less important.
  1806. */
  1807. f_weight = div64_u64(runtime << 16, period + 1);
  1808. f_weight = (f_weight * p->numa_faults[cpubuf_idx]) /
  1809. (total_faults + 1);
  1810. f_diff = f_weight - p->numa_faults[cpu_idx] / 2;
  1811. p->numa_faults[cpubuf_idx] = 0;
  1812. p->numa_faults[mem_idx] += diff;
  1813. p->numa_faults[cpu_idx] += f_diff;
  1814. faults += p->numa_faults[mem_idx];
  1815. p->total_numa_faults += diff;
  1816. if (p->numa_group) {
  1817. /*
  1818. * safe because we can only change our own group
  1819. *
  1820. * mem_idx represents the offset for a given
  1821. * nid and priv in a specific region because it
  1822. * is at the beginning of the numa_faults array.
  1823. */
  1824. p->numa_group->faults[mem_idx] += diff;
  1825. p->numa_group->faults_cpu[mem_idx] += f_diff;
  1826. p->numa_group->total_faults += diff;
  1827. group_faults += p->numa_group->faults[mem_idx];
  1828. }
  1829. }
  1830. if (faults > max_faults) {
  1831. max_faults = faults;
  1832. max_nid = nid;
  1833. }
  1834. if (group_faults > max_group_faults) {
  1835. max_group_faults = group_faults;
  1836. max_group_nid = nid;
  1837. }
  1838. }
  1839. update_task_scan_period(p, fault_types[0], fault_types[1]);
  1840. if (p->numa_group) {
  1841. numa_group_count_active_nodes(p->numa_group);
  1842. spin_unlock_irq(group_lock);
  1843. max_nid = preferred_group_nid(p, max_group_nid);
  1844. }
  1845. if (max_faults) {
  1846. /* Set the new preferred node */
  1847. if (max_nid != p->numa_preferred_nid)
  1848. sched_setnuma(p, max_nid);
  1849. if (task_node(p) != p->numa_preferred_nid)
  1850. numa_migrate_preferred(p);
  1851. }
  1852. }
  1853. static inline int get_numa_group(struct numa_group *grp)
  1854. {
  1855. return atomic_inc_not_zero(&grp->refcount);
  1856. }
  1857. static inline void put_numa_group(struct numa_group *grp)
  1858. {
  1859. if (atomic_dec_and_test(&grp->refcount))
  1860. kfree_rcu(grp, rcu);
  1861. }
  1862. static void task_numa_group(struct task_struct *p, int cpupid, int flags,
  1863. int *priv)
  1864. {
  1865. struct numa_group *grp, *my_grp;
  1866. struct task_struct *tsk;
  1867. bool join = false;
  1868. int cpu = cpupid_to_cpu(cpupid);
  1869. int i;
  1870. if (unlikely(!p->numa_group)) {
  1871. unsigned int size = sizeof(struct numa_group) +
  1872. 4*nr_node_ids*sizeof(unsigned long);
  1873. grp = kzalloc(size, GFP_KERNEL | __GFP_NOWARN);
  1874. if (!grp)
  1875. return;
  1876. atomic_set(&grp->refcount, 1);
  1877. grp->active_nodes = 1;
  1878. grp->max_faults_cpu = 0;
  1879. spin_lock_init(&grp->lock);
  1880. grp->gid = p->pid;
  1881. /* Second half of the array tracks nids where faults happen */
  1882. grp->faults_cpu = grp->faults + NR_NUMA_HINT_FAULT_TYPES *
  1883. nr_node_ids;
  1884. for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
  1885. grp->faults[i] = p->numa_faults[i];
  1886. grp->total_faults = p->total_numa_faults;
  1887. grp->nr_tasks++;
  1888. rcu_assign_pointer(p->numa_group, grp);
  1889. }
  1890. rcu_read_lock();
  1891. tsk = READ_ONCE(cpu_rq(cpu)->curr);
  1892. if (!cpupid_match_pid(tsk, cpupid))
  1893. goto no_join;
  1894. grp = rcu_dereference(tsk->numa_group);
  1895. if (!grp)
  1896. goto no_join;
  1897. my_grp = p->numa_group;
  1898. if (grp == my_grp)
  1899. goto no_join;
  1900. /*
  1901. * Only join the other group if its bigger; if we're the bigger group,
  1902. * the other task will join us.
  1903. */
  1904. if (my_grp->nr_tasks > grp->nr_tasks)
  1905. goto no_join;
  1906. /*
  1907. * Tie-break on the grp address.
  1908. */
  1909. if (my_grp->nr_tasks == grp->nr_tasks && my_grp > grp)
  1910. goto no_join;
  1911. /* Always join threads in the same process. */
  1912. if (tsk->mm == current->mm)
  1913. join = true;
  1914. /* Simple filter to avoid false positives due to PID collisions */
  1915. if (flags & TNF_SHARED)
  1916. join = true;
  1917. /* Update priv based on whether false sharing was detected */
  1918. *priv = !join;
  1919. if (join && !get_numa_group(grp))
  1920. goto no_join;
  1921. rcu_read_unlock();
  1922. if (!join)
  1923. return;
  1924. BUG_ON(irqs_disabled());
  1925. double_lock_irq(&my_grp->lock, &grp->lock);
  1926. for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) {
  1927. my_grp->faults[i] -= p->numa_faults[i];
  1928. grp->faults[i] += p->numa_faults[i];
  1929. }
  1930. my_grp->total_faults -= p->total_numa_faults;
  1931. grp->total_faults += p->total_numa_faults;
  1932. my_grp->nr_tasks--;
  1933. grp->nr_tasks++;
  1934. spin_unlock(&my_grp->lock);
  1935. spin_unlock_irq(&grp->lock);
  1936. rcu_assign_pointer(p->numa_group, grp);
  1937. put_numa_group(my_grp);
  1938. return;
  1939. no_join:
  1940. rcu_read_unlock();
  1941. return;
  1942. }
  1943. void task_numa_free(struct task_struct *p)
  1944. {
  1945. struct numa_group *grp = p->numa_group;
  1946. void *numa_faults = p->numa_faults;
  1947. unsigned long flags;
  1948. int i;
  1949. if (grp) {
  1950. spin_lock_irqsave(&grp->lock, flags);
  1951. for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
  1952. grp->faults[i] -= p->numa_faults[i];
  1953. grp->total_faults -= p->total_numa_faults;
  1954. grp->nr_tasks--;
  1955. spin_unlock_irqrestore(&grp->lock, flags);
  1956. RCU_INIT_POINTER(p->numa_group, NULL);
  1957. put_numa_group(grp);
  1958. }
  1959. p->numa_faults = NULL;
  1960. kfree(numa_faults);
  1961. }
  1962. /*
  1963. * Got a PROT_NONE fault for a page on @node.
  1964. */
  1965. void task_numa_fault(int last_cpupid, int mem_node, int pages, int flags)
  1966. {
  1967. struct task_struct *p = current;
  1968. bool migrated = flags & TNF_MIGRATED;
  1969. int cpu_node = task_node(current);
  1970. int local = !!(flags & TNF_FAULT_LOCAL);
  1971. struct numa_group *ng;
  1972. int priv;
  1973. if (!static_branch_likely(&sched_numa_balancing))
  1974. return;
  1975. /* for example, ksmd faulting in a user's mm */
  1976. if (!p->mm)
  1977. return;
  1978. /* Allocate buffer to track faults on a per-node basis */
  1979. if (unlikely(!p->numa_faults)) {
  1980. int size = sizeof(*p->numa_faults) *
  1981. NR_NUMA_HINT_FAULT_BUCKETS * nr_node_ids;
  1982. p->numa_faults = kzalloc(size, GFP_KERNEL|__GFP_NOWARN);
  1983. if (!p->numa_faults)
  1984. return;
  1985. p->total_numa_faults = 0;
  1986. memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
  1987. }
  1988. /*
  1989. * First accesses are treated as private, otherwise consider accesses
  1990. * to be private if the accessing pid has not changed
  1991. */
  1992. if (unlikely(last_cpupid == (-1 & LAST_CPUPID_MASK))) {
  1993. priv = 1;
  1994. } else {
  1995. priv = cpupid_match_pid(p, last_cpupid);
  1996. if (!priv && !(flags & TNF_NO_GROUP))
  1997. task_numa_group(p, last_cpupid, flags, &priv);
  1998. }
  1999. /*
  2000. * If a workload spans multiple NUMA nodes, a shared fault that
  2001. * occurs wholly within the set of nodes that the workload is
  2002. * actively using should be counted as local. This allows the
  2003. * scan rate to slow down when a workload has settled down.
  2004. */
  2005. ng = p->numa_group;
  2006. if (!priv && !local && ng && ng->active_nodes > 1 &&
  2007. numa_is_active_node(cpu_node, ng) &&
  2008. numa_is_active_node(mem_node, ng))
  2009. local = 1;
  2010. task_numa_placement(p);
  2011. /*
  2012. * Retry task to preferred node migration periodically, in case it
  2013. * case it previously failed, or the scheduler moved us.
  2014. */
  2015. if (time_after(jiffies, p->numa_migrate_retry))
  2016. numa_migrate_preferred(p);
  2017. if (migrated)
  2018. p->numa_pages_migrated += pages;
  2019. if (flags & TNF_MIGRATE_FAIL)
  2020. p->numa_faults_locality[2] += pages;
  2021. p->numa_faults[task_faults_idx(NUMA_MEMBUF, mem_node, priv)] += pages;
  2022. p->numa_faults[task_faults_idx(NUMA_CPUBUF, cpu_node, priv)] += pages;
  2023. p->numa_faults_locality[local] += pages;
  2024. }
  2025. static void reset_ptenuma_scan(struct task_struct *p)
  2026. {
  2027. /*
  2028. * We only did a read acquisition of the mmap sem, so
  2029. * p->mm->numa_scan_seq is written to without exclusive access
  2030. * and the update is not guaranteed to be atomic. That's not
  2031. * much of an issue though, since this is just used for
  2032. * statistical sampling. Use READ_ONCE/WRITE_ONCE, which are not
  2033. * expensive, to avoid any form of compiler optimizations:
  2034. */
  2035. WRITE_ONCE(p->mm->numa_scan_seq, READ_ONCE(p->mm->numa_scan_seq) + 1);
  2036. p->mm->numa_scan_offset = 0;
  2037. }
  2038. /*
  2039. * The expensive part of numa migration is done from task_work context.
  2040. * Triggered from task_tick_numa().
  2041. */
  2042. void task_numa_work(struct callback_head *work)
  2043. {
  2044. unsigned long migrate, next_scan, now = jiffies;
  2045. struct task_struct *p = current;
  2046. struct mm_struct *mm = p->mm;
  2047. u64 runtime = p->se.sum_exec_runtime;
  2048. struct vm_area_struct *vma;
  2049. unsigned long start, end;
  2050. unsigned long nr_pte_updates = 0;
  2051. long pages, virtpages;
  2052. SCHED_WARN_ON(p != container_of(work, struct task_struct, numa_work));
  2053. work->next = work; /* protect against double add */
  2054. /*
  2055. * Who cares about NUMA placement when they're dying.
  2056. *
  2057. * NOTE: make sure not to dereference p->mm before this check,
  2058. * exit_task_work() happens _after_ exit_mm() so we could be called
  2059. * without p->mm even though we still had it when we enqueued this
  2060. * work.
  2061. */
  2062. if (p->flags & PF_EXITING)
  2063. return;
  2064. if (!mm->numa_next_scan) {
  2065. mm->numa_next_scan = now +
  2066. msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
  2067. }
  2068. /*
  2069. * Enforce maximal scan/migration frequency..
  2070. */
  2071. migrate = mm->numa_next_scan;
  2072. if (time_before(now, migrate))
  2073. return;
  2074. if (p->numa_scan_period == 0) {
  2075. p->numa_scan_period_max = task_scan_max(p);
  2076. p->numa_scan_period = task_scan_start(p);
  2077. }
  2078. next_scan = now + msecs_to_jiffies(p->numa_scan_period);
  2079. if (cmpxchg(&mm->numa_next_scan, migrate, next_scan) != migrate)
  2080. return;
  2081. /*
  2082. * Delay this task enough that another task of this mm will likely win
  2083. * the next time around.
  2084. */
  2085. p->node_stamp += 2 * TICK_NSEC;
  2086. start = mm->numa_scan_offset;
  2087. pages = sysctl_numa_balancing_scan_size;
  2088. pages <<= 20 - PAGE_SHIFT; /* MB in pages */
  2089. virtpages = pages * 8; /* Scan up to this much virtual space */
  2090. if (!pages)
  2091. return;
  2092. if (!down_read_trylock(&mm->mmap_sem))
  2093. return;
  2094. vma = find_vma(mm, start);
  2095. if (!vma) {
  2096. reset_ptenuma_scan(p);
  2097. start = 0;
  2098. vma = mm->mmap;
  2099. }
  2100. for (; vma; vma = vma->vm_next) {
  2101. if (!vma_migratable(vma) || !vma_policy_mof(vma) ||
  2102. is_vm_hugetlb_page(vma) || (vma->vm_flags & VM_MIXEDMAP)) {
  2103. continue;
  2104. }
  2105. /*
  2106. * Shared library pages mapped by multiple processes are not
  2107. * migrated as it is expected they are cache replicated. Avoid
  2108. * hinting faults in read-only file-backed mappings or the vdso
  2109. * as migrating the pages will be of marginal benefit.
  2110. */
  2111. if (!vma->vm_mm ||
  2112. (vma->vm_file && (vma->vm_flags & (VM_READ|VM_WRITE)) == (VM_READ)))
  2113. continue;
  2114. /*
  2115. * Skip inaccessible VMAs to avoid any confusion between
  2116. * PROT_NONE and NUMA hinting ptes
  2117. */
  2118. if (!(vma->vm_flags & (VM_READ | VM_EXEC | VM_WRITE)))
  2119. continue;
  2120. do {
  2121. start = max(start, vma->vm_start);
  2122. end = ALIGN(start + (pages << PAGE_SHIFT), HPAGE_SIZE);
  2123. end = min(end, vma->vm_end);
  2124. nr_pte_updates = change_prot_numa(vma, start, end);
  2125. /*
  2126. * Try to scan sysctl_numa_balancing_size worth of
  2127. * hpages that have at least one present PTE that
  2128. * is not already pte-numa. If the VMA contains
  2129. * areas that are unused or already full of prot_numa
  2130. * PTEs, scan up to virtpages, to skip through those
  2131. * areas faster.
  2132. */
  2133. if (nr_pte_updates)
  2134. pages -= (end - start) >> PAGE_SHIFT;
  2135. virtpages -= (end - start) >> PAGE_SHIFT;
  2136. start = end;
  2137. if (pages <= 0 || virtpages <= 0)
  2138. goto out;
  2139. cond_resched();
  2140. } while (end != vma->vm_end);
  2141. }
  2142. out:
  2143. /*
  2144. * It is possible to reach the end of the VMA list but the last few
  2145. * VMAs are not guaranteed to the vma_migratable. If they are not, we
  2146. * would find the !migratable VMA on the next scan but not reset the
  2147. * scanner to the start so check it now.
  2148. */
  2149. if (vma)
  2150. mm->numa_scan_offset = start;
  2151. else
  2152. reset_ptenuma_scan(p);
  2153. up_read(&mm->mmap_sem);
  2154. /*
  2155. * Make sure tasks use at least 32x as much time to run other code
  2156. * than they used here, to limit NUMA PTE scanning overhead to 3% max.
  2157. * Usually update_task_scan_period slows down scanning enough; on an
  2158. * overloaded system we need to limit overhead on a per task basis.
  2159. */
  2160. if (unlikely(p->se.sum_exec_runtime != runtime)) {
  2161. u64 diff = p->se.sum_exec_runtime - runtime;
  2162. p->node_stamp += 32 * diff;
  2163. }
  2164. }
  2165. /*
  2166. * Drive the periodic memory faults..
  2167. */
  2168. void task_tick_numa(struct rq *rq, struct task_struct *curr)
  2169. {
  2170. struct callback_head *work = &curr->numa_work;
  2171. u64 period, now;
  2172. /*
  2173. * We don't care about NUMA placement if we don't have memory.
  2174. */
  2175. if (!curr->mm || (curr->flags & PF_EXITING) || work->next != work)
  2176. return;
  2177. /*
  2178. * Using runtime rather than walltime has the dual advantage that
  2179. * we (mostly) drive the selection from busy threads and that the
  2180. * task needs to have done some actual work before we bother with
  2181. * NUMA placement.
  2182. */
  2183. now = curr->se.sum_exec_runtime;
  2184. period = (u64)curr->numa_scan_period * NSEC_PER_MSEC;
  2185. if (now > curr->node_stamp + period) {
  2186. if (!curr->node_stamp)
  2187. curr->numa_scan_period = task_scan_start(curr);
  2188. curr->node_stamp += period;
  2189. if (!time_before(jiffies, curr->mm->numa_next_scan)) {
  2190. init_task_work(work, task_numa_work); /* TODO: move this into sched_fork() */
  2191. task_work_add(curr, work, true);
  2192. }
  2193. }
  2194. }
  2195. #else
  2196. static void task_tick_numa(struct rq *rq, struct task_struct *curr)
  2197. {
  2198. }
  2199. static inline void account_numa_enqueue(struct rq *rq, struct task_struct *p)
  2200. {
  2201. }
  2202. static inline void account_numa_dequeue(struct rq *rq, struct task_struct *p)
  2203. {
  2204. }
  2205. #endif /* CONFIG_NUMA_BALANCING */
  2206. static void
  2207. account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
  2208. {
  2209. update_load_add(&cfs_rq->load, se->load.weight);
  2210. if (!parent_entity(se))
  2211. update_load_add(&rq_of(cfs_rq)->load, se->load.weight);
  2212. #ifdef CONFIG_SMP
  2213. if (entity_is_task(se)) {
  2214. struct rq *rq = rq_of(cfs_rq);
  2215. account_numa_enqueue(rq, task_of(se));
  2216. list_add(&se->group_node, &rq->cfs_tasks);
  2217. }
  2218. #endif
  2219. cfs_rq->nr_running++;
  2220. }
  2221. static void
  2222. account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
  2223. {
  2224. update_load_sub(&cfs_rq->load, se->load.weight);
  2225. if (!parent_entity(se))
  2226. update_load_sub(&rq_of(cfs_rq)->load, se->load.weight);
  2227. #ifdef CONFIG_SMP
  2228. if (entity_is_task(se)) {
  2229. account_numa_dequeue(rq_of(cfs_rq), task_of(se));
  2230. list_del_init(&se->group_node);
  2231. }
  2232. #endif
  2233. cfs_rq->nr_running--;
  2234. }
  2235. /*
  2236. * Signed add and clamp on underflow.
  2237. *
  2238. * Explicitly do a load-store to ensure the intermediate value never hits
  2239. * memory. This allows lockless observations without ever seeing the negative
  2240. * values.
  2241. */
  2242. #define add_positive(_ptr, _val) do { \
  2243. typeof(_ptr) ptr = (_ptr); \
  2244. typeof(_val) val = (_val); \
  2245. typeof(*ptr) res, var = READ_ONCE(*ptr); \
  2246. \
  2247. res = var + val; \
  2248. \
  2249. if (val < 0 && res > var) \
  2250. res = 0; \
  2251. \
  2252. WRITE_ONCE(*ptr, res); \
  2253. } while (0)
  2254. /*
  2255. * Unsigned subtract and clamp on underflow.
  2256. *
  2257. * Explicitly do a load-store to ensure the intermediate value never hits
  2258. * memory. This allows lockless observations without ever seeing the negative
  2259. * values.
  2260. */
  2261. #define sub_positive(_ptr, _val) do { \
  2262. typeof(_ptr) ptr = (_ptr); \
  2263. typeof(*ptr) val = (_val); \
  2264. typeof(*ptr) res, var = READ_ONCE(*ptr); \
  2265. res = var - val; \
  2266. if (res > var) \
  2267. res = 0; \
  2268. WRITE_ONCE(*ptr, res); \
  2269. } while (0)
  2270. #ifdef CONFIG_SMP
  2271. /*
  2272. * XXX we want to get rid of these helpers and use the full load resolution.
  2273. */
  2274. static inline long se_weight(struct sched_entity *se)
  2275. {
  2276. return scale_load_down(se->load.weight);
  2277. }
  2278. static inline long se_runnable(struct sched_entity *se)
  2279. {
  2280. return scale_load_down(se->runnable_weight);
  2281. }
  2282. static inline void
  2283. enqueue_runnable_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
  2284. {
  2285. cfs_rq->runnable_weight += se->runnable_weight;
  2286. cfs_rq->avg.runnable_load_avg += se->avg.runnable_load_avg;
  2287. cfs_rq->avg.runnable_load_sum += se_runnable(se) * se->avg.runnable_load_sum;
  2288. }
  2289. static inline void
  2290. dequeue_runnable_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
  2291. {
  2292. cfs_rq->runnable_weight -= se->runnable_weight;
  2293. sub_positive(&cfs_rq->avg.runnable_load_avg, se->avg.runnable_load_avg);
  2294. sub_positive(&cfs_rq->avg.runnable_load_sum,
  2295. se_runnable(se) * se->avg.runnable_load_sum);
  2296. }
  2297. static inline void
  2298. enqueue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
  2299. {
  2300. cfs_rq->avg.load_avg += se->avg.load_avg;
  2301. cfs_rq->avg.load_sum += se_weight(se) * se->avg.load_sum;
  2302. }
  2303. static inline void
  2304. dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
  2305. {
  2306. sub_positive(&cfs_rq->avg.load_avg, se->avg.load_avg);
  2307. sub_positive(&cfs_rq->avg.load_sum, se_weight(se) * se->avg.load_sum);
  2308. }
  2309. #else
  2310. static inline void
  2311. enqueue_runnable_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) { }
  2312. static inline void
  2313. dequeue_runnable_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) { }
  2314. static inline void
  2315. enqueue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) { }
  2316. static inline void
  2317. dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) { }
  2318. #endif
  2319. static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se,
  2320. unsigned long weight, unsigned long runnable)
  2321. {
  2322. if (se->on_rq) {
  2323. /* commit outstanding execution time */
  2324. if (cfs_rq->curr == se)
  2325. update_curr(cfs_rq);
  2326. account_entity_dequeue(cfs_rq, se);
  2327. dequeue_runnable_load_avg(cfs_rq, se);
  2328. }
  2329. dequeue_load_avg(cfs_rq, se);
  2330. se->runnable_weight = runnable;
  2331. update_load_set(&se->load, weight);
  2332. #ifdef CONFIG_SMP
  2333. do {
  2334. u32 divider = LOAD_AVG_MAX - 1024 + se->avg.period_contrib;
  2335. se->avg.load_avg = div_u64(se_weight(se) * se->avg.load_sum, divider);
  2336. se->avg.runnable_load_avg =
  2337. div_u64(se_runnable(se) * se->avg.runnable_load_sum, divider);
  2338. } while (0);
  2339. #endif
  2340. enqueue_load_avg(cfs_rq, se);
  2341. if (se->on_rq) {
  2342. account_entity_enqueue(cfs_rq, se);
  2343. enqueue_runnable_load_avg(cfs_rq, se);
  2344. }
  2345. }
  2346. void reweight_task(struct task_struct *p, int prio)
  2347. {
  2348. struct sched_entity *se = &p->se;
  2349. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  2350. struct load_weight *load = &se->load;
  2351. unsigned long weight = scale_load(sched_prio_to_weight[prio]);
  2352. reweight_entity(cfs_rq, se, weight, weight);
  2353. load->inv_weight = sched_prio_to_wmult[prio];
  2354. }
  2355. #ifdef CONFIG_FAIR_GROUP_SCHED
  2356. #ifdef CONFIG_SMP
  2357. /*
  2358. * All this does is approximate the hierarchical proportion which includes that
  2359. * global sum we all love to hate.
  2360. *
  2361. * That is, the weight of a group entity, is the proportional share of the
  2362. * group weight based on the group runqueue weights. That is:
  2363. *
  2364. * tg->weight * grq->load.weight
  2365. * ge->load.weight = ----------------------------- (1)
  2366. * \Sum grq->load.weight
  2367. *
  2368. * Now, because computing that sum is prohibitively expensive to compute (been
  2369. * there, done that) we approximate it with this average stuff. The average
  2370. * moves slower and therefore the approximation is cheaper and more stable.
  2371. *
  2372. * So instead of the above, we substitute:
  2373. *
  2374. * grq->load.weight -> grq->avg.load_avg (2)
  2375. *
  2376. * which yields the following:
  2377. *
  2378. * tg->weight * grq->avg.load_avg
  2379. * ge->load.weight = ------------------------------ (3)
  2380. * tg->load_avg
  2381. *
  2382. * Where: tg->load_avg ~= \Sum grq->avg.load_avg
  2383. *
  2384. * That is shares_avg, and it is right (given the approximation (2)).
  2385. *
  2386. * The problem with it is that because the average is slow -- it was designed
  2387. * to be exactly that of course -- this leads to transients in boundary
  2388. * conditions. In specific, the case where the group was idle and we start the
  2389. * one task. It takes time for our CPU's grq->avg.load_avg to build up,
  2390. * yielding bad latency etc..
  2391. *
  2392. * Now, in that special case (1) reduces to:
  2393. *
  2394. * tg->weight * grq->load.weight
  2395. * ge->load.weight = ----------------------------- = tg->weight (4)
  2396. * grp->load.weight
  2397. *
  2398. * That is, the sum collapses because all other CPUs are idle; the UP scenario.
  2399. *
  2400. * So what we do is modify our approximation (3) to approach (4) in the (near)
  2401. * UP case, like:
  2402. *
  2403. * ge->load.weight =
  2404. *
  2405. * tg->weight * grq->load.weight
  2406. * --------------------------------------------------- (5)
  2407. * tg->load_avg - grq->avg.load_avg + grq->load.weight
  2408. *
  2409. * But because grq->load.weight can drop to 0, resulting in a divide by zero,
  2410. * we need to use grq->avg.load_avg as its lower bound, which then gives:
  2411. *
  2412. *
  2413. * tg->weight * grq->load.weight
  2414. * ge->load.weight = ----------------------------- (6)
  2415. * tg_load_avg'
  2416. *
  2417. * Where:
  2418. *
  2419. * tg_load_avg' = tg->load_avg - grq->avg.load_avg +
  2420. * max(grq->load.weight, grq->avg.load_avg)
  2421. *
  2422. * And that is shares_weight and is icky. In the (near) UP case it approaches
  2423. * (4) while in the normal case it approaches (3). It consistently
  2424. * overestimates the ge->load.weight and therefore:
  2425. *
  2426. * \Sum ge->load.weight >= tg->weight
  2427. *
  2428. * hence icky!
  2429. */
  2430. static long calc_group_shares(struct cfs_rq *cfs_rq)
  2431. {
  2432. long tg_weight, tg_shares, load, shares;
  2433. struct task_group *tg = cfs_rq->tg;
  2434. tg_shares = READ_ONCE(tg->shares);
  2435. load = max(scale_load_down(cfs_rq->load.weight), cfs_rq->avg.load_avg);
  2436. tg_weight = atomic_long_read(&tg->load_avg);
  2437. /* Ensure tg_weight >= load */
  2438. tg_weight -= cfs_rq->tg_load_avg_contrib;
  2439. tg_weight += load;
  2440. shares = (tg_shares * load);
  2441. if (tg_weight)
  2442. shares /= tg_weight;
  2443. /*
  2444. * MIN_SHARES has to be unscaled here to support per-CPU partitioning
  2445. * of a group with small tg->shares value. It is a floor value which is
  2446. * assigned as a minimum load.weight to the sched_entity representing
  2447. * the group on a CPU.
  2448. *
  2449. * E.g. on 64-bit for a group with tg->shares of scale_load(15)=15*1024
  2450. * on an 8-core system with 8 tasks each runnable on one CPU shares has
  2451. * to be 15*1024*1/8=1920 instead of scale_load(MIN_SHARES)=2*1024. In
  2452. * case no task is runnable on a CPU MIN_SHARES=2 should be returned
  2453. * instead of 0.
  2454. */
  2455. return clamp_t(long, shares, MIN_SHARES, tg_shares);
  2456. }
  2457. /*
  2458. * This calculates the effective runnable weight for a group entity based on
  2459. * the group entity weight calculated above.
  2460. *
  2461. * Because of the above approximation (2), our group entity weight is
  2462. * an load_avg based ratio (3). This means that it includes blocked load and
  2463. * does not represent the runnable weight.
  2464. *
  2465. * Approximate the group entity's runnable weight per ratio from the group
  2466. * runqueue:
  2467. *
  2468. * grq->avg.runnable_load_avg
  2469. * ge->runnable_weight = ge->load.weight * -------------------------- (7)
  2470. * grq->avg.load_avg
  2471. *
  2472. * However, analogous to above, since the avg numbers are slow, this leads to
  2473. * transients in the from-idle case. Instead we use:
  2474. *
  2475. * ge->runnable_weight = ge->load.weight *
  2476. *
  2477. * max(grq->avg.runnable_load_avg, grq->runnable_weight)
  2478. * ----------------------------------------------------- (8)
  2479. * max(grq->avg.load_avg, grq->load.weight)
  2480. *
  2481. * Where these max() serve both to use the 'instant' values to fix the slow
  2482. * from-idle and avoid the /0 on to-idle, similar to (6).
  2483. */
  2484. static long calc_group_runnable(struct cfs_rq *cfs_rq, long shares)
  2485. {
  2486. long runnable, load_avg;
  2487. load_avg = max(cfs_rq->avg.load_avg,
  2488. scale_load_down(cfs_rq->load.weight));
  2489. runnable = max(cfs_rq->avg.runnable_load_avg,
  2490. scale_load_down(cfs_rq->runnable_weight));
  2491. runnable *= shares;
  2492. if (load_avg)
  2493. runnable /= load_avg;
  2494. return clamp_t(long, runnable, MIN_SHARES, shares);
  2495. }
  2496. #endif /* CONFIG_SMP */
  2497. static inline int throttled_hierarchy(struct cfs_rq *cfs_rq);
  2498. /*
  2499. * Recomputes the group entity based on the current state of its group
  2500. * runqueue.
  2501. */
  2502. static void update_cfs_group(struct sched_entity *se)
  2503. {
  2504. struct cfs_rq *gcfs_rq = group_cfs_rq(se);
  2505. long shares, runnable;
  2506. if (!gcfs_rq)
  2507. return;
  2508. if (throttled_hierarchy(gcfs_rq))
  2509. return;
  2510. #ifndef CONFIG_SMP
  2511. runnable = shares = READ_ONCE(gcfs_rq->tg->shares);
  2512. if (likely(se->load.weight == shares))
  2513. return;
  2514. #else
  2515. shares = calc_group_shares(gcfs_rq);
  2516. runnable = calc_group_runnable(gcfs_rq, shares);
  2517. #endif
  2518. reweight_entity(cfs_rq_of(se), se, shares, runnable);
  2519. }
  2520. #else /* CONFIG_FAIR_GROUP_SCHED */
  2521. static inline void update_cfs_group(struct sched_entity *se)
  2522. {
  2523. }
  2524. #endif /* CONFIG_FAIR_GROUP_SCHED */
  2525. static inline void cfs_rq_util_change(struct cfs_rq *cfs_rq, int flags)
  2526. {
  2527. struct rq *rq = rq_of(cfs_rq);
  2528. if (&rq->cfs == cfs_rq || (flags & SCHED_CPUFREQ_MIGRATION)) {
  2529. /*
  2530. * There are a few boundary cases this might miss but it should
  2531. * get called often enough that that should (hopefully) not be
  2532. * a real problem.
  2533. *
  2534. * It will not get called when we go idle, because the idle
  2535. * thread is a different class (!fair), nor will the utilization
  2536. * number include things like RT tasks.
  2537. *
  2538. * As is, the util number is not freq-invariant (we'd have to
  2539. * implement arch_scale_freq_capacity() for that).
  2540. *
  2541. * See cpu_util().
  2542. */
  2543. cpufreq_update_util(rq, flags);
  2544. }
  2545. }
  2546. #ifdef CONFIG_SMP
  2547. /*
  2548. * Approximate:
  2549. * val * y^n, where y^32 ~= 0.5 (~1 scheduling period)
  2550. */
  2551. static u64 decay_load(u64 val, u64 n)
  2552. {
  2553. unsigned int local_n;
  2554. if (unlikely(n > LOAD_AVG_PERIOD * 63))
  2555. return 0;
  2556. /* after bounds checking we can collapse to 32-bit */
  2557. local_n = n;
  2558. /*
  2559. * As y^PERIOD = 1/2, we can combine
  2560. * y^n = 1/2^(n/PERIOD) * y^(n%PERIOD)
  2561. * With a look-up table which covers y^n (n<PERIOD)
  2562. *
  2563. * To achieve constant time decay_load.
  2564. */
  2565. if (unlikely(local_n >= LOAD_AVG_PERIOD)) {
  2566. val >>= local_n / LOAD_AVG_PERIOD;
  2567. local_n %= LOAD_AVG_PERIOD;
  2568. }
  2569. val = mul_u64_u32_shr(val, runnable_avg_yN_inv[local_n], 32);
  2570. return val;
  2571. }
  2572. static u32 __accumulate_pelt_segments(u64 periods, u32 d1, u32 d3)
  2573. {
  2574. u32 c1, c2, c3 = d3; /* y^0 == 1 */
  2575. /*
  2576. * c1 = d1 y^p
  2577. */
  2578. c1 = decay_load((u64)d1, periods);
  2579. /*
  2580. * p-1
  2581. * c2 = 1024 \Sum y^n
  2582. * n=1
  2583. *
  2584. * inf inf
  2585. * = 1024 ( \Sum y^n - \Sum y^n - y^0 )
  2586. * n=0 n=p
  2587. */
  2588. c2 = LOAD_AVG_MAX - decay_load(LOAD_AVG_MAX, periods) - 1024;
  2589. return c1 + c2 + c3;
  2590. }
  2591. /*
  2592. * Accumulate the three separate parts of the sum; d1 the remainder
  2593. * of the last (incomplete) period, d2 the span of full periods and d3
  2594. * the remainder of the (incomplete) current period.
  2595. *
  2596. * d1 d2 d3
  2597. * ^ ^ ^
  2598. * | | |
  2599. * |<->|<----------------->|<--->|
  2600. * ... |---x---|------| ... |------|-----x (now)
  2601. *
  2602. * p-1
  2603. * u' = (u + d1) y^p + 1024 \Sum y^n + d3 y^0
  2604. * n=1
  2605. *
  2606. * = u y^p + (Step 1)
  2607. *
  2608. * p-1
  2609. * d1 y^p + 1024 \Sum y^n + d3 y^0 (Step 2)
  2610. * n=1
  2611. */
  2612. static __always_inline u32
  2613. accumulate_sum(u64 delta, int cpu, struct sched_avg *sa,
  2614. unsigned long load, unsigned long runnable, int running)
  2615. {
  2616. unsigned long scale_freq, scale_cpu;
  2617. u32 contrib = (u32)delta; /* p == 0 -> delta < 1024 */
  2618. u64 periods;
  2619. scale_freq = arch_scale_freq_capacity(cpu);
  2620. scale_cpu = arch_scale_cpu_capacity(NULL, cpu);
  2621. delta += sa->period_contrib;
  2622. periods = delta / 1024; /* A period is 1024us (~1ms) */
  2623. /*
  2624. * Step 1: decay old *_sum if we crossed period boundaries.
  2625. */
  2626. if (periods) {
  2627. sa->load_sum = decay_load(sa->load_sum, periods);
  2628. sa->runnable_load_sum =
  2629. decay_load(sa->runnable_load_sum, periods);
  2630. sa->util_sum = decay_load((u64)(sa->util_sum), periods);
  2631. /*
  2632. * Step 2
  2633. */
  2634. delta %= 1024;
  2635. contrib = __accumulate_pelt_segments(periods,
  2636. 1024 - sa->period_contrib, delta);
  2637. }
  2638. sa->period_contrib = delta;
  2639. contrib = cap_scale(contrib, scale_freq);
  2640. if (load)
  2641. sa->load_sum += load * contrib;
  2642. if (runnable)
  2643. sa->runnable_load_sum += runnable * contrib;
  2644. if (running)
  2645. sa->util_sum += contrib * scale_cpu;
  2646. return periods;
  2647. }
  2648. /*
  2649. * We can represent the historical contribution to runnable average as the
  2650. * coefficients of a geometric series. To do this we sub-divide our runnable
  2651. * history into segments of approximately 1ms (1024us); label the segment that
  2652. * occurred N-ms ago p_N, with p_0 corresponding to the current period, e.g.
  2653. *
  2654. * [<- 1024us ->|<- 1024us ->|<- 1024us ->| ...
  2655. * p0 p1 p2
  2656. * (now) (~1ms ago) (~2ms ago)
  2657. *
  2658. * Let u_i denote the fraction of p_i that the entity was runnable.
  2659. *
  2660. * We then designate the fractions u_i as our co-efficients, yielding the
  2661. * following representation of historical load:
  2662. * u_0 + u_1*y + u_2*y^2 + u_3*y^3 + ...
  2663. *
  2664. * We choose y based on the with of a reasonably scheduling period, fixing:
  2665. * y^32 = 0.5
  2666. *
  2667. * This means that the contribution to load ~32ms ago (u_32) will be weighted
  2668. * approximately half as much as the contribution to load within the last ms
  2669. * (u_0).
  2670. *
  2671. * When a period "rolls over" and we have new u_0`, multiplying the previous
  2672. * sum again by y is sufficient to update:
  2673. * load_avg = u_0` + y*(u_0 + u_1*y + u_2*y^2 + ... )
  2674. * = u_0 + u_1*y + u_2*y^2 + ... [re-labeling u_i --> u_{i+1}]
  2675. */
  2676. static __always_inline int
  2677. ___update_load_sum(u64 now, int cpu, struct sched_avg *sa,
  2678. unsigned long load, unsigned long runnable, int running)
  2679. {
  2680. u64 delta;
  2681. delta = now - sa->last_update_time;
  2682. /*
  2683. * This should only happen when time goes backwards, which it
  2684. * unfortunately does during sched clock init when we swap over to TSC.
  2685. */
  2686. if ((s64)delta < 0) {
  2687. sa->last_update_time = now;
  2688. return 0;
  2689. }
  2690. /*
  2691. * Use 1024ns as the unit of measurement since it's a reasonable
  2692. * approximation of 1us and fast to compute.
  2693. */
  2694. delta >>= 10;
  2695. if (!delta)
  2696. return 0;
  2697. sa->last_update_time += delta << 10;
  2698. /*
  2699. * running is a subset of runnable (weight) so running can't be set if
  2700. * runnable is clear. But there are some corner cases where the current
  2701. * se has been already dequeued but cfs_rq->curr still points to it.
  2702. * This means that weight will be 0 but not running for a sched_entity
  2703. * but also for a cfs_rq if the latter becomes idle. As an example,
  2704. * this happens during idle_balance() which calls
  2705. * update_blocked_averages()
  2706. */
  2707. if (!load)
  2708. runnable = running = 0;
  2709. /*
  2710. * Now we know we crossed measurement unit boundaries. The *_avg
  2711. * accrues by two steps:
  2712. *
  2713. * Step 1: accumulate *_sum since last_update_time. If we haven't
  2714. * crossed period boundaries, finish.
  2715. */
  2716. if (!accumulate_sum(delta, cpu, sa, load, runnable, running))
  2717. return 0;
  2718. return 1;
  2719. }
  2720. static __always_inline void
  2721. ___update_load_avg(struct sched_avg *sa, unsigned long load, unsigned long runnable)
  2722. {
  2723. u32 divider = LOAD_AVG_MAX - 1024 + sa->period_contrib;
  2724. /*
  2725. * Step 2: update *_avg.
  2726. */
  2727. sa->load_avg = div_u64(load * sa->load_sum, divider);
  2728. sa->runnable_load_avg = div_u64(runnable * sa->runnable_load_sum, divider);
  2729. sa->util_avg = sa->util_sum / divider;
  2730. }
  2731. /*
  2732. * When a task is dequeued, its estimated utilization should not be update if
  2733. * its util_avg has not been updated at least once.
  2734. * This flag is used to synchronize util_avg updates with util_est updates.
  2735. * We map this information into the LSB bit of the utilization saved at
  2736. * dequeue time (i.e. util_est.dequeued).
  2737. */
  2738. #define UTIL_AVG_UNCHANGED 0x1
  2739. static inline void cfs_se_util_change(struct sched_avg *avg)
  2740. {
  2741. unsigned int enqueued;
  2742. if (!sched_feat(UTIL_EST))
  2743. return;
  2744. /* Avoid store if the flag has been already set */
  2745. enqueued = avg->util_est.enqueued;
  2746. if (!(enqueued & UTIL_AVG_UNCHANGED))
  2747. return;
  2748. /* Reset flag to report util_avg has been updated */
  2749. enqueued &= ~UTIL_AVG_UNCHANGED;
  2750. WRITE_ONCE(avg->util_est.enqueued, enqueued);
  2751. }
  2752. /*
  2753. * sched_entity:
  2754. *
  2755. * task:
  2756. * se_runnable() == se_weight()
  2757. *
  2758. * group: [ see update_cfs_group() ]
  2759. * se_weight() = tg->weight * grq->load_avg / tg->load_avg
  2760. * se_runnable() = se_weight(se) * grq->runnable_load_avg / grq->load_avg
  2761. *
  2762. * load_sum := runnable_sum
  2763. * load_avg = se_weight(se) * runnable_avg
  2764. *
  2765. * runnable_load_sum := runnable_sum
  2766. * runnable_load_avg = se_runnable(se) * runnable_avg
  2767. *
  2768. * XXX collapse load_sum and runnable_load_sum
  2769. *
  2770. * cfq_rs:
  2771. *
  2772. * load_sum = \Sum se_weight(se) * se->avg.load_sum
  2773. * load_avg = \Sum se->avg.load_avg
  2774. *
  2775. * runnable_load_sum = \Sum se_runnable(se) * se->avg.runnable_load_sum
  2776. * runnable_load_avg = \Sum se->avg.runable_load_avg
  2777. */
  2778. static int
  2779. __update_load_avg_blocked_se(u64 now, int cpu, struct sched_entity *se)
  2780. {
  2781. if (entity_is_task(se))
  2782. se->runnable_weight = se->load.weight;
  2783. if (___update_load_sum(now, cpu, &se->avg, 0, 0, 0)) {
  2784. ___update_load_avg(&se->avg, se_weight(se), se_runnable(se));
  2785. return 1;
  2786. }
  2787. return 0;
  2788. }
  2789. static int
  2790. __update_load_avg_se(u64 now, int cpu, struct cfs_rq *cfs_rq, struct sched_entity *se)
  2791. {
  2792. if (entity_is_task(se))
  2793. se->runnable_weight = se->load.weight;
  2794. if (___update_load_sum(now, cpu, &se->avg, !!se->on_rq, !!se->on_rq,
  2795. cfs_rq->curr == se)) {
  2796. ___update_load_avg(&se->avg, se_weight(se), se_runnable(se));
  2797. cfs_se_util_change(&se->avg);
  2798. return 1;
  2799. }
  2800. return 0;
  2801. }
  2802. static int
  2803. __update_load_avg_cfs_rq(u64 now, int cpu, struct cfs_rq *cfs_rq)
  2804. {
  2805. if (___update_load_sum(now, cpu, &cfs_rq->avg,
  2806. scale_load_down(cfs_rq->load.weight),
  2807. scale_load_down(cfs_rq->runnable_weight),
  2808. cfs_rq->curr != NULL)) {
  2809. ___update_load_avg(&cfs_rq->avg, 1, 1);
  2810. return 1;
  2811. }
  2812. return 0;
  2813. }
  2814. #ifdef CONFIG_FAIR_GROUP_SCHED
  2815. /**
  2816. * update_tg_load_avg - update the tg's load avg
  2817. * @cfs_rq: the cfs_rq whose avg changed
  2818. * @force: update regardless of how small the difference
  2819. *
  2820. * This function 'ensures': tg->load_avg := \Sum tg->cfs_rq[]->avg.load.
  2821. * However, because tg->load_avg is a global value there are performance
  2822. * considerations.
  2823. *
  2824. * In order to avoid having to look at the other cfs_rq's, we use a
  2825. * differential update where we store the last value we propagated. This in
  2826. * turn allows skipping updates if the differential is 'small'.
  2827. *
  2828. * Updating tg's load_avg is necessary before update_cfs_share().
  2829. */
  2830. static inline void update_tg_load_avg(struct cfs_rq *cfs_rq, int force)
  2831. {
  2832. long delta = cfs_rq->avg.load_avg - cfs_rq->tg_load_avg_contrib;
  2833. /*
  2834. * No need to update load_avg for root_task_group as it is not used.
  2835. */
  2836. if (cfs_rq->tg == &root_task_group)
  2837. return;
  2838. if (force || abs(delta) > cfs_rq->tg_load_avg_contrib / 64) {
  2839. atomic_long_add(delta, &cfs_rq->tg->load_avg);
  2840. cfs_rq->tg_load_avg_contrib = cfs_rq->avg.load_avg;
  2841. }
  2842. }
  2843. /*
  2844. * Called within set_task_rq() right before setting a task's CPU. The
  2845. * caller only guarantees p->pi_lock is held; no other assumptions,
  2846. * including the state of rq->lock, should be made.
  2847. */
  2848. void set_task_rq_fair(struct sched_entity *se,
  2849. struct cfs_rq *prev, struct cfs_rq *next)
  2850. {
  2851. u64 p_last_update_time;
  2852. u64 n_last_update_time;
  2853. if (!sched_feat(ATTACH_AGE_LOAD))
  2854. return;
  2855. /*
  2856. * We are supposed to update the task to "current" time, then its up to
  2857. * date and ready to go to new CPU/cfs_rq. But we have difficulty in
  2858. * getting what current time is, so simply throw away the out-of-date
  2859. * time. This will result in the wakee task is less decayed, but giving
  2860. * the wakee more load sounds not bad.
  2861. */
  2862. if (!(se->avg.last_update_time && prev))
  2863. return;
  2864. #ifndef CONFIG_64BIT
  2865. {
  2866. u64 p_last_update_time_copy;
  2867. u64 n_last_update_time_copy;
  2868. do {
  2869. p_last_update_time_copy = prev->load_last_update_time_copy;
  2870. n_last_update_time_copy = next->load_last_update_time_copy;
  2871. smp_rmb();
  2872. p_last_update_time = prev->avg.last_update_time;
  2873. n_last_update_time = next->avg.last_update_time;
  2874. } while (p_last_update_time != p_last_update_time_copy ||
  2875. n_last_update_time != n_last_update_time_copy);
  2876. }
  2877. #else
  2878. p_last_update_time = prev->avg.last_update_time;
  2879. n_last_update_time = next->avg.last_update_time;
  2880. #endif
  2881. __update_load_avg_blocked_se(p_last_update_time, cpu_of(rq_of(prev)), se);
  2882. se->avg.last_update_time = n_last_update_time;
  2883. }
  2884. /*
  2885. * When on migration a sched_entity joins/leaves the PELT hierarchy, we need to
  2886. * propagate its contribution. The key to this propagation is the invariant
  2887. * that for each group:
  2888. *
  2889. * ge->avg == grq->avg (1)
  2890. *
  2891. * _IFF_ we look at the pure running and runnable sums. Because they
  2892. * represent the very same entity, just at different points in the hierarchy.
  2893. *
  2894. * Per the above update_tg_cfs_util() is trivial and simply copies the running
  2895. * sum over (but still wrong, because the group entity and group rq do not have
  2896. * their PELT windows aligned).
  2897. *
  2898. * However, update_tg_cfs_runnable() is more complex. So we have:
  2899. *
  2900. * ge->avg.load_avg = ge->load.weight * ge->avg.runnable_avg (2)
  2901. *
  2902. * And since, like util, the runnable part should be directly transferable,
  2903. * the following would _appear_ to be the straight forward approach:
  2904. *
  2905. * grq->avg.load_avg = grq->load.weight * grq->avg.runnable_avg (3)
  2906. *
  2907. * And per (1) we have:
  2908. *
  2909. * ge->avg.runnable_avg == grq->avg.runnable_avg
  2910. *
  2911. * Which gives:
  2912. *
  2913. * ge->load.weight * grq->avg.load_avg
  2914. * ge->avg.load_avg = ----------------------------------- (4)
  2915. * grq->load.weight
  2916. *
  2917. * Except that is wrong!
  2918. *
  2919. * Because while for entities historical weight is not important and we
  2920. * really only care about our future and therefore can consider a pure
  2921. * runnable sum, runqueues can NOT do this.
  2922. *
  2923. * We specifically want runqueues to have a load_avg that includes
  2924. * historical weights. Those represent the blocked load, the load we expect
  2925. * to (shortly) return to us. This only works by keeping the weights as
  2926. * integral part of the sum. We therefore cannot decompose as per (3).
  2927. *
  2928. * Another reason this doesn't work is that runnable isn't a 0-sum entity.
  2929. * Imagine a rq with 2 tasks that each are runnable 2/3 of the time. Then the
  2930. * rq itself is runnable anywhere between 2/3 and 1 depending on how the
  2931. * runnable section of these tasks overlap (or not). If they were to perfectly
  2932. * align the rq as a whole would be runnable 2/3 of the time. If however we
  2933. * always have at least 1 runnable task, the rq as a whole is always runnable.
  2934. *
  2935. * So we'll have to approximate.. :/
  2936. *
  2937. * Given the constraint:
  2938. *
  2939. * ge->avg.running_sum <= ge->avg.runnable_sum <= LOAD_AVG_MAX
  2940. *
  2941. * We can construct a rule that adds runnable to a rq by assuming minimal
  2942. * overlap.
  2943. *
  2944. * On removal, we'll assume each task is equally runnable; which yields:
  2945. *
  2946. * grq->avg.runnable_sum = grq->avg.load_sum / grq->load.weight
  2947. *
  2948. * XXX: only do this for the part of runnable > running ?
  2949. *
  2950. */
  2951. static inline void
  2952. update_tg_cfs_util(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
  2953. {
  2954. long delta = gcfs_rq->avg.util_avg - se->avg.util_avg;
  2955. /* Nothing to update */
  2956. if (!delta)
  2957. return;
  2958. /*
  2959. * The relation between sum and avg is:
  2960. *
  2961. * LOAD_AVG_MAX - 1024 + sa->period_contrib
  2962. *
  2963. * however, the PELT windows are not aligned between grq and gse.
  2964. */
  2965. /* Set new sched_entity's utilization */
  2966. se->avg.util_avg = gcfs_rq->avg.util_avg;
  2967. se->avg.util_sum = se->avg.util_avg * LOAD_AVG_MAX;
  2968. /* Update parent cfs_rq utilization */
  2969. add_positive(&cfs_rq->avg.util_avg, delta);
  2970. cfs_rq->avg.util_sum = cfs_rq->avg.util_avg * LOAD_AVG_MAX;
  2971. }
  2972. static inline void
  2973. update_tg_cfs_runnable(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
  2974. {
  2975. long delta_avg, running_sum, runnable_sum = gcfs_rq->prop_runnable_sum;
  2976. unsigned long runnable_load_avg, load_avg;
  2977. u64 runnable_load_sum, load_sum = 0;
  2978. s64 delta_sum;
  2979. if (!runnable_sum)
  2980. return;
  2981. gcfs_rq->prop_runnable_sum = 0;
  2982. if (runnable_sum >= 0) {
  2983. /*
  2984. * Add runnable; clip at LOAD_AVG_MAX. Reflects that until
  2985. * the CPU is saturated running == runnable.
  2986. */
  2987. runnable_sum += se->avg.load_sum;
  2988. runnable_sum = min(runnable_sum, (long)LOAD_AVG_MAX);
  2989. } else {
  2990. /*
  2991. * Estimate the new unweighted runnable_sum of the gcfs_rq by
  2992. * assuming all tasks are equally runnable.
  2993. */
  2994. if (scale_load_down(gcfs_rq->load.weight)) {
  2995. load_sum = div_s64(gcfs_rq->avg.load_sum,
  2996. scale_load_down(gcfs_rq->load.weight));
  2997. }
  2998. /* But make sure to not inflate se's runnable */
  2999. runnable_sum = min(se->avg.load_sum, load_sum);
  3000. }
  3001. /*
  3002. * runnable_sum can't be lower than running_sum
  3003. * As running sum is scale with CPU capacity wehreas the runnable sum
  3004. * is not we rescale running_sum 1st
  3005. */
  3006. running_sum = se->avg.util_sum /
  3007. arch_scale_cpu_capacity(NULL, cpu_of(rq_of(cfs_rq)));
  3008. runnable_sum = max(runnable_sum, running_sum);
  3009. load_sum = (s64)se_weight(se) * runnable_sum;
  3010. load_avg = div_s64(load_sum, LOAD_AVG_MAX);
  3011. delta_sum = load_sum - (s64)se_weight(se) * se->avg.load_sum;
  3012. delta_avg = load_avg - se->avg.load_avg;
  3013. se->avg.load_sum = runnable_sum;
  3014. se->avg.load_avg = load_avg;
  3015. add_positive(&cfs_rq->avg.load_avg, delta_avg);
  3016. add_positive(&cfs_rq->avg.load_sum, delta_sum);
  3017. runnable_load_sum = (s64)se_runnable(se) * runnable_sum;
  3018. runnable_load_avg = div_s64(runnable_load_sum, LOAD_AVG_MAX);
  3019. delta_sum = runnable_load_sum - se_weight(se) * se->avg.runnable_load_sum;
  3020. delta_avg = runnable_load_avg - se->avg.runnable_load_avg;
  3021. se->avg.runnable_load_sum = runnable_sum;
  3022. se->avg.runnable_load_avg = runnable_load_avg;
  3023. if (se->on_rq) {
  3024. add_positive(&cfs_rq->avg.runnable_load_avg, delta_avg);
  3025. add_positive(&cfs_rq->avg.runnable_load_sum, delta_sum);
  3026. }
  3027. }
  3028. static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum)
  3029. {
  3030. cfs_rq->propagate = 1;
  3031. cfs_rq->prop_runnable_sum += runnable_sum;
  3032. }
  3033. /* Update task and its cfs_rq load average */
  3034. static inline int propagate_entity_load_avg(struct sched_entity *se)
  3035. {
  3036. struct cfs_rq *cfs_rq, *gcfs_rq;
  3037. if (entity_is_task(se))
  3038. return 0;
  3039. gcfs_rq = group_cfs_rq(se);
  3040. if (!gcfs_rq->propagate)
  3041. return 0;
  3042. gcfs_rq->propagate = 0;
  3043. cfs_rq = cfs_rq_of(se);
  3044. add_tg_cfs_propagate(cfs_rq, gcfs_rq->prop_runnable_sum);
  3045. update_tg_cfs_util(cfs_rq, se, gcfs_rq);
  3046. update_tg_cfs_runnable(cfs_rq, se, gcfs_rq);
  3047. return 1;
  3048. }
  3049. /*
  3050. * Check if we need to update the load and the utilization of a blocked
  3051. * group_entity:
  3052. */
  3053. static inline bool skip_blocked_update(struct sched_entity *se)
  3054. {
  3055. struct cfs_rq *gcfs_rq = group_cfs_rq(se);
  3056. /*
  3057. * If sched_entity still have not zero load or utilization, we have to
  3058. * decay it:
  3059. */
  3060. if (se->avg.load_avg || se->avg.util_avg)
  3061. return false;
  3062. /*
  3063. * If there is a pending propagation, we have to update the load and
  3064. * the utilization of the sched_entity:
  3065. */
  3066. if (gcfs_rq->propagate)
  3067. return false;
  3068. /*
  3069. * Otherwise, the load and the utilization of the sched_entity is
  3070. * already zero and there is no pending propagation, so it will be a
  3071. * waste of time to try to decay it:
  3072. */
  3073. return true;
  3074. }
  3075. #else /* CONFIG_FAIR_GROUP_SCHED */
  3076. static inline void update_tg_load_avg(struct cfs_rq *cfs_rq, int force) {}
  3077. static inline int propagate_entity_load_avg(struct sched_entity *se)
  3078. {
  3079. return 0;
  3080. }
  3081. static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum) {}
  3082. #endif /* CONFIG_FAIR_GROUP_SCHED */
  3083. /**
  3084. * update_cfs_rq_load_avg - update the cfs_rq's load/util averages
  3085. * @now: current time, as per cfs_rq_clock_task()
  3086. * @cfs_rq: cfs_rq to update
  3087. *
  3088. * The cfs_rq avg is the direct sum of all its entities (blocked and runnable)
  3089. * avg. The immediate corollary is that all (fair) tasks must be attached, see
  3090. * post_init_entity_util_avg().
  3091. *
  3092. * cfs_rq->avg is used for task_h_load() and update_cfs_share() for example.
  3093. *
  3094. * Returns true if the load decayed or we removed load.
  3095. *
  3096. * Since both these conditions indicate a changed cfs_rq->avg.load we should
  3097. * call update_tg_load_avg() when this function returns true.
  3098. */
  3099. static inline int
  3100. update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq)
  3101. {
  3102. unsigned long removed_load = 0, removed_util = 0, removed_runnable_sum = 0;
  3103. struct sched_avg *sa = &cfs_rq->avg;
  3104. int decayed = 0;
  3105. if (cfs_rq->removed.nr) {
  3106. unsigned long r;
  3107. u32 divider = LOAD_AVG_MAX - 1024 + sa->period_contrib;
  3108. raw_spin_lock(&cfs_rq->removed.lock);
  3109. swap(cfs_rq->removed.util_avg, removed_util);
  3110. swap(cfs_rq->removed.load_avg, removed_load);
  3111. swap(cfs_rq->removed.runnable_sum, removed_runnable_sum);
  3112. cfs_rq->removed.nr = 0;
  3113. raw_spin_unlock(&cfs_rq->removed.lock);
  3114. r = removed_load;
  3115. sub_positive(&sa->load_avg, r);
  3116. sub_positive(&sa->load_sum, r * divider);
  3117. r = removed_util;
  3118. sub_positive(&sa->util_avg, r);
  3119. sub_positive(&sa->util_sum, r * divider);
  3120. add_tg_cfs_propagate(cfs_rq, -(long)removed_runnable_sum);
  3121. decayed = 1;
  3122. }
  3123. decayed |= __update_load_avg_cfs_rq(now, cpu_of(rq_of(cfs_rq)), cfs_rq);
  3124. #ifndef CONFIG_64BIT
  3125. smp_wmb();
  3126. cfs_rq->load_last_update_time_copy = sa->last_update_time;
  3127. #endif
  3128. if (decayed)
  3129. cfs_rq_util_change(cfs_rq, 0);
  3130. return decayed;
  3131. }
  3132. /**
  3133. * attach_entity_load_avg - attach this entity to its cfs_rq load avg
  3134. * @cfs_rq: cfs_rq to attach to
  3135. * @se: sched_entity to attach
  3136. *
  3137. * Must call update_cfs_rq_load_avg() before this, since we rely on
  3138. * cfs_rq->avg.last_update_time being current.
  3139. */
  3140. static void attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
  3141. {
  3142. u32 divider = LOAD_AVG_MAX - 1024 + cfs_rq->avg.period_contrib;
  3143. /*
  3144. * When we attach the @se to the @cfs_rq, we must align the decay
  3145. * window because without that, really weird and wonderful things can
  3146. * happen.
  3147. *
  3148. * XXX illustrate
  3149. */
  3150. se->avg.last_update_time = cfs_rq->avg.last_update_time;
  3151. se->avg.period_contrib = cfs_rq->avg.period_contrib;
  3152. /*
  3153. * Hell(o) Nasty stuff.. we need to recompute _sum based on the new
  3154. * period_contrib. This isn't strictly correct, but since we're
  3155. * entirely outside of the PELT hierarchy, nobody cares if we truncate
  3156. * _sum a little.
  3157. */
  3158. se->avg.util_sum = se->avg.util_avg * divider;
  3159. se->avg.load_sum = divider;
  3160. if (se_weight(se)) {
  3161. se->avg.load_sum =
  3162. div_u64(se->avg.load_avg * se->avg.load_sum, se_weight(se));
  3163. }
  3164. se->avg.runnable_load_sum = se->avg.load_sum;
  3165. enqueue_load_avg(cfs_rq, se);
  3166. cfs_rq->avg.util_avg += se->avg.util_avg;
  3167. cfs_rq->avg.util_sum += se->avg.util_sum;
  3168. add_tg_cfs_propagate(cfs_rq, se->avg.load_sum);
  3169. cfs_rq_util_change(cfs_rq, flags);
  3170. }
  3171. /**
  3172. * detach_entity_load_avg - detach this entity from its cfs_rq load avg
  3173. * @cfs_rq: cfs_rq to detach from
  3174. * @se: sched_entity to detach
  3175. *
  3176. * Must call update_cfs_rq_load_avg() before this, since we rely on
  3177. * cfs_rq->avg.last_update_time being current.
  3178. */
  3179. static void detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
  3180. {
  3181. dequeue_load_avg(cfs_rq, se);
  3182. sub_positive(&cfs_rq->avg.util_avg, se->avg.util_avg);
  3183. sub_positive(&cfs_rq->avg.util_sum, se->avg.util_sum);
  3184. add_tg_cfs_propagate(cfs_rq, -se->avg.load_sum);
  3185. cfs_rq_util_change(cfs_rq, 0);
  3186. }
  3187. /*
  3188. * Optional action to be done while updating the load average
  3189. */
  3190. #define UPDATE_TG 0x1
  3191. #define SKIP_AGE_LOAD 0x2
  3192. #define DO_ATTACH 0x4
  3193. /* Update task and its cfs_rq load average */
  3194. static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
  3195. {
  3196. u64 now = cfs_rq_clock_task(cfs_rq);
  3197. struct rq *rq = rq_of(cfs_rq);
  3198. int cpu = cpu_of(rq);
  3199. int decayed;
  3200. /*
  3201. * Track task load average for carrying it to new CPU after migrated, and
  3202. * track group sched_entity load average for task_h_load calc in migration
  3203. */
  3204. if (se->avg.last_update_time && !(flags & SKIP_AGE_LOAD))
  3205. __update_load_avg_se(now, cpu, cfs_rq, se);
  3206. decayed = update_cfs_rq_load_avg(now, cfs_rq);
  3207. decayed |= propagate_entity_load_avg(se);
  3208. if (!se->avg.last_update_time && (flags & DO_ATTACH)) {
  3209. /*
  3210. * DO_ATTACH means we're here from enqueue_entity().
  3211. * !last_update_time means we've passed through
  3212. * migrate_task_rq_fair() indicating we migrated.
  3213. *
  3214. * IOW we're enqueueing a task on a new CPU.
  3215. */
  3216. attach_entity_load_avg(cfs_rq, se, SCHED_CPUFREQ_MIGRATION);
  3217. update_tg_load_avg(cfs_rq, 0);
  3218. } else if (decayed && (flags & UPDATE_TG))
  3219. update_tg_load_avg(cfs_rq, 0);
  3220. }
  3221. #ifndef CONFIG_64BIT
  3222. static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq)
  3223. {
  3224. u64 last_update_time_copy;
  3225. u64 last_update_time;
  3226. do {
  3227. last_update_time_copy = cfs_rq->load_last_update_time_copy;
  3228. smp_rmb();
  3229. last_update_time = cfs_rq->avg.last_update_time;
  3230. } while (last_update_time != last_update_time_copy);
  3231. return last_update_time;
  3232. }
  3233. #else
  3234. static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq)
  3235. {
  3236. return cfs_rq->avg.last_update_time;
  3237. }
  3238. #endif
  3239. /*
  3240. * Synchronize entity load avg of dequeued entity without locking
  3241. * the previous rq.
  3242. */
  3243. void sync_entity_load_avg(struct sched_entity *se)
  3244. {
  3245. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  3246. u64 last_update_time;
  3247. last_update_time = cfs_rq_last_update_time(cfs_rq);
  3248. __update_load_avg_blocked_se(last_update_time, cpu_of(rq_of(cfs_rq)), se);
  3249. }
  3250. /*
  3251. * Task first catches up with cfs_rq, and then subtract
  3252. * itself from the cfs_rq (task must be off the queue now).
  3253. */
  3254. void remove_entity_load_avg(struct sched_entity *se)
  3255. {
  3256. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  3257. unsigned long flags;
  3258. /*
  3259. * tasks cannot exit without having gone through wake_up_new_task() ->
  3260. * post_init_entity_util_avg() which will have added things to the
  3261. * cfs_rq, so we can remove unconditionally.
  3262. *
  3263. * Similarly for groups, they will have passed through
  3264. * post_init_entity_util_avg() before unregister_sched_fair_group()
  3265. * calls this.
  3266. */
  3267. sync_entity_load_avg(se);
  3268. raw_spin_lock_irqsave(&cfs_rq->removed.lock, flags);
  3269. ++cfs_rq->removed.nr;
  3270. cfs_rq->removed.util_avg += se->avg.util_avg;
  3271. cfs_rq->removed.load_avg += se->avg.load_avg;
  3272. cfs_rq->removed.runnable_sum += se->avg.load_sum; /* == runnable_sum */
  3273. raw_spin_unlock_irqrestore(&cfs_rq->removed.lock, flags);
  3274. }
  3275. static inline unsigned long cfs_rq_runnable_load_avg(struct cfs_rq *cfs_rq)
  3276. {
  3277. return cfs_rq->avg.runnable_load_avg;
  3278. }
  3279. static inline unsigned long cfs_rq_load_avg(struct cfs_rq *cfs_rq)
  3280. {
  3281. return cfs_rq->avg.load_avg;
  3282. }
  3283. static int idle_balance(struct rq *this_rq, struct rq_flags *rf);
  3284. static inline unsigned long task_util(struct task_struct *p)
  3285. {
  3286. return READ_ONCE(p->se.avg.util_avg);
  3287. }
  3288. static inline unsigned long _task_util_est(struct task_struct *p)
  3289. {
  3290. struct util_est ue = READ_ONCE(p->se.avg.util_est);
  3291. return max(ue.ewma, ue.enqueued);
  3292. }
  3293. static inline unsigned long task_util_est(struct task_struct *p)
  3294. {
  3295. return max(task_util(p), _task_util_est(p));
  3296. }
  3297. static inline void util_est_enqueue(struct cfs_rq *cfs_rq,
  3298. struct task_struct *p)
  3299. {
  3300. unsigned int enqueued;
  3301. if (!sched_feat(UTIL_EST))
  3302. return;
  3303. /* Update root cfs_rq's estimated utilization */
  3304. enqueued = cfs_rq->avg.util_est.enqueued;
  3305. enqueued += (_task_util_est(p) | UTIL_AVG_UNCHANGED);
  3306. WRITE_ONCE(cfs_rq->avg.util_est.enqueued, enqueued);
  3307. }
  3308. /*
  3309. * Check if a (signed) value is within a specified (unsigned) margin,
  3310. * based on the observation that:
  3311. *
  3312. * abs(x) < y := (unsigned)(x + y - 1) < (2 * y - 1)
  3313. *
  3314. * NOTE: this only works when value + maring < INT_MAX.
  3315. */
  3316. static inline bool within_margin(int value, int margin)
  3317. {
  3318. return ((unsigned int)(value + margin - 1) < (2 * margin - 1));
  3319. }
  3320. static void
  3321. util_est_dequeue(struct cfs_rq *cfs_rq, struct task_struct *p, bool task_sleep)
  3322. {
  3323. long last_ewma_diff;
  3324. struct util_est ue;
  3325. if (!sched_feat(UTIL_EST))
  3326. return;
  3327. /*
  3328. * Update root cfs_rq's estimated utilization
  3329. *
  3330. * If *p is the last task then the root cfs_rq's estimated utilization
  3331. * of a CPU is 0 by definition.
  3332. */
  3333. ue.enqueued = 0;
  3334. if (cfs_rq->nr_running) {
  3335. ue.enqueued = cfs_rq->avg.util_est.enqueued;
  3336. ue.enqueued -= min_t(unsigned int, ue.enqueued,
  3337. (_task_util_est(p) | UTIL_AVG_UNCHANGED));
  3338. }
  3339. WRITE_ONCE(cfs_rq->avg.util_est.enqueued, ue.enqueued);
  3340. /*
  3341. * Skip update of task's estimated utilization when the task has not
  3342. * yet completed an activation, e.g. being migrated.
  3343. */
  3344. if (!task_sleep)
  3345. return;
  3346. /*
  3347. * If the PELT values haven't changed since enqueue time,
  3348. * skip the util_est update.
  3349. */
  3350. ue = p->se.avg.util_est;
  3351. if (ue.enqueued & UTIL_AVG_UNCHANGED)
  3352. return;
  3353. /*
  3354. * Skip update of task's estimated utilization when its EWMA is
  3355. * already ~1% close to its last activation value.
  3356. */
  3357. ue.enqueued = (task_util(p) | UTIL_AVG_UNCHANGED);
  3358. last_ewma_diff = ue.enqueued - ue.ewma;
  3359. if (within_margin(last_ewma_diff, (SCHED_CAPACITY_SCALE / 100)))
  3360. return;
  3361. /*
  3362. * Update Task's estimated utilization
  3363. *
  3364. * When *p completes an activation we can consolidate another sample
  3365. * of the task size. This is done by storing the current PELT value
  3366. * as ue.enqueued and by using this value to update the Exponential
  3367. * Weighted Moving Average (EWMA):
  3368. *
  3369. * ewma(t) = w * task_util(p) + (1-w) * ewma(t-1)
  3370. * = w * task_util(p) + ewma(t-1) - w * ewma(t-1)
  3371. * = w * (task_util(p) - ewma(t-1)) + ewma(t-1)
  3372. * = w * ( last_ewma_diff ) + ewma(t-1)
  3373. * = w * (last_ewma_diff + ewma(t-1) / w)
  3374. *
  3375. * Where 'w' is the weight of new samples, which is configured to be
  3376. * 0.25, thus making w=1/4 ( >>= UTIL_EST_WEIGHT_SHIFT)
  3377. */
  3378. ue.ewma <<= UTIL_EST_WEIGHT_SHIFT;
  3379. ue.ewma += last_ewma_diff;
  3380. ue.ewma >>= UTIL_EST_WEIGHT_SHIFT;
  3381. WRITE_ONCE(p->se.avg.util_est, ue);
  3382. }
  3383. #else /* CONFIG_SMP */
  3384. static inline int
  3385. update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq)
  3386. {
  3387. return 0;
  3388. }
  3389. #define UPDATE_TG 0x0
  3390. #define SKIP_AGE_LOAD 0x0
  3391. #define DO_ATTACH 0x0
  3392. static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int not_used1)
  3393. {
  3394. cfs_rq_util_change(cfs_rq, 0);
  3395. }
  3396. static inline void remove_entity_load_avg(struct sched_entity *se) {}
  3397. static inline void
  3398. attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) {}
  3399. static inline void
  3400. detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
  3401. static inline int idle_balance(struct rq *rq, struct rq_flags *rf)
  3402. {
  3403. return 0;
  3404. }
  3405. static inline void
  3406. util_est_enqueue(struct cfs_rq *cfs_rq, struct task_struct *p) {}
  3407. static inline void
  3408. util_est_dequeue(struct cfs_rq *cfs_rq, struct task_struct *p,
  3409. bool task_sleep) {}
  3410. #endif /* CONFIG_SMP */
  3411. static void check_spread(struct cfs_rq *cfs_rq, struct sched_entity *se)
  3412. {
  3413. #ifdef CONFIG_SCHED_DEBUG
  3414. s64 d = se->vruntime - cfs_rq->min_vruntime;
  3415. if (d < 0)
  3416. d = -d;
  3417. if (d > 3*sysctl_sched_latency)
  3418. schedstat_inc(cfs_rq->nr_spread_over);
  3419. #endif
  3420. }
  3421. static void
  3422. place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int initial)
  3423. {
  3424. u64 vruntime = cfs_rq->min_vruntime;
  3425. /*
  3426. * The 'current' period is already promised to the current tasks,
  3427. * however the extra weight of the new task will slow them down a
  3428. * little, place the new task so that it fits in the slot that
  3429. * stays open at the end.
  3430. */
  3431. if (initial && sched_feat(START_DEBIT))
  3432. vruntime += sched_vslice(cfs_rq, se);
  3433. /* sleeps up to a single latency don't count. */
  3434. if (!initial) {
  3435. unsigned long thresh = sysctl_sched_latency;
  3436. /*
  3437. * Halve their sleep time's effect, to allow
  3438. * for a gentler effect of sleepers:
  3439. */
  3440. if (sched_feat(GENTLE_FAIR_SLEEPERS))
  3441. thresh >>= 1;
  3442. vruntime -= thresh;
  3443. }
  3444. /* ensure we never gain time by being placed backwards. */
  3445. se->vruntime = max_vruntime(se->vruntime, vruntime);
  3446. }
  3447. static void check_enqueue_throttle(struct cfs_rq *cfs_rq);
  3448. static inline void check_schedstat_required(void)
  3449. {
  3450. #ifdef CONFIG_SCHEDSTATS
  3451. if (schedstat_enabled())
  3452. return;
  3453. /* Force schedstat enabled if a dependent tracepoint is active */
  3454. if (trace_sched_stat_wait_enabled() ||
  3455. trace_sched_stat_sleep_enabled() ||
  3456. trace_sched_stat_iowait_enabled() ||
  3457. trace_sched_stat_blocked_enabled() ||
  3458. trace_sched_stat_runtime_enabled()) {
  3459. printk_deferred_once("Scheduler tracepoints stat_sleep, stat_iowait, "
  3460. "stat_blocked and stat_runtime require the "
  3461. "kernel parameter schedstats=enable or "
  3462. "kernel.sched_schedstats=1\n");
  3463. }
  3464. #endif
  3465. }
  3466. /*
  3467. * MIGRATION
  3468. *
  3469. * dequeue
  3470. * update_curr()
  3471. * update_min_vruntime()
  3472. * vruntime -= min_vruntime
  3473. *
  3474. * enqueue
  3475. * update_curr()
  3476. * update_min_vruntime()
  3477. * vruntime += min_vruntime
  3478. *
  3479. * this way the vruntime transition between RQs is done when both
  3480. * min_vruntime are up-to-date.
  3481. *
  3482. * WAKEUP (remote)
  3483. *
  3484. * ->migrate_task_rq_fair() (p->state == TASK_WAKING)
  3485. * vruntime -= min_vruntime
  3486. *
  3487. * enqueue
  3488. * update_curr()
  3489. * update_min_vruntime()
  3490. * vruntime += min_vruntime
  3491. *
  3492. * this way we don't have the most up-to-date min_vruntime on the originating
  3493. * CPU and an up-to-date min_vruntime on the destination CPU.
  3494. */
  3495. static void
  3496. enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
  3497. {
  3498. bool renorm = !(flags & ENQUEUE_WAKEUP) || (flags & ENQUEUE_MIGRATED);
  3499. bool curr = cfs_rq->curr == se;
  3500. /*
  3501. * If we're the current task, we must renormalise before calling
  3502. * update_curr().
  3503. */
  3504. if (renorm && curr)
  3505. se->vruntime += cfs_rq->min_vruntime;
  3506. update_curr(cfs_rq);
  3507. /*
  3508. * Otherwise, renormalise after, such that we're placed at the current
  3509. * moment in time, instead of some random moment in the past. Being
  3510. * placed in the past could significantly boost this task to the
  3511. * fairness detriment of existing tasks.
  3512. */
  3513. if (renorm && !curr)
  3514. se->vruntime += cfs_rq->min_vruntime;
  3515. /*
  3516. * When enqueuing a sched_entity, we must:
  3517. * - Update loads to have both entity and cfs_rq synced with now.
  3518. * - Add its load to cfs_rq->runnable_avg
  3519. * - For group_entity, update its weight to reflect the new share of
  3520. * its group cfs_rq
  3521. * - Add its new weight to cfs_rq->load.weight
  3522. */
  3523. update_load_avg(cfs_rq, se, UPDATE_TG | DO_ATTACH);
  3524. update_cfs_group(se);
  3525. enqueue_runnable_load_avg(cfs_rq, se);
  3526. account_entity_enqueue(cfs_rq, se);
  3527. if (flags & ENQUEUE_WAKEUP)
  3528. place_entity(cfs_rq, se, 0);
  3529. check_schedstat_required();
  3530. update_stats_enqueue(cfs_rq, se, flags);
  3531. check_spread(cfs_rq, se);
  3532. if (!curr)
  3533. __enqueue_entity(cfs_rq, se);
  3534. se->on_rq = 1;
  3535. if (cfs_rq->nr_running == 1) {
  3536. list_add_leaf_cfs_rq(cfs_rq);
  3537. check_enqueue_throttle(cfs_rq);
  3538. }
  3539. }
  3540. static void __clear_buddies_last(struct sched_entity *se)
  3541. {
  3542. for_each_sched_entity(se) {
  3543. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  3544. if (cfs_rq->last != se)
  3545. break;
  3546. cfs_rq->last = NULL;
  3547. }
  3548. }
  3549. static void __clear_buddies_next(struct sched_entity *se)
  3550. {
  3551. for_each_sched_entity(se) {
  3552. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  3553. if (cfs_rq->next != se)
  3554. break;
  3555. cfs_rq->next = NULL;
  3556. }
  3557. }
  3558. static void __clear_buddies_skip(struct sched_entity *se)
  3559. {
  3560. for_each_sched_entity(se) {
  3561. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  3562. if (cfs_rq->skip != se)
  3563. break;
  3564. cfs_rq->skip = NULL;
  3565. }
  3566. }
  3567. static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
  3568. {
  3569. if (cfs_rq->last == se)
  3570. __clear_buddies_last(se);
  3571. if (cfs_rq->next == se)
  3572. __clear_buddies_next(se);
  3573. if (cfs_rq->skip == se)
  3574. __clear_buddies_skip(se);
  3575. }
  3576. static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq);
  3577. static void
  3578. dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
  3579. {
  3580. /*
  3581. * Update run-time statistics of the 'current'.
  3582. */
  3583. update_curr(cfs_rq);
  3584. /*
  3585. * When dequeuing a sched_entity, we must:
  3586. * - Update loads to have both entity and cfs_rq synced with now.
  3587. * - Substract its load from the cfs_rq->runnable_avg.
  3588. * - Substract its previous weight from cfs_rq->load.weight.
  3589. * - For group entity, update its weight to reflect the new share
  3590. * of its group cfs_rq.
  3591. */
  3592. update_load_avg(cfs_rq, se, UPDATE_TG);
  3593. dequeue_runnable_load_avg(cfs_rq, se);
  3594. update_stats_dequeue(cfs_rq, se, flags);
  3595. clear_buddies(cfs_rq, se);
  3596. if (se != cfs_rq->curr)
  3597. __dequeue_entity(cfs_rq, se);
  3598. se->on_rq = 0;
  3599. account_entity_dequeue(cfs_rq, se);
  3600. /*
  3601. * Normalize after update_curr(); which will also have moved
  3602. * min_vruntime if @se is the one holding it back. But before doing
  3603. * update_min_vruntime() again, which will discount @se's position and
  3604. * can move min_vruntime forward still more.
  3605. */
  3606. if (!(flags & DEQUEUE_SLEEP))
  3607. se->vruntime -= cfs_rq->min_vruntime;
  3608. /* return excess runtime on last dequeue */
  3609. return_cfs_rq_runtime(cfs_rq);
  3610. update_cfs_group(se);
  3611. /*
  3612. * Now advance min_vruntime if @se was the entity holding it back,
  3613. * except when: DEQUEUE_SAVE && !DEQUEUE_MOVE, in this case we'll be
  3614. * put back on, and if we advance min_vruntime, we'll be placed back
  3615. * further than we started -- ie. we'll be penalized.
  3616. */
  3617. if ((flags & (DEQUEUE_SAVE | DEQUEUE_MOVE)) == DEQUEUE_SAVE)
  3618. update_min_vruntime(cfs_rq);
  3619. }
  3620. /*
  3621. * Preempt the current task with a newly woken task if needed:
  3622. */
  3623. static void
  3624. check_preempt_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr)
  3625. {
  3626. unsigned long ideal_runtime, delta_exec;
  3627. struct sched_entity *se;
  3628. s64 delta;
  3629. ideal_runtime = sched_slice(cfs_rq, curr);
  3630. delta_exec = curr->sum_exec_runtime - curr->prev_sum_exec_runtime;
  3631. if (delta_exec > ideal_runtime) {
  3632. resched_curr(rq_of(cfs_rq));
  3633. /*
  3634. * The current task ran long enough, ensure it doesn't get
  3635. * re-elected due to buddy favours.
  3636. */
  3637. clear_buddies(cfs_rq, curr);
  3638. return;
  3639. }
  3640. /*
  3641. * Ensure that a task that missed wakeup preemption by a
  3642. * narrow margin doesn't have to wait for a full slice.
  3643. * This also mitigates buddy induced latencies under load.
  3644. */
  3645. if (delta_exec < sysctl_sched_min_granularity)
  3646. return;
  3647. se = __pick_first_entity(cfs_rq);
  3648. delta = curr->vruntime - se->vruntime;
  3649. if (delta < 0)
  3650. return;
  3651. if (delta > ideal_runtime)
  3652. resched_curr(rq_of(cfs_rq));
  3653. }
  3654. static void
  3655. set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
  3656. {
  3657. /* 'current' is not kept within the tree. */
  3658. if (se->on_rq) {
  3659. /*
  3660. * Any task has to be enqueued before it get to execute on
  3661. * a CPU. So account for the time it spent waiting on the
  3662. * runqueue.
  3663. */
  3664. update_stats_wait_end(cfs_rq, se);
  3665. __dequeue_entity(cfs_rq, se);
  3666. update_load_avg(cfs_rq, se, UPDATE_TG);
  3667. }
  3668. update_stats_curr_start(cfs_rq, se);
  3669. cfs_rq->curr = se;
  3670. /*
  3671. * Track our maximum slice length, if the CPU's load is at
  3672. * least twice that of our own weight (i.e. dont track it
  3673. * when there are only lesser-weight tasks around):
  3674. */
  3675. if (schedstat_enabled() && rq_of(cfs_rq)->load.weight >= 2*se->load.weight) {
  3676. schedstat_set(se->statistics.slice_max,
  3677. max((u64)schedstat_val(se->statistics.slice_max),
  3678. se->sum_exec_runtime - se->prev_sum_exec_runtime));
  3679. }
  3680. se->prev_sum_exec_runtime = se->sum_exec_runtime;
  3681. }
  3682. static int
  3683. wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se);
  3684. /*
  3685. * Pick the next process, keeping these things in mind, in this order:
  3686. * 1) keep things fair between processes/task groups
  3687. * 2) pick the "next" process, since someone really wants that to run
  3688. * 3) pick the "last" process, for cache locality
  3689. * 4) do not run the "skip" process, if something else is available
  3690. */
  3691. static struct sched_entity *
  3692. pick_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *curr)
  3693. {
  3694. struct sched_entity *left = __pick_first_entity(cfs_rq);
  3695. struct sched_entity *se;
  3696. /*
  3697. * If curr is set we have to see if its left of the leftmost entity
  3698. * still in the tree, provided there was anything in the tree at all.
  3699. */
  3700. if (!left || (curr && entity_before(curr, left)))
  3701. left = curr;
  3702. se = left; /* ideally we run the leftmost entity */
  3703. /*
  3704. * Avoid running the skip buddy, if running something else can
  3705. * be done without getting too unfair.
  3706. */
  3707. if (cfs_rq->skip == se) {
  3708. struct sched_entity *second;
  3709. if (se == curr) {
  3710. second = __pick_first_entity(cfs_rq);
  3711. } else {
  3712. second = __pick_next_entity(se);
  3713. if (!second || (curr && entity_before(curr, second)))
  3714. second = curr;
  3715. }
  3716. if (second && wakeup_preempt_entity(second, left) < 1)
  3717. se = second;
  3718. }
  3719. /*
  3720. * Prefer last buddy, try to return the CPU to a preempted task.
  3721. */
  3722. if (cfs_rq->last && wakeup_preempt_entity(cfs_rq->last, left) < 1)
  3723. se = cfs_rq->last;
  3724. /*
  3725. * Someone really wants this to run. If it's not unfair, run it.
  3726. */
  3727. if (cfs_rq->next && wakeup_preempt_entity(cfs_rq->next, left) < 1)
  3728. se = cfs_rq->next;
  3729. clear_buddies(cfs_rq, se);
  3730. return se;
  3731. }
  3732. static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq);
  3733. static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
  3734. {
  3735. /*
  3736. * If still on the runqueue then deactivate_task()
  3737. * was not called and update_curr() has to be done:
  3738. */
  3739. if (prev->on_rq)
  3740. update_curr(cfs_rq);
  3741. /* throttle cfs_rqs exceeding runtime */
  3742. check_cfs_rq_runtime(cfs_rq);
  3743. check_spread(cfs_rq, prev);
  3744. if (prev->on_rq) {
  3745. update_stats_wait_start(cfs_rq, prev);
  3746. /* Put 'current' back into the tree. */
  3747. __enqueue_entity(cfs_rq, prev);
  3748. /* in !on_rq case, update occurred at dequeue */
  3749. update_load_avg(cfs_rq, prev, 0);
  3750. }
  3751. cfs_rq->curr = NULL;
  3752. }
  3753. static void
  3754. entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
  3755. {
  3756. /*
  3757. * Update run-time statistics of the 'current'.
  3758. */
  3759. update_curr(cfs_rq);
  3760. /*
  3761. * Ensure that runnable average is periodically updated.
  3762. */
  3763. update_load_avg(cfs_rq, curr, UPDATE_TG);
  3764. update_cfs_group(curr);
  3765. #ifdef CONFIG_SCHED_HRTICK
  3766. /*
  3767. * queued ticks are scheduled to match the slice, so don't bother
  3768. * validating it and just reschedule.
  3769. */
  3770. if (queued) {
  3771. resched_curr(rq_of(cfs_rq));
  3772. return;
  3773. }
  3774. /*
  3775. * don't let the period tick interfere with the hrtick preemption
  3776. */
  3777. if (!sched_feat(DOUBLE_TICK) &&
  3778. hrtimer_active(&rq_of(cfs_rq)->hrtick_timer))
  3779. return;
  3780. #endif
  3781. if (cfs_rq->nr_running > 1)
  3782. check_preempt_tick(cfs_rq, curr);
  3783. }
  3784. /**************************************************
  3785. * CFS bandwidth control machinery
  3786. */
  3787. #ifdef CONFIG_CFS_BANDWIDTH
  3788. #ifdef HAVE_JUMP_LABEL
  3789. static struct static_key __cfs_bandwidth_used;
  3790. static inline bool cfs_bandwidth_used(void)
  3791. {
  3792. return static_key_false(&__cfs_bandwidth_used);
  3793. }
  3794. void cfs_bandwidth_usage_inc(void)
  3795. {
  3796. static_key_slow_inc_cpuslocked(&__cfs_bandwidth_used);
  3797. }
  3798. void cfs_bandwidth_usage_dec(void)
  3799. {
  3800. static_key_slow_dec_cpuslocked(&__cfs_bandwidth_used);
  3801. }
  3802. #else /* HAVE_JUMP_LABEL */
  3803. static bool cfs_bandwidth_used(void)
  3804. {
  3805. return true;
  3806. }
  3807. void cfs_bandwidth_usage_inc(void) {}
  3808. void cfs_bandwidth_usage_dec(void) {}
  3809. #endif /* HAVE_JUMP_LABEL */
  3810. /*
  3811. * default period for cfs group bandwidth.
  3812. * default: 0.1s, units: nanoseconds
  3813. */
  3814. static inline u64 default_cfs_period(void)
  3815. {
  3816. return 100000000ULL;
  3817. }
  3818. static inline u64 sched_cfs_bandwidth_slice(void)
  3819. {
  3820. return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC;
  3821. }
  3822. /*
  3823. * Replenish runtime according to assigned quota and update expiration time.
  3824. * We use sched_clock_cpu directly instead of rq->clock to avoid adding
  3825. * additional synchronization around rq->lock.
  3826. *
  3827. * requires cfs_b->lock
  3828. */
  3829. void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
  3830. {
  3831. u64 now;
  3832. if (cfs_b->quota == RUNTIME_INF)
  3833. return;
  3834. now = sched_clock_cpu(smp_processor_id());
  3835. cfs_b->runtime = cfs_b->quota;
  3836. cfs_b->runtime_expires = now + ktime_to_ns(cfs_b->period);
  3837. }
  3838. static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
  3839. {
  3840. return &tg->cfs_bandwidth;
  3841. }
  3842. /* rq->task_clock normalized against any time this cfs_rq has spent throttled */
  3843. static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq)
  3844. {
  3845. if (unlikely(cfs_rq->throttle_count))
  3846. return cfs_rq->throttled_clock_task - cfs_rq->throttled_clock_task_time;
  3847. return rq_clock_task(rq_of(cfs_rq)) - cfs_rq->throttled_clock_task_time;
  3848. }
  3849. /* returns 0 on failure to allocate runtime */
  3850. static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  3851. {
  3852. struct task_group *tg = cfs_rq->tg;
  3853. struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(tg);
  3854. u64 amount = 0, min_amount, expires;
  3855. /* note: this is a positive sum as runtime_remaining <= 0 */
  3856. min_amount = sched_cfs_bandwidth_slice() - cfs_rq->runtime_remaining;
  3857. raw_spin_lock(&cfs_b->lock);
  3858. if (cfs_b->quota == RUNTIME_INF)
  3859. amount = min_amount;
  3860. else {
  3861. start_cfs_bandwidth(cfs_b);
  3862. if (cfs_b->runtime > 0) {
  3863. amount = min(cfs_b->runtime, min_amount);
  3864. cfs_b->runtime -= amount;
  3865. cfs_b->idle = 0;
  3866. }
  3867. }
  3868. expires = cfs_b->runtime_expires;
  3869. raw_spin_unlock(&cfs_b->lock);
  3870. cfs_rq->runtime_remaining += amount;
  3871. /*
  3872. * we may have advanced our local expiration to account for allowed
  3873. * spread between our sched_clock and the one on which runtime was
  3874. * issued.
  3875. */
  3876. if ((s64)(expires - cfs_rq->runtime_expires) > 0)
  3877. cfs_rq->runtime_expires = expires;
  3878. return cfs_rq->runtime_remaining > 0;
  3879. }
  3880. /*
  3881. * Note: This depends on the synchronization provided by sched_clock and the
  3882. * fact that rq->clock snapshots this value.
  3883. */
  3884. static void expire_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  3885. {
  3886. struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
  3887. /* if the deadline is ahead of our clock, nothing to do */
  3888. if (likely((s64)(rq_clock(rq_of(cfs_rq)) - cfs_rq->runtime_expires) < 0))
  3889. return;
  3890. if (cfs_rq->runtime_remaining < 0)
  3891. return;
  3892. /*
  3893. * If the local deadline has passed we have to consider the
  3894. * possibility that our sched_clock is 'fast' and the global deadline
  3895. * has not truly expired.
  3896. *
  3897. * Fortunately we can check determine whether this the case by checking
  3898. * whether the global deadline has advanced. It is valid to compare
  3899. * cfs_b->runtime_expires without any locks since we only care about
  3900. * exact equality, so a partial write will still work.
  3901. */
  3902. if (cfs_rq->runtime_expires != cfs_b->runtime_expires) {
  3903. /* extend local deadline, drift is bounded above by 2 ticks */
  3904. cfs_rq->runtime_expires += TICK_NSEC;
  3905. } else {
  3906. /* global deadline is ahead, expiration has passed */
  3907. cfs_rq->runtime_remaining = 0;
  3908. }
  3909. }
  3910. static void __account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
  3911. {
  3912. /* dock delta_exec before expiring quota (as it could span periods) */
  3913. cfs_rq->runtime_remaining -= delta_exec;
  3914. expire_cfs_rq_runtime(cfs_rq);
  3915. if (likely(cfs_rq->runtime_remaining > 0))
  3916. return;
  3917. /*
  3918. * if we're unable to extend our runtime we resched so that the active
  3919. * hierarchy can be throttled
  3920. */
  3921. if (!assign_cfs_rq_runtime(cfs_rq) && likely(cfs_rq->curr))
  3922. resched_curr(rq_of(cfs_rq));
  3923. }
  3924. static __always_inline
  3925. void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
  3926. {
  3927. if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled)
  3928. return;
  3929. __account_cfs_rq_runtime(cfs_rq, delta_exec);
  3930. }
  3931. static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
  3932. {
  3933. return cfs_bandwidth_used() && cfs_rq->throttled;
  3934. }
  3935. /* check whether cfs_rq, or any parent, is throttled */
  3936. static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
  3937. {
  3938. return cfs_bandwidth_used() && cfs_rq->throttle_count;
  3939. }
  3940. /*
  3941. * Ensure that neither of the group entities corresponding to src_cpu or
  3942. * dest_cpu are members of a throttled hierarchy when performing group
  3943. * load-balance operations.
  3944. */
  3945. static inline int throttled_lb_pair(struct task_group *tg,
  3946. int src_cpu, int dest_cpu)
  3947. {
  3948. struct cfs_rq *src_cfs_rq, *dest_cfs_rq;
  3949. src_cfs_rq = tg->cfs_rq[src_cpu];
  3950. dest_cfs_rq = tg->cfs_rq[dest_cpu];
  3951. return throttled_hierarchy(src_cfs_rq) ||
  3952. throttled_hierarchy(dest_cfs_rq);
  3953. }
  3954. /* updated child weight may affect parent so we have to do this bottom up */
  3955. static int tg_unthrottle_up(struct task_group *tg, void *data)
  3956. {
  3957. struct rq *rq = data;
  3958. struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
  3959. cfs_rq->throttle_count--;
  3960. if (!cfs_rq->throttle_count) {
  3961. /* adjust cfs_rq_clock_task() */
  3962. cfs_rq->throttled_clock_task_time += rq_clock_task(rq) -
  3963. cfs_rq->throttled_clock_task;
  3964. }
  3965. return 0;
  3966. }
  3967. static int tg_throttle_down(struct task_group *tg, void *data)
  3968. {
  3969. struct rq *rq = data;
  3970. struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
  3971. /* group is entering throttled state, stop time */
  3972. if (!cfs_rq->throttle_count)
  3973. cfs_rq->throttled_clock_task = rq_clock_task(rq);
  3974. cfs_rq->throttle_count++;
  3975. return 0;
  3976. }
  3977. static void throttle_cfs_rq(struct cfs_rq *cfs_rq)
  3978. {
  3979. struct rq *rq = rq_of(cfs_rq);
  3980. struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
  3981. struct sched_entity *se;
  3982. long task_delta, dequeue = 1;
  3983. bool empty;
  3984. se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))];
  3985. /* freeze hierarchy runnable averages while throttled */
  3986. rcu_read_lock();
  3987. walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq);
  3988. rcu_read_unlock();
  3989. task_delta = cfs_rq->h_nr_running;
  3990. for_each_sched_entity(se) {
  3991. struct cfs_rq *qcfs_rq = cfs_rq_of(se);
  3992. /* throttled entity or throttle-on-deactivate */
  3993. if (!se->on_rq)
  3994. break;
  3995. if (dequeue)
  3996. dequeue_entity(qcfs_rq, se, DEQUEUE_SLEEP);
  3997. qcfs_rq->h_nr_running -= task_delta;
  3998. if (qcfs_rq->load.weight)
  3999. dequeue = 0;
  4000. }
  4001. if (!se)
  4002. sub_nr_running(rq, task_delta);
  4003. cfs_rq->throttled = 1;
  4004. cfs_rq->throttled_clock = rq_clock(rq);
  4005. raw_spin_lock(&cfs_b->lock);
  4006. empty = list_empty(&cfs_b->throttled_cfs_rq);
  4007. /*
  4008. * Add to the _head_ of the list, so that an already-started
  4009. * distribute_cfs_runtime will not see us
  4010. */
  4011. list_add_rcu(&cfs_rq->throttled_list, &cfs_b->throttled_cfs_rq);
  4012. /*
  4013. * If we're the first throttled task, make sure the bandwidth
  4014. * timer is running.
  4015. */
  4016. if (empty)
  4017. start_cfs_bandwidth(cfs_b);
  4018. raw_spin_unlock(&cfs_b->lock);
  4019. }
  4020. void unthrottle_cfs_rq(struct cfs_rq *cfs_rq)
  4021. {
  4022. struct rq *rq = rq_of(cfs_rq);
  4023. struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
  4024. struct sched_entity *se;
  4025. int enqueue = 1;
  4026. long task_delta;
  4027. se = cfs_rq->tg->se[cpu_of(rq)];
  4028. cfs_rq->throttled = 0;
  4029. update_rq_clock(rq);
  4030. raw_spin_lock(&cfs_b->lock);
  4031. cfs_b->throttled_time += rq_clock(rq) - cfs_rq->throttled_clock;
  4032. list_del_rcu(&cfs_rq->throttled_list);
  4033. raw_spin_unlock(&cfs_b->lock);
  4034. /* update hierarchical throttle state */
  4035. walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq);
  4036. if (!cfs_rq->load.weight)
  4037. return;
  4038. task_delta = cfs_rq->h_nr_running;
  4039. for_each_sched_entity(se) {
  4040. if (se->on_rq)
  4041. enqueue = 0;
  4042. cfs_rq = cfs_rq_of(se);
  4043. if (enqueue)
  4044. enqueue_entity(cfs_rq, se, ENQUEUE_WAKEUP);
  4045. cfs_rq->h_nr_running += task_delta;
  4046. if (cfs_rq_throttled(cfs_rq))
  4047. break;
  4048. }
  4049. if (!se)
  4050. add_nr_running(rq, task_delta);
  4051. /* Determine whether we need to wake up potentially idle CPU: */
  4052. if (rq->curr == rq->idle && rq->cfs.nr_running)
  4053. resched_curr(rq);
  4054. }
  4055. static u64 distribute_cfs_runtime(struct cfs_bandwidth *cfs_b,
  4056. u64 remaining, u64 expires)
  4057. {
  4058. struct cfs_rq *cfs_rq;
  4059. u64 runtime;
  4060. u64 starting_runtime = remaining;
  4061. rcu_read_lock();
  4062. list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
  4063. throttled_list) {
  4064. struct rq *rq = rq_of(cfs_rq);
  4065. struct rq_flags rf;
  4066. rq_lock(rq, &rf);
  4067. if (!cfs_rq_throttled(cfs_rq))
  4068. goto next;
  4069. runtime = -cfs_rq->runtime_remaining + 1;
  4070. if (runtime > remaining)
  4071. runtime = remaining;
  4072. remaining -= runtime;
  4073. cfs_rq->runtime_remaining += runtime;
  4074. cfs_rq->runtime_expires = expires;
  4075. /* we check whether we're throttled above */
  4076. if (cfs_rq->runtime_remaining > 0)
  4077. unthrottle_cfs_rq(cfs_rq);
  4078. next:
  4079. rq_unlock(rq, &rf);
  4080. if (!remaining)
  4081. break;
  4082. }
  4083. rcu_read_unlock();
  4084. return starting_runtime - remaining;
  4085. }
  4086. /*
  4087. * Responsible for refilling a task_group's bandwidth and unthrottling its
  4088. * cfs_rqs as appropriate. If there has been no activity within the last
  4089. * period the timer is deactivated until scheduling resumes; cfs_b->idle is
  4090. * used to track this state.
  4091. */
  4092. static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun)
  4093. {
  4094. u64 runtime, runtime_expires;
  4095. int throttled;
  4096. /* no need to continue the timer with no bandwidth constraint */
  4097. if (cfs_b->quota == RUNTIME_INF)
  4098. goto out_deactivate;
  4099. throttled = !list_empty(&cfs_b->throttled_cfs_rq);
  4100. cfs_b->nr_periods += overrun;
  4101. /*
  4102. * idle depends on !throttled (for the case of a large deficit), and if
  4103. * we're going inactive then everything else can be deferred
  4104. */
  4105. if (cfs_b->idle && !throttled)
  4106. goto out_deactivate;
  4107. __refill_cfs_bandwidth_runtime(cfs_b);
  4108. if (!throttled) {
  4109. /* mark as potentially idle for the upcoming period */
  4110. cfs_b->idle = 1;
  4111. return 0;
  4112. }
  4113. /* account preceding periods in which throttling occurred */
  4114. cfs_b->nr_throttled += overrun;
  4115. runtime_expires = cfs_b->runtime_expires;
  4116. /*
  4117. * This check is repeated as we are holding onto the new bandwidth while
  4118. * we unthrottle. This can potentially race with an unthrottled group
  4119. * trying to acquire new bandwidth from the global pool. This can result
  4120. * in us over-using our runtime if it is all used during this loop, but
  4121. * only by limited amounts in that extreme case.
  4122. */
  4123. while (throttled && cfs_b->runtime > 0) {
  4124. runtime = cfs_b->runtime;
  4125. raw_spin_unlock(&cfs_b->lock);
  4126. /* we can't nest cfs_b->lock while distributing bandwidth */
  4127. runtime = distribute_cfs_runtime(cfs_b, runtime,
  4128. runtime_expires);
  4129. raw_spin_lock(&cfs_b->lock);
  4130. throttled = !list_empty(&cfs_b->throttled_cfs_rq);
  4131. cfs_b->runtime -= min(runtime, cfs_b->runtime);
  4132. }
  4133. /*
  4134. * While we are ensured activity in the period following an
  4135. * unthrottle, this also covers the case in which the new bandwidth is
  4136. * insufficient to cover the existing bandwidth deficit. (Forcing the
  4137. * timer to remain active while there are any throttled entities.)
  4138. */
  4139. cfs_b->idle = 0;
  4140. return 0;
  4141. out_deactivate:
  4142. return 1;
  4143. }
  4144. /* a cfs_rq won't donate quota below this amount */
  4145. static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC;
  4146. /* minimum remaining period time to redistribute slack quota */
  4147. static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC;
  4148. /* how long we wait to gather additional slack before distributing */
  4149. static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC;
  4150. /*
  4151. * Are we near the end of the current quota period?
  4152. *
  4153. * Requires cfs_b->lock for hrtimer_expires_remaining to be safe against the
  4154. * hrtimer base being cleared by hrtimer_start. In the case of
  4155. * migrate_hrtimers, base is never cleared, so we are fine.
  4156. */
  4157. static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire)
  4158. {
  4159. struct hrtimer *refresh_timer = &cfs_b->period_timer;
  4160. u64 remaining;
  4161. /* if the call-back is running a quota refresh is already occurring */
  4162. if (hrtimer_callback_running(refresh_timer))
  4163. return 1;
  4164. /* is a quota refresh about to occur? */
  4165. remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer));
  4166. if (remaining < min_expire)
  4167. return 1;
  4168. return 0;
  4169. }
  4170. static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b)
  4171. {
  4172. u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration;
  4173. /* if there's a quota refresh soon don't bother with slack */
  4174. if (runtime_refresh_within(cfs_b, min_left))
  4175. return;
  4176. hrtimer_start(&cfs_b->slack_timer,
  4177. ns_to_ktime(cfs_bandwidth_slack_period),
  4178. HRTIMER_MODE_REL);
  4179. }
  4180. /* we know any runtime found here is valid as update_curr() precedes return */
  4181. static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  4182. {
  4183. struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
  4184. s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;
  4185. if (slack_runtime <= 0)
  4186. return;
  4187. raw_spin_lock(&cfs_b->lock);
  4188. if (cfs_b->quota != RUNTIME_INF &&
  4189. cfs_rq->runtime_expires == cfs_b->runtime_expires) {
  4190. cfs_b->runtime += slack_runtime;
  4191. /* we are under rq->lock, defer unthrottling using a timer */
  4192. if (cfs_b->runtime > sched_cfs_bandwidth_slice() &&
  4193. !list_empty(&cfs_b->throttled_cfs_rq))
  4194. start_cfs_slack_bandwidth(cfs_b);
  4195. }
  4196. raw_spin_unlock(&cfs_b->lock);
  4197. /* even if it's not valid for return we don't want to try again */
  4198. cfs_rq->runtime_remaining -= slack_runtime;
  4199. }
  4200. static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  4201. {
  4202. if (!cfs_bandwidth_used())
  4203. return;
  4204. if (!cfs_rq->runtime_enabled || cfs_rq->nr_running)
  4205. return;
  4206. __return_cfs_rq_runtime(cfs_rq);
  4207. }
  4208. /*
  4209. * This is done with a timer (instead of inline with bandwidth return) since
  4210. * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
  4211. */
  4212. static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)
  4213. {
  4214. u64 runtime = 0, slice = sched_cfs_bandwidth_slice();
  4215. u64 expires;
  4216. /* confirm we're still not at a refresh boundary */
  4217. raw_spin_lock(&cfs_b->lock);
  4218. if (runtime_refresh_within(cfs_b, min_bandwidth_expiration)) {
  4219. raw_spin_unlock(&cfs_b->lock);
  4220. return;
  4221. }
  4222. if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice)
  4223. runtime = cfs_b->runtime;
  4224. expires = cfs_b->runtime_expires;
  4225. raw_spin_unlock(&cfs_b->lock);
  4226. if (!runtime)
  4227. return;
  4228. runtime = distribute_cfs_runtime(cfs_b, runtime, expires);
  4229. raw_spin_lock(&cfs_b->lock);
  4230. if (expires == cfs_b->runtime_expires)
  4231. cfs_b->runtime -= min(runtime, cfs_b->runtime);
  4232. raw_spin_unlock(&cfs_b->lock);
  4233. }
  4234. /*
  4235. * When a group wakes up we want to make sure that its quota is not already
  4236. * expired/exceeded, otherwise it may be allowed to steal additional ticks of
  4237. * runtime as update_curr() throttling can not not trigger until it's on-rq.
  4238. */
  4239. static void check_enqueue_throttle(struct cfs_rq *cfs_rq)
  4240. {
  4241. if (!cfs_bandwidth_used())
  4242. return;
  4243. /* an active group must be handled by the update_curr()->put() path */
  4244. if (!cfs_rq->runtime_enabled || cfs_rq->curr)
  4245. return;
  4246. /* ensure the group is not already throttled */
  4247. if (cfs_rq_throttled(cfs_rq))
  4248. return;
  4249. /* update runtime allocation */
  4250. account_cfs_rq_runtime(cfs_rq, 0);
  4251. if (cfs_rq->runtime_remaining <= 0)
  4252. throttle_cfs_rq(cfs_rq);
  4253. }
  4254. static void sync_throttle(struct task_group *tg, int cpu)
  4255. {
  4256. struct cfs_rq *pcfs_rq, *cfs_rq;
  4257. if (!cfs_bandwidth_used())
  4258. return;
  4259. if (!tg->parent)
  4260. return;
  4261. cfs_rq = tg->cfs_rq[cpu];
  4262. pcfs_rq = tg->parent->cfs_rq[cpu];
  4263. cfs_rq->throttle_count = pcfs_rq->throttle_count;
  4264. cfs_rq->throttled_clock_task = rq_clock_task(cpu_rq(cpu));
  4265. }
  4266. /* conditionally throttle active cfs_rq's from put_prev_entity() */
  4267. static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  4268. {
  4269. if (!cfs_bandwidth_used())
  4270. return false;
  4271. if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0))
  4272. return false;
  4273. /*
  4274. * it's possible for a throttled entity to be forced into a running
  4275. * state (e.g. set_curr_task), in this case we're finished.
  4276. */
  4277. if (cfs_rq_throttled(cfs_rq))
  4278. return true;
  4279. throttle_cfs_rq(cfs_rq);
  4280. return true;
  4281. }
  4282. static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer)
  4283. {
  4284. struct cfs_bandwidth *cfs_b =
  4285. container_of(timer, struct cfs_bandwidth, slack_timer);
  4286. do_sched_cfs_slack_timer(cfs_b);
  4287. return HRTIMER_NORESTART;
  4288. }
  4289. static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)
  4290. {
  4291. struct cfs_bandwidth *cfs_b =
  4292. container_of(timer, struct cfs_bandwidth, period_timer);
  4293. int overrun;
  4294. int idle = 0;
  4295. raw_spin_lock(&cfs_b->lock);
  4296. for (;;) {
  4297. overrun = hrtimer_forward_now(timer, cfs_b->period);
  4298. if (!overrun)
  4299. break;
  4300. idle = do_sched_cfs_period_timer(cfs_b, overrun);
  4301. }
  4302. if (idle)
  4303. cfs_b->period_active = 0;
  4304. raw_spin_unlock(&cfs_b->lock);
  4305. return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
  4306. }
  4307. void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
  4308. {
  4309. raw_spin_lock_init(&cfs_b->lock);
  4310. cfs_b->runtime = 0;
  4311. cfs_b->quota = RUNTIME_INF;
  4312. cfs_b->period = ns_to_ktime(default_cfs_period());
  4313. INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq);
  4314. hrtimer_init(&cfs_b->period_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED);
  4315. cfs_b->period_timer.function = sched_cfs_period_timer;
  4316. hrtimer_init(&cfs_b->slack_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
  4317. cfs_b->slack_timer.function = sched_cfs_slack_timer;
  4318. }
  4319. static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  4320. {
  4321. cfs_rq->runtime_enabled = 0;
  4322. INIT_LIST_HEAD(&cfs_rq->throttled_list);
  4323. }
  4324. void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
  4325. {
  4326. lockdep_assert_held(&cfs_b->lock);
  4327. if (!cfs_b->period_active) {
  4328. cfs_b->period_active = 1;
  4329. hrtimer_forward_now(&cfs_b->period_timer, cfs_b->period);
  4330. hrtimer_start_expires(&cfs_b->period_timer, HRTIMER_MODE_ABS_PINNED);
  4331. }
  4332. }
  4333. static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
  4334. {
  4335. /* init_cfs_bandwidth() was not called */
  4336. if (!cfs_b->throttled_cfs_rq.next)
  4337. return;
  4338. hrtimer_cancel(&cfs_b->period_timer);
  4339. hrtimer_cancel(&cfs_b->slack_timer);
  4340. }
  4341. /*
  4342. * Both these CPU hotplug callbacks race against unregister_fair_sched_group()
  4343. *
  4344. * The race is harmless, since modifying bandwidth settings of unhooked group
  4345. * bits doesn't do much.
  4346. */
  4347. /* cpu online calback */
  4348. static void __maybe_unused update_runtime_enabled(struct rq *rq)
  4349. {
  4350. struct task_group *tg;
  4351. lockdep_assert_held(&rq->lock);
  4352. rcu_read_lock();
  4353. list_for_each_entry_rcu(tg, &task_groups, list) {
  4354. struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
  4355. struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
  4356. raw_spin_lock(&cfs_b->lock);
  4357. cfs_rq->runtime_enabled = cfs_b->quota != RUNTIME_INF;
  4358. raw_spin_unlock(&cfs_b->lock);
  4359. }
  4360. rcu_read_unlock();
  4361. }
  4362. /* cpu offline callback */
  4363. static void __maybe_unused unthrottle_offline_cfs_rqs(struct rq *rq)
  4364. {
  4365. struct task_group *tg;
  4366. lockdep_assert_held(&rq->lock);
  4367. rcu_read_lock();
  4368. list_for_each_entry_rcu(tg, &task_groups, list) {
  4369. struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
  4370. if (!cfs_rq->runtime_enabled)
  4371. continue;
  4372. /*
  4373. * clock_task is not advancing so we just need to make sure
  4374. * there's some valid quota amount
  4375. */
  4376. cfs_rq->runtime_remaining = 1;
  4377. /*
  4378. * Offline rq is schedulable till CPU is completely disabled
  4379. * in take_cpu_down(), so we prevent new cfs throttling here.
  4380. */
  4381. cfs_rq->runtime_enabled = 0;
  4382. if (cfs_rq_throttled(cfs_rq))
  4383. unthrottle_cfs_rq(cfs_rq);
  4384. }
  4385. rcu_read_unlock();
  4386. }
  4387. #else /* CONFIG_CFS_BANDWIDTH */
  4388. static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq)
  4389. {
  4390. return rq_clock_task(rq_of(cfs_rq));
  4391. }
  4392. static void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) {}
  4393. static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq) { return false; }
  4394. static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {}
  4395. static inline void sync_throttle(struct task_group *tg, int cpu) {}
  4396. static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
  4397. static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
  4398. {
  4399. return 0;
  4400. }
  4401. static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
  4402. {
  4403. return 0;
  4404. }
  4405. static inline int throttled_lb_pair(struct task_group *tg,
  4406. int src_cpu, int dest_cpu)
  4407. {
  4408. return 0;
  4409. }
  4410. void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
  4411. #ifdef CONFIG_FAIR_GROUP_SCHED
  4412. static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
  4413. #endif
  4414. static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
  4415. {
  4416. return NULL;
  4417. }
  4418. static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
  4419. static inline void update_runtime_enabled(struct rq *rq) {}
  4420. static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {}
  4421. #endif /* CONFIG_CFS_BANDWIDTH */
  4422. /**************************************************
  4423. * CFS operations on tasks:
  4424. */
  4425. #ifdef CONFIG_SCHED_HRTICK
  4426. static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
  4427. {
  4428. struct sched_entity *se = &p->se;
  4429. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  4430. SCHED_WARN_ON(task_rq(p) != rq);
  4431. if (rq->cfs.h_nr_running > 1) {
  4432. u64 slice = sched_slice(cfs_rq, se);
  4433. u64 ran = se->sum_exec_runtime - se->prev_sum_exec_runtime;
  4434. s64 delta = slice - ran;
  4435. if (delta < 0) {
  4436. if (rq->curr == p)
  4437. resched_curr(rq);
  4438. return;
  4439. }
  4440. hrtick_start(rq, delta);
  4441. }
  4442. }
  4443. /*
  4444. * called from enqueue/dequeue and updates the hrtick when the
  4445. * current task is from our class and nr_running is low enough
  4446. * to matter.
  4447. */
  4448. static void hrtick_update(struct rq *rq)
  4449. {
  4450. struct task_struct *curr = rq->curr;
  4451. if (!hrtick_enabled(rq) || curr->sched_class != &fair_sched_class)
  4452. return;
  4453. if (cfs_rq_of(&curr->se)->nr_running < sched_nr_latency)
  4454. hrtick_start_fair(rq, curr);
  4455. }
  4456. #else /* !CONFIG_SCHED_HRTICK */
  4457. static inline void
  4458. hrtick_start_fair(struct rq *rq, struct task_struct *p)
  4459. {
  4460. }
  4461. static inline void hrtick_update(struct rq *rq)
  4462. {
  4463. }
  4464. #endif
  4465. /*
  4466. * The enqueue_task method is called before nr_running is
  4467. * increased. Here we update the fair scheduling stats and
  4468. * then put the task into the rbtree:
  4469. */
  4470. static void
  4471. enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
  4472. {
  4473. struct cfs_rq *cfs_rq;
  4474. struct sched_entity *se = &p->se;
  4475. /*
  4476. * If in_iowait is set, the code below may not trigger any cpufreq
  4477. * utilization updates, so do it here explicitly with the IOWAIT flag
  4478. * passed.
  4479. */
  4480. if (p->in_iowait)
  4481. cpufreq_update_util(rq, SCHED_CPUFREQ_IOWAIT);
  4482. for_each_sched_entity(se) {
  4483. if (se->on_rq)
  4484. break;
  4485. cfs_rq = cfs_rq_of(se);
  4486. enqueue_entity(cfs_rq, se, flags);
  4487. /*
  4488. * end evaluation on encountering a throttled cfs_rq
  4489. *
  4490. * note: in the case of encountering a throttled cfs_rq we will
  4491. * post the final h_nr_running increment below.
  4492. */
  4493. if (cfs_rq_throttled(cfs_rq))
  4494. break;
  4495. cfs_rq->h_nr_running++;
  4496. flags = ENQUEUE_WAKEUP;
  4497. }
  4498. for_each_sched_entity(se) {
  4499. cfs_rq = cfs_rq_of(se);
  4500. cfs_rq->h_nr_running++;
  4501. if (cfs_rq_throttled(cfs_rq))
  4502. break;
  4503. update_load_avg(cfs_rq, se, UPDATE_TG);
  4504. update_cfs_group(se);
  4505. }
  4506. if (!se)
  4507. add_nr_running(rq, 1);
  4508. util_est_enqueue(&rq->cfs, p);
  4509. hrtick_update(rq);
  4510. }
  4511. static void set_next_buddy(struct sched_entity *se);
  4512. /*
  4513. * The dequeue_task method is called before nr_running is
  4514. * decreased. We remove the task from the rbtree and
  4515. * update the fair scheduling stats:
  4516. */
  4517. static void dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
  4518. {
  4519. struct cfs_rq *cfs_rq;
  4520. struct sched_entity *se = &p->se;
  4521. int task_sleep = flags & DEQUEUE_SLEEP;
  4522. for_each_sched_entity(se) {
  4523. cfs_rq = cfs_rq_of(se);
  4524. dequeue_entity(cfs_rq, se, flags);
  4525. /*
  4526. * end evaluation on encountering a throttled cfs_rq
  4527. *
  4528. * note: in the case of encountering a throttled cfs_rq we will
  4529. * post the final h_nr_running decrement below.
  4530. */
  4531. if (cfs_rq_throttled(cfs_rq))
  4532. break;
  4533. cfs_rq->h_nr_running--;
  4534. /* Don't dequeue parent if it has other entities besides us */
  4535. if (cfs_rq->load.weight) {
  4536. /* Avoid re-evaluating load for this entity: */
  4537. se = parent_entity(se);
  4538. /*
  4539. * Bias pick_next to pick a task from this cfs_rq, as
  4540. * p is sleeping when it is within its sched_slice.
  4541. */
  4542. if (task_sleep && se && !throttled_hierarchy(cfs_rq))
  4543. set_next_buddy(se);
  4544. break;
  4545. }
  4546. flags |= DEQUEUE_SLEEP;
  4547. }
  4548. for_each_sched_entity(se) {
  4549. cfs_rq = cfs_rq_of(se);
  4550. cfs_rq->h_nr_running--;
  4551. if (cfs_rq_throttled(cfs_rq))
  4552. break;
  4553. update_load_avg(cfs_rq, se, UPDATE_TG);
  4554. update_cfs_group(se);
  4555. }
  4556. if (!se)
  4557. sub_nr_running(rq, 1);
  4558. util_est_dequeue(&rq->cfs, p, task_sleep);
  4559. hrtick_update(rq);
  4560. }
  4561. #ifdef CONFIG_SMP
  4562. /* Working cpumask for: load_balance, load_balance_newidle. */
  4563. DEFINE_PER_CPU(cpumask_var_t, load_balance_mask);
  4564. DEFINE_PER_CPU(cpumask_var_t, select_idle_mask);
  4565. #ifdef CONFIG_NO_HZ_COMMON
  4566. /*
  4567. * per rq 'load' arrray crap; XXX kill this.
  4568. */
  4569. /*
  4570. * The exact cpuload calculated at every tick would be:
  4571. *
  4572. * load' = (1 - 1/2^i) * load + (1/2^i) * cur_load
  4573. *
  4574. * If a CPU misses updates for n ticks (as it was idle) and update gets
  4575. * called on the n+1-th tick when CPU may be busy, then we have:
  4576. *
  4577. * load_n = (1 - 1/2^i)^n * load_0
  4578. * load_n+1 = (1 - 1/2^i) * load_n + (1/2^i) * cur_load
  4579. *
  4580. * decay_load_missed() below does efficient calculation of
  4581. *
  4582. * load' = (1 - 1/2^i)^n * load
  4583. *
  4584. * Because x^(n+m) := x^n * x^m we can decompose any x^n in power-of-2 factors.
  4585. * This allows us to precompute the above in said factors, thereby allowing the
  4586. * reduction of an arbitrary n in O(log_2 n) steps. (See also
  4587. * fixed_power_int())
  4588. *
  4589. * The calculation is approximated on a 128 point scale.
  4590. */
  4591. #define DEGRADE_SHIFT 7
  4592. static const u8 degrade_zero_ticks[CPU_LOAD_IDX_MAX] = {0, 8, 32, 64, 128};
  4593. static const u8 degrade_factor[CPU_LOAD_IDX_MAX][DEGRADE_SHIFT + 1] = {
  4594. { 0, 0, 0, 0, 0, 0, 0, 0 },
  4595. { 64, 32, 8, 0, 0, 0, 0, 0 },
  4596. { 96, 72, 40, 12, 1, 0, 0, 0 },
  4597. { 112, 98, 75, 43, 15, 1, 0, 0 },
  4598. { 120, 112, 98, 76, 45, 16, 2, 0 }
  4599. };
  4600. /*
  4601. * Update cpu_load for any missed ticks, due to tickless idle. The backlog
  4602. * would be when CPU is idle and so we just decay the old load without
  4603. * adding any new load.
  4604. */
  4605. static unsigned long
  4606. decay_load_missed(unsigned long load, unsigned long missed_updates, int idx)
  4607. {
  4608. int j = 0;
  4609. if (!missed_updates)
  4610. return load;
  4611. if (missed_updates >= degrade_zero_ticks[idx])
  4612. return 0;
  4613. if (idx == 1)
  4614. return load >> missed_updates;
  4615. while (missed_updates) {
  4616. if (missed_updates % 2)
  4617. load = (load * degrade_factor[idx][j]) >> DEGRADE_SHIFT;
  4618. missed_updates >>= 1;
  4619. j++;
  4620. }
  4621. return load;
  4622. }
  4623. static struct {
  4624. cpumask_var_t idle_cpus_mask;
  4625. atomic_t nr_cpus;
  4626. int has_blocked; /* Idle CPUS has blocked load */
  4627. unsigned long next_balance; /* in jiffy units */
  4628. unsigned long next_blocked; /* Next update of blocked load in jiffies */
  4629. } nohz ____cacheline_aligned;
  4630. #endif /* CONFIG_NO_HZ_COMMON */
  4631. /**
  4632. * __cpu_load_update - update the rq->cpu_load[] statistics
  4633. * @this_rq: The rq to update statistics for
  4634. * @this_load: The current load
  4635. * @pending_updates: The number of missed updates
  4636. *
  4637. * Update rq->cpu_load[] statistics. This function is usually called every
  4638. * scheduler tick (TICK_NSEC).
  4639. *
  4640. * This function computes a decaying average:
  4641. *
  4642. * load[i]' = (1 - 1/2^i) * load[i] + (1/2^i) * load
  4643. *
  4644. * Because of NOHZ it might not get called on every tick which gives need for
  4645. * the @pending_updates argument.
  4646. *
  4647. * load[i]_n = (1 - 1/2^i) * load[i]_n-1 + (1/2^i) * load_n-1
  4648. * = A * load[i]_n-1 + B ; A := (1 - 1/2^i), B := (1/2^i) * load
  4649. * = A * (A * load[i]_n-2 + B) + B
  4650. * = A * (A * (A * load[i]_n-3 + B) + B) + B
  4651. * = A^3 * load[i]_n-3 + (A^2 + A + 1) * B
  4652. * = A^n * load[i]_0 + (A^(n-1) + A^(n-2) + ... + 1) * B
  4653. * = A^n * load[i]_0 + ((1 - A^n) / (1 - A)) * B
  4654. * = (1 - 1/2^i)^n * (load[i]_0 - load) + load
  4655. *
  4656. * In the above we've assumed load_n := load, which is true for NOHZ_FULL as
  4657. * any change in load would have resulted in the tick being turned back on.
  4658. *
  4659. * For regular NOHZ, this reduces to:
  4660. *
  4661. * load[i]_n = (1 - 1/2^i)^n * load[i]_0
  4662. *
  4663. * see decay_load_misses(). For NOHZ_FULL we get to subtract and add the extra
  4664. * term.
  4665. */
  4666. static void cpu_load_update(struct rq *this_rq, unsigned long this_load,
  4667. unsigned long pending_updates)
  4668. {
  4669. unsigned long __maybe_unused tickless_load = this_rq->cpu_load[0];
  4670. int i, scale;
  4671. this_rq->nr_load_updates++;
  4672. /* Update our load: */
  4673. this_rq->cpu_load[0] = this_load; /* Fasttrack for idx 0 */
  4674. for (i = 1, scale = 2; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
  4675. unsigned long old_load, new_load;
  4676. /* scale is effectively 1 << i now, and >> i divides by scale */
  4677. old_load = this_rq->cpu_load[i];
  4678. #ifdef CONFIG_NO_HZ_COMMON
  4679. old_load = decay_load_missed(old_load, pending_updates - 1, i);
  4680. if (tickless_load) {
  4681. old_load -= decay_load_missed(tickless_load, pending_updates - 1, i);
  4682. /*
  4683. * old_load can never be a negative value because a
  4684. * decayed tickless_load cannot be greater than the
  4685. * original tickless_load.
  4686. */
  4687. old_load += tickless_load;
  4688. }
  4689. #endif
  4690. new_load = this_load;
  4691. /*
  4692. * Round up the averaging division if load is increasing. This
  4693. * prevents us from getting stuck on 9 if the load is 10, for
  4694. * example.
  4695. */
  4696. if (new_load > old_load)
  4697. new_load += scale - 1;
  4698. this_rq->cpu_load[i] = (old_load * (scale - 1) + new_load) >> i;
  4699. }
  4700. sched_avg_update(this_rq);
  4701. }
  4702. /* Used instead of source_load when we know the type == 0 */
  4703. static unsigned long weighted_cpuload(struct rq *rq)
  4704. {
  4705. return cfs_rq_runnable_load_avg(&rq->cfs);
  4706. }
  4707. #ifdef CONFIG_NO_HZ_COMMON
  4708. /*
  4709. * There is no sane way to deal with nohz on smp when using jiffies because the
  4710. * CPU doing the jiffies update might drift wrt the CPU doing the jiffy reading
  4711. * causing off-by-one errors in observed deltas; {0,2} instead of {1,1}.
  4712. *
  4713. * Therefore we need to avoid the delta approach from the regular tick when
  4714. * possible since that would seriously skew the load calculation. This is why we
  4715. * use cpu_load_update_periodic() for CPUs out of nohz. However we'll rely on
  4716. * jiffies deltas for updates happening while in nohz mode (idle ticks, idle
  4717. * loop exit, nohz_idle_balance, nohz full exit...)
  4718. *
  4719. * This means we might still be one tick off for nohz periods.
  4720. */
  4721. static void cpu_load_update_nohz(struct rq *this_rq,
  4722. unsigned long curr_jiffies,
  4723. unsigned long load)
  4724. {
  4725. unsigned long pending_updates;
  4726. pending_updates = curr_jiffies - this_rq->last_load_update_tick;
  4727. if (pending_updates) {
  4728. this_rq->last_load_update_tick = curr_jiffies;
  4729. /*
  4730. * In the regular NOHZ case, we were idle, this means load 0.
  4731. * In the NOHZ_FULL case, we were non-idle, we should consider
  4732. * its weighted load.
  4733. */
  4734. cpu_load_update(this_rq, load, pending_updates);
  4735. }
  4736. }
  4737. /*
  4738. * Called from nohz_idle_balance() to update the load ratings before doing the
  4739. * idle balance.
  4740. */
  4741. static void cpu_load_update_idle(struct rq *this_rq)
  4742. {
  4743. /*
  4744. * bail if there's load or we're actually up-to-date.
  4745. */
  4746. if (weighted_cpuload(this_rq))
  4747. return;
  4748. cpu_load_update_nohz(this_rq, READ_ONCE(jiffies), 0);
  4749. }
  4750. /*
  4751. * Record CPU load on nohz entry so we know the tickless load to account
  4752. * on nohz exit. cpu_load[0] happens then to be updated more frequently
  4753. * than other cpu_load[idx] but it should be fine as cpu_load readers
  4754. * shouldn't rely into synchronized cpu_load[*] updates.
  4755. */
  4756. void cpu_load_update_nohz_start(void)
  4757. {
  4758. struct rq *this_rq = this_rq();
  4759. /*
  4760. * This is all lockless but should be fine. If weighted_cpuload changes
  4761. * concurrently we'll exit nohz. And cpu_load write can race with
  4762. * cpu_load_update_idle() but both updater would be writing the same.
  4763. */
  4764. this_rq->cpu_load[0] = weighted_cpuload(this_rq);
  4765. }
  4766. /*
  4767. * Account the tickless load in the end of a nohz frame.
  4768. */
  4769. void cpu_load_update_nohz_stop(void)
  4770. {
  4771. unsigned long curr_jiffies = READ_ONCE(jiffies);
  4772. struct rq *this_rq = this_rq();
  4773. unsigned long load;
  4774. struct rq_flags rf;
  4775. if (curr_jiffies == this_rq->last_load_update_tick)
  4776. return;
  4777. load = weighted_cpuload(this_rq);
  4778. rq_lock(this_rq, &rf);
  4779. update_rq_clock(this_rq);
  4780. cpu_load_update_nohz(this_rq, curr_jiffies, load);
  4781. rq_unlock(this_rq, &rf);
  4782. }
  4783. #else /* !CONFIG_NO_HZ_COMMON */
  4784. static inline void cpu_load_update_nohz(struct rq *this_rq,
  4785. unsigned long curr_jiffies,
  4786. unsigned long load) { }
  4787. #endif /* CONFIG_NO_HZ_COMMON */
  4788. static void cpu_load_update_periodic(struct rq *this_rq, unsigned long load)
  4789. {
  4790. #ifdef CONFIG_NO_HZ_COMMON
  4791. /* See the mess around cpu_load_update_nohz(). */
  4792. this_rq->last_load_update_tick = READ_ONCE(jiffies);
  4793. #endif
  4794. cpu_load_update(this_rq, load, 1);
  4795. }
  4796. /*
  4797. * Called from scheduler_tick()
  4798. */
  4799. void cpu_load_update_active(struct rq *this_rq)
  4800. {
  4801. unsigned long load = weighted_cpuload(this_rq);
  4802. if (tick_nohz_tick_stopped())
  4803. cpu_load_update_nohz(this_rq, READ_ONCE(jiffies), load);
  4804. else
  4805. cpu_load_update_periodic(this_rq, load);
  4806. }
  4807. /*
  4808. * Return a low guess at the load of a migration-source CPU weighted
  4809. * according to the scheduling class and "nice" value.
  4810. *
  4811. * We want to under-estimate the load of migration sources, to
  4812. * balance conservatively.
  4813. */
  4814. static unsigned long source_load(int cpu, int type)
  4815. {
  4816. struct rq *rq = cpu_rq(cpu);
  4817. unsigned long total = weighted_cpuload(rq);
  4818. if (type == 0 || !sched_feat(LB_BIAS))
  4819. return total;
  4820. return min(rq->cpu_load[type-1], total);
  4821. }
  4822. /*
  4823. * Return a high guess at the load of a migration-target CPU weighted
  4824. * according to the scheduling class and "nice" value.
  4825. */
  4826. static unsigned long target_load(int cpu, int type)
  4827. {
  4828. struct rq *rq = cpu_rq(cpu);
  4829. unsigned long total = weighted_cpuload(rq);
  4830. if (type == 0 || !sched_feat(LB_BIAS))
  4831. return total;
  4832. return max(rq->cpu_load[type-1], total);
  4833. }
  4834. static unsigned long capacity_of(int cpu)
  4835. {
  4836. return cpu_rq(cpu)->cpu_capacity;
  4837. }
  4838. static unsigned long capacity_orig_of(int cpu)
  4839. {
  4840. return cpu_rq(cpu)->cpu_capacity_orig;
  4841. }
  4842. static unsigned long cpu_avg_load_per_task(int cpu)
  4843. {
  4844. struct rq *rq = cpu_rq(cpu);
  4845. unsigned long nr_running = READ_ONCE(rq->cfs.h_nr_running);
  4846. unsigned long load_avg = weighted_cpuload(rq);
  4847. if (nr_running)
  4848. return load_avg / nr_running;
  4849. return 0;
  4850. }
  4851. static void record_wakee(struct task_struct *p)
  4852. {
  4853. /*
  4854. * Only decay a single time; tasks that have less then 1 wakeup per
  4855. * jiffy will not have built up many flips.
  4856. */
  4857. if (time_after(jiffies, current->wakee_flip_decay_ts + HZ)) {
  4858. current->wakee_flips >>= 1;
  4859. current->wakee_flip_decay_ts = jiffies;
  4860. }
  4861. if (current->last_wakee != p) {
  4862. current->last_wakee = p;
  4863. current->wakee_flips++;
  4864. }
  4865. }
  4866. /*
  4867. * Detect M:N waker/wakee relationships via a switching-frequency heuristic.
  4868. *
  4869. * A waker of many should wake a different task than the one last awakened
  4870. * at a frequency roughly N times higher than one of its wakees.
  4871. *
  4872. * In order to determine whether we should let the load spread vs consolidating
  4873. * to shared cache, we look for a minimum 'flip' frequency of llc_size in one
  4874. * partner, and a factor of lls_size higher frequency in the other.
  4875. *
  4876. * With both conditions met, we can be relatively sure that the relationship is
  4877. * non-monogamous, with partner count exceeding socket size.
  4878. *
  4879. * Waker/wakee being client/server, worker/dispatcher, interrupt source or
  4880. * whatever is irrelevant, spread criteria is apparent partner count exceeds
  4881. * socket size.
  4882. */
  4883. static int wake_wide(struct task_struct *p)
  4884. {
  4885. unsigned int master = current->wakee_flips;
  4886. unsigned int slave = p->wakee_flips;
  4887. int factor = this_cpu_read(sd_llc_size);
  4888. if (master < slave)
  4889. swap(master, slave);
  4890. if (slave < factor || master < slave * factor)
  4891. return 0;
  4892. return 1;
  4893. }
  4894. /*
  4895. * The purpose of wake_affine() is to quickly determine on which CPU we can run
  4896. * soonest. For the purpose of speed we only consider the waking and previous
  4897. * CPU.
  4898. *
  4899. * wake_affine_idle() - only considers 'now', it check if the waking CPU is
  4900. * cache-affine and is (or will be) idle.
  4901. *
  4902. * wake_affine_weight() - considers the weight to reflect the average
  4903. * scheduling latency of the CPUs. This seems to work
  4904. * for the overloaded case.
  4905. */
  4906. static int
  4907. wake_affine_idle(int this_cpu, int prev_cpu, int sync)
  4908. {
  4909. /*
  4910. * If this_cpu is idle, it implies the wakeup is from interrupt
  4911. * context. Only allow the move if cache is shared. Otherwise an
  4912. * interrupt intensive workload could force all tasks onto one
  4913. * node depending on the IO topology or IRQ affinity settings.
  4914. *
  4915. * If the prev_cpu is idle and cache affine then avoid a migration.
  4916. * There is no guarantee that the cache hot data from an interrupt
  4917. * is more important than cache hot data on the prev_cpu and from
  4918. * a cpufreq perspective, it's better to have higher utilisation
  4919. * on one CPU.
  4920. */
  4921. if (idle_cpu(this_cpu) && cpus_share_cache(this_cpu, prev_cpu))
  4922. return idle_cpu(prev_cpu) ? prev_cpu : this_cpu;
  4923. if (sync && cpu_rq(this_cpu)->nr_running == 1)
  4924. return this_cpu;
  4925. return nr_cpumask_bits;
  4926. }
  4927. static int
  4928. wake_affine_weight(struct sched_domain *sd, struct task_struct *p,
  4929. int this_cpu, int prev_cpu, int sync)
  4930. {
  4931. s64 this_eff_load, prev_eff_load;
  4932. unsigned long task_load;
  4933. this_eff_load = target_load(this_cpu, sd->wake_idx);
  4934. if (sync) {
  4935. unsigned long current_load = task_h_load(current);
  4936. if (current_load > this_eff_load)
  4937. return this_cpu;
  4938. this_eff_load -= current_load;
  4939. }
  4940. task_load = task_h_load(p);
  4941. this_eff_load += task_load;
  4942. if (sched_feat(WA_BIAS))
  4943. this_eff_load *= 100;
  4944. this_eff_load *= capacity_of(prev_cpu);
  4945. prev_eff_load = source_load(prev_cpu, sd->wake_idx);
  4946. prev_eff_load -= task_load;
  4947. if (sched_feat(WA_BIAS))
  4948. prev_eff_load *= 100 + (sd->imbalance_pct - 100) / 2;
  4949. prev_eff_load *= capacity_of(this_cpu);
  4950. /*
  4951. * If sync, adjust the weight of prev_eff_load such that if
  4952. * prev_eff == this_eff that select_idle_sibling() will consider
  4953. * stacking the wakee on top of the waker if no other CPU is
  4954. * idle.
  4955. */
  4956. if (sync)
  4957. prev_eff_load += 1;
  4958. return this_eff_load < prev_eff_load ? this_cpu : nr_cpumask_bits;
  4959. }
  4960. static int wake_affine(struct sched_domain *sd, struct task_struct *p,
  4961. int this_cpu, int prev_cpu, int sync)
  4962. {
  4963. int target = nr_cpumask_bits;
  4964. if (sched_feat(WA_IDLE))
  4965. target = wake_affine_idle(this_cpu, prev_cpu, sync);
  4966. if (sched_feat(WA_WEIGHT) && target == nr_cpumask_bits)
  4967. target = wake_affine_weight(sd, p, this_cpu, prev_cpu, sync);
  4968. schedstat_inc(p->se.statistics.nr_wakeups_affine_attempts);
  4969. if (target == nr_cpumask_bits)
  4970. return prev_cpu;
  4971. schedstat_inc(sd->ttwu_move_affine);
  4972. schedstat_inc(p->se.statistics.nr_wakeups_affine);
  4973. return target;
  4974. }
  4975. static unsigned long cpu_util_wake(int cpu, struct task_struct *p);
  4976. static unsigned long capacity_spare_wake(int cpu, struct task_struct *p)
  4977. {
  4978. return max_t(long, capacity_of(cpu) - cpu_util_wake(cpu, p), 0);
  4979. }
  4980. /*
  4981. * find_idlest_group finds and returns the least busy CPU group within the
  4982. * domain.
  4983. *
  4984. * Assumes p is allowed on at least one CPU in sd.
  4985. */
  4986. static struct sched_group *
  4987. find_idlest_group(struct sched_domain *sd, struct task_struct *p,
  4988. int this_cpu, int sd_flag)
  4989. {
  4990. struct sched_group *idlest = NULL, *group = sd->groups;
  4991. struct sched_group *most_spare_sg = NULL;
  4992. unsigned long min_runnable_load = ULONG_MAX;
  4993. unsigned long this_runnable_load = ULONG_MAX;
  4994. unsigned long min_avg_load = ULONG_MAX, this_avg_load = ULONG_MAX;
  4995. unsigned long most_spare = 0, this_spare = 0;
  4996. int load_idx = sd->forkexec_idx;
  4997. int imbalance_scale = 100 + (sd->imbalance_pct-100)/2;
  4998. unsigned long imbalance = scale_load_down(NICE_0_LOAD) *
  4999. (sd->imbalance_pct-100) / 100;
  5000. if (sd_flag & SD_BALANCE_WAKE)
  5001. load_idx = sd->wake_idx;
  5002. do {
  5003. unsigned long load, avg_load, runnable_load;
  5004. unsigned long spare_cap, max_spare_cap;
  5005. int local_group;
  5006. int i;
  5007. /* Skip over this group if it has no CPUs allowed */
  5008. if (!cpumask_intersects(sched_group_span(group),
  5009. &p->cpus_allowed))
  5010. continue;
  5011. local_group = cpumask_test_cpu(this_cpu,
  5012. sched_group_span(group));
  5013. /*
  5014. * Tally up the load of all CPUs in the group and find
  5015. * the group containing the CPU with most spare capacity.
  5016. */
  5017. avg_load = 0;
  5018. runnable_load = 0;
  5019. max_spare_cap = 0;
  5020. for_each_cpu(i, sched_group_span(group)) {
  5021. /* Bias balancing toward CPUs of our domain */
  5022. if (local_group)
  5023. load = source_load(i, load_idx);
  5024. else
  5025. load = target_load(i, load_idx);
  5026. runnable_load += load;
  5027. avg_load += cfs_rq_load_avg(&cpu_rq(i)->cfs);
  5028. spare_cap = capacity_spare_wake(i, p);
  5029. if (spare_cap > max_spare_cap)
  5030. max_spare_cap = spare_cap;
  5031. }
  5032. /* Adjust by relative CPU capacity of the group */
  5033. avg_load = (avg_load * SCHED_CAPACITY_SCALE) /
  5034. group->sgc->capacity;
  5035. runnable_load = (runnable_load * SCHED_CAPACITY_SCALE) /
  5036. group->sgc->capacity;
  5037. if (local_group) {
  5038. this_runnable_load = runnable_load;
  5039. this_avg_load = avg_load;
  5040. this_spare = max_spare_cap;
  5041. } else {
  5042. if (min_runnable_load > (runnable_load + imbalance)) {
  5043. /*
  5044. * The runnable load is significantly smaller
  5045. * so we can pick this new CPU:
  5046. */
  5047. min_runnable_load = runnable_load;
  5048. min_avg_load = avg_load;
  5049. idlest = group;
  5050. } else if ((runnable_load < (min_runnable_load + imbalance)) &&
  5051. (100*min_avg_load > imbalance_scale*avg_load)) {
  5052. /*
  5053. * The runnable loads are close so take the
  5054. * blocked load into account through avg_load:
  5055. */
  5056. min_avg_load = avg_load;
  5057. idlest = group;
  5058. }
  5059. if (most_spare < max_spare_cap) {
  5060. most_spare = max_spare_cap;
  5061. most_spare_sg = group;
  5062. }
  5063. }
  5064. } while (group = group->next, group != sd->groups);
  5065. /*
  5066. * The cross-over point between using spare capacity or least load
  5067. * is too conservative for high utilization tasks on partially
  5068. * utilized systems if we require spare_capacity > task_util(p),
  5069. * so we allow for some task stuffing by using
  5070. * spare_capacity > task_util(p)/2.
  5071. *
  5072. * Spare capacity can't be used for fork because the utilization has
  5073. * not been set yet, we must first select a rq to compute the initial
  5074. * utilization.
  5075. */
  5076. if (sd_flag & SD_BALANCE_FORK)
  5077. goto skip_spare;
  5078. if (this_spare > task_util(p) / 2 &&
  5079. imbalance_scale*this_spare > 100*most_spare)
  5080. return NULL;
  5081. if (most_spare > task_util(p) / 2)
  5082. return most_spare_sg;
  5083. skip_spare:
  5084. if (!idlest)
  5085. return NULL;
  5086. /*
  5087. * When comparing groups across NUMA domains, it's possible for the
  5088. * local domain to be very lightly loaded relative to the remote
  5089. * domains but "imbalance" skews the comparison making remote CPUs
  5090. * look much more favourable. When considering cross-domain, add
  5091. * imbalance to the runnable load on the remote node and consider
  5092. * staying local.
  5093. */
  5094. if ((sd->flags & SD_NUMA) &&
  5095. min_runnable_load + imbalance >= this_runnable_load)
  5096. return NULL;
  5097. if (min_runnable_load > (this_runnable_load + imbalance))
  5098. return NULL;
  5099. if ((this_runnable_load < (min_runnable_load + imbalance)) &&
  5100. (100*this_avg_load < imbalance_scale*min_avg_load))
  5101. return NULL;
  5102. return idlest;
  5103. }
  5104. /*
  5105. * find_idlest_group_cpu - find the idlest CPU among the CPUs in the group.
  5106. */
  5107. static int
  5108. find_idlest_group_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
  5109. {
  5110. unsigned long load, min_load = ULONG_MAX;
  5111. unsigned int min_exit_latency = UINT_MAX;
  5112. u64 latest_idle_timestamp = 0;
  5113. int least_loaded_cpu = this_cpu;
  5114. int shallowest_idle_cpu = -1;
  5115. int i;
  5116. /* Check if we have any choice: */
  5117. if (group->group_weight == 1)
  5118. return cpumask_first(sched_group_span(group));
  5119. /* Traverse only the allowed CPUs */
  5120. for_each_cpu_and(i, sched_group_span(group), &p->cpus_allowed) {
  5121. if (idle_cpu(i)) {
  5122. struct rq *rq = cpu_rq(i);
  5123. struct cpuidle_state *idle = idle_get_state(rq);
  5124. if (idle && idle->exit_latency < min_exit_latency) {
  5125. /*
  5126. * We give priority to a CPU whose idle state
  5127. * has the smallest exit latency irrespective
  5128. * of any idle timestamp.
  5129. */
  5130. min_exit_latency = idle->exit_latency;
  5131. latest_idle_timestamp = rq->idle_stamp;
  5132. shallowest_idle_cpu = i;
  5133. } else if ((!idle || idle->exit_latency == min_exit_latency) &&
  5134. rq->idle_stamp > latest_idle_timestamp) {
  5135. /*
  5136. * If equal or no active idle state, then
  5137. * the most recently idled CPU might have
  5138. * a warmer cache.
  5139. */
  5140. latest_idle_timestamp = rq->idle_stamp;
  5141. shallowest_idle_cpu = i;
  5142. }
  5143. } else if (shallowest_idle_cpu == -1) {
  5144. load = weighted_cpuload(cpu_rq(i));
  5145. if (load < min_load) {
  5146. min_load = load;
  5147. least_loaded_cpu = i;
  5148. }
  5149. }
  5150. }
  5151. return shallowest_idle_cpu != -1 ? shallowest_idle_cpu : least_loaded_cpu;
  5152. }
  5153. static inline int find_idlest_cpu(struct sched_domain *sd, struct task_struct *p,
  5154. int cpu, int prev_cpu, int sd_flag)
  5155. {
  5156. int new_cpu = cpu;
  5157. if (!cpumask_intersects(sched_domain_span(sd), &p->cpus_allowed))
  5158. return prev_cpu;
  5159. while (sd) {
  5160. struct sched_group *group;
  5161. struct sched_domain *tmp;
  5162. int weight;
  5163. if (!(sd->flags & sd_flag)) {
  5164. sd = sd->child;
  5165. continue;
  5166. }
  5167. group = find_idlest_group(sd, p, cpu, sd_flag);
  5168. if (!group) {
  5169. sd = sd->child;
  5170. continue;
  5171. }
  5172. new_cpu = find_idlest_group_cpu(group, p, cpu);
  5173. if (new_cpu == cpu) {
  5174. /* Now try balancing at a lower domain level of 'cpu': */
  5175. sd = sd->child;
  5176. continue;
  5177. }
  5178. /* Now try balancing at a lower domain level of 'new_cpu': */
  5179. cpu = new_cpu;
  5180. weight = sd->span_weight;
  5181. sd = NULL;
  5182. for_each_domain(cpu, tmp) {
  5183. if (weight <= tmp->span_weight)
  5184. break;
  5185. if (tmp->flags & sd_flag)
  5186. sd = tmp;
  5187. }
  5188. }
  5189. return new_cpu;
  5190. }
  5191. #ifdef CONFIG_SCHED_SMT
  5192. static inline void set_idle_cores(int cpu, int val)
  5193. {
  5194. struct sched_domain_shared *sds;
  5195. sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
  5196. if (sds)
  5197. WRITE_ONCE(sds->has_idle_cores, val);
  5198. }
  5199. static inline bool test_idle_cores(int cpu, bool def)
  5200. {
  5201. struct sched_domain_shared *sds;
  5202. sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
  5203. if (sds)
  5204. return READ_ONCE(sds->has_idle_cores);
  5205. return def;
  5206. }
  5207. /*
  5208. * Scans the local SMT mask to see if the entire core is idle, and records this
  5209. * information in sd_llc_shared->has_idle_cores.
  5210. *
  5211. * Since SMT siblings share all cache levels, inspecting this limited remote
  5212. * state should be fairly cheap.
  5213. */
  5214. void __update_idle_core(struct rq *rq)
  5215. {
  5216. int core = cpu_of(rq);
  5217. int cpu;
  5218. rcu_read_lock();
  5219. if (test_idle_cores(core, true))
  5220. goto unlock;
  5221. for_each_cpu(cpu, cpu_smt_mask(core)) {
  5222. if (cpu == core)
  5223. continue;
  5224. if (!idle_cpu(cpu))
  5225. goto unlock;
  5226. }
  5227. set_idle_cores(core, 1);
  5228. unlock:
  5229. rcu_read_unlock();
  5230. }
  5231. /*
  5232. * Scan the entire LLC domain for idle cores; this dynamically switches off if
  5233. * there are no idle cores left in the system; tracked through
  5234. * sd_llc->shared->has_idle_cores and enabled through update_idle_core() above.
  5235. */
  5236. static int select_idle_core(struct task_struct *p, struct sched_domain *sd, int target)
  5237. {
  5238. struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_idle_mask);
  5239. int core, cpu;
  5240. if (!static_branch_likely(&sched_smt_present))
  5241. return -1;
  5242. if (!test_idle_cores(target, false))
  5243. return -1;
  5244. cpumask_and(cpus, sched_domain_span(sd), &p->cpus_allowed);
  5245. for_each_cpu_wrap(core, cpus, target) {
  5246. bool idle = true;
  5247. for_each_cpu(cpu, cpu_smt_mask(core)) {
  5248. cpumask_clear_cpu(cpu, cpus);
  5249. if (!idle_cpu(cpu))
  5250. idle = false;
  5251. }
  5252. if (idle)
  5253. return core;
  5254. }
  5255. /*
  5256. * Failed to find an idle core; stop looking for one.
  5257. */
  5258. set_idle_cores(target, 0);
  5259. return -1;
  5260. }
  5261. /*
  5262. * Scan the local SMT mask for idle CPUs.
  5263. */
  5264. static int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target)
  5265. {
  5266. int cpu;
  5267. if (!static_branch_likely(&sched_smt_present))
  5268. return -1;
  5269. for_each_cpu(cpu, cpu_smt_mask(target)) {
  5270. if (!cpumask_test_cpu(cpu, &p->cpus_allowed))
  5271. continue;
  5272. if (idle_cpu(cpu))
  5273. return cpu;
  5274. }
  5275. return -1;
  5276. }
  5277. #else /* CONFIG_SCHED_SMT */
  5278. static inline int select_idle_core(struct task_struct *p, struct sched_domain *sd, int target)
  5279. {
  5280. return -1;
  5281. }
  5282. static inline int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target)
  5283. {
  5284. return -1;
  5285. }
  5286. #endif /* CONFIG_SCHED_SMT */
  5287. /*
  5288. * Scan the LLC domain for idle CPUs; this is dynamically regulated by
  5289. * comparing the average scan cost (tracked in sd->avg_scan_cost) against the
  5290. * average idle time for this rq (as found in rq->avg_idle).
  5291. */
  5292. static int select_idle_cpu(struct task_struct *p, struct sched_domain *sd, int target)
  5293. {
  5294. struct sched_domain *this_sd;
  5295. u64 avg_cost, avg_idle;
  5296. u64 time, cost;
  5297. s64 delta;
  5298. int cpu, nr = INT_MAX;
  5299. this_sd = rcu_dereference(*this_cpu_ptr(&sd_llc));
  5300. if (!this_sd)
  5301. return -1;
  5302. /*
  5303. * Due to large variance we need a large fuzz factor; hackbench in
  5304. * particularly is sensitive here.
  5305. */
  5306. avg_idle = this_rq()->avg_idle / 512;
  5307. avg_cost = this_sd->avg_scan_cost + 1;
  5308. if (sched_feat(SIS_AVG_CPU) && avg_idle < avg_cost)
  5309. return -1;
  5310. if (sched_feat(SIS_PROP)) {
  5311. u64 span_avg = sd->span_weight * avg_idle;
  5312. if (span_avg > 4*avg_cost)
  5313. nr = div_u64(span_avg, avg_cost);
  5314. else
  5315. nr = 4;
  5316. }
  5317. time = local_clock();
  5318. for_each_cpu_wrap(cpu, sched_domain_span(sd), target) {
  5319. if (!--nr)
  5320. return -1;
  5321. if (!cpumask_test_cpu(cpu, &p->cpus_allowed))
  5322. continue;
  5323. if (idle_cpu(cpu))
  5324. break;
  5325. }
  5326. time = local_clock() - time;
  5327. cost = this_sd->avg_scan_cost;
  5328. delta = (s64)(time - cost) / 8;
  5329. this_sd->avg_scan_cost += delta;
  5330. return cpu;
  5331. }
  5332. /*
  5333. * Try and locate an idle core/thread in the LLC cache domain.
  5334. */
  5335. static int select_idle_sibling(struct task_struct *p, int prev, int target)
  5336. {
  5337. struct sched_domain *sd;
  5338. int i, recent_used_cpu;
  5339. if (idle_cpu(target))
  5340. return target;
  5341. /*
  5342. * If the previous CPU is cache affine and idle, don't be stupid:
  5343. */
  5344. if (prev != target && cpus_share_cache(prev, target) && idle_cpu(prev))
  5345. return prev;
  5346. /* Check a recently used CPU as a potential idle candidate: */
  5347. recent_used_cpu = p->recent_used_cpu;
  5348. if (recent_used_cpu != prev &&
  5349. recent_used_cpu != target &&
  5350. cpus_share_cache(recent_used_cpu, target) &&
  5351. idle_cpu(recent_used_cpu) &&
  5352. cpumask_test_cpu(p->recent_used_cpu, &p->cpus_allowed)) {
  5353. /*
  5354. * Replace recent_used_cpu with prev as it is a potential
  5355. * candidate for the next wake:
  5356. */
  5357. p->recent_used_cpu = prev;
  5358. return recent_used_cpu;
  5359. }
  5360. sd = rcu_dereference(per_cpu(sd_llc, target));
  5361. if (!sd)
  5362. return target;
  5363. i = select_idle_core(p, sd, target);
  5364. if ((unsigned)i < nr_cpumask_bits)
  5365. return i;
  5366. i = select_idle_cpu(p, sd, target);
  5367. if ((unsigned)i < nr_cpumask_bits)
  5368. return i;
  5369. i = select_idle_smt(p, sd, target);
  5370. if ((unsigned)i < nr_cpumask_bits)
  5371. return i;
  5372. return target;
  5373. }
  5374. /**
  5375. * Amount of capacity of a CPU that is (estimated to be) used by CFS tasks
  5376. * @cpu: the CPU to get the utilization of
  5377. *
  5378. * The unit of the return value must be the one of capacity so we can compare
  5379. * the utilization with the capacity of the CPU that is available for CFS task
  5380. * (ie cpu_capacity).
  5381. *
  5382. * cfs_rq.avg.util_avg is the sum of running time of runnable tasks plus the
  5383. * recent utilization of currently non-runnable tasks on a CPU. It represents
  5384. * the amount of utilization of a CPU in the range [0..capacity_orig] where
  5385. * capacity_orig is the cpu_capacity available at the highest frequency
  5386. * (arch_scale_freq_capacity()).
  5387. * The utilization of a CPU converges towards a sum equal to or less than the
  5388. * current capacity (capacity_curr <= capacity_orig) of the CPU because it is
  5389. * the running time on this CPU scaled by capacity_curr.
  5390. *
  5391. * The estimated utilization of a CPU is defined to be the maximum between its
  5392. * cfs_rq.avg.util_avg and the sum of the estimated utilization of the tasks
  5393. * currently RUNNABLE on that CPU.
  5394. * This allows to properly represent the expected utilization of a CPU which
  5395. * has just got a big task running since a long sleep period. At the same time
  5396. * however it preserves the benefits of the "blocked utilization" in
  5397. * describing the potential for other tasks waking up on the same CPU.
  5398. *
  5399. * Nevertheless, cfs_rq.avg.util_avg can be higher than capacity_curr or even
  5400. * higher than capacity_orig because of unfortunate rounding in
  5401. * cfs.avg.util_avg or just after migrating tasks and new task wakeups until
  5402. * the average stabilizes with the new running time. We need to check that the
  5403. * utilization stays within the range of [0..capacity_orig] and cap it if
  5404. * necessary. Without utilization capping, a group could be seen as overloaded
  5405. * (CPU0 utilization at 121% + CPU1 utilization at 80%) whereas CPU1 has 20% of
  5406. * available capacity. We allow utilization to overshoot capacity_curr (but not
  5407. * capacity_orig) as it useful for predicting the capacity required after task
  5408. * migrations (scheduler-driven DVFS).
  5409. *
  5410. * Return: the (estimated) utilization for the specified CPU
  5411. */
  5412. static inline unsigned long cpu_util(int cpu)
  5413. {
  5414. struct cfs_rq *cfs_rq;
  5415. unsigned int util;
  5416. cfs_rq = &cpu_rq(cpu)->cfs;
  5417. util = READ_ONCE(cfs_rq->avg.util_avg);
  5418. if (sched_feat(UTIL_EST))
  5419. util = max(util, READ_ONCE(cfs_rq->avg.util_est.enqueued));
  5420. return min_t(unsigned long, util, capacity_orig_of(cpu));
  5421. }
  5422. /*
  5423. * cpu_util_wake: Compute CPU utilization with any contributions from
  5424. * the waking task p removed.
  5425. */
  5426. static unsigned long cpu_util_wake(int cpu, struct task_struct *p)
  5427. {
  5428. struct cfs_rq *cfs_rq;
  5429. unsigned int util;
  5430. /* Task has no contribution or is new */
  5431. if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
  5432. return cpu_util(cpu);
  5433. cfs_rq = &cpu_rq(cpu)->cfs;
  5434. util = READ_ONCE(cfs_rq->avg.util_avg);
  5435. /* Discount task's blocked util from CPU's util */
  5436. util -= min_t(unsigned int, util, task_util(p));
  5437. /*
  5438. * Covered cases:
  5439. *
  5440. * a) if *p is the only task sleeping on this CPU, then:
  5441. * cpu_util (== task_util) > util_est (== 0)
  5442. * and thus we return:
  5443. * cpu_util_wake = (cpu_util - task_util) = 0
  5444. *
  5445. * b) if other tasks are SLEEPING on this CPU, which is now exiting
  5446. * IDLE, then:
  5447. * cpu_util >= task_util
  5448. * cpu_util > util_est (== 0)
  5449. * and thus we discount *p's blocked utilization to return:
  5450. * cpu_util_wake = (cpu_util - task_util) >= 0
  5451. *
  5452. * c) if other tasks are RUNNABLE on that CPU and
  5453. * util_est > cpu_util
  5454. * then we use util_est since it returns a more restrictive
  5455. * estimation of the spare capacity on that CPU, by just
  5456. * considering the expected utilization of tasks already
  5457. * runnable on that CPU.
  5458. *
  5459. * Cases a) and b) are covered by the above code, while case c) is
  5460. * covered by the following code when estimated utilization is
  5461. * enabled.
  5462. */
  5463. if (sched_feat(UTIL_EST))
  5464. util = max(util, READ_ONCE(cfs_rq->avg.util_est.enqueued));
  5465. /*
  5466. * Utilization (estimated) can exceed the CPU capacity, thus let's
  5467. * clamp to the maximum CPU capacity to ensure consistency with
  5468. * the cpu_util call.
  5469. */
  5470. return min_t(unsigned long, util, capacity_orig_of(cpu));
  5471. }
  5472. /*
  5473. * Disable WAKE_AFFINE in the case where task @p doesn't fit in the
  5474. * capacity of either the waking CPU @cpu or the previous CPU @prev_cpu.
  5475. *
  5476. * In that case WAKE_AFFINE doesn't make sense and we'll let
  5477. * BALANCE_WAKE sort things out.
  5478. */
  5479. static int wake_cap(struct task_struct *p, int cpu, int prev_cpu)
  5480. {
  5481. long min_cap, max_cap;
  5482. min_cap = min(capacity_orig_of(prev_cpu), capacity_orig_of(cpu));
  5483. max_cap = cpu_rq(cpu)->rd->max_cpu_capacity;
  5484. /* Minimum capacity is close to max, no need to abort wake_affine */
  5485. if (max_cap - min_cap < max_cap >> 3)
  5486. return 0;
  5487. /* Bring task utilization in sync with prev_cpu */
  5488. sync_entity_load_avg(&p->se);
  5489. return min_cap * 1024 < task_util(p) * capacity_margin;
  5490. }
  5491. /*
  5492. * select_task_rq_fair: Select target runqueue for the waking task in domains
  5493. * that have the 'sd_flag' flag set. In practice, this is SD_BALANCE_WAKE,
  5494. * SD_BALANCE_FORK, or SD_BALANCE_EXEC.
  5495. *
  5496. * Balances load by selecting the idlest CPU in the idlest group, or under
  5497. * certain conditions an idle sibling CPU if the domain has SD_WAKE_AFFINE set.
  5498. *
  5499. * Returns the target CPU number.
  5500. *
  5501. * preempt must be disabled.
  5502. */
  5503. static int
  5504. select_task_rq_fair(struct task_struct *p, int prev_cpu, int sd_flag, int wake_flags)
  5505. {
  5506. struct sched_domain *tmp, *affine_sd = NULL, *sd = NULL;
  5507. int cpu = smp_processor_id();
  5508. int new_cpu = prev_cpu;
  5509. int want_affine = 0;
  5510. int sync = (wake_flags & WF_SYNC) && !(current->flags & PF_EXITING);
  5511. if (sd_flag & SD_BALANCE_WAKE) {
  5512. record_wakee(p);
  5513. want_affine = !wake_wide(p) && !wake_cap(p, cpu, prev_cpu)
  5514. && cpumask_test_cpu(cpu, &p->cpus_allowed);
  5515. }
  5516. rcu_read_lock();
  5517. for_each_domain(cpu, tmp) {
  5518. if (!(tmp->flags & SD_LOAD_BALANCE))
  5519. break;
  5520. /*
  5521. * If both 'cpu' and 'prev_cpu' are part of this domain,
  5522. * cpu is a valid SD_WAKE_AFFINE target.
  5523. */
  5524. if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
  5525. cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
  5526. affine_sd = tmp;
  5527. break;
  5528. }
  5529. if (tmp->flags & sd_flag)
  5530. sd = tmp;
  5531. else if (!want_affine)
  5532. break;
  5533. }
  5534. if (affine_sd) {
  5535. sd = NULL; /* Prefer wake_affine over balance flags */
  5536. if (cpu == prev_cpu)
  5537. goto pick_cpu;
  5538. new_cpu = wake_affine(affine_sd, p, cpu, prev_cpu, sync);
  5539. }
  5540. if (sd && !(sd_flag & SD_BALANCE_FORK)) {
  5541. /*
  5542. * We're going to need the task's util for capacity_spare_wake
  5543. * in find_idlest_group. Sync it up to prev_cpu's
  5544. * last_update_time.
  5545. */
  5546. sync_entity_load_avg(&p->se);
  5547. }
  5548. if (!sd) {
  5549. pick_cpu:
  5550. if (sd_flag & SD_BALANCE_WAKE) { /* XXX always ? */
  5551. new_cpu = select_idle_sibling(p, prev_cpu, new_cpu);
  5552. if (want_affine)
  5553. current->recent_used_cpu = cpu;
  5554. }
  5555. } else {
  5556. new_cpu = find_idlest_cpu(sd, p, cpu, prev_cpu, sd_flag);
  5557. }
  5558. rcu_read_unlock();
  5559. return new_cpu;
  5560. }
  5561. static void detach_entity_cfs_rq(struct sched_entity *se);
  5562. /*
  5563. * Called immediately before a task is migrated to a new CPU; task_cpu(p) and
  5564. * cfs_rq_of(p) references at time of call are still valid and identify the
  5565. * previous CPU. The caller guarantees p->pi_lock or task_rq(p)->lock is held.
  5566. */
  5567. static void migrate_task_rq_fair(struct task_struct *p)
  5568. {
  5569. /*
  5570. * As blocked tasks retain absolute vruntime the migration needs to
  5571. * deal with this by subtracting the old and adding the new
  5572. * min_vruntime -- the latter is done by enqueue_entity() when placing
  5573. * the task on the new runqueue.
  5574. */
  5575. if (p->state == TASK_WAKING) {
  5576. struct sched_entity *se = &p->se;
  5577. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  5578. u64 min_vruntime;
  5579. #ifndef CONFIG_64BIT
  5580. u64 min_vruntime_copy;
  5581. do {
  5582. min_vruntime_copy = cfs_rq->min_vruntime_copy;
  5583. smp_rmb();
  5584. min_vruntime = cfs_rq->min_vruntime;
  5585. } while (min_vruntime != min_vruntime_copy);
  5586. #else
  5587. min_vruntime = cfs_rq->min_vruntime;
  5588. #endif
  5589. se->vruntime -= min_vruntime;
  5590. }
  5591. if (p->on_rq == TASK_ON_RQ_MIGRATING) {
  5592. /*
  5593. * In case of TASK_ON_RQ_MIGRATING we in fact hold the 'old'
  5594. * rq->lock and can modify state directly.
  5595. */
  5596. lockdep_assert_held(&task_rq(p)->lock);
  5597. detach_entity_cfs_rq(&p->se);
  5598. } else {
  5599. /*
  5600. * We are supposed to update the task to "current" time, then
  5601. * its up to date and ready to go to new CPU/cfs_rq. But we
  5602. * have difficulty in getting what current time is, so simply
  5603. * throw away the out-of-date time. This will result in the
  5604. * wakee task is less decayed, but giving the wakee more load
  5605. * sounds not bad.
  5606. */
  5607. remove_entity_load_avg(&p->se);
  5608. }
  5609. /* Tell new CPU we are migrated */
  5610. p->se.avg.last_update_time = 0;
  5611. /* We have migrated, no longer consider this task hot */
  5612. p->se.exec_start = 0;
  5613. }
  5614. static void task_dead_fair(struct task_struct *p)
  5615. {
  5616. remove_entity_load_avg(&p->se);
  5617. }
  5618. #endif /* CONFIG_SMP */
  5619. static unsigned long wakeup_gran(struct sched_entity *se)
  5620. {
  5621. unsigned long gran = sysctl_sched_wakeup_granularity;
  5622. /*
  5623. * Since its curr running now, convert the gran from real-time
  5624. * to virtual-time in his units.
  5625. *
  5626. * By using 'se' instead of 'curr' we penalize light tasks, so
  5627. * they get preempted easier. That is, if 'se' < 'curr' then
  5628. * the resulting gran will be larger, therefore penalizing the
  5629. * lighter, if otoh 'se' > 'curr' then the resulting gran will
  5630. * be smaller, again penalizing the lighter task.
  5631. *
  5632. * This is especially important for buddies when the leftmost
  5633. * task is higher priority than the buddy.
  5634. */
  5635. return calc_delta_fair(gran, se);
  5636. }
  5637. /*
  5638. * Should 'se' preempt 'curr'.
  5639. *
  5640. * |s1
  5641. * |s2
  5642. * |s3
  5643. * g
  5644. * |<--->|c
  5645. *
  5646. * w(c, s1) = -1
  5647. * w(c, s2) = 0
  5648. * w(c, s3) = 1
  5649. *
  5650. */
  5651. static int
  5652. wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se)
  5653. {
  5654. s64 gran, vdiff = curr->vruntime - se->vruntime;
  5655. if (vdiff <= 0)
  5656. return -1;
  5657. gran = wakeup_gran(se);
  5658. if (vdiff > gran)
  5659. return 1;
  5660. return 0;
  5661. }
  5662. static void set_last_buddy(struct sched_entity *se)
  5663. {
  5664. if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE))
  5665. return;
  5666. for_each_sched_entity(se) {
  5667. if (SCHED_WARN_ON(!se->on_rq))
  5668. return;
  5669. cfs_rq_of(se)->last = se;
  5670. }
  5671. }
  5672. static void set_next_buddy(struct sched_entity *se)
  5673. {
  5674. if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE))
  5675. return;
  5676. for_each_sched_entity(se) {
  5677. if (SCHED_WARN_ON(!se->on_rq))
  5678. return;
  5679. cfs_rq_of(se)->next = se;
  5680. }
  5681. }
  5682. static void set_skip_buddy(struct sched_entity *se)
  5683. {
  5684. for_each_sched_entity(se)
  5685. cfs_rq_of(se)->skip = se;
  5686. }
  5687. /*
  5688. * Preempt the current task with a newly woken task if needed:
  5689. */
  5690. static void check_preempt_wakeup(struct rq *rq, struct task_struct *p, int wake_flags)
  5691. {
  5692. struct task_struct *curr = rq->curr;
  5693. struct sched_entity *se = &curr->se, *pse = &p->se;
  5694. struct cfs_rq *cfs_rq = task_cfs_rq(curr);
  5695. int scale = cfs_rq->nr_running >= sched_nr_latency;
  5696. int next_buddy_marked = 0;
  5697. if (unlikely(se == pse))
  5698. return;
  5699. /*
  5700. * This is possible from callers such as attach_tasks(), in which we
  5701. * unconditionally check_prempt_curr() after an enqueue (which may have
  5702. * lead to a throttle). This both saves work and prevents false
  5703. * next-buddy nomination below.
  5704. */
  5705. if (unlikely(throttled_hierarchy(cfs_rq_of(pse))))
  5706. return;
  5707. if (sched_feat(NEXT_BUDDY) && scale && !(wake_flags & WF_FORK)) {
  5708. set_next_buddy(pse);
  5709. next_buddy_marked = 1;
  5710. }
  5711. /*
  5712. * We can come here with TIF_NEED_RESCHED already set from new task
  5713. * wake up path.
  5714. *
  5715. * Note: this also catches the edge-case of curr being in a throttled
  5716. * group (e.g. via set_curr_task), since update_curr() (in the
  5717. * enqueue of curr) will have resulted in resched being set. This
  5718. * prevents us from potentially nominating it as a false LAST_BUDDY
  5719. * below.
  5720. */
  5721. if (test_tsk_need_resched(curr))
  5722. return;
  5723. /* Idle tasks are by definition preempted by non-idle tasks. */
  5724. if (unlikely(curr->policy == SCHED_IDLE) &&
  5725. likely(p->policy != SCHED_IDLE))
  5726. goto preempt;
  5727. /*
  5728. * Batch and idle tasks do not preempt non-idle tasks (their preemption
  5729. * is driven by the tick):
  5730. */
  5731. if (unlikely(p->policy != SCHED_NORMAL) || !sched_feat(WAKEUP_PREEMPTION))
  5732. return;
  5733. find_matching_se(&se, &pse);
  5734. update_curr(cfs_rq_of(se));
  5735. BUG_ON(!pse);
  5736. if (wakeup_preempt_entity(se, pse) == 1) {
  5737. /*
  5738. * Bias pick_next to pick the sched entity that is
  5739. * triggering this preemption.
  5740. */
  5741. if (!next_buddy_marked)
  5742. set_next_buddy(pse);
  5743. goto preempt;
  5744. }
  5745. return;
  5746. preempt:
  5747. resched_curr(rq);
  5748. /*
  5749. * Only set the backward buddy when the current task is still
  5750. * on the rq. This can happen when a wakeup gets interleaved
  5751. * with schedule on the ->pre_schedule() or idle_balance()
  5752. * point, either of which can * drop the rq lock.
  5753. *
  5754. * Also, during early boot the idle thread is in the fair class,
  5755. * for obvious reasons its a bad idea to schedule back to it.
  5756. */
  5757. if (unlikely(!se->on_rq || curr == rq->idle))
  5758. return;
  5759. if (sched_feat(LAST_BUDDY) && scale && entity_is_task(se))
  5760. set_last_buddy(se);
  5761. }
  5762. static struct task_struct *
  5763. pick_next_task_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
  5764. {
  5765. struct cfs_rq *cfs_rq = &rq->cfs;
  5766. struct sched_entity *se;
  5767. struct task_struct *p;
  5768. int new_tasks;
  5769. again:
  5770. if (!cfs_rq->nr_running)
  5771. goto idle;
  5772. #ifdef CONFIG_FAIR_GROUP_SCHED
  5773. if (prev->sched_class != &fair_sched_class)
  5774. goto simple;
  5775. /*
  5776. * Because of the set_next_buddy() in dequeue_task_fair() it is rather
  5777. * likely that a next task is from the same cgroup as the current.
  5778. *
  5779. * Therefore attempt to avoid putting and setting the entire cgroup
  5780. * hierarchy, only change the part that actually changes.
  5781. */
  5782. do {
  5783. struct sched_entity *curr = cfs_rq->curr;
  5784. /*
  5785. * Since we got here without doing put_prev_entity() we also
  5786. * have to consider cfs_rq->curr. If it is still a runnable
  5787. * entity, update_curr() will update its vruntime, otherwise
  5788. * forget we've ever seen it.
  5789. */
  5790. if (curr) {
  5791. if (curr->on_rq)
  5792. update_curr(cfs_rq);
  5793. else
  5794. curr = NULL;
  5795. /*
  5796. * This call to check_cfs_rq_runtime() will do the
  5797. * throttle and dequeue its entity in the parent(s).
  5798. * Therefore the nr_running test will indeed
  5799. * be correct.
  5800. */
  5801. if (unlikely(check_cfs_rq_runtime(cfs_rq))) {
  5802. cfs_rq = &rq->cfs;
  5803. if (!cfs_rq->nr_running)
  5804. goto idle;
  5805. goto simple;
  5806. }
  5807. }
  5808. se = pick_next_entity(cfs_rq, curr);
  5809. cfs_rq = group_cfs_rq(se);
  5810. } while (cfs_rq);
  5811. p = task_of(se);
  5812. /*
  5813. * Since we haven't yet done put_prev_entity and if the selected task
  5814. * is a different task than we started out with, try and touch the
  5815. * least amount of cfs_rqs.
  5816. */
  5817. if (prev != p) {
  5818. struct sched_entity *pse = &prev->se;
  5819. while (!(cfs_rq = is_same_group(se, pse))) {
  5820. int se_depth = se->depth;
  5821. int pse_depth = pse->depth;
  5822. if (se_depth <= pse_depth) {
  5823. put_prev_entity(cfs_rq_of(pse), pse);
  5824. pse = parent_entity(pse);
  5825. }
  5826. if (se_depth >= pse_depth) {
  5827. set_next_entity(cfs_rq_of(se), se);
  5828. se = parent_entity(se);
  5829. }
  5830. }
  5831. put_prev_entity(cfs_rq, pse);
  5832. set_next_entity(cfs_rq, se);
  5833. }
  5834. goto done;
  5835. simple:
  5836. #endif
  5837. put_prev_task(rq, prev);
  5838. do {
  5839. se = pick_next_entity(cfs_rq, NULL);
  5840. set_next_entity(cfs_rq, se);
  5841. cfs_rq = group_cfs_rq(se);
  5842. } while (cfs_rq);
  5843. p = task_of(se);
  5844. done: __maybe_unused;
  5845. #ifdef CONFIG_SMP
  5846. /*
  5847. * Move the next running task to the front of
  5848. * the list, so our cfs_tasks list becomes MRU
  5849. * one.
  5850. */
  5851. list_move(&p->se.group_node, &rq->cfs_tasks);
  5852. #endif
  5853. if (hrtick_enabled(rq))
  5854. hrtick_start_fair(rq, p);
  5855. return p;
  5856. idle:
  5857. new_tasks = idle_balance(rq, rf);
  5858. /*
  5859. * Because idle_balance() releases (and re-acquires) rq->lock, it is
  5860. * possible for any higher priority task to appear. In that case we
  5861. * must re-start the pick_next_entity() loop.
  5862. */
  5863. if (new_tasks < 0)
  5864. return RETRY_TASK;
  5865. if (new_tasks > 0)
  5866. goto again;
  5867. return NULL;
  5868. }
  5869. /*
  5870. * Account for a descheduled task:
  5871. */
  5872. static void put_prev_task_fair(struct rq *rq, struct task_struct *prev)
  5873. {
  5874. struct sched_entity *se = &prev->se;
  5875. struct cfs_rq *cfs_rq;
  5876. for_each_sched_entity(se) {
  5877. cfs_rq = cfs_rq_of(se);
  5878. put_prev_entity(cfs_rq, se);
  5879. }
  5880. }
  5881. /*
  5882. * sched_yield() is very simple
  5883. *
  5884. * The magic of dealing with the ->skip buddy is in pick_next_entity.
  5885. */
  5886. static void yield_task_fair(struct rq *rq)
  5887. {
  5888. struct task_struct *curr = rq->curr;
  5889. struct cfs_rq *cfs_rq = task_cfs_rq(curr);
  5890. struct sched_entity *se = &curr->se;
  5891. /*
  5892. * Are we the only task in the tree?
  5893. */
  5894. if (unlikely(rq->nr_running == 1))
  5895. return;
  5896. clear_buddies(cfs_rq, se);
  5897. if (curr->policy != SCHED_BATCH) {
  5898. update_rq_clock(rq);
  5899. /*
  5900. * Update run-time statistics of the 'current'.
  5901. */
  5902. update_curr(cfs_rq);
  5903. /*
  5904. * Tell update_rq_clock() that we've just updated,
  5905. * so we don't do microscopic update in schedule()
  5906. * and double the fastpath cost.
  5907. */
  5908. rq_clock_skip_update(rq);
  5909. }
  5910. set_skip_buddy(se);
  5911. }
  5912. static bool yield_to_task_fair(struct rq *rq, struct task_struct *p, bool preempt)
  5913. {
  5914. struct sched_entity *se = &p->se;
  5915. /* throttled hierarchies are not runnable */
  5916. if (!se->on_rq || throttled_hierarchy(cfs_rq_of(se)))
  5917. return false;
  5918. /* Tell the scheduler that we'd really like pse to run next. */
  5919. set_next_buddy(se);
  5920. yield_task_fair(rq);
  5921. return true;
  5922. }
  5923. #ifdef CONFIG_SMP
  5924. /**************************************************
  5925. * Fair scheduling class load-balancing methods.
  5926. *
  5927. * BASICS
  5928. *
  5929. * The purpose of load-balancing is to achieve the same basic fairness the
  5930. * per-CPU scheduler provides, namely provide a proportional amount of compute
  5931. * time to each task. This is expressed in the following equation:
  5932. *
  5933. * W_i,n/P_i == W_j,n/P_j for all i,j (1)
  5934. *
  5935. * Where W_i,n is the n-th weight average for CPU i. The instantaneous weight
  5936. * W_i,0 is defined as:
  5937. *
  5938. * W_i,0 = \Sum_j w_i,j (2)
  5939. *
  5940. * Where w_i,j is the weight of the j-th runnable task on CPU i. This weight
  5941. * is derived from the nice value as per sched_prio_to_weight[].
  5942. *
  5943. * The weight average is an exponential decay average of the instantaneous
  5944. * weight:
  5945. *
  5946. * W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0 (3)
  5947. *
  5948. * C_i is the compute capacity of CPU i, typically it is the
  5949. * fraction of 'recent' time available for SCHED_OTHER task execution. But it
  5950. * can also include other factors [XXX].
  5951. *
  5952. * To achieve this balance we define a measure of imbalance which follows
  5953. * directly from (1):
  5954. *
  5955. * imb_i,j = max{ avg(W/C), W_i/C_i } - min{ avg(W/C), W_j/C_j } (4)
  5956. *
  5957. * We them move tasks around to minimize the imbalance. In the continuous
  5958. * function space it is obvious this converges, in the discrete case we get
  5959. * a few fun cases generally called infeasible weight scenarios.
  5960. *
  5961. * [XXX expand on:
  5962. * - infeasible weights;
  5963. * - local vs global optima in the discrete case. ]
  5964. *
  5965. *
  5966. * SCHED DOMAINS
  5967. *
  5968. * In order to solve the imbalance equation (4), and avoid the obvious O(n^2)
  5969. * for all i,j solution, we create a tree of CPUs that follows the hardware
  5970. * topology where each level pairs two lower groups (or better). This results
  5971. * in O(log n) layers. Furthermore we reduce the number of CPUs going up the
  5972. * tree to only the first of the previous level and we decrease the frequency
  5973. * of load-balance at each level inv. proportional to the number of CPUs in
  5974. * the groups.
  5975. *
  5976. * This yields:
  5977. *
  5978. * log_2 n 1 n
  5979. * \Sum { --- * --- * 2^i } = O(n) (5)
  5980. * i = 0 2^i 2^i
  5981. * `- size of each group
  5982. * | | `- number of CPUs doing load-balance
  5983. * | `- freq
  5984. * `- sum over all levels
  5985. *
  5986. * Coupled with a limit on how many tasks we can migrate every balance pass,
  5987. * this makes (5) the runtime complexity of the balancer.
  5988. *
  5989. * An important property here is that each CPU is still (indirectly) connected
  5990. * to every other CPU in at most O(log n) steps:
  5991. *
  5992. * The adjacency matrix of the resulting graph is given by:
  5993. *
  5994. * log_2 n
  5995. * A_i,j = \Union (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1) (6)
  5996. * k = 0
  5997. *
  5998. * And you'll find that:
  5999. *
  6000. * A^(log_2 n)_i,j != 0 for all i,j (7)
  6001. *
  6002. * Showing there's indeed a path between every CPU in at most O(log n) steps.
  6003. * The task movement gives a factor of O(m), giving a convergence complexity
  6004. * of:
  6005. *
  6006. * O(nm log n), n := nr_cpus, m := nr_tasks (8)
  6007. *
  6008. *
  6009. * WORK CONSERVING
  6010. *
  6011. * In order to avoid CPUs going idle while there's still work to do, new idle
  6012. * balancing is more aggressive and has the newly idle CPU iterate up the domain
  6013. * tree itself instead of relying on other CPUs to bring it work.
  6014. *
  6015. * This adds some complexity to both (5) and (8) but it reduces the total idle
  6016. * time.
  6017. *
  6018. * [XXX more?]
  6019. *
  6020. *
  6021. * CGROUPS
  6022. *
  6023. * Cgroups make a horror show out of (2), instead of a simple sum we get:
  6024. *
  6025. * s_k,i
  6026. * W_i,0 = \Sum_j \Prod_k w_k * ----- (9)
  6027. * S_k
  6028. *
  6029. * Where
  6030. *
  6031. * s_k,i = \Sum_j w_i,j,k and S_k = \Sum_i s_k,i (10)
  6032. *
  6033. * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on CPU i.
  6034. *
  6035. * The big problem is S_k, its a global sum needed to compute a local (W_i)
  6036. * property.
  6037. *
  6038. * [XXX write more on how we solve this.. _after_ merging pjt's patches that
  6039. * rewrite all of this once again.]
  6040. */
  6041. static unsigned long __read_mostly max_load_balance_interval = HZ/10;
  6042. enum fbq_type { regular, remote, all };
  6043. #define LBF_ALL_PINNED 0x01
  6044. #define LBF_NEED_BREAK 0x02
  6045. #define LBF_DST_PINNED 0x04
  6046. #define LBF_SOME_PINNED 0x08
  6047. #define LBF_NOHZ_STATS 0x10
  6048. #define LBF_NOHZ_AGAIN 0x20
  6049. struct lb_env {
  6050. struct sched_domain *sd;
  6051. struct rq *src_rq;
  6052. int src_cpu;
  6053. int dst_cpu;
  6054. struct rq *dst_rq;
  6055. struct cpumask *dst_grpmask;
  6056. int new_dst_cpu;
  6057. enum cpu_idle_type idle;
  6058. long imbalance;
  6059. /* The set of CPUs under consideration for load-balancing */
  6060. struct cpumask *cpus;
  6061. unsigned int flags;
  6062. unsigned int loop;
  6063. unsigned int loop_break;
  6064. unsigned int loop_max;
  6065. enum fbq_type fbq_type;
  6066. struct list_head tasks;
  6067. };
  6068. /*
  6069. * Is this task likely cache-hot:
  6070. */
  6071. static int task_hot(struct task_struct *p, struct lb_env *env)
  6072. {
  6073. s64 delta;
  6074. lockdep_assert_held(&env->src_rq->lock);
  6075. if (p->sched_class != &fair_sched_class)
  6076. return 0;
  6077. if (unlikely(p->policy == SCHED_IDLE))
  6078. return 0;
  6079. /*
  6080. * Buddy candidates are cache hot:
  6081. */
  6082. if (sched_feat(CACHE_HOT_BUDDY) && env->dst_rq->nr_running &&
  6083. (&p->se == cfs_rq_of(&p->se)->next ||
  6084. &p->se == cfs_rq_of(&p->se)->last))
  6085. return 1;
  6086. if (sysctl_sched_migration_cost == -1)
  6087. return 1;
  6088. if (sysctl_sched_migration_cost == 0)
  6089. return 0;
  6090. delta = rq_clock_task(env->src_rq) - p->se.exec_start;
  6091. return delta < (s64)sysctl_sched_migration_cost;
  6092. }
  6093. #ifdef CONFIG_NUMA_BALANCING
  6094. /*
  6095. * Returns 1, if task migration degrades locality
  6096. * Returns 0, if task migration improves locality i.e migration preferred.
  6097. * Returns -1, if task migration is not affected by locality.
  6098. */
  6099. static int migrate_degrades_locality(struct task_struct *p, struct lb_env *env)
  6100. {
  6101. struct numa_group *numa_group = rcu_dereference(p->numa_group);
  6102. unsigned long src_faults, dst_faults;
  6103. int src_nid, dst_nid;
  6104. if (!static_branch_likely(&sched_numa_balancing))
  6105. return -1;
  6106. if (!p->numa_faults || !(env->sd->flags & SD_NUMA))
  6107. return -1;
  6108. src_nid = cpu_to_node(env->src_cpu);
  6109. dst_nid = cpu_to_node(env->dst_cpu);
  6110. if (src_nid == dst_nid)
  6111. return -1;
  6112. /* Migrating away from the preferred node is always bad. */
  6113. if (src_nid == p->numa_preferred_nid) {
  6114. if (env->src_rq->nr_running > env->src_rq->nr_preferred_running)
  6115. return 1;
  6116. else
  6117. return -1;
  6118. }
  6119. /* Encourage migration to the preferred node. */
  6120. if (dst_nid == p->numa_preferred_nid)
  6121. return 0;
  6122. /* Leaving a core idle is often worse than degrading locality. */
  6123. if (env->idle != CPU_NOT_IDLE)
  6124. return -1;
  6125. if (numa_group) {
  6126. src_faults = group_faults(p, src_nid);
  6127. dst_faults = group_faults(p, dst_nid);
  6128. } else {
  6129. src_faults = task_faults(p, src_nid);
  6130. dst_faults = task_faults(p, dst_nid);
  6131. }
  6132. return dst_faults < src_faults;
  6133. }
  6134. #else
  6135. static inline int migrate_degrades_locality(struct task_struct *p,
  6136. struct lb_env *env)
  6137. {
  6138. return -1;
  6139. }
  6140. #endif
  6141. /*
  6142. * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
  6143. */
  6144. static
  6145. int can_migrate_task(struct task_struct *p, struct lb_env *env)
  6146. {
  6147. int tsk_cache_hot;
  6148. lockdep_assert_held(&env->src_rq->lock);
  6149. /*
  6150. * We do not migrate tasks that are:
  6151. * 1) throttled_lb_pair, or
  6152. * 2) cannot be migrated to this CPU due to cpus_allowed, or
  6153. * 3) running (obviously), or
  6154. * 4) are cache-hot on their current CPU.
  6155. */
  6156. if (throttled_lb_pair(task_group(p), env->src_cpu, env->dst_cpu))
  6157. return 0;
  6158. if (!cpumask_test_cpu(env->dst_cpu, &p->cpus_allowed)) {
  6159. int cpu;
  6160. schedstat_inc(p->se.statistics.nr_failed_migrations_affine);
  6161. env->flags |= LBF_SOME_PINNED;
  6162. /*
  6163. * Remember if this task can be migrated to any other CPU in
  6164. * our sched_group. We may want to revisit it if we couldn't
  6165. * meet load balance goals by pulling other tasks on src_cpu.
  6166. *
  6167. * Avoid computing new_dst_cpu for NEWLY_IDLE or if we have
  6168. * already computed one in current iteration.
  6169. */
  6170. if (env->idle == CPU_NEWLY_IDLE || (env->flags & LBF_DST_PINNED))
  6171. return 0;
  6172. /* Prevent to re-select dst_cpu via env's CPUs: */
  6173. for_each_cpu_and(cpu, env->dst_grpmask, env->cpus) {
  6174. if (cpumask_test_cpu(cpu, &p->cpus_allowed)) {
  6175. env->flags |= LBF_DST_PINNED;
  6176. env->new_dst_cpu = cpu;
  6177. break;
  6178. }
  6179. }
  6180. return 0;
  6181. }
  6182. /* Record that we found atleast one task that could run on dst_cpu */
  6183. env->flags &= ~LBF_ALL_PINNED;
  6184. if (task_running(env->src_rq, p)) {
  6185. schedstat_inc(p->se.statistics.nr_failed_migrations_running);
  6186. return 0;
  6187. }
  6188. /*
  6189. * Aggressive migration if:
  6190. * 1) destination numa is preferred
  6191. * 2) task is cache cold, or
  6192. * 3) too many balance attempts have failed.
  6193. */
  6194. tsk_cache_hot = migrate_degrades_locality(p, env);
  6195. if (tsk_cache_hot == -1)
  6196. tsk_cache_hot = task_hot(p, env);
  6197. if (tsk_cache_hot <= 0 ||
  6198. env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
  6199. if (tsk_cache_hot == 1) {
  6200. schedstat_inc(env->sd->lb_hot_gained[env->idle]);
  6201. schedstat_inc(p->se.statistics.nr_forced_migrations);
  6202. }
  6203. return 1;
  6204. }
  6205. schedstat_inc(p->se.statistics.nr_failed_migrations_hot);
  6206. return 0;
  6207. }
  6208. /*
  6209. * detach_task() -- detach the task for the migration specified in env
  6210. */
  6211. static void detach_task(struct task_struct *p, struct lb_env *env)
  6212. {
  6213. lockdep_assert_held(&env->src_rq->lock);
  6214. p->on_rq = TASK_ON_RQ_MIGRATING;
  6215. deactivate_task(env->src_rq, p, DEQUEUE_NOCLOCK);
  6216. set_task_cpu(p, env->dst_cpu);
  6217. }
  6218. /*
  6219. * detach_one_task() -- tries to dequeue exactly one task from env->src_rq, as
  6220. * part of active balancing operations within "domain".
  6221. *
  6222. * Returns a task if successful and NULL otherwise.
  6223. */
  6224. static struct task_struct *detach_one_task(struct lb_env *env)
  6225. {
  6226. struct task_struct *p;
  6227. lockdep_assert_held(&env->src_rq->lock);
  6228. list_for_each_entry_reverse(p,
  6229. &env->src_rq->cfs_tasks, se.group_node) {
  6230. if (!can_migrate_task(p, env))
  6231. continue;
  6232. detach_task(p, env);
  6233. /*
  6234. * Right now, this is only the second place where
  6235. * lb_gained[env->idle] is updated (other is detach_tasks)
  6236. * so we can safely collect stats here rather than
  6237. * inside detach_tasks().
  6238. */
  6239. schedstat_inc(env->sd->lb_gained[env->idle]);
  6240. return p;
  6241. }
  6242. return NULL;
  6243. }
  6244. static const unsigned int sched_nr_migrate_break = 32;
  6245. /*
  6246. * detach_tasks() -- tries to detach up to imbalance weighted load from
  6247. * busiest_rq, as part of a balancing operation within domain "sd".
  6248. *
  6249. * Returns number of detached tasks if successful and 0 otherwise.
  6250. */
  6251. static int detach_tasks(struct lb_env *env)
  6252. {
  6253. struct list_head *tasks = &env->src_rq->cfs_tasks;
  6254. struct task_struct *p;
  6255. unsigned long load;
  6256. int detached = 0;
  6257. lockdep_assert_held(&env->src_rq->lock);
  6258. if (env->imbalance <= 0)
  6259. return 0;
  6260. while (!list_empty(tasks)) {
  6261. /*
  6262. * We don't want to steal all, otherwise we may be treated likewise,
  6263. * which could at worst lead to a livelock crash.
  6264. */
  6265. if (env->idle != CPU_NOT_IDLE && env->src_rq->nr_running <= 1)
  6266. break;
  6267. p = list_last_entry(tasks, struct task_struct, se.group_node);
  6268. env->loop++;
  6269. /* We've more or less seen every task there is, call it quits */
  6270. if (env->loop > env->loop_max)
  6271. break;
  6272. /* take a breather every nr_migrate tasks */
  6273. if (env->loop > env->loop_break) {
  6274. env->loop_break += sched_nr_migrate_break;
  6275. env->flags |= LBF_NEED_BREAK;
  6276. break;
  6277. }
  6278. if (!can_migrate_task(p, env))
  6279. goto next;
  6280. load = task_h_load(p);
  6281. if (sched_feat(LB_MIN) && load < 16 && !env->sd->nr_balance_failed)
  6282. goto next;
  6283. if ((load / 2) > env->imbalance)
  6284. goto next;
  6285. detach_task(p, env);
  6286. list_add(&p->se.group_node, &env->tasks);
  6287. detached++;
  6288. env->imbalance -= load;
  6289. #ifdef CONFIG_PREEMPT
  6290. /*
  6291. * NEWIDLE balancing is a source of latency, so preemptible
  6292. * kernels will stop after the first task is detached to minimize
  6293. * the critical section.
  6294. */
  6295. if (env->idle == CPU_NEWLY_IDLE)
  6296. break;
  6297. #endif
  6298. /*
  6299. * We only want to steal up to the prescribed amount of
  6300. * weighted load.
  6301. */
  6302. if (env->imbalance <= 0)
  6303. break;
  6304. continue;
  6305. next:
  6306. list_move(&p->se.group_node, tasks);
  6307. }
  6308. /*
  6309. * Right now, this is one of only two places we collect this stat
  6310. * so we can safely collect detach_one_task() stats here rather
  6311. * than inside detach_one_task().
  6312. */
  6313. schedstat_add(env->sd->lb_gained[env->idle], detached);
  6314. return detached;
  6315. }
  6316. /*
  6317. * attach_task() -- attach the task detached by detach_task() to its new rq.
  6318. */
  6319. static void attach_task(struct rq *rq, struct task_struct *p)
  6320. {
  6321. lockdep_assert_held(&rq->lock);
  6322. BUG_ON(task_rq(p) != rq);
  6323. activate_task(rq, p, ENQUEUE_NOCLOCK);
  6324. p->on_rq = TASK_ON_RQ_QUEUED;
  6325. check_preempt_curr(rq, p, 0);
  6326. }
  6327. /*
  6328. * attach_one_task() -- attaches the task returned from detach_one_task() to
  6329. * its new rq.
  6330. */
  6331. static void attach_one_task(struct rq *rq, struct task_struct *p)
  6332. {
  6333. struct rq_flags rf;
  6334. rq_lock(rq, &rf);
  6335. update_rq_clock(rq);
  6336. attach_task(rq, p);
  6337. rq_unlock(rq, &rf);
  6338. }
  6339. /*
  6340. * attach_tasks() -- attaches all tasks detached by detach_tasks() to their
  6341. * new rq.
  6342. */
  6343. static void attach_tasks(struct lb_env *env)
  6344. {
  6345. struct list_head *tasks = &env->tasks;
  6346. struct task_struct *p;
  6347. struct rq_flags rf;
  6348. rq_lock(env->dst_rq, &rf);
  6349. update_rq_clock(env->dst_rq);
  6350. while (!list_empty(tasks)) {
  6351. p = list_first_entry(tasks, struct task_struct, se.group_node);
  6352. list_del_init(&p->se.group_node);
  6353. attach_task(env->dst_rq, p);
  6354. }
  6355. rq_unlock(env->dst_rq, &rf);
  6356. }
  6357. static inline bool cfs_rq_has_blocked(struct cfs_rq *cfs_rq)
  6358. {
  6359. if (cfs_rq->avg.load_avg)
  6360. return true;
  6361. if (cfs_rq->avg.util_avg)
  6362. return true;
  6363. return false;
  6364. }
  6365. #ifdef CONFIG_FAIR_GROUP_SCHED
  6366. static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq)
  6367. {
  6368. if (cfs_rq->load.weight)
  6369. return false;
  6370. if (cfs_rq->avg.load_sum)
  6371. return false;
  6372. if (cfs_rq->avg.util_sum)
  6373. return false;
  6374. if (cfs_rq->avg.runnable_load_sum)
  6375. return false;
  6376. return true;
  6377. }
  6378. static void update_blocked_averages(int cpu)
  6379. {
  6380. struct rq *rq = cpu_rq(cpu);
  6381. struct cfs_rq *cfs_rq, *pos;
  6382. struct rq_flags rf;
  6383. bool done = true;
  6384. rq_lock_irqsave(rq, &rf);
  6385. update_rq_clock(rq);
  6386. /*
  6387. * Iterates the task_group tree in a bottom up fashion, see
  6388. * list_add_leaf_cfs_rq() for details.
  6389. */
  6390. for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) {
  6391. struct sched_entity *se;
  6392. /* throttled entities do not contribute to load */
  6393. if (throttled_hierarchy(cfs_rq))
  6394. continue;
  6395. if (update_cfs_rq_load_avg(cfs_rq_clock_task(cfs_rq), cfs_rq))
  6396. update_tg_load_avg(cfs_rq, 0);
  6397. /* Propagate pending load changes to the parent, if any: */
  6398. se = cfs_rq->tg->se[cpu];
  6399. if (se && !skip_blocked_update(se))
  6400. update_load_avg(cfs_rq_of(se), se, 0);
  6401. /*
  6402. * There can be a lot of idle CPU cgroups. Don't let fully
  6403. * decayed cfs_rqs linger on the list.
  6404. */
  6405. if (cfs_rq_is_decayed(cfs_rq))
  6406. list_del_leaf_cfs_rq(cfs_rq);
  6407. /* Don't need periodic decay once load/util_avg are null */
  6408. if (cfs_rq_has_blocked(cfs_rq))
  6409. done = false;
  6410. }
  6411. #ifdef CONFIG_NO_HZ_COMMON
  6412. rq->last_blocked_load_update_tick = jiffies;
  6413. if (done)
  6414. rq->has_blocked_load = 0;
  6415. #endif
  6416. rq_unlock_irqrestore(rq, &rf);
  6417. }
  6418. /*
  6419. * Compute the hierarchical load factor for cfs_rq and all its ascendants.
  6420. * This needs to be done in a top-down fashion because the load of a child
  6421. * group is a fraction of its parents load.
  6422. */
  6423. static void update_cfs_rq_h_load(struct cfs_rq *cfs_rq)
  6424. {
  6425. struct rq *rq = rq_of(cfs_rq);
  6426. struct sched_entity *se = cfs_rq->tg->se[cpu_of(rq)];
  6427. unsigned long now = jiffies;
  6428. unsigned long load;
  6429. if (cfs_rq->last_h_load_update == now)
  6430. return;
  6431. cfs_rq->h_load_next = NULL;
  6432. for_each_sched_entity(se) {
  6433. cfs_rq = cfs_rq_of(se);
  6434. cfs_rq->h_load_next = se;
  6435. if (cfs_rq->last_h_load_update == now)
  6436. break;
  6437. }
  6438. if (!se) {
  6439. cfs_rq->h_load = cfs_rq_load_avg(cfs_rq);
  6440. cfs_rq->last_h_load_update = now;
  6441. }
  6442. while ((se = cfs_rq->h_load_next) != NULL) {
  6443. load = cfs_rq->h_load;
  6444. load = div64_ul(load * se->avg.load_avg,
  6445. cfs_rq_load_avg(cfs_rq) + 1);
  6446. cfs_rq = group_cfs_rq(se);
  6447. cfs_rq->h_load = load;
  6448. cfs_rq->last_h_load_update = now;
  6449. }
  6450. }
  6451. static unsigned long task_h_load(struct task_struct *p)
  6452. {
  6453. struct cfs_rq *cfs_rq = task_cfs_rq(p);
  6454. update_cfs_rq_h_load(cfs_rq);
  6455. return div64_ul(p->se.avg.load_avg * cfs_rq->h_load,
  6456. cfs_rq_load_avg(cfs_rq) + 1);
  6457. }
  6458. #else
  6459. static inline void update_blocked_averages(int cpu)
  6460. {
  6461. struct rq *rq = cpu_rq(cpu);
  6462. struct cfs_rq *cfs_rq = &rq->cfs;
  6463. struct rq_flags rf;
  6464. rq_lock_irqsave(rq, &rf);
  6465. update_rq_clock(rq);
  6466. update_cfs_rq_load_avg(cfs_rq_clock_task(cfs_rq), cfs_rq);
  6467. #ifdef CONFIG_NO_HZ_COMMON
  6468. rq->last_blocked_load_update_tick = jiffies;
  6469. if (!cfs_rq_has_blocked(cfs_rq))
  6470. rq->has_blocked_load = 0;
  6471. #endif
  6472. rq_unlock_irqrestore(rq, &rf);
  6473. }
  6474. static unsigned long task_h_load(struct task_struct *p)
  6475. {
  6476. return p->se.avg.load_avg;
  6477. }
  6478. #endif
  6479. /********** Helpers for find_busiest_group ************************/
  6480. enum group_type {
  6481. group_other = 0,
  6482. group_imbalanced,
  6483. group_overloaded,
  6484. };
  6485. /*
  6486. * sg_lb_stats - stats of a sched_group required for load_balancing
  6487. */
  6488. struct sg_lb_stats {
  6489. unsigned long avg_load; /*Avg load across the CPUs of the group */
  6490. unsigned long group_load; /* Total load over the CPUs of the group */
  6491. unsigned long sum_weighted_load; /* Weighted load of group's tasks */
  6492. unsigned long load_per_task;
  6493. unsigned long group_capacity;
  6494. unsigned long group_util; /* Total utilization of the group */
  6495. unsigned int sum_nr_running; /* Nr tasks running in the group */
  6496. unsigned int idle_cpus;
  6497. unsigned int group_weight;
  6498. enum group_type group_type;
  6499. int group_no_capacity;
  6500. #ifdef CONFIG_NUMA_BALANCING
  6501. unsigned int nr_numa_running;
  6502. unsigned int nr_preferred_running;
  6503. #endif
  6504. };
  6505. /*
  6506. * sd_lb_stats - Structure to store the statistics of a sched_domain
  6507. * during load balancing.
  6508. */
  6509. struct sd_lb_stats {
  6510. struct sched_group *busiest; /* Busiest group in this sd */
  6511. struct sched_group *local; /* Local group in this sd */
  6512. unsigned long total_running;
  6513. unsigned long total_load; /* Total load of all groups in sd */
  6514. unsigned long total_capacity; /* Total capacity of all groups in sd */
  6515. unsigned long avg_load; /* Average load across all groups in sd */
  6516. struct sg_lb_stats busiest_stat;/* Statistics of the busiest group */
  6517. struct sg_lb_stats local_stat; /* Statistics of the local group */
  6518. };
  6519. static inline void init_sd_lb_stats(struct sd_lb_stats *sds)
  6520. {
  6521. /*
  6522. * Skimp on the clearing to avoid duplicate work. We can avoid clearing
  6523. * local_stat because update_sg_lb_stats() does a full clear/assignment.
  6524. * We must however clear busiest_stat::avg_load because
  6525. * update_sd_pick_busiest() reads this before assignment.
  6526. */
  6527. *sds = (struct sd_lb_stats){
  6528. .busiest = NULL,
  6529. .local = NULL,
  6530. .total_running = 0UL,
  6531. .total_load = 0UL,
  6532. .total_capacity = 0UL,
  6533. .busiest_stat = {
  6534. .avg_load = 0UL,
  6535. .sum_nr_running = 0,
  6536. .group_type = group_other,
  6537. },
  6538. };
  6539. }
  6540. /**
  6541. * get_sd_load_idx - Obtain the load index for a given sched domain.
  6542. * @sd: The sched_domain whose load_idx is to be obtained.
  6543. * @idle: The idle status of the CPU for whose sd load_idx is obtained.
  6544. *
  6545. * Return: The load index.
  6546. */
  6547. static inline int get_sd_load_idx(struct sched_domain *sd,
  6548. enum cpu_idle_type idle)
  6549. {
  6550. int load_idx;
  6551. switch (idle) {
  6552. case CPU_NOT_IDLE:
  6553. load_idx = sd->busy_idx;
  6554. break;
  6555. case CPU_NEWLY_IDLE:
  6556. load_idx = sd->newidle_idx;
  6557. break;
  6558. default:
  6559. load_idx = sd->idle_idx;
  6560. break;
  6561. }
  6562. return load_idx;
  6563. }
  6564. static unsigned long scale_rt_capacity(int cpu)
  6565. {
  6566. struct rq *rq = cpu_rq(cpu);
  6567. u64 total, used, age_stamp, avg;
  6568. s64 delta;
  6569. /*
  6570. * Since we're reading these variables without serialization make sure
  6571. * we read them once before doing sanity checks on them.
  6572. */
  6573. age_stamp = READ_ONCE(rq->age_stamp);
  6574. avg = READ_ONCE(rq->rt_avg);
  6575. delta = __rq_clock_broken(rq) - age_stamp;
  6576. if (unlikely(delta < 0))
  6577. delta = 0;
  6578. total = sched_avg_period() + delta;
  6579. used = div_u64(avg, total);
  6580. if (likely(used < SCHED_CAPACITY_SCALE))
  6581. return SCHED_CAPACITY_SCALE - used;
  6582. return 1;
  6583. }
  6584. static void update_cpu_capacity(struct sched_domain *sd, int cpu)
  6585. {
  6586. unsigned long capacity = arch_scale_cpu_capacity(sd, cpu);
  6587. struct sched_group *sdg = sd->groups;
  6588. cpu_rq(cpu)->cpu_capacity_orig = capacity;
  6589. capacity *= scale_rt_capacity(cpu);
  6590. capacity >>= SCHED_CAPACITY_SHIFT;
  6591. if (!capacity)
  6592. capacity = 1;
  6593. cpu_rq(cpu)->cpu_capacity = capacity;
  6594. sdg->sgc->capacity = capacity;
  6595. sdg->sgc->min_capacity = capacity;
  6596. }
  6597. void update_group_capacity(struct sched_domain *sd, int cpu)
  6598. {
  6599. struct sched_domain *child = sd->child;
  6600. struct sched_group *group, *sdg = sd->groups;
  6601. unsigned long capacity, min_capacity;
  6602. unsigned long interval;
  6603. interval = msecs_to_jiffies(sd->balance_interval);
  6604. interval = clamp(interval, 1UL, max_load_balance_interval);
  6605. sdg->sgc->next_update = jiffies + interval;
  6606. if (!child) {
  6607. update_cpu_capacity(sd, cpu);
  6608. return;
  6609. }
  6610. capacity = 0;
  6611. min_capacity = ULONG_MAX;
  6612. if (child->flags & SD_OVERLAP) {
  6613. /*
  6614. * SD_OVERLAP domains cannot assume that child groups
  6615. * span the current group.
  6616. */
  6617. for_each_cpu(cpu, sched_group_span(sdg)) {
  6618. struct sched_group_capacity *sgc;
  6619. struct rq *rq = cpu_rq(cpu);
  6620. /*
  6621. * build_sched_domains() -> init_sched_groups_capacity()
  6622. * gets here before we've attached the domains to the
  6623. * runqueues.
  6624. *
  6625. * Use capacity_of(), which is set irrespective of domains
  6626. * in update_cpu_capacity().
  6627. *
  6628. * This avoids capacity from being 0 and
  6629. * causing divide-by-zero issues on boot.
  6630. */
  6631. if (unlikely(!rq->sd)) {
  6632. capacity += capacity_of(cpu);
  6633. } else {
  6634. sgc = rq->sd->groups->sgc;
  6635. capacity += sgc->capacity;
  6636. }
  6637. min_capacity = min(capacity, min_capacity);
  6638. }
  6639. } else {
  6640. /*
  6641. * !SD_OVERLAP domains can assume that child groups
  6642. * span the current group.
  6643. */
  6644. group = child->groups;
  6645. do {
  6646. struct sched_group_capacity *sgc = group->sgc;
  6647. capacity += sgc->capacity;
  6648. min_capacity = min(sgc->min_capacity, min_capacity);
  6649. group = group->next;
  6650. } while (group != child->groups);
  6651. }
  6652. sdg->sgc->capacity = capacity;
  6653. sdg->sgc->min_capacity = min_capacity;
  6654. }
  6655. /*
  6656. * Check whether the capacity of the rq has been noticeably reduced by side
  6657. * activity. The imbalance_pct is used for the threshold.
  6658. * Return true is the capacity is reduced
  6659. */
  6660. static inline int
  6661. check_cpu_capacity(struct rq *rq, struct sched_domain *sd)
  6662. {
  6663. return ((rq->cpu_capacity * sd->imbalance_pct) <
  6664. (rq->cpu_capacity_orig * 100));
  6665. }
  6666. /*
  6667. * Group imbalance indicates (and tries to solve) the problem where balancing
  6668. * groups is inadequate due to ->cpus_allowed constraints.
  6669. *
  6670. * Imagine a situation of two groups of 4 CPUs each and 4 tasks each with a
  6671. * cpumask covering 1 CPU of the first group and 3 CPUs of the second group.
  6672. * Something like:
  6673. *
  6674. * { 0 1 2 3 } { 4 5 6 7 }
  6675. * * * * *
  6676. *
  6677. * If we were to balance group-wise we'd place two tasks in the first group and
  6678. * two tasks in the second group. Clearly this is undesired as it will overload
  6679. * cpu 3 and leave one of the CPUs in the second group unused.
  6680. *
  6681. * The current solution to this issue is detecting the skew in the first group
  6682. * by noticing the lower domain failed to reach balance and had difficulty
  6683. * moving tasks due to affinity constraints.
  6684. *
  6685. * When this is so detected; this group becomes a candidate for busiest; see
  6686. * update_sd_pick_busiest(). And calculate_imbalance() and
  6687. * find_busiest_group() avoid some of the usual balance conditions to allow it
  6688. * to create an effective group imbalance.
  6689. *
  6690. * This is a somewhat tricky proposition since the next run might not find the
  6691. * group imbalance and decide the groups need to be balanced again. A most
  6692. * subtle and fragile situation.
  6693. */
  6694. static inline int sg_imbalanced(struct sched_group *group)
  6695. {
  6696. return group->sgc->imbalance;
  6697. }
  6698. /*
  6699. * group_has_capacity returns true if the group has spare capacity that could
  6700. * be used by some tasks.
  6701. * We consider that a group has spare capacity if the * number of task is
  6702. * smaller than the number of CPUs or if the utilization is lower than the
  6703. * available capacity for CFS tasks.
  6704. * For the latter, we use a threshold to stabilize the state, to take into
  6705. * account the variance of the tasks' load and to return true if the available
  6706. * capacity in meaningful for the load balancer.
  6707. * As an example, an available capacity of 1% can appear but it doesn't make
  6708. * any benefit for the load balance.
  6709. */
  6710. static inline bool
  6711. group_has_capacity(struct lb_env *env, struct sg_lb_stats *sgs)
  6712. {
  6713. if (sgs->sum_nr_running < sgs->group_weight)
  6714. return true;
  6715. if ((sgs->group_capacity * 100) >
  6716. (sgs->group_util * env->sd->imbalance_pct))
  6717. return true;
  6718. return false;
  6719. }
  6720. /*
  6721. * group_is_overloaded returns true if the group has more tasks than it can
  6722. * handle.
  6723. * group_is_overloaded is not equals to !group_has_capacity because a group
  6724. * with the exact right number of tasks, has no more spare capacity but is not
  6725. * overloaded so both group_has_capacity and group_is_overloaded return
  6726. * false.
  6727. */
  6728. static inline bool
  6729. group_is_overloaded(struct lb_env *env, struct sg_lb_stats *sgs)
  6730. {
  6731. if (sgs->sum_nr_running <= sgs->group_weight)
  6732. return false;
  6733. if ((sgs->group_capacity * 100) <
  6734. (sgs->group_util * env->sd->imbalance_pct))
  6735. return true;
  6736. return false;
  6737. }
  6738. /*
  6739. * group_smaller_cpu_capacity: Returns true if sched_group sg has smaller
  6740. * per-CPU capacity than sched_group ref.
  6741. */
  6742. static inline bool
  6743. group_smaller_cpu_capacity(struct sched_group *sg, struct sched_group *ref)
  6744. {
  6745. return sg->sgc->min_capacity * capacity_margin <
  6746. ref->sgc->min_capacity * 1024;
  6747. }
  6748. static inline enum
  6749. group_type group_classify(struct sched_group *group,
  6750. struct sg_lb_stats *sgs)
  6751. {
  6752. if (sgs->group_no_capacity)
  6753. return group_overloaded;
  6754. if (sg_imbalanced(group))
  6755. return group_imbalanced;
  6756. return group_other;
  6757. }
  6758. static bool update_nohz_stats(struct rq *rq, bool force)
  6759. {
  6760. #ifdef CONFIG_NO_HZ_COMMON
  6761. unsigned int cpu = rq->cpu;
  6762. if (!rq->has_blocked_load)
  6763. return false;
  6764. if (!cpumask_test_cpu(cpu, nohz.idle_cpus_mask))
  6765. return false;
  6766. if (!force && !time_after(jiffies, rq->last_blocked_load_update_tick))
  6767. return true;
  6768. update_blocked_averages(cpu);
  6769. return rq->has_blocked_load;
  6770. #else
  6771. return false;
  6772. #endif
  6773. }
  6774. /**
  6775. * update_sg_lb_stats - Update sched_group's statistics for load balancing.
  6776. * @env: The load balancing environment.
  6777. * @group: sched_group whose statistics are to be updated.
  6778. * @load_idx: Load index of sched_domain of this_cpu for load calc.
  6779. * @local_group: Does group contain this_cpu.
  6780. * @sgs: variable to hold the statistics for this group.
  6781. * @overload: Indicate more than one runnable task for any CPU.
  6782. */
  6783. static inline void update_sg_lb_stats(struct lb_env *env,
  6784. struct sched_group *group, int load_idx,
  6785. int local_group, struct sg_lb_stats *sgs,
  6786. bool *overload)
  6787. {
  6788. unsigned long load;
  6789. int i, nr_running;
  6790. memset(sgs, 0, sizeof(*sgs));
  6791. for_each_cpu_and(i, sched_group_span(group), env->cpus) {
  6792. struct rq *rq = cpu_rq(i);
  6793. if ((env->flags & LBF_NOHZ_STATS) && update_nohz_stats(rq, false))
  6794. env->flags |= LBF_NOHZ_AGAIN;
  6795. /* Bias balancing toward CPUs of our domain: */
  6796. if (local_group)
  6797. load = target_load(i, load_idx);
  6798. else
  6799. load = source_load(i, load_idx);
  6800. sgs->group_load += load;
  6801. sgs->group_util += cpu_util(i);
  6802. sgs->sum_nr_running += rq->cfs.h_nr_running;
  6803. nr_running = rq->nr_running;
  6804. if (nr_running > 1)
  6805. *overload = true;
  6806. #ifdef CONFIG_NUMA_BALANCING
  6807. sgs->nr_numa_running += rq->nr_numa_running;
  6808. sgs->nr_preferred_running += rq->nr_preferred_running;
  6809. #endif
  6810. sgs->sum_weighted_load += weighted_cpuload(rq);
  6811. /*
  6812. * No need to call idle_cpu() if nr_running is not 0
  6813. */
  6814. if (!nr_running && idle_cpu(i))
  6815. sgs->idle_cpus++;
  6816. }
  6817. /* Adjust by relative CPU capacity of the group */
  6818. sgs->group_capacity = group->sgc->capacity;
  6819. sgs->avg_load = (sgs->group_load*SCHED_CAPACITY_SCALE) / sgs->group_capacity;
  6820. if (sgs->sum_nr_running)
  6821. sgs->load_per_task = sgs->sum_weighted_load / sgs->sum_nr_running;
  6822. sgs->group_weight = group->group_weight;
  6823. sgs->group_no_capacity = group_is_overloaded(env, sgs);
  6824. sgs->group_type = group_classify(group, sgs);
  6825. }
  6826. /**
  6827. * update_sd_pick_busiest - return 1 on busiest group
  6828. * @env: The load balancing environment.
  6829. * @sds: sched_domain statistics
  6830. * @sg: sched_group candidate to be checked for being the busiest
  6831. * @sgs: sched_group statistics
  6832. *
  6833. * Determine if @sg is a busier group than the previously selected
  6834. * busiest group.
  6835. *
  6836. * Return: %true if @sg is a busier group than the previously selected
  6837. * busiest group. %false otherwise.
  6838. */
  6839. static bool update_sd_pick_busiest(struct lb_env *env,
  6840. struct sd_lb_stats *sds,
  6841. struct sched_group *sg,
  6842. struct sg_lb_stats *sgs)
  6843. {
  6844. struct sg_lb_stats *busiest = &sds->busiest_stat;
  6845. if (sgs->group_type > busiest->group_type)
  6846. return true;
  6847. if (sgs->group_type < busiest->group_type)
  6848. return false;
  6849. if (sgs->avg_load <= busiest->avg_load)
  6850. return false;
  6851. if (!(env->sd->flags & SD_ASYM_CPUCAPACITY))
  6852. goto asym_packing;
  6853. /*
  6854. * Candidate sg has no more than one task per CPU and
  6855. * has higher per-CPU capacity. Migrating tasks to less
  6856. * capable CPUs may harm throughput. Maximize throughput,
  6857. * power/energy consequences are not considered.
  6858. */
  6859. if (sgs->sum_nr_running <= sgs->group_weight &&
  6860. group_smaller_cpu_capacity(sds->local, sg))
  6861. return false;
  6862. asym_packing:
  6863. /* This is the busiest node in its class. */
  6864. if (!(env->sd->flags & SD_ASYM_PACKING))
  6865. return true;
  6866. /* No ASYM_PACKING if target CPU is already busy */
  6867. if (env->idle == CPU_NOT_IDLE)
  6868. return true;
  6869. /*
  6870. * ASYM_PACKING needs to move all the work to the highest
  6871. * prority CPUs in the group, therefore mark all groups
  6872. * of lower priority than ourself as busy.
  6873. */
  6874. if (sgs->sum_nr_running &&
  6875. sched_asym_prefer(env->dst_cpu, sg->asym_prefer_cpu)) {
  6876. if (!sds->busiest)
  6877. return true;
  6878. /* Prefer to move from lowest priority CPU's work */
  6879. if (sched_asym_prefer(sds->busiest->asym_prefer_cpu,
  6880. sg->asym_prefer_cpu))
  6881. return true;
  6882. }
  6883. return false;
  6884. }
  6885. #ifdef CONFIG_NUMA_BALANCING
  6886. static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
  6887. {
  6888. if (sgs->sum_nr_running > sgs->nr_numa_running)
  6889. return regular;
  6890. if (sgs->sum_nr_running > sgs->nr_preferred_running)
  6891. return remote;
  6892. return all;
  6893. }
  6894. static inline enum fbq_type fbq_classify_rq(struct rq *rq)
  6895. {
  6896. if (rq->nr_running > rq->nr_numa_running)
  6897. return regular;
  6898. if (rq->nr_running > rq->nr_preferred_running)
  6899. return remote;
  6900. return all;
  6901. }
  6902. #else
  6903. static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
  6904. {
  6905. return all;
  6906. }
  6907. static inline enum fbq_type fbq_classify_rq(struct rq *rq)
  6908. {
  6909. return regular;
  6910. }
  6911. #endif /* CONFIG_NUMA_BALANCING */
  6912. /**
  6913. * update_sd_lb_stats - Update sched_domain's statistics for load balancing.
  6914. * @env: The load balancing environment.
  6915. * @sds: variable to hold the statistics for this sched_domain.
  6916. */
  6917. static inline void update_sd_lb_stats(struct lb_env *env, struct sd_lb_stats *sds)
  6918. {
  6919. struct sched_domain *child = env->sd->child;
  6920. struct sched_group *sg = env->sd->groups;
  6921. struct sg_lb_stats *local = &sds->local_stat;
  6922. struct sg_lb_stats tmp_sgs;
  6923. int load_idx, prefer_sibling = 0;
  6924. bool overload = false;
  6925. if (child && child->flags & SD_PREFER_SIBLING)
  6926. prefer_sibling = 1;
  6927. #ifdef CONFIG_NO_HZ_COMMON
  6928. if (env->idle == CPU_NEWLY_IDLE && READ_ONCE(nohz.has_blocked))
  6929. env->flags |= LBF_NOHZ_STATS;
  6930. #endif
  6931. load_idx = get_sd_load_idx(env->sd, env->idle);
  6932. do {
  6933. struct sg_lb_stats *sgs = &tmp_sgs;
  6934. int local_group;
  6935. local_group = cpumask_test_cpu(env->dst_cpu, sched_group_span(sg));
  6936. if (local_group) {
  6937. sds->local = sg;
  6938. sgs = local;
  6939. if (env->idle != CPU_NEWLY_IDLE ||
  6940. time_after_eq(jiffies, sg->sgc->next_update))
  6941. update_group_capacity(env->sd, env->dst_cpu);
  6942. }
  6943. update_sg_lb_stats(env, sg, load_idx, local_group, sgs,
  6944. &overload);
  6945. if (local_group)
  6946. goto next_group;
  6947. /*
  6948. * In case the child domain prefers tasks go to siblings
  6949. * first, lower the sg capacity so that we'll try
  6950. * and move all the excess tasks away. We lower the capacity
  6951. * of a group only if the local group has the capacity to fit
  6952. * these excess tasks. The extra check prevents the case where
  6953. * you always pull from the heaviest group when it is already
  6954. * under-utilized (possible with a large weight task outweighs
  6955. * the tasks on the system).
  6956. */
  6957. if (prefer_sibling && sds->local &&
  6958. group_has_capacity(env, local) &&
  6959. (sgs->sum_nr_running > local->sum_nr_running + 1)) {
  6960. sgs->group_no_capacity = 1;
  6961. sgs->group_type = group_classify(sg, sgs);
  6962. }
  6963. if (update_sd_pick_busiest(env, sds, sg, sgs)) {
  6964. sds->busiest = sg;
  6965. sds->busiest_stat = *sgs;
  6966. }
  6967. next_group:
  6968. /* Now, start updating sd_lb_stats */
  6969. sds->total_running += sgs->sum_nr_running;
  6970. sds->total_load += sgs->group_load;
  6971. sds->total_capacity += sgs->group_capacity;
  6972. sg = sg->next;
  6973. } while (sg != env->sd->groups);
  6974. #ifdef CONFIG_NO_HZ_COMMON
  6975. if ((env->flags & LBF_NOHZ_AGAIN) &&
  6976. cpumask_subset(nohz.idle_cpus_mask, sched_domain_span(env->sd))) {
  6977. WRITE_ONCE(nohz.next_blocked,
  6978. jiffies + msecs_to_jiffies(LOAD_AVG_PERIOD));
  6979. }
  6980. #endif
  6981. if (env->sd->flags & SD_NUMA)
  6982. env->fbq_type = fbq_classify_group(&sds->busiest_stat);
  6983. if (!env->sd->parent) {
  6984. /* update overload indicator if we are at root domain */
  6985. if (env->dst_rq->rd->overload != overload)
  6986. env->dst_rq->rd->overload = overload;
  6987. }
  6988. }
  6989. /**
  6990. * check_asym_packing - Check to see if the group is packed into the
  6991. * sched domain.
  6992. *
  6993. * This is primarily intended to used at the sibling level. Some
  6994. * cores like POWER7 prefer to use lower numbered SMT threads. In the
  6995. * case of POWER7, it can move to lower SMT modes only when higher
  6996. * threads are idle. When in lower SMT modes, the threads will
  6997. * perform better since they share less core resources. Hence when we
  6998. * have idle threads, we want them to be the higher ones.
  6999. *
  7000. * This packing function is run on idle threads. It checks to see if
  7001. * the busiest CPU in this domain (core in the P7 case) has a higher
  7002. * CPU number than the packing function is being run on. Here we are
  7003. * assuming lower CPU number will be equivalent to lower a SMT thread
  7004. * number.
  7005. *
  7006. * Return: 1 when packing is required and a task should be moved to
  7007. * this CPU. The amount of the imbalance is returned in env->imbalance.
  7008. *
  7009. * @env: The load balancing environment.
  7010. * @sds: Statistics of the sched_domain which is to be packed
  7011. */
  7012. static int check_asym_packing(struct lb_env *env, struct sd_lb_stats *sds)
  7013. {
  7014. int busiest_cpu;
  7015. if (!(env->sd->flags & SD_ASYM_PACKING))
  7016. return 0;
  7017. if (env->idle == CPU_NOT_IDLE)
  7018. return 0;
  7019. if (!sds->busiest)
  7020. return 0;
  7021. busiest_cpu = sds->busiest->asym_prefer_cpu;
  7022. if (sched_asym_prefer(busiest_cpu, env->dst_cpu))
  7023. return 0;
  7024. env->imbalance = DIV_ROUND_CLOSEST(
  7025. sds->busiest_stat.avg_load * sds->busiest_stat.group_capacity,
  7026. SCHED_CAPACITY_SCALE);
  7027. return 1;
  7028. }
  7029. /**
  7030. * fix_small_imbalance - Calculate the minor imbalance that exists
  7031. * amongst the groups of a sched_domain, during
  7032. * load balancing.
  7033. * @env: The load balancing environment.
  7034. * @sds: Statistics of the sched_domain whose imbalance is to be calculated.
  7035. */
  7036. static inline
  7037. void fix_small_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
  7038. {
  7039. unsigned long tmp, capa_now = 0, capa_move = 0;
  7040. unsigned int imbn = 2;
  7041. unsigned long scaled_busy_load_per_task;
  7042. struct sg_lb_stats *local, *busiest;
  7043. local = &sds->local_stat;
  7044. busiest = &sds->busiest_stat;
  7045. if (!local->sum_nr_running)
  7046. local->load_per_task = cpu_avg_load_per_task(env->dst_cpu);
  7047. else if (busiest->load_per_task > local->load_per_task)
  7048. imbn = 1;
  7049. scaled_busy_load_per_task =
  7050. (busiest->load_per_task * SCHED_CAPACITY_SCALE) /
  7051. busiest->group_capacity;
  7052. if (busiest->avg_load + scaled_busy_load_per_task >=
  7053. local->avg_load + (scaled_busy_load_per_task * imbn)) {
  7054. env->imbalance = busiest->load_per_task;
  7055. return;
  7056. }
  7057. /*
  7058. * OK, we don't have enough imbalance to justify moving tasks,
  7059. * however we may be able to increase total CPU capacity used by
  7060. * moving them.
  7061. */
  7062. capa_now += busiest->group_capacity *
  7063. min(busiest->load_per_task, busiest->avg_load);
  7064. capa_now += local->group_capacity *
  7065. min(local->load_per_task, local->avg_load);
  7066. capa_now /= SCHED_CAPACITY_SCALE;
  7067. /* Amount of load we'd subtract */
  7068. if (busiest->avg_load > scaled_busy_load_per_task) {
  7069. capa_move += busiest->group_capacity *
  7070. min(busiest->load_per_task,
  7071. busiest->avg_load - scaled_busy_load_per_task);
  7072. }
  7073. /* Amount of load we'd add */
  7074. if (busiest->avg_load * busiest->group_capacity <
  7075. busiest->load_per_task * SCHED_CAPACITY_SCALE) {
  7076. tmp = (busiest->avg_load * busiest->group_capacity) /
  7077. local->group_capacity;
  7078. } else {
  7079. tmp = (busiest->load_per_task * SCHED_CAPACITY_SCALE) /
  7080. local->group_capacity;
  7081. }
  7082. capa_move += local->group_capacity *
  7083. min(local->load_per_task, local->avg_load + tmp);
  7084. capa_move /= SCHED_CAPACITY_SCALE;
  7085. /* Move if we gain throughput */
  7086. if (capa_move > capa_now)
  7087. env->imbalance = busiest->load_per_task;
  7088. }
  7089. /**
  7090. * calculate_imbalance - Calculate the amount of imbalance present within the
  7091. * groups of a given sched_domain during load balance.
  7092. * @env: load balance environment
  7093. * @sds: statistics of the sched_domain whose imbalance is to be calculated.
  7094. */
  7095. static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
  7096. {
  7097. unsigned long max_pull, load_above_capacity = ~0UL;
  7098. struct sg_lb_stats *local, *busiest;
  7099. local = &sds->local_stat;
  7100. busiest = &sds->busiest_stat;
  7101. if (busiest->group_type == group_imbalanced) {
  7102. /*
  7103. * In the group_imb case we cannot rely on group-wide averages
  7104. * to ensure CPU-load equilibrium, look at wider averages. XXX
  7105. */
  7106. busiest->load_per_task =
  7107. min(busiest->load_per_task, sds->avg_load);
  7108. }
  7109. /*
  7110. * Avg load of busiest sg can be less and avg load of local sg can
  7111. * be greater than avg load across all sgs of sd because avg load
  7112. * factors in sg capacity and sgs with smaller group_type are
  7113. * skipped when updating the busiest sg:
  7114. */
  7115. if (busiest->avg_load <= sds->avg_load ||
  7116. local->avg_load >= sds->avg_load) {
  7117. env->imbalance = 0;
  7118. return fix_small_imbalance(env, sds);
  7119. }
  7120. /*
  7121. * If there aren't any idle CPUs, avoid creating some.
  7122. */
  7123. if (busiest->group_type == group_overloaded &&
  7124. local->group_type == group_overloaded) {
  7125. load_above_capacity = busiest->sum_nr_running * SCHED_CAPACITY_SCALE;
  7126. if (load_above_capacity > busiest->group_capacity) {
  7127. load_above_capacity -= busiest->group_capacity;
  7128. load_above_capacity *= scale_load_down(NICE_0_LOAD);
  7129. load_above_capacity /= busiest->group_capacity;
  7130. } else
  7131. load_above_capacity = ~0UL;
  7132. }
  7133. /*
  7134. * We're trying to get all the CPUs to the average_load, so we don't
  7135. * want to push ourselves above the average load, nor do we wish to
  7136. * reduce the max loaded CPU below the average load. At the same time,
  7137. * we also don't want to reduce the group load below the group
  7138. * capacity. Thus we look for the minimum possible imbalance.
  7139. */
  7140. max_pull = min(busiest->avg_load - sds->avg_load, load_above_capacity);
  7141. /* How much load to actually move to equalise the imbalance */
  7142. env->imbalance = min(
  7143. max_pull * busiest->group_capacity,
  7144. (sds->avg_load - local->avg_load) * local->group_capacity
  7145. ) / SCHED_CAPACITY_SCALE;
  7146. /*
  7147. * if *imbalance is less than the average load per runnable task
  7148. * there is no guarantee that any tasks will be moved so we'll have
  7149. * a think about bumping its value to force at least one task to be
  7150. * moved
  7151. */
  7152. if (env->imbalance < busiest->load_per_task)
  7153. return fix_small_imbalance(env, sds);
  7154. }
  7155. /******* find_busiest_group() helpers end here *********************/
  7156. /**
  7157. * find_busiest_group - Returns the busiest group within the sched_domain
  7158. * if there is an imbalance.
  7159. *
  7160. * Also calculates the amount of weighted load which should be moved
  7161. * to restore balance.
  7162. *
  7163. * @env: The load balancing environment.
  7164. *
  7165. * Return: - The busiest group if imbalance exists.
  7166. */
  7167. static struct sched_group *find_busiest_group(struct lb_env *env)
  7168. {
  7169. struct sg_lb_stats *local, *busiest;
  7170. struct sd_lb_stats sds;
  7171. init_sd_lb_stats(&sds);
  7172. /*
  7173. * Compute the various statistics relavent for load balancing at
  7174. * this level.
  7175. */
  7176. update_sd_lb_stats(env, &sds);
  7177. local = &sds.local_stat;
  7178. busiest = &sds.busiest_stat;
  7179. /* ASYM feature bypasses nice load balance check */
  7180. if (check_asym_packing(env, &sds))
  7181. return sds.busiest;
  7182. /* There is no busy sibling group to pull tasks from */
  7183. if (!sds.busiest || busiest->sum_nr_running == 0)
  7184. goto out_balanced;
  7185. /* XXX broken for overlapping NUMA groups */
  7186. sds.avg_load = (SCHED_CAPACITY_SCALE * sds.total_load)
  7187. / sds.total_capacity;
  7188. /*
  7189. * If the busiest group is imbalanced the below checks don't
  7190. * work because they assume all things are equal, which typically
  7191. * isn't true due to cpus_allowed constraints and the like.
  7192. */
  7193. if (busiest->group_type == group_imbalanced)
  7194. goto force_balance;
  7195. /*
  7196. * When dst_cpu is idle, prevent SMP nice and/or asymmetric group
  7197. * capacities from resulting in underutilization due to avg_load.
  7198. */
  7199. if (env->idle != CPU_NOT_IDLE && group_has_capacity(env, local) &&
  7200. busiest->group_no_capacity)
  7201. goto force_balance;
  7202. /*
  7203. * If the local group is busier than the selected busiest group
  7204. * don't try and pull any tasks.
  7205. */
  7206. if (local->avg_load >= busiest->avg_load)
  7207. goto out_balanced;
  7208. /*
  7209. * Don't pull any tasks if this group is already above the domain
  7210. * average load.
  7211. */
  7212. if (local->avg_load >= sds.avg_load)
  7213. goto out_balanced;
  7214. if (env->idle == CPU_IDLE) {
  7215. /*
  7216. * This CPU is idle. If the busiest group is not overloaded
  7217. * and there is no imbalance between this and busiest group
  7218. * wrt idle CPUs, it is balanced. The imbalance becomes
  7219. * significant if the diff is greater than 1 otherwise we
  7220. * might end up to just move the imbalance on another group
  7221. */
  7222. if ((busiest->group_type != group_overloaded) &&
  7223. (local->idle_cpus <= (busiest->idle_cpus + 1)))
  7224. goto out_balanced;
  7225. } else {
  7226. /*
  7227. * In the CPU_NEWLY_IDLE, CPU_NOT_IDLE cases, use
  7228. * imbalance_pct to be conservative.
  7229. */
  7230. if (100 * busiest->avg_load <=
  7231. env->sd->imbalance_pct * local->avg_load)
  7232. goto out_balanced;
  7233. }
  7234. force_balance:
  7235. /* Looks like there is an imbalance. Compute it */
  7236. calculate_imbalance(env, &sds);
  7237. return sds.busiest;
  7238. out_balanced:
  7239. env->imbalance = 0;
  7240. return NULL;
  7241. }
  7242. /*
  7243. * find_busiest_queue - find the busiest runqueue among the CPUs in the group.
  7244. */
  7245. static struct rq *find_busiest_queue(struct lb_env *env,
  7246. struct sched_group *group)
  7247. {
  7248. struct rq *busiest = NULL, *rq;
  7249. unsigned long busiest_load = 0, busiest_capacity = 1;
  7250. int i;
  7251. for_each_cpu_and(i, sched_group_span(group), env->cpus) {
  7252. unsigned long capacity, wl;
  7253. enum fbq_type rt;
  7254. rq = cpu_rq(i);
  7255. rt = fbq_classify_rq(rq);
  7256. /*
  7257. * We classify groups/runqueues into three groups:
  7258. * - regular: there are !numa tasks
  7259. * - remote: there are numa tasks that run on the 'wrong' node
  7260. * - all: there is no distinction
  7261. *
  7262. * In order to avoid migrating ideally placed numa tasks,
  7263. * ignore those when there's better options.
  7264. *
  7265. * If we ignore the actual busiest queue to migrate another
  7266. * task, the next balance pass can still reduce the busiest
  7267. * queue by moving tasks around inside the node.
  7268. *
  7269. * If we cannot move enough load due to this classification
  7270. * the next pass will adjust the group classification and
  7271. * allow migration of more tasks.
  7272. *
  7273. * Both cases only affect the total convergence complexity.
  7274. */
  7275. if (rt > env->fbq_type)
  7276. continue;
  7277. capacity = capacity_of(i);
  7278. wl = weighted_cpuload(rq);
  7279. /*
  7280. * When comparing with imbalance, use weighted_cpuload()
  7281. * which is not scaled with the CPU capacity.
  7282. */
  7283. if (rq->nr_running == 1 && wl > env->imbalance &&
  7284. !check_cpu_capacity(rq, env->sd))
  7285. continue;
  7286. /*
  7287. * For the load comparisons with the other CPU's, consider
  7288. * the weighted_cpuload() scaled with the CPU capacity, so
  7289. * that the load can be moved away from the CPU that is
  7290. * potentially running at a lower capacity.
  7291. *
  7292. * Thus we're looking for max(wl_i / capacity_i), crosswise
  7293. * multiplication to rid ourselves of the division works out
  7294. * to: wl_i * capacity_j > wl_j * capacity_i; where j is
  7295. * our previous maximum.
  7296. */
  7297. if (wl * busiest_capacity > busiest_load * capacity) {
  7298. busiest_load = wl;
  7299. busiest_capacity = capacity;
  7300. busiest = rq;
  7301. }
  7302. }
  7303. return busiest;
  7304. }
  7305. /*
  7306. * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
  7307. * so long as it is large enough.
  7308. */
  7309. #define MAX_PINNED_INTERVAL 512
  7310. static int need_active_balance(struct lb_env *env)
  7311. {
  7312. struct sched_domain *sd = env->sd;
  7313. if (env->idle == CPU_NEWLY_IDLE) {
  7314. /*
  7315. * ASYM_PACKING needs to force migrate tasks from busy but
  7316. * lower priority CPUs in order to pack all tasks in the
  7317. * highest priority CPUs.
  7318. */
  7319. if ((sd->flags & SD_ASYM_PACKING) &&
  7320. sched_asym_prefer(env->dst_cpu, env->src_cpu))
  7321. return 1;
  7322. }
  7323. /*
  7324. * The dst_cpu is idle and the src_cpu CPU has only 1 CFS task.
  7325. * It's worth migrating the task if the src_cpu's capacity is reduced
  7326. * because of other sched_class or IRQs if more capacity stays
  7327. * available on dst_cpu.
  7328. */
  7329. if ((env->idle != CPU_NOT_IDLE) &&
  7330. (env->src_rq->cfs.h_nr_running == 1)) {
  7331. if ((check_cpu_capacity(env->src_rq, sd)) &&
  7332. (capacity_of(env->src_cpu)*sd->imbalance_pct < capacity_of(env->dst_cpu)*100))
  7333. return 1;
  7334. }
  7335. return unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2);
  7336. }
  7337. static int active_load_balance_cpu_stop(void *data);
  7338. static int should_we_balance(struct lb_env *env)
  7339. {
  7340. struct sched_group *sg = env->sd->groups;
  7341. int cpu, balance_cpu = -1;
  7342. /*
  7343. * Ensure the balancing environment is consistent; can happen
  7344. * when the softirq triggers 'during' hotplug.
  7345. */
  7346. if (!cpumask_test_cpu(env->dst_cpu, env->cpus))
  7347. return 0;
  7348. /*
  7349. * In the newly idle case, we will allow all the CPUs
  7350. * to do the newly idle load balance.
  7351. */
  7352. if (env->idle == CPU_NEWLY_IDLE)
  7353. return 1;
  7354. /* Try to find first idle CPU */
  7355. for_each_cpu_and(cpu, group_balance_mask(sg), env->cpus) {
  7356. if (!idle_cpu(cpu))
  7357. continue;
  7358. balance_cpu = cpu;
  7359. break;
  7360. }
  7361. if (balance_cpu == -1)
  7362. balance_cpu = group_balance_cpu(sg);
  7363. /*
  7364. * First idle CPU or the first CPU(busiest) in this sched group
  7365. * is eligible for doing load balancing at this and above domains.
  7366. */
  7367. return balance_cpu == env->dst_cpu;
  7368. }
  7369. /*
  7370. * Check this_cpu to ensure it is balanced within domain. Attempt to move
  7371. * tasks if there is an imbalance.
  7372. */
  7373. static int load_balance(int this_cpu, struct rq *this_rq,
  7374. struct sched_domain *sd, enum cpu_idle_type idle,
  7375. int *continue_balancing)
  7376. {
  7377. int ld_moved, cur_ld_moved, active_balance = 0;
  7378. struct sched_domain *sd_parent = sd->parent;
  7379. struct sched_group *group;
  7380. struct rq *busiest;
  7381. struct rq_flags rf;
  7382. struct cpumask *cpus = this_cpu_cpumask_var_ptr(load_balance_mask);
  7383. struct lb_env env = {
  7384. .sd = sd,
  7385. .dst_cpu = this_cpu,
  7386. .dst_rq = this_rq,
  7387. .dst_grpmask = sched_group_span(sd->groups),
  7388. .idle = idle,
  7389. .loop_break = sched_nr_migrate_break,
  7390. .cpus = cpus,
  7391. .fbq_type = all,
  7392. .tasks = LIST_HEAD_INIT(env.tasks),
  7393. };
  7394. cpumask_and(cpus, sched_domain_span(sd), cpu_active_mask);
  7395. schedstat_inc(sd->lb_count[idle]);
  7396. redo:
  7397. if (!should_we_balance(&env)) {
  7398. *continue_balancing = 0;
  7399. goto out_balanced;
  7400. }
  7401. group = find_busiest_group(&env);
  7402. if (!group) {
  7403. schedstat_inc(sd->lb_nobusyg[idle]);
  7404. goto out_balanced;
  7405. }
  7406. busiest = find_busiest_queue(&env, group);
  7407. if (!busiest) {
  7408. schedstat_inc(sd->lb_nobusyq[idle]);
  7409. goto out_balanced;
  7410. }
  7411. BUG_ON(busiest == env.dst_rq);
  7412. schedstat_add(sd->lb_imbalance[idle], env.imbalance);
  7413. env.src_cpu = busiest->cpu;
  7414. env.src_rq = busiest;
  7415. ld_moved = 0;
  7416. if (busiest->nr_running > 1) {
  7417. /*
  7418. * Attempt to move tasks. If find_busiest_group has found
  7419. * an imbalance but busiest->nr_running <= 1, the group is
  7420. * still unbalanced. ld_moved simply stays zero, so it is
  7421. * correctly treated as an imbalance.
  7422. */
  7423. env.flags |= LBF_ALL_PINNED;
  7424. env.loop_max = min(sysctl_sched_nr_migrate, busiest->nr_running);
  7425. more_balance:
  7426. rq_lock_irqsave(busiest, &rf);
  7427. update_rq_clock(busiest);
  7428. /*
  7429. * cur_ld_moved - load moved in current iteration
  7430. * ld_moved - cumulative load moved across iterations
  7431. */
  7432. cur_ld_moved = detach_tasks(&env);
  7433. /*
  7434. * We've detached some tasks from busiest_rq. Every
  7435. * task is masked "TASK_ON_RQ_MIGRATING", so we can safely
  7436. * unlock busiest->lock, and we are able to be sure
  7437. * that nobody can manipulate the tasks in parallel.
  7438. * See task_rq_lock() family for the details.
  7439. */
  7440. rq_unlock(busiest, &rf);
  7441. if (cur_ld_moved) {
  7442. attach_tasks(&env);
  7443. ld_moved += cur_ld_moved;
  7444. }
  7445. local_irq_restore(rf.flags);
  7446. if (env.flags & LBF_NEED_BREAK) {
  7447. env.flags &= ~LBF_NEED_BREAK;
  7448. goto more_balance;
  7449. }
  7450. /*
  7451. * Revisit (affine) tasks on src_cpu that couldn't be moved to
  7452. * us and move them to an alternate dst_cpu in our sched_group
  7453. * where they can run. The upper limit on how many times we
  7454. * iterate on same src_cpu is dependent on number of CPUs in our
  7455. * sched_group.
  7456. *
  7457. * This changes load balance semantics a bit on who can move
  7458. * load to a given_cpu. In addition to the given_cpu itself
  7459. * (or a ilb_cpu acting on its behalf where given_cpu is
  7460. * nohz-idle), we now have balance_cpu in a position to move
  7461. * load to given_cpu. In rare situations, this may cause
  7462. * conflicts (balance_cpu and given_cpu/ilb_cpu deciding
  7463. * _independently_ and at _same_ time to move some load to
  7464. * given_cpu) causing exceess load to be moved to given_cpu.
  7465. * This however should not happen so much in practice and
  7466. * moreover subsequent load balance cycles should correct the
  7467. * excess load moved.
  7468. */
  7469. if ((env.flags & LBF_DST_PINNED) && env.imbalance > 0) {
  7470. /* Prevent to re-select dst_cpu via env's CPUs */
  7471. cpumask_clear_cpu(env.dst_cpu, env.cpus);
  7472. env.dst_rq = cpu_rq(env.new_dst_cpu);
  7473. env.dst_cpu = env.new_dst_cpu;
  7474. env.flags &= ~LBF_DST_PINNED;
  7475. env.loop = 0;
  7476. env.loop_break = sched_nr_migrate_break;
  7477. /*
  7478. * Go back to "more_balance" rather than "redo" since we
  7479. * need to continue with same src_cpu.
  7480. */
  7481. goto more_balance;
  7482. }
  7483. /*
  7484. * We failed to reach balance because of affinity.
  7485. */
  7486. if (sd_parent) {
  7487. int *group_imbalance = &sd_parent->groups->sgc->imbalance;
  7488. if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0)
  7489. *group_imbalance = 1;
  7490. }
  7491. /* All tasks on this runqueue were pinned by CPU affinity */
  7492. if (unlikely(env.flags & LBF_ALL_PINNED)) {
  7493. cpumask_clear_cpu(cpu_of(busiest), cpus);
  7494. /*
  7495. * Attempting to continue load balancing at the current
  7496. * sched_domain level only makes sense if there are
  7497. * active CPUs remaining as possible busiest CPUs to
  7498. * pull load from which are not contained within the
  7499. * destination group that is receiving any migrated
  7500. * load.
  7501. */
  7502. if (!cpumask_subset(cpus, env.dst_grpmask)) {
  7503. env.loop = 0;
  7504. env.loop_break = sched_nr_migrate_break;
  7505. goto redo;
  7506. }
  7507. goto out_all_pinned;
  7508. }
  7509. }
  7510. if (!ld_moved) {
  7511. schedstat_inc(sd->lb_failed[idle]);
  7512. /*
  7513. * Increment the failure counter only on periodic balance.
  7514. * We do not want newidle balance, which can be very
  7515. * frequent, pollute the failure counter causing
  7516. * excessive cache_hot migrations and active balances.
  7517. */
  7518. if (idle != CPU_NEWLY_IDLE)
  7519. sd->nr_balance_failed++;
  7520. if (need_active_balance(&env)) {
  7521. unsigned long flags;
  7522. raw_spin_lock_irqsave(&busiest->lock, flags);
  7523. /*
  7524. * Don't kick the active_load_balance_cpu_stop,
  7525. * if the curr task on busiest CPU can't be
  7526. * moved to this_cpu:
  7527. */
  7528. if (!cpumask_test_cpu(this_cpu, &busiest->curr->cpus_allowed)) {
  7529. raw_spin_unlock_irqrestore(&busiest->lock,
  7530. flags);
  7531. env.flags |= LBF_ALL_PINNED;
  7532. goto out_one_pinned;
  7533. }
  7534. /*
  7535. * ->active_balance synchronizes accesses to
  7536. * ->active_balance_work. Once set, it's cleared
  7537. * only after active load balance is finished.
  7538. */
  7539. if (!busiest->active_balance) {
  7540. busiest->active_balance = 1;
  7541. busiest->push_cpu = this_cpu;
  7542. active_balance = 1;
  7543. }
  7544. raw_spin_unlock_irqrestore(&busiest->lock, flags);
  7545. if (active_balance) {
  7546. stop_one_cpu_nowait(cpu_of(busiest),
  7547. active_load_balance_cpu_stop, busiest,
  7548. &busiest->active_balance_work);
  7549. }
  7550. /* We've kicked active balancing, force task migration. */
  7551. sd->nr_balance_failed = sd->cache_nice_tries+1;
  7552. }
  7553. } else
  7554. sd->nr_balance_failed = 0;
  7555. if (likely(!active_balance)) {
  7556. /* We were unbalanced, so reset the balancing interval */
  7557. sd->balance_interval = sd->min_interval;
  7558. } else {
  7559. /*
  7560. * If we've begun active balancing, start to back off. This
  7561. * case may not be covered by the all_pinned logic if there
  7562. * is only 1 task on the busy runqueue (because we don't call
  7563. * detach_tasks).
  7564. */
  7565. if (sd->balance_interval < sd->max_interval)
  7566. sd->balance_interval *= 2;
  7567. }
  7568. goto out;
  7569. out_balanced:
  7570. /*
  7571. * We reach balance although we may have faced some affinity
  7572. * constraints. Clear the imbalance flag if it was set.
  7573. */
  7574. if (sd_parent) {
  7575. int *group_imbalance = &sd_parent->groups->sgc->imbalance;
  7576. if (*group_imbalance)
  7577. *group_imbalance = 0;
  7578. }
  7579. out_all_pinned:
  7580. /*
  7581. * We reach balance because all tasks are pinned at this level so
  7582. * we can't migrate them. Let the imbalance flag set so parent level
  7583. * can try to migrate them.
  7584. */
  7585. schedstat_inc(sd->lb_balanced[idle]);
  7586. sd->nr_balance_failed = 0;
  7587. out_one_pinned:
  7588. /* tune up the balancing interval */
  7589. if (((env.flags & LBF_ALL_PINNED) &&
  7590. sd->balance_interval < MAX_PINNED_INTERVAL) ||
  7591. (sd->balance_interval < sd->max_interval))
  7592. sd->balance_interval *= 2;
  7593. ld_moved = 0;
  7594. out:
  7595. return ld_moved;
  7596. }
  7597. static inline unsigned long
  7598. get_sd_balance_interval(struct sched_domain *sd, int cpu_busy)
  7599. {
  7600. unsigned long interval = sd->balance_interval;
  7601. if (cpu_busy)
  7602. interval *= sd->busy_factor;
  7603. /* scale ms to jiffies */
  7604. interval = msecs_to_jiffies(interval);
  7605. interval = clamp(interval, 1UL, max_load_balance_interval);
  7606. return interval;
  7607. }
  7608. static inline void
  7609. update_next_balance(struct sched_domain *sd, unsigned long *next_balance)
  7610. {
  7611. unsigned long interval, next;
  7612. /* used by idle balance, so cpu_busy = 0 */
  7613. interval = get_sd_balance_interval(sd, 0);
  7614. next = sd->last_balance + interval;
  7615. if (time_after(*next_balance, next))
  7616. *next_balance = next;
  7617. }
  7618. /*
  7619. * active_load_balance_cpu_stop is run by the CPU stopper. It pushes
  7620. * running tasks off the busiest CPU onto idle CPUs. It requires at
  7621. * least 1 task to be running on each physical CPU where possible, and
  7622. * avoids physical / logical imbalances.
  7623. */
  7624. static int active_load_balance_cpu_stop(void *data)
  7625. {
  7626. struct rq *busiest_rq = data;
  7627. int busiest_cpu = cpu_of(busiest_rq);
  7628. int target_cpu = busiest_rq->push_cpu;
  7629. struct rq *target_rq = cpu_rq(target_cpu);
  7630. struct sched_domain *sd;
  7631. struct task_struct *p = NULL;
  7632. struct rq_flags rf;
  7633. rq_lock_irq(busiest_rq, &rf);
  7634. /*
  7635. * Between queueing the stop-work and running it is a hole in which
  7636. * CPUs can become inactive. We should not move tasks from or to
  7637. * inactive CPUs.
  7638. */
  7639. if (!cpu_active(busiest_cpu) || !cpu_active(target_cpu))
  7640. goto out_unlock;
  7641. /* Make sure the requested CPU hasn't gone down in the meantime: */
  7642. if (unlikely(busiest_cpu != smp_processor_id() ||
  7643. !busiest_rq->active_balance))
  7644. goto out_unlock;
  7645. /* Is there any task to move? */
  7646. if (busiest_rq->nr_running <= 1)
  7647. goto out_unlock;
  7648. /*
  7649. * This condition is "impossible", if it occurs
  7650. * we need to fix it. Originally reported by
  7651. * Bjorn Helgaas on a 128-CPU setup.
  7652. */
  7653. BUG_ON(busiest_rq == target_rq);
  7654. /* Search for an sd spanning us and the target CPU. */
  7655. rcu_read_lock();
  7656. for_each_domain(target_cpu, sd) {
  7657. if ((sd->flags & SD_LOAD_BALANCE) &&
  7658. cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
  7659. break;
  7660. }
  7661. if (likely(sd)) {
  7662. struct lb_env env = {
  7663. .sd = sd,
  7664. .dst_cpu = target_cpu,
  7665. .dst_rq = target_rq,
  7666. .src_cpu = busiest_rq->cpu,
  7667. .src_rq = busiest_rq,
  7668. .idle = CPU_IDLE,
  7669. /*
  7670. * can_migrate_task() doesn't need to compute new_dst_cpu
  7671. * for active balancing. Since we have CPU_IDLE, but no
  7672. * @dst_grpmask we need to make that test go away with lying
  7673. * about DST_PINNED.
  7674. */
  7675. .flags = LBF_DST_PINNED,
  7676. };
  7677. schedstat_inc(sd->alb_count);
  7678. update_rq_clock(busiest_rq);
  7679. p = detach_one_task(&env);
  7680. if (p) {
  7681. schedstat_inc(sd->alb_pushed);
  7682. /* Active balancing done, reset the failure counter. */
  7683. sd->nr_balance_failed = 0;
  7684. } else {
  7685. schedstat_inc(sd->alb_failed);
  7686. }
  7687. }
  7688. rcu_read_unlock();
  7689. out_unlock:
  7690. busiest_rq->active_balance = 0;
  7691. rq_unlock(busiest_rq, &rf);
  7692. if (p)
  7693. attach_one_task(target_rq, p);
  7694. local_irq_enable();
  7695. return 0;
  7696. }
  7697. static DEFINE_SPINLOCK(balancing);
  7698. /*
  7699. * Scale the max load_balance interval with the number of CPUs in the system.
  7700. * This trades load-balance latency on larger machines for less cross talk.
  7701. */
  7702. void update_max_interval(void)
  7703. {
  7704. max_load_balance_interval = HZ*num_online_cpus()/10;
  7705. }
  7706. /*
  7707. * It checks each scheduling domain to see if it is due to be balanced,
  7708. * and initiates a balancing operation if so.
  7709. *
  7710. * Balancing parameters are set up in init_sched_domains.
  7711. */
  7712. static void rebalance_domains(struct rq *rq, enum cpu_idle_type idle)
  7713. {
  7714. int continue_balancing = 1;
  7715. int cpu = rq->cpu;
  7716. unsigned long interval;
  7717. struct sched_domain *sd;
  7718. /* Earliest time when we have to do rebalance again */
  7719. unsigned long next_balance = jiffies + 60*HZ;
  7720. int update_next_balance = 0;
  7721. int need_serialize, need_decay = 0;
  7722. u64 max_cost = 0;
  7723. rcu_read_lock();
  7724. for_each_domain(cpu, sd) {
  7725. /*
  7726. * Decay the newidle max times here because this is a regular
  7727. * visit to all the domains. Decay ~1% per second.
  7728. */
  7729. if (time_after(jiffies, sd->next_decay_max_lb_cost)) {
  7730. sd->max_newidle_lb_cost =
  7731. (sd->max_newidle_lb_cost * 253) / 256;
  7732. sd->next_decay_max_lb_cost = jiffies + HZ;
  7733. need_decay = 1;
  7734. }
  7735. max_cost += sd->max_newidle_lb_cost;
  7736. if (!(sd->flags & SD_LOAD_BALANCE))
  7737. continue;
  7738. /*
  7739. * Stop the load balance at this level. There is another
  7740. * CPU in our sched group which is doing load balancing more
  7741. * actively.
  7742. */
  7743. if (!continue_balancing) {
  7744. if (need_decay)
  7745. continue;
  7746. break;
  7747. }
  7748. interval = get_sd_balance_interval(sd, idle != CPU_IDLE);
  7749. need_serialize = sd->flags & SD_SERIALIZE;
  7750. if (need_serialize) {
  7751. if (!spin_trylock(&balancing))
  7752. goto out;
  7753. }
  7754. if (time_after_eq(jiffies, sd->last_balance + interval)) {
  7755. if (load_balance(cpu, rq, sd, idle, &continue_balancing)) {
  7756. /*
  7757. * The LBF_DST_PINNED logic could have changed
  7758. * env->dst_cpu, so we can't know our idle
  7759. * state even if we migrated tasks. Update it.
  7760. */
  7761. idle = idle_cpu(cpu) ? CPU_IDLE : CPU_NOT_IDLE;
  7762. }
  7763. sd->last_balance = jiffies;
  7764. interval = get_sd_balance_interval(sd, idle != CPU_IDLE);
  7765. }
  7766. if (need_serialize)
  7767. spin_unlock(&balancing);
  7768. out:
  7769. if (time_after(next_balance, sd->last_balance + interval)) {
  7770. next_balance = sd->last_balance + interval;
  7771. update_next_balance = 1;
  7772. }
  7773. }
  7774. if (need_decay) {
  7775. /*
  7776. * Ensure the rq-wide value also decays but keep it at a
  7777. * reasonable floor to avoid funnies with rq->avg_idle.
  7778. */
  7779. rq->max_idle_balance_cost =
  7780. max((u64)sysctl_sched_migration_cost, max_cost);
  7781. }
  7782. rcu_read_unlock();
  7783. /*
  7784. * next_balance will be updated only when there is a need.
  7785. * When the cpu is attached to null domain for ex, it will not be
  7786. * updated.
  7787. */
  7788. if (likely(update_next_balance)) {
  7789. rq->next_balance = next_balance;
  7790. #ifdef CONFIG_NO_HZ_COMMON
  7791. /*
  7792. * If this CPU has been elected to perform the nohz idle
  7793. * balance. Other idle CPUs have already rebalanced with
  7794. * nohz_idle_balance() and nohz.next_balance has been
  7795. * updated accordingly. This CPU is now running the idle load
  7796. * balance for itself and we need to update the
  7797. * nohz.next_balance accordingly.
  7798. */
  7799. if ((idle == CPU_IDLE) && time_after(nohz.next_balance, rq->next_balance))
  7800. nohz.next_balance = rq->next_balance;
  7801. #endif
  7802. }
  7803. }
  7804. static inline int on_null_domain(struct rq *rq)
  7805. {
  7806. return unlikely(!rcu_dereference_sched(rq->sd));
  7807. }
  7808. #ifdef CONFIG_NO_HZ_COMMON
  7809. /*
  7810. * idle load balancing details
  7811. * - When one of the busy CPUs notice that there may be an idle rebalancing
  7812. * needed, they will kick the idle load balancer, which then does idle
  7813. * load balancing for all the idle CPUs.
  7814. */
  7815. static inline int find_new_ilb(void)
  7816. {
  7817. int ilb = cpumask_first(nohz.idle_cpus_mask);
  7818. if (ilb < nr_cpu_ids && idle_cpu(ilb))
  7819. return ilb;
  7820. return nr_cpu_ids;
  7821. }
  7822. /*
  7823. * Kick a CPU to do the nohz balancing, if it is time for it. We pick the
  7824. * nohz_load_balancer CPU (if there is one) otherwise fallback to any idle
  7825. * CPU (if there is one).
  7826. */
  7827. static void kick_ilb(unsigned int flags)
  7828. {
  7829. int ilb_cpu;
  7830. nohz.next_balance++;
  7831. ilb_cpu = find_new_ilb();
  7832. if (ilb_cpu >= nr_cpu_ids)
  7833. return;
  7834. flags = atomic_fetch_or(flags, nohz_flags(ilb_cpu));
  7835. if (flags & NOHZ_KICK_MASK)
  7836. return;
  7837. /*
  7838. * Use smp_send_reschedule() instead of resched_cpu().
  7839. * This way we generate a sched IPI on the target CPU which
  7840. * is idle. And the softirq performing nohz idle load balance
  7841. * will be run before returning from the IPI.
  7842. */
  7843. smp_send_reschedule(ilb_cpu);
  7844. }
  7845. /*
  7846. * Current heuristic for kicking the idle load balancer in the presence
  7847. * of an idle cpu in the system.
  7848. * - This rq has more than one task.
  7849. * - This rq has at least one CFS task and the capacity of the CPU is
  7850. * significantly reduced because of RT tasks or IRQs.
  7851. * - At parent of LLC scheduler domain level, this cpu's scheduler group has
  7852. * multiple busy cpu.
  7853. * - For SD_ASYM_PACKING, if the lower numbered cpu's in the scheduler
  7854. * domain span are idle.
  7855. */
  7856. static void nohz_balancer_kick(struct rq *rq)
  7857. {
  7858. unsigned long now = jiffies;
  7859. struct sched_domain_shared *sds;
  7860. struct sched_domain *sd;
  7861. int nr_busy, i, cpu = rq->cpu;
  7862. unsigned int flags = 0;
  7863. if (unlikely(rq->idle_balance))
  7864. return;
  7865. /*
  7866. * We may be recently in ticked or tickless idle mode. At the first
  7867. * busy tick after returning from idle, we will update the busy stats.
  7868. */
  7869. nohz_balance_exit_idle(rq);
  7870. /*
  7871. * None are in tickless mode and hence no need for NOHZ idle load
  7872. * balancing.
  7873. */
  7874. if (likely(!atomic_read(&nohz.nr_cpus)))
  7875. return;
  7876. if (READ_ONCE(nohz.has_blocked) &&
  7877. time_after(now, READ_ONCE(nohz.next_blocked)))
  7878. flags = NOHZ_STATS_KICK;
  7879. if (time_before(now, nohz.next_balance))
  7880. goto out;
  7881. if (rq->nr_running >= 2) {
  7882. flags = NOHZ_KICK_MASK;
  7883. goto out;
  7884. }
  7885. rcu_read_lock();
  7886. sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
  7887. if (sds) {
  7888. /*
  7889. * XXX: write a coherent comment on why we do this.
  7890. * See also: http://lkml.kernel.org/r/20111202010832.602203411@sbsiddha-desk.sc.intel.com
  7891. */
  7892. nr_busy = atomic_read(&sds->nr_busy_cpus);
  7893. if (nr_busy > 1) {
  7894. flags = NOHZ_KICK_MASK;
  7895. goto unlock;
  7896. }
  7897. }
  7898. sd = rcu_dereference(rq->sd);
  7899. if (sd) {
  7900. if ((rq->cfs.h_nr_running >= 1) &&
  7901. check_cpu_capacity(rq, sd)) {
  7902. flags = NOHZ_KICK_MASK;
  7903. goto unlock;
  7904. }
  7905. }
  7906. sd = rcu_dereference(per_cpu(sd_asym, cpu));
  7907. if (sd) {
  7908. for_each_cpu(i, sched_domain_span(sd)) {
  7909. if (i == cpu ||
  7910. !cpumask_test_cpu(i, nohz.idle_cpus_mask))
  7911. continue;
  7912. if (sched_asym_prefer(i, cpu)) {
  7913. flags = NOHZ_KICK_MASK;
  7914. goto unlock;
  7915. }
  7916. }
  7917. }
  7918. unlock:
  7919. rcu_read_unlock();
  7920. out:
  7921. if (flags)
  7922. kick_ilb(flags);
  7923. }
  7924. static void set_cpu_sd_state_busy(int cpu)
  7925. {
  7926. struct sched_domain *sd;
  7927. rcu_read_lock();
  7928. sd = rcu_dereference(per_cpu(sd_llc, cpu));
  7929. if (!sd || !sd->nohz_idle)
  7930. goto unlock;
  7931. sd->nohz_idle = 0;
  7932. atomic_inc(&sd->shared->nr_busy_cpus);
  7933. unlock:
  7934. rcu_read_unlock();
  7935. }
  7936. void nohz_balance_exit_idle(struct rq *rq)
  7937. {
  7938. SCHED_WARN_ON(rq != this_rq());
  7939. if (likely(!rq->nohz_tick_stopped))
  7940. return;
  7941. rq->nohz_tick_stopped = 0;
  7942. cpumask_clear_cpu(rq->cpu, nohz.idle_cpus_mask);
  7943. atomic_dec(&nohz.nr_cpus);
  7944. set_cpu_sd_state_busy(rq->cpu);
  7945. }
  7946. static void set_cpu_sd_state_idle(int cpu)
  7947. {
  7948. struct sched_domain *sd;
  7949. rcu_read_lock();
  7950. sd = rcu_dereference(per_cpu(sd_llc, cpu));
  7951. if (!sd || sd->nohz_idle)
  7952. goto unlock;
  7953. sd->nohz_idle = 1;
  7954. atomic_dec(&sd->shared->nr_busy_cpus);
  7955. unlock:
  7956. rcu_read_unlock();
  7957. }
  7958. /*
  7959. * This routine will record that the CPU is going idle with tick stopped.
  7960. * This info will be used in performing idle load balancing in the future.
  7961. */
  7962. void nohz_balance_enter_idle(int cpu)
  7963. {
  7964. struct rq *rq = cpu_rq(cpu);
  7965. SCHED_WARN_ON(cpu != smp_processor_id());
  7966. /* If this CPU is going down, then nothing needs to be done: */
  7967. if (!cpu_active(cpu))
  7968. return;
  7969. /* Spare idle load balancing on CPUs that don't want to be disturbed: */
  7970. if (!housekeeping_cpu(cpu, HK_FLAG_SCHED))
  7971. return;
  7972. /*
  7973. * Can be set safely without rq->lock held
  7974. * If a clear happens, it will have evaluated last additions because
  7975. * rq->lock is held during the check and the clear
  7976. */
  7977. rq->has_blocked_load = 1;
  7978. /*
  7979. * The tick is still stopped but load could have been added in the
  7980. * meantime. We set the nohz.has_blocked flag to trig a check of the
  7981. * *_avg. The CPU is already part of nohz.idle_cpus_mask so the clear
  7982. * of nohz.has_blocked can only happen after checking the new load
  7983. */
  7984. if (rq->nohz_tick_stopped)
  7985. goto out;
  7986. /* If we're a completely isolated CPU, we don't play: */
  7987. if (on_null_domain(rq))
  7988. return;
  7989. rq->nohz_tick_stopped = 1;
  7990. cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
  7991. atomic_inc(&nohz.nr_cpus);
  7992. /*
  7993. * Ensures that if nohz_idle_balance() fails to observe our
  7994. * @idle_cpus_mask store, it must observe the @has_blocked
  7995. * store.
  7996. */
  7997. smp_mb__after_atomic();
  7998. set_cpu_sd_state_idle(cpu);
  7999. out:
  8000. /*
  8001. * Each time a cpu enter idle, we assume that it has blocked load and
  8002. * enable the periodic update of the load of idle cpus
  8003. */
  8004. WRITE_ONCE(nohz.has_blocked, 1);
  8005. }
  8006. /*
  8007. * Internal function that runs load balance for all idle cpus. The load balance
  8008. * can be a simple update of blocked load or a complete load balance with
  8009. * tasks movement depending of flags.
  8010. * The function returns false if the loop has stopped before running
  8011. * through all idle CPUs.
  8012. */
  8013. static bool _nohz_idle_balance(struct rq *this_rq, unsigned int flags,
  8014. enum cpu_idle_type idle)
  8015. {
  8016. /* Earliest time when we have to do rebalance again */
  8017. unsigned long now = jiffies;
  8018. unsigned long next_balance = now + 60*HZ;
  8019. bool has_blocked_load = false;
  8020. int update_next_balance = 0;
  8021. int this_cpu = this_rq->cpu;
  8022. int balance_cpu;
  8023. int ret = false;
  8024. struct rq *rq;
  8025. SCHED_WARN_ON((flags & NOHZ_KICK_MASK) == NOHZ_BALANCE_KICK);
  8026. /*
  8027. * We assume there will be no idle load after this update and clear
  8028. * the has_blocked flag. If a cpu enters idle in the mean time, it will
  8029. * set the has_blocked flag and trig another update of idle load.
  8030. * Because a cpu that becomes idle, is added to idle_cpus_mask before
  8031. * setting the flag, we are sure to not clear the state and not
  8032. * check the load of an idle cpu.
  8033. */
  8034. WRITE_ONCE(nohz.has_blocked, 0);
  8035. /*
  8036. * Ensures that if we miss the CPU, we must see the has_blocked
  8037. * store from nohz_balance_enter_idle().
  8038. */
  8039. smp_mb();
  8040. for_each_cpu(balance_cpu, nohz.idle_cpus_mask) {
  8041. if (balance_cpu == this_cpu || !idle_cpu(balance_cpu))
  8042. continue;
  8043. /*
  8044. * If this CPU gets work to do, stop the load balancing
  8045. * work being done for other CPUs. Next load
  8046. * balancing owner will pick it up.
  8047. */
  8048. if (need_resched()) {
  8049. has_blocked_load = true;
  8050. goto abort;
  8051. }
  8052. rq = cpu_rq(balance_cpu);
  8053. has_blocked_load |= update_nohz_stats(rq, true);
  8054. /*
  8055. * If time for next balance is due,
  8056. * do the balance.
  8057. */
  8058. if (time_after_eq(jiffies, rq->next_balance)) {
  8059. struct rq_flags rf;
  8060. rq_lock_irqsave(rq, &rf);
  8061. update_rq_clock(rq);
  8062. cpu_load_update_idle(rq);
  8063. rq_unlock_irqrestore(rq, &rf);
  8064. if (flags & NOHZ_BALANCE_KICK)
  8065. rebalance_domains(rq, CPU_IDLE);
  8066. }
  8067. if (time_after(next_balance, rq->next_balance)) {
  8068. next_balance = rq->next_balance;
  8069. update_next_balance = 1;
  8070. }
  8071. }
  8072. /* Newly idle CPU doesn't need an update */
  8073. if (idle != CPU_NEWLY_IDLE) {
  8074. update_blocked_averages(this_cpu);
  8075. has_blocked_load |= this_rq->has_blocked_load;
  8076. }
  8077. if (flags & NOHZ_BALANCE_KICK)
  8078. rebalance_domains(this_rq, CPU_IDLE);
  8079. WRITE_ONCE(nohz.next_blocked,
  8080. now + msecs_to_jiffies(LOAD_AVG_PERIOD));
  8081. /* The full idle balance loop has been done */
  8082. ret = true;
  8083. abort:
  8084. /* There is still blocked load, enable periodic update */
  8085. if (has_blocked_load)
  8086. WRITE_ONCE(nohz.has_blocked, 1);
  8087. /*
  8088. * next_balance will be updated only when there is a need.
  8089. * When the CPU is attached to null domain for ex, it will not be
  8090. * updated.
  8091. */
  8092. if (likely(update_next_balance))
  8093. nohz.next_balance = next_balance;
  8094. return ret;
  8095. }
  8096. /*
  8097. * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the
  8098. * rebalancing for all the cpus for whom scheduler ticks are stopped.
  8099. */
  8100. static bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
  8101. {
  8102. int this_cpu = this_rq->cpu;
  8103. unsigned int flags;
  8104. if (!(atomic_read(nohz_flags(this_cpu)) & NOHZ_KICK_MASK))
  8105. return false;
  8106. if (idle != CPU_IDLE) {
  8107. atomic_andnot(NOHZ_KICK_MASK, nohz_flags(this_cpu));
  8108. return false;
  8109. }
  8110. /*
  8111. * barrier, pairs with nohz_balance_enter_idle(), ensures ...
  8112. */
  8113. flags = atomic_fetch_andnot(NOHZ_KICK_MASK, nohz_flags(this_cpu));
  8114. if (!(flags & NOHZ_KICK_MASK))
  8115. return false;
  8116. _nohz_idle_balance(this_rq, flags, idle);
  8117. return true;
  8118. }
  8119. static void nohz_newidle_balance(struct rq *this_rq)
  8120. {
  8121. int this_cpu = this_rq->cpu;
  8122. /*
  8123. * This CPU doesn't want to be disturbed by scheduler
  8124. * housekeeping
  8125. */
  8126. if (!housekeeping_cpu(this_cpu, HK_FLAG_SCHED))
  8127. return;
  8128. /* Will wake up very soon. No time for doing anything else*/
  8129. if (this_rq->avg_idle < sysctl_sched_migration_cost)
  8130. return;
  8131. /* Don't need to update blocked load of idle CPUs*/
  8132. if (!READ_ONCE(nohz.has_blocked) ||
  8133. time_before(jiffies, READ_ONCE(nohz.next_blocked)))
  8134. return;
  8135. raw_spin_unlock(&this_rq->lock);
  8136. /*
  8137. * This CPU is going to be idle and blocked load of idle CPUs
  8138. * need to be updated. Run the ilb locally as it is a good
  8139. * candidate for ilb instead of waking up another idle CPU.
  8140. * Kick an normal ilb if we failed to do the update.
  8141. */
  8142. if (!_nohz_idle_balance(this_rq, NOHZ_STATS_KICK, CPU_NEWLY_IDLE))
  8143. kick_ilb(NOHZ_STATS_KICK);
  8144. raw_spin_lock(&this_rq->lock);
  8145. }
  8146. #else /* !CONFIG_NO_HZ_COMMON */
  8147. static inline void nohz_balancer_kick(struct rq *rq) { }
  8148. static inline bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
  8149. {
  8150. return false;
  8151. }
  8152. static inline void nohz_newidle_balance(struct rq *this_rq) { }
  8153. #endif /* CONFIG_NO_HZ_COMMON */
  8154. /*
  8155. * idle_balance is called by schedule() if this_cpu is about to become
  8156. * idle. Attempts to pull tasks from other CPUs.
  8157. */
  8158. static int idle_balance(struct rq *this_rq, struct rq_flags *rf)
  8159. {
  8160. unsigned long next_balance = jiffies + HZ;
  8161. int this_cpu = this_rq->cpu;
  8162. struct sched_domain *sd;
  8163. int pulled_task = 0;
  8164. u64 curr_cost = 0;
  8165. /*
  8166. * We must set idle_stamp _before_ calling idle_balance(), such that we
  8167. * measure the duration of idle_balance() as idle time.
  8168. */
  8169. this_rq->idle_stamp = rq_clock(this_rq);
  8170. /*
  8171. * Do not pull tasks towards !active CPUs...
  8172. */
  8173. if (!cpu_active(this_cpu))
  8174. return 0;
  8175. /*
  8176. * This is OK, because current is on_cpu, which avoids it being picked
  8177. * for load-balance and preemption/IRQs are still disabled avoiding
  8178. * further scheduler activity on it and we're being very careful to
  8179. * re-start the picking loop.
  8180. */
  8181. rq_unpin_lock(this_rq, rf);
  8182. if (this_rq->avg_idle < sysctl_sched_migration_cost ||
  8183. !this_rq->rd->overload) {
  8184. rcu_read_lock();
  8185. sd = rcu_dereference_check_sched_domain(this_rq->sd);
  8186. if (sd)
  8187. update_next_balance(sd, &next_balance);
  8188. rcu_read_unlock();
  8189. nohz_newidle_balance(this_rq);
  8190. goto out;
  8191. }
  8192. raw_spin_unlock(&this_rq->lock);
  8193. update_blocked_averages(this_cpu);
  8194. rcu_read_lock();
  8195. for_each_domain(this_cpu, sd) {
  8196. int continue_balancing = 1;
  8197. u64 t0, domain_cost;
  8198. if (!(sd->flags & SD_LOAD_BALANCE))
  8199. continue;
  8200. if (this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost) {
  8201. update_next_balance(sd, &next_balance);
  8202. break;
  8203. }
  8204. if (sd->flags & SD_BALANCE_NEWIDLE) {
  8205. t0 = sched_clock_cpu(this_cpu);
  8206. pulled_task = load_balance(this_cpu, this_rq,
  8207. sd, CPU_NEWLY_IDLE,
  8208. &continue_balancing);
  8209. domain_cost = sched_clock_cpu(this_cpu) - t0;
  8210. if (domain_cost > sd->max_newidle_lb_cost)
  8211. sd->max_newidle_lb_cost = domain_cost;
  8212. curr_cost += domain_cost;
  8213. }
  8214. update_next_balance(sd, &next_balance);
  8215. /*
  8216. * Stop searching for tasks to pull if there are
  8217. * now runnable tasks on this rq.
  8218. */
  8219. if (pulled_task || this_rq->nr_running > 0)
  8220. break;
  8221. }
  8222. rcu_read_unlock();
  8223. raw_spin_lock(&this_rq->lock);
  8224. if (curr_cost > this_rq->max_idle_balance_cost)
  8225. this_rq->max_idle_balance_cost = curr_cost;
  8226. out:
  8227. /*
  8228. * While browsing the domains, we released the rq lock, a task could
  8229. * have been enqueued in the meantime. Since we're not going idle,
  8230. * pretend we pulled a task.
  8231. */
  8232. if (this_rq->cfs.h_nr_running && !pulled_task)
  8233. pulled_task = 1;
  8234. /* Move the next balance forward */
  8235. if (time_after(this_rq->next_balance, next_balance))
  8236. this_rq->next_balance = next_balance;
  8237. /* Is there a task of a high priority class? */
  8238. if (this_rq->nr_running != this_rq->cfs.h_nr_running)
  8239. pulled_task = -1;
  8240. if (pulled_task)
  8241. this_rq->idle_stamp = 0;
  8242. rq_repin_lock(this_rq, rf);
  8243. return pulled_task;
  8244. }
  8245. /*
  8246. * run_rebalance_domains is triggered when needed from the scheduler tick.
  8247. * Also triggered for nohz idle balancing (with nohz_balancing_kick set).
  8248. */
  8249. static __latent_entropy void run_rebalance_domains(struct softirq_action *h)
  8250. {
  8251. struct rq *this_rq = this_rq();
  8252. enum cpu_idle_type idle = this_rq->idle_balance ?
  8253. CPU_IDLE : CPU_NOT_IDLE;
  8254. /*
  8255. * If this CPU has a pending nohz_balance_kick, then do the
  8256. * balancing on behalf of the other idle CPUs whose ticks are
  8257. * stopped. Do nohz_idle_balance *before* rebalance_domains to
  8258. * give the idle CPUs a chance to load balance. Else we may
  8259. * load balance only within the local sched_domain hierarchy
  8260. * and abort nohz_idle_balance altogether if we pull some load.
  8261. */
  8262. if (nohz_idle_balance(this_rq, idle))
  8263. return;
  8264. /* normal load balance */
  8265. update_blocked_averages(this_rq->cpu);
  8266. rebalance_domains(this_rq, idle);
  8267. }
  8268. /*
  8269. * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
  8270. */
  8271. void trigger_load_balance(struct rq *rq)
  8272. {
  8273. /* Don't need to rebalance while attached to NULL domain */
  8274. if (unlikely(on_null_domain(rq)))
  8275. return;
  8276. if (time_after_eq(jiffies, rq->next_balance))
  8277. raise_softirq(SCHED_SOFTIRQ);
  8278. nohz_balancer_kick(rq);
  8279. }
  8280. static void rq_online_fair(struct rq *rq)
  8281. {
  8282. update_sysctl();
  8283. update_runtime_enabled(rq);
  8284. }
  8285. static void rq_offline_fair(struct rq *rq)
  8286. {
  8287. update_sysctl();
  8288. /* Ensure any throttled groups are reachable by pick_next_task */
  8289. unthrottle_offline_cfs_rqs(rq);
  8290. }
  8291. #endif /* CONFIG_SMP */
  8292. /*
  8293. * scheduler tick hitting a task of our scheduling class.
  8294. *
  8295. * NOTE: This function can be called remotely by the tick offload that
  8296. * goes along full dynticks. Therefore no local assumption can be made
  8297. * and everything must be accessed through the @rq and @curr passed in
  8298. * parameters.
  8299. */
  8300. static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)
  8301. {
  8302. struct cfs_rq *cfs_rq;
  8303. struct sched_entity *se = &curr->se;
  8304. for_each_sched_entity(se) {
  8305. cfs_rq = cfs_rq_of(se);
  8306. entity_tick(cfs_rq, se, queued);
  8307. }
  8308. if (static_branch_unlikely(&sched_numa_balancing))
  8309. task_tick_numa(rq, curr);
  8310. }
  8311. /*
  8312. * called on fork with the child task as argument from the parent's context
  8313. * - child not yet on the tasklist
  8314. * - preemption disabled
  8315. */
  8316. static void task_fork_fair(struct task_struct *p)
  8317. {
  8318. struct cfs_rq *cfs_rq;
  8319. struct sched_entity *se = &p->se, *curr;
  8320. struct rq *rq = this_rq();
  8321. struct rq_flags rf;
  8322. rq_lock(rq, &rf);
  8323. update_rq_clock(rq);
  8324. cfs_rq = task_cfs_rq(current);
  8325. curr = cfs_rq->curr;
  8326. if (curr) {
  8327. update_curr(cfs_rq);
  8328. se->vruntime = curr->vruntime;
  8329. }
  8330. place_entity(cfs_rq, se, 1);
  8331. if (sysctl_sched_child_runs_first && curr && entity_before(curr, se)) {
  8332. /*
  8333. * Upon rescheduling, sched_class::put_prev_task() will place
  8334. * 'current' within the tree based on its new key value.
  8335. */
  8336. swap(curr->vruntime, se->vruntime);
  8337. resched_curr(rq);
  8338. }
  8339. se->vruntime -= cfs_rq->min_vruntime;
  8340. rq_unlock(rq, &rf);
  8341. }
  8342. /*
  8343. * Priority of the task has changed. Check to see if we preempt
  8344. * the current task.
  8345. */
  8346. static void
  8347. prio_changed_fair(struct rq *rq, struct task_struct *p, int oldprio)
  8348. {
  8349. if (!task_on_rq_queued(p))
  8350. return;
  8351. /*
  8352. * Reschedule if we are currently running on this runqueue and
  8353. * our priority decreased, or if we are not currently running on
  8354. * this runqueue and our priority is higher than the current's
  8355. */
  8356. if (rq->curr == p) {
  8357. if (p->prio > oldprio)
  8358. resched_curr(rq);
  8359. } else
  8360. check_preempt_curr(rq, p, 0);
  8361. }
  8362. static inline bool vruntime_normalized(struct task_struct *p)
  8363. {
  8364. struct sched_entity *se = &p->se;
  8365. /*
  8366. * In both the TASK_ON_RQ_QUEUED and TASK_ON_RQ_MIGRATING cases,
  8367. * the dequeue_entity(.flags=0) will already have normalized the
  8368. * vruntime.
  8369. */
  8370. if (p->on_rq)
  8371. return true;
  8372. /*
  8373. * When !on_rq, vruntime of the task has usually NOT been normalized.
  8374. * But there are some cases where it has already been normalized:
  8375. *
  8376. * - A forked child which is waiting for being woken up by
  8377. * wake_up_new_task().
  8378. * - A task which has been woken up by try_to_wake_up() and
  8379. * waiting for actually being woken up by sched_ttwu_pending().
  8380. */
  8381. if (!se->sum_exec_runtime || p->state == TASK_WAKING)
  8382. return true;
  8383. return false;
  8384. }
  8385. #ifdef CONFIG_FAIR_GROUP_SCHED
  8386. /*
  8387. * Propagate the changes of the sched_entity across the tg tree to make it
  8388. * visible to the root
  8389. */
  8390. static void propagate_entity_cfs_rq(struct sched_entity *se)
  8391. {
  8392. struct cfs_rq *cfs_rq;
  8393. /* Start to propagate at parent */
  8394. se = se->parent;
  8395. for_each_sched_entity(se) {
  8396. cfs_rq = cfs_rq_of(se);
  8397. if (cfs_rq_throttled(cfs_rq))
  8398. break;
  8399. update_load_avg(cfs_rq, se, UPDATE_TG);
  8400. }
  8401. }
  8402. #else
  8403. static void propagate_entity_cfs_rq(struct sched_entity *se) { }
  8404. #endif
  8405. static void detach_entity_cfs_rq(struct sched_entity *se)
  8406. {
  8407. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  8408. /* Catch up with the cfs_rq and remove our load when we leave */
  8409. update_load_avg(cfs_rq, se, 0);
  8410. detach_entity_load_avg(cfs_rq, se);
  8411. update_tg_load_avg(cfs_rq, false);
  8412. propagate_entity_cfs_rq(se);
  8413. }
  8414. static void attach_entity_cfs_rq(struct sched_entity *se)
  8415. {
  8416. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  8417. #ifdef CONFIG_FAIR_GROUP_SCHED
  8418. /*
  8419. * Since the real-depth could have been changed (only FAIR
  8420. * class maintain depth value), reset depth properly.
  8421. */
  8422. se->depth = se->parent ? se->parent->depth + 1 : 0;
  8423. #endif
  8424. /* Synchronize entity with its cfs_rq */
  8425. update_load_avg(cfs_rq, se, sched_feat(ATTACH_AGE_LOAD) ? 0 : SKIP_AGE_LOAD);
  8426. attach_entity_load_avg(cfs_rq, se, 0);
  8427. update_tg_load_avg(cfs_rq, false);
  8428. propagate_entity_cfs_rq(se);
  8429. }
  8430. static void detach_task_cfs_rq(struct task_struct *p)
  8431. {
  8432. struct sched_entity *se = &p->se;
  8433. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  8434. if (!vruntime_normalized(p)) {
  8435. /*
  8436. * Fix up our vruntime so that the current sleep doesn't
  8437. * cause 'unlimited' sleep bonus.
  8438. */
  8439. place_entity(cfs_rq, se, 0);
  8440. se->vruntime -= cfs_rq->min_vruntime;
  8441. }
  8442. detach_entity_cfs_rq(se);
  8443. }
  8444. static void attach_task_cfs_rq(struct task_struct *p)
  8445. {
  8446. struct sched_entity *se = &p->se;
  8447. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  8448. attach_entity_cfs_rq(se);
  8449. if (!vruntime_normalized(p))
  8450. se->vruntime += cfs_rq->min_vruntime;
  8451. }
  8452. static void switched_from_fair(struct rq *rq, struct task_struct *p)
  8453. {
  8454. detach_task_cfs_rq(p);
  8455. }
  8456. static void switched_to_fair(struct rq *rq, struct task_struct *p)
  8457. {
  8458. attach_task_cfs_rq(p);
  8459. if (task_on_rq_queued(p)) {
  8460. /*
  8461. * We were most likely switched from sched_rt, so
  8462. * kick off the schedule if running, otherwise just see
  8463. * if we can still preempt the current task.
  8464. */
  8465. if (rq->curr == p)
  8466. resched_curr(rq);
  8467. else
  8468. check_preempt_curr(rq, p, 0);
  8469. }
  8470. }
  8471. /* Account for a task changing its policy or group.
  8472. *
  8473. * This routine is mostly called to set cfs_rq->curr field when a task
  8474. * migrates between groups/classes.
  8475. */
  8476. static void set_curr_task_fair(struct rq *rq)
  8477. {
  8478. struct sched_entity *se = &rq->curr->se;
  8479. for_each_sched_entity(se) {
  8480. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  8481. set_next_entity(cfs_rq, se);
  8482. /* ensure bandwidth has been allocated on our new cfs_rq */
  8483. account_cfs_rq_runtime(cfs_rq, 0);
  8484. }
  8485. }
  8486. void init_cfs_rq(struct cfs_rq *cfs_rq)
  8487. {
  8488. cfs_rq->tasks_timeline = RB_ROOT_CACHED;
  8489. cfs_rq->min_vruntime = (u64)(-(1LL << 20));
  8490. #ifndef CONFIG_64BIT
  8491. cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
  8492. #endif
  8493. #ifdef CONFIG_SMP
  8494. raw_spin_lock_init(&cfs_rq->removed.lock);
  8495. #endif
  8496. }
  8497. #ifdef CONFIG_FAIR_GROUP_SCHED
  8498. static void task_set_group_fair(struct task_struct *p)
  8499. {
  8500. struct sched_entity *se = &p->se;
  8501. set_task_rq(p, task_cpu(p));
  8502. se->depth = se->parent ? se->parent->depth + 1 : 0;
  8503. }
  8504. static void task_move_group_fair(struct task_struct *p)
  8505. {
  8506. detach_task_cfs_rq(p);
  8507. set_task_rq(p, task_cpu(p));
  8508. #ifdef CONFIG_SMP
  8509. /* Tell se's cfs_rq has been changed -- migrated */
  8510. p->se.avg.last_update_time = 0;
  8511. #endif
  8512. attach_task_cfs_rq(p);
  8513. }
  8514. static void task_change_group_fair(struct task_struct *p, int type)
  8515. {
  8516. switch (type) {
  8517. case TASK_SET_GROUP:
  8518. task_set_group_fair(p);
  8519. break;
  8520. case TASK_MOVE_GROUP:
  8521. task_move_group_fair(p);
  8522. break;
  8523. }
  8524. }
  8525. void free_fair_sched_group(struct task_group *tg)
  8526. {
  8527. int i;
  8528. destroy_cfs_bandwidth(tg_cfs_bandwidth(tg));
  8529. for_each_possible_cpu(i) {
  8530. if (tg->cfs_rq)
  8531. kfree(tg->cfs_rq[i]);
  8532. if (tg->se)
  8533. kfree(tg->se[i]);
  8534. }
  8535. kfree(tg->cfs_rq);
  8536. kfree(tg->se);
  8537. }
  8538. int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
  8539. {
  8540. struct sched_entity *se;
  8541. struct cfs_rq *cfs_rq;
  8542. int i;
  8543. tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL);
  8544. if (!tg->cfs_rq)
  8545. goto err;
  8546. tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL);
  8547. if (!tg->se)
  8548. goto err;
  8549. tg->shares = NICE_0_LOAD;
  8550. init_cfs_bandwidth(tg_cfs_bandwidth(tg));
  8551. for_each_possible_cpu(i) {
  8552. cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
  8553. GFP_KERNEL, cpu_to_node(i));
  8554. if (!cfs_rq)
  8555. goto err;
  8556. se = kzalloc_node(sizeof(struct sched_entity),
  8557. GFP_KERNEL, cpu_to_node(i));
  8558. if (!se)
  8559. goto err_free_rq;
  8560. init_cfs_rq(cfs_rq);
  8561. init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
  8562. init_entity_runnable_average(se);
  8563. }
  8564. return 1;
  8565. err_free_rq:
  8566. kfree(cfs_rq);
  8567. err:
  8568. return 0;
  8569. }
  8570. void online_fair_sched_group(struct task_group *tg)
  8571. {
  8572. struct sched_entity *se;
  8573. struct rq *rq;
  8574. int i;
  8575. for_each_possible_cpu(i) {
  8576. rq = cpu_rq(i);
  8577. se = tg->se[i];
  8578. raw_spin_lock_irq(&rq->lock);
  8579. update_rq_clock(rq);
  8580. attach_entity_cfs_rq(se);
  8581. sync_throttle(tg, i);
  8582. raw_spin_unlock_irq(&rq->lock);
  8583. }
  8584. }
  8585. void unregister_fair_sched_group(struct task_group *tg)
  8586. {
  8587. unsigned long flags;
  8588. struct rq *rq;
  8589. int cpu;
  8590. for_each_possible_cpu(cpu) {
  8591. if (tg->se[cpu])
  8592. remove_entity_load_avg(tg->se[cpu]);
  8593. /*
  8594. * Only empty task groups can be destroyed; so we can speculatively
  8595. * check on_list without danger of it being re-added.
  8596. */
  8597. if (!tg->cfs_rq[cpu]->on_list)
  8598. continue;
  8599. rq = cpu_rq(cpu);
  8600. raw_spin_lock_irqsave(&rq->lock, flags);
  8601. list_del_leaf_cfs_rq(tg->cfs_rq[cpu]);
  8602. raw_spin_unlock_irqrestore(&rq->lock, flags);
  8603. }
  8604. }
  8605. void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
  8606. struct sched_entity *se, int cpu,
  8607. struct sched_entity *parent)
  8608. {
  8609. struct rq *rq = cpu_rq(cpu);
  8610. cfs_rq->tg = tg;
  8611. cfs_rq->rq = rq;
  8612. init_cfs_rq_runtime(cfs_rq);
  8613. tg->cfs_rq[cpu] = cfs_rq;
  8614. tg->se[cpu] = se;
  8615. /* se could be NULL for root_task_group */
  8616. if (!se)
  8617. return;
  8618. if (!parent) {
  8619. se->cfs_rq = &rq->cfs;
  8620. se->depth = 0;
  8621. } else {
  8622. se->cfs_rq = parent->my_q;
  8623. se->depth = parent->depth + 1;
  8624. }
  8625. se->my_q = cfs_rq;
  8626. /* guarantee group entities always have weight */
  8627. update_load_set(&se->load, NICE_0_LOAD);
  8628. se->parent = parent;
  8629. }
  8630. static DEFINE_MUTEX(shares_mutex);
  8631. int sched_group_set_shares(struct task_group *tg, unsigned long shares)
  8632. {
  8633. int i;
  8634. /*
  8635. * We can't change the weight of the root cgroup.
  8636. */
  8637. if (!tg->se[0])
  8638. return -EINVAL;
  8639. shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
  8640. mutex_lock(&shares_mutex);
  8641. if (tg->shares == shares)
  8642. goto done;
  8643. tg->shares = shares;
  8644. for_each_possible_cpu(i) {
  8645. struct rq *rq = cpu_rq(i);
  8646. struct sched_entity *se = tg->se[i];
  8647. struct rq_flags rf;
  8648. /* Propagate contribution to hierarchy */
  8649. rq_lock_irqsave(rq, &rf);
  8650. update_rq_clock(rq);
  8651. for_each_sched_entity(se) {
  8652. update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
  8653. update_cfs_group(se);
  8654. }
  8655. rq_unlock_irqrestore(rq, &rf);
  8656. }
  8657. done:
  8658. mutex_unlock(&shares_mutex);
  8659. return 0;
  8660. }
  8661. #else /* CONFIG_FAIR_GROUP_SCHED */
  8662. void free_fair_sched_group(struct task_group *tg) { }
  8663. int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
  8664. {
  8665. return 1;
  8666. }
  8667. void online_fair_sched_group(struct task_group *tg) { }
  8668. void unregister_fair_sched_group(struct task_group *tg) { }
  8669. #endif /* CONFIG_FAIR_GROUP_SCHED */
  8670. static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task)
  8671. {
  8672. struct sched_entity *se = &task->se;
  8673. unsigned int rr_interval = 0;
  8674. /*
  8675. * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
  8676. * idle runqueue:
  8677. */
  8678. if (rq->cfs.load.weight)
  8679. rr_interval = NS_TO_JIFFIES(sched_slice(cfs_rq_of(se), se));
  8680. return rr_interval;
  8681. }
  8682. /*
  8683. * All the scheduling class methods:
  8684. */
  8685. const struct sched_class fair_sched_class = {
  8686. .next = &idle_sched_class,
  8687. .enqueue_task = enqueue_task_fair,
  8688. .dequeue_task = dequeue_task_fair,
  8689. .yield_task = yield_task_fair,
  8690. .yield_to_task = yield_to_task_fair,
  8691. .check_preempt_curr = check_preempt_wakeup,
  8692. .pick_next_task = pick_next_task_fair,
  8693. .put_prev_task = put_prev_task_fair,
  8694. #ifdef CONFIG_SMP
  8695. .select_task_rq = select_task_rq_fair,
  8696. .migrate_task_rq = migrate_task_rq_fair,
  8697. .rq_online = rq_online_fair,
  8698. .rq_offline = rq_offline_fair,
  8699. .task_dead = task_dead_fair,
  8700. .set_cpus_allowed = set_cpus_allowed_common,
  8701. #endif
  8702. .set_curr_task = set_curr_task_fair,
  8703. .task_tick = task_tick_fair,
  8704. .task_fork = task_fork_fair,
  8705. .prio_changed = prio_changed_fair,
  8706. .switched_from = switched_from_fair,
  8707. .switched_to = switched_to_fair,
  8708. .get_rr_interval = get_rr_interval_fair,
  8709. .update_curr = update_curr_fair,
  8710. #ifdef CONFIG_FAIR_GROUP_SCHED
  8711. .task_change_group = task_change_group_fair,
  8712. #endif
  8713. };
  8714. #ifdef CONFIG_SCHED_DEBUG
  8715. void print_cfs_stats(struct seq_file *m, int cpu)
  8716. {
  8717. struct cfs_rq *cfs_rq, *pos;
  8718. rcu_read_lock();
  8719. for_each_leaf_cfs_rq_safe(cpu_rq(cpu), cfs_rq, pos)
  8720. print_cfs_rq(m, cpu, cfs_rq);
  8721. rcu_read_unlock();
  8722. }
  8723. #ifdef CONFIG_NUMA_BALANCING
  8724. void show_numa_stats(struct task_struct *p, struct seq_file *m)
  8725. {
  8726. int node;
  8727. unsigned long tsf = 0, tpf = 0, gsf = 0, gpf = 0;
  8728. for_each_online_node(node) {
  8729. if (p->numa_faults) {
  8730. tsf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 0)];
  8731. tpf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 1)];
  8732. }
  8733. if (p->numa_group) {
  8734. gsf = p->numa_group->faults[task_faults_idx(NUMA_MEM, node, 0)],
  8735. gpf = p->numa_group->faults[task_faults_idx(NUMA_MEM, node, 1)];
  8736. }
  8737. print_numa_stats(m, node, tsf, tpf, gsf, gpf);
  8738. }
  8739. }
  8740. #endif /* CONFIG_NUMA_BALANCING */
  8741. #endif /* CONFIG_SCHED_DEBUG */
  8742. __init void init_sched_fair_class(void)
  8743. {
  8744. #ifdef CONFIG_SMP
  8745. open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
  8746. #ifdef CONFIG_NO_HZ_COMMON
  8747. nohz.next_balance = jiffies;
  8748. nohz.next_blocked = jiffies;
  8749. zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);
  8750. #endif
  8751. #endif /* SMP */
  8752. }