fair.c 188 KB

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