fair.c 275 KB

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