fair.c 272 KB

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