fair.c 217 KB

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