fair.c 206 KB

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