fair.c 203 KB

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