fair.c 203 KB

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