fair.c 229 KB

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