fair.c 236 KB

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