fair.c 260 KB

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