fair.c 228 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749
  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. /* Group cfs_rq's load_avg is used for task_h_load and update_cfs_share */
  2452. static inline int
  2453. update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq, bool update_freq)
  2454. {
  2455. struct sched_avg *sa = &cfs_rq->avg;
  2456. int decayed, removed_load = 0, removed_util = 0;
  2457. if (atomic_long_read(&cfs_rq->removed_load_avg)) {
  2458. s64 r = atomic_long_xchg(&cfs_rq->removed_load_avg, 0);
  2459. sa->load_avg = max_t(long, sa->load_avg - r, 0);
  2460. sa->load_sum = max_t(s64, sa->load_sum - r * LOAD_AVG_MAX, 0);
  2461. removed_load = 1;
  2462. }
  2463. if (atomic_long_read(&cfs_rq->removed_util_avg)) {
  2464. long r = atomic_long_xchg(&cfs_rq->removed_util_avg, 0);
  2465. sa->util_avg = max_t(long, sa->util_avg - r, 0);
  2466. sa->util_sum = max_t(s32, sa->util_sum - r * LOAD_AVG_MAX, 0);
  2467. removed_util = 1;
  2468. }
  2469. decayed = __update_load_avg(now, cpu_of(rq_of(cfs_rq)), sa,
  2470. scale_load_down(cfs_rq->load.weight), cfs_rq->curr != NULL, cfs_rq);
  2471. #ifndef CONFIG_64BIT
  2472. smp_wmb();
  2473. cfs_rq->load_last_update_time_copy = sa->last_update_time;
  2474. #endif
  2475. if (update_freq && (decayed || removed_util))
  2476. cfs_rq_util_change(cfs_rq);
  2477. return decayed || removed_load;
  2478. }
  2479. /* Update task and its cfs_rq load average */
  2480. static inline void update_load_avg(struct sched_entity *se, int update_tg)
  2481. {
  2482. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  2483. u64 now = cfs_rq_clock_task(cfs_rq);
  2484. struct rq *rq = rq_of(cfs_rq);
  2485. int cpu = cpu_of(rq);
  2486. /*
  2487. * Track task load average for carrying it to new CPU after migrated, and
  2488. * track group sched_entity load average for task_h_load calc in migration
  2489. */
  2490. __update_load_avg(now, cpu, &se->avg,
  2491. se->on_rq * scale_load_down(se->load.weight),
  2492. cfs_rq->curr == se, NULL);
  2493. if (update_cfs_rq_load_avg(now, cfs_rq, true) && update_tg)
  2494. update_tg_load_avg(cfs_rq, 0);
  2495. }
  2496. static void attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
  2497. {
  2498. if (!sched_feat(ATTACH_AGE_LOAD))
  2499. goto skip_aging;
  2500. /*
  2501. * If we got migrated (either between CPUs or between cgroups) we'll
  2502. * have aged the average right before clearing @last_update_time.
  2503. */
  2504. if (se->avg.last_update_time) {
  2505. __update_load_avg(cfs_rq->avg.last_update_time, cpu_of(rq_of(cfs_rq)),
  2506. &se->avg, 0, 0, NULL);
  2507. /*
  2508. * XXX: we could have just aged the entire load away if we've been
  2509. * absent from the fair class for too long.
  2510. */
  2511. }
  2512. skip_aging:
  2513. se->avg.last_update_time = cfs_rq->avg.last_update_time;
  2514. cfs_rq->avg.load_avg += se->avg.load_avg;
  2515. cfs_rq->avg.load_sum += se->avg.load_sum;
  2516. cfs_rq->avg.util_avg += se->avg.util_avg;
  2517. cfs_rq->avg.util_sum += se->avg.util_sum;
  2518. cfs_rq_util_change(cfs_rq);
  2519. }
  2520. static void detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
  2521. {
  2522. __update_load_avg(cfs_rq->avg.last_update_time, cpu_of(rq_of(cfs_rq)),
  2523. &se->avg, se->on_rq * scale_load_down(se->load.weight),
  2524. cfs_rq->curr == se, NULL);
  2525. cfs_rq->avg.load_avg = max_t(long, cfs_rq->avg.load_avg - se->avg.load_avg, 0);
  2526. cfs_rq->avg.load_sum = max_t(s64, cfs_rq->avg.load_sum - se->avg.load_sum, 0);
  2527. cfs_rq->avg.util_avg = max_t(long, cfs_rq->avg.util_avg - se->avg.util_avg, 0);
  2528. cfs_rq->avg.util_sum = max_t(s32, cfs_rq->avg.util_sum - se->avg.util_sum, 0);
  2529. cfs_rq_util_change(cfs_rq);
  2530. }
  2531. /* Add the load generated by se into cfs_rq's load average */
  2532. static inline void
  2533. enqueue_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
  2534. {
  2535. struct sched_avg *sa = &se->avg;
  2536. u64 now = cfs_rq_clock_task(cfs_rq);
  2537. int migrated, decayed;
  2538. migrated = !sa->last_update_time;
  2539. if (!migrated) {
  2540. __update_load_avg(now, cpu_of(rq_of(cfs_rq)), sa,
  2541. se->on_rq * scale_load_down(se->load.weight),
  2542. cfs_rq->curr == se, NULL);
  2543. }
  2544. decayed = update_cfs_rq_load_avg(now, cfs_rq, !migrated);
  2545. cfs_rq->runnable_load_avg += sa->load_avg;
  2546. cfs_rq->runnable_load_sum += sa->load_sum;
  2547. if (migrated)
  2548. attach_entity_load_avg(cfs_rq, se);
  2549. if (decayed || migrated)
  2550. update_tg_load_avg(cfs_rq, 0);
  2551. }
  2552. /* Remove the runnable load generated by se from cfs_rq's runnable load average */
  2553. static inline void
  2554. dequeue_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
  2555. {
  2556. update_load_avg(se, 1);
  2557. cfs_rq->runnable_load_avg =
  2558. max_t(long, cfs_rq->runnable_load_avg - se->avg.load_avg, 0);
  2559. cfs_rq->runnable_load_sum =
  2560. max_t(s64, cfs_rq->runnable_load_sum - se->avg.load_sum, 0);
  2561. }
  2562. #ifndef CONFIG_64BIT
  2563. static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq)
  2564. {
  2565. u64 last_update_time_copy;
  2566. u64 last_update_time;
  2567. do {
  2568. last_update_time_copy = cfs_rq->load_last_update_time_copy;
  2569. smp_rmb();
  2570. last_update_time = cfs_rq->avg.last_update_time;
  2571. } while (last_update_time != last_update_time_copy);
  2572. return last_update_time;
  2573. }
  2574. #else
  2575. static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq)
  2576. {
  2577. return cfs_rq->avg.last_update_time;
  2578. }
  2579. #endif
  2580. /*
  2581. * Task first catches up with cfs_rq, and then subtract
  2582. * itself from the cfs_rq (task must be off the queue now).
  2583. */
  2584. void remove_entity_load_avg(struct sched_entity *se)
  2585. {
  2586. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  2587. u64 last_update_time;
  2588. /*
  2589. * Newly created task or never used group entity should not be removed
  2590. * from its (source) cfs_rq
  2591. */
  2592. if (se->avg.last_update_time == 0)
  2593. return;
  2594. last_update_time = cfs_rq_last_update_time(cfs_rq);
  2595. __update_load_avg(last_update_time, cpu_of(rq_of(cfs_rq)), &se->avg, 0, 0, NULL);
  2596. atomic_long_add(se->avg.load_avg, &cfs_rq->removed_load_avg);
  2597. atomic_long_add(se->avg.util_avg, &cfs_rq->removed_util_avg);
  2598. }
  2599. static inline unsigned long cfs_rq_runnable_load_avg(struct cfs_rq *cfs_rq)
  2600. {
  2601. return cfs_rq->runnable_load_avg;
  2602. }
  2603. static inline unsigned long cfs_rq_load_avg(struct cfs_rq *cfs_rq)
  2604. {
  2605. return cfs_rq->avg.load_avg;
  2606. }
  2607. static int idle_balance(struct rq *this_rq);
  2608. #else /* CONFIG_SMP */
  2609. static inline void update_load_avg(struct sched_entity *se, int not_used)
  2610. {
  2611. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  2612. struct rq *rq = rq_of(cfs_rq);
  2613. cpufreq_trigger_update(rq_clock(rq));
  2614. }
  2615. static inline void
  2616. enqueue_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
  2617. static inline void
  2618. dequeue_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
  2619. static inline void remove_entity_load_avg(struct sched_entity *se) {}
  2620. static inline void
  2621. attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
  2622. static inline void
  2623. detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
  2624. static inline int idle_balance(struct rq *rq)
  2625. {
  2626. return 0;
  2627. }
  2628. #endif /* CONFIG_SMP */
  2629. static void enqueue_sleeper(struct cfs_rq *cfs_rq, struct sched_entity *se)
  2630. {
  2631. #ifdef CONFIG_SCHEDSTATS
  2632. struct task_struct *tsk = NULL;
  2633. if (entity_is_task(se))
  2634. tsk = task_of(se);
  2635. if (se->statistics.sleep_start) {
  2636. u64 delta = rq_clock(rq_of(cfs_rq)) - se->statistics.sleep_start;
  2637. if ((s64)delta < 0)
  2638. delta = 0;
  2639. if (unlikely(delta > se->statistics.sleep_max))
  2640. se->statistics.sleep_max = delta;
  2641. se->statistics.sleep_start = 0;
  2642. se->statistics.sum_sleep_runtime += delta;
  2643. if (tsk) {
  2644. account_scheduler_latency(tsk, delta >> 10, 1);
  2645. trace_sched_stat_sleep(tsk, delta);
  2646. }
  2647. }
  2648. if (se->statistics.block_start) {
  2649. u64 delta = rq_clock(rq_of(cfs_rq)) - se->statistics.block_start;
  2650. if ((s64)delta < 0)
  2651. delta = 0;
  2652. if (unlikely(delta > se->statistics.block_max))
  2653. se->statistics.block_max = delta;
  2654. se->statistics.block_start = 0;
  2655. se->statistics.sum_sleep_runtime += delta;
  2656. if (tsk) {
  2657. if (tsk->in_iowait) {
  2658. se->statistics.iowait_sum += delta;
  2659. se->statistics.iowait_count++;
  2660. trace_sched_stat_iowait(tsk, delta);
  2661. }
  2662. trace_sched_stat_blocked(tsk, delta);
  2663. /*
  2664. * Blocking time is in units of nanosecs, so shift by
  2665. * 20 to get a milliseconds-range estimation of the
  2666. * amount of time that the task spent sleeping:
  2667. */
  2668. if (unlikely(prof_on == SLEEP_PROFILING)) {
  2669. profile_hits(SLEEP_PROFILING,
  2670. (void *)get_wchan(tsk),
  2671. delta >> 20);
  2672. }
  2673. account_scheduler_latency(tsk, delta >> 10, 0);
  2674. }
  2675. }
  2676. #endif
  2677. }
  2678. static void check_spread(struct cfs_rq *cfs_rq, struct sched_entity *se)
  2679. {
  2680. #ifdef CONFIG_SCHED_DEBUG
  2681. s64 d = se->vruntime - cfs_rq->min_vruntime;
  2682. if (d < 0)
  2683. d = -d;
  2684. if (d > 3*sysctl_sched_latency)
  2685. schedstat_inc(cfs_rq, nr_spread_over);
  2686. #endif
  2687. }
  2688. static void
  2689. place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int initial)
  2690. {
  2691. u64 vruntime = cfs_rq->min_vruntime;
  2692. /*
  2693. * The 'current' period is already promised to the current tasks,
  2694. * however the extra weight of the new task will slow them down a
  2695. * little, place the new task so that it fits in the slot that
  2696. * stays open at the end.
  2697. */
  2698. if (initial && sched_feat(START_DEBIT))
  2699. vruntime += sched_vslice(cfs_rq, se);
  2700. /* sleeps up to a single latency don't count. */
  2701. if (!initial) {
  2702. unsigned long thresh = sysctl_sched_latency;
  2703. /*
  2704. * Halve their sleep time's effect, to allow
  2705. * for a gentler effect of sleepers:
  2706. */
  2707. if (sched_feat(GENTLE_FAIR_SLEEPERS))
  2708. thresh >>= 1;
  2709. vruntime -= thresh;
  2710. }
  2711. /* ensure we never gain time by being placed backwards. */
  2712. se->vruntime = max_vruntime(se->vruntime, vruntime);
  2713. }
  2714. static void check_enqueue_throttle(struct cfs_rq *cfs_rq);
  2715. static inline void check_schedstat_required(void)
  2716. {
  2717. #ifdef CONFIG_SCHEDSTATS
  2718. if (schedstat_enabled())
  2719. return;
  2720. /* Force schedstat enabled if a dependent tracepoint is active */
  2721. if (trace_sched_stat_wait_enabled() ||
  2722. trace_sched_stat_sleep_enabled() ||
  2723. trace_sched_stat_iowait_enabled() ||
  2724. trace_sched_stat_blocked_enabled() ||
  2725. trace_sched_stat_runtime_enabled()) {
  2726. pr_warn_once("Scheduler tracepoints stat_sleep, stat_iowait, "
  2727. "stat_blocked and stat_runtime require the "
  2728. "kernel parameter schedstats=enabled or "
  2729. "kernel.sched_schedstats=1\n");
  2730. }
  2731. #endif
  2732. }
  2733. /*
  2734. * MIGRATION
  2735. *
  2736. * dequeue
  2737. * update_curr()
  2738. * update_min_vruntime()
  2739. * vruntime -= min_vruntime
  2740. *
  2741. * enqueue
  2742. * update_curr()
  2743. * update_min_vruntime()
  2744. * vruntime += min_vruntime
  2745. *
  2746. * this way the vruntime transition between RQs is done when both
  2747. * min_vruntime are up-to-date.
  2748. *
  2749. * WAKEUP (remote)
  2750. *
  2751. * ->migrate_task_rq_fair() (p->state == TASK_WAKING)
  2752. * vruntime -= min_vruntime
  2753. *
  2754. * enqueue
  2755. * update_curr()
  2756. * update_min_vruntime()
  2757. * vruntime += min_vruntime
  2758. *
  2759. * this way we don't have the most up-to-date min_vruntime on the originating
  2760. * CPU and an up-to-date min_vruntime on the destination CPU.
  2761. */
  2762. static void
  2763. enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
  2764. {
  2765. bool renorm = !(flags & ENQUEUE_WAKEUP) || (flags & ENQUEUE_MIGRATED);
  2766. bool curr = cfs_rq->curr == se;
  2767. /*
  2768. * If we're the current task, we must renormalise before calling
  2769. * update_curr().
  2770. */
  2771. if (renorm && curr)
  2772. se->vruntime += cfs_rq->min_vruntime;
  2773. update_curr(cfs_rq);
  2774. /*
  2775. * Otherwise, renormalise after, such that we're placed at the current
  2776. * moment in time, instead of some random moment in the past. Being
  2777. * placed in the past could significantly boost this task to the
  2778. * fairness detriment of existing tasks.
  2779. */
  2780. if (renorm && !curr)
  2781. se->vruntime += cfs_rq->min_vruntime;
  2782. enqueue_entity_load_avg(cfs_rq, se);
  2783. account_entity_enqueue(cfs_rq, se);
  2784. update_cfs_shares(cfs_rq);
  2785. if (flags & ENQUEUE_WAKEUP) {
  2786. place_entity(cfs_rq, se, 0);
  2787. if (schedstat_enabled())
  2788. enqueue_sleeper(cfs_rq, se);
  2789. }
  2790. check_schedstat_required();
  2791. if (schedstat_enabled()) {
  2792. update_stats_enqueue(cfs_rq, se);
  2793. check_spread(cfs_rq, se);
  2794. }
  2795. if (!curr)
  2796. __enqueue_entity(cfs_rq, se);
  2797. se->on_rq = 1;
  2798. if (cfs_rq->nr_running == 1) {
  2799. list_add_leaf_cfs_rq(cfs_rq);
  2800. check_enqueue_throttle(cfs_rq);
  2801. }
  2802. }
  2803. static void __clear_buddies_last(struct sched_entity *se)
  2804. {
  2805. for_each_sched_entity(se) {
  2806. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  2807. if (cfs_rq->last != se)
  2808. break;
  2809. cfs_rq->last = NULL;
  2810. }
  2811. }
  2812. static void __clear_buddies_next(struct sched_entity *se)
  2813. {
  2814. for_each_sched_entity(se) {
  2815. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  2816. if (cfs_rq->next != se)
  2817. break;
  2818. cfs_rq->next = NULL;
  2819. }
  2820. }
  2821. static void __clear_buddies_skip(struct sched_entity *se)
  2822. {
  2823. for_each_sched_entity(se) {
  2824. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  2825. if (cfs_rq->skip != se)
  2826. break;
  2827. cfs_rq->skip = NULL;
  2828. }
  2829. }
  2830. static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
  2831. {
  2832. if (cfs_rq->last == se)
  2833. __clear_buddies_last(se);
  2834. if (cfs_rq->next == se)
  2835. __clear_buddies_next(se);
  2836. if (cfs_rq->skip == se)
  2837. __clear_buddies_skip(se);
  2838. }
  2839. static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq);
  2840. static void
  2841. dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
  2842. {
  2843. /*
  2844. * Update run-time statistics of the 'current'.
  2845. */
  2846. update_curr(cfs_rq);
  2847. dequeue_entity_load_avg(cfs_rq, se);
  2848. if (schedstat_enabled())
  2849. update_stats_dequeue(cfs_rq, se, flags);
  2850. clear_buddies(cfs_rq, se);
  2851. if (se != cfs_rq->curr)
  2852. __dequeue_entity(cfs_rq, se);
  2853. se->on_rq = 0;
  2854. account_entity_dequeue(cfs_rq, se);
  2855. /*
  2856. * Normalize the entity after updating the min_vruntime because the
  2857. * update can refer to the ->curr item and we need to reflect this
  2858. * movement in our normalized position.
  2859. */
  2860. if (!(flags & DEQUEUE_SLEEP))
  2861. se->vruntime -= cfs_rq->min_vruntime;
  2862. /* return excess runtime on last dequeue */
  2863. return_cfs_rq_runtime(cfs_rq);
  2864. update_min_vruntime(cfs_rq);
  2865. update_cfs_shares(cfs_rq);
  2866. }
  2867. /*
  2868. * Preempt the current task with a newly woken task if needed:
  2869. */
  2870. static void
  2871. check_preempt_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr)
  2872. {
  2873. unsigned long ideal_runtime, delta_exec;
  2874. struct sched_entity *se;
  2875. s64 delta;
  2876. ideal_runtime = sched_slice(cfs_rq, curr);
  2877. delta_exec = curr->sum_exec_runtime - curr->prev_sum_exec_runtime;
  2878. if (delta_exec > ideal_runtime) {
  2879. resched_curr(rq_of(cfs_rq));
  2880. /*
  2881. * The current task ran long enough, ensure it doesn't get
  2882. * re-elected due to buddy favours.
  2883. */
  2884. clear_buddies(cfs_rq, curr);
  2885. return;
  2886. }
  2887. /*
  2888. * Ensure that a task that missed wakeup preemption by a
  2889. * narrow margin doesn't have to wait for a full slice.
  2890. * This also mitigates buddy induced latencies under load.
  2891. */
  2892. if (delta_exec < sysctl_sched_min_granularity)
  2893. return;
  2894. se = __pick_first_entity(cfs_rq);
  2895. delta = curr->vruntime - se->vruntime;
  2896. if (delta < 0)
  2897. return;
  2898. if (delta > ideal_runtime)
  2899. resched_curr(rq_of(cfs_rq));
  2900. }
  2901. static void
  2902. set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
  2903. {
  2904. /* 'current' is not kept within the tree. */
  2905. if (se->on_rq) {
  2906. /*
  2907. * Any task has to be enqueued before it get to execute on
  2908. * a CPU. So account for the time it spent waiting on the
  2909. * runqueue.
  2910. */
  2911. if (schedstat_enabled())
  2912. update_stats_wait_end(cfs_rq, se);
  2913. __dequeue_entity(cfs_rq, se);
  2914. update_load_avg(se, 1);
  2915. }
  2916. update_stats_curr_start(cfs_rq, se);
  2917. cfs_rq->curr = se;
  2918. #ifdef CONFIG_SCHEDSTATS
  2919. /*
  2920. * Track our maximum slice length, if the CPU's load is at
  2921. * least twice that of our own weight (i.e. dont track it
  2922. * when there are only lesser-weight tasks around):
  2923. */
  2924. if (schedstat_enabled() && rq_of(cfs_rq)->load.weight >= 2*se->load.weight) {
  2925. se->statistics.slice_max = max(se->statistics.slice_max,
  2926. se->sum_exec_runtime - se->prev_sum_exec_runtime);
  2927. }
  2928. #endif
  2929. se->prev_sum_exec_runtime = se->sum_exec_runtime;
  2930. }
  2931. static int
  2932. wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se);
  2933. /*
  2934. * Pick the next process, keeping these things in mind, in this order:
  2935. * 1) keep things fair between processes/task groups
  2936. * 2) pick the "next" process, since someone really wants that to run
  2937. * 3) pick the "last" process, for cache locality
  2938. * 4) do not run the "skip" process, if something else is available
  2939. */
  2940. static struct sched_entity *
  2941. pick_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *curr)
  2942. {
  2943. struct sched_entity *left = __pick_first_entity(cfs_rq);
  2944. struct sched_entity *se;
  2945. /*
  2946. * If curr is set we have to see if its left of the leftmost entity
  2947. * still in the tree, provided there was anything in the tree at all.
  2948. */
  2949. if (!left || (curr && entity_before(curr, left)))
  2950. left = curr;
  2951. se = left; /* ideally we run the leftmost entity */
  2952. /*
  2953. * Avoid running the skip buddy, if running something else can
  2954. * be done without getting too unfair.
  2955. */
  2956. if (cfs_rq->skip == se) {
  2957. struct sched_entity *second;
  2958. if (se == curr) {
  2959. second = __pick_first_entity(cfs_rq);
  2960. } else {
  2961. second = __pick_next_entity(se);
  2962. if (!second || (curr && entity_before(curr, second)))
  2963. second = curr;
  2964. }
  2965. if (second && wakeup_preempt_entity(second, left) < 1)
  2966. se = second;
  2967. }
  2968. /*
  2969. * Prefer last buddy, try to return the CPU to a preempted task.
  2970. */
  2971. if (cfs_rq->last && wakeup_preempt_entity(cfs_rq->last, left) < 1)
  2972. se = cfs_rq->last;
  2973. /*
  2974. * Someone really wants this to run. If it's not unfair, run it.
  2975. */
  2976. if (cfs_rq->next && wakeup_preempt_entity(cfs_rq->next, left) < 1)
  2977. se = cfs_rq->next;
  2978. clear_buddies(cfs_rq, se);
  2979. return se;
  2980. }
  2981. static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq);
  2982. static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
  2983. {
  2984. /*
  2985. * If still on the runqueue then deactivate_task()
  2986. * was not called and update_curr() has to be done:
  2987. */
  2988. if (prev->on_rq)
  2989. update_curr(cfs_rq);
  2990. /* throttle cfs_rqs exceeding runtime */
  2991. check_cfs_rq_runtime(cfs_rq);
  2992. if (schedstat_enabled()) {
  2993. check_spread(cfs_rq, prev);
  2994. if (prev->on_rq)
  2995. update_stats_wait_start(cfs_rq, prev);
  2996. }
  2997. if (prev->on_rq) {
  2998. /* Put 'current' back into the tree. */
  2999. __enqueue_entity(cfs_rq, prev);
  3000. /* in !on_rq case, update occurred at dequeue */
  3001. update_load_avg(prev, 0);
  3002. }
  3003. cfs_rq->curr = NULL;
  3004. }
  3005. static void
  3006. entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
  3007. {
  3008. /*
  3009. * Update run-time statistics of the 'current'.
  3010. */
  3011. update_curr(cfs_rq);
  3012. /*
  3013. * Ensure that runnable average is periodically updated.
  3014. */
  3015. update_load_avg(curr, 1);
  3016. update_cfs_shares(cfs_rq);
  3017. #ifdef CONFIG_SCHED_HRTICK
  3018. /*
  3019. * queued ticks are scheduled to match the slice, so don't bother
  3020. * validating it and just reschedule.
  3021. */
  3022. if (queued) {
  3023. resched_curr(rq_of(cfs_rq));
  3024. return;
  3025. }
  3026. /*
  3027. * don't let the period tick interfere with the hrtick preemption
  3028. */
  3029. if (!sched_feat(DOUBLE_TICK) &&
  3030. hrtimer_active(&rq_of(cfs_rq)->hrtick_timer))
  3031. return;
  3032. #endif
  3033. if (cfs_rq->nr_running > 1)
  3034. check_preempt_tick(cfs_rq, curr);
  3035. }
  3036. /**************************************************
  3037. * CFS bandwidth control machinery
  3038. */
  3039. #ifdef CONFIG_CFS_BANDWIDTH
  3040. #ifdef HAVE_JUMP_LABEL
  3041. static struct static_key __cfs_bandwidth_used;
  3042. static inline bool cfs_bandwidth_used(void)
  3043. {
  3044. return static_key_false(&__cfs_bandwidth_used);
  3045. }
  3046. void cfs_bandwidth_usage_inc(void)
  3047. {
  3048. static_key_slow_inc(&__cfs_bandwidth_used);
  3049. }
  3050. void cfs_bandwidth_usage_dec(void)
  3051. {
  3052. static_key_slow_dec(&__cfs_bandwidth_used);
  3053. }
  3054. #else /* HAVE_JUMP_LABEL */
  3055. static bool cfs_bandwidth_used(void)
  3056. {
  3057. return true;
  3058. }
  3059. void cfs_bandwidth_usage_inc(void) {}
  3060. void cfs_bandwidth_usage_dec(void) {}
  3061. #endif /* HAVE_JUMP_LABEL */
  3062. /*
  3063. * default period for cfs group bandwidth.
  3064. * default: 0.1s, units: nanoseconds
  3065. */
  3066. static inline u64 default_cfs_period(void)
  3067. {
  3068. return 100000000ULL;
  3069. }
  3070. static inline u64 sched_cfs_bandwidth_slice(void)
  3071. {
  3072. return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC;
  3073. }
  3074. /*
  3075. * Replenish runtime according to assigned quota and update expiration time.
  3076. * We use sched_clock_cpu directly instead of rq->clock to avoid adding
  3077. * additional synchronization around rq->lock.
  3078. *
  3079. * requires cfs_b->lock
  3080. */
  3081. void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
  3082. {
  3083. u64 now;
  3084. if (cfs_b->quota == RUNTIME_INF)
  3085. return;
  3086. now = sched_clock_cpu(smp_processor_id());
  3087. cfs_b->runtime = cfs_b->quota;
  3088. cfs_b->runtime_expires = now + ktime_to_ns(cfs_b->period);
  3089. }
  3090. static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
  3091. {
  3092. return &tg->cfs_bandwidth;
  3093. }
  3094. /* rq->task_clock normalized against any time this cfs_rq has spent throttled */
  3095. static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq)
  3096. {
  3097. if (unlikely(cfs_rq->throttle_count))
  3098. return cfs_rq->throttled_clock_task;
  3099. return rq_clock_task(rq_of(cfs_rq)) - cfs_rq->throttled_clock_task_time;
  3100. }
  3101. /* returns 0 on failure to allocate runtime */
  3102. static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  3103. {
  3104. struct task_group *tg = cfs_rq->tg;
  3105. struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(tg);
  3106. u64 amount = 0, min_amount, expires;
  3107. /* note: this is a positive sum as runtime_remaining <= 0 */
  3108. min_amount = sched_cfs_bandwidth_slice() - cfs_rq->runtime_remaining;
  3109. raw_spin_lock(&cfs_b->lock);
  3110. if (cfs_b->quota == RUNTIME_INF)
  3111. amount = min_amount;
  3112. else {
  3113. start_cfs_bandwidth(cfs_b);
  3114. if (cfs_b->runtime > 0) {
  3115. amount = min(cfs_b->runtime, min_amount);
  3116. cfs_b->runtime -= amount;
  3117. cfs_b->idle = 0;
  3118. }
  3119. }
  3120. expires = cfs_b->runtime_expires;
  3121. raw_spin_unlock(&cfs_b->lock);
  3122. cfs_rq->runtime_remaining += amount;
  3123. /*
  3124. * we may have advanced our local expiration to account for allowed
  3125. * spread between our sched_clock and the one on which runtime was
  3126. * issued.
  3127. */
  3128. if ((s64)(expires - cfs_rq->runtime_expires) > 0)
  3129. cfs_rq->runtime_expires = expires;
  3130. return cfs_rq->runtime_remaining > 0;
  3131. }
  3132. /*
  3133. * Note: This depends on the synchronization provided by sched_clock and the
  3134. * fact that rq->clock snapshots this value.
  3135. */
  3136. static void expire_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  3137. {
  3138. struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
  3139. /* if the deadline is ahead of our clock, nothing to do */
  3140. if (likely((s64)(rq_clock(rq_of(cfs_rq)) - cfs_rq->runtime_expires) < 0))
  3141. return;
  3142. if (cfs_rq->runtime_remaining < 0)
  3143. return;
  3144. /*
  3145. * If the local deadline has passed we have to consider the
  3146. * possibility that our sched_clock is 'fast' and the global deadline
  3147. * has not truly expired.
  3148. *
  3149. * Fortunately we can check determine whether this the case by checking
  3150. * whether the global deadline has advanced. It is valid to compare
  3151. * cfs_b->runtime_expires without any locks since we only care about
  3152. * exact equality, so a partial write will still work.
  3153. */
  3154. if (cfs_rq->runtime_expires != cfs_b->runtime_expires) {
  3155. /* extend local deadline, drift is bounded above by 2 ticks */
  3156. cfs_rq->runtime_expires += TICK_NSEC;
  3157. } else {
  3158. /* global deadline is ahead, expiration has passed */
  3159. cfs_rq->runtime_remaining = 0;
  3160. }
  3161. }
  3162. static void __account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
  3163. {
  3164. /* dock delta_exec before expiring quota (as it could span periods) */
  3165. cfs_rq->runtime_remaining -= delta_exec;
  3166. expire_cfs_rq_runtime(cfs_rq);
  3167. if (likely(cfs_rq->runtime_remaining > 0))
  3168. return;
  3169. /*
  3170. * if we're unable to extend our runtime we resched so that the active
  3171. * hierarchy can be throttled
  3172. */
  3173. if (!assign_cfs_rq_runtime(cfs_rq) && likely(cfs_rq->curr))
  3174. resched_curr(rq_of(cfs_rq));
  3175. }
  3176. static __always_inline
  3177. void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
  3178. {
  3179. if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled)
  3180. return;
  3181. __account_cfs_rq_runtime(cfs_rq, delta_exec);
  3182. }
  3183. static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
  3184. {
  3185. return cfs_bandwidth_used() && cfs_rq->throttled;
  3186. }
  3187. /* check whether cfs_rq, or any parent, is throttled */
  3188. static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
  3189. {
  3190. return cfs_bandwidth_used() && cfs_rq->throttle_count;
  3191. }
  3192. /*
  3193. * Ensure that neither of the group entities corresponding to src_cpu or
  3194. * dest_cpu are members of a throttled hierarchy when performing group
  3195. * load-balance operations.
  3196. */
  3197. static inline int throttled_lb_pair(struct task_group *tg,
  3198. int src_cpu, int dest_cpu)
  3199. {
  3200. struct cfs_rq *src_cfs_rq, *dest_cfs_rq;
  3201. src_cfs_rq = tg->cfs_rq[src_cpu];
  3202. dest_cfs_rq = tg->cfs_rq[dest_cpu];
  3203. return throttled_hierarchy(src_cfs_rq) ||
  3204. throttled_hierarchy(dest_cfs_rq);
  3205. }
  3206. /* updated child weight may affect parent so we have to do this bottom up */
  3207. static int tg_unthrottle_up(struct task_group *tg, void *data)
  3208. {
  3209. struct rq *rq = data;
  3210. struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
  3211. cfs_rq->throttle_count--;
  3212. #ifdef CONFIG_SMP
  3213. if (!cfs_rq->throttle_count) {
  3214. /* adjust cfs_rq_clock_task() */
  3215. cfs_rq->throttled_clock_task_time += rq_clock_task(rq) -
  3216. cfs_rq->throttled_clock_task;
  3217. }
  3218. #endif
  3219. return 0;
  3220. }
  3221. static int tg_throttle_down(struct task_group *tg, void *data)
  3222. {
  3223. struct rq *rq = data;
  3224. struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
  3225. /* group is entering throttled state, stop time */
  3226. if (!cfs_rq->throttle_count)
  3227. cfs_rq->throttled_clock_task = rq_clock_task(rq);
  3228. cfs_rq->throttle_count++;
  3229. return 0;
  3230. }
  3231. static void throttle_cfs_rq(struct cfs_rq *cfs_rq)
  3232. {
  3233. struct rq *rq = rq_of(cfs_rq);
  3234. struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
  3235. struct sched_entity *se;
  3236. long task_delta, dequeue = 1;
  3237. bool empty;
  3238. se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))];
  3239. /* freeze hierarchy runnable averages while throttled */
  3240. rcu_read_lock();
  3241. walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq);
  3242. rcu_read_unlock();
  3243. task_delta = cfs_rq->h_nr_running;
  3244. for_each_sched_entity(se) {
  3245. struct cfs_rq *qcfs_rq = cfs_rq_of(se);
  3246. /* throttled entity or throttle-on-deactivate */
  3247. if (!se->on_rq)
  3248. break;
  3249. if (dequeue)
  3250. dequeue_entity(qcfs_rq, se, DEQUEUE_SLEEP);
  3251. qcfs_rq->h_nr_running -= task_delta;
  3252. if (qcfs_rq->load.weight)
  3253. dequeue = 0;
  3254. }
  3255. if (!se)
  3256. sub_nr_running(rq, task_delta);
  3257. cfs_rq->throttled = 1;
  3258. cfs_rq->throttled_clock = rq_clock(rq);
  3259. raw_spin_lock(&cfs_b->lock);
  3260. empty = list_empty(&cfs_b->throttled_cfs_rq);
  3261. /*
  3262. * Add to the _head_ of the list, so that an already-started
  3263. * distribute_cfs_runtime will not see us
  3264. */
  3265. list_add_rcu(&cfs_rq->throttled_list, &cfs_b->throttled_cfs_rq);
  3266. /*
  3267. * If we're the first throttled task, make sure the bandwidth
  3268. * timer is running.
  3269. */
  3270. if (empty)
  3271. start_cfs_bandwidth(cfs_b);
  3272. raw_spin_unlock(&cfs_b->lock);
  3273. }
  3274. void unthrottle_cfs_rq(struct cfs_rq *cfs_rq)
  3275. {
  3276. struct rq *rq = rq_of(cfs_rq);
  3277. struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
  3278. struct sched_entity *se;
  3279. int enqueue = 1;
  3280. long task_delta;
  3281. se = cfs_rq->tg->se[cpu_of(rq)];
  3282. cfs_rq->throttled = 0;
  3283. update_rq_clock(rq);
  3284. raw_spin_lock(&cfs_b->lock);
  3285. cfs_b->throttled_time += rq_clock(rq) - cfs_rq->throttled_clock;
  3286. list_del_rcu(&cfs_rq->throttled_list);
  3287. raw_spin_unlock(&cfs_b->lock);
  3288. /* update hierarchical throttle state */
  3289. walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq);
  3290. if (!cfs_rq->load.weight)
  3291. return;
  3292. task_delta = cfs_rq->h_nr_running;
  3293. for_each_sched_entity(se) {
  3294. if (se->on_rq)
  3295. enqueue = 0;
  3296. cfs_rq = cfs_rq_of(se);
  3297. if (enqueue)
  3298. enqueue_entity(cfs_rq, se, ENQUEUE_WAKEUP);
  3299. cfs_rq->h_nr_running += task_delta;
  3300. if (cfs_rq_throttled(cfs_rq))
  3301. break;
  3302. }
  3303. if (!se)
  3304. add_nr_running(rq, task_delta);
  3305. /* determine whether we need to wake up potentially idle cpu */
  3306. if (rq->curr == rq->idle && rq->cfs.nr_running)
  3307. resched_curr(rq);
  3308. }
  3309. static u64 distribute_cfs_runtime(struct cfs_bandwidth *cfs_b,
  3310. u64 remaining, u64 expires)
  3311. {
  3312. struct cfs_rq *cfs_rq;
  3313. u64 runtime;
  3314. u64 starting_runtime = remaining;
  3315. rcu_read_lock();
  3316. list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
  3317. throttled_list) {
  3318. struct rq *rq = rq_of(cfs_rq);
  3319. raw_spin_lock(&rq->lock);
  3320. if (!cfs_rq_throttled(cfs_rq))
  3321. goto next;
  3322. runtime = -cfs_rq->runtime_remaining + 1;
  3323. if (runtime > remaining)
  3324. runtime = remaining;
  3325. remaining -= runtime;
  3326. cfs_rq->runtime_remaining += runtime;
  3327. cfs_rq->runtime_expires = expires;
  3328. /* we check whether we're throttled above */
  3329. if (cfs_rq->runtime_remaining > 0)
  3330. unthrottle_cfs_rq(cfs_rq);
  3331. next:
  3332. raw_spin_unlock(&rq->lock);
  3333. if (!remaining)
  3334. break;
  3335. }
  3336. rcu_read_unlock();
  3337. return starting_runtime - remaining;
  3338. }
  3339. /*
  3340. * Responsible for refilling a task_group's bandwidth and unthrottling its
  3341. * cfs_rqs as appropriate. If there has been no activity within the last
  3342. * period the timer is deactivated until scheduling resumes; cfs_b->idle is
  3343. * used to track this state.
  3344. */
  3345. static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun)
  3346. {
  3347. u64 runtime, runtime_expires;
  3348. int throttled;
  3349. /* no need to continue the timer with no bandwidth constraint */
  3350. if (cfs_b->quota == RUNTIME_INF)
  3351. goto out_deactivate;
  3352. throttled = !list_empty(&cfs_b->throttled_cfs_rq);
  3353. cfs_b->nr_periods += overrun;
  3354. /*
  3355. * idle depends on !throttled (for the case of a large deficit), and if
  3356. * we're going inactive then everything else can be deferred
  3357. */
  3358. if (cfs_b->idle && !throttled)
  3359. goto out_deactivate;
  3360. __refill_cfs_bandwidth_runtime(cfs_b);
  3361. if (!throttled) {
  3362. /* mark as potentially idle for the upcoming period */
  3363. cfs_b->idle = 1;
  3364. return 0;
  3365. }
  3366. /* account preceding periods in which throttling occurred */
  3367. cfs_b->nr_throttled += overrun;
  3368. runtime_expires = cfs_b->runtime_expires;
  3369. /*
  3370. * This check is repeated as we are holding onto the new bandwidth while
  3371. * we unthrottle. This can potentially race with an unthrottled group
  3372. * trying to acquire new bandwidth from the global pool. This can result
  3373. * in us over-using our runtime if it is all used during this loop, but
  3374. * only by limited amounts in that extreme case.
  3375. */
  3376. while (throttled && cfs_b->runtime > 0) {
  3377. runtime = cfs_b->runtime;
  3378. raw_spin_unlock(&cfs_b->lock);
  3379. /* we can't nest cfs_b->lock while distributing bandwidth */
  3380. runtime = distribute_cfs_runtime(cfs_b, runtime,
  3381. runtime_expires);
  3382. raw_spin_lock(&cfs_b->lock);
  3383. throttled = !list_empty(&cfs_b->throttled_cfs_rq);
  3384. cfs_b->runtime -= min(runtime, cfs_b->runtime);
  3385. }
  3386. /*
  3387. * While we are ensured activity in the period following an
  3388. * unthrottle, this also covers the case in which the new bandwidth is
  3389. * insufficient to cover the existing bandwidth deficit. (Forcing the
  3390. * timer to remain active while there are any throttled entities.)
  3391. */
  3392. cfs_b->idle = 0;
  3393. return 0;
  3394. out_deactivate:
  3395. return 1;
  3396. }
  3397. /* a cfs_rq won't donate quota below this amount */
  3398. static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC;
  3399. /* minimum remaining period time to redistribute slack quota */
  3400. static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC;
  3401. /* how long we wait to gather additional slack before distributing */
  3402. static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC;
  3403. /*
  3404. * Are we near the end of the current quota period?
  3405. *
  3406. * Requires cfs_b->lock for hrtimer_expires_remaining to be safe against the
  3407. * hrtimer base being cleared by hrtimer_start. In the case of
  3408. * migrate_hrtimers, base is never cleared, so we are fine.
  3409. */
  3410. static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire)
  3411. {
  3412. struct hrtimer *refresh_timer = &cfs_b->period_timer;
  3413. u64 remaining;
  3414. /* if the call-back is running a quota refresh is already occurring */
  3415. if (hrtimer_callback_running(refresh_timer))
  3416. return 1;
  3417. /* is a quota refresh about to occur? */
  3418. remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer));
  3419. if (remaining < min_expire)
  3420. return 1;
  3421. return 0;
  3422. }
  3423. static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b)
  3424. {
  3425. u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration;
  3426. /* if there's a quota refresh soon don't bother with slack */
  3427. if (runtime_refresh_within(cfs_b, min_left))
  3428. return;
  3429. hrtimer_start(&cfs_b->slack_timer,
  3430. ns_to_ktime(cfs_bandwidth_slack_period),
  3431. HRTIMER_MODE_REL);
  3432. }
  3433. /* we know any runtime found here is valid as update_curr() precedes return */
  3434. static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  3435. {
  3436. struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
  3437. s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;
  3438. if (slack_runtime <= 0)
  3439. return;
  3440. raw_spin_lock(&cfs_b->lock);
  3441. if (cfs_b->quota != RUNTIME_INF &&
  3442. cfs_rq->runtime_expires == cfs_b->runtime_expires) {
  3443. cfs_b->runtime += slack_runtime;
  3444. /* we are under rq->lock, defer unthrottling using a timer */
  3445. if (cfs_b->runtime > sched_cfs_bandwidth_slice() &&
  3446. !list_empty(&cfs_b->throttled_cfs_rq))
  3447. start_cfs_slack_bandwidth(cfs_b);
  3448. }
  3449. raw_spin_unlock(&cfs_b->lock);
  3450. /* even if it's not valid for return we don't want to try again */
  3451. cfs_rq->runtime_remaining -= slack_runtime;
  3452. }
  3453. static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  3454. {
  3455. if (!cfs_bandwidth_used())
  3456. return;
  3457. if (!cfs_rq->runtime_enabled || cfs_rq->nr_running)
  3458. return;
  3459. __return_cfs_rq_runtime(cfs_rq);
  3460. }
  3461. /*
  3462. * This is done with a timer (instead of inline with bandwidth return) since
  3463. * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
  3464. */
  3465. static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)
  3466. {
  3467. u64 runtime = 0, slice = sched_cfs_bandwidth_slice();
  3468. u64 expires;
  3469. /* confirm we're still not at a refresh boundary */
  3470. raw_spin_lock(&cfs_b->lock);
  3471. if (runtime_refresh_within(cfs_b, min_bandwidth_expiration)) {
  3472. raw_spin_unlock(&cfs_b->lock);
  3473. return;
  3474. }
  3475. if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice)
  3476. runtime = cfs_b->runtime;
  3477. expires = cfs_b->runtime_expires;
  3478. raw_spin_unlock(&cfs_b->lock);
  3479. if (!runtime)
  3480. return;
  3481. runtime = distribute_cfs_runtime(cfs_b, runtime, expires);
  3482. raw_spin_lock(&cfs_b->lock);
  3483. if (expires == cfs_b->runtime_expires)
  3484. cfs_b->runtime -= min(runtime, cfs_b->runtime);
  3485. raw_spin_unlock(&cfs_b->lock);
  3486. }
  3487. /*
  3488. * When a group wakes up we want to make sure that its quota is not already
  3489. * expired/exceeded, otherwise it may be allowed to steal additional ticks of
  3490. * runtime as update_curr() throttling can not not trigger until it's on-rq.
  3491. */
  3492. static void check_enqueue_throttle(struct cfs_rq *cfs_rq)
  3493. {
  3494. if (!cfs_bandwidth_used())
  3495. return;
  3496. /* an active group must be handled by the update_curr()->put() path */
  3497. if (!cfs_rq->runtime_enabled || cfs_rq->curr)
  3498. return;
  3499. /* ensure the group is not already throttled */
  3500. if (cfs_rq_throttled(cfs_rq))
  3501. return;
  3502. /* update runtime allocation */
  3503. account_cfs_rq_runtime(cfs_rq, 0);
  3504. if (cfs_rq->runtime_remaining <= 0)
  3505. throttle_cfs_rq(cfs_rq);
  3506. }
  3507. /* conditionally throttle active cfs_rq's from put_prev_entity() */
  3508. static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  3509. {
  3510. if (!cfs_bandwidth_used())
  3511. return false;
  3512. if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0))
  3513. return false;
  3514. /*
  3515. * it's possible for a throttled entity to be forced into a running
  3516. * state (e.g. set_curr_task), in this case we're finished.
  3517. */
  3518. if (cfs_rq_throttled(cfs_rq))
  3519. return true;
  3520. throttle_cfs_rq(cfs_rq);
  3521. return true;
  3522. }
  3523. static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer)
  3524. {
  3525. struct cfs_bandwidth *cfs_b =
  3526. container_of(timer, struct cfs_bandwidth, slack_timer);
  3527. do_sched_cfs_slack_timer(cfs_b);
  3528. return HRTIMER_NORESTART;
  3529. }
  3530. static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)
  3531. {
  3532. struct cfs_bandwidth *cfs_b =
  3533. container_of(timer, struct cfs_bandwidth, period_timer);
  3534. int overrun;
  3535. int idle = 0;
  3536. raw_spin_lock(&cfs_b->lock);
  3537. for (;;) {
  3538. overrun = hrtimer_forward_now(timer, cfs_b->period);
  3539. if (!overrun)
  3540. break;
  3541. idle = do_sched_cfs_period_timer(cfs_b, overrun);
  3542. }
  3543. if (idle)
  3544. cfs_b->period_active = 0;
  3545. raw_spin_unlock(&cfs_b->lock);
  3546. return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
  3547. }
  3548. void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
  3549. {
  3550. raw_spin_lock_init(&cfs_b->lock);
  3551. cfs_b->runtime = 0;
  3552. cfs_b->quota = RUNTIME_INF;
  3553. cfs_b->period = ns_to_ktime(default_cfs_period());
  3554. INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq);
  3555. hrtimer_init(&cfs_b->period_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED);
  3556. cfs_b->period_timer.function = sched_cfs_period_timer;
  3557. hrtimer_init(&cfs_b->slack_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
  3558. cfs_b->slack_timer.function = sched_cfs_slack_timer;
  3559. }
  3560. static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  3561. {
  3562. cfs_rq->runtime_enabled = 0;
  3563. INIT_LIST_HEAD(&cfs_rq->throttled_list);
  3564. }
  3565. void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
  3566. {
  3567. lockdep_assert_held(&cfs_b->lock);
  3568. if (!cfs_b->period_active) {
  3569. cfs_b->period_active = 1;
  3570. hrtimer_forward_now(&cfs_b->period_timer, cfs_b->period);
  3571. hrtimer_start_expires(&cfs_b->period_timer, HRTIMER_MODE_ABS_PINNED);
  3572. }
  3573. }
  3574. static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
  3575. {
  3576. /* init_cfs_bandwidth() was not called */
  3577. if (!cfs_b->throttled_cfs_rq.next)
  3578. return;
  3579. hrtimer_cancel(&cfs_b->period_timer);
  3580. hrtimer_cancel(&cfs_b->slack_timer);
  3581. }
  3582. static void __maybe_unused update_runtime_enabled(struct rq *rq)
  3583. {
  3584. struct cfs_rq *cfs_rq;
  3585. for_each_leaf_cfs_rq(rq, cfs_rq) {
  3586. struct cfs_bandwidth *cfs_b = &cfs_rq->tg->cfs_bandwidth;
  3587. raw_spin_lock(&cfs_b->lock);
  3588. cfs_rq->runtime_enabled = cfs_b->quota != RUNTIME_INF;
  3589. raw_spin_unlock(&cfs_b->lock);
  3590. }
  3591. }
  3592. static void __maybe_unused unthrottle_offline_cfs_rqs(struct rq *rq)
  3593. {
  3594. struct cfs_rq *cfs_rq;
  3595. for_each_leaf_cfs_rq(rq, cfs_rq) {
  3596. if (!cfs_rq->runtime_enabled)
  3597. continue;
  3598. /*
  3599. * clock_task is not advancing so we just need to make sure
  3600. * there's some valid quota amount
  3601. */
  3602. cfs_rq->runtime_remaining = 1;
  3603. /*
  3604. * Offline rq is schedulable till cpu is completely disabled
  3605. * in take_cpu_down(), so we prevent new cfs throttling here.
  3606. */
  3607. cfs_rq->runtime_enabled = 0;
  3608. if (cfs_rq_throttled(cfs_rq))
  3609. unthrottle_cfs_rq(cfs_rq);
  3610. }
  3611. }
  3612. #else /* CONFIG_CFS_BANDWIDTH */
  3613. static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq)
  3614. {
  3615. return rq_clock_task(rq_of(cfs_rq));
  3616. }
  3617. static void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) {}
  3618. static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq) { return false; }
  3619. static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {}
  3620. static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
  3621. static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
  3622. {
  3623. return 0;
  3624. }
  3625. static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
  3626. {
  3627. return 0;
  3628. }
  3629. static inline int throttled_lb_pair(struct task_group *tg,
  3630. int src_cpu, int dest_cpu)
  3631. {
  3632. return 0;
  3633. }
  3634. void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
  3635. #ifdef CONFIG_FAIR_GROUP_SCHED
  3636. static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
  3637. #endif
  3638. static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
  3639. {
  3640. return NULL;
  3641. }
  3642. static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
  3643. static inline void update_runtime_enabled(struct rq *rq) {}
  3644. static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {}
  3645. #endif /* CONFIG_CFS_BANDWIDTH */
  3646. /**************************************************
  3647. * CFS operations on tasks:
  3648. */
  3649. #ifdef CONFIG_SCHED_HRTICK
  3650. static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
  3651. {
  3652. struct sched_entity *se = &p->se;
  3653. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  3654. WARN_ON(task_rq(p) != rq);
  3655. if (cfs_rq->nr_running > 1) {
  3656. u64 slice = sched_slice(cfs_rq, se);
  3657. u64 ran = se->sum_exec_runtime - se->prev_sum_exec_runtime;
  3658. s64 delta = slice - ran;
  3659. if (delta < 0) {
  3660. if (rq->curr == p)
  3661. resched_curr(rq);
  3662. return;
  3663. }
  3664. hrtick_start(rq, delta);
  3665. }
  3666. }
  3667. /*
  3668. * called from enqueue/dequeue and updates the hrtick when the
  3669. * current task is from our class and nr_running is low enough
  3670. * to matter.
  3671. */
  3672. static void hrtick_update(struct rq *rq)
  3673. {
  3674. struct task_struct *curr = rq->curr;
  3675. if (!hrtick_enabled(rq) || curr->sched_class != &fair_sched_class)
  3676. return;
  3677. if (cfs_rq_of(&curr->se)->nr_running < sched_nr_latency)
  3678. hrtick_start_fair(rq, curr);
  3679. }
  3680. #else /* !CONFIG_SCHED_HRTICK */
  3681. static inline void
  3682. hrtick_start_fair(struct rq *rq, struct task_struct *p)
  3683. {
  3684. }
  3685. static inline void hrtick_update(struct rq *rq)
  3686. {
  3687. }
  3688. #endif
  3689. /*
  3690. * The enqueue_task method is called before nr_running is
  3691. * increased. Here we update the fair scheduling stats and
  3692. * then put the task into the rbtree:
  3693. */
  3694. static void
  3695. enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
  3696. {
  3697. struct cfs_rq *cfs_rq;
  3698. struct sched_entity *se = &p->se;
  3699. for_each_sched_entity(se) {
  3700. if (se->on_rq)
  3701. break;
  3702. cfs_rq = cfs_rq_of(se);
  3703. enqueue_entity(cfs_rq, se, flags);
  3704. /*
  3705. * end evaluation on encountering a throttled cfs_rq
  3706. *
  3707. * note: in the case of encountering a throttled cfs_rq we will
  3708. * post the final h_nr_running increment below.
  3709. */
  3710. if (cfs_rq_throttled(cfs_rq))
  3711. break;
  3712. cfs_rq->h_nr_running++;
  3713. flags = ENQUEUE_WAKEUP;
  3714. }
  3715. for_each_sched_entity(se) {
  3716. cfs_rq = cfs_rq_of(se);
  3717. cfs_rq->h_nr_running++;
  3718. if (cfs_rq_throttled(cfs_rq))
  3719. break;
  3720. update_load_avg(se, 1);
  3721. update_cfs_shares(cfs_rq);
  3722. }
  3723. if (!se)
  3724. add_nr_running(rq, 1);
  3725. hrtick_update(rq);
  3726. }
  3727. static void set_next_buddy(struct sched_entity *se);
  3728. /*
  3729. * The dequeue_task method is called before nr_running is
  3730. * decreased. We remove the task from the rbtree and
  3731. * update the fair scheduling stats:
  3732. */
  3733. static void dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
  3734. {
  3735. struct cfs_rq *cfs_rq;
  3736. struct sched_entity *se = &p->se;
  3737. int task_sleep = flags & DEQUEUE_SLEEP;
  3738. for_each_sched_entity(se) {
  3739. cfs_rq = cfs_rq_of(se);
  3740. dequeue_entity(cfs_rq, se, flags);
  3741. /*
  3742. * end evaluation on encountering a throttled cfs_rq
  3743. *
  3744. * note: in the case of encountering a throttled cfs_rq we will
  3745. * post the final h_nr_running decrement below.
  3746. */
  3747. if (cfs_rq_throttled(cfs_rq))
  3748. break;
  3749. cfs_rq->h_nr_running--;
  3750. /* Don't dequeue parent if it has other entities besides us */
  3751. if (cfs_rq->load.weight) {
  3752. /*
  3753. * Bias pick_next to pick a task from this cfs_rq, as
  3754. * p is sleeping when it is within its sched_slice.
  3755. */
  3756. if (task_sleep && parent_entity(se))
  3757. set_next_buddy(parent_entity(se));
  3758. /* avoid re-evaluating load for this entity */
  3759. se = parent_entity(se);
  3760. break;
  3761. }
  3762. flags |= DEQUEUE_SLEEP;
  3763. }
  3764. for_each_sched_entity(se) {
  3765. cfs_rq = cfs_rq_of(se);
  3766. cfs_rq->h_nr_running--;
  3767. if (cfs_rq_throttled(cfs_rq))
  3768. break;
  3769. update_load_avg(se, 1);
  3770. update_cfs_shares(cfs_rq);
  3771. }
  3772. if (!se)
  3773. sub_nr_running(rq, 1);
  3774. hrtick_update(rq);
  3775. }
  3776. #ifdef CONFIG_SMP
  3777. #ifdef CONFIG_NO_HZ_COMMON
  3778. /*
  3779. * per rq 'load' arrray crap; XXX kill this.
  3780. */
  3781. /*
  3782. * The exact cpuload calculated at every tick would be:
  3783. *
  3784. * load' = (1 - 1/2^i) * load + (1/2^i) * cur_load
  3785. *
  3786. * If a cpu misses updates for n ticks (as it was idle) and update gets
  3787. * called on the n+1-th tick when cpu may be busy, then we have:
  3788. *
  3789. * load_n = (1 - 1/2^i)^n * load_0
  3790. * load_n+1 = (1 - 1/2^i) * load_n + (1/2^i) * cur_load
  3791. *
  3792. * decay_load_missed() below does efficient calculation of
  3793. *
  3794. * load' = (1 - 1/2^i)^n * load
  3795. *
  3796. * Because x^(n+m) := x^n * x^m we can decompose any x^n in power-of-2 factors.
  3797. * This allows us to precompute the above in said factors, thereby allowing the
  3798. * reduction of an arbitrary n in O(log_2 n) steps. (See also
  3799. * fixed_power_int())
  3800. *
  3801. * The calculation is approximated on a 128 point scale.
  3802. */
  3803. #define DEGRADE_SHIFT 7
  3804. static const u8 degrade_zero_ticks[CPU_LOAD_IDX_MAX] = {0, 8, 32, 64, 128};
  3805. static const u8 degrade_factor[CPU_LOAD_IDX_MAX][DEGRADE_SHIFT + 1] = {
  3806. { 0, 0, 0, 0, 0, 0, 0, 0 },
  3807. { 64, 32, 8, 0, 0, 0, 0, 0 },
  3808. { 96, 72, 40, 12, 1, 0, 0, 0 },
  3809. { 112, 98, 75, 43, 15, 1, 0, 0 },
  3810. { 120, 112, 98, 76, 45, 16, 2, 0 }
  3811. };
  3812. /*
  3813. * Update cpu_load for any missed ticks, due to tickless idle. The backlog
  3814. * would be when CPU is idle and so we just decay the old load without
  3815. * adding any new load.
  3816. */
  3817. static unsigned long
  3818. decay_load_missed(unsigned long load, unsigned long missed_updates, int idx)
  3819. {
  3820. int j = 0;
  3821. if (!missed_updates)
  3822. return load;
  3823. if (missed_updates >= degrade_zero_ticks[idx])
  3824. return 0;
  3825. if (idx == 1)
  3826. return load >> missed_updates;
  3827. while (missed_updates) {
  3828. if (missed_updates % 2)
  3829. load = (load * degrade_factor[idx][j]) >> DEGRADE_SHIFT;
  3830. missed_updates >>= 1;
  3831. j++;
  3832. }
  3833. return load;
  3834. }
  3835. #endif /* CONFIG_NO_HZ_COMMON */
  3836. /**
  3837. * __cpu_load_update - update the rq->cpu_load[] statistics
  3838. * @this_rq: The rq to update statistics for
  3839. * @this_load: The current load
  3840. * @pending_updates: The number of missed updates
  3841. *
  3842. * Update rq->cpu_load[] statistics. This function is usually called every
  3843. * scheduler tick (TICK_NSEC).
  3844. *
  3845. * This function computes a decaying average:
  3846. *
  3847. * load[i]' = (1 - 1/2^i) * load[i] + (1/2^i) * load
  3848. *
  3849. * Because of NOHZ it might not get called on every tick which gives need for
  3850. * the @pending_updates argument.
  3851. *
  3852. * load[i]_n = (1 - 1/2^i) * load[i]_n-1 + (1/2^i) * load_n-1
  3853. * = A * load[i]_n-1 + B ; A := (1 - 1/2^i), B := (1/2^i) * load
  3854. * = A * (A * load[i]_n-2 + B) + B
  3855. * = A * (A * (A * load[i]_n-3 + B) + B) + B
  3856. * = A^3 * load[i]_n-3 + (A^2 + A + 1) * B
  3857. * = A^n * load[i]_0 + (A^(n-1) + A^(n-2) + ... + 1) * B
  3858. * = A^n * load[i]_0 + ((1 - A^n) / (1 - A)) * B
  3859. * = (1 - 1/2^i)^n * (load[i]_0 - load) + load
  3860. *
  3861. * In the above we've assumed load_n := load, which is true for NOHZ_FULL as
  3862. * any change in load would have resulted in the tick being turned back on.
  3863. *
  3864. * For regular NOHZ, this reduces to:
  3865. *
  3866. * load[i]_n = (1 - 1/2^i)^n * load[i]_0
  3867. *
  3868. * see decay_load_misses(). For NOHZ_FULL we get to subtract and add the extra
  3869. * term.
  3870. */
  3871. static void cpu_load_update(struct rq *this_rq, unsigned long this_load,
  3872. unsigned long pending_updates)
  3873. {
  3874. unsigned long __maybe_unused tickless_load = this_rq->cpu_load[0];
  3875. int i, scale;
  3876. this_rq->nr_load_updates++;
  3877. /* Update our load: */
  3878. this_rq->cpu_load[0] = this_load; /* Fasttrack for idx 0 */
  3879. for (i = 1, scale = 2; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
  3880. unsigned long old_load, new_load;
  3881. /* scale is effectively 1 << i now, and >> i divides by scale */
  3882. old_load = this_rq->cpu_load[i];
  3883. #ifdef CONFIG_NO_HZ_COMMON
  3884. old_load = decay_load_missed(old_load, pending_updates - 1, i);
  3885. if (tickless_load) {
  3886. old_load -= decay_load_missed(tickless_load, pending_updates - 1, i);
  3887. /*
  3888. * old_load can never be a negative value because a
  3889. * decayed tickless_load cannot be greater than the
  3890. * original tickless_load.
  3891. */
  3892. old_load += tickless_load;
  3893. }
  3894. #endif
  3895. new_load = this_load;
  3896. /*
  3897. * Round up the averaging division if load is increasing. This
  3898. * prevents us from getting stuck on 9 if the load is 10, for
  3899. * example.
  3900. */
  3901. if (new_load > old_load)
  3902. new_load += scale - 1;
  3903. this_rq->cpu_load[i] = (old_load * (scale - 1) + new_load) >> i;
  3904. }
  3905. sched_avg_update(this_rq);
  3906. }
  3907. /* Used instead of source_load when we know the type == 0 */
  3908. static unsigned long weighted_cpuload(const int cpu)
  3909. {
  3910. return cfs_rq_runnable_load_avg(&cpu_rq(cpu)->cfs);
  3911. }
  3912. #ifdef CONFIG_NO_HZ_COMMON
  3913. /*
  3914. * There is no sane way to deal with nohz on smp when using jiffies because the
  3915. * cpu doing the jiffies update might drift wrt the cpu doing the jiffy reading
  3916. * causing off-by-one errors in observed deltas; {0,2} instead of {1,1}.
  3917. *
  3918. * Therefore we need to avoid the delta approach from the regular tick when
  3919. * possible since that would seriously skew the load calculation. This is why we
  3920. * use cpu_load_update_periodic() for CPUs out of nohz. However we'll rely on
  3921. * jiffies deltas for updates happening while in nohz mode (idle ticks, idle
  3922. * loop exit, nohz_idle_balance, nohz full exit...)
  3923. *
  3924. * This means we might still be one tick off for nohz periods.
  3925. */
  3926. static void cpu_load_update_nohz(struct rq *this_rq,
  3927. unsigned long curr_jiffies,
  3928. unsigned long load)
  3929. {
  3930. unsigned long pending_updates;
  3931. pending_updates = curr_jiffies - this_rq->last_load_update_tick;
  3932. if (pending_updates) {
  3933. this_rq->last_load_update_tick = curr_jiffies;
  3934. /*
  3935. * In the regular NOHZ case, we were idle, this means load 0.
  3936. * In the NOHZ_FULL case, we were non-idle, we should consider
  3937. * its weighted load.
  3938. */
  3939. cpu_load_update(this_rq, load, pending_updates);
  3940. }
  3941. }
  3942. /*
  3943. * Called from nohz_idle_balance() to update the load ratings before doing the
  3944. * idle balance.
  3945. */
  3946. static void cpu_load_update_idle(struct rq *this_rq)
  3947. {
  3948. /*
  3949. * bail if there's load or we're actually up-to-date.
  3950. */
  3951. if (weighted_cpuload(cpu_of(this_rq)))
  3952. return;
  3953. cpu_load_update_nohz(this_rq, READ_ONCE(jiffies), 0);
  3954. }
  3955. /*
  3956. * Record CPU load on nohz entry so we know the tickless load to account
  3957. * on nohz exit. cpu_load[0] happens then to be updated more frequently
  3958. * than other cpu_load[idx] but it should be fine as cpu_load readers
  3959. * shouldn't rely into synchronized cpu_load[*] updates.
  3960. */
  3961. void cpu_load_update_nohz_start(void)
  3962. {
  3963. struct rq *this_rq = this_rq();
  3964. /*
  3965. * This is all lockless but should be fine. If weighted_cpuload changes
  3966. * concurrently we'll exit nohz. And cpu_load write can race with
  3967. * cpu_load_update_idle() but both updater would be writing the same.
  3968. */
  3969. this_rq->cpu_load[0] = weighted_cpuload(cpu_of(this_rq));
  3970. }
  3971. /*
  3972. * Account the tickless load in the end of a nohz frame.
  3973. */
  3974. void cpu_load_update_nohz_stop(void)
  3975. {
  3976. unsigned long curr_jiffies = READ_ONCE(jiffies);
  3977. struct rq *this_rq = this_rq();
  3978. unsigned long load;
  3979. if (curr_jiffies == this_rq->last_load_update_tick)
  3980. return;
  3981. load = weighted_cpuload(cpu_of(this_rq));
  3982. raw_spin_lock(&this_rq->lock);
  3983. update_rq_clock(this_rq);
  3984. cpu_load_update_nohz(this_rq, curr_jiffies, load);
  3985. raw_spin_unlock(&this_rq->lock);
  3986. }
  3987. #else /* !CONFIG_NO_HZ_COMMON */
  3988. static inline void cpu_load_update_nohz(struct rq *this_rq,
  3989. unsigned long curr_jiffies,
  3990. unsigned long load) { }
  3991. #endif /* CONFIG_NO_HZ_COMMON */
  3992. static void cpu_load_update_periodic(struct rq *this_rq, unsigned long load)
  3993. {
  3994. #ifdef CONFIG_NO_HZ_COMMON
  3995. /* See the mess around cpu_load_update_nohz(). */
  3996. this_rq->last_load_update_tick = READ_ONCE(jiffies);
  3997. #endif
  3998. cpu_load_update(this_rq, load, 1);
  3999. }
  4000. /*
  4001. * Called from scheduler_tick()
  4002. */
  4003. void cpu_load_update_active(struct rq *this_rq)
  4004. {
  4005. unsigned long load = weighted_cpuload(cpu_of(this_rq));
  4006. if (tick_nohz_tick_stopped())
  4007. cpu_load_update_nohz(this_rq, READ_ONCE(jiffies), load);
  4008. else
  4009. cpu_load_update_periodic(this_rq, load);
  4010. }
  4011. /*
  4012. * Return a low guess at the load of a migration-source cpu weighted
  4013. * according to the scheduling class and "nice" value.
  4014. *
  4015. * We want to under-estimate the load of migration sources, to
  4016. * balance conservatively.
  4017. */
  4018. static unsigned long source_load(int cpu, int type)
  4019. {
  4020. struct rq *rq = cpu_rq(cpu);
  4021. unsigned long total = weighted_cpuload(cpu);
  4022. if (type == 0 || !sched_feat(LB_BIAS))
  4023. return total;
  4024. return min(rq->cpu_load[type-1], total);
  4025. }
  4026. /*
  4027. * Return a high guess at the load of a migration-target cpu weighted
  4028. * according to the scheduling class and "nice" value.
  4029. */
  4030. static unsigned long target_load(int cpu, int type)
  4031. {
  4032. struct rq *rq = cpu_rq(cpu);
  4033. unsigned long total = weighted_cpuload(cpu);
  4034. if (type == 0 || !sched_feat(LB_BIAS))
  4035. return total;
  4036. return max(rq->cpu_load[type-1], total);
  4037. }
  4038. static unsigned long capacity_of(int cpu)
  4039. {
  4040. return cpu_rq(cpu)->cpu_capacity;
  4041. }
  4042. static unsigned long capacity_orig_of(int cpu)
  4043. {
  4044. return cpu_rq(cpu)->cpu_capacity_orig;
  4045. }
  4046. static unsigned long cpu_avg_load_per_task(int cpu)
  4047. {
  4048. struct rq *rq = cpu_rq(cpu);
  4049. unsigned long nr_running = READ_ONCE(rq->cfs.h_nr_running);
  4050. unsigned long load_avg = weighted_cpuload(cpu);
  4051. if (nr_running)
  4052. return load_avg / nr_running;
  4053. return 0;
  4054. }
  4055. #ifdef CONFIG_FAIR_GROUP_SCHED
  4056. /*
  4057. * effective_load() calculates the load change as seen from the root_task_group
  4058. *
  4059. * Adding load to a group doesn't make a group heavier, but can cause movement
  4060. * of group shares between cpus. Assuming the shares were perfectly aligned one
  4061. * can calculate the shift in shares.
  4062. *
  4063. * Calculate the effective load difference if @wl is added (subtracted) to @tg
  4064. * on this @cpu and results in a total addition (subtraction) of @wg to the
  4065. * total group weight.
  4066. *
  4067. * Given a runqueue weight distribution (rw_i) we can compute a shares
  4068. * distribution (s_i) using:
  4069. *
  4070. * s_i = rw_i / \Sum rw_j (1)
  4071. *
  4072. * Suppose we have 4 CPUs and our @tg is a direct child of the root group and
  4073. * has 7 equal weight tasks, distributed as below (rw_i), with the resulting
  4074. * shares distribution (s_i):
  4075. *
  4076. * rw_i = { 2, 4, 1, 0 }
  4077. * s_i = { 2/7, 4/7, 1/7, 0 }
  4078. *
  4079. * As per wake_affine() we're interested in the load of two CPUs (the CPU the
  4080. * task used to run on and the CPU the waker is running on), we need to
  4081. * compute the effect of waking a task on either CPU and, in case of a sync
  4082. * wakeup, compute the effect of the current task going to sleep.
  4083. *
  4084. * So for a change of @wl to the local @cpu with an overall group weight change
  4085. * of @wl we can compute the new shares distribution (s'_i) using:
  4086. *
  4087. * s'_i = (rw_i + @wl) / (@wg + \Sum rw_j) (2)
  4088. *
  4089. * Suppose we're interested in CPUs 0 and 1, and want to compute the load
  4090. * differences in waking a task to CPU 0. The additional task changes the
  4091. * weight and shares distributions like:
  4092. *
  4093. * rw'_i = { 3, 4, 1, 0 }
  4094. * s'_i = { 3/8, 4/8, 1/8, 0 }
  4095. *
  4096. * We can then compute the difference in effective weight by using:
  4097. *
  4098. * dw_i = S * (s'_i - s_i) (3)
  4099. *
  4100. * Where 'S' is the group weight as seen by its parent.
  4101. *
  4102. * Therefore the effective change in loads on CPU 0 would be 5/56 (3/8 - 2/7)
  4103. * times the weight of the group. The effect on CPU 1 would be -4/56 (4/8 -
  4104. * 4/7) times the weight of the group.
  4105. */
  4106. static long effective_load(struct task_group *tg, int cpu, long wl, long wg)
  4107. {
  4108. struct sched_entity *se = tg->se[cpu];
  4109. if (!tg->parent) /* the trivial, non-cgroup case */
  4110. return wl;
  4111. for_each_sched_entity(se) {
  4112. long w, W;
  4113. tg = se->my_q->tg;
  4114. /*
  4115. * W = @wg + \Sum rw_j
  4116. */
  4117. W = wg + calc_tg_weight(tg, se->my_q);
  4118. /*
  4119. * w = rw_i + @wl
  4120. */
  4121. w = cfs_rq_load_avg(se->my_q) + wl;
  4122. /*
  4123. * wl = S * s'_i; see (2)
  4124. */
  4125. if (W > 0 && w < W)
  4126. wl = (w * (long)tg->shares) / W;
  4127. else
  4128. wl = tg->shares;
  4129. /*
  4130. * Per the above, wl is the new se->load.weight value; since
  4131. * those are clipped to [MIN_SHARES, ...) do so now. See
  4132. * calc_cfs_shares().
  4133. */
  4134. if (wl < MIN_SHARES)
  4135. wl = MIN_SHARES;
  4136. /*
  4137. * wl = dw_i = S * (s'_i - s_i); see (3)
  4138. */
  4139. wl -= se->avg.load_avg;
  4140. /*
  4141. * Recursively apply this logic to all parent groups to compute
  4142. * the final effective load change on the root group. Since
  4143. * only the @tg group gets extra weight, all parent groups can
  4144. * only redistribute existing shares. @wl is the shift in shares
  4145. * resulting from this level per the above.
  4146. */
  4147. wg = 0;
  4148. }
  4149. return wl;
  4150. }
  4151. #else
  4152. static long effective_load(struct task_group *tg, int cpu, long wl, long wg)
  4153. {
  4154. return wl;
  4155. }
  4156. #endif
  4157. static void record_wakee(struct task_struct *p)
  4158. {
  4159. /*
  4160. * Only decay a single time; tasks that have less then 1 wakeup per
  4161. * jiffy will not have built up many flips.
  4162. */
  4163. if (time_after(jiffies, current->wakee_flip_decay_ts + HZ)) {
  4164. current->wakee_flips >>= 1;
  4165. current->wakee_flip_decay_ts = jiffies;
  4166. }
  4167. if (current->last_wakee != p) {
  4168. current->last_wakee = p;
  4169. current->wakee_flips++;
  4170. }
  4171. }
  4172. /*
  4173. * Detect M:N waker/wakee relationships via a switching-frequency heuristic.
  4174. *
  4175. * A waker of many should wake a different task than the one last awakened
  4176. * at a frequency roughly N times higher than one of its wakees.
  4177. *
  4178. * In order to determine whether we should let the load spread vs consolidating
  4179. * to shared cache, we look for a minimum 'flip' frequency of llc_size in one
  4180. * partner, and a factor of lls_size higher frequency in the other.
  4181. *
  4182. * With both conditions met, we can be relatively sure that the relationship is
  4183. * non-monogamous, with partner count exceeding socket size.
  4184. *
  4185. * Waker/wakee being client/server, worker/dispatcher, interrupt source or
  4186. * whatever is irrelevant, spread criteria is apparent partner count exceeds
  4187. * socket size.
  4188. */
  4189. static int wake_wide(struct task_struct *p)
  4190. {
  4191. unsigned int master = current->wakee_flips;
  4192. unsigned int slave = p->wakee_flips;
  4193. int factor = this_cpu_read(sd_llc_size);
  4194. if (master < slave)
  4195. swap(master, slave);
  4196. if (slave < factor || master < slave * factor)
  4197. return 0;
  4198. return 1;
  4199. }
  4200. static int wake_affine(struct sched_domain *sd, struct task_struct *p, int sync)
  4201. {
  4202. s64 this_load, load;
  4203. s64 this_eff_load, prev_eff_load;
  4204. int idx, this_cpu, prev_cpu;
  4205. struct task_group *tg;
  4206. unsigned long weight;
  4207. int balanced;
  4208. idx = sd->wake_idx;
  4209. this_cpu = smp_processor_id();
  4210. prev_cpu = task_cpu(p);
  4211. load = source_load(prev_cpu, idx);
  4212. this_load = target_load(this_cpu, idx);
  4213. /*
  4214. * If sync wakeup then subtract the (maximum possible)
  4215. * effect of the currently running task from the load
  4216. * of the current CPU:
  4217. */
  4218. if (sync) {
  4219. tg = task_group(current);
  4220. weight = current->se.avg.load_avg;
  4221. this_load += effective_load(tg, this_cpu, -weight, -weight);
  4222. load += effective_load(tg, prev_cpu, 0, -weight);
  4223. }
  4224. tg = task_group(p);
  4225. weight = p->se.avg.load_avg;
  4226. /*
  4227. * In low-load situations, where prev_cpu is idle and this_cpu is idle
  4228. * due to the sync cause above having dropped this_load to 0, we'll
  4229. * always have an imbalance, but there's really nothing you can do
  4230. * about that, so that's good too.
  4231. *
  4232. * Otherwise check if either cpus are near enough in load to allow this
  4233. * task to be woken on this_cpu.
  4234. */
  4235. this_eff_load = 100;
  4236. this_eff_load *= capacity_of(prev_cpu);
  4237. prev_eff_load = 100 + (sd->imbalance_pct - 100) / 2;
  4238. prev_eff_load *= capacity_of(this_cpu);
  4239. if (this_load > 0) {
  4240. this_eff_load *= this_load +
  4241. effective_load(tg, this_cpu, weight, weight);
  4242. prev_eff_load *= load + effective_load(tg, prev_cpu, 0, weight);
  4243. }
  4244. balanced = this_eff_load <= prev_eff_load;
  4245. schedstat_inc(p, se.statistics.nr_wakeups_affine_attempts);
  4246. if (!balanced)
  4247. return 0;
  4248. schedstat_inc(sd, ttwu_move_affine);
  4249. schedstat_inc(p, se.statistics.nr_wakeups_affine);
  4250. return 1;
  4251. }
  4252. /*
  4253. * find_idlest_group finds and returns the least busy CPU group within the
  4254. * domain.
  4255. */
  4256. static struct sched_group *
  4257. find_idlest_group(struct sched_domain *sd, struct task_struct *p,
  4258. int this_cpu, int sd_flag)
  4259. {
  4260. struct sched_group *idlest = NULL, *group = sd->groups;
  4261. unsigned long min_load = ULONG_MAX, this_load = 0;
  4262. int load_idx = sd->forkexec_idx;
  4263. int imbalance = 100 + (sd->imbalance_pct-100)/2;
  4264. if (sd_flag & SD_BALANCE_WAKE)
  4265. load_idx = sd->wake_idx;
  4266. do {
  4267. unsigned long load, avg_load;
  4268. int local_group;
  4269. int i;
  4270. /* Skip over this group if it has no CPUs allowed */
  4271. if (!cpumask_intersects(sched_group_cpus(group),
  4272. tsk_cpus_allowed(p)))
  4273. continue;
  4274. local_group = cpumask_test_cpu(this_cpu,
  4275. sched_group_cpus(group));
  4276. /* Tally up the load of all CPUs in the group */
  4277. avg_load = 0;
  4278. for_each_cpu(i, sched_group_cpus(group)) {
  4279. /* Bias balancing toward cpus of our domain */
  4280. if (local_group)
  4281. load = source_load(i, load_idx);
  4282. else
  4283. load = target_load(i, load_idx);
  4284. avg_load += load;
  4285. }
  4286. /* Adjust by relative CPU capacity of the group */
  4287. avg_load = (avg_load * SCHED_CAPACITY_SCALE) / group->sgc->capacity;
  4288. if (local_group) {
  4289. this_load = avg_load;
  4290. } else if (avg_load < min_load) {
  4291. min_load = avg_load;
  4292. idlest = group;
  4293. }
  4294. } while (group = group->next, group != sd->groups);
  4295. if (!idlest || 100*this_load < imbalance*min_load)
  4296. return NULL;
  4297. return idlest;
  4298. }
  4299. /*
  4300. * find_idlest_cpu - find the idlest cpu among the cpus in group.
  4301. */
  4302. static int
  4303. find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
  4304. {
  4305. unsigned long load, min_load = ULONG_MAX;
  4306. unsigned int min_exit_latency = UINT_MAX;
  4307. u64 latest_idle_timestamp = 0;
  4308. int least_loaded_cpu = this_cpu;
  4309. int shallowest_idle_cpu = -1;
  4310. int i;
  4311. /* Traverse only the allowed CPUs */
  4312. for_each_cpu_and(i, sched_group_cpus(group), tsk_cpus_allowed(p)) {
  4313. if (idle_cpu(i)) {
  4314. struct rq *rq = cpu_rq(i);
  4315. struct cpuidle_state *idle = idle_get_state(rq);
  4316. if (idle && idle->exit_latency < min_exit_latency) {
  4317. /*
  4318. * We give priority to a CPU whose idle state
  4319. * has the smallest exit latency irrespective
  4320. * of any idle timestamp.
  4321. */
  4322. min_exit_latency = idle->exit_latency;
  4323. latest_idle_timestamp = rq->idle_stamp;
  4324. shallowest_idle_cpu = i;
  4325. } else if ((!idle || idle->exit_latency == min_exit_latency) &&
  4326. rq->idle_stamp > latest_idle_timestamp) {
  4327. /*
  4328. * If equal or no active idle state, then
  4329. * the most recently idled CPU might have
  4330. * a warmer cache.
  4331. */
  4332. latest_idle_timestamp = rq->idle_stamp;
  4333. shallowest_idle_cpu = i;
  4334. }
  4335. } else if (shallowest_idle_cpu == -1) {
  4336. load = weighted_cpuload(i);
  4337. if (load < min_load || (load == min_load && i == this_cpu)) {
  4338. min_load = load;
  4339. least_loaded_cpu = i;
  4340. }
  4341. }
  4342. }
  4343. return shallowest_idle_cpu != -1 ? shallowest_idle_cpu : least_loaded_cpu;
  4344. }
  4345. /*
  4346. * Try and locate an idle CPU in the sched_domain.
  4347. */
  4348. static int select_idle_sibling(struct task_struct *p, int target)
  4349. {
  4350. struct sched_domain *sd;
  4351. struct sched_group *sg;
  4352. int i = task_cpu(p);
  4353. if (idle_cpu(target))
  4354. return target;
  4355. /*
  4356. * If the prevous cpu is cache affine and idle, don't be stupid.
  4357. */
  4358. if (i != target && cpus_share_cache(i, target) && idle_cpu(i))
  4359. return i;
  4360. /*
  4361. * Otherwise, iterate the domains and find an eligible idle cpu.
  4362. *
  4363. * A completely idle sched group at higher domains is more
  4364. * desirable than an idle group at a lower level, because lower
  4365. * domains have smaller groups and usually share hardware
  4366. * resources which causes tasks to contend on them, e.g. x86
  4367. * hyperthread siblings in the lowest domain (SMT) can contend
  4368. * on the shared cpu pipeline.
  4369. *
  4370. * However, while we prefer idle groups at higher domains
  4371. * finding an idle cpu at the lowest domain is still better than
  4372. * returning 'target', which we've already established, isn't
  4373. * idle.
  4374. */
  4375. sd = rcu_dereference(per_cpu(sd_llc, target));
  4376. for_each_lower_domain(sd) {
  4377. sg = sd->groups;
  4378. do {
  4379. if (!cpumask_intersects(sched_group_cpus(sg),
  4380. tsk_cpus_allowed(p)))
  4381. goto next;
  4382. /* Ensure the entire group is idle */
  4383. for_each_cpu(i, sched_group_cpus(sg)) {
  4384. if (i == target || !idle_cpu(i))
  4385. goto next;
  4386. }
  4387. /*
  4388. * It doesn't matter which cpu we pick, the
  4389. * whole group is idle.
  4390. */
  4391. target = cpumask_first_and(sched_group_cpus(sg),
  4392. tsk_cpus_allowed(p));
  4393. goto done;
  4394. next:
  4395. sg = sg->next;
  4396. } while (sg != sd->groups);
  4397. }
  4398. done:
  4399. return target;
  4400. }
  4401. /*
  4402. * cpu_util returns the amount of capacity of a CPU that is used by CFS
  4403. * tasks. The unit of the return value must be the one of capacity so we can
  4404. * compare the utilization with the capacity of the CPU that is available for
  4405. * CFS task (ie cpu_capacity).
  4406. *
  4407. * cfs_rq.avg.util_avg is the sum of running time of runnable tasks plus the
  4408. * recent utilization of currently non-runnable tasks on a CPU. It represents
  4409. * the amount of utilization of a CPU in the range [0..capacity_orig] where
  4410. * capacity_orig is the cpu_capacity available at the highest frequency
  4411. * (arch_scale_freq_capacity()).
  4412. * The utilization of a CPU converges towards a sum equal to or less than the
  4413. * current capacity (capacity_curr <= capacity_orig) of the CPU because it is
  4414. * the running time on this CPU scaled by capacity_curr.
  4415. *
  4416. * Nevertheless, cfs_rq.avg.util_avg can be higher than capacity_curr or even
  4417. * higher than capacity_orig because of unfortunate rounding in
  4418. * cfs.avg.util_avg or just after migrating tasks and new task wakeups until
  4419. * the average stabilizes with the new running time. We need to check that the
  4420. * utilization stays within the range of [0..capacity_orig] and cap it if
  4421. * necessary. Without utilization capping, a group could be seen as overloaded
  4422. * (CPU0 utilization at 121% + CPU1 utilization at 80%) whereas CPU1 has 20% of
  4423. * available capacity. We allow utilization to overshoot capacity_curr (but not
  4424. * capacity_orig) as it useful for predicting the capacity required after task
  4425. * migrations (scheduler-driven DVFS).
  4426. */
  4427. static int cpu_util(int cpu)
  4428. {
  4429. unsigned long util = cpu_rq(cpu)->cfs.avg.util_avg;
  4430. unsigned long capacity = capacity_orig_of(cpu);
  4431. return (util >= capacity) ? capacity : util;
  4432. }
  4433. /*
  4434. * select_task_rq_fair: Select target runqueue for the waking task in domains
  4435. * that have the 'sd_flag' flag set. In practice, this is SD_BALANCE_WAKE,
  4436. * SD_BALANCE_FORK, or SD_BALANCE_EXEC.
  4437. *
  4438. * Balances load by selecting the idlest cpu in the idlest group, or under
  4439. * certain conditions an idle sibling cpu if the domain has SD_WAKE_AFFINE set.
  4440. *
  4441. * Returns the target cpu number.
  4442. *
  4443. * preempt must be disabled.
  4444. */
  4445. static int
  4446. select_task_rq_fair(struct task_struct *p, int prev_cpu, int sd_flag, int wake_flags)
  4447. {
  4448. struct sched_domain *tmp, *affine_sd = NULL, *sd = NULL;
  4449. int cpu = smp_processor_id();
  4450. int new_cpu = prev_cpu;
  4451. int want_affine = 0;
  4452. int sync = wake_flags & WF_SYNC;
  4453. if (sd_flag & SD_BALANCE_WAKE) {
  4454. record_wakee(p);
  4455. want_affine = !wake_wide(p) && cpumask_test_cpu(cpu, tsk_cpus_allowed(p));
  4456. }
  4457. rcu_read_lock();
  4458. for_each_domain(cpu, tmp) {
  4459. if (!(tmp->flags & SD_LOAD_BALANCE))
  4460. break;
  4461. /*
  4462. * If both cpu and prev_cpu are part of this domain,
  4463. * cpu is a valid SD_WAKE_AFFINE target.
  4464. */
  4465. if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
  4466. cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
  4467. affine_sd = tmp;
  4468. break;
  4469. }
  4470. if (tmp->flags & sd_flag)
  4471. sd = tmp;
  4472. else if (!want_affine)
  4473. break;
  4474. }
  4475. if (affine_sd) {
  4476. sd = NULL; /* Prefer wake_affine over balance flags */
  4477. if (cpu != prev_cpu && wake_affine(affine_sd, p, sync))
  4478. new_cpu = cpu;
  4479. }
  4480. if (!sd) {
  4481. if (sd_flag & SD_BALANCE_WAKE) /* XXX always ? */
  4482. new_cpu = select_idle_sibling(p, new_cpu);
  4483. } else while (sd) {
  4484. struct sched_group *group;
  4485. int weight;
  4486. if (!(sd->flags & sd_flag)) {
  4487. sd = sd->child;
  4488. continue;
  4489. }
  4490. group = find_idlest_group(sd, p, cpu, sd_flag);
  4491. if (!group) {
  4492. sd = sd->child;
  4493. continue;
  4494. }
  4495. new_cpu = find_idlest_cpu(group, p, cpu);
  4496. if (new_cpu == -1 || new_cpu == cpu) {
  4497. /* Now try balancing at a lower domain level of cpu */
  4498. sd = sd->child;
  4499. continue;
  4500. }
  4501. /* Now try balancing at a lower domain level of new_cpu */
  4502. cpu = new_cpu;
  4503. weight = sd->span_weight;
  4504. sd = NULL;
  4505. for_each_domain(cpu, tmp) {
  4506. if (weight <= tmp->span_weight)
  4507. break;
  4508. if (tmp->flags & sd_flag)
  4509. sd = tmp;
  4510. }
  4511. /* while loop will break here if sd == NULL */
  4512. }
  4513. rcu_read_unlock();
  4514. return new_cpu;
  4515. }
  4516. /*
  4517. * Called immediately before a task is migrated to a new cpu; task_cpu(p) and
  4518. * cfs_rq_of(p) references at time of call are still valid and identify the
  4519. * previous cpu. The caller guarantees p->pi_lock or task_rq(p)->lock is held.
  4520. */
  4521. static void migrate_task_rq_fair(struct task_struct *p)
  4522. {
  4523. /*
  4524. * As blocked tasks retain absolute vruntime the migration needs to
  4525. * deal with this by subtracting the old and adding the new
  4526. * min_vruntime -- the latter is done by enqueue_entity() when placing
  4527. * the task on the new runqueue.
  4528. */
  4529. if (p->state == TASK_WAKING) {
  4530. struct sched_entity *se = &p->se;
  4531. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  4532. u64 min_vruntime;
  4533. #ifndef CONFIG_64BIT
  4534. u64 min_vruntime_copy;
  4535. do {
  4536. min_vruntime_copy = cfs_rq->min_vruntime_copy;
  4537. smp_rmb();
  4538. min_vruntime = cfs_rq->min_vruntime;
  4539. } while (min_vruntime != min_vruntime_copy);
  4540. #else
  4541. min_vruntime = cfs_rq->min_vruntime;
  4542. #endif
  4543. se->vruntime -= min_vruntime;
  4544. }
  4545. /*
  4546. * We are supposed to update the task to "current" time, then its up to date
  4547. * and ready to go to new CPU/cfs_rq. But we have difficulty in getting
  4548. * what current time is, so simply throw away the out-of-date time. This
  4549. * will result in the wakee task is less decayed, but giving the wakee more
  4550. * load sounds not bad.
  4551. */
  4552. remove_entity_load_avg(&p->se);
  4553. /* Tell new CPU we are migrated */
  4554. p->se.avg.last_update_time = 0;
  4555. /* We have migrated, no longer consider this task hot */
  4556. p->se.exec_start = 0;
  4557. }
  4558. static void task_dead_fair(struct task_struct *p)
  4559. {
  4560. remove_entity_load_avg(&p->se);
  4561. }
  4562. #endif /* CONFIG_SMP */
  4563. static unsigned long
  4564. wakeup_gran(struct sched_entity *curr, struct sched_entity *se)
  4565. {
  4566. unsigned long gran = sysctl_sched_wakeup_granularity;
  4567. /*
  4568. * Since its curr running now, convert the gran from real-time
  4569. * to virtual-time in his units.
  4570. *
  4571. * By using 'se' instead of 'curr' we penalize light tasks, so
  4572. * they get preempted easier. That is, if 'se' < 'curr' then
  4573. * the resulting gran will be larger, therefore penalizing the
  4574. * lighter, if otoh 'se' > 'curr' then the resulting gran will
  4575. * be smaller, again penalizing the lighter task.
  4576. *
  4577. * This is especially important for buddies when the leftmost
  4578. * task is higher priority than the buddy.
  4579. */
  4580. return calc_delta_fair(gran, se);
  4581. }
  4582. /*
  4583. * Should 'se' preempt 'curr'.
  4584. *
  4585. * |s1
  4586. * |s2
  4587. * |s3
  4588. * g
  4589. * |<--->|c
  4590. *
  4591. * w(c, s1) = -1
  4592. * w(c, s2) = 0
  4593. * w(c, s3) = 1
  4594. *
  4595. */
  4596. static int
  4597. wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se)
  4598. {
  4599. s64 gran, vdiff = curr->vruntime - se->vruntime;
  4600. if (vdiff <= 0)
  4601. return -1;
  4602. gran = wakeup_gran(curr, se);
  4603. if (vdiff > gran)
  4604. return 1;
  4605. return 0;
  4606. }
  4607. static void set_last_buddy(struct sched_entity *se)
  4608. {
  4609. if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE))
  4610. return;
  4611. for_each_sched_entity(se)
  4612. cfs_rq_of(se)->last = se;
  4613. }
  4614. static void set_next_buddy(struct sched_entity *se)
  4615. {
  4616. if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE))
  4617. return;
  4618. for_each_sched_entity(se)
  4619. cfs_rq_of(se)->next = se;
  4620. }
  4621. static void set_skip_buddy(struct sched_entity *se)
  4622. {
  4623. for_each_sched_entity(se)
  4624. cfs_rq_of(se)->skip = se;
  4625. }
  4626. /*
  4627. * Preempt the current task with a newly woken task if needed:
  4628. */
  4629. static void check_preempt_wakeup(struct rq *rq, struct task_struct *p, int wake_flags)
  4630. {
  4631. struct task_struct *curr = rq->curr;
  4632. struct sched_entity *se = &curr->se, *pse = &p->se;
  4633. struct cfs_rq *cfs_rq = task_cfs_rq(curr);
  4634. int scale = cfs_rq->nr_running >= sched_nr_latency;
  4635. int next_buddy_marked = 0;
  4636. if (unlikely(se == pse))
  4637. return;
  4638. /*
  4639. * This is possible from callers such as attach_tasks(), in which we
  4640. * unconditionally check_prempt_curr() after an enqueue (which may have
  4641. * lead to a throttle). This both saves work and prevents false
  4642. * next-buddy nomination below.
  4643. */
  4644. if (unlikely(throttled_hierarchy(cfs_rq_of(pse))))
  4645. return;
  4646. if (sched_feat(NEXT_BUDDY) && scale && !(wake_flags & WF_FORK)) {
  4647. set_next_buddy(pse);
  4648. next_buddy_marked = 1;
  4649. }
  4650. /*
  4651. * We can come here with TIF_NEED_RESCHED already set from new task
  4652. * wake up path.
  4653. *
  4654. * Note: this also catches the edge-case of curr being in a throttled
  4655. * group (e.g. via set_curr_task), since update_curr() (in the
  4656. * enqueue of curr) will have resulted in resched being set. This
  4657. * prevents us from potentially nominating it as a false LAST_BUDDY
  4658. * below.
  4659. */
  4660. if (test_tsk_need_resched(curr))
  4661. return;
  4662. /* Idle tasks are by definition preempted by non-idle tasks. */
  4663. if (unlikely(curr->policy == SCHED_IDLE) &&
  4664. likely(p->policy != SCHED_IDLE))
  4665. goto preempt;
  4666. /*
  4667. * Batch and idle tasks do not preempt non-idle tasks (their preemption
  4668. * is driven by the tick):
  4669. */
  4670. if (unlikely(p->policy != SCHED_NORMAL) || !sched_feat(WAKEUP_PREEMPTION))
  4671. return;
  4672. find_matching_se(&se, &pse);
  4673. update_curr(cfs_rq_of(se));
  4674. BUG_ON(!pse);
  4675. if (wakeup_preempt_entity(se, pse) == 1) {
  4676. /*
  4677. * Bias pick_next to pick the sched entity that is
  4678. * triggering this preemption.
  4679. */
  4680. if (!next_buddy_marked)
  4681. set_next_buddy(pse);
  4682. goto preempt;
  4683. }
  4684. return;
  4685. preempt:
  4686. resched_curr(rq);
  4687. /*
  4688. * Only set the backward buddy when the current task is still
  4689. * on the rq. This can happen when a wakeup gets interleaved
  4690. * with schedule on the ->pre_schedule() or idle_balance()
  4691. * point, either of which can * drop the rq lock.
  4692. *
  4693. * Also, during early boot the idle thread is in the fair class,
  4694. * for obvious reasons its a bad idea to schedule back to it.
  4695. */
  4696. if (unlikely(!se->on_rq || curr == rq->idle))
  4697. return;
  4698. if (sched_feat(LAST_BUDDY) && scale && entity_is_task(se))
  4699. set_last_buddy(se);
  4700. }
  4701. static struct task_struct *
  4702. pick_next_task_fair(struct rq *rq, struct task_struct *prev, struct pin_cookie cookie)
  4703. {
  4704. struct cfs_rq *cfs_rq = &rq->cfs;
  4705. struct sched_entity *se;
  4706. struct task_struct *p;
  4707. int new_tasks;
  4708. again:
  4709. #ifdef CONFIG_FAIR_GROUP_SCHED
  4710. if (!cfs_rq->nr_running)
  4711. goto idle;
  4712. if (prev->sched_class != &fair_sched_class)
  4713. goto simple;
  4714. /*
  4715. * Because of the set_next_buddy() in dequeue_task_fair() it is rather
  4716. * likely that a next task is from the same cgroup as the current.
  4717. *
  4718. * Therefore attempt to avoid putting and setting the entire cgroup
  4719. * hierarchy, only change the part that actually changes.
  4720. */
  4721. do {
  4722. struct sched_entity *curr = cfs_rq->curr;
  4723. /*
  4724. * Since we got here without doing put_prev_entity() we also
  4725. * have to consider cfs_rq->curr. If it is still a runnable
  4726. * entity, update_curr() will update its vruntime, otherwise
  4727. * forget we've ever seen it.
  4728. */
  4729. if (curr) {
  4730. if (curr->on_rq)
  4731. update_curr(cfs_rq);
  4732. else
  4733. curr = NULL;
  4734. /*
  4735. * This call to check_cfs_rq_runtime() will do the
  4736. * throttle and dequeue its entity in the parent(s).
  4737. * Therefore the 'simple' nr_running test will indeed
  4738. * be correct.
  4739. */
  4740. if (unlikely(check_cfs_rq_runtime(cfs_rq)))
  4741. goto simple;
  4742. }
  4743. se = pick_next_entity(cfs_rq, curr);
  4744. cfs_rq = group_cfs_rq(se);
  4745. } while (cfs_rq);
  4746. p = task_of(se);
  4747. /*
  4748. * Since we haven't yet done put_prev_entity and if the selected task
  4749. * is a different task than we started out with, try and touch the
  4750. * least amount of cfs_rqs.
  4751. */
  4752. if (prev != p) {
  4753. struct sched_entity *pse = &prev->se;
  4754. while (!(cfs_rq = is_same_group(se, pse))) {
  4755. int se_depth = se->depth;
  4756. int pse_depth = pse->depth;
  4757. if (se_depth <= pse_depth) {
  4758. put_prev_entity(cfs_rq_of(pse), pse);
  4759. pse = parent_entity(pse);
  4760. }
  4761. if (se_depth >= pse_depth) {
  4762. set_next_entity(cfs_rq_of(se), se);
  4763. se = parent_entity(se);
  4764. }
  4765. }
  4766. put_prev_entity(cfs_rq, pse);
  4767. set_next_entity(cfs_rq, se);
  4768. }
  4769. if (hrtick_enabled(rq))
  4770. hrtick_start_fair(rq, p);
  4771. return p;
  4772. simple:
  4773. cfs_rq = &rq->cfs;
  4774. #endif
  4775. if (!cfs_rq->nr_running)
  4776. goto idle;
  4777. put_prev_task(rq, prev);
  4778. do {
  4779. se = pick_next_entity(cfs_rq, NULL);
  4780. set_next_entity(cfs_rq, se);
  4781. cfs_rq = group_cfs_rq(se);
  4782. } while (cfs_rq);
  4783. p = task_of(se);
  4784. if (hrtick_enabled(rq))
  4785. hrtick_start_fair(rq, p);
  4786. return p;
  4787. idle:
  4788. /*
  4789. * This is OK, because current is on_cpu, which avoids it being picked
  4790. * for load-balance and preemption/IRQs are still disabled avoiding
  4791. * further scheduler activity on it and we're being very careful to
  4792. * re-start the picking loop.
  4793. */
  4794. lockdep_unpin_lock(&rq->lock, cookie);
  4795. new_tasks = idle_balance(rq);
  4796. lockdep_repin_lock(&rq->lock, cookie);
  4797. /*
  4798. * Because idle_balance() releases (and re-acquires) rq->lock, it is
  4799. * possible for any higher priority task to appear. In that case we
  4800. * must re-start the pick_next_entity() loop.
  4801. */
  4802. if (new_tasks < 0)
  4803. return RETRY_TASK;
  4804. if (new_tasks > 0)
  4805. goto again;
  4806. return NULL;
  4807. }
  4808. /*
  4809. * Account for a descheduled task:
  4810. */
  4811. static void put_prev_task_fair(struct rq *rq, struct task_struct *prev)
  4812. {
  4813. struct sched_entity *se = &prev->se;
  4814. struct cfs_rq *cfs_rq;
  4815. for_each_sched_entity(se) {
  4816. cfs_rq = cfs_rq_of(se);
  4817. put_prev_entity(cfs_rq, se);
  4818. }
  4819. }
  4820. /*
  4821. * sched_yield() is very simple
  4822. *
  4823. * The magic of dealing with the ->skip buddy is in pick_next_entity.
  4824. */
  4825. static void yield_task_fair(struct rq *rq)
  4826. {
  4827. struct task_struct *curr = rq->curr;
  4828. struct cfs_rq *cfs_rq = task_cfs_rq(curr);
  4829. struct sched_entity *se = &curr->se;
  4830. /*
  4831. * Are we the only task in the tree?
  4832. */
  4833. if (unlikely(rq->nr_running == 1))
  4834. return;
  4835. clear_buddies(cfs_rq, se);
  4836. if (curr->policy != SCHED_BATCH) {
  4837. update_rq_clock(rq);
  4838. /*
  4839. * Update run-time statistics of the 'current'.
  4840. */
  4841. update_curr(cfs_rq);
  4842. /*
  4843. * Tell update_rq_clock() that we've just updated,
  4844. * so we don't do microscopic update in schedule()
  4845. * and double the fastpath cost.
  4846. */
  4847. rq_clock_skip_update(rq, true);
  4848. }
  4849. set_skip_buddy(se);
  4850. }
  4851. static bool yield_to_task_fair(struct rq *rq, struct task_struct *p, bool preempt)
  4852. {
  4853. struct sched_entity *se = &p->se;
  4854. /* throttled hierarchies are not runnable */
  4855. if (!se->on_rq || throttled_hierarchy(cfs_rq_of(se)))
  4856. return false;
  4857. /* Tell the scheduler that we'd really like pse to run next. */
  4858. set_next_buddy(se);
  4859. yield_task_fair(rq);
  4860. return true;
  4861. }
  4862. #ifdef CONFIG_SMP
  4863. /**************************************************
  4864. * Fair scheduling class load-balancing methods.
  4865. *
  4866. * BASICS
  4867. *
  4868. * The purpose of load-balancing is to achieve the same basic fairness the
  4869. * per-cpu scheduler provides, namely provide a proportional amount of compute
  4870. * time to each task. This is expressed in the following equation:
  4871. *
  4872. * W_i,n/P_i == W_j,n/P_j for all i,j (1)
  4873. *
  4874. * Where W_i,n is the n-th weight average for cpu i. The instantaneous weight
  4875. * W_i,0 is defined as:
  4876. *
  4877. * W_i,0 = \Sum_j w_i,j (2)
  4878. *
  4879. * Where w_i,j is the weight of the j-th runnable task on cpu i. This weight
  4880. * is derived from the nice value as per sched_prio_to_weight[].
  4881. *
  4882. * The weight average is an exponential decay average of the instantaneous
  4883. * weight:
  4884. *
  4885. * W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0 (3)
  4886. *
  4887. * C_i is the compute capacity of cpu i, typically it is the
  4888. * fraction of 'recent' time available for SCHED_OTHER task execution. But it
  4889. * can also include other factors [XXX].
  4890. *
  4891. * To achieve this balance we define a measure of imbalance which follows
  4892. * directly from (1):
  4893. *
  4894. * imb_i,j = max{ avg(W/C), W_i/C_i } - min{ avg(W/C), W_j/C_j } (4)
  4895. *
  4896. * We them move tasks around to minimize the imbalance. In the continuous
  4897. * function space it is obvious this converges, in the discrete case we get
  4898. * a few fun cases generally called infeasible weight scenarios.
  4899. *
  4900. * [XXX expand on:
  4901. * - infeasible weights;
  4902. * - local vs global optima in the discrete case. ]
  4903. *
  4904. *
  4905. * SCHED DOMAINS
  4906. *
  4907. * In order to solve the imbalance equation (4), and avoid the obvious O(n^2)
  4908. * for all i,j solution, we create a tree of cpus that follows the hardware
  4909. * topology where each level pairs two lower groups (or better). This results
  4910. * in O(log n) layers. Furthermore we reduce the number of cpus going up the
  4911. * tree to only the first of the previous level and we decrease the frequency
  4912. * of load-balance at each level inv. proportional to the number of cpus in
  4913. * the groups.
  4914. *
  4915. * This yields:
  4916. *
  4917. * log_2 n 1 n
  4918. * \Sum { --- * --- * 2^i } = O(n) (5)
  4919. * i = 0 2^i 2^i
  4920. * `- size of each group
  4921. * | | `- number of cpus doing load-balance
  4922. * | `- freq
  4923. * `- sum over all levels
  4924. *
  4925. * Coupled with a limit on how many tasks we can migrate every balance pass,
  4926. * this makes (5) the runtime complexity of the balancer.
  4927. *
  4928. * An important property here is that each CPU is still (indirectly) connected
  4929. * to every other cpu in at most O(log n) steps:
  4930. *
  4931. * The adjacency matrix of the resulting graph is given by:
  4932. *
  4933. * log_2 n
  4934. * A_i,j = \Union (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1) (6)
  4935. * k = 0
  4936. *
  4937. * And you'll find that:
  4938. *
  4939. * A^(log_2 n)_i,j != 0 for all i,j (7)
  4940. *
  4941. * Showing there's indeed a path between every cpu in at most O(log n) steps.
  4942. * The task movement gives a factor of O(m), giving a convergence complexity
  4943. * of:
  4944. *
  4945. * O(nm log n), n := nr_cpus, m := nr_tasks (8)
  4946. *
  4947. *
  4948. * WORK CONSERVING
  4949. *
  4950. * In order to avoid CPUs going idle while there's still work to do, new idle
  4951. * balancing is more aggressive and has the newly idle cpu iterate up the domain
  4952. * tree itself instead of relying on other CPUs to bring it work.
  4953. *
  4954. * This adds some complexity to both (5) and (8) but it reduces the total idle
  4955. * time.
  4956. *
  4957. * [XXX more?]
  4958. *
  4959. *
  4960. * CGROUPS
  4961. *
  4962. * Cgroups make a horror show out of (2), instead of a simple sum we get:
  4963. *
  4964. * s_k,i
  4965. * W_i,0 = \Sum_j \Prod_k w_k * ----- (9)
  4966. * S_k
  4967. *
  4968. * Where
  4969. *
  4970. * s_k,i = \Sum_j w_i,j,k and S_k = \Sum_i s_k,i (10)
  4971. *
  4972. * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on cpu i.
  4973. *
  4974. * The big problem is S_k, its a global sum needed to compute a local (W_i)
  4975. * property.
  4976. *
  4977. * [XXX write more on how we solve this.. _after_ merging pjt's patches that
  4978. * rewrite all of this once again.]
  4979. */
  4980. static unsigned long __read_mostly max_load_balance_interval = HZ/10;
  4981. enum fbq_type { regular, remote, all };
  4982. #define LBF_ALL_PINNED 0x01
  4983. #define LBF_NEED_BREAK 0x02
  4984. #define LBF_DST_PINNED 0x04
  4985. #define LBF_SOME_PINNED 0x08
  4986. struct lb_env {
  4987. struct sched_domain *sd;
  4988. struct rq *src_rq;
  4989. int src_cpu;
  4990. int dst_cpu;
  4991. struct rq *dst_rq;
  4992. struct cpumask *dst_grpmask;
  4993. int new_dst_cpu;
  4994. enum cpu_idle_type idle;
  4995. long imbalance;
  4996. /* The set of CPUs under consideration for load-balancing */
  4997. struct cpumask *cpus;
  4998. unsigned int flags;
  4999. unsigned int loop;
  5000. unsigned int loop_break;
  5001. unsigned int loop_max;
  5002. enum fbq_type fbq_type;
  5003. struct list_head tasks;
  5004. };
  5005. /*
  5006. * Is this task likely cache-hot:
  5007. */
  5008. static int task_hot(struct task_struct *p, struct lb_env *env)
  5009. {
  5010. s64 delta;
  5011. lockdep_assert_held(&env->src_rq->lock);
  5012. if (p->sched_class != &fair_sched_class)
  5013. return 0;
  5014. if (unlikely(p->policy == SCHED_IDLE))
  5015. return 0;
  5016. /*
  5017. * Buddy candidates are cache hot:
  5018. */
  5019. if (sched_feat(CACHE_HOT_BUDDY) && env->dst_rq->nr_running &&
  5020. (&p->se == cfs_rq_of(&p->se)->next ||
  5021. &p->se == cfs_rq_of(&p->se)->last))
  5022. return 1;
  5023. if (sysctl_sched_migration_cost == -1)
  5024. return 1;
  5025. if (sysctl_sched_migration_cost == 0)
  5026. return 0;
  5027. delta = rq_clock_task(env->src_rq) - p->se.exec_start;
  5028. return delta < (s64)sysctl_sched_migration_cost;
  5029. }
  5030. #ifdef CONFIG_NUMA_BALANCING
  5031. /*
  5032. * Returns 1, if task migration degrades locality
  5033. * Returns 0, if task migration improves locality i.e migration preferred.
  5034. * Returns -1, if task migration is not affected by locality.
  5035. */
  5036. static int migrate_degrades_locality(struct task_struct *p, struct lb_env *env)
  5037. {
  5038. struct numa_group *numa_group = rcu_dereference(p->numa_group);
  5039. unsigned long src_faults, dst_faults;
  5040. int src_nid, dst_nid;
  5041. if (!static_branch_likely(&sched_numa_balancing))
  5042. return -1;
  5043. if (!p->numa_faults || !(env->sd->flags & SD_NUMA))
  5044. return -1;
  5045. src_nid = cpu_to_node(env->src_cpu);
  5046. dst_nid = cpu_to_node(env->dst_cpu);
  5047. if (src_nid == dst_nid)
  5048. return -1;
  5049. /* Migrating away from the preferred node is always bad. */
  5050. if (src_nid == p->numa_preferred_nid) {
  5051. if (env->src_rq->nr_running > env->src_rq->nr_preferred_running)
  5052. return 1;
  5053. else
  5054. return -1;
  5055. }
  5056. /* Encourage migration to the preferred node. */
  5057. if (dst_nid == p->numa_preferred_nid)
  5058. return 0;
  5059. if (numa_group) {
  5060. src_faults = group_faults(p, src_nid);
  5061. dst_faults = group_faults(p, dst_nid);
  5062. } else {
  5063. src_faults = task_faults(p, src_nid);
  5064. dst_faults = task_faults(p, dst_nid);
  5065. }
  5066. return dst_faults < src_faults;
  5067. }
  5068. #else
  5069. static inline int migrate_degrades_locality(struct task_struct *p,
  5070. struct lb_env *env)
  5071. {
  5072. return -1;
  5073. }
  5074. #endif
  5075. /*
  5076. * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
  5077. */
  5078. static
  5079. int can_migrate_task(struct task_struct *p, struct lb_env *env)
  5080. {
  5081. int tsk_cache_hot;
  5082. lockdep_assert_held(&env->src_rq->lock);
  5083. /*
  5084. * We do not migrate tasks that are:
  5085. * 1) throttled_lb_pair, or
  5086. * 2) cannot be migrated to this CPU due to cpus_allowed, or
  5087. * 3) running (obviously), or
  5088. * 4) are cache-hot on their current CPU.
  5089. */
  5090. if (throttled_lb_pair(task_group(p), env->src_cpu, env->dst_cpu))
  5091. return 0;
  5092. if (!cpumask_test_cpu(env->dst_cpu, tsk_cpus_allowed(p))) {
  5093. int cpu;
  5094. schedstat_inc(p, se.statistics.nr_failed_migrations_affine);
  5095. env->flags |= LBF_SOME_PINNED;
  5096. /*
  5097. * Remember if this task can be migrated to any other cpu in
  5098. * our sched_group. We may want to revisit it if we couldn't
  5099. * meet load balance goals by pulling other tasks on src_cpu.
  5100. *
  5101. * Also avoid computing new_dst_cpu if we have already computed
  5102. * one in current iteration.
  5103. */
  5104. if (!env->dst_grpmask || (env->flags & LBF_DST_PINNED))
  5105. return 0;
  5106. /* Prevent to re-select dst_cpu via env's cpus */
  5107. for_each_cpu_and(cpu, env->dst_grpmask, env->cpus) {
  5108. if (cpumask_test_cpu(cpu, tsk_cpus_allowed(p))) {
  5109. env->flags |= LBF_DST_PINNED;
  5110. env->new_dst_cpu = cpu;
  5111. break;
  5112. }
  5113. }
  5114. return 0;
  5115. }
  5116. /* Record that we found atleast one task that could run on dst_cpu */
  5117. env->flags &= ~LBF_ALL_PINNED;
  5118. if (task_running(env->src_rq, p)) {
  5119. schedstat_inc(p, se.statistics.nr_failed_migrations_running);
  5120. return 0;
  5121. }
  5122. /*
  5123. * Aggressive migration if:
  5124. * 1) destination numa is preferred
  5125. * 2) task is cache cold, or
  5126. * 3) too many balance attempts have failed.
  5127. */
  5128. tsk_cache_hot = migrate_degrades_locality(p, env);
  5129. if (tsk_cache_hot == -1)
  5130. tsk_cache_hot = task_hot(p, env);
  5131. if (tsk_cache_hot <= 0 ||
  5132. env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
  5133. if (tsk_cache_hot == 1) {
  5134. schedstat_inc(env->sd, lb_hot_gained[env->idle]);
  5135. schedstat_inc(p, se.statistics.nr_forced_migrations);
  5136. }
  5137. return 1;
  5138. }
  5139. schedstat_inc(p, se.statistics.nr_failed_migrations_hot);
  5140. return 0;
  5141. }
  5142. /*
  5143. * detach_task() -- detach the task for the migration specified in env
  5144. */
  5145. static void detach_task(struct task_struct *p, struct lb_env *env)
  5146. {
  5147. lockdep_assert_held(&env->src_rq->lock);
  5148. p->on_rq = TASK_ON_RQ_MIGRATING;
  5149. deactivate_task(env->src_rq, p, 0);
  5150. set_task_cpu(p, env->dst_cpu);
  5151. }
  5152. /*
  5153. * detach_one_task() -- tries to dequeue exactly one task from env->src_rq, as
  5154. * part of active balancing operations within "domain".
  5155. *
  5156. * Returns a task if successful and NULL otherwise.
  5157. */
  5158. static struct task_struct *detach_one_task(struct lb_env *env)
  5159. {
  5160. struct task_struct *p, *n;
  5161. lockdep_assert_held(&env->src_rq->lock);
  5162. list_for_each_entry_safe(p, n, &env->src_rq->cfs_tasks, se.group_node) {
  5163. if (!can_migrate_task(p, env))
  5164. continue;
  5165. detach_task(p, env);
  5166. /*
  5167. * Right now, this is only the second place where
  5168. * lb_gained[env->idle] is updated (other is detach_tasks)
  5169. * so we can safely collect stats here rather than
  5170. * inside detach_tasks().
  5171. */
  5172. schedstat_inc(env->sd, lb_gained[env->idle]);
  5173. return p;
  5174. }
  5175. return NULL;
  5176. }
  5177. static const unsigned int sched_nr_migrate_break = 32;
  5178. /*
  5179. * detach_tasks() -- tries to detach up to imbalance weighted load from
  5180. * busiest_rq, as part of a balancing operation within domain "sd".
  5181. *
  5182. * Returns number of detached tasks if successful and 0 otherwise.
  5183. */
  5184. static int detach_tasks(struct lb_env *env)
  5185. {
  5186. struct list_head *tasks = &env->src_rq->cfs_tasks;
  5187. struct task_struct *p;
  5188. unsigned long load;
  5189. int detached = 0;
  5190. lockdep_assert_held(&env->src_rq->lock);
  5191. if (env->imbalance <= 0)
  5192. return 0;
  5193. while (!list_empty(tasks)) {
  5194. /*
  5195. * We don't want to steal all, otherwise we may be treated likewise,
  5196. * which could at worst lead to a livelock crash.
  5197. */
  5198. if (env->idle != CPU_NOT_IDLE && env->src_rq->nr_running <= 1)
  5199. break;
  5200. p = list_first_entry(tasks, struct task_struct, se.group_node);
  5201. env->loop++;
  5202. /* We've more or less seen every task there is, call it quits */
  5203. if (env->loop > env->loop_max)
  5204. break;
  5205. /* take a breather every nr_migrate tasks */
  5206. if (env->loop > env->loop_break) {
  5207. env->loop_break += sched_nr_migrate_break;
  5208. env->flags |= LBF_NEED_BREAK;
  5209. break;
  5210. }
  5211. if (!can_migrate_task(p, env))
  5212. goto next;
  5213. load = task_h_load(p);
  5214. if (sched_feat(LB_MIN) && load < 16 && !env->sd->nr_balance_failed)
  5215. goto next;
  5216. if ((load / 2) > env->imbalance)
  5217. goto next;
  5218. detach_task(p, env);
  5219. list_add(&p->se.group_node, &env->tasks);
  5220. detached++;
  5221. env->imbalance -= load;
  5222. #ifdef CONFIG_PREEMPT
  5223. /*
  5224. * NEWIDLE balancing is a source of latency, so preemptible
  5225. * kernels will stop after the first task is detached to minimize
  5226. * the critical section.
  5227. */
  5228. if (env->idle == CPU_NEWLY_IDLE)
  5229. break;
  5230. #endif
  5231. /*
  5232. * We only want to steal up to the prescribed amount of
  5233. * weighted load.
  5234. */
  5235. if (env->imbalance <= 0)
  5236. break;
  5237. continue;
  5238. next:
  5239. list_move_tail(&p->se.group_node, tasks);
  5240. }
  5241. /*
  5242. * Right now, this is one of only two places we collect this stat
  5243. * so we can safely collect detach_one_task() stats here rather
  5244. * than inside detach_one_task().
  5245. */
  5246. schedstat_add(env->sd, lb_gained[env->idle], detached);
  5247. return detached;
  5248. }
  5249. /*
  5250. * attach_task() -- attach the task detached by detach_task() to its new rq.
  5251. */
  5252. static void attach_task(struct rq *rq, struct task_struct *p)
  5253. {
  5254. lockdep_assert_held(&rq->lock);
  5255. BUG_ON(task_rq(p) != rq);
  5256. activate_task(rq, p, 0);
  5257. p->on_rq = TASK_ON_RQ_QUEUED;
  5258. check_preempt_curr(rq, p, 0);
  5259. }
  5260. /*
  5261. * attach_one_task() -- attaches the task returned from detach_one_task() to
  5262. * its new rq.
  5263. */
  5264. static void attach_one_task(struct rq *rq, struct task_struct *p)
  5265. {
  5266. raw_spin_lock(&rq->lock);
  5267. attach_task(rq, p);
  5268. raw_spin_unlock(&rq->lock);
  5269. }
  5270. /*
  5271. * attach_tasks() -- attaches all tasks detached by detach_tasks() to their
  5272. * new rq.
  5273. */
  5274. static void attach_tasks(struct lb_env *env)
  5275. {
  5276. struct list_head *tasks = &env->tasks;
  5277. struct task_struct *p;
  5278. raw_spin_lock(&env->dst_rq->lock);
  5279. while (!list_empty(tasks)) {
  5280. p = list_first_entry(tasks, struct task_struct, se.group_node);
  5281. list_del_init(&p->se.group_node);
  5282. attach_task(env->dst_rq, p);
  5283. }
  5284. raw_spin_unlock(&env->dst_rq->lock);
  5285. }
  5286. #ifdef CONFIG_FAIR_GROUP_SCHED
  5287. static void update_blocked_averages(int cpu)
  5288. {
  5289. struct rq *rq = cpu_rq(cpu);
  5290. struct cfs_rq *cfs_rq;
  5291. unsigned long flags;
  5292. raw_spin_lock_irqsave(&rq->lock, flags);
  5293. update_rq_clock(rq);
  5294. /*
  5295. * Iterates the task_group tree in a bottom up fashion, see
  5296. * list_add_leaf_cfs_rq() for details.
  5297. */
  5298. for_each_leaf_cfs_rq(rq, cfs_rq) {
  5299. /* throttled entities do not contribute to load */
  5300. if (throttled_hierarchy(cfs_rq))
  5301. continue;
  5302. if (update_cfs_rq_load_avg(cfs_rq_clock_task(cfs_rq), cfs_rq, true))
  5303. update_tg_load_avg(cfs_rq, 0);
  5304. }
  5305. raw_spin_unlock_irqrestore(&rq->lock, flags);
  5306. }
  5307. /*
  5308. * Compute the hierarchical load factor for cfs_rq and all its ascendants.
  5309. * This needs to be done in a top-down fashion because the load of a child
  5310. * group is a fraction of its parents load.
  5311. */
  5312. static void update_cfs_rq_h_load(struct cfs_rq *cfs_rq)
  5313. {
  5314. struct rq *rq = rq_of(cfs_rq);
  5315. struct sched_entity *se = cfs_rq->tg->se[cpu_of(rq)];
  5316. unsigned long now = jiffies;
  5317. unsigned long load;
  5318. if (cfs_rq->last_h_load_update == now)
  5319. return;
  5320. cfs_rq->h_load_next = NULL;
  5321. for_each_sched_entity(se) {
  5322. cfs_rq = cfs_rq_of(se);
  5323. cfs_rq->h_load_next = se;
  5324. if (cfs_rq->last_h_load_update == now)
  5325. break;
  5326. }
  5327. if (!se) {
  5328. cfs_rq->h_load = cfs_rq_load_avg(cfs_rq);
  5329. cfs_rq->last_h_load_update = now;
  5330. }
  5331. while ((se = cfs_rq->h_load_next) != NULL) {
  5332. load = cfs_rq->h_load;
  5333. load = div64_ul(load * se->avg.load_avg,
  5334. cfs_rq_load_avg(cfs_rq) + 1);
  5335. cfs_rq = group_cfs_rq(se);
  5336. cfs_rq->h_load = load;
  5337. cfs_rq->last_h_load_update = now;
  5338. }
  5339. }
  5340. static unsigned long task_h_load(struct task_struct *p)
  5341. {
  5342. struct cfs_rq *cfs_rq = task_cfs_rq(p);
  5343. update_cfs_rq_h_load(cfs_rq);
  5344. return div64_ul(p->se.avg.load_avg * cfs_rq->h_load,
  5345. cfs_rq_load_avg(cfs_rq) + 1);
  5346. }
  5347. #else
  5348. static inline void update_blocked_averages(int cpu)
  5349. {
  5350. struct rq *rq = cpu_rq(cpu);
  5351. struct cfs_rq *cfs_rq = &rq->cfs;
  5352. unsigned long flags;
  5353. raw_spin_lock_irqsave(&rq->lock, flags);
  5354. update_rq_clock(rq);
  5355. update_cfs_rq_load_avg(cfs_rq_clock_task(cfs_rq), cfs_rq, true);
  5356. raw_spin_unlock_irqrestore(&rq->lock, flags);
  5357. }
  5358. static unsigned long task_h_load(struct task_struct *p)
  5359. {
  5360. return p->se.avg.load_avg;
  5361. }
  5362. #endif
  5363. /********** Helpers for find_busiest_group ************************/
  5364. enum group_type {
  5365. group_other = 0,
  5366. group_imbalanced,
  5367. group_overloaded,
  5368. };
  5369. /*
  5370. * sg_lb_stats - stats of a sched_group required for load_balancing
  5371. */
  5372. struct sg_lb_stats {
  5373. unsigned long avg_load; /*Avg load across the CPUs of the group */
  5374. unsigned long group_load; /* Total load over the CPUs of the group */
  5375. unsigned long sum_weighted_load; /* Weighted load of group's tasks */
  5376. unsigned long load_per_task;
  5377. unsigned long group_capacity;
  5378. unsigned long group_util; /* Total utilization of the group */
  5379. unsigned int sum_nr_running; /* Nr tasks running in the group */
  5380. unsigned int idle_cpus;
  5381. unsigned int group_weight;
  5382. enum group_type group_type;
  5383. int group_no_capacity;
  5384. #ifdef CONFIG_NUMA_BALANCING
  5385. unsigned int nr_numa_running;
  5386. unsigned int nr_preferred_running;
  5387. #endif
  5388. };
  5389. /*
  5390. * sd_lb_stats - Structure to store the statistics of a sched_domain
  5391. * during load balancing.
  5392. */
  5393. struct sd_lb_stats {
  5394. struct sched_group *busiest; /* Busiest group in this sd */
  5395. struct sched_group *local; /* Local group in this sd */
  5396. unsigned long total_load; /* Total load of all groups in sd */
  5397. unsigned long total_capacity; /* Total capacity of all groups in sd */
  5398. unsigned long avg_load; /* Average load across all groups in sd */
  5399. struct sg_lb_stats busiest_stat;/* Statistics of the busiest group */
  5400. struct sg_lb_stats local_stat; /* Statistics of the local group */
  5401. };
  5402. static inline void init_sd_lb_stats(struct sd_lb_stats *sds)
  5403. {
  5404. /*
  5405. * Skimp on the clearing to avoid duplicate work. We can avoid clearing
  5406. * local_stat because update_sg_lb_stats() does a full clear/assignment.
  5407. * We must however clear busiest_stat::avg_load because
  5408. * update_sd_pick_busiest() reads this before assignment.
  5409. */
  5410. *sds = (struct sd_lb_stats){
  5411. .busiest = NULL,
  5412. .local = NULL,
  5413. .total_load = 0UL,
  5414. .total_capacity = 0UL,
  5415. .busiest_stat = {
  5416. .avg_load = 0UL,
  5417. .sum_nr_running = 0,
  5418. .group_type = group_other,
  5419. },
  5420. };
  5421. }
  5422. /**
  5423. * get_sd_load_idx - Obtain the load index for a given sched domain.
  5424. * @sd: The sched_domain whose load_idx is to be obtained.
  5425. * @idle: The idle status of the CPU for whose sd load_idx is obtained.
  5426. *
  5427. * Return: The load index.
  5428. */
  5429. static inline int get_sd_load_idx(struct sched_domain *sd,
  5430. enum cpu_idle_type idle)
  5431. {
  5432. int load_idx;
  5433. switch (idle) {
  5434. case CPU_NOT_IDLE:
  5435. load_idx = sd->busy_idx;
  5436. break;
  5437. case CPU_NEWLY_IDLE:
  5438. load_idx = sd->newidle_idx;
  5439. break;
  5440. default:
  5441. load_idx = sd->idle_idx;
  5442. break;
  5443. }
  5444. return load_idx;
  5445. }
  5446. static unsigned long scale_rt_capacity(int cpu)
  5447. {
  5448. struct rq *rq = cpu_rq(cpu);
  5449. u64 total, used, age_stamp, avg;
  5450. s64 delta;
  5451. /*
  5452. * Since we're reading these variables without serialization make sure
  5453. * we read them once before doing sanity checks on them.
  5454. */
  5455. age_stamp = READ_ONCE(rq->age_stamp);
  5456. avg = READ_ONCE(rq->rt_avg);
  5457. delta = __rq_clock_broken(rq) - age_stamp;
  5458. if (unlikely(delta < 0))
  5459. delta = 0;
  5460. total = sched_avg_period() + delta;
  5461. used = div_u64(avg, total);
  5462. if (likely(used < SCHED_CAPACITY_SCALE))
  5463. return SCHED_CAPACITY_SCALE - used;
  5464. return 1;
  5465. }
  5466. static void update_cpu_capacity(struct sched_domain *sd, int cpu)
  5467. {
  5468. unsigned long capacity = arch_scale_cpu_capacity(sd, cpu);
  5469. struct sched_group *sdg = sd->groups;
  5470. cpu_rq(cpu)->cpu_capacity_orig = capacity;
  5471. capacity *= scale_rt_capacity(cpu);
  5472. capacity >>= SCHED_CAPACITY_SHIFT;
  5473. if (!capacity)
  5474. capacity = 1;
  5475. cpu_rq(cpu)->cpu_capacity = capacity;
  5476. sdg->sgc->capacity = capacity;
  5477. }
  5478. void update_group_capacity(struct sched_domain *sd, int cpu)
  5479. {
  5480. struct sched_domain *child = sd->child;
  5481. struct sched_group *group, *sdg = sd->groups;
  5482. unsigned long capacity;
  5483. unsigned long interval;
  5484. interval = msecs_to_jiffies(sd->balance_interval);
  5485. interval = clamp(interval, 1UL, max_load_balance_interval);
  5486. sdg->sgc->next_update = jiffies + interval;
  5487. if (!child) {
  5488. update_cpu_capacity(sd, cpu);
  5489. return;
  5490. }
  5491. capacity = 0;
  5492. if (child->flags & SD_OVERLAP) {
  5493. /*
  5494. * SD_OVERLAP domains cannot assume that child groups
  5495. * span the current group.
  5496. */
  5497. for_each_cpu(cpu, sched_group_cpus(sdg)) {
  5498. struct sched_group_capacity *sgc;
  5499. struct rq *rq = cpu_rq(cpu);
  5500. /*
  5501. * build_sched_domains() -> init_sched_groups_capacity()
  5502. * gets here before we've attached the domains to the
  5503. * runqueues.
  5504. *
  5505. * Use capacity_of(), which is set irrespective of domains
  5506. * in update_cpu_capacity().
  5507. *
  5508. * This avoids capacity from being 0 and
  5509. * causing divide-by-zero issues on boot.
  5510. */
  5511. if (unlikely(!rq->sd)) {
  5512. capacity += capacity_of(cpu);
  5513. continue;
  5514. }
  5515. sgc = rq->sd->groups->sgc;
  5516. capacity += sgc->capacity;
  5517. }
  5518. } else {
  5519. /*
  5520. * !SD_OVERLAP domains can assume that child groups
  5521. * span the current group.
  5522. */
  5523. group = child->groups;
  5524. do {
  5525. capacity += group->sgc->capacity;
  5526. group = group->next;
  5527. } while (group != child->groups);
  5528. }
  5529. sdg->sgc->capacity = capacity;
  5530. }
  5531. /*
  5532. * Check whether the capacity of the rq has been noticeably reduced by side
  5533. * activity. The imbalance_pct is used for the threshold.
  5534. * Return true is the capacity is reduced
  5535. */
  5536. static inline int
  5537. check_cpu_capacity(struct rq *rq, struct sched_domain *sd)
  5538. {
  5539. return ((rq->cpu_capacity * sd->imbalance_pct) <
  5540. (rq->cpu_capacity_orig * 100));
  5541. }
  5542. /*
  5543. * Group imbalance indicates (and tries to solve) the problem where balancing
  5544. * groups is inadequate due to tsk_cpus_allowed() constraints.
  5545. *
  5546. * Imagine a situation of two groups of 4 cpus each and 4 tasks each with a
  5547. * cpumask covering 1 cpu of the first group and 3 cpus of the second group.
  5548. * Something like:
  5549. *
  5550. * { 0 1 2 3 } { 4 5 6 7 }
  5551. * * * * *
  5552. *
  5553. * If we were to balance group-wise we'd place two tasks in the first group and
  5554. * two tasks in the second group. Clearly this is undesired as it will overload
  5555. * cpu 3 and leave one of the cpus in the second group unused.
  5556. *
  5557. * The current solution to this issue is detecting the skew in the first group
  5558. * by noticing the lower domain failed to reach balance and had difficulty
  5559. * moving tasks due to affinity constraints.
  5560. *
  5561. * When this is so detected; this group becomes a candidate for busiest; see
  5562. * update_sd_pick_busiest(). And calculate_imbalance() and
  5563. * find_busiest_group() avoid some of the usual balance conditions to allow it
  5564. * to create an effective group imbalance.
  5565. *
  5566. * This is a somewhat tricky proposition since the next run might not find the
  5567. * group imbalance and decide the groups need to be balanced again. A most
  5568. * subtle and fragile situation.
  5569. */
  5570. static inline int sg_imbalanced(struct sched_group *group)
  5571. {
  5572. return group->sgc->imbalance;
  5573. }
  5574. /*
  5575. * group_has_capacity returns true if the group has spare capacity that could
  5576. * be used by some tasks.
  5577. * We consider that a group has spare capacity if the * number of task is
  5578. * smaller than the number of CPUs or if the utilization is lower than the
  5579. * available capacity for CFS tasks.
  5580. * For the latter, we use a threshold to stabilize the state, to take into
  5581. * account the variance of the tasks' load and to return true if the available
  5582. * capacity in meaningful for the load balancer.
  5583. * As an example, an available capacity of 1% can appear but it doesn't make
  5584. * any benefit for the load balance.
  5585. */
  5586. static inline bool
  5587. group_has_capacity(struct lb_env *env, struct sg_lb_stats *sgs)
  5588. {
  5589. if (sgs->sum_nr_running < sgs->group_weight)
  5590. return true;
  5591. if ((sgs->group_capacity * 100) >
  5592. (sgs->group_util * env->sd->imbalance_pct))
  5593. return true;
  5594. return false;
  5595. }
  5596. /*
  5597. * group_is_overloaded returns true if the group has more tasks than it can
  5598. * handle.
  5599. * group_is_overloaded is not equals to !group_has_capacity because a group
  5600. * with the exact right number of tasks, has no more spare capacity but is not
  5601. * overloaded so both group_has_capacity and group_is_overloaded return
  5602. * false.
  5603. */
  5604. static inline bool
  5605. group_is_overloaded(struct lb_env *env, struct sg_lb_stats *sgs)
  5606. {
  5607. if (sgs->sum_nr_running <= sgs->group_weight)
  5608. return false;
  5609. if ((sgs->group_capacity * 100) <
  5610. (sgs->group_util * env->sd->imbalance_pct))
  5611. return true;
  5612. return false;
  5613. }
  5614. static inline enum
  5615. group_type group_classify(struct sched_group *group,
  5616. struct sg_lb_stats *sgs)
  5617. {
  5618. if (sgs->group_no_capacity)
  5619. return group_overloaded;
  5620. if (sg_imbalanced(group))
  5621. return group_imbalanced;
  5622. return group_other;
  5623. }
  5624. /**
  5625. * update_sg_lb_stats - Update sched_group's statistics for load balancing.
  5626. * @env: The load balancing environment.
  5627. * @group: sched_group whose statistics are to be updated.
  5628. * @load_idx: Load index of sched_domain of this_cpu for load calc.
  5629. * @local_group: Does group contain this_cpu.
  5630. * @sgs: variable to hold the statistics for this group.
  5631. * @overload: Indicate more than one runnable task for any CPU.
  5632. */
  5633. static inline void update_sg_lb_stats(struct lb_env *env,
  5634. struct sched_group *group, int load_idx,
  5635. int local_group, struct sg_lb_stats *sgs,
  5636. bool *overload)
  5637. {
  5638. unsigned long load;
  5639. int i, nr_running;
  5640. memset(sgs, 0, sizeof(*sgs));
  5641. for_each_cpu_and(i, sched_group_cpus(group), env->cpus) {
  5642. struct rq *rq = cpu_rq(i);
  5643. /* Bias balancing toward cpus of our domain */
  5644. if (local_group)
  5645. load = target_load(i, load_idx);
  5646. else
  5647. load = source_load(i, load_idx);
  5648. sgs->group_load += load;
  5649. sgs->group_util += cpu_util(i);
  5650. sgs->sum_nr_running += rq->cfs.h_nr_running;
  5651. nr_running = rq->nr_running;
  5652. if (nr_running > 1)
  5653. *overload = true;
  5654. #ifdef CONFIG_NUMA_BALANCING
  5655. sgs->nr_numa_running += rq->nr_numa_running;
  5656. sgs->nr_preferred_running += rq->nr_preferred_running;
  5657. #endif
  5658. sgs->sum_weighted_load += weighted_cpuload(i);
  5659. /*
  5660. * No need to call idle_cpu() if nr_running is not 0
  5661. */
  5662. if (!nr_running && idle_cpu(i))
  5663. sgs->idle_cpus++;
  5664. }
  5665. /* Adjust by relative CPU capacity of the group */
  5666. sgs->group_capacity = group->sgc->capacity;
  5667. sgs->avg_load = (sgs->group_load*SCHED_CAPACITY_SCALE) / sgs->group_capacity;
  5668. if (sgs->sum_nr_running)
  5669. sgs->load_per_task = sgs->sum_weighted_load / sgs->sum_nr_running;
  5670. sgs->group_weight = group->group_weight;
  5671. sgs->group_no_capacity = group_is_overloaded(env, sgs);
  5672. sgs->group_type = group_classify(group, sgs);
  5673. }
  5674. /**
  5675. * update_sd_pick_busiest - return 1 on busiest group
  5676. * @env: The load balancing environment.
  5677. * @sds: sched_domain statistics
  5678. * @sg: sched_group candidate to be checked for being the busiest
  5679. * @sgs: sched_group statistics
  5680. *
  5681. * Determine if @sg is a busier group than the previously selected
  5682. * busiest group.
  5683. *
  5684. * Return: %true if @sg is a busier group than the previously selected
  5685. * busiest group. %false otherwise.
  5686. */
  5687. static bool update_sd_pick_busiest(struct lb_env *env,
  5688. struct sd_lb_stats *sds,
  5689. struct sched_group *sg,
  5690. struct sg_lb_stats *sgs)
  5691. {
  5692. struct sg_lb_stats *busiest = &sds->busiest_stat;
  5693. if (sgs->group_type > busiest->group_type)
  5694. return true;
  5695. if (sgs->group_type < busiest->group_type)
  5696. return false;
  5697. if (sgs->avg_load <= busiest->avg_load)
  5698. return false;
  5699. /* This is the busiest node in its class. */
  5700. if (!(env->sd->flags & SD_ASYM_PACKING))
  5701. return true;
  5702. /* No ASYM_PACKING if target cpu is already busy */
  5703. if (env->idle == CPU_NOT_IDLE)
  5704. return true;
  5705. /*
  5706. * ASYM_PACKING needs to move all the work to the lowest
  5707. * numbered CPUs in the group, therefore mark all groups
  5708. * higher than ourself as busy.
  5709. */
  5710. if (sgs->sum_nr_running && env->dst_cpu < group_first_cpu(sg)) {
  5711. if (!sds->busiest)
  5712. return true;
  5713. /* Prefer to move from highest possible cpu's work */
  5714. if (group_first_cpu(sds->busiest) < group_first_cpu(sg))
  5715. return true;
  5716. }
  5717. return false;
  5718. }
  5719. #ifdef CONFIG_NUMA_BALANCING
  5720. static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
  5721. {
  5722. if (sgs->sum_nr_running > sgs->nr_numa_running)
  5723. return regular;
  5724. if (sgs->sum_nr_running > sgs->nr_preferred_running)
  5725. return remote;
  5726. return all;
  5727. }
  5728. static inline enum fbq_type fbq_classify_rq(struct rq *rq)
  5729. {
  5730. if (rq->nr_running > rq->nr_numa_running)
  5731. return regular;
  5732. if (rq->nr_running > rq->nr_preferred_running)
  5733. return remote;
  5734. return all;
  5735. }
  5736. #else
  5737. static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
  5738. {
  5739. return all;
  5740. }
  5741. static inline enum fbq_type fbq_classify_rq(struct rq *rq)
  5742. {
  5743. return regular;
  5744. }
  5745. #endif /* CONFIG_NUMA_BALANCING */
  5746. /**
  5747. * update_sd_lb_stats - Update sched_domain's statistics for load balancing.
  5748. * @env: The load balancing environment.
  5749. * @sds: variable to hold the statistics for this sched_domain.
  5750. */
  5751. static inline void update_sd_lb_stats(struct lb_env *env, struct sd_lb_stats *sds)
  5752. {
  5753. struct sched_domain *child = env->sd->child;
  5754. struct sched_group *sg = env->sd->groups;
  5755. struct sg_lb_stats tmp_sgs;
  5756. int load_idx, prefer_sibling = 0;
  5757. bool overload = false;
  5758. if (child && child->flags & SD_PREFER_SIBLING)
  5759. prefer_sibling = 1;
  5760. load_idx = get_sd_load_idx(env->sd, env->idle);
  5761. do {
  5762. struct sg_lb_stats *sgs = &tmp_sgs;
  5763. int local_group;
  5764. local_group = cpumask_test_cpu(env->dst_cpu, sched_group_cpus(sg));
  5765. if (local_group) {
  5766. sds->local = sg;
  5767. sgs = &sds->local_stat;
  5768. if (env->idle != CPU_NEWLY_IDLE ||
  5769. time_after_eq(jiffies, sg->sgc->next_update))
  5770. update_group_capacity(env->sd, env->dst_cpu);
  5771. }
  5772. update_sg_lb_stats(env, sg, load_idx, local_group, sgs,
  5773. &overload);
  5774. if (local_group)
  5775. goto next_group;
  5776. /*
  5777. * In case the child domain prefers tasks go to siblings
  5778. * first, lower the sg capacity so that we'll try
  5779. * and move all the excess tasks away. We lower the capacity
  5780. * of a group only if the local group has the capacity to fit
  5781. * these excess tasks. The extra check prevents the case where
  5782. * you always pull from the heaviest group when it is already
  5783. * under-utilized (possible with a large weight task outweighs
  5784. * the tasks on the system).
  5785. */
  5786. if (prefer_sibling && sds->local &&
  5787. group_has_capacity(env, &sds->local_stat) &&
  5788. (sgs->sum_nr_running > 1)) {
  5789. sgs->group_no_capacity = 1;
  5790. sgs->group_type = group_classify(sg, sgs);
  5791. }
  5792. if (update_sd_pick_busiest(env, sds, sg, sgs)) {
  5793. sds->busiest = sg;
  5794. sds->busiest_stat = *sgs;
  5795. }
  5796. next_group:
  5797. /* Now, start updating sd_lb_stats */
  5798. sds->total_load += sgs->group_load;
  5799. sds->total_capacity += sgs->group_capacity;
  5800. sg = sg->next;
  5801. } while (sg != env->sd->groups);
  5802. if (env->sd->flags & SD_NUMA)
  5803. env->fbq_type = fbq_classify_group(&sds->busiest_stat);
  5804. if (!env->sd->parent) {
  5805. /* update overload indicator if we are at root domain */
  5806. if (env->dst_rq->rd->overload != overload)
  5807. env->dst_rq->rd->overload = overload;
  5808. }
  5809. }
  5810. /**
  5811. * check_asym_packing - Check to see if the group is packed into the
  5812. * sched doman.
  5813. *
  5814. * This is primarily intended to used at the sibling level. Some
  5815. * cores like POWER7 prefer to use lower numbered SMT threads. In the
  5816. * case of POWER7, it can move to lower SMT modes only when higher
  5817. * threads are idle. When in lower SMT modes, the threads will
  5818. * perform better since they share less core resources. Hence when we
  5819. * have idle threads, we want them to be the higher ones.
  5820. *
  5821. * This packing function is run on idle threads. It checks to see if
  5822. * the busiest CPU in this domain (core in the P7 case) has a higher
  5823. * CPU number than the packing function is being run on. Here we are
  5824. * assuming lower CPU number will be equivalent to lower a SMT thread
  5825. * number.
  5826. *
  5827. * Return: 1 when packing is required and a task should be moved to
  5828. * this CPU. The amount of the imbalance is returned in *imbalance.
  5829. *
  5830. * @env: The load balancing environment.
  5831. * @sds: Statistics of the sched_domain which is to be packed
  5832. */
  5833. static int check_asym_packing(struct lb_env *env, struct sd_lb_stats *sds)
  5834. {
  5835. int busiest_cpu;
  5836. if (!(env->sd->flags & SD_ASYM_PACKING))
  5837. return 0;
  5838. if (env->idle == CPU_NOT_IDLE)
  5839. return 0;
  5840. if (!sds->busiest)
  5841. return 0;
  5842. busiest_cpu = group_first_cpu(sds->busiest);
  5843. if (env->dst_cpu > busiest_cpu)
  5844. return 0;
  5845. env->imbalance = DIV_ROUND_CLOSEST(
  5846. sds->busiest_stat.avg_load * sds->busiest_stat.group_capacity,
  5847. SCHED_CAPACITY_SCALE);
  5848. return 1;
  5849. }
  5850. /**
  5851. * fix_small_imbalance - Calculate the minor imbalance that exists
  5852. * amongst the groups of a sched_domain, during
  5853. * load balancing.
  5854. * @env: The load balancing environment.
  5855. * @sds: Statistics of the sched_domain whose imbalance is to be calculated.
  5856. */
  5857. static inline
  5858. void fix_small_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
  5859. {
  5860. unsigned long tmp, capa_now = 0, capa_move = 0;
  5861. unsigned int imbn = 2;
  5862. unsigned long scaled_busy_load_per_task;
  5863. struct sg_lb_stats *local, *busiest;
  5864. local = &sds->local_stat;
  5865. busiest = &sds->busiest_stat;
  5866. if (!local->sum_nr_running)
  5867. local->load_per_task = cpu_avg_load_per_task(env->dst_cpu);
  5868. else if (busiest->load_per_task > local->load_per_task)
  5869. imbn = 1;
  5870. scaled_busy_load_per_task =
  5871. (busiest->load_per_task * SCHED_CAPACITY_SCALE) /
  5872. busiest->group_capacity;
  5873. if (busiest->avg_load + scaled_busy_load_per_task >=
  5874. local->avg_load + (scaled_busy_load_per_task * imbn)) {
  5875. env->imbalance = busiest->load_per_task;
  5876. return;
  5877. }
  5878. /*
  5879. * OK, we don't have enough imbalance to justify moving tasks,
  5880. * however we may be able to increase total CPU capacity used by
  5881. * moving them.
  5882. */
  5883. capa_now += busiest->group_capacity *
  5884. min(busiest->load_per_task, busiest->avg_load);
  5885. capa_now += local->group_capacity *
  5886. min(local->load_per_task, local->avg_load);
  5887. capa_now /= SCHED_CAPACITY_SCALE;
  5888. /* Amount of load we'd subtract */
  5889. if (busiest->avg_load > scaled_busy_load_per_task) {
  5890. capa_move += busiest->group_capacity *
  5891. min(busiest->load_per_task,
  5892. busiest->avg_load - scaled_busy_load_per_task);
  5893. }
  5894. /* Amount of load we'd add */
  5895. if (busiest->avg_load * busiest->group_capacity <
  5896. busiest->load_per_task * SCHED_CAPACITY_SCALE) {
  5897. tmp = (busiest->avg_load * busiest->group_capacity) /
  5898. local->group_capacity;
  5899. } else {
  5900. tmp = (busiest->load_per_task * SCHED_CAPACITY_SCALE) /
  5901. local->group_capacity;
  5902. }
  5903. capa_move += local->group_capacity *
  5904. min(local->load_per_task, local->avg_load + tmp);
  5905. capa_move /= SCHED_CAPACITY_SCALE;
  5906. /* Move if we gain throughput */
  5907. if (capa_move > capa_now)
  5908. env->imbalance = busiest->load_per_task;
  5909. }
  5910. /**
  5911. * calculate_imbalance - Calculate the amount of imbalance present within the
  5912. * groups of a given sched_domain during load balance.
  5913. * @env: load balance environment
  5914. * @sds: statistics of the sched_domain whose imbalance is to be calculated.
  5915. */
  5916. static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
  5917. {
  5918. unsigned long max_pull, load_above_capacity = ~0UL;
  5919. struct sg_lb_stats *local, *busiest;
  5920. local = &sds->local_stat;
  5921. busiest = &sds->busiest_stat;
  5922. if (busiest->group_type == group_imbalanced) {
  5923. /*
  5924. * In the group_imb case we cannot rely on group-wide averages
  5925. * to ensure cpu-load equilibrium, look at wider averages. XXX
  5926. */
  5927. busiest->load_per_task =
  5928. min(busiest->load_per_task, sds->avg_load);
  5929. }
  5930. /*
  5931. * Avg load of busiest sg can be less and avg load of local sg can
  5932. * be greater than avg load across all sgs of sd because avg load
  5933. * factors in sg capacity and sgs with smaller group_type are
  5934. * skipped when updating the busiest sg:
  5935. */
  5936. if (busiest->avg_load <= sds->avg_load ||
  5937. local->avg_load >= sds->avg_load) {
  5938. env->imbalance = 0;
  5939. return fix_small_imbalance(env, sds);
  5940. }
  5941. /*
  5942. * If there aren't any idle cpus, avoid creating some.
  5943. */
  5944. if (busiest->group_type == group_overloaded &&
  5945. local->group_type == group_overloaded) {
  5946. load_above_capacity = busiest->sum_nr_running * SCHED_CAPACITY_SCALE;
  5947. if (load_above_capacity > busiest->group_capacity) {
  5948. load_above_capacity -= busiest->group_capacity;
  5949. load_above_capacity *= NICE_0_LOAD;
  5950. load_above_capacity /= busiest->group_capacity;
  5951. } else
  5952. load_above_capacity = ~0UL;
  5953. }
  5954. /*
  5955. * We're trying to get all the cpus to the average_load, so we don't
  5956. * want to push ourselves above the average load, nor do we wish to
  5957. * reduce the max loaded cpu below the average load. At the same time,
  5958. * we also don't want to reduce the group load below the group
  5959. * capacity. Thus we look for the minimum possible imbalance.
  5960. */
  5961. max_pull = min(busiest->avg_load - sds->avg_load, load_above_capacity);
  5962. /* How much load to actually move to equalise the imbalance */
  5963. env->imbalance = min(
  5964. max_pull * busiest->group_capacity,
  5965. (sds->avg_load - local->avg_load) * local->group_capacity
  5966. ) / SCHED_CAPACITY_SCALE;
  5967. /*
  5968. * if *imbalance is less than the average load per runnable task
  5969. * there is no guarantee that any tasks will be moved so we'll have
  5970. * a think about bumping its value to force at least one task to be
  5971. * moved
  5972. */
  5973. if (env->imbalance < busiest->load_per_task)
  5974. return fix_small_imbalance(env, sds);
  5975. }
  5976. /******* find_busiest_group() helpers end here *********************/
  5977. /**
  5978. * find_busiest_group - Returns the busiest group within the sched_domain
  5979. * if there is an imbalance.
  5980. *
  5981. * Also calculates the amount of weighted load which should be moved
  5982. * to restore balance.
  5983. *
  5984. * @env: The load balancing environment.
  5985. *
  5986. * Return: - The busiest group if imbalance exists.
  5987. */
  5988. static struct sched_group *find_busiest_group(struct lb_env *env)
  5989. {
  5990. struct sg_lb_stats *local, *busiest;
  5991. struct sd_lb_stats sds;
  5992. init_sd_lb_stats(&sds);
  5993. /*
  5994. * Compute the various statistics relavent for load balancing at
  5995. * this level.
  5996. */
  5997. update_sd_lb_stats(env, &sds);
  5998. local = &sds.local_stat;
  5999. busiest = &sds.busiest_stat;
  6000. /* ASYM feature bypasses nice load balance check */
  6001. if (check_asym_packing(env, &sds))
  6002. return sds.busiest;
  6003. /* There is no busy sibling group to pull tasks from */
  6004. if (!sds.busiest || busiest->sum_nr_running == 0)
  6005. goto out_balanced;
  6006. sds.avg_load = (SCHED_CAPACITY_SCALE * sds.total_load)
  6007. / sds.total_capacity;
  6008. /*
  6009. * If the busiest group is imbalanced the below checks don't
  6010. * work because they assume all things are equal, which typically
  6011. * isn't true due to cpus_allowed constraints and the like.
  6012. */
  6013. if (busiest->group_type == group_imbalanced)
  6014. goto force_balance;
  6015. /* SD_BALANCE_NEWIDLE trumps SMP nice when underutilized */
  6016. if (env->idle == CPU_NEWLY_IDLE && group_has_capacity(env, local) &&
  6017. busiest->group_no_capacity)
  6018. goto force_balance;
  6019. /*
  6020. * If the local group is busier than the selected busiest group
  6021. * don't try and pull any tasks.
  6022. */
  6023. if (local->avg_load >= busiest->avg_load)
  6024. goto out_balanced;
  6025. /*
  6026. * Don't pull any tasks if this group is already above the domain
  6027. * average load.
  6028. */
  6029. if (local->avg_load >= sds.avg_load)
  6030. goto out_balanced;
  6031. if (env->idle == CPU_IDLE) {
  6032. /*
  6033. * This cpu is idle. If the busiest group is not overloaded
  6034. * and there is no imbalance between this and busiest group
  6035. * wrt idle cpus, it is balanced. The imbalance becomes
  6036. * significant if the diff is greater than 1 otherwise we
  6037. * might end up to just move the imbalance on another group
  6038. */
  6039. if ((busiest->group_type != group_overloaded) &&
  6040. (local->idle_cpus <= (busiest->idle_cpus + 1)))
  6041. goto out_balanced;
  6042. } else {
  6043. /*
  6044. * In the CPU_NEWLY_IDLE, CPU_NOT_IDLE cases, use
  6045. * imbalance_pct to be conservative.
  6046. */
  6047. if (100 * busiest->avg_load <=
  6048. env->sd->imbalance_pct * local->avg_load)
  6049. goto out_balanced;
  6050. }
  6051. force_balance:
  6052. /* Looks like there is an imbalance. Compute it */
  6053. calculate_imbalance(env, &sds);
  6054. return sds.busiest;
  6055. out_balanced:
  6056. env->imbalance = 0;
  6057. return NULL;
  6058. }
  6059. /*
  6060. * find_busiest_queue - find the busiest runqueue among the cpus in group.
  6061. */
  6062. static struct rq *find_busiest_queue(struct lb_env *env,
  6063. struct sched_group *group)
  6064. {
  6065. struct rq *busiest = NULL, *rq;
  6066. unsigned long busiest_load = 0, busiest_capacity = 1;
  6067. int i;
  6068. for_each_cpu_and(i, sched_group_cpus(group), env->cpus) {
  6069. unsigned long capacity, wl;
  6070. enum fbq_type rt;
  6071. rq = cpu_rq(i);
  6072. rt = fbq_classify_rq(rq);
  6073. /*
  6074. * We classify groups/runqueues into three groups:
  6075. * - regular: there are !numa tasks
  6076. * - remote: there are numa tasks that run on the 'wrong' node
  6077. * - all: there is no distinction
  6078. *
  6079. * In order to avoid migrating ideally placed numa tasks,
  6080. * ignore those when there's better options.
  6081. *
  6082. * If we ignore the actual busiest queue to migrate another
  6083. * task, the next balance pass can still reduce the busiest
  6084. * queue by moving tasks around inside the node.
  6085. *
  6086. * If we cannot move enough load due to this classification
  6087. * the next pass will adjust the group classification and
  6088. * allow migration of more tasks.
  6089. *
  6090. * Both cases only affect the total convergence complexity.
  6091. */
  6092. if (rt > env->fbq_type)
  6093. continue;
  6094. capacity = capacity_of(i);
  6095. wl = weighted_cpuload(i);
  6096. /*
  6097. * When comparing with imbalance, use weighted_cpuload()
  6098. * which is not scaled with the cpu capacity.
  6099. */
  6100. if (rq->nr_running == 1 && wl > env->imbalance &&
  6101. !check_cpu_capacity(rq, env->sd))
  6102. continue;
  6103. /*
  6104. * For the load comparisons with the other cpu's, consider
  6105. * the weighted_cpuload() scaled with the cpu capacity, so
  6106. * that the load can be moved away from the cpu that is
  6107. * potentially running at a lower capacity.
  6108. *
  6109. * Thus we're looking for max(wl_i / capacity_i), crosswise
  6110. * multiplication to rid ourselves of the division works out
  6111. * to: wl_i * capacity_j > wl_j * capacity_i; where j is
  6112. * our previous maximum.
  6113. */
  6114. if (wl * busiest_capacity > busiest_load * capacity) {
  6115. busiest_load = wl;
  6116. busiest_capacity = capacity;
  6117. busiest = rq;
  6118. }
  6119. }
  6120. return busiest;
  6121. }
  6122. /*
  6123. * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
  6124. * so long as it is large enough.
  6125. */
  6126. #define MAX_PINNED_INTERVAL 512
  6127. /* Working cpumask for load_balance and load_balance_newidle. */
  6128. DEFINE_PER_CPU(cpumask_var_t, load_balance_mask);
  6129. static int need_active_balance(struct lb_env *env)
  6130. {
  6131. struct sched_domain *sd = env->sd;
  6132. if (env->idle == CPU_NEWLY_IDLE) {
  6133. /*
  6134. * ASYM_PACKING needs to force migrate tasks from busy but
  6135. * higher numbered CPUs in order to pack all tasks in the
  6136. * lowest numbered CPUs.
  6137. */
  6138. if ((sd->flags & SD_ASYM_PACKING) && env->src_cpu > env->dst_cpu)
  6139. return 1;
  6140. }
  6141. /*
  6142. * The dst_cpu is idle and the src_cpu CPU has only 1 CFS task.
  6143. * It's worth migrating the task if the src_cpu's capacity is reduced
  6144. * because of other sched_class or IRQs if more capacity stays
  6145. * available on dst_cpu.
  6146. */
  6147. if ((env->idle != CPU_NOT_IDLE) &&
  6148. (env->src_rq->cfs.h_nr_running == 1)) {
  6149. if ((check_cpu_capacity(env->src_rq, sd)) &&
  6150. (capacity_of(env->src_cpu)*sd->imbalance_pct < capacity_of(env->dst_cpu)*100))
  6151. return 1;
  6152. }
  6153. return unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2);
  6154. }
  6155. static int active_load_balance_cpu_stop(void *data);
  6156. static int should_we_balance(struct lb_env *env)
  6157. {
  6158. struct sched_group *sg = env->sd->groups;
  6159. struct cpumask *sg_cpus, *sg_mask;
  6160. int cpu, balance_cpu = -1;
  6161. /*
  6162. * In the newly idle case, we will allow all the cpu's
  6163. * to do the newly idle load balance.
  6164. */
  6165. if (env->idle == CPU_NEWLY_IDLE)
  6166. return 1;
  6167. sg_cpus = sched_group_cpus(sg);
  6168. sg_mask = sched_group_mask(sg);
  6169. /* Try to find first idle cpu */
  6170. for_each_cpu_and(cpu, sg_cpus, env->cpus) {
  6171. if (!cpumask_test_cpu(cpu, sg_mask) || !idle_cpu(cpu))
  6172. continue;
  6173. balance_cpu = cpu;
  6174. break;
  6175. }
  6176. if (balance_cpu == -1)
  6177. balance_cpu = group_balance_cpu(sg);
  6178. /*
  6179. * First idle cpu or the first cpu(busiest) in this sched group
  6180. * is eligible for doing load balancing at this and above domains.
  6181. */
  6182. return balance_cpu == env->dst_cpu;
  6183. }
  6184. /*
  6185. * Check this_cpu to ensure it is balanced within domain. Attempt to move
  6186. * tasks if there is an imbalance.
  6187. */
  6188. static int load_balance(int this_cpu, struct rq *this_rq,
  6189. struct sched_domain *sd, enum cpu_idle_type idle,
  6190. int *continue_balancing)
  6191. {
  6192. int ld_moved, cur_ld_moved, active_balance = 0;
  6193. struct sched_domain *sd_parent = sd->parent;
  6194. struct sched_group *group;
  6195. struct rq *busiest;
  6196. unsigned long flags;
  6197. struct cpumask *cpus = this_cpu_cpumask_var_ptr(load_balance_mask);
  6198. struct lb_env env = {
  6199. .sd = sd,
  6200. .dst_cpu = this_cpu,
  6201. .dst_rq = this_rq,
  6202. .dst_grpmask = sched_group_cpus(sd->groups),
  6203. .idle = idle,
  6204. .loop_break = sched_nr_migrate_break,
  6205. .cpus = cpus,
  6206. .fbq_type = all,
  6207. .tasks = LIST_HEAD_INIT(env.tasks),
  6208. };
  6209. /*
  6210. * For NEWLY_IDLE load_balancing, we don't need to consider
  6211. * other cpus in our group
  6212. */
  6213. if (idle == CPU_NEWLY_IDLE)
  6214. env.dst_grpmask = NULL;
  6215. cpumask_copy(cpus, cpu_active_mask);
  6216. schedstat_inc(sd, lb_count[idle]);
  6217. redo:
  6218. if (!should_we_balance(&env)) {
  6219. *continue_balancing = 0;
  6220. goto out_balanced;
  6221. }
  6222. group = find_busiest_group(&env);
  6223. if (!group) {
  6224. schedstat_inc(sd, lb_nobusyg[idle]);
  6225. goto out_balanced;
  6226. }
  6227. busiest = find_busiest_queue(&env, group);
  6228. if (!busiest) {
  6229. schedstat_inc(sd, lb_nobusyq[idle]);
  6230. goto out_balanced;
  6231. }
  6232. BUG_ON(busiest == env.dst_rq);
  6233. schedstat_add(sd, lb_imbalance[idle], env.imbalance);
  6234. env.src_cpu = busiest->cpu;
  6235. env.src_rq = busiest;
  6236. ld_moved = 0;
  6237. if (busiest->nr_running > 1) {
  6238. /*
  6239. * Attempt to move tasks. If find_busiest_group has found
  6240. * an imbalance but busiest->nr_running <= 1, the group is
  6241. * still unbalanced. ld_moved simply stays zero, so it is
  6242. * correctly treated as an imbalance.
  6243. */
  6244. env.flags |= LBF_ALL_PINNED;
  6245. env.loop_max = min(sysctl_sched_nr_migrate, busiest->nr_running);
  6246. more_balance:
  6247. raw_spin_lock_irqsave(&busiest->lock, flags);
  6248. /*
  6249. * cur_ld_moved - load moved in current iteration
  6250. * ld_moved - cumulative load moved across iterations
  6251. */
  6252. cur_ld_moved = detach_tasks(&env);
  6253. /*
  6254. * We've detached some tasks from busiest_rq. Every
  6255. * task is masked "TASK_ON_RQ_MIGRATING", so we can safely
  6256. * unlock busiest->lock, and we are able to be sure
  6257. * that nobody can manipulate the tasks in parallel.
  6258. * See task_rq_lock() family for the details.
  6259. */
  6260. raw_spin_unlock(&busiest->lock);
  6261. if (cur_ld_moved) {
  6262. attach_tasks(&env);
  6263. ld_moved += cur_ld_moved;
  6264. }
  6265. local_irq_restore(flags);
  6266. if (env.flags & LBF_NEED_BREAK) {
  6267. env.flags &= ~LBF_NEED_BREAK;
  6268. goto more_balance;
  6269. }
  6270. /*
  6271. * Revisit (affine) tasks on src_cpu that couldn't be moved to
  6272. * us and move them to an alternate dst_cpu in our sched_group
  6273. * where they can run. The upper limit on how many times we
  6274. * iterate on same src_cpu is dependent on number of cpus in our
  6275. * sched_group.
  6276. *
  6277. * This changes load balance semantics a bit on who can move
  6278. * load to a given_cpu. In addition to the given_cpu itself
  6279. * (or a ilb_cpu acting on its behalf where given_cpu is
  6280. * nohz-idle), we now have balance_cpu in a position to move
  6281. * load to given_cpu. In rare situations, this may cause
  6282. * conflicts (balance_cpu and given_cpu/ilb_cpu deciding
  6283. * _independently_ and at _same_ time to move some load to
  6284. * given_cpu) causing exceess load to be moved to given_cpu.
  6285. * This however should not happen so much in practice and
  6286. * moreover subsequent load balance cycles should correct the
  6287. * excess load moved.
  6288. */
  6289. if ((env.flags & LBF_DST_PINNED) && env.imbalance > 0) {
  6290. /* Prevent to re-select dst_cpu via env's cpus */
  6291. cpumask_clear_cpu(env.dst_cpu, env.cpus);
  6292. env.dst_rq = cpu_rq(env.new_dst_cpu);
  6293. env.dst_cpu = env.new_dst_cpu;
  6294. env.flags &= ~LBF_DST_PINNED;
  6295. env.loop = 0;
  6296. env.loop_break = sched_nr_migrate_break;
  6297. /*
  6298. * Go back to "more_balance" rather than "redo" since we
  6299. * need to continue with same src_cpu.
  6300. */
  6301. goto more_balance;
  6302. }
  6303. /*
  6304. * We failed to reach balance because of affinity.
  6305. */
  6306. if (sd_parent) {
  6307. int *group_imbalance = &sd_parent->groups->sgc->imbalance;
  6308. if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0)
  6309. *group_imbalance = 1;
  6310. }
  6311. /* All tasks on this runqueue were pinned by CPU affinity */
  6312. if (unlikely(env.flags & LBF_ALL_PINNED)) {
  6313. cpumask_clear_cpu(cpu_of(busiest), cpus);
  6314. if (!cpumask_empty(cpus)) {
  6315. env.loop = 0;
  6316. env.loop_break = sched_nr_migrate_break;
  6317. goto redo;
  6318. }
  6319. goto out_all_pinned;
  6320. }
  6321. }
  6322. if (!ld_moved) {
  6323. schedstat_inc(sd, lb_failed[idle]);
  6324. /*
  6325. * Increment the failure counter only on periodic balance.
  6326. * We do not want newidle balance, which can be very
  6327. * frequent, pollute the failure counter causing
  6328. * excessive cache_hot migrations and active balances.
  6329. */
  6330. if (idle != CPU_NEWLY_IDLE)
  6331. sd->nr_balance_failed++;
  6332. if (need_active_balance(&env)) {
  6333. raw_spin_lock_irqsave(&busiest->lock, flags);
  6334. /* don't kick the active_load_balance_cpu_stop,
  6335. * if the curr task on busiest cpu can't be
  6336. * moved to this_cpu
  6337. */
  6338. if (!cpumask_test_cpu(this_cpu,
  6339. tsk_cpus_allowed(busiest->curr))) {
  6340. raw_spin_unlock_irqrestore(&busiest->lock,
  6341. flags);
  6342. env.flags |= LBF_ALL_PINNED;
  6343. goto out_one_pinned;
  6344. }
  6345. /*
  6346. * ->active_balance synchronizes accesses to
  6347. * ->active_balance_work. Once set, it's cleared
  6348. * only after active load balance is finished.
  6349. */
  6350. if (!busiest->active_balance) {
  6351. busiest->active_balance = 1;
  6352. busiest->push_cpu = this_cpu;
  6353. active_balance = 1;
  6354. }
  6355. raw_spin_unlock_irqrestore(&busiest->lock, flags);
  6356. if (active_balance) {
  6357. stop_one_cpu_nowait(cpu_of(busiest),
  6358. active_load_balance_cpu_stop, busiest,
  6359. &busiest->active_balance_work);
  6360. }
  6361. /* We've kicked active balancing, force task migration. */
  6362. sd->nr_balance_failed = sd->cache_nice_tries+1;
  6363. }
  6364. } else
  6365. sd->nr_balance_failed = 0;
  6366. if (likely(!active_balance)) {
  6367. /* We were unbalanced, so reset the balancing interval */
  6368. sd->balance_interval = sd->min_interval;
  6369. } else {
  6370. /*
  6371. * If we've begun active balancing, start to back off. This
  6372. * case may not be covered by the all_pinned logic if there
  6373. * is only 1 task on the busy runqueue (because we don't call
  6374. * detach_tasks).
  6375. */
  6376. if (sd->balance_interval < sd->max_interval)
  6377. sd->balance_interval *= 2;
  6378. }
  6379. goto out;
  6380. out_balanced:
  6381. /*
  6382. * We reach balance although we may have faced some affinity
  6383. * constraints. Clear the imbalance flag if it was set.
  6384. */
  6385. if (sd_parent) {
  6386. int *group_imbalance = &sd_parent->groups->sgc->imbalance;
  6387. if (*group_imbalance)
  6388. *group_imbalance = 0;
  6389. }
  6390. out_all_pinned:
  6391. /*
  6392. * We reach balance because all tasks are pinned at this level so
  6393. * we can't migrate them. Let the imbalance flag set so parent level
  6394. * can try to migrate them.
  6395. */
  6396. schedstat_inc(sd, lb_balanced[idle]);
  6397. sd->nr_balance_failed = 0;
  6398. out_one_pinned:
  6399. /* tune up the balancing interval */
  6400. if (((env.flags & LBF_ALL_PINNED) &&
  6401. sd->balance_interval < MAX_PINNED_INTERVAL) ||
  6402. (sd->balance_interval < sd->max_interval))
  6403. sd->balance_interval *= 2;
  6404. ld_moved = 0;
  6405. out:
  6406. return ld_moved;
  6407. }
  6408. static inline unsigned long
  6409. get_sd_balance_interval(struct sched_domain *sd, int cpu_busy)
  6410. {
  6411. unsigned long interval = sd->balance_interval;
  6412. if (cpu_busy)
  6413. interval *= sd->busy_factor;
  6414. /* scale ms to jiffies */
  6415. interval = msecs_to_jiffies(interval);
  6416. interval = clamp(interval, 1UL, max_load_balance_interval);
  6417. return interval;
  6418. }
  6419. static inline void
  6420. update_next_balance(struct sched_domain *sd, int cpu_busy, unsigned long *next_balance)
  6421. {
  6422. unsigned long interval, next;
  6423. interval = get_sd_balance_interval(sd, cpu_busy);
  6424. next = sd->last_balance + interval;
  6425. if (time_after(*next_balance, next))
  6426. *next_balance = next;
  6427. }
  6428. /*
  6429. * idle_balance is called by schedule() if this_cpu is about to become
  6430. * idle. Attempts to pull tasks from other CPUs.
  6431. */
  6432. static int idle_balance(struct rq *this_rq)
  6433. {
  6434. unsigned long next_balance = jiffies + HZ;
  6435. int this_cpu = this_rq->cpu;
  6436. struct sched_domain *sd;
  6437. int pulled_task = 0;
  6438. u64 curr_cost = 0;
  6439. /*
  6440. * We must set idle_stamp _before_ calling idle_balance(), such that we
  6441. * measure the duration of idle_balance() as idle time.
  6442. */
  6443. this_rq->idle_stamp = rq_clock(this_rq);
  6444. if (this_rq->avg_idle < sysctl_sched_migration_cost ||
  6445. !this_rq->rd->overload) {
  6446. rcu_read_lock();
  6447. sd = rcu_dereference_check_sched_domain(this_rq->sd);
  6448. if (sd)
  6449. update_next_balance(sd, 0, &next_balance);
  6450. rcu_read_unlock();
  6451. goto out;
  6452. }
  6453. raw_spin_unlock(&this_rq->lock);
  6454. update_blocked_averages(this_cpu);
  6455. rcu_read_lock();
  6456. for_each_domain(this_cpu, sd) {
  6457. int continue_balancing = 1;
  6458. u64 t0, domain_cost;
  6459. if (!(sd->flags & SD_LOAD_BALANCE))
  6460. continue;
  6461. if (this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost) {
  6462. update_next_balance(sd, 0, &next_balance);
  6463. break;
  6464. }
  6465. if (sd->flags & SD_BALANCE_NEWIDLE) {
  6466. t0 = sched_clock_cpu(this_cpu);
  6467. pulled_task = load_balance(this_cpu, this_rq,
  6468. sd, CPU_NEWLY_IDLE,
  6469. &continue_balancing);
  6470. domain_cost = sched_clock_cpu(this_cpu) - t0;
  6471. if (domain_cost > sd->max_newidle_lb_cost)
  6472. sd->max_newidle_lb_cost = domain_cost;
  6473. curr_cost += domain_cost;
  6474. }
  6475. update_next_balance(sd, 0, &next_balance);
  6476. /*
  6477. * Stop searching for tasks to pull if there are
  6478. * now runnable tasks on this rq.
  6479. */
  6480. if (pulled_task || this_rq->nr_running > 0)
  6481. break;
  6482. }
  6483. rcu_read_unlock();
  6484. raw_spin_lock(&this_rq->lock);
  6485. if (curr_cost > this_rq->max_idle_balance_cost)
  6486. this_rq->max_idle_balance_cost = curr_cost;
  6487. /*
  6488. * While browsing the domains, we released the rq lock, a task could
  6489. * have been enqueued in the meantime. Since we're not going idle,
  6490. * pretend we pulled a task.
  6491. */
  6492. if (this_rq->cfs.h_nr_running && !pulled_task)
  6493. pulled_task = 1;
  6494. out:
  6495. /* Move the next balance forward */
  6496. if (time_after(this_rq->next_balance, next_balance))
  6497. this_rq->next_balance = next_balance;
  6498. /* Is there a task of a high priority class? */
  6499. if (this_rq->nr_running != this_rq->cfs.h_nr_running)
  6500. pulled_task = -1;
  6501. if (pulled_task)
  6502. this_rq->idle_stamp = 0;
  6503. return pulled_task;
  6504. }
  6505. /*
  6506. * active_load_balance_cpu_stop is run by cpu stopper. It pushes
  6507. * running tasks off the busiest CPU onto idle CPUs. It requires at
  6508. * least 1 task to be running on each physical CPU where possible, and
  6509. * avoids physical / logical imbalances.
  6510. */
  6511. static int active_load_balance_cpu_stop(void *data)
  6512. {
  6513. struct rq *busiest_rq = data;
  6514. int busiest_cpu = cpu_of(busiest_rq);
  6515. int target_cpu = busiest_rq->push_cpu;
  6516. struct rq *target_rq = cpu_rq(target_cpu);
  6517. struct sched_domain *sd;
  6518. struct task_struct *p = NULL;
  6519. raw_spin_lock_irq(&busiest_rq->lock);
  6520. /* make sure the requested cpu hasn't gone down in the meantime */
  6521. if (unlikely(busiest_cpu != smp_processor_id() ||
  6522. !busiest_rq->active_balance))
  6523. goto out_unlock;
  6524. /* Is there any task to move? */
  6525. if (busiest_rq->nr_running <= 1)
  6526. goto out_unlock;
  6527. /*
  6528. * This condition is "impossible", if it occurs
  6529. * we need to fix it. Originally reported by
  6530. * Bjorn Helgaas on a 128-cpu setup.
  6531. */
  6532. BUG_ON(busiest_rq == target_rq);
  6533. /* Search for an sd spanning us and the target CPU. */
  6534. rcu_read_lock();
  6535. for_each_domain(target_cpu, sd) {
  6536. if ((sd->flags & SD_LOAD_BALANCE) &&
  6537. cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
  6538. break;
  6539. }
  6540. if (likely(sd)) {
  6541. struct lb_env env = {
  6542. .sd = sd,
  6543. .dst_cpu = target_cpu,
  6544. .dst_rq = target_rq,
  6545. .src_cpu = busiest_rq->cpu,
  6546. .src_rq = busiest_rq,
  6547. .idle = CPU_IDLE,
  6548. };
  6549. schedstat_inc(sd, alb_count);
  6550. p = detach_one_task(&env);
  6551. if (p) {
  6552. schedstat_inc(sd, alb_pushed);
  6553. /* Active balancing done, reset the failure counter. */
  6554. sd->nr_balance_failed = 0;
  6555. } else {
  6556. schedstat_inc(sd, alb_failed);
  6557. }
  6558. }
  6559. rcu_read_unlock();
  6560. out_unlock:
  6561. busiest_rq->active_balance = 0;
  6562. raw_spin_unlock(&busiest_rq->lock);
  6563. if (p)
  6564. attach_one_task(target_rq, p);
  6565. local_irq_enable();
  6566. return 0;
  6567. }
  6568. static inline int on_null_domain(struct rq *rq)
  6569. {
  6570. return unlikely(!rcu_dereference_sched(rq->sd));
  6571. }
  6572. #ifdef CONFIG_NO_HZ_COMMON
  6573. /*
  6574. * idle load balancing details
  6575. * - When one of the busy CPUs notice that there may be an idle rebalancing
  6576. * needed, they will kick the idle load balancer, which then does idle
  6577. * load balancing for all the idle CPUs.
  6578. */
  6579. static struct {
  6580. cpumask_var_t idle_cpus_mask;
  6581. atomic_t nr_cpus;
  6582. unsigned long next_balance; /* in jiffy units */
  6583. } nohz ____cacheline_aligned;
  6584. static inline int find_new_ilb(void)
  6585. {
  6586. int ilb = cpumask_first(nohz.idle_cpus_mask);
  6587. if (ilb < nr_cpu_ids && idle_cpu(ilb))
  6588. return ilb;
  6589. return nr_cpu_ids;
  6590. }
  6591. /*
  6592. * Kick a CPU to do the nohz balancing, if it is time for it. We pick the
  6593. * nohz_load_balancer CPU (if there is one) otherwise fallback to any idle
  6594. * CPU (if there is one).
  6595. */
  6596. static void nohz_balancer_kick(void)
  6597. {
  6598. int ilb_cpu;
  6599. nohz.next_balance++;
  6600. ilb_cpu = find_new_ilb();
  6601. if (ilb_cpu >= nr_cpu_ids)
  6602. return;
  6603. if (test_and_set_bit(NOHZ_BALANCE_KICK, nohz_flags(ilb_cpu)))
  6604. return;
  6605. /*
  6606. * Use smp_send_reschedule() instead of resched_cpu().
  6607. * This way we generate a sched IPI on the target cpu which
  6608. * is idle. And the softirq performing nohz idle load balance
  6609. * will be run before returning from the IPI.
  6610. */
  6611. smp_send_reschedule(ilb_cpu);
  6612. return;
  6613. }
  6614. void nohz_balance_exit_idle(unsigned int cpu)
  6615. {
  6616. if (unlikely(test_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu)))) {
  6617. /*
  6618. * Completely isolated CPUs don't ever set, so we must test.
  6619. */
  6620. if (likely(cpumask_test_cpu(cpu, nohz.idle_cpus_mask))) {
  6621. cpumask_clear_cpu(cpu, nohz.idle_cpus_mask);
  6622. atomic_dec(&nohz.nr_cpus);
  6623. }
  6624. clear_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu));
  6625. }
  6626. }
  6627. static inline void set_cpu_sd_state_busy(void)
  6628. {
  6629. struct sched_domain *sd;
  6630. int cpu = smp_processor_id();
  6631. rcu_read_lock();
  6632. sd = rcu_dereference(per_cpu(sd_busy, cpu));
  6633. if (!sd || !sd->nohz_idle)
  6634. goto unlock;
  6635. sd->nohz_idle = 0;
  6636. atomic_inc(&sd->groups->sgc->nr_busy_cpus);
  6637. unlock:
  6638. rcu_read_unlock();
  6639. }
  6640. void set_cpu_sd_state_idle(void)
  6641. {
  6642. struct sched_domain *sd;
  6643. int cpu = smp_processor_id();
  6644. rcu_read_lock();
  6645. sd = rcu_dereference(per_cpu(sd_busy, cpu));
  6646. if (!sd || sd->nohz_idle)
  6647. goto unlock;
  6648. sd->nohz_idle = 1;
  6649. atomic_dec(&sd->groups->sgc->nr_busy_cpus);
  6650. unlock:
  6651. rcu_read_unlock();
  6652. }
  6653. /*
  6654. * This routine will record that the cpu is going idle with tick stopped.
  6655. * This info will be used in performing idle load balancing in the future.
  6656. */
  6657. void nohz_balance_enter_idle(int cpu)
  6658. {
  6659. /*
  6660. * If this cpu is going down, then nothing needs to be done.
  6661. */
  6662. if (!cpu_active(cpu))
  6663. return;
  6664. if (test_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu)))
  6665. return;
  6666. /*
  6667. * If we're a completely isolated CPU, we don't play.
  6668. */
  6669. if (on_null_domain(cpu_rq(cpu)))
  6670. return;
  6671. cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
  6672. atomic_inc(&nohz.nr_cpus);
  6673. set_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu));
  6674. }
  6675. #endif
  6676. static DEFINE_SPINLOCK(balancing);
  6677. /*
  6678. * Scale the max load_balance interval with the number of CPUs in the system.
  6679. * This trades load-balance latency on larger machines for less cross talk.
  6680. */
  6681. void update_max_interval(void)
  6682. {
  6683. max_load_balance_interval = HZ*num_online_cpus()/10;
  6684. }
  6685. /*
  6686. * It checks each scheduling domain to see if it is due to be balanced,
  6687. * and initiates a balancing operation if so.
  6688. *
  6689. * Balancing parameters are set up in init_sched_domains.
  6690. */
  6691. static void rebalance_domains(struct rq *rq, enum cpu_idle_type idle)
  6692. {
  6693. int continue_balancing = 1;
  6694. int cpu = rq->cpu;
  6695. unsigned long interval;
  6696. struct sched_domain *sd;
  6697. /* Earliest time when we have to do rebalance again */
  6698. unsigned long next_balance = jiffies + 60*HZ;
  6699. int update_next_balance = 0;
  6700. int need_serialize, need_decay = 0;
  6701. u64 max_cost = 0;
  6702. update_blocked_averages(cpu);
  6703. rcu_read_lock();
  6704. for_each_domain(cpu, sd) {
  6705. /*
  6706. * Decay the newidle max times here because this is a regular
  6707. * visit to all the domains. Decay ~1% per second.
  6708. */
  6709. if (time_after(jiffies, sd->next_decay_max_lb_cost)) {
  6710. sd->max_newidle_lb_cost =
  6711. (sd->max_newidle_lb_cost * 253) / 256;
  6712. sd->next_decay_max_lb_cost = jiffies + HZ;
  6713. need_decay = 1;
  6714. }
  6715. max_cost += sd->max_newidle_lb_cost;
  6716. if (!(sd->flags & SD_LOAD_BALANCE))
  6717. continue;
  6718. /*
  6719. * Stop the load balance at this level. There is another
  6720. * CPU in our sched group which is doing load balancing more
  6721. * actively.
  6722. */
  6723. if (!continue_balancing) {
  6724. if (need_decay)
  6725. continue;
  6726. break;
  6727. }
  6728. interval = get_sd_balance_interval(sd, idle != CPU_IDLE);
  6729. need_serialize = sd->flags & SD_SERIALIZE;
  6730. if (need_serialize) {
  6731. if (!spin_trylock(&balancing))
  6732. goto out;
  6733. }
  6734. if (time_after_eq(jiffies, sd->last_balance + interval)) {
  6735. if (load_balance(cpu, rq, sd, idle, &continue_balancing)) {
  6736. /*
  6737. * The LBF_DST_PINNED logic could have changed
  6738. * env->dst_cpu, so we can't know our idle
  6739. * state even if we migrated tasks. Update it.
  6740. */
  6741. idle = idle_cpu(cpu) ? CPU_IDLE : CPU_NOT_IDLE;
  6742. }
  6743. sd->last_balance = jiffies;
  6744. interval = get_sd_balance_interval(sd, idle != CPU_IDLE);
  6745. }
  6746. if (need_serialize)
  6747. spin_unlock(&balancing);
  6748. out:
  6749. if (time_after(next_balance, sd->last_balance + interval)) {
  6750. next_balance = sd->last_balance + interval;
  6751. update_next_balance = 1;
  6752. }
  6753. }
  6754. if (need_decay) {
  6755. /*
  6756. * Ensure the rq-wide value also decays but keep it at a
  6757. * reasonable floor to avoid funnies with rq->avg_idle.
  6758. */
  6759. rq->max_idle_balance_cost =
  6760. max((u64)sysctl_sched_migration_cost, max_cost);
  6761. }
  6762. rcu_read_unlock();
  6763. /*
  6764. * next_balance will be updated only when there is a need.
  6765. * When the cpu is attached to null domain for ex, it will not be
  6766. * updated.
  6767. */
  6768. if (likely(update_next_balance)) {
  6769. rq->next_balance = next_balance;
  6770. #ifdef CONFIG_NO_HZ_COMMON
  6771. /*
  6772. * If this CPU has been elected to perform the nohz idle
  6773. * balance. Other idle CPUs have already rebalanced with
  6774. * nohz_idle_balance() and nohz.next_balance has been
  6775. * updated accordingly. This CPU is now running the idle load
  6776. * balance for itself and we need to update the
  6777. * nohz.next_balance accordingly.
  6778. */
  6779. if ((idle == CPU_IDLE) && time_after(nohz.next_balance, rq->next_balance))
  6780. nohz.next_balance = rq->next_balance;
  6781. #endif
  6782. }
  6783. }
  6784. #ifdef CONFIG_NO_HZ_COMMON
  6785. /*
  6786. * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the
  6787. * rebalancing for all the cpus for whom scheduler ticks are stopped.
  6788. */
  6789. static void nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
  6790. {
  6791. int this_cpu = this_rq->cpu;
  6792. struct rq *rq;
  6793. int balance_cpu;
  6794. /* Earliest time when we have to do rebalance again */
  6795. unsigned long next_balance = jiffies + 60*HZ;
  6796. int update_next_balance = 0;
  6797. if (idle != CPU_IDLE ||
  6798. !test_bit(NOHZ_BALANCE_KICK, nohz_flags(this_cpu)))
  6799. goto end;
  6800. for_each_cpu(balance_cpu, nohz.idle_cpus_mask) {
  6801. if (balance_cpu == this_cpu || !idle_cpu(balance_cpu))
  6802. continue;
  6803. /*
  6804. * If this cpu gets work to do, stop the load balancing
  6805. * work being done for other cpus. Next load
  6806. * balancing owner will pick it up.
  6807. */
  6808. if (need_resched())
  6809. break;
  6810. rq = cpu_rq(balance_cpu);
  6811. /*
  6812. * If time for next balance is due,
  6813. * do the balance.
  6814. */
  6815. if (time_after_eq(jiffies, rq->next_balance)) {
  6816. raw_spin_lock_irq(&rq->lock);
  6817. update_rq_clock(rq);
  6818. cpu_load_update_idle(rq);
  6819. raw_spin_unlock_irq(&rq->lock);
  6820. rebalance_domains(rq, CPU_IDLE);
  6821. }
  6822. if (time_after(next_balance, rq->next_balance)) {
  6823. next_balance = rq->next_balance;
  6824. update_next_balance = 1;
  6825. }
  6826. }
  6827. /*
  6828. * next_balance will be updated only when there is a need.
  6829. * When the CPU is attached to null domain for ex, it will not be
  6830. * updated.
  6831. */
  6832. if (likely(update_next_balance))
  6833. nohz.next_balance = next_balance;
  6834. end:
  6835. clear_bit(NOHZ_BALANCE_KICK, nohz_flags(this_cpu));
  6836. }
  6837. /*
  6838. * Current heuristic for kicking the idle load balancer in the presence
  6839. * of an idle cpu in the system.
  6840. * - This rq has more than one task.
  6841. * - This rq has at least one CFS task and the capacity of the CPU is
  6842. * significantly reduced because of RT tasks or IRQs.
  6843. * - At parent of LLC scheduler domain level, this cpu's scheduler group has
  6844. * multiple busy cpu.
  6845. * - For SD_ASYM_PACKING, if the lower numbered cpu's in the scheduler
  6846. * domain span are idle.
  6847. */
  6848. static inline bool nohz_kick_needed(struct rq *rq)
  6849. {
  6850. unsigned long now = jiffies;
  6851. struct sched_domain *sd;
  6852. struct sched_group_capacity *sgc;
  6853. int nr_busy, cpu = rq->cpu;
  6854. bool kick = false;
  6855. if (unlikely(rq->idle_balance))
  6856. return false;
  6857. /*
  6858. * We may be recently in ticked or tickless idle mode. At the first
  6859. * busy tick after returning from idle, we will update the busy stats.
  6860. */
  6861. set_cpu_sd_state_busy();
  6862. nohz_balance_exit_idle(cpu);
  6863. /*
  6864. * None are in tickless mode and hence no need for NOHZ idle load
  6865. * balancing.
  6866. */
  6867. if (likely(!atomic_read(&nohz.nr_cpus)))
  6868. return false;
  6869. if (time_before(now, nohz.next_balance))
  6870. return false;
  6871. if (rq->nr_running >= 2)
  6872. return true;
  6873. rcu_read_lock();
  6874. sd = rcu_dereference(per_cpu(sd_busy, cpu));
  6875. if (sd) {
  6876. sgc = sd->groups->sgc;
  6877. nr_busy = atomic_read(&sgc->nr_busy_cpus);
  6878. if (nr_busy > 1) {
  6879. kick = true;
  6880. goto unlock;
  6881. }
  6882. }
  6883. sd = rcu_dereference(rq->sd);
  6884. if (sd) {
  6885. if ((rq->cfs.h_nr_running >= 1) &&
  6886. check_cpu_capacity(rq, sd)) {
  6887. kick = true;
  6888. goto unlock;
  6889. }
  6890. }
  6891. sd = rcu_dereference(per_cpu(sd_asym, cpu));
  6892. if (sd && (cpumask_first_and(nohz.idle_cpus_mask,
  6893. sched_domain_span(sd)) < cpu)) {
  6894. kick = true;
  6895. goto unlock;
  6896. }
  6897. unlock:
  6898. rcu_read_unlock();
  6899. return kick;
  6900. }
  6901. #else
  6902. static void nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle) { }
  6903. #endif
  6904. /*
  6905. * run_rebalance_domains is triggered when needed from the scheduler tick.
  6906. * Also triggered for nohz idle balancing (with nohz_balancing_kick set).
  6907. */
  6908. static void run_rebalance_domains(struct softirq_action *h)
  6909. {
  6910. struct rq *this_rq = this_rq();
  6911. enum cpu_idle_type idle = this_rq->idle_balance ?
  6912. CPU_IDLE : CPU_NOT_IDLE;
  6913. /*
  6914. * If this cpu has a pending nohz_balance_kick, then do the
  6915. * balancing on behalf of the other idle cpus whose ticks are
  6916. * stopped. Do nohz_idle_balance *before* rebalance_domains to
  6917. * give the idle cpus a chance to load balance. Else we may
  6918. * load balance only within the local sched_domain hierarchy
  6919. * and abort nohz_idle_balance altogether if we pull some load.
  6920. */
  6921. nohz_idle_balance(this_rq, idle);
  6922. rebalance_domains(this_rq, idle);
  6923. }
  6924. /*
  6925. * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
  6926. */
  6927. void trigger_load_balance(struct rq *rq)
  6928. {
  6929. /* Don't need to rebalance while attached to NULL domain */
  6930. if (unlikely(on_null_domain(rq)))
  6931. return;
  6932. if (time_after_eq(jiffies, rq->next_balance))
  6933. raise_softirq(SCHED_SOFTIRQ);
  6934. #ifdef CONFIG_NO_HZ_COMMON
  6935. if (nohz_kick_needed(rq))
  6936. nohz_balancer_kick();
  6937. #endif
  6938. }
  6939. static void rq_online_fair(struct rq *rq)
  6940. {
  6941. update_sysctl();
  6942. update_runtime_enabled(rq);
  6943. }
  6944. static void rq_offline_fair(struct rq *rq)
  6945. {
  6946. update_sysctl();
  6947. /* Ensure any throttled groups are reachable by pick_next_task */
  6948. unthrottle_offline_cfs_rqs(rq);
  6949. }
  6950. #endif /* CONFIG_SMP */
  6951. /*
  6952. * scheduler tick hitting a task of our scheduling class:
  6953. */
  6954. static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)
  6955. {
  6956. struct cfs_rq *cfs_rq;
  6957. struct sched_entity *se = &curr->se;
  6958. for_each_sched_entity(se) {
  6959. cfs_rq = cfs_rq_of(se);
  6960. entity_tick(cfs_rq, se, queued);
  6961. }
  6962. if (static_branch_unlikely(&sched_numa_balancing))
  6963. task_tick_numa(rq, curr);
  6964. }
  6965. /*
  6966. * called on fork with the child task as argument from the parent's context
  6967. * - child not yet on the tasklist
  6968. * - preemption disabled
  6969. */
  6970. static void task_fork_fair(struct task_struct *p)
  6971. {
  6972. struct cfs_rq *cfs_rq;
  6973. struct sched_entity *se = &p->se, *curr;
  6974. int this_cpu = smp_processor_id();
  6975. struct rq *rq = this_rq();
  6976. unsigned long flags;
  6977. raw_spin_lock_irqsave(&rq->lock, flags);
  6978. update_rq_clock(rq);
  6979. cfs_rq = task_cfs_rq(current);
  6980. curr = cfs_rq->curr;
  6981. /*
  6982. * Not only the cpu but also the task_group of the parent might have
  6983. * been changed after parent->se.parent,cfs_rq were copied to
  6984. * child->se.parent,cfs_rq. So call __set_task_cpu() to make those
  6985. * of child point to valid ones.
  6986. */
  6987. rcu_read_lock();
  6988. __set_task_cpu(p, this_cpu);
  6989. rcu_read_unlock();
  6990. update_curr(cfs_rq);
  6991. if (curr)
  6992. se->vruntime = curr->vruntime;
  6993. place_entity(cfs_rq, se, 1);
  6994. if (sysctl_sched_child_runs_first && curr && entity_before(curr, se)) {
  6995. /*
  6996. * Upon rescheduling, sched_class::put_prev_task() will place
  6997. * 'current' within the tree based on its new key value.
  6998. */
  6999. swap(curr->vruntime, se->vruntime);
  7000. resched_curr(rq);
  7001. }
  7002. se->vruntime -= cfs_rq->min_vruntime;
  7003. raw_spin_unlock_irqrestore(&rq->lock, flags);
  7004. }
  7005. /*
  7006. * Priority of the task has changed. Check to see if we preempt
  7007. * the current task.
  7008. */
  7009. static void
  7010. prio_changed_fair(struct rq *rq, struct task_struct *p, int oldprio)
  7011. {
  7012. if (!task_on_rq_queued(p))
  7013. return;
  7014. /*
  7015. * Reschedule if we are currently running on this runqueue and
  7016. * our priority decreased, or if we are not currently running on
  7017. * this runqueue and our priority is higher than the current's
  7018. */
  7019. if (rq->curr == p) {
  7020. if (p->prio > oldprio)
  7021. resched_curr(rq);
  7022. } else
  7023. check_preempt_curr(rq, p, 0);
  7024. }
  7025. static inline bool vruntime_normalized(struct task_struct *p)
  7026. {
  7027. struct sched_entity *se = &p->se;
  7028. /*
  7029. * In both the TASK_ON_RQ_QUEUED and TASK_ON_RQ_MIGRATING cases,
  7030. * the dequeue_entity(.flags=0) will already have normalized the
  7031. * vruntime.
  7032. */
  7033. if (p->on_rq)
  7034. return true;
  7035. /*
  7036. * When !on_rq, vruntime of the task has usually NOT been normalized.
  7037. * But there are some cases where it has already been normalized:
  7038. *
  7039. * - A forked child which is waiting for being woken up by
  7040. * wake_up_new_task().
  7041. * - A task which has been woken up by try_to_wake_up() and
  7042. * waiting for actually being woken up by sched_ttwu_pending().
  7043. */
  7044. if (!se->sum_exec_runtime || p->state == TASK_WAKING)
  7045. return true;
  7046. return false;
  7047. }
  7048. static void detach_task_cfs_rq(struct task_struct *p)
  7049. {
  7050. struct sched_entity *se = &p->se;
  7051. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  7052. if (!vruntime_normalized(p)) {
  7053. /*
  7054. * Fix up our vruntime so that the current sleep doesn't
  7055. * cause 'unlimited' sleep bonus.
  7056. */
  7057. place_entity(cfs_rq, se, 0);
  7058. se->vruntime -= cfs_rq->min_vruntime;
  7059. }
  7060. /* Catch up with the cfs_rq and remove our load when we leave */
  7061. detach_entity_load_avg(cfs_rq, se);
  7062. }
  7063. static void attach_task_cfs_rq(struct task_struct *p)
  7064. {
  7065. struct sched_entity *se = &p->se;
  7066. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  7067. #ifdef CONFIG_FAIR_GROUP_SCHED
  7068. /*
  7069. * Since the real-depth could have been changed (only FAIR
  7070. * class maintain depth value), reset depth properly.
  7071. */
  7072. se->depth = se->parent ? se->parent->depth + 1 : 0;
  7073. #endif
  7074. /* Synchronize task with its cfs_rq */
  7075. attach_entity_load_avg(cfs_rq, se);
  7076. if (!vruntime_normalized(p))
  7077. se->vruntime += cfs_rq->min_vruntime;
  7078. }
  7079. static void switched_from_fair(struct rq *rq, struct task_struct *p)
  7080. {
  7081. detach_task_cfs_rq(p);
  7082. }
  7083. static void switched_to_fair(struct rq *rq, struct task_struct *p)
  7084. {
  7085. attach_task_cfs_rq(p);
  7086. if (task_on_rq_queued(p)) {
  7087. /*
  7088. * We were most likely switched from sched_rt, so
  7089. * kick off the schedule if running, otherwise just see
  7090. * if we can still preempt the current task.
  7091. */
  7092. if (rq->curr == p)
  7093. resched_curr(rq);
  7094. else
  7095. check_preempt_curr(rq, p, 0);
  7096. }
  7097. }
  7098. /* Account for a task changing its policy or group.
  7099. *
  7100. * This routine is mostly called to set cfs_rq->curr field when a task
  7101. * migrates between groups/classes.
  7102. */
  7103. static void set_curr_task_fair(struct rq *rq)
  7104. {
  7105. struct sched_entity *se = &rq->curr->se;
  7106. for_each_sched_entity(se) {
  7107. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  7108. set_next_entity(cfs_rq, se);
  7109. /* ensure bandwidth has been allocated on our new cfs_rq */
  7110. account_cfs_rq_runtime(cfs_rq, 0);
  7111. }
  7112. }
  7113. void init_cfs_rq(struct cfs_rq *cfs_rq)
  7114. {
  7115. cfs_rq->tasks_timeline = RB_ROOT;
  7116. cfs_rq->min_vruntime = (u64)(-(1LL << 20));
  7117. #ifndef CONFIG_64BIT
  7118. cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
  7119. #endif
  7120. #ifdef CONFIG_SMP
  7121. atomic_long_set(&cfs_rq->removed_load_avg, 0);
  7122. atomic_long_set(&cfs_rq->removed_util_avg, 0);
  7123. #endif
  7124. }
  7125. #ifdef CONFIG_FAIR_GROUP_SCHED
  7126. static void task_move_group_fair(struct task_struct *p)
  7127. {
  7128. detach_task_cfs_rq(p);
  7129. set_task_rq(p, task_cpu(p));
  7130. #ifdef CONFIG_SMP
  7131. /* Tell se's cfs_rq has been changed -- migrated */
  7132. p->se.avg.last_update_time = 0;
  7133. #endif
  7134. attach_task_cfs_rq(p);
  7135. }
  7136. void free_fair_sched_group(struct task_group *tg)
  7137. {
  7138. int i;
  7139. destroy_cfs_bandwidth(tg_cfs_bandwidth(tg));
  7140. for_each_possible_cpu(i) {
  7141. if (tg->cfs_rq)
  7142. kfree(tg->cfs_rq[i]);
  7143. if (tg->se)
  7144. kfree(tg->se[i]);
  7145. }
  7146. kfree(tg->cfs_rq);
  7147. kfree(tg->se);
  7148. }
  7149. int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
  7150. {
  7151. struct cfs_rq *cfs_rq;
  7152. struct sched_entity *se;
  7153. int i;
  7154. tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL);
  7155. if (!tg->cfs_rq)
  7156. goto err;
  7157. tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL);
  7158. if (!tg->se)
  7159. goto err;
  7160. tg->shares = NICE_0_LOAD;
  7161. init_cfs_bandwidth(tg_cfs_bandwidth(tg));
  7162. for_each_possible_cpu(i) {
  7163. cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
  7164. GFP_KERNEL, cpu_to_node(i));
  7165. if (!cfs_rq)
  7166. goto err;
  7167. se = kzalloc_node(sizeof(struct sched_entity),
  7168. GFP_KERNEL, cpu_to_node(i));
  7169. if (!se)
  7170. goto err_free_rq;
  7171. init_cfs_rq(cfs_rq);
  7172. init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
  7173. init_entity_runnable_average(se);
  7174. post_init_entity_util_avg(se);
  7175. }
  7176. return 1;
  7177. err_free_rq:
  7178. kfree(cfs_rq);
  7179. err:
  7180. return 0;
  7181. }
  7182. void unregister_fair_sched_group(struct task_group *tg)
  7183. {
  7184. unsigned long flags;
  7185. struct rq *rq;
  7186. int cpu;
  7187. for_each_possible_cpu(cpu) {
  7188. if (tg->se[cpu])
  7189. remove_entity_load_avg(tg->se[cpu]);
  7190. /*
  7191. * Only empty task groups can be destroyed; so we can speculatively
  7192. * check on_list without danger of it being re-added.
  7193. */
  7194. if (!tg->cfs_rq[cpu]->on_list)
  7195. continue;
  7196. rq = cpu_rq(cpu);
  7197. raw_spin_lock_irqsave(&rq->lock, flags);
  7198. list_del_leaf_cfs_rq(tg->cfs_rq[cpu]);
  7199. raw_spin_unlock_irqrestore(&rq->lock, flags);
  7200. }
  7201. }
  7202. void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
  7203. struct sched_entity *se, int cpu,
  7204. struct sched_entity *parent)
  7205. {
  7206. struct rq *rq = cpu_rq(cpu);
  7207. cfs_rq->tg = tg;
  7208. cfs_rq->rq = rq;
  7209. init_cfs_rq_runtime(cfs_rq);
  7210. tg->cfs_rq[cpu] = cfs_rq;
  7211. tg->se[cpu] = se;
  7212. /* se could be NULL for root_task_group */
  7213. if (!se)
  7214. return;
  7215. if (!parent) {
  7216. se->cfs_rq = &rq->cfs;
  7217. se->depth = 0;
  7218. } else {
  7219. se->cfs_rq = parent->my_q;
  7220. se->depth = parent->depth + 1;
  7221. }
  7222. se->my_q = cfs_rq;
  7223. /* guarantee group entities always have weight */
  7224. update_load_set(&se->load, NICE_0_LOAD);
  7225. se->parent = parent;
  7226. }
  7227. static DEFINE_MUTEX(shares_mutex);
  7228. int sched_group_set_shares(struct task_group *tg, unsigned long shares)
  7229. {
  7230. int i;
  7231. unsigned long flags;
  7232. /*
  7233. * We can't change the weight of the root cgroup.
  7234. */
  7235. if (!tg->se[0])
  7236. return -EINVAL;
  7237. shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
  7238. mutex_lock(&shares_mutex);
  7239. if (tg->shares == shares)
  7240. goto done;
  7241. tg->shares = shares;
  7242. for_each_possible_cpu(i) {
  7243. struct rq *rq = cpu_rq(i);
  7244. struct sched_entity *se;
  7245. se = tg->se[i];
  7246. /* Propagate contribution to hierarchy */
  7247. raw_spin_lock_irqsave(&rq->lock, flags);
  7248. /* Possible calls to update_curr() need rq clock */
  7249. update_rq_clock(rq);
  7250. for_each_sched_entity(se)
  7251. update_cfs_shares(group_cfs_rq(se));
  7252. raw_spin_unlock_irqrestore(&rq->lock, flags);
  7253. }
  7254. done:
  7255. mutex_unlock(&shares_mutex);
  7256. return 0;
  7257. }
  7258. #else /* CONFIG_FAIR_GROUP_SCHED */
  7259. void free_fair_sched_group(struct task_group *tg) { }
  7260. int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
  7261. {
  7262. return 1;
  7263. }
  7264. void unregister_fair_sched_group(struct task_group *tg) { }
  7265. #endif /* CONFIG_FAIR_GROUP_SCHED */
  7266. static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task)
  7267. {
  7268. struct sched_entity *se = &task->se;
  7269. unsigned int rr_interval = 0;
  7270. /*
  7271. * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
  7272. * idle runqueue:
  7273. */
  7274. if (rq->cfs.load.weight)
  7275. rr_interval = NS_TO_JIFFIES(sched_slice(cfs_rq_of(se), se));
  7276. return rr_interval;
  7277. }
  7278. /*
  7279. * All the scheduling class methods:
  7280. */
  7281. const struct sched_class fair_sched_class = {
  7282. .next = &idle_sched_class,
  7283. .enqueue_task = enqueue_task_fair,
  7284. .dequeue_task = dequeue_task_fair,
  7285. .yield_task = yield_task_fair,
  7286. .yield_to_task = yield_to_task_fair,
  7287. .check_preempt_curr = check_preempt_wakeup,
  7288. .pick_next_task = pick_next_task_fair,
  7289. .put_prev_task = put_prev_task_fair,
  7290. #ifdef CONFIG_SMP
  7291. .select_task_rq = select_task_rq_fair,
  7292. .migrate_task_rq = migrate_task_rq_fair,
  7293. .rq_online = rq_online_fair,
  7294. .rq_offline = rq_offline_fair,
  7295. .task_dead = task_dead_fair,
  7296. .set_cpus_allowed = set_cpus_allowed_common,
  7297. #endif
  7298. .set_curr_task = set_curr_task_fair,
  7299. .task_tick = task_tick_fair,
  7300. .task_fork = task_fork_fair,
  7301. .prio_changed = prio_changed_fair,
  7302. .switched_from = switched_from_fair,
  7303. .switched_to = switched_to_fair,
  7304. .get_rr_interval = get_rr_interval_fair,
  7305. .update_curr = update_curr_fair,
  7306. #ifdef CONFIG_FAIR_GROUP_SCHED
  7307. .task_move_group = task_move_group_fair,
  7308. #endif
  7309. };
  7310. #ifdef CONFIG_SCHED_DEBUG
  7311. void print_cfs_stats(struct seq_file *m, int cpu)
  7312. {
  7313. struct cfs_rq *cfs_rq;
  7314. rcu_read_lock();
  7315. for_each_leaf_cfs_rq(cpu_rq(cpu), cfs_rq)
  7316. print_cfs_rq(m, cpu, cfs_rq);
  7317. rcu_read_unlock();
  7318. }
  7319. #ifdef CONFIG_NUMA_BALANCING
  7320. void show_numa_stats(struct task_struct *p, struct seq_file *m)
  7321. {
  7322. int node;
  7323. unsigned long tsf = 0, tpf = 0, gsf = 0, gpf = 0;
  7324. for_each_online_node(node) {
  7325. if (p->numa_faults) {
  7326. tsf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 0)];
  7327. tpf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 1)];
  7328. }
  7329. if (p->numa_group) {
  7330. gsf = p->numa_group->faults[task_faults_idx(NUMA_MEM, node, 0)],
  7331. gpf = p->numa_group->faults[task_faults_idx(NUMA_MEM, node, 1)];
  7332. }
  7333. print_numa_stats(m, node, tsf, tpf, gsf, gpf);
  7334. }
  7335. }
  7336. #endif /* CONFIG_NUMA_BALANCING */
  7337. #endif /* CONFIG_SCHED_DEBUG */
  7338. __init void init_sched_fair_class(void)
  7339. {
  7340. #ifdef CONFIG_SMP
  7341. open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
  7342. #ifdef CONFIG_NO_HZ_COMMON
  7343. nohz.next_balance = jiffies;
  7344. zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);
  7345. #endif
  7346. #endif /* SMP */
  7347. }