fair.c 188 KB

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