fair.c 188 KB

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