fair.c 291 KB

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