fair.c 275 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Completely Fair Scheduling (CFS) Class (SCHED_NORMAL/SCHED_BATCH)
  4. *
  5. * Copyright (C) 2007 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
  6. *
  7. * Interactivity improvements by Mike Galbraith
  8. * (C) 2007 Mike Galbraith <efault@gmx.de>
  9. *
  10. * Various enhancements by Dmitry Adamushko.
  11. * (C) 2007 Dmitry Adamushko <dmitry.adamushko@gmail.com>
  12. *
  13. * Group scheduling enhancements by Srivatsa Vaddagiri
  14. * Copyright IBM Corporation, 2007
  15. * Author: Srivatsa Vaddagiri <vatsa@linux.vnet.ibm.com>
  16. *
  17. * Scaled math optimizations by Thomas Gleixner
  18. * Copyright (C) 2007, Thomas Gleixner <tglx@linutronix.de>
  19. *
  20. * Adaptive scheduling granularity, math enhancements by Peter Zijlstra
  21. * Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra
  22. */
  23. #include "sched.h"
  24. #include <trace/events/sched.h>
  25. /*
  26. * Targeted preemption latency for CPU-bound tasks:
  27. *
  28. * NOTE: this latency value is not the same as the concept of
  29. * 'timeslice length' - timeslices in CFS are of variable length
  30. * and have no persistent notion like in traditional, time-slice
  31. * based scheduling concepts.
  32. *
  33. * (to see the precise effective timeslice length of your workload,
  34. * run vmstat and monitor the context-switches (cs) field)
  35. *
  36. * (default: 6ms * (1 + ilog(ncpus)), units: nanoseconds)
  37. */
  38. unsigned int sysctl_sched_latency = 6000000ULL;
  39. unsigned int normalized_sysctl_sched_latency = 6000000ULL;
  40. /*
  41. * The initial- and re-scaling of tunables is configurable
  42. *
  43. * Options are:
  44. *
  45. * SCHED_TUNABLESCALING_NONE - unscaled, always *1
  46. * SCHED_TUNABLESCALING_LOG - scaled logarithmical, *1+ilog(ncpus)
  47. * SCHED_TUNABLESCALING_LINEAR - scaled linear, *ncpus
  48. *
  49. * (default SCHED_TUNABLESCALING_LOG = *(1+ilog(ncpus))
  50. */
  51. enum sched_tunable_scaling sysctl_sched_tunable_scaling = SCHED_TUNABLESCALING_LOG;
  52. /*
  53. * Minimal preemption granularity for CPU-bound tasks:
  54. *
  55. * (default: 0.75 msec * (1 + ilog(ncpus)), units: nanoseconds)
  56. */
  57. unsigned int sysctl_sched_min_granularity = 750000ULL;
  58. unsigned int normalized_sysctl_sched_min_granularity = 750000ULL;
  59. /*
  60. * This value is kept at sysctl_sched_latency/sysctl_sched_min_granularity
  61. */
  62. static unsigned int sched_nr_latency = 8;
  63. /*
  64. * After fork, child runs first. If set to 0 (default) then
  65. * parent will (try to) run first.
  66. */
  67. unsigned int sysctl_sched_child_runs_first __read_mostly;
  68. /*
  69. * SCHED_OTHER wake-up granularity.
  70. *
  71. * This option delays the preemption effects of decoupled workloads
  72. * and reduces their over-scheduling. Synchronous workloads will still
  73. * have immediate wakeup/sleep latencies.
  74. *
  75. * (default: 1 msec * (1 + ilog(ncpus)), units: nanoseconds)
  76. */
  77. unsigned int sysctl_sched_wakeup_granularity = 1000000UL;
  78. unsigned int normalized_sysctl_sched_wakeup_granularity = 1000000UL;
  79. const_debug unsigned int sysctl_sched_migration_cost = 500000UL;
  80. #ifdef CONFIG_SMP
  81. /*
  82. * For asym packing, by default the lower numbered CPU has higher priority.
  83. */
  84. int __weak arch_asym_cpu_priority(int cpu)
  85. {
  86. return -cpu;
  87. }
  88. #endif
  89. #ifdef CONFIG_CFS_BANDWIDTH
  90. /*
  91. * Amount of runtime to allocate from global (tg) to local (per-cfs_rq) pool
  92. * each time a cfs_rq requests quota.
  93. *
  94. * Note: in the case that the slice exceeds the runtime remaining (either due
  95. * to consumption or the quota being specified to be smaller than the slice)
  96. * we will always only issue the remaining available time.
  97. *
  98. * (default: 5 msec, units: microseconds)
  99. */
  100. unsigned int sysctl_sched_cfs_bandwidth_slice = 5000UL;
  101. #endif
  102. /*
  103. * The margin used when comparing utilization with CPU capacity:
  104. * util * margin < capacity * 1024
  105. *
  106. * (default: ~20%)
  107. */
  108. unsigned int capacity_margin = 1280;
  109. static inline void update_load_add(struct load_weight *lw, unsigned long inc)
  110. {
  111. lw->weight += inc;
  112. lw->inv_weight = 0;
  113. }
  114. static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
  115. {
  116. lw->weight -= dec;
  117. lw->inv_weight = 0;
  118. }
  119. static inline void update_load_set(struct load_weight *lw, unsigned long w)
  120. {
  121. lw->weight = w;
  122. lw->inv_weight = 0;
  123. }
  124. /*
  125. * Increase the granularity value when there are more CPUs,
  126. * because with more CPUs the 'effective latency' as visible
  127. * to users decreases. But the relationship is not linear,
  128. * so pick a second-best guess by going with the log2 of the
  129. * number of CPUs.
  130. *
  131. * This idea comes from the SD scheduler of Con Kolivas:
  132. */
  133. static unsigned int get_update_sysctl_factor(void)
  134. {
  135. unsigned int cpus = min_t(unsigned int, num_online_cpus(), 8);
  136. unsigned int factor;
  137. switch (sysctl_sched_tunable_scaling) {
  138. case SCHED_TUNABLESCALING_NONE:
  139. factor = 1;
  140. break;
  141. case SCHED_TUNABLESCALING_LINEAR:
  142. factor = cpus;
  143. break;
  144. case SCHED_TUNABLESCALING_LOG:
  145. default:
  146. factor = 1 + ilog2(cpus);
  147. break;
  148. }
  149. return factor;
  150. }
  151. static void update_sysctl(void)
  152. {
  153. unsigned int factor = get_update_sysctl_factor();
  154. #define SET_SYSCTL(name) \
  155. (sysctl_##name = (factor) * normalized_sysctl_##name)
  156. SET_SYSCTL(sched_min_granularity);
  157. SET_SYSCTL(sched_latency);
  158. SET_SYSCTL(sched_wakeup_granularity);
  159. #undef SET_SYSCTL
  160. }
  161. void sched_init_granularity(void)
  162. {
  163. update_sysctl();
  164. }
  165. #define WMULT_CONST (~0U)
  166. #define WMULT_SHIFT 32
  167. static void __update_inv_weight(struct load_weight *lw)
  168. {
  169. unsigned long w;
  170. if (likely(lw->inv_weight))
  171. return;
  172. w = scale_load_down(lw->weight);
  173. if (BITS_PER_LONG > 32 && unlikely(w >= WMULT_CONST))
  174. lw->inv_weight = 1;
  175. else if (unlikely(!w))
  176. lw->inv_weight = WMULT_CONST;
  177. else
  178. lw->inv_weight = WMULT_CONST / w;
  179. }
  180. /*
  181. * delta_exec * weight / lw.weight
  182. * OR
  183. * (delta_exec * (weight * lw->inv_weight)) >> WMULT_SHIFT
  184. *
  185. * Either weight := NICE_0_LOAD and lw \e sched_prio_to_wmult[], in which case
  186. * we're guaranteed shift stays positive because inv_weight is guaranteed to
  187. * fit 32 bits, and NICE_0_LOAD gives another 10 bits; therefore shift >= 22.
  188. *
  189. * Or, weight =< lw.weight (because lw.weight is the runqueue weight), thus
  190. * weight/lw.weight <= 1, and therefore our shift will also be positive.
  191. */
  192. static u64 __calc_delta(u64 delta_exec, unsigned long weight, struct load_weight *lw)
  193. {
  194. u64 fact = scale_load_down(weight);
  195. int shift = WMULT_SHIFT;
  196. __update_inv_weight(lw);
  197. if (unlikely(fact >> 32)) {
  198. while (fact >> 32) {
  199. fact >>= 1;
  200. shift--;
  201. }
  202. }
  203. /* hint to use a 32x32->64 mul */
  204. fact = (u64)(u32)fact * lw->inv_weight;
  205. while (fact >> 32) {
  206. fact >>= 1;
  207. shift--;
  208. }
  209. return mul_u64_u32_shr(delta_exec, fact, shift);
  210. }
  211. const struct sched_class fair_sched_class;
  212. /**************************************************************
  213. * CFS operations on generic schedulable entities:
  214. */
  215. #ifdef CONFIG_FAIR_GROUP_SCHED
  216. /* cpu runqueue to which this cfs_rq is attached */
  217. static inline struct rq *rq_of(struct cfs_rq *cfs_rq)
  218. {
  219. return cfs_rq->rq;
  220. }
  221. /* An entity is a task if it doesn't "own" a runqueue */
  222. #define entity_is_task(se) (!se->my_q)
  223. static inline struct task_struct *task_of(struct sched_entity *se)
  224. {
  225. SCHED_WARN_ON(!entity_is_task(se));
  226. return container_of(se, struct task_struct, se);
  227. }
  228. /* Walk up scheduling entities hierarchy */
  229. #define for_each_sched_entity(se) \
  230. for (; se; se = se->parent)
  231. static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
  232. {
  233. return p->se.cfs_rq;
  234. }
  235. /* runqueue on which this entity is (to be) queued */
  236. static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se)
  237. {
  238. return se->cfs_rq;
  239. }
  240. /* runqueue "owned" by this group */
  241. static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
  242. {
  243. return grp->my_q;
  244. }
  245. static inline void list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
  246. {
  247. if (!cfs_rq->on_list) {
  248. struct rq *rq = rq_of(cfs_rq);
  249. int cpu = cpu_of(rq);
  250. /*
  251. * Ensure we either appear before our parent (if already
  252. * enqueued) or force our parent to appear after us when it is
  253. * enqueued. The fact that we always enqueue bottom-up
  254. * reduces this to two cases and a special case for the root
  255. * cfs_rq. Furthermore, it also means that we will always reset
  256. * tmp_alone_branch either when the branch is connected
  257. * to a tree or when we reach the beg of the tree
  258. */
  259. if (cfs_rq->tg->parent &&
  260. cfs_rq->tg->parent->cfs_rq[cpu]->on_list) {
  261. /*
  262. * If parent is already on the list, we add the child
  263. * just before. Thanks to circular linked property of
  264. * the list, this means to put the child at the tail
  265. * of the list that starts by parent.
  266. */
  267. list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
  268. &(cfs_rq->tg->parent->cfs_rq[cpu]->leaf_cfs_rq_list));
  269. /*
  270. * The branch is now connected to its tree so we can
  271. * reset tmp_alone_branch to the beginning of the
  272. * list.
  273. */
  274. rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
  275. } else if (!cfs_rq->tg->parent) {
  276. /*
  277. * cfs rq without parent should be put
  278. * at the tail of the list.
  279. */
  280. list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
  281. &rq->leaf_cfs_rq_list);
  282. /*
  283. * We have reach the beg of a tree so we can reset
  284. * tmp_alone_branch to the beginning of the list.
  285. */
  286. rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
  287. } else {
  288. /*
  289. * The parent has not already been added so we want to
  290. * make sure that it will be put after us.
  291. * tmp_alone_branch points to the beg of the branch
  292. * where we will add parent.
  293. */
  294. list_add_rcu(&cfs_rq->leaf_cfs_rq_list,
  295. rq->tmp_alone_branch);
  296. /*
  297. * update tmp_alone_branch to points to the new beg
  298. * of the branch
  299. */
  300. rq->tmp_alone_branch = &cfs_rq->leaf_cfs_rq_list;
  301. }
  302. cfs_rq->on_list = 1;
  303. }
  304. }
  305. static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
  306. {
  307. if (cfs_rq->on_list) {
  308. list_del_rcu(&cfs_rq->leaf_cfs_rq_list);
  309. cfs_rq->on_list = 0;
  310. }
  311. }
  312. /* Iterate thr' all leaf cfs_rq's on a runqueue */
  313. #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) \
  314. list_for_each_entry_safe(cfs_rq, pos, &rq->leaf_cfs_rq_list, \
  315. leaf_cfs_rq_list)
  316. /* Do the two (enqueued) entities belong to the same group ? */
  317. static inline struct cfs_rq *
  318. is_same_group(struct sched_entity *se, struct sched_entity *pse)
  319. {
  320. if (se->cfs_rq == pse->cfs_rq)
  321. return se->cfs_rq;
  322. return NULL;
  323. }
  324. static inline struct sched_entity *parent_entity(struct sched_entity *se)
  325. {
  326. return se->parent;
  327. }
  328. static void
  329. find_matching_se(struct sched_entity **se, struct sched_entity **pse)
  330. {
  331. int se_depth, pse_depth;
  332. /*
  333. * preemption test can be made between sibling entities who are in the
  334. * same cfs_rq i.e who have a common parent. Walk up the hierarchy of
  335. * both tasks until we find their ancestors who are siblings of common
  336. * parent.
  337. */
  338. /* First walk up until both entities are at same depth */
  339. se_depth = (*se)->depth;
  340. pse_depth = (*pse)->depth;
  341. while (se_depth > pse_depth) {
  342. se_depth--;
  343. *se = parent_entity(*se);
  344. }
  345. while (pse_depth > se_depth) {
  346. pse_depth--;
  347. *pse = parent_entity(*pse);
  348. }
  349. while (!is_same_group(*se, *pse)) {
  350. *se = parent_entity(*se);
  351. *pse = parent_entity(*pse);
  352. }
  353. }
  354. #else /* !CONFIG_FAIR_GROUP_SCHED */
  355. static inline struct task_struct *task_of(struct sched_entity *se)
  356. {
  357. return container_of(se, struct task_struct, se);
  358. }
  359. static inline struct rq *rq_of(struct cfs_rq *cfs_rq)
  360. {
  361. return container_of(cfs_rq, struct rq, cfs);
  362. }
  363. #define entity_is_task(se) 1
  364. #define for_each_sched_entity(se) \
  365. for (; se; se = NULL)
  366. static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
  367. {
  368. return &task_rq(p)->cfs;
  369. }
  370. static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se)
  371. {
  372. struct task_struct *p = task_of(se);
  373. struct rq *rq = task_rq(p);
  374. return &rq->cfs;
  375. }
  376. /* runqueue "owned" by this group */
  377. static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
  378. {
  379. return NULL;
  380. }
  381. static inline void list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
  382. {
  383. }
  384. static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
  385. {
  386. }
  387. #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) \
  388. for (cfs_rq = &rq->cfs, pos = NULL; cfs_rq; cfs_rq = pos)
  389. static inline struct sched_entity *parent_entity(struct sched_entity *se)
  390. {
  391. return NULL;
  392. }
  393. static inline void
  394. find_matching_se(struct sched_entity **se, struct sched_entity **pse)
  395. {
  396. }
  397. #endif /* CONFIG_FAIR_GROUP_SCHED */
  398. static __always_inline
  399. void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec);
  400. /**************************************************************
  401. * Scheduling class tree data structure manipulation methods:
  402. */
  403. static inline u64 max_vruntime(u64 max_vruntime, u64 vruntime)
  404. {
  405. s64 delta = (s64)(vruntime - max_vruntime);
  406. if (delta > 0)
  407. max_vruntime = vruntime;
  408. return max_vruntime;
  409. }
  410. static inline u64 min_vruntime(u64 min_vruntime, u64 vruntime)
  411. {
  412. s64 delta = (s64)(vruntime - min_vruntime);
  413. if (delta < 0)
  414. min_vruntime = vruntime;
  415. return min_vruntime;
  416. }
  417. static inline int entity_before(struct sched_entity *a,
  418. struct sched_entity *b)
  419. {
  420. return (s64)(a->vruntime - b->vruntime) < 0;
  421. }
  422. static void update_min_vruntime(struct cfs_rq *cfs_rq)
  423. {
  424. struct sched_entity *curr = cfs_rq->curr;
  425. struct rb_node *leftmost = rb_first_cached(&cfs_rq->tasks_timeline);
  426. u64 vruntime = cfs_rq->min_vruntime;
  427. if (curr) {
  428. if (curr->on_rq)
  429. vruntime = curr->vruntime;
  430. else
  431. curr = NULL;
  432. }
  433. if (leftmost) { /* non-empty tree */
  434. struct sched_entity *se;
  435. se = rb_entry(leftmost, struct sched_entity, run_node);
  436. if (!curr)
  437. vruntime = se->vruntime;
  438. else
  439. vruntime = min_vruntime(vruntime, se->vruntime);
  440. }
  441. /* ensure we never gain time by being placed backwards. */
  442. cfs_rq->min_vruntime = max_vruntime(cfs_rq->min_vruntime, vruntime);
  443. #ifndef CONFIG_64BIT
  444. smp_wmb();
  445. cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
  446. #endif
  447. }
  448. /*
  449. * Enqueue an entity into the rb-tree:
  450. */
  451. static void __enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
  452. {
  453. struct rb_node **link = &cfs_rq->tasks_timeline.rb_root.rb_node;
  454. struct rb_node *parent = NULL;
  455. struct sched_entity *entry;
  456. bool leftmost = true;
  457. /*
  458. * Find the right place in the rbtree:
  459. */
  460. while (*link) {
  461. parent = *link;
  462. entry = rb_entry(parent, struct sched_entity, run_node);
  463. /*
  464. * We dont care about collisions. Nodes with
  465. * the same key stay together.
  466. */
  467. if (entity_before(se, entry)) {
  468. link = &parent->rb_left;
  469. } else {
  470. link = &parent->rb_right;
  471. leftmost = false;
  472. }
  473. }
  474. rb_link_node(&se->run_node, parent, link);
  475. rb_insert_color_cached(&se->run_node,
  476. &cfs_rq->tasks_timeline, leftmost);
  477. }
  478. static void __dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
  479. {
  480. rb_erase_cached(&se->run_node, &cfs_rq->tasks_timeline);
  481. }
  482. struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq)
  483. {
  484. struct rb_node *left = rb_first_cached(&cfs_rq->tasks_timeline);
  485. if (!left)
  486. return NULL;
  487. return rb_entry(left, struct sched_entity, run_node);
  488. }
  489. static struct sched_entity *__pick_next_entity(struct sched_entity *se)
  490. {
  491. struct rb_node *next = rb_next(&se->run_node);
  492. if (!next)
  493. return NULL;
  494. return rb_entry(next, struct sched_entity, run_node);
  495. }
  496. #ifdef CONFIG_SCHED_DEBUG
  497. struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq)
  498. {
  499. struct rb_node *last = rb_last(&cfs_rq->tasks_timeline.rb_root);
  500. if (!last)
  501. return NULL;
  502. return rb_entry(last, struct sched_entity, run_node);
  503. }
  504. /**************************************************************
  505. * Scheduling class statistics methods:
  506. */
  507. int sched_proc_update_handler(struct ctl_table *table, int write,
  508. void __user *buffer, size_t *lenp,
  509. loff_t *ppos)
  510. {
  511. int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
  512. unsigned int factor = get_update_sysctl_factor();
  513. if (ret || !write)
  514. return ret;
  515. sched_nr_latency = DIV_ROUND_UP(sysctl_sched_latency,
  516. sysctl_sched_min_granularity);
  517. #define WRT_SYSCTL(name) \
  518. (normalized_sysctl_##name = sysctl_##name / (factor))
  519. WRT_SYSCTL(sched_min_granularity);
  520. WRT_SYSCTL(sched_latency);
  521. WRT_SYSCTL(sched_wakeup_granularity);
  522. #undef WRT_SYSCTL
  523. return 0;
  524. }
  525. #endif
  526. /*
  527. * delta /= w
  528. */
  529. static inline u64 calc_delta_fair(u64 delta, struct sched_entity *se)
  530. {
  531. if (unlikely(se->load.weight != NICE_0_LOAD))
  532. delta = __calc_delta(delta, NICE_0_LOAD, &se->load);
  533. return delta;
  534. }
  535. /*
  536. * The idea is to set a period in which each task runs once.
  537. *
  538. * When there are too many tasks (sched_nr_latency) we have to stretch
  539. * this period because otherwise the slices get too small.
  540. *
  541. * p = (nr <= nl) ? l : l*nr/nl
  542. */
  543. static u64 __sched_period(unsigned long nr_running)
  544. {
  545. if (unlikely(nr_running > sched_nr_latency))
  546. return nr_running * sysctl_sched_min_granularity;
  547. else
  548. return sysctl_sched_latency;
  549. }
  550. /*
  551. * We calculate the wall-time slice from the period by taking a part
  552. * proportional to the weight.
  553. *
  554. * s = p*P[w/rw]
  555. */
  556. static u64 sched_slice(struct cfs_rq *cfs_rq, struct sched_entity *se)
  557. {
  558. u64 slice = __sched_period(cfs_rq->nr_running + !se->on_rq);
  559. for_each_sched_entity(se) {
  560. struct load_weight *load;
  561. struct load_weight lw;
  562. cfs_rq = cfs_rq_of(se);
  563. load = &cfs_rq->load;
  564. if (unlikely(!se->on_rq)) {
  565. lw = cfs_rq->load;
  566. update_load_add(&lw, se->load.weight);
  567. load = &lw;
  568. }
  569. slice = __calc_delta(slice, se->load.weight, load);
  570. }
  571. return slice;
  572. }
  573. /*
  574. * We calculate the vruntime slice of a to-be-inserted task.
  575. *
  576. * vs = s/w
  577. */
  578. static u64 sched_vslice(struct cfs_rq *cfs_rq, struct sched_entity *se)
  579. {
  580. return calc_delta_fair(sched_slice(cfs_rq, se), se);
  581. }
  582. #ifdef CONFIG_SMP
  583. #include "sched-pelt.h"
  584. static int select_idle_sibling(struct task_struct *p, int prev_cpu, int cpu);
  585. static unsigned long task_h_load(struct task_struct *p);
  586. /* Give new sched_entity start runnable values to heavy its load in infant time */
  587. void init_entity_runnable_average(struct sched_entity *se)
  588. {
  589. struct sched_avg *sa = &se->avg;
  590. memset(sa, 0, sizeof(*sa));
  591. /*
  592. * Tasks are intialized with full load to be seen as heavy tasks until
  593. * they get a chance to stabilize to their real load level.
  594. * Group entities are intialized with zero load to reflect the fact that
  595. * nothing has been attached to the task group yet.
  596. */
  597. if (entity_is_task(se))
  598. sa->runnable_load_avg = sa->load_avg = scale_load_down(se->load.weight);
  599. se->runnable_weight = se->load.weight;
  600. /* when this task enqueue'ed, it will contribute to its cfs_rq's load_avg */
  601. }
  602. static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq);
  603. static void attach_entity_cfs_rq(struct sched_entity *se);
  604. /*
  605. * With new tasks being created, their initial util_avgs are extrapolated
  606. * based on the cfs_rq's current util_avg:
  607. *
  608. * util_avg = cfs_rq->util_avg / (cfs_rq->load_avg + 1) * se.load.weight
  609. *
  610. * However, in many cases, the above util_avg does not give a desired
  611. * value. Moreover, the sum of the util_avgs may be divergent, such
  612. * as when the series is a harmonic series.
  613. *
  614. * To solve this problem, we also cap the util_avg of successive tasks to
  615. * only 1/2 of the left utilization budget:
  616. *
  617. * util_avg_cap = (1024 - cfs_rq->avg.util_avg) / 2^n
  618. *
  619. * where n denotes the nth task.
  620. *
  621. * For example, a simplest series from the beginning would be like:
  622. *
  623. * task util_avg: 512, 256, 128, 64, 32, 16, 8, ...
  624. * cfs_rq util_avg: 512, 768, 896, 960, 992, 1008, 1016, ...
  625. *
  626. * Finally, that extrapolated util_avg is clamped to the cap (util_avg_cap)
  627. * if util_avg > util_avg_cap.
  628. */
  629. void post_init_entity_util_avg(struct sched_entity *se)
  630. {
  631. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  632. struct sched_avg *sa = &se->avg;
  633. long cap = (long)(SCHED_CAPACITY_SCALE - cfs_rq->avg.util_avg) / 2;
  634. if (cap > 0) {
  635. if (cfs_rq->avg.util_avg != 0) {
  636. sa->util_avg = cfs_rq->avg.util_avg * se->load.weight;
  637. sa->util_avg /= (cfs_rq->avg.load_avg + 1);
  638. if (sa->util_avg > cap)
  639. sa->util_avg = cap;
  640. } else {
  641. sa->util_avg = cap;
  642. }
  643. }
  644. if (entity_is_task(se)) {
  645. struct task_struct *p = task_of(se);
  646. if (p->sched_class != &fair_sched_class) {
  647. /*
  648. * For !fair tasks do:
  649. *
  650. update_cfs_rq_load_avg(now, cfs_rq);
  651. attach_entity_load_avg(cfs_rq, se, 0);
  652. switched_from_fair(rq, p);
  653. *
  654. * such that the next switched_to_fair() has the
  655. * expected state.
  656. */
  657. se->avg.last_update_time = cfs_rq_clock_task(cfs_rq);
  658. return;
  659. }
  660. }
  661. attach_entity_cfs_rq(se);
  662. }
  663. #else /* !CONFIG_SMP */
  664. void init_entity_runnable_average(struct sched_entity *se)
  665. {
  666. }
  667. void post_init_entity_util_avg(struct sched_entity *se)
  668. {
  669. }
  670. static void update_tg_load_avg(struct cfs_rq *cfs_rq, int force)
  671. {
  672. }
  673. #endif /* CONFIG_SMP */
  674. /*
  675. * Update the current task's runtime statistics.
  676. */
  677. static void update_curr(struct cfs_rq *cfs_rq)
  678. {
  679. struct sched_entity *curr = cfs_rq->curr;
  680. u64 now = rq_clock_task(rq_of(cfs_rq));
  681. u64 delta_exec;
  682. if (unlikely(!curr))
  683. return;
  684. delta_exec = now - curr->exec_start;
  685. if (unlikely((s64)delta_exec <= 0))
  686. return;
  687. curr->exec_start = now;
  688. schedstat_set(curr->statistics.exec_max,
  689. max(delta_exec, curr->statistics.exec_max));
  690. curr->sum_exec_runtime += delta_exec;
  691. schedstat_add(cfs_rq->exec_clock, delta_exec);
  692. curr->vruntime += calc_delta_fair(delta_exec, curr);
  693. update_min_vruntime(cfs_rq);
  694. if (entity_is_task(curr)) {
  695. struct task_struct *curtask = task_of(curr);
  696. trace_sched_stat_runtime(curtask, delta_exec, curr->vruntime);
  697. cgroup_account_cputime(curtask, delta_exec);
  698. account_group_exec_runtime(curtask, delta_exec);
  699. }
  700. account_cfs_rq_runtime(cfs_rq, delta_exec);
  701. }
  702. static void update_curr_fair(struct rq *rq)
  703. {
  704. update_curr(cfs_rq_of(&rq->curr->se));
  705. }
  706. static inline void
  707. update_stats_wait_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
  708. {
  709. u64 wait_start, prev_wait_start;
  710. if (!schedstat_enabled())
  711. return;
  712. wait_start = rq_clock(rq_of(cfs_rq));
  713. prev_wait_start = schedstat_val(se->statistics.wait_start);
  714. if (entity_is_task(se) && task_on_rq_migrating(task_of(se)) &&
  715. likely(wait_start > prev_wait_start))
  716. wait_start -= prev_wait_start;
  717. __schedstat_set(se->statistics.wait_start, wait_start);
  718. }
  719. static inline void
  720. update_stats_wait_end(struct cfs_rq *cfs_rq, struct sched_entity *se)
  721. {
  722. struct task_struct *p;
  723. u64 delta;
  724. if (!schedstat_enabled())
  725. return;
  726. delta = rq_clock(rq_of(cfs_rq)) - schedstat_val(se->statistics.wait_start);
  727. if (entity_is_task(se)) {
  728. p = task_of(se);
  729. if (task_on_rq_migrating(p)) {
  730. /*
  731. * Preserve migrating task's wait time so wait_start
  732. * time stamp can be adjusted to accumulate wait time
  733. * prior to migration.
  734. */
  735. __schedstat_set(se->statistics.wait_start, delta);
  736. return;
  737. }
  738. trace_sched_stat_wait(p, delta);
  739. }
  740. __schedstat_set(se->statistics.wait_max,
  741. max(schedstat_val(se->statistics.wait_max), delta));
  742. __schedstat_inc(se->statistics.wait_count);
  743. __schedstat_add(se->statistics.wait_sum, delta);
  744. __schedstat_set(se->statistics.wait_start, 0);
  745. }
  746. static inline void
  747. update_stats_enqueue_sleeper(struct cfs_rq *cfs_rq, struct sched_entity *se)
  748. {
  749. struct task_struct *tsk = NULL;
  750. u64 sleep_start, block_start;
  751. if (!schedstat_enabled())
  752. return;
  753. sleep_start = schedstat_val(se->statistics.sleep_start);
  754. block_start = schedstat_val(se->statistics.block_start);
  755. if (entity_is_task(se))
  756. tsk = task_of(se);
  757. if (sleep_start) {
  758. u64 delta = rq_clock(rq_of(cfs_rq)) - sleep_start;
  759. if ((s64)delta < 0)
  760. delta = 0;
  761. if (unlikely(delta > schedstat_val(se->statistics.sleep_max)))
  762. __schedstat_set(se->statistics.sleep_max, delta);
  763. __schedstat_set(se->statistics.sleep_start, 0);
  764. __schedstat_add(se->statistics.sum_sleep_runtime, delta);
  765. if (tsk) {
  766. account_scheduler_latency(tsk, delta >> 10, 1);
  767. trace_sched_stat_sleep(tsk, delta);
  768. }
  769. }
  770. if (block_start) {
  771. u64 delta = rq_clock(rq_of(cfs_rq)) - block_start;
  772. if ((s64)delta < 0)
  773. delta = 0;
  774. if (unlikely(delta > schedstat_val(se->statistics.block_max)))
  775. __schedstat_set(se->statistics.block_max, delta);
  776. __schedstat_set(se->statistics.block_start, 0);
  777. __schedstat_add(se->statistics.sum_sleep_runtime, delta);
  778. if (tsk) {
  779. if (tsk->in_iowait) {
  780. __schedstat_add(se->statistics.iowait_sum, delta);
  781. __schedstat_inc(se->statistics.iowait_count);
  782. trace_sched_stat_iowait(tsk, delta);
  783. }
  784. trace_sched_stat_blocked(tsk, delta);
  785. /*
  786. * Blocking time is in units of nanosecs, so shift by
  787. * 20 to get a milliseconds-range estimation of the
  788. * amount of time that the task spent sleeping:
  789. */
  790. if (unlikely(prof_on == SLEEP_PROFILING)) {
  791. profile_hits(SLEEP_PROFILING,
  792. (void *)get_wchan(tsk),
  793. delta >> 20);
  794. }
  795. account_scheduler_latency(tsk, delta >> 10, 0);
  796. }
  797. }
  798. }
  799. /*
  800. * Task is being enqueued - update stats:
  801. */
  802. static inline void
  803. update_stats_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
  804. {
  805. if (!schedstat_enabled())
  806. return;
  807. /*
  808. * Are we enqueueing a waiting task? (for current tasks
  809. * a dequeue/enqueue event is a NOP)
  810. */
  811. if (se != cfs_rq->curr)
  812. update_stats_wait_start(cfs_rq, se);
  813. if (flags & ENQUEUE_WAKEUP)
  814. update_stats_enqueue_sleeper(cfs_rq, se);
  815. }
  816. static inline void
  817. update_stats_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
  818. {
  819. if (!schedstat_enabled())
  820. return;
  821. /*
  822. * Mark the end of the wait period if dequeueing a
  823. * waiting task:
  824. */
  825. if (se != cfs_rq->curr)
  826. update_stats_wait_end(cfs_rq, se);
  827. if ((flags & DEQUEUE_SLEEP) && entity_is_task(se)) {
  828. struct task_struct *tsk = task_of(se);
  829. if (tsk->state & TASK_INTERRUPTIBLE)
  830. __schedstat_set(se->statistics.sleep_start,
  831. rq_clock(rq_of(cfs_rq)));
  832. if (tsk->state & TASK_UNINTERRUPTIBLE)
  833. __schedstat_set(se->statistics.block_start,
  834. rq_clock(rq_of(cfs_rq)));
  835. }
  836. }
  837. /*
  838. * We are picking a new current task - update its stats:
  839. */
  840. static inline void
  841. update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
  842. {
  843. /*
  844. * We are starting a new run period:
  845. */
  846. se->exec_start = rq_clock_task(rq_of(cfs_rq));
  847. }
  848. /**************************************************
  849. * Scheduling class queueing methods:
  850. */
  851. #ifdef CONFIG_NUMA_BALANCING
  852. /*
  853. * Approximate time to scan a full NUMA task in ms. The task scan period is
  854. * calculated based on the tasks virtual memory size and
  855. * numa_balancing_scan_size.
  856. */
  857. unsigned int sysctl_numa_balancing_scan_period_min = 1000;
  858. unsigned int sysctl_numa_balancing_scan_period_max = 60000;
  859. /* Portion of address space to scan in MB */
  860. unsigned int sysctl_numa_balancing_scan_size = 256;
  861. /* Scan @scan_size MB every @scan_period after an initial @scan_delay in ms */
  862. unsigned int sysctl_numa_balancing_scan_delay = 1000;
  863. struct numa_group {
  864. atomic_t refcount;
  865. spinlock_t lock; /* nr_tasks, tasks */
  866. int nr_tasks;
  867. pid_t gid;
  868. int active_nodes;
  869. struct rcu_head rcu;
  870. unsigned long total_faults;
  871. unsigned long max_faults_cpu;
  872. /*
  873. * Faults_cpu is used to decide whether memory should move
  874. * towards the CPU. As a consequence, these stats are weighted
  875. * more by CPU use than by memory faults.
  876. */
  877. unsigned long *faults_cpu;
  878. unsigned long faults[0];
  879. };
  880. static inline unsigned long group_faults_priv(struct numa_group *ng);
  881. static inline unsigned long group_faults_shared(struct numa_group *ng);
  882. static unsigned int task_nr_scan_windows(struct task_struct *p)
  883. {
  884. unsigned long rss = 0;
  885. unsigned long nr_scan_pages;
  886. /*
  887. * Calculations based on RSS as non-present and empty pages are skipped
  888. * by the PTE scanner and NUMA hinting faults should be trapped based
  889. * on resident pages
  890. */
  891. nr_scan_pages = sysctl_numa_balancing_scan_size << (20 - PAGE_SHIFT);
  892. rss = get_mm_rss(p->mm);
  893. if (!rss)
  894. rss = nr_scan_pages;
  895. rss = round_up(rss, nr_scan_pages);
  896. return rss / nr_scan_pages;
  897. }
  898. /* For sanitys sake, never scan more PTEs than MAX_SCAN_WINDOW MB/sec. */
  899. #define MAX_SCAN_WINDOW 2560
  900. static unsigned int task_scan_min(struct task_struct *p)
  901. {
  902. unsigned int scan_size = READ_ONCE(sysctl_numa_balancing_scan_size);
  903. unsigned int scan, floor;
  904. unsigned int windows = 1;
  905. if (scan_size < MAX_SCAN_WINDOW)
  906. windows = MAX_SCAN_WINDOW / scan_size;
  907. floor = 1000 / windows;
  908. scan = sysctl_numa_balancing_scan_period_min / task_nr_scan_windows(p);
  909. return max_t(unsigned int, floor, scan);
  910. }
  911. static unsigned int task_scan_start(struct task_struct *p)
  912. {
  913. unsigned long smin = task_scan_min(p);
  914. unsigned long period = smin;
  915. /* Scale the maximum scan period with the amount of shared memory. */
  916. if (p->numa_group) {
  917. struct numa_group *ng = p->numa_group;
  918. unsigned long shared = group_faults_shared(ng);
  919. unsigned long private = group_faults_priv(ng);
  920. period *= atomic_read(&ng->refcount);
  921. period *= shared + 1;
  922. period /= private + shared + 1;
  923. }
  924. return max(smin, period);
  925. }
  926. static unsigned int task_scan_max(struct task_struct *p)
  927. {
  928. unsigned long smin = task_scan_min(p);
  929. unsigned long smax;
  930. /* Watch for min being lower than max due to floor calculations */
  931. smax = sysctl_numa_balancing_scan_period_max / task_nr_scan_windows(p);
  932. /* Scale the maximum scan period with the amount of shared memory. */
  933. if (p->numa_group) {
  934. struct numa_group *ng = p->numa_group;
  935. unsigned long shared = group_faults_shared(ng);
  936. unsigned long private = group_faults_priv(ng);
  937. unsigned long period = smax;
  938. period *= atomic_read(&ng->refcount);
  939. period *= shared + 1;
  940. period /= private + shared + 1;
  941. smax = max(smax, period);
  942. }
  943. return max(smin, smax);
  944. }
  945. void init_numa_balancing(unsigned long clone_flags, struct task_struct *p)
  946. {
  947. int mm_users = 0;
  948. struct mm_struct *mm = p->mm;
  949. if (mm) {
  950. mm_users = atomic_read(&mm->mm_users);
  951. if (mm_users == 1) {
  952. mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
  953. mm->numa_scan_seq = 0;
  954. }
  955. }
  956. p->node_stamp = 0;
  957. p->numa_scan_seq = mm ? mm->numa_scan_seq : 0;
  958. p->numa_scan_period = sysctl_numa_balancing_scan_delay;
  959. p->numa_work.next = &p->numa_work;
  960. p->numa_faults = NULL;
  961. p->numa_group = NULL;
  962. p->last_task_numa_placement = 0;
  963. p->last_sum_exec_runtime = 0;
  964. /* New address space, reset the preferred nid */
  965. if (!(clone_flags & CLONE_VM)) {
  966. p->numa_preferred_nid = -1;
  967. return;
  968. }
  969. /*
  970. * New thread, keep existing numa_preferred_nid which should be copied
  971. * already by arch_dup_task_struct but stagger when scans start.
  972. */
  973. if (mm) {
  974. unsigned int delay;
  975. delay = min_t(unsigned int, task_scan_max(current),
  976. current->numa_scan_period * mm_users * NSEC_PER_MSEC);
  977. delay += 2 * TICK_NSEC;
  978. p->node_stamp = delay;
  979. }
  980. }
  981. static void account_numa_enqueue(struct rq *rq, struct task_struct *p)
  982. {
  983. rq->nr_numa_running += (p->numa_preferred_nid != -1);
  984. rq->nr_preferred_running += (p->numa_preferred_nid == task_node(p));
  985. }
  986. static void account_numa_dequeue(struct rq *rq, struct task_struct *p)
  987. {
  988. rq->nr_numa_running -= (p->numa_preferred_nid != -1);
  989. rq->nr_preferred_running -= (p->numa_preferred_nid == task_node(p));
  990. }
  991. /* Shared or private faults. */
  992. #define NR_NUMA_HINT_FAULT_TYPES 2
  993. /* Memory and CPU locality */
  994. #define NR_NUMA_HINT_FAULT_STATS (NR_NUMA_HINT_FAULT_TYPES * 2)
  995. /* Averaged statistics, and temporary buffers. */
  996. #define NR_NUMA_HINT_FAULT_BUCKETS (NR_NUMA_HINT_FAULT_STATS * 2)
  997. pid_t task_numa_group_id(struct task_struct *p)
  998. {
  999. return p->numa_group ? p->numa_group->gid : 0;
  1000. }
  1001. /*
  1002. * The averaged statistics, shared & private, memory & CPU,
  1003. * occupy the first half of the array. The second half of the
  1004. * array is for current counters, which are averaged into the
  1005. * first set by task_numa_placement.
  1006. */
  1007. static inline int task_faults_idx(enum numa_faults_stats s, int nid, int priv)
  1008. {
  1009. return NR_NUMA_HINT_FAULT_TYPES * (s * nr_node_ids + nid) + priv;
  1010. }
  1011. static inline unsigned long task_faults(struct task_struct *p, int nid)
  1012. {
  1013. if (!p->numa_faults)
  1014. return 0;
  1015. return p->numa_faults[task_faults_idx(NUMA_MEM, nid, 0)] +
  1016. p->numa_faults[task_faults_idx(NUMA_MEM, nid, 1)];
  1017. }
  1018. static inline unsigned long group_faults(struct task_struct *p, int nid)
  1019. {
  1020. if (!p->numa_group)
  1021. return 0;
  1022. return p->numa_group->faults[task_faults_idx(NUMA_MEM, nid, 0)] +
  1023. p->numa_group->faults[task_faults_idx(NUMA_MEM, nid, 1)];
  1024. }
  1025. static inline unsigned long group_faults_cpu(struct numa_group *group, int nid)
  1026. {
  1027. return group->faults_cpu[task_faults_idx(NUMA_MEM, nid, 0)] +
  1028. group->faults_cpu[task_faults_idx(NUMA_MEM, nid, 1)];
  1029. }
  1030. static inline unsigned long group_faults_priv(struct numa_group *ng)
  1031. {
  1032. unsigned long faults = 0;
  1033. int node;
  1034. for_each_online_node(node) {
  1035. faults += ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
  1036. }
  1037. return faults;
  1038. }
  1039. static inline unsigned long group_faults_shared(struct numa_group *ng)
  1040. {
  1041. unsigned long faults = 0;
  1042. int node;
  1043. for_each_online_node(node) {
  1044. faults += ng->faults[task_faults_idx(NUMA_MEM, node, 0)];
  1045. }
  1046. return faults;
  1047. }
  1048. /*
  1049. * A node triggering more than 1/3 as many NUMA faults as the maximum is
  1050. * considered part of a numa group's pseudo-interleaving set. Migrations
  1051. * between these nodes are slowed down, to allow things to settle down.
  1052. */
  1053. #define ACTIVE_NODE_FRACTION 3
  1054. static bool numa_is_active_node(int nid, struct numa_group *ng)
  1055. {
  1056. return group_faults_cpu(ng, nid) * ACTIVE_NODE_FRACTION > ng->max_faults_cpu;
  1057. }
  1058. /* Handle placement on systems where not all nodes are directly connected. */
  1059. static unsigned long score_nearby_nodes(struct task_struct *p, int nid,
  1060. int maxdist, bool task)
  1061. {
  1062. unsigned long score = 0;
  1063. int node;
  1064. /*
  1065. * All nodes are directly connected, and the same distance
  1066. * from each other. No need for fancy placement algorithms.
  1067. */
  1068. if (sched_numa_topology_type == NUMA_DIRECT)
  1069. return 0;
  1070. /*
  1071. * This code is called for each node, introducing N^2 complexity,
  1072. * which should be ok given the number of nodes rarely exceeds 8.
  1073. */
  1074. for_each_online_node(node) {
  1075. unsigned long faults;
  1076. int dist = node_distance(nid, node);
  1077. /*
  1078. * The furthest away nodes in the system are not interesting
  1079. * for placement; nid was already counted.
  1080. */
  1081. if (dist == sched_max_numa_distance || node == nid)
  1082. continue;
  1083. /*
  1084. * On systems with a backplane NUMA topology, compare groups
  1085. * of nodes, and move tasks towards the group with the most
  1086. * memory accesses. When comparing two nodes at distance
  1087. * "hoplimit", only nodes closer by than "hoplimit" are part
  1088. * of each group. Skip other nodes.
  1089. */
  1090. if (sched_numa_topology_type == NUMA_BACKPLANE &&
  1091. dist > maxdist)
  1092. continue;
  1093. /* Add up the faults from nearby nodes. */
  1094. if (task)
  1095. faults = task_faults(p, node);
  1096. else
  1097. faults = group_faults(p, node);
  1098. /*
  1099. * On systems with a glueless mesh NUMA topology, there are
  1100. * no fixed "groups of nodes". Instead, nodes that are not
  1101. * directly connected bounce traffic through intermediate
  1102. * nodes; a numa_group can occupy any set of nodes.
  1103. * The further away a node is, the less the faults count.
  1104. * This seems to result in good task placement.
  1105. */
  1106. if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
  1107. faults *= (sched_max_numa_distance - dist);
  1108. faults /= (sched_max_numa_distance - LOCAL_DISTANCE);
  1109. }
  1110. score += faults;
  1111. }
  1112. return score;
  1113. }
  1114. /*
  1115. * These return the fraction of accesses done by a particular task, or
  1116. * task group, on a particular numa node. The group weight is given a
  1117. * larger multiplier, in order to group tasks together that are almost
  1118. * evenly spread out between numa nodes.
  1119. */
  1120. static inline unsigned long task_weight(struct task_struct *p, int nid,
  1121. int dist)
  1122. {
  1123. unsigned long faults, total_faults;
  1124. if (!p->numa_faults)
  1125. return 0;
  1126. total_faults = p->total_numa_faults;
  1127. if (!total_faults)
  1128. return 0;
  1129. faults = task_faults(p, nid);
  1130. faults += score_nearby_nodes(p, nid, dist, true);
  1131. return 1000 * faults / total_faults;
  1132. }
  1133. static inline unsigned long group_weight(struct task_struct *p, int nid,
  1134. int dist)
  1135. {
  1136. unsigned long faults, total_faults;
  1137. if (!p->numa_group)
  1138. return 0;
  1139. total_faults = p->numa_group->total_faults;
  1140. if (!total_faults)
  1141. return 0;
  1142. faults = group_faults(p, nid);
  1143. faults += score_nearby_nodes(p, nid, dist, false);
  1144. return 1000 * faults / total_faults;
  1145. }
  1146. bool should_numa_migrate_memory(struct task_struct *p, struct page * page,
  1147. int src_nid, int dst_cpu)
  1148. {
  1149. struct numa_group *ng = p->numa_group;
  1150. int dst_nid = cpu_to_node(dst_cpu);
  1151. int last_cpupid, this_cpupid;
  1152. this_cpupid = cpu_pid_to_cpupid(dst_cpu, current->pid);
  1153. /*
  1154. * Multi-stage node selection is used in conjunction with a periodic
  1155. * migration fault to build a temporal task<->page relation. By using
  1156. * a two-stage filter we remove short/unlikely relations.
  1157. *
  1158. * Using P(p) ~ n_p / n_t as per frequentist probability, we can equate
  1159. * a task's usage of a particular page (n_p) per total usage of this
  1160. * page (n_t) (in a given time-span) to a probability.
  1161. *
  1162. * Our periodic faults will sample this probability and getting the
  1163. * same result twice in a row, given these samples are fully
  1164. * independent, is then given by P(n)^2, provided our sample period
  1165. * is sufficiently short compared to the usage pattern.
  1166. *
  1167. * This quadric squishes small probabilities, making it less likely we
  1168. * act on an unlikely task<->page relation.
  1169. */
  1170. last_cpupid = page_cpupid_xchg_last(page, this_cpupid);
  1171. if (!cpupid_pid_unset(last_cpupid) &&
  1172. cpupid_to_nid(last_cpupid) != dst_nid)
  1173. return false;
  1174. /* Always allow migrate on private faults */
  1175. if (cpupid_match_pid(p, last_cpupid))
  1176. return true;
  1177. /* A shared fault, but p->numa_group has not been set up yet. */
  1178. if (!ng)
  1179. return true;
  1180. /*
  1181. * Destination node is much more heavily used than the source
  1182. * node? Allow migration.
  1183. */
  1184. if (group_faults_cpu(ng, dst_nid) > group_faults_cpu(ng, src_nid) *
  1185. ACTIVE_NODE_FRACTION)
  1186. return true;
  1187. /*
  1188. * Distribute memory according to CPU & memory use on each node,
  1189. * with 3/4 hysteresis to avoid unnecessary memory migrations:
  1190. *
  1191. * faults_cpu(dst) 3 faults_cpu(src)
  1192. * --------------- * - > ---------------
  1193. * faults_mem(dst) 4 faults_mem(src)
  1194. */
  1195. return group_faults_cpu(ng, dst_nid) * group_faults(p, src_nid) * 3 >
  1196. group_faults_cpu(ng, src_nid) * group_faults(p, dst_nid) * 4;
  1197. }
  1198. static unsigned long weighted_cpuload(struct rq *rq);
  1199. static unsigned long source_load(int cpu, int type);
  1200. static unsigned long target_load(int cpu, int type);
  1201. static unsigned long capacity_of(int cpu);
  1202. /* Cached statistics for all CPUs within a node */
  1203. struct numa_stats {
  1204. unsigned long nr_running;
  1205. unsigned long load;
  1206. /* Total compute capacity of CPUs on a node */
  1207. unsigned long compute_capacity;
  1208. /* Approximate capacity in terms of runnable tasks on a node */
  1209. unsigned long task_capacity;
  1210. int has_free_capacity;
  1211. };
  1212. /*
  1213. * XXX borrowed from update_sg_lb_stats
  1214. */
  1215. static void update_numa_stats(struct numa_stats *ns, int nid)
  1216. {
  1217. int smt, cpu, cpus = 0;
  1218. unsigned long capacity;
  1219. memset(ns, 0, sizeof(*ns));
  1220. for_each_cpu(cpu, cpumask_of_node(nid)) {
  1221. struct rq *rq = cpu_rq(cpu);
  1222. ns->nr_running += rq->nr_running;
  1223. ns->load += weighted_cpuload(rq);
  1224. ns->compute_capacity += capacity_of(cpu);
  1225. cpus++;
  1226. }
  1227. /*
  1228. * If we raced with hotplug and there are no CPUs left in our mask
  1229. * the @ns structure is NULL'ed and task_numa_compare() will
  1230. * not find this node attractive.
  1231. *
  1232. * We'll either bail at !has_free_capacity, or we'll detect a huge
  1233. * imbalance and bail there.
  1234. */
  1235. if (!cpus)
  1236. return;
  1237. /* smt := ceil(cpus / capacity), assumes: 1 < smt_power < 2 */
  1238. smt = DIV_ROUND_UP(SCHED_CAPACITY_SCALE * cpus, ns->compute_capacity);
  1239. capacity = cpus / smt; /* cores */
  1240. ns->task_capacity = min_t(unsigned, capacity,
  1241. DIV_ROUND_CLOSEST(ns->compute_capacity, SCHED_CAPACITY_SCALE));
  1242. ns->has_free_capacity = (ns->nr_running < ns->task_capacity);
  1243. }
  1244. struct task_numa_env {
  1245. struct task_struct *p;
  1246. int src_cpu, src_nid;
  1247. int dst_cpu, dst_nid;
  1248. struct numa_stats src_stats, dst_stats;
  1249. int imbalance_pct;
  1250. int dist;
  1251. struct task_struct *best_task;
  1252. long best_imp;
  1253. int best_cpu;
  1254. };
  1255. static void task_numa_assign(struct task_numa_env *env,
  1256. struct task_struct *p, long imp)
  1257. {
  1258. if (env->best_task)
  1259. put_task_struct(env->best_task);
  1260. if (p)
  1261. get_task_struct(p);
  1262. env->best_task = p;
  1263. env->best_imp = imp;
  1264. env->best_cpu = env->dst_cpu;
  1265. }
  1266. static bool load_too_imbalanced(long src_load, long dst_load,
  1267. struct task_numa_env *env)
  1268. {
  1269. long imb, old_imb;
  1270. long orig_src_load, orig_dst_load;
  1271. long src_capacity, dst_capacity;
  1272. /*
  1273. * The load is corrected for the CPU capacity available on each node.
  1274. *
  1275. * src_load dst_load
  1276. * ------------ vs ---------
  1277. * src_capacity dst_capacity
  1278. */
  1279. src_capacity = env->src_stats.compute_capacity;
  1280. dst_capacity = env->dst_stats.compute_capacity;
  1281. /* We care about the slope of the imbalance, not the direction. */
  1282. if (dst_load < src_load)
  1283. swap(dst_load, src_load);
  1284. /* Is the difference below the threshold? */
  1285. imb = dst_load * src_capacity * 100 -
  1286. src_load * dst_capacity * env->imbalance_pct;
  1287. if (imb <= 0)
  1288. return false;
  1289. /*
  1290. * The imbalance is above the allowed threshold.
  1291. * Compare it with the old imbalance.
  1292. */
  1293. orig_src_load = env->src_stats.load;
  1294. orig_dst_load = env->dst_stats.load;
  1295. if (orig_dst_load < orig_src_load)
  1296. swap(orig_dst_load, orig_src_load);
  1297. old_imb = orig_dst_load * src_capacity * 100 -
  1298. orig_src_load * dst_capacity * env->imbalance_pct;
  1299. /* Would this change make things worse? */
  1300. return (imb > old_imb);
  1301. }
  1302. /*
  1303. * This checks if the overall compute and NUMA accesses of the system would
  1304. * be improved if the source tasks was migrated to the target dst_cpu taking
  1305. * into account that it might be best if task running on the dst_cpu should
  1306. * be exchanged with the source task
  1307. */
  1308. static void task_numa_compare(struct task_numa_env *env,
  1309. long taskimp, long groupimp)
  1310. {
  1311. struct rq *src_rq = cpu_rq(env->src_cpu);
  1312. struct rq *dst_rq = cpu_rq(env->dst_cpu);
  1313. struct task_struct *cur;
  1314. long src_load, dst_load;
  1315. long load;
  1316. long imp = env->p->numa_group ? groupimp : taskimp;
  1317. long moveimp = imp;
  1318. int dist = env->dist;
  1319. rcu_read_lock();
  1320. cur = task_rcu_dereference(&dst_rq->curr);
  1321. if (cur && ((cur->flags & PF_EXITING) || is_idle_task(cur)))
  1322. cur = NULL;
  1323. /*
  1324. * Because we have preemption enabled we can get migrated around and
  1325. * end try selecting ourselves (current == env->p) as a swap candidate.
  1326. */
  1327. if (cur == env->p)
  1328. goto unlock;
  1329. /*
  1330. * "imp" is the fault differential for the source task between the
  1331. * source and destination node. Calculate the total differential for
  1332. * the source task and potential destination task. The more negative
  1333. * the value is, the more rmeote accesses that would be expected to
  1334. * be incurred if the tasks were swapped.
  1335. */
  1336. if (cur) {
  1337. /* Skip this swap candidate if cannot move to the source CPU: */
  1338. if (!cpumask_test_cpu(env->src_cpu, &cur->cpus_allowed))
  1339. goto unlock;
  1340. /*
  1341. * If dst and source tasks are in the same NUMA group, or not
  1342. * in any group then look only at task weights.
  1343. */
  1344. if (cur->numa_group == env->p->numa_group) {
  1345. imp = taskimp + task_weight(cur, env->src_nid, dist) -
  1346. task_weight(cur, env->dst_nid, dist);
  1347. /*
  1348. * Add some hysteresis to prevent swapping the
  1349. * tasks within a group over tiny differences.
  1350. */
  1351. if (cur->numa_group)
  1352. imp -= imp/16;
  1353. } else {
  1354. /*
  1355. * Compare the group weights. If a task is all by
  1356. * itself (not part of a group), use the task weight
  1357. * instead.
  1358. */
  1359. if (cur->numa_group)
  1360. imp += group_weight(cur, env->src_nid, dist) -
  1361. group_weight(cur, env->dst_nid, dist);
  1362. else
  1363. imp += task_weight(cur, env->src_nid, dist) -
  1364. task_weight(cur, env->dst_nid, dist);
  1365. }
  1366. }
  1367. if (imp <= env->best_imp && moveimp <= env->best_imp)
  1368. goto unlock;
  1369. if (!cur) {
  1370. /* Is there capacity at our destination? */
  1371. if (env->src_stats.nr_running <= env->src_stats.task_capacity &&
  1372. !env->dst_stats.has_free_capacity)
  1373. goto unlock;
  1374. goto balance;
  1375. }
  1376. /* Balance doesn't matter much if we're running a task per CPU: */
  1377. if (imp > env->best_imp && src_rq->nr_running == 1 &&
  1378. dst_rq->nr_running == 1)
  1379. goto assign;
  1380. /*
  1381. * In the overloaded case, try and keep the load balanced.
  1382. */
  1383. balance:
  1384. load = task_h_load(env->p);
  1385. dst_load = env->dst_stats.load + load;
  1386. src_load = env->src_stats.load - load;
  1387. if (moveimp > imp && moveimp > env->best_imp) {
  1388. /*
  1389. * If the improvement from just moving env->p direction is
  1390. * better than swapping tasks around, check if a move is
  1391. * possible. Store a slightly smaller score than moveimp,
  1392. * so an actually idle CPU will win.
  1393. */
  1394. if (!load_too_imbalanced(src_load, dst_load, env)) {
  1395. imp = moveimp - 1;
  1396. cur = NULL;
  1397. goto assign;
  1398. }
  1399. }
  1400. if (imp <= env->best_imp)
  1401. goto unlock;
  1402. if (cur) {
  1403. load = task_h_load(cur);
  1404. dst_load -= load;
  1405. src_load += load;
  1406. }
  1407. if (load_too_imbalanced(src_load, dst_load, env))
  1408. goto unlock;
  1409. /*
  1410. * One idle CPU per node is evaluated for a task numa move.
  1411. * Call select_idle_sibling to maybe find a better one.
  1412. */
  1413. if (!cur) {
  1414. /*
  1415. * select_idle_siblings() uses an per-CPU cpumask that
  1416. * can be used from IRQ context.
  1417. */
  1418. local_irq_disable();
  1419. env->dst_cpu = select_idle_sibling(env->p, env->src_cpu,
  1420. env->dst_cpu);
  1421. local_irq_enable();
  1422. }
  1423. assign:
  1424. task_numa_assign(env, cur, imp);
  1425. unlock:
  1426. rcu_read_unlock();
  1427. }
  1428. static void task_numa_find_cpu(struct task_numa_env *env,
  1429. long taskimp, long groupimp)
  1430. {
  1431. int cpu;
  1432. for_each_cpu(cpu, cpumask_of_node(env->dst_nid)) {
  1433. /* Skip this CPU if the source task cannot migrate */
  1434. if (!cpumask_test_cpu(cpu, &env->p->cpus_allowed))
  1435. continue;
  1436. env->dst_cpu = cpu;
  1437. task_numa_compare(env, taskimp, groupimp);
  1438. }
  1439. }
  1440. /* Only move tasks to a NUMA node less busy than the current node. */
  1441. static bool numa_has_capacity(struct task_numa_env *env)
  1442. {
  1443. struct numa_stats *src = &env->src_stats;
  1444. struct numa_stats *dst = &env->dst_stats;
  1445. if (src->has_free_capacity && !dst->has_free_capacity)
  1446. return false;
  1447. /*
  1448. * Only consider a task move if the source has a higher load
  1449. * than the destination, corrected for CPU capacity on each node.
  1450. *
  1451. * src->load dst->load
  1452. * --------------------- vs ---------------------
  1453. * src->compute_capacity dst->compute_capacity
  1454. */
  1455. if (src->load * dst->compute_capacity * env->imbalance_pct >
  1456. dst->load * src->compute_capacity * 100)
  1457. return true;
  1458. return false;
  1459. }
  1460. static int task_numa_migrate(struct task_struct *p)
  1461. {
  1462. struct task_numa_env env = {
  1463. .p = p,
  1464. .src_cpu = task_cpu(p),
  1465. .src_nid = task_node(p),
  1466. .imbalance_pct = 112,
  1467. .best_task = NULL,
  1468. .best_imp = 0,
  1469. .best_cpu = -1,
  1470. };
  1471. struct sched_domain *sd;
  1472. unsigned long taskweight, groupweight;
  1473. int nid, ret, dist;
  1474. long taskimp, groupimp;
  1475. /*
  1476. * Pick the lowest SD_NUMA domain, as that would have the smallest
  1477. * imbalance and would be the first to start moving tasks about.
  1478. *
  1479. * And we want to avoid any moving of tasks about, as that would create
  1480. * random movement of tasks -- counter the numa conditions we're trying
  1481. * to satisfy here.
  1482. */
  1483. rcu_read_lock();
  1484. sd = rcu_dereference(per_cpu(sd_numa, env.src_cpu));
  1485. if (sd)
  1486. env.imbalance_pct = 100 + (sd->imbalance_pct - 100) / 2;
  1487. rcu_read_unlock();
  1488. /*
  1489. * Cpusets can break the scheduler domain tree into smaller
  1490. * balance domains, some of which do not cross NUMA boundaries.
  1491. * Tasks that are "trapped" in such domains cannot be migrated
  1492. * elsewhere, so there is no point in (re)trying.
  1493. */
  1494. if (unlikely(!sd)) {
  1495. p->numa_preferred_nid = task_node(p);
  1496. return -EINVAL;
  1497. }
  1498. env.dst_nid = p->numa_preferred_nid;
  1499. dist = env.dist = node_distance(env.src_nid, env.dst_nid);
  1500. taskweight = task_weight(p, env.src_nid, dist);
  1501. groupweight = group_weight(p, env.src_nid, dist);
  1502. update_numa_stats(&env.src_stats, env.src_nid);
  1503. taskimp = task_weight(p, env.dst_nid, dist) - taskweight;
  1504. groupimp = group_weight(p, env.dst_nid, dist) - groupweight;
  1505. update_numa_stats(&env.dst_stats, env.dst_nid);
  1506. /* Try to find a spot on the preferred nid. */
  1507. if (numa_has_capacity(&env))
  1508. task_numa_find_cpu(&env, taskimp, groupimp);
  1509. /*
  1510. * Look at other nodes in these cases:
  1511. * - there is no space available on the preferred_nid
  1512. * - the task is part of a numa_group that is interleaved across
  1513. * multiple NUMA nodes; in order to better consolidate the group,
  1514. * we need to check other locations.
  1515. */
  1516. if (env.best_cpu == -1 || (p->numa_group && p->numa_group->active_nodes > 1)) {
  1517. for_each_online_node(nid) {
  1518. if (nid == env.src_nid || nid == p->numa_preferred_nid)
  1519. continue;
  1520. dist = node_distance(env.src_nid, env.dst_nid);
  1521. if (sched_numa_topology_type == NUMA_BACKPLANE &&
  1522. dist != env.dist) {
  1523. taskweight = task_weight(p, env.src_nid, dist);
  1524. groupweight = group_weight(p, env.src_nid, dist);
  1525. }
  1526. /* Only consider nodes where both task and groups benefit */
  1527. taskimp = task_weight(p, nid, dist) - taskweight;
  1528. groupimp = group_weight(p, nid, dist) - groupweight;
  1529. if (taskimp < 0 && groupimp < 0)
  1530. continue;
  1531. env.dist = dist;
  1532. env.dst_nid = nid;
  1533. update_numa_stats(&env.dst_stats, env.dst_nid);
  1534. if (numa_has_capacity(&env))
  1535. task_numa_find_cpu(&env, taskimp, groupimp);
  1536. }
  1537. }
  1538. /*
  1539. * If the task is part of a workload that spans multiple NUMA nodes,
  1540. * and is migrating into one of the workload's active nodes, remember
  1541. * this node as the task's preferred numa node, so the workload can
  1542. * settle down.
  1543. * A task that migrated to a second choice node will be better off
  1544. * trying for a better one later. Do not set the preferred node here.
  1545. */
  1546. if (p->numa_group) {
  1547. struct numa_group *ng = p->numa_group;
  1548. if (env.best_cpu == -1)
  1549. nid = env.src_nid;
  1550. else
  1551. nid = env.dst_nid;
  1552. if (ng->active_nodes > 1 && numa_is_active_node(env.dst_nid, ng))
  1553. sched_setnuma(p, env.dst_nid);
  1554. }
  1555. /* No better CPU than the current one was found. */
  1556. if (env.best_cpu == -1)
  1557. return -EAGAIN;
  1558. /*
  1559. * Reset the scan period if the task is being rescheduled on an
  1560. * alternative node to recheck if the tasks is now properly placed.
  1561. */
  1562. p->numa_scan_period = task_scan_start(p);
  1563. if (env.best_task == NULL) {
  1564. ret = migrate_task_to(p, env.best_cpu);
  1565. if (ret != 0)
  1566. trace_sched_stick_numa(p, env.src_cpu, env.best_cpu);
  1567. return ret;
  1568. }
  1569. ret = migrate_swap(p, env.best_task);
  1570. if (ret != 0)
  1571. trace_sched_stick_numa(p, env.src_cpu, task_cpu(env.best_task));
  1572. put_task_struct(env.best_task);
  1573. return ret;
  1574. }
  1575. /* Attempt to migrate a task to a CPU on the preferred node. */
  1576. static void numa_migrate_preferred(struct task_struct *p)
  1577. {
  1578. unsigned long interval = HZ;
  1579. /* This task has no NUMA fault statistics yet */
  1580. if (unlikely(p->numa_preferred_nid == -1 || !p->numa_faults))
  1581. return;
  1582. /* Periodically retry migrating the task to the preferred node */
  1583. interval = min(interval, msecs_to_jiffies(p->numa_scan_period) / 16);
  1584. p->numa_migrate_retry = jiffies + interval;
  1585. /* Success if task is already running on preferred CPU */
  1586. if (task_node(p) == p->numa_preferred_nid)
  1587. return;
  1588. /* Otherwise, try migrate to a CPU on the preferred node */
  1589. task_numa_migrate(p);
  1590. }
  1591. /*
  1592. * Find out how many nodes on the workload is actively running on. Do this by
  1593. * tracking the nodes from which NUMA hinting faults are triggered. This can
  1594. * be different from the set of nodes where the workload's memory is currently
  1595. * located.
  1596. */
  1597. static void numa_group_count_active_nodes(struct numa_group *numa_group)
  1598. {
  1599. unsigned long faults, max_faults = 0;
  1600. int nid, active_nodes = 0;
  1601. for_each_online_node(nid) {
  1602. faults = group_faults_cpu(numa_group, nid);
  1603. if (faults > max_faults)
  1604. max_faults = faults;
  1605. }
  1606. for_each_online_node(nid) {
  1607. faults = group_faults_cpu(numa_group, nid);
  1608. if (faults * ACTIVE_NODE_FRACTION > max_faults)
  1609. active_nodes++;
  1610. }
  1611. numa_group->max_faults_cpu = max_faults;
  1612. numa_group->active_nodes = active_nodes;
  1613. }
  1614. /*
  1615. * When adapting the scan rate, the period is divided into NUMA_PERIOD_SLOTS
  1616. * increments. The more local the fault statistics are, the higher the scan
  1617. * period will be for the next scan window. If local/(local+remote) ratio is
  1618. * below NUMA_PERIOD_THRESHOLD (where range of ratio is 1..NUMA_PERIOD_SLOTS)
  1619. * the scan period will decrease. Aim for 70% local accesses.
  1620. */
  1621. #define NUMA_PERIOD_SLOTS 10
  1622. #define NUMA_PERIOD_THRESHOLD 7
  1623. /*
  1624. * Increase the scan period (slow down scanning) if the majority of
  1625. * our memory is already on our local node, or if the majority of
  1626. * the page accesses are shared with other processes.
  1627. * Otherwise, decrease the scan period.
  1628. */
  1629. static void update_task_scan_period(struct task_struct *p,
  1630. unsigned long shared, unsigned long private)
  1631. {
  1632. unsigned int period_slot;
  1633. int lr_ratio, ps_ratio;
  1634. int diff;
  1635. unsigned long remote = p->numa_faults_locality[0];
  1636. unsigned long local = p->numa_faults_locality[1];
  1637. /*
  1638. * If there were no record hinting faults then either the task is
  1639. * completely idle or all activity is areas that are not of interest
  1640. * to automatic numa balancing. Related to that, if there were failed
  1641. * migration then it implies we are migrating too quickly or the local
  1642. * node is overloaded. In either case, scan slower
  1643. */
  1644. if (local + shared == 0 || p->numa_faults_locality[2]) {
  1645. p->numa_scan_period = min(p->numa_scan_period_max,
  1646. p->numa_scan_period << 1);
  1647. p->mm->numa_next_scan = jiffies +
  1648. msecs_to_jiffies(p->numa_scan_period);
  1649. return;
  1650. }
  1651. /*
  1652. * Prepare to scale scan period relative to the current period.
  1653. * == NUMA_PERIOD_THRESHOLD scan period stays the same
  1654. * < NUMA_PERIOD_THRESHOLD scan period decreases (scan faster)
  1655. * >= NUMA_PERIOD_THRESHOLD scan period increases (scan slower)
  1656. */
  1657. period_slot = DIV_ROUND_UP(p->numa_scan_period, NUMA_PERIOD_SLOTS);
  1658. lr_ratio = (local * NUMA_PERIOD_SLOTS) / (local + remote);
  1659. ps_ratio = (private * NUMA_PERIOD_SLOTS) / (private + shared);
  1660. if (ps_ratio >= NUMA_PERIOD_THRESHOLD) {
  1661. /*
  1662. * Most memory accesses are local. There is no need to
  1663. * do fast NUMA scanning, since memory is already local.
  1664. */
  1665. int slot = ps_ratio - NUMA_PERIOD_THRESHOLD;
  1666. if (!slot)
  1667. slot = 1;
  1668. diff = slot * period_slot;
  1669. } else if (lr_ratio >= NUMA_PERIOD_THRESHOLD) {
  1670. /*
  1671. * Most memory accesses are shared with other tasks.
  1672. * There is no point in continuing fast NUMA scanning,
  1673. * since other tasks may just move the memory elsewhere.
  1674. */
  1675. int slot = lr_ratio - NUMA_PERIOD_THRESHOLD;
  1676. if (!slot)
  1677. slot = 1;
  1678. diff = slot * period_slot;
  1679. } else {
  1680. /*
  1681. * Private memory faults exceed (SLOTS-THRESHOLD)/SLOTS,
  1682. * yet they are not on the local NUMA node. Speed up
  1683. * NUMA scanning to get the memory moved over.
  1684. */
  1685. int ratio = max(lr_ratio, ps_ratio);
  1686. diff = -(NUMA_PERIOD_THRESHOLD - ratio) * period_slot;
  1687. }
  1688. p->numa_scan_period = clamp(p->numa_scan_period + diff,
  1689. task_scan_min(p), task_scan_max(p));
  1690. memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
  1691. }
  1692. /*
  1693. * Get the fraction of time the task has been running since the last
  1694. * NUMA placement cycle. The scheduler keeps similar statistics, but
  1695. * decays those on a 32ms period, which is orders of magnitude off
  1696. * from the dozens-of-seconds NUMA balancing period. Use the scheduler
  1697. * stats only if the task is so new there are no NUMA statistics yet.
  1698. */
  1699. static u64 numa_get_avg_runtime(struct task_struct *p, u64 *period)
  1700. {
  1701. u64 runtime, delta, now;
  1702. /* Use the start of this time slice to avoid calculations. */
  1703. now = p->se.exec_start;
  1704. runtime = p->se.sum_exec_runtime;
  1705. if (p->last_task_numa_placement) {
  1706. delta = runtime - p->last_sum_exec_runtime;
  1707. *period = now - p->last_task_numa_placement;
  1708. } else {
  1709. delta = p->se.avg.load_sum;
  1710. *period = LOAD_AVG_MAX;
  1711. }
  1712. p->last_sum_exec_runtime = runtime;
  1713. p->last_task_numa_placement = now;
  1714. return delta;
  1715. }
  1716. /*
  1717. * Determine the preferred nid for a task in a numa_group. This needs to
  1718. * be done in a way that produces consistent results with group_weight,
  1719. * otherwise workloads might not converge.
  1720. */
  1721. static int preferred_group_nid(struct task_struct *p, int nid)
  1722. {
  1723. nodemask_t nodes;
  1724. int dist;
  1725. /* Direct connections between all NUMA nodes. */
  1726. if (sched_numa_topology_type == NUMA_DIRECT)
  1727. return nid;
  1728. /*
  1729. * On a system with glueless mesh NUMA topology, group_weight
  1730. * scores nodes according to the number of NUMA hinting faults on
  1731. * both the node itself, and on nearby nodes.
  1732. */
  1733. if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
  1734. unsigned long score, max_score = 0;
  1735. int node, max_node = nid;
  1736. dist = sched_max_numa_distance;
  1737. for_each_online_node(node) {
  1738. score = group_weight(p, node, dist);
  1739. if (score > max_score) {
  1740. max_score = score;
  1741. max_node = node;
  1742. }
  1743. }
  1744. return max_node;
  1745. }
  1746. /*
  1747. * Finding the preferred nid in a system with NUMA backplane
  1748. * interconnect topology is more involved. The goal is to locate
  1749. * tasks from numa_groups near each other in the system, and
  1750. * untangle workloads from different sides of the system. This requires
  1751. * searching down the hierarchy of node groups, recursively searching
  1752. * inside the highest scoring group of nodes. The nodemask tricks
  1753. * keep the complexity of the search down.
  1754. */
  1755. nodes = node_online_map;
  1756. for (dist = sched_max_numa_distance; dist > LOCAL_DISTANCE; dist--) {
  1757. unsigned long max_faults = 0;
  1758. nodemask_t max_group = NODE_MASK_NONE;
  1759. int a, b;
  1760. /* Are there nodes at this distance from each other? */
  1761. if (!find_numa_distance(dist))
  1762. continue;
  1763. for_each_node_mask(a, nodes) {
  1764. unsigned long faults = 0;
  1765. nodemask_t this_group;
  1766. nodes_clear(this_group);
  1767. /* Sum group's NUMA faults; includes a==b case. */
  1768. for_each_node_mask(b, nodes) {
  1769. if (node_distance(a, b) < dist) {
  1770. faults += group_faults(p, b);
  1771. node_set(b, this_group);
  1772. node_clear(b, nodes);
  1773. }
  1774. }
  1775. /* Remember the top group. */
  1776. if (faults > max_faults) {
  1777. max_faults = faults;
  1778. max_group = this_group;
  1779. /*
  1780. * subtle: at the smallest distance there is
  1781. * just one node left in each "group", the
  1782. * winner is the preferred nid.
  1783. */
  1784. nid = a;
  1785. }
  1786. }
  1787. /* Next round, evaluate the nodes within max_group. */
  1788. if (!max_faults)
  1789. break;
  1790. nodes = max_group;
  1791. }
  1792. return nid;
  1793. }
  1794. static void task_numa_placement(struct task_struct *p)
  1795. {
  1796. int seq, nid, max_nid = -1, max_group_nid = -1;
  1797. unsigned long max_faults = 0, max_group_faults = 0;
  1798. unsigned long fault_types[2] = { 0, 0 };
  1799. unsigned long total_faults;
  1800. u64 runtime, period;
  1801. spinlock_t *group_lock = NULL;
  1802. /*
  1803. * The p->mm->numa_scan_seq field gets updated without
  1804. * exclusive access. Use READ_ONCE() here to ensure
  1805. * that the field is read in a single access:
  1806. */
  1807. seq = READ_ONCE(p->mm->numa_scan_seq);
  1808. if (p->numa_scan_seq == seq)
  1809. return;
  1810. p->numa_scan_seq = seq;
  1811. p->numa_scan_period_max = task_scan_max(p);
  1812. total_faults = p->numa_faults_locality[0] +
  1813. p->numa_faults_locality[1];
  1814. runtime = numa_get_avg_runtime(p, &period);
  1815. /* If the task is part of a group prevent parallel updates to group stats */
  1816. if (p->numa_group) {
  1817. group_lock = &p->numa_group->lock;
  1818. spin_lock_irq(group_lock);
  1819. }
  1820. /* Find the node with the highest number of faults */
  1821. for_each_online_node(nid) {
  1822. /* Keep track of the offsets in numa_faults array */
  1823. int mem_idx, membuf_idx, cpu_idx, cpubuf_idx;
  1824. unsigned long faults = 0, group_faults = 0;
  1825. int priv;
  1826. for (priv = 0; priv < NR_NUMA_HINT_FAULT_TYPES; priv++) {
  1827. long diff, f_diff, f_weight;
  1828. mem_idx = task_faults_idx(NUMA_MEM, nid, priv);
  1829. membuf_idx = task_faults_idx(NUMA_MEMBUF, nid, priv);
  1830. cpu_idx = task_faults_idx(NUMA_CPU, nid, priv);
  1831. cpubuf_idx = task_faults_idx(NUMA_CPUBUF, nid, priv);
  1832. /* Decay existing window, copy faults since last scan */
  1833. diff = p->numa_faults[membuf_idx] - p->numa_faults[mem_idx] / 2;
  1834. fault_types[priv] += p->numa_faults[membuf_idx];
  1835. p->numa_faults[membuf_idx] = 0;
  1836. /*
  1837. * Normalize the faults_from, so all tasks in a group
  1838. * count according to CPU use, instead of by the raw
  1839. * number of faults. Tasks with little runtime have
  1840. * little over-all impact on throughput, and thus their
  1841. * faults are less important.
  1842. */
  1843. f_weight = div64_u64(runtime << 16, period + 1);
  1844. f_weight = (f_weight * p->numa_faults[cpubuf_idx]) /
  1845. (total_faults + 1);
  1846. f_diff = f_weight - p->numa_faults[cpu_idx] / 2;
  1847. p->numa_faults[cpubuf_idx] = 0;
  1848. p->numa_faults[mem_idx] += diff;
  1849. p->numa_faults[cpu_idx] += f_diff;
  1850. faults += p->numa_faults[mem_idx];
  1851. p->total_numa_faults += diff;
  1852. if (p->numa_group) {
  1853. /*
  1854. * safe because we can only change our own group
  1855. *
  1856. * mem_idx represents the offset for a given
  1857. * nid and priv in a specific region because it
  1858. * is at the beginning of the numa_faults array.
  1859. */
  1860. p->numa_group->faults[mem_idx] += diff;
  1861. p->numa_group->faults_cpu[mem_idx] += f_diff;
  1862. p->numa_group->total_faults += diff;
  1863. group_faults += p->numa_group->faults[mem_idx];
  1864. }
  1865. }
  1866. if (faults > max_faults) {
  1867. max_faults = faults;
  1868. max_nid = nid;
  1869. }
  1870. if (group_faults > max_group_faults) {
  1871. max_group_faults = group_faults;
  1872. max_group_nid = nid;
  1873. }
  1874. }
  1875. update_task_scan_period(p, fault_types[0], fault_types[1]);
  1876. if (p->numa_group) {
  1877. numa_group_count_active_nodes(p->numa_group);
  1878. spin_unlock_irq(group_lock);
  1879. max_nid = preferred_group_nid(p, max_group_nid);
  1880. }
  1881. if (max_faults) {
  1882. /* Set the new preferred node */
  1883. if (max_nid != p->numa_preferred_nid)
  1884. sched_setnuma(p, max_nid);
  1885. if (task_node(p) != p->numa_preferred_nid)
  1886. numa_migrate_preferred(p);
  1887. }
  1888. }
  1889. static inline int get_numa_group(struct numa_group *grp)
  1890. {
  1891. return atomic_inc_not_zero(&grp->refcount);
  1892. }
  1893. static inline void put_numa_group(struct numa_group *grp)
  1894. {
  1895. if (atomic_dec_and_test(&grp->refcount))
  1896. kfree_rcu(grp, rcu);
  1897. }
  1898. static void task_numa_group(struct task_struct *p, int cpupid, int flags,
  1899. int *priv)
  1900. {
  1901. struct numa_group *grp, *my_grp;
  1902. struct task_struct *tsk;
  1903. bool join = false;
  1904. int cpu = cpupid_to_cpu(cpupid);
  1905. int i;
  1906. if (unlikely(!p->numa_group)) {
  1907. unsigned int size = sizeof(struct numa_group) +
  1908. 4*nr_node_ids*sizeof(unsigned long);
  1909. grp = kzalloc(size, GFP_KERNEL | __GFP_NOWARN);
  1910. if (!grp)
  1911. return;
  1912. atomic_set(&grp->refcount, 1);
  1913. grp->active_nodes = 1;
  1914. grp->max_faults_cpu = 0;
  1915. spin_lock_init(&grp->lock);
  1916. grp->gid = p->pid;
  1917. /* Second half of the array tracks nids where faults happen */
  1918. grp->faults_cpu = grp->faults + NR_NUMA_HINT_FAULT_TYPES *
  1919. nr_node_ids;
  1920. for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
  1921. grp->faults[i] = p->numa_faults[i];
  1922. grp->total_faults = p->total_numa_faults;
  1923. grp->nr_tasks++;
  1924. rcu_assign_pointer(p->numa_group, grp);
  1925. }
  1926. rcu_read_lock();
  1927. tsk = READ_ONCE(cpu_rq(cpu)->curr);
  1928. if (!cpupid_match_pid(tsk, cpupid))
  1929. goto no_join;
  1930. grp = rcu_dereference(tsk->numa_group);
  1931. if (!grp)
  1932. goto no_join;
  1933. my_grp = p->numa_group;
  1934. if (grp == my_grp)
  1935. goto no_join;
  1936. /*
  1937. * Only join the other group if its bigger; if we're the bigger group,
  1938. * the other task will join us.
  1939. */
  1940. if (my_grp->nr_tasks > grp->nr_tasks)
  1941. goto no_join;
  1942. /*
  1943. * Tie-break on the grp address.
  1944. */
  1945. if (my_grp->nr_tasks == grp->nr_tasks && my_grp > grp)
  1946. goto no_join;
  1947. /* Always join threads in the same process. */
  1948. if (tsk->mm == current->mm)
  1949. join = true;
  1950. /* Simple filter to avoid false positives due to PID collisions */
  1951. if (flags & TNF_SHARED)
  1952. join = true;
  1953. /* Update priv based on whether false sharing was detected */
  1954. *priv = !join;
  1955. if (join && !get_numa_group(grp))
  1956. goto no_join;
  1957. rcu_read_unlock();
  1958. if (!join)
  1959. return;
  1960. BUG_ON(irqs_disabled());
  1961. double_lock_irq(&my_grp->lock, &grp->lock);
  1962. for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) {
  1963. my_grp->faults[i] -= p->numa_faults[i];
  1964. grp->faults[i] += p->numa_faults[i];
  1965. }
  1966. my_grp->total_faults -= p->total_numa_faults;
  1967. grp->total_faults += p->total_numa_faults;
  1968. my_grp->nr_tasks--;
  1969. grp->nr_tasks++;
  1970. spin_unlock(&my_grp->lock);
  1971. spin_unlock_irq(&grp->lock);
  1972. rcu_assign_pointer(p->numa_group, grp);
  1973. put_numa_group(my_grp);
  1974. return;
  1975. no_join:
  1976. rcu_read_unlock();
  1977. return;
  1978. }
  1979. void task_numa_free(struct task_struct *p)
  1980. {
  1981. struct numa_group *grp = p->numa_group;
  1982. void *numa_faults = p->numa_faults;
  1983. unsigned long flags;
  1984. int i;
  1985. if (grp) {
  1986. spin_lock_irqsave(&grp->lock, flags);
  1987. for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
  1988. grp->faults[i] -= p->numa_faults[i];
  1989. grp->total_faults -= p->total_numa_faults;
  1990. grp->nr_tasks--;
  1991. spin_unlock_irqrestore(&grp->lock, flags);
  1992. RCU_INIT_POINTER(p->numa_group, NULL);
  1993. put_numa_group(grp);
  1994. }
  1995. p->numa_faults = NULL;
  1996. kfree(numa_faults);
  1997. }
  1998. /*
  1999. * Got a PROT_NONE fault for a page on @node.
  2000. */
  2001. void task_numa_fault(int last_cpupid, int mem_node, int pages, int flags)
  2002. {
  2003. struct task_struct *p = current;
  2004. bool migrated = flags & TNF_MIGRATED;
  2005. int cpu_node = task_node(current);
  2006. int local = !!(flags & TNF_FAULT_LOCAL);
  2007. struct numa_group *ng;
  2008. int priv;
  2009. if (!static_branch_likely(&sched_numa_balancing))
  2010. return;
  2011. /* for example, ksmd faulting in a user's mm */
  2012. if (!p->mm)
  2013. return;
  2014. /* Allocate buffer to track faults on a per-node basis */
  2015. if (unlikely(!p->numa_faults)) {
  2016. int size = sizeof(*p->numa_faults) *
  2017. NR_NUMA_HINT_FAULT_BUCKETS * nr_node_ids;
  2018. p->numa_faults = kzalloc(size, GFP_KERNEL|__GFP_NOWARN);
  2019. if (!p->numa_faults)
  2020. return;
  2021. p->total_numa_faults = 0;
  2022. memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
  2023. }
  2024. /*
  2025. * First accesses are treated as private, otherwise consider accesses
  2026. * to be private if the accessing pid has not changed
  2027. */
  2028. if (unlikely(last_cpupid == (-1 & LAST_CPUPID_MASK))) {
  2029. priv = 1;
  2030. } else {
  2031. priv = cpupid_match_pid(p, last_cpupid);
  2032. if (!priv && !(flags & TNF_NO_GROUP))
  2033. task_numa_group(p, last_cpupid, flags, &priv);
  2034. }
  2035. /*
  2036. * If a workload spans multiple NUMA nodes, a shared fault that
  2037. * occurs wholly within the set of nodes that the workload is
  2038. * actively using should be counted as local. This allows the
  2039. * scan rate to slow down when a workload has settled down.
  2040. */
  2041. ng = p->numa_group;
  2042. if (!priv && !local && ng && ng->active_nodes > 1 &&
  2043. numa_is_active_node(cpu_node, ng) &&
  2044. numa_is_active_node(mem_node, ng))
  2045. local = 1;
  2046. task_numa_placement(p);
  2047. /*
  2048. * Retry task to preferred node migration periodically, in case it
  2049. * case it previously failed, or the scheduler moved us.
  2050. */
  2051. if (time_after(jiffies, p->numa_migrate_retry))
  2052. numa_migrate_preferred(p);
  2053. if (migrated)
  2054. p->numa_pages_migrated += pages;
  2055. if (flags & TNF_MIGRATE_FAIL)
  2056. p->numa_faults_locality[2] += pages;
  2057. p->numa_faults[task_faults_idx(NUMA_MEMBUF, mem_node, priv)] += pages;
  2058. p->numa_faults[task_faults_idx(NUMA_CPUBUF, cpu_node, priv)] += pages;
  2059. p->numa_faults_locality[local] += pages;
  2060. }
  2061. static void reset_ptenuma_scan(struct task_struct *p)
  2062. {
  2063. /*
  2064. * We only did a read acquisition of the mmap sem, so
  2065. * p->mm->numa_scan_seq is written to without exclusive access
  2066. * and the update is not guaranteed to be atomic. That's not
  2067. * much of an issue though, since this is just used for
  2068. * statistical sampling. Use READ_ONCE/WRITE_ONCE, which are not
  2069. * expensive, to avoid any form of compiler optimizations:
  2070. */
  2071. WRITE_ONCE(p->mm->numa_scan_seq, READ_ONCE(p->mm->numa_scan_seq) + 1);
  2072. p->mm->numa_scan_offset = 0;
  2073. }
  2074. /*
  2075. * The expensive part of numa migration is done from task_work context.
  2076. * Triggered from task_tick_numa().
  2077. */
  2078. void task_numa_work(struct callback_head *work)
  2079. {
  2080. unsigned long migrate, next_scan, now = jiffies;
  2081. struct task_struct *p = current;
  2082. struct mm_struct *mm = p->mm;
  2083. u64 runtime = p->se.sum_exec_runtime;
  2084. struct vm_area_struct *vma;
  2085. unsigned long start, end;
  2086. unsigned long nr_pte_updates = 0;
  2087. long pages, virtpages;
  2088. SCHED_WARN_ON(p != container_of(work, struct task_struct, numa_work));
  2089. work->next = work; /* protect against double add */
  2090. /*
  2091. * Who cares about NUMA placement when they're dying.
  2092. *
  2093. * NOTE: make sure not to dereference p->mm before this check,
  2094. * exit_task_work() happens _after_ exit_mm() so we could be called
  2095. * without p->mm even though we still had it when we enqueued this
  2096. * work.
  2097. */
  2098. if (p->flags & PF_EXITING)
  2099. return;
  2100. if (!mm->numa_next_scan) {
  2101. mm->numa_next_scan = now +
  2102. msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
  2103. }
  2104. /*
  2105. * Enforce maximal scan/migration frequency..
  2106. */
  2107. migrate = mm->numa_next_scan;
  2108. if (time_before(now, migrate))
  2109. return;
  2110. if (p->numa_scan_period == 0) {
  2111. p->numa_scan_period_max = task_scan_max(p);
  2112. p->numa_scan_period = task_scan_start(p);
  2113. }
  2114. next_scan = now + msecs_to_jiffies(p->numa_scan_period);
  2115. if (cmpxchg(&mm->numa_next_scan, migrate, next_scan) != migrate)
  2116. return;
  2117. /*
  2118. * Delay this task enough that another task of this mm will likely win
  2119. * the next time around.
  2120. */
  2121. p->node_stamp += 2 * TICK_NSEC;
  2122. start = mm->numa_scan_offset;
  2123. pages = sysctl_numa_balancing_scan_size;
  2124. pages <<= 20 - PAGE_SHIFT; /* MB in pages */
  2125. virtpages = pages * 8; /* Scan up to this much virtual space */
  2126. if (!pages)
  2127. return;
  2128. if (!down_read_trylock(&mm->mmap_sem))
  2129. return;
  2130. vma = find_vma(mm, start);
  2131. if (!vma) {
  2132. reset_ptenuma_scan(p);
  2133. start = 0;
  2134. vma = mm->mmap;
  2135. }
  2136. for (; vma; vma = vma->vm_next) {
  2137. if (!vma_migratable(vma) || !vma_policy_mof(vma) ||
  2138. is_vm_hugetlb_page(vma) || (vma->vm_flags & VM_MIXEDMAP)) {
  2139. continue;
  2140. }
  2141. /*
  2142. * Shared library pages mapped by multiple processes are not
  2143. * migrated as it is expected they are cache replicated. Avoid
  2144. * hinting faults in read-only file-backed mappings or the vdso
  2145. * as migrating the pages will be of marginal benefit.
  2146. */
  2147. if (!vma->vm_mm ||
  2148. (vma->vm_file && (vma->vm_flags & (VM_READ|VM_WRITE)) == (VM_READ)))
  2149. continue;
  2150. /*
  2151. * Skip inaccessible VMAs to avoid any confusion between
  2152. * PROT_NONE and NUMA hinting ptes
  2153. */
  2154. if (!(vma->vm_flags & (VM_READ | VM_EXEC | VM_WRITE)))
  2155. continue;
  2156. do {
  2157. start = max(start, vma->vm_start);
  2158. end = ALIGN(start + (pages << PAGE_SHIFT), HPAGE_SIZE);
  2159. end = min(end, vma->vm_end);
  2160. nr_pte_updates = change_prot_numa(vma, start, end);
  2161. /*
  2162. * Try to scan sysctl_numa_balancing_size worth of
  2163. * hpages that have at least one present PTE that
  2164. * is not already pte-numa. If the VMA contains
  2165. * areas that are unused or already full of prot_numa
  2166. * PTEs, scan up to virtpages, to skip through those
  2167. * areas faster.
  2168. */
  2169. if (nr_pte_updates)
  2170. pages -= (end - start) >> PAGE_SHIFT;
  2171. virtpages -= (end - start) >> PAGE_SHIFT;
  2172. start = end;
  2173. if (pages <= 0 || virtpages <= 0)
  2174. goto out;
  2175. cond_resched();
  2176. } while (end != vma->vm_end);
  2177. }
  2178. out:
  2179. /*
  2180. * It is possible to reach the end of the VMA list but the last few
  2181. * VMAs are not guaranteed to the vma_migratable. If they are not, we
  2182. * would find the !migratable VMA on the next scan but not reset the
  2183. * scanner to the start so check it now.
  2184. */
  2185. if (vma)
  2186. mm->numa_scan_offset = start;
  2187. else
  2188. reset_ptenuma_scan(p);
  2189. up_read(&mm->mmap_sem);
  2190. /*
  2191. * Make sure tasks use at least 32x as much time to run other code
  2192. * than they used here, to limit NUMA PTE scanning overhead to 3% max.
  2193. * Usually update_task_scan_period slows down scanning enough; on an
  2194. * overloaded system we need to limit overhead on a per task basis.
  2195. */
  2196. if (unlikely(p->se.sum_exec_runtime != runtime)) {
  2197. u64 diff = p->se.sum_exec_runtime - runtime;
  2198. p->node_stamp += 32 * diff;
  2199. }
  2200. }
  2201. /*
  2202. * Drive the periodic memory faults..
  2203. */
  2204. void task_tick_numa(struct rq *rq, struct task_struct *curr)
  2205. {
  2206. struct callback_head *work = &curr->numa_work;
  2207. u64 period, now;
  2208. /*
  2209. * We don't care about NUMA placement if we don't have memory.
  2210. */
  2211. if (!curr->mm || (curr->flags & PF_EXITING) || work->next != work)
  2212. return;
  2213. /*
  2214. * Using runtime rather than walltime has the dual advantage that
  2215. * we (mostly) drive the selection from busy threads and that the
  2216. * task needs to have done some actual work before we bother with
  2217. * NUMA placement.
  2218. */
  2219. now = curr->se.sum_exec_runtime;
  2220. period = (u64)curr->numa_scan_period * NSEC_PER_MSEC;
  2221. if (now > curr->node_stamp + period) {
  2222. if (!curr->node_stamp)
  2223. curr->numa_scan_period = task_scan_start(curr);
  2224. curr->node_stamp += period;
  2225. if (!time_before(jiffies, curr->mm->numa_next_scan)) {
  2226. init_task_work(work, task_numa_work); /* TODO: move this into sched_fork() */
  2227. task_work_add(curr, work, true);
  2228. }
  2229. }
  2230. }
  2231. #else
  2232. static void task_tick_numa(struct rq *rq, struct task_struct *curr)
  2233. {
  2234. }
  2235. static inline void account_numa_enqueue(struct rq *rq, struct task_struct *p)
  2236. {
  2237. }
  2238. static inline void account_numa_dequeue(struct rq *rq, struct task_struct *p)
  2239. {
  2240. }
  2241. #endif /* CONFIG_NUMA_BALANCING */
  2242. static void
  2243. account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
  2244. {
  2245. update_load_add(&cfs_rq->load, se->load.weight);
  2246. if (!parent_entity(se))
  2247. update_load_add(&rq_of(cfs_rq)->load, se->load.weight);
  2248. #ifdef CONFIG_SMP
  2249. if (entity_is_task(se)) {
  2250. struct rq *rq = rq_of(cfs_rq);
  2251. account_numa_enqueue(rq, task_of(se));
  2252. list_add(&se->group_node, &rq->cfs_tasks);
  2253. }
  2254. #endif
  2255. cfs_rq->nr_running++;
  2256. }
  2257. static void
  2258. account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
  2259. {
  2260. update_load_sub(&cfs_rq->load, se->load.weight);
  2261. if (!parent_entity(se))
  2262. update_load_sub(&rq_of(cfs_rq)->load, se->load.weight);
  2263. #ifdef CONFIG_SMP
  2264. if (entity_is_task(se)) {
  2265. account_numa_dequeue(rq_of(cfs_rq), task_of(se));
  2266. list_del_init(&se->group_node);
  2267. }
  2268. #endif
  2269. cfs_rq->nr_running--;
  2270. }
  2271. /*
  2272. * Signed add and clamp on underflow.
  2273. *
  2274. * Explicitly do a load-store to ensure the intermediate value never hits
  2275. * memory. This allows lockless observations without ever seeing the negative
  2276. * values.
  2277. */
  2278. #define add_positive(_ptr, _val) do { \
  2279. typeof(_ptr) ptr = (_ptr); \
  2280. typeof(_val) val = (_val); \
  2281. typeof(*ptr) res, var = READ_ONCE(*ptr); \
  2282. \
  2283. res = var + val; \
  2284. \
  2285. if (val < 0 && res > var) \
  2286. res = 0; \
  2287. \
  2288. WRITE_ONCE(*ptr, res); \
  2289. } while (0)
  2290. /*
  2291. * Unsigned subtract and clamp on underflow.
  2292. *
  2293. * Explicitly do a load-store to ensure the intermediate value never hits
  2294. * memory. This allows lockless observations without ever seeing the negative
  2295. * values.
  2296. */
  2297. #define sub_positive(_ptr, _val) do { \
  2298. typeof(_ptr) ptr = (_ptr); \
  2299. typeof(*ptr) val = (_val); \
  2300. typeof(*ptr) res, var = READ_ONCE(*ptr); \
  2301. res = var - val; \
  2302. if (res > var) \
  2303. res = 0; \
  2304. WRITE_ONCE(*ptr, res); \
  2305. } while (0)
  2306. #ifdef CONFIG_SMP
  2307. /*
  2308. * XXX we want to get rid of these helpers and use the full load resolution.
  2309. */
  2310. static inline long se_weight(struct sched_entity *se)
  2311. {
  2312. return scale_load_down(se->load.weight);
  2313. }
  2314. static inline long se_runnable(struct sched_entity *se)
  2315. {
  2316. return scale_load_down(se->runnable_weight);
  2317. }
  2318. static inline void
  2319. enqueue_runnable_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
  2320. {
  2321. cfs_rq->runnable_weight += se->runnable_weight;
  2322. cfs_rq->avg.runnable_load_avg += se->avg.runnable_load_avg;
  2323. cfs_rq->avg.runnable_load_sum += se_runnable(se) * se->avg.runnable_load_sum;
  2324. }
  2325. static inline void
  2326. dequeue_runnable_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
  2327. {
  2328. cfs_rq->runnable_weight -= se->runnable_weight;
  2329. sub_positive(&cfs_rq->avg.runnable_load_avg, se->avg.runnable_load_avg);
  2330. sub_positive(&cfs_rq->avg.runnable_load_sum,
  2331. se_runnable(se) * se->avg.runnable_load_sum);
  2332. }
  2333. static inline void
  2334. enqueue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
  2335. {
  2336. cfs_rq->avg.load_avg += se->avg.load_avg;
  2337. cfs_rq->avg.load_sum += se_weight(se) * se->avg.load_sum;
  2338. }
  2339. static inline void
  2340. dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
  2341. {
  2342. sub_positive(&cfs_rq->avg.load_avg, se->avg.load_avg);
  2343. sub_positive(&cfs_rq->avg.load_sum, se_weight(se) * se->avg.load_sum);
  2344. }
  2345. #else
  2346. static inline void
  2347. enqueue_runnable_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) { }
  2348. static inline void
  2349. dequeue_runnable_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) { }
  2350. static inline void
  2351. enqueue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) { }
  2352. static inline void
  2353. dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) { }
  2354. #endif
  2355. static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se,
  2356. unsigned long weight, unsigned long runnable)
  2357. {
  2358. if (se->on_rq) {
  2359. /* commit outstanding execution time */
  2360. if (cfs_rq->curr == se)
  2361. update_curr(cfs_rq);
  2362. account_entity_dequeue(cfs_rq, se);
  2363. dequeue_runnable_load_avg(cfs_rq, se);
  2364. }
  2365. dequeue_load_avg(cfs_rq, se);
  2366. se->runnable_weight = runnable;
  2367. update_load_set(&se->load, weight);
  2368. #ifdef CONFIG_SMP
  2369. do {
  2370. u32 divider = LOAD_AVG_MAX - 1024 + se->avg.period_contrib;
  2371. se->avg.load_avg = div_u64(se_weight(se) * se->avg.load_sum, divider);
  2372. se->avg.runnable_load_avg =
  2373. div_u64(se_runnable(se) * se->avg.runnable_load_sum, divider);
  2374. } while (0);
  2375. #endif
  2376. enqueue_load_avg(cfs_rq, se);
  2377. if (se->on_rq) {
  2378. account_entity_enqueue(cfs_rq, se);
  2379. enqueue_runnable_load_avg(cfs_rq, se);
  2380. }
  2381. }
  2382. void reweight_task(struct task_struct *p, int prio)
  2383. {
  2384. struct sched_entity *se = &p->se;
  2385. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  2386. struct load_weight *load = &se->load;
  2387. unsigned long weight = scale_load(sched_prio_to_weight[prio]);
  2388. reweight_entity(cfs_rq, se, weight, weight);
  2389. load->inv_weight = sched_prio_to_wmult[prio];
  2390. }
  2391. #ifdef CONFIG_FAIR_GROUP_SCHED
  2392. #ifdef CONFIG_SMP
  2393. /*
  2394. * All this does is approximate the hierarchical proportion which includes that
  2395. * global sum we all love to hate.
  2396. *
  2397. * That is, the weight of a group entity, is the proportional share of the
  2398. * group weight based on the group runqueue weights. That is:
  2399. *
  2400. * tg->weight * grq->load.weight
  2401. * ge->load.weight = ----------------------------- (1)
  2402. * \Sum grq->load.weight
  2403. *
  2404. * Now, because computing that sum is prohibitively expensive to compute (been
  2405. * there, done that) we approximate it with this average stuff. The average
  2406. * moves slower and therefore the approximation is cheaper and more stable.
  2407. *
  2408. * So instead of the above, we substitute:
  2409. *
  2410. * grq->load.weight -> grq->avg.load_avg (2)
  2411. *
  2412. * which yields the following:
  2413. *
  2414. * tg->weight * grq->avg.load_avg
  2415. * ge->load.weight = ------------------------------ (3)
  2416. * tg->load_avg
  2417. *
  2418. * Where: tg->load_avg ~= \Sum grq->avg.load_avg
  2419. *
  2420. * That is shares_avg, and it is right (given the approximation (2)).
  2421. *
  2422. * The problem with it is that because the average is slow -- it was designed
  2423. * to be exactly that of course -- this leads to transients in boundary
  2424. * conditions. In specific, the case where the group was idle and we start the
  2425. * one task. It takes time for our CPU's grq->avg.load_avg to build up,
  2426. * yielding bad latency etc..
  2427. *
  2428. * Now, in that special case (1) reduces to:
  2429. *
  2430. * tg->weight * grq->load.weight
  2431. * ge->load.weight = ----------------------------- = tg->weight (4)
  2432. * grp->load.weight
  2433. *
  2434. * That is, the sum collapses because all other CPUs are idle; the UP scenario.
  2435. *
  2436. * So what we do is modify our approximation (3) to approach (4) in the (near)
  2437. * UP case, like:
  2438. *
  2439. * ge->load.weight =
  2440. *
  2441. * tg->weight * grq->load.weight
  2442. * --------------------------------------------------- (5)
  2443. * tg->load_avg - grq->avg.load_avg + grq->load.weight
  2444. *
  2445. * But because grq->load.weight can drop to 0, resulting in a divide by zero,
  2446. * we need to use grq->avg.load_avg as its lower bound, which then gives:
  2447. *
  2448. *
  2449. * tg->weight * grq->load.weight
  2450. * ge->load.weight = ----------------------------- (6)
  2451. * tg_load_avg'
  2452. *
  2453. * Where:
  2454. *
  2455. * tg_load_avg' = tg->load_avg - grq->avg.load_avg +
  2456. * max(grq->load.weight, grq->avg.load_avg)
  2457. *
  2458. * And that is shares_weight and is icky. In the (near) UP case it approaches
  2459. * (4) while in the normal case it approaches (3). It consistently
  2460. * overestimates the ge->load.weight and therefore:
  2461. *
  2462. * \Sum ge->load.weight >= tg->weight
  2463. *
  2464. * hence icky!
  2465. */
  2466. static long calc_group_shares(struct cfs_rq *cfs_rq)
  2467. {
  2468. long tg_weight, tg_shares, load, shares;
  2469. struct task_group *tg = cfs_rq->tg;
  2470. tg_shares = READ_ONCE(tg->shares);
  2471. load = max(scale_load_down(cfs_rq->load.weight), cfs_rq->avg.load_avg);
  2472. tg_weight = atomic_long_read(&tg->load_avg);
  2473. /* Ensure tg_weight >= load */
  2474. tg_weight -= cfs_rq->tg_load_avg_contrib;
  2475. tg_weight += load;
  2476. shares = (tg_shares * load);
  2477. if (tg_weight)
  2478. shares /= tg_weight;
  2479. /*
  2480. * MIN_SHARES has to be unscaled here to support per-CPU partitioning
  2481. * of a group with small tg->shares value. It is a floor value which is
  2482. * assigned as a minimum load.weight to the sched_entity representing
  2483. * the group on a CPU.
  2484. *
  2485. * E.g. on 64-bit for a group with tg->shares of scale_load(15)=15*1024
  2486. * on an 8-core system with 8 tasks each runnable on one CPU shares has
  2487. * to be 15*1024*1/8=1920 instead of scale_load(MIN_SHARES)=2*1024. In
  2488. * case no task is runnable on a CPU MIN_SHARES=2 should be returned
  2489. * instead of 0.
  2490. */
  2491. return clamp_t(long, shares, MIN_SHARES, tg_shares);
  2492. }
  2493. /*
  2494. * This calculates the effective runnable weight for a group entity based on
  2495. * the group entity weight calculated above.
  2496. *
  2497. * Because of the above approximation (2), our group entity weight is
  2498. * an load_avg based ratio (3). This means that it includes blocked load and
  2499. * does not represent the runnable weight.
  2500. *
  2501. * Approximate the group entity's runnable weight per ratio from the group
  2502. * runqueue:
  2503. *
  2504. * grq->avg.runnable_load_avg
  2505. * ge->runnable_weight = ge->load.weight * -------------------------- (7)
  2506. * grq->avg.load_avg
  2507. *
  2508. * However, analogous to above, since the avg numbers are slow, this leads to
  2509. * transients in the from-idle case. Instead we use:
  2510. *
  2511. * ge->runnable_weight = ge->load.weight *
  2512. *
  2513. * max(grq->avg.runnable_load_avg, grq->runnable_weight)
  2514. * ----------------------------------------------------- (8)
  2515. * max(grq->avg.load_avg, grq->load.weight)
  2516. *
  2517. * Where these max() serve both to use the 'instant' values to fix the slow
  2518. * from-idle and avoid the /0 on to-idle, similar to (6).
  2519. */
  2520. static long calc_group_runnable(struct cfs_rq *cfs_rq, long shares)
  2521. {
  2522. long runnable, load_avg;
  2523. load_avg = max(cfs_rq->avg.load_avg,
  2524. scale_load_down(cfs_rq->load.weight));
  2525. runnable = max(cfs_rq->avg.runnable_load_avg,
  2526. scale_load_down(cfs_rq->runnable_weight));
  2527. runnable *= shares;
  2528. if (load_avg)
  2529. runnable /= load_avg;
  2530. return clamp_t(long, runnable, MIN_SHARES, shares);
  2531. }
  2532. #endif /* CONFIG_SMP */
  2533. static inline int throttled_hierarchy(struct cfs_rq *cfs_rq);
  2534. /*
  2535. * Recomputes the group entity based on the current state of its group
  2536. * runqueue.
  2537. */
  2538. static void update_cfs_group(struct sched_entity *se)
  2539. {
  2540. struct cfs_rq *gcfs_rq = group_cfs_rq(se);
  2541. long shares, runnable;
  2542. if (!gcfs_rq)
  2543. return;
  2544. if (throttled_hierarchy(gcfs_rq))
  2545. return;
  2546. #ifndef CONFIG_SMP
  2547. runnable = shares = READ_ONCE(gcfs_rq->tg->shares);
  2548. if (likely(se->load.weight == shares))
  2549. return;
  2550. #else
  2551. shares = calc_group_shares(gcfs_rq);
  2552. runnable = calc_group_runnable(gcfs_rq, shares);
  2553. #endif
  2554. reweight_entity(cfs_rq_of(se), se, shares, runnable);
  2555. }
  2556. #else /* CONFIG_FAIR_GROUP_SCHED */
  2557. static inline void update_cfs_group(struct sched_entity *se)
  2558. {
  2559. }
  2560. #endif /* CONFIG_FAIR_GROUP_SCHED */
  2561. static inline void cfs_rq_util_change(struct cfs_rq *cfs_rq, int flags)
  2562. {
  2563. struct rq *rq = rq_of(cfs_rq);
  2564. if (&rq->cfs == cfs_rq || (flags & SCHED_CPUFREQ_MIGRATION)) {
  2565. /*
  2566. * There are a few boundary cases this might miss but it should
  2567. * get called often enough that that should (hopefully) not be
  2568. * a real problem.
  2569. *
  2570. * It will not get called when we go idle, because the idle
  2571. * thread is a different class (!fair), nor will the utilization
  2572. * number include things like RT tasks.
  2573. *
  2574. * As is, the util number is not freq-invariant (we'd have to
  2575. * implement arch_scale_freq_capacity() for that).
  2576. *
  2577. * See cpu_util().
  2578. */
  2579. cpufreq_update_util(rq, flags);
  2580. }
  2581. }
  2582. #ifdef CONFIG_SMP
  2583. /*
  2584. * Approximate:
  2585. * val * y^n, where y^32 ~= 0.5 (~1 scheduling period)
  2586. */
  2587. static u64 decay_load(u64 val, u64 n)
  2588. {
  2589. unsigned int local_n;
  2590. if (unlikely(n > LOAD_AVG_PERIOD * 63))
  2591. return 0;
  2592. /* after bounds checking we can collapse to 32-bit */
  2593. local_n = n;
  2594. /*
  2595. * As y^PERIOD = 1/2, we can combine
  2596. * y^n = 1/2^(n/PERIOD) * y^(n%PERIOD)
  2597. * With a look-up table which covers y^n (n<PERIOD)
  2598. *
  2599. * To achieve constant time decay_load.
  2600. */
  2601. if (unlikely(local_n >= LOAD_AVG_PERIOD)) {
  2602. val >>= local_n / LOAD_AVG_PERIOD;
  2603. local_n %= LOAD_AVG_PERIOD;
  2604. }
  2605. val = mul_u64_u32_shr(val, runnable_avg_yN_inv[local_n], 32);
  2606. return val;
  2607. }
  2608. static u32 __accumulate_pelt_segments(u64 periods, u32 d1, u32 d3)
  2609. {
  2610. u32 c1, c2, c3 = d3; /* y^0 == 1 */
  2611. /*
  2612. * c1 = d1 y^p
  2613. */
  2614. c1 = decay_load((u64)d1, periods);
  2615. /*
  2616. * p-1
  2617. * c2 = 1024 \Sum y^n
  2618. * n=1
  2619. *
  2620. * inf inf
  2621. * = 1024 ( \Sum y^n - \Sum y^n - y^0 )
  2622. * n=0 n=p
  2623. */
  2624. c2 = LOAD_AVG_MAX - decay_load(LOAD_AVG_MAX, periods) - 1024;
  2625. return c1 + c2 + c3;
  2626. }
  2627. /*
  2628. * Accumulate the three separate parts of the sum; d1 the remainder
  2629. * of the last (incomplete) period, d2 the span of full periods and d3
  2630. * the remainder of the (incomplete) current period.
  2631. *
  2632. * d1 d2 d3
  2633. * ^ ^ ^
  2634. * | | |
  2635. * |<->|<----------------->|<--->|
  2636. * ... |---x---|------| ... |------|-----x (now)
  2637. *
  2638. * p-1
  2639. * u' = (u + d1) y^p + 1024 \Sum y^n + d3 y^0
  2640. * n=1
  2641. *
  2642. * = u y^p + (Step 1)
  2643. *
  2644. * p-1
  2645. * d1 y^p + 1024 \Sum y^n + d3 y^0 (Step 2)
  2646. * n=1
  2647. */
  2648. static __always_inline u32
  2649. accumulate_sum(u64 delta, int cpu, struct sched_avg *sa,
  2650. unsigned long load, unsigned long runnable, int running)
  2651. {
  2652. unsigned long scale_freq, scale_cpu;
  2653. u32 contrib = (u32)delta; /* p == 0 -> delta < 1024 */
  2654. u64 periods;
  2655. scale_freq = arch_scale_freq_capacity(cpu);
  2656. scale_cpu = arch_scale_cpu_capacity(NULL, cpu);
  2657. delta += sa->period_contrib;
  2658. periods = delta / 1024; /* A period is 1024us (~1ms) */
  2659. /*
  2660. * Step 1: decay old *_sum if we crossed period boundaries.
  2661. */
  2662. if (periods) {
  2663. sa->load_sum = decay_load(sa->load_sum, periods);
  2664. sa->runnable_load_sum =
  2665. decay_load(sa->runnable_load_sum, periods);
  2666. sa->util_sum = decay_load((u64)(sa->util_sum), periods);
  2667. /*
  2668. * Step 2
  2669. */
  2670. delta %= 1024;
  2671. contrib = __accumulate_pelt_segments(periods,
  2672. 1024 - sa->period_contrib, delta);
  2673. }
  2674. sa->period_contrib = delta;
  2675. contrib = cap_scale(contrib, scale_freq);
  2676. if (load)
  2677. sa->load_sum += load * contrib;
  2678. if (runnable)
  2679. sa->runnable_load_sum += runnable * contrib;
  2680. if (running)
  2681. sa->util_sum += contrib * scale_cpu;
  2682. return periods;
  2683. }
  2684. /*
  2685. * We can represent the historical contribution to runnable average as the
  2686. * coefficients of a geometric series. To do this we sub-divide our runnable
  2687. * history into segments of approximately 1ms (1024us); label the segment that
  2688. * occurred N-ms ago p_N, with p_0 corresponding to the current period, e.g.
  2689. *
  2690. * [<- 1024us ->|<- 1024us ->|<- 1024us ->| ...
  2691. * p0 p1 p2
  2692. * (now) (~1ms ago) (~2ms ago)
  2693. *
  2694. * Let u_i denote the fraction of p_i that the entity was runnable.
  2695. *
  2696. * We then designate the fractions u_i as our co-efficients, yielding the
  2697. * following representation of historical load:
  2698. * u_0 + u_1*y + u_2*y^2 + u_3*y^3 + ...
  2699. *
  2700. * We choose y based on the with of a reasonably scheduling period, fixing:
  2701. * y^32 = 0.5
  2702. *
  2703. * This means that the contribution to load ~32ms ago (u_32) will be weighted
  2704. * approximately half as much as the contribution to load within the last ms
  2705. * (u_0).
  2706. *
  2707. * When a period "rolls over" and we have new u_0`, multiplying the previous
  2708. * sum again by y is sufficient to update:
  2709. * load_avg = u_0` + y*(u_0 + u_1*y + u_2*y^2 + ... )
  2710. * = u_0 + u_1*y + u_2*y^2 + ... [re-labeling u_i --> u_{i+1}]
  2711. */
  2712. static __always_inline int
  2713. ___update_load_sum(u64 now, int cpu, struct sched_avg *sa,
  2714. unsigned long load, unsigned long runnable, int running)
  2715. {
  2716. u64 delta;
  2717. delta = now - sa->last_update_time;
  2718. /*
  2719. * This should only happen when time goes backwards, which it
  2720. * unfortunately does during sched clock init when we swap over to TSC.
  2721. */
  2722. if ((s64)delta < 0) {
  2723. sa->last_update_time = now;
  2724. return 0;
  2725. }
  2726. /*
  2727. * Use 1024ns as the unit of measurement since it's a reasonable
  2728. * approximation of 1us and fast to compute.
  2729. */
  2730. delta >>= 10;
  2731. if (!delta)
  2732. return 0;
  2733. sa->last_update_time += delta << 10;
  2734. /*
  2735. * running is a subset of runnable (weight) so running can't be set if
  2736. * runnable is clear. But there are some corner cases where the current
  2737. * se has been already dequeued but cfs_rq->curr still points to it.
  2738. * This means that weight will be 0 but not running for a sched_entity
  2739. * but also for a cfs_rq if the latter becomes idle. As an example,
  2740. * this happens during idle_balance() which calls
  2741. * update_blocked_averages()
  2742. */
  2743. if (!load)
  2744. runnable = running = 0;
  2745. /*
  2746. * Now we know we crossed measurement unit boundaries. The *_avg
  2747. * accrues by two steps:
  2748. *
  2749. * Step 1: accumulate *_sum since last_update_time. If we haven't
  2750. * crossed period boundaries, finish.
  2751. */
  2752. if (!accumulate_sum(delta, cpu, sa, load, runnable, running))
  2753. return 0;
  2754. return 1;
  2755. }
  2756. static __always_inline void
  2757. ___update_load_avg(struct sched_avg *sa, unsigned long load, unsigned long runnable)
  2758. {
  2759. u32 divider = LOAD_AVG_MAX - 1024 + sa->period_contrib;
  2760. /*
  2761. * Step 2: update *_avg.
  2762. */
  2763. sa->load_avg = div_u64(load * sa->load_sum, divider);
  2764. sa->runnable_load_avg = div_u64(runnable * sa->runnable_load_sum, divider);
  2765. sa->util_avg = sa->util_sum / divider;
  2766. }
  2767. /*
  2768. * When a task is dequeued, its estimated utilization should not be update if
  2769. * its util_avg has not been updated at least once.
  2770. * This flag is used to synchronize util_avg updates with util_est updates.
  2771. * We map this information into the LSB bit of the utilization saved at
  2772. * dequeue time (i.e. util_est.dequeued).
  2773. */
  2774. #define UTIL_AVG_UNCHANGED 0x1
  2775. static inline void cfs_se_util_change(struct sched_avg *avg)
  2776. {
  2777. unsigned int enqueued;
  2778. if (!sched_feat(UTIL_EST))
  2779. return;
  2780. /* Avoid store if the flag has been already set */
  2781. enqueued = avg->util_est.enqueued;
  2782. if (!(enqueued & UTIL_AVG_UNCHANGED))
  2783. return;
  2784. /* Reset flag to report util_avg has been updated */
  2785. enqueued &= ~UTIL_AVG_UNCHANGED;
  2786. WRITE_ONCE(avg->util_est.enqueued, enqueued);
  2787. }
  2788. /*
  2789. * sched_entity:
  2790. *
  2791. * task:
  2792. * se_runnable() == se_weight()
  2793. *
  2794. * group: [ see update_cfs_group() ]
  2795. * se_weight() = tg->weight * grq->load_avg / tg->load_avg
  2796. * se_runnable() = se_weight(se) * grq->runnable_load_avg / grq->load_avg
  2797. *
  2798. * load_sum := runnable_sum
  2799. * load_avg = se_weight(se) * runnable_avg
  2800. *
  2801. * runnable_load_sum := runnable_sum
  2802. * runnable_load_avg = se_runnable(se) * runnable_avg
  2803. *
  2804. * XXX collapse load_sum and runnable_load_sum
  2805. *
  2806. * cfq_rs:
  2807. *
  2808. * load_sum = \Sum se_weight(se) * se->avg.load_sum
  2809. * load_avg = \Sum se->avg.load_avg
  2810. *
  2811. * runnable_load_sum = \Sum se_runnable(se) * se->avg.runnable_load_sum
  2812. * runnable_load_avg = \Sum se->avg.runable_load_avg
  2813. */
  2814. static int
  2815. __update_load_avg_blocked_se(u64 now, int cpu, struct sched_entity *se)
  2816. {
  2817. if (entity_is_task(se))
  2818. se->runnable_weight = se->load.weight;
  2819. if (___update_load_sum(now, cpu, &se->avg, 0, 0, 0)) {
  2820. ___update_load_avg(&se->avg, se_weight(se), se_runnable(se));
  2821. return 1;
  2822. }
  2823. return 0;
  2824. }
  2825. static int
  2826. __update_load_avg_se(u64 now, int cpu, struct cfs_rq *cfs_rq, struct sched_entity *se)
  2827. {
  2828. if (entity_is_task(se))
  2829. se->runnable_weight = se->load.weight;
  2830. if (___update_load_sum(now, cpu, &se->avg, !!se->on_rq, !!se->on_rq,
  2831. cfs_rq->curr == se)) {
  2832. ___update_load_avg(&se->avg, se_weight(se), se_runnable(se));
  2833. cfs_se_util_change(&se->avg);
  2834. return 1;
  2835. }
  2836. return 0;
  2837. }
  2838. static int
  2839. __update_load_avg_cfs_rq(u64 now, int cpu, struct cfs_rq *cfs_rq)
  2840. {
  2841. if (___update_load_sum(now, cpu, &cfs_rq->avg,
  2842. scale_load_down(cfs_rq->load.weight),
  2843. scale_load_down(cfs_rq->runnable_weight),
  2844. cfs_rq->curr != NULL)) {
  2845. ___update_load_avg(&cfs_rq->avg, 1, 1);
  2846. return 1;
  2847. }
  2848. return 0;
  2849. }
  2850. #ifdef CONFIG_FAIR_GROUP_SCHED
  2851. /**
  2852. * update_tg_load_avg - update the tg's load avg
  2853. * @cfs_rq: the cfs_rq whose avg changed
  2854. * @force: update regardless of how small the difference
  2855. *
  2856. * This function 'ensures': tg->load_avg := \Sum tg->cfs_rq[]->avg.load.
  2857. * However, because tg->load_avg is a global value there are performance
  2858. * considerations.
  2859. *
  2860. * In order to avoid having to look at the other cfs_rq's, we use a
  2861. * differential update where we store the last value we propagated. This in
  2862. * turn allows skipping updates if the differential is 'small'.
  2863. *
  2864. * Updating tg's load_avg is necessary before update_cfs_share().
  2865. */
  2866. static inline void update_tg_load_avg(struct cfs_rq *cfs_rq, int force)
  2867. {
  2868. long delta = cfs_rq->avg.load_avg - cfs_rq->tg_load_avg_contrib;
  2869. /*
  2870. * No need to update load_avg for root_task_group as it is not used.
  2871. */
  2872. if (cfs_rq->tg == &root_task_group)
  2873. return;
  2874. if (force || abs(delta) > cfs_rq->tg_load_avg_contrib / 64) {
  2875. atomic_long_add(delta, &cfs_rq->tg->load_avg);
  2876. cfs_rq->tg_load_avg_contrib = cfs_rq->avg.load_avg;
  2877. }
  2878. }
  2879. /*
  2880. * Called within set_task_rq() right before setting a task's CPU. The
  2881. * caller only guarantees p->pi_lock is held; no other assumptions,
  2882. * including the state of rq->lock, should be made.
  2883. */
  2884. void set_task_rq_fair(struct sched_entity *se,
  2885. struct cfs_rq *prev, struct cfs_rq *next)
  2886. {
  2887. u64 p_last_update_time;
  2888. u64 n_last_update_time;
  2889. if (!sched_feat(ATTACH_AGE_LOAD))
  2890. return;
  2891. /*
  2892. * We are supposed to update the task to "current" time, then its up to
  2893. * date and ready to go to new CPU/cfs_rq. But we have difficulty in
  2894. * getting what current time is, so simply throw away the out-of-date
  2895. * time. This will result in the wakee task is less decayed, but giving
  2896. * the wakee more load sounds not bad.
  2897. */
  2898. if (!(se->avg.last_update_time && prev))
  2899. return;
  2900. #ifndef CONFIG_64BIT
  2901. {
  2902. u64 p_last_update_time_copy;
  2903. u64 n_last_update_time_copy;
  2904. do {
  2905. p_last_update_time_copy = prev->load_last_update_time_copy;
  2906. n_last_update_time_copy = next->load_last_update_time_copy;
  2907. smp_rmb();
  2908. p_last_update_time = prev->avg.last_update_time;
  2909. n_last_update_time = next->avg.last_update_time;
  2910. } while (p_last_update_time != p_last_update_time_copy ||
  2911. n_last_update_time != n_last_update_time_copy);
  2912. }
  2913. #else
  2914. p_last_update_time = prev->avg.last_update_time;
  2915. n_last_update_time = next->avg.last_update_time;
  2916. #endif
  2917. __update_load_avg_blocked_se(p_last_update_time, cpu_of(rq_of(prev)), se);
  2918. se->avg.last_update_time = n_last_update_time;
  2919. }
  2920. /*
  2921. * When on migration a sched_entity joins/leaves the PELT hierarchy, we need to
  2922. * propagate its contribution. The key to this propagation is the invariant
  2923. * that for each group:
  2924. *
  2925. * ge->avg == grq->avg (1)
  2926. *
  2927. * _IFF_ we look at the pure running and runnable sums. Because they
  2928. * represent the very same entity, just at different points in the hierarchy.
  2929. *
  2930. * Per the above update_tg_cfs_util() is trivial and simply copies the running
  2931. * sum over (but still wrong, because the group entity and group rq do not have
  2932. * their PELT windows aligned).
  2933. *
  2934. * However, update_tg_cfs_runnable() is more complex. So we have:
  2935. *
  2936. * ge->avg.load_avg = ge->load.weight * ge->avg.runnable_avg (2)
  2937. *
  2938. * And since, like util, the runnable part should be directly transferable,
  2939. * the following would _appear_ to be the straight forward approach:
  2940. *
  2941. * grq->avg.load_avg = grq->load.weight * grq->avg.runnable_avg (3)
  2942. *
  2943. * And per (1) we have:
  2944. *
  2945. * ge->avg.runnable_avg == grq->avg.runnable_avg
  2946. *
  2947. * Which gives:
  2948. *
  2949. * ge->load.weight * grq->avg.load_avg
  2950. * ge->avg.load_avg = ----------------------------------- (4)
  2951. * grq->load.weight
  2952. *
  2953. * Except that is wrong!
  2954. *
  2955. * Because while for entities historical weight is not important and we
  2956. * really only care about our future and therefore can consider a pure
  2957. * runnable sum, runqueues can NOT do this.
  2958. *
  2959. * We specifically want runqueues to have a load_avg that includes
  2960. * historical weights. Those represent the blocked load, the load we expect
  2961. * to (shortly) return to us. This only works by keeping the weights as
  2962. * integral part of the sum. We therefore cannot decompose as per (3).
  2963. *
  2964. * Another reason this doesn't work is that runnable isn't a 0-sum entity.
  2965. * Imagine a rq with 2 tasks that each are runnable 2/3 of the time. Then the
  2966. * rq itself is runnable anywhere between 2/3 and 1 depending on how the
  2967. * runnable section of these tasks overlap (or not). If they were to perfectly
  2968. * align the rq as a whole would be runnable 2/3 of the time. If however we
  2969. * always have at least 1 runnable task, the rq as a whole is always runnable.
  2970. *
  2971. * So we'll have to approximate.. :/
  2972. *
  2973. * Given the constraint:
  2974. *
  2975. * ge->avg.running_sum <= ge->avg.runnable_sum <= LOAD_AVG_MAX
  2976. *
  2977. * We can construct a rule that adds runnable to a rq by assuming minimal
  2978. * overlap.
  2979. *
  2980. * On removal, we'll assume each task is equally runnable; which yields:
  2981. *
  2982. * grq->avg.runnable_sum = grq->avg.load_sum / grq->load.weight
  2983. *
  2984. * XXX: only do this for the part of runnable > running ?
  2985. *
  2986. */
  2987. static inline void
  2988. update_tg_cfs_util(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
  2989. {
  2990. long delta = gcfs_rq->avg.util_avg - se->avg.util_avg;
  2991. /* Nothing to update */
  2992. if (!delta)
  2993. return;
  2994. /*
  2995. * The relation between sum and avg is:
  2996. *
  2997. * LOAD_AVG_MAX - 1024 + sa->period_contrib
  2998. *
  2999. * however, the PELT windows are not aligned between grq and gse.
  3000. */
  3001. /* Set new sched_entity's utilization */
  3002. se->avg.util_avg = gcfs_rq->avg.util_avg;
  3003. se->avg.util_sum = se->avg.util_avg * LOAD_AVG_MAX;
  3004. /* Update parent cfs_rq utilization */
  3005. add_positive(&cfs_rq->avg.util_avg, delta);
  3006. cfs_rq->avg.util_sum = cfs_rq->avg.util_avg * LOAD_AVG_MAX;
  3007. }
  3008. static inline void
  3009. update_tg_cfs_runnable(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
  3010. {
  3011. long delta_avg, running_sum, runnable_sum = gcfs_rq->prop_runnable_sum;
  3012. unsigned long runnable_load_avg, load_avg;
  3013. u64 runnable_load_sum, load_sum = 0;
  3014. s64 delta_sum;
  3015. if (!runnable_sum)
  3016. return;
  3017. gcfs_rq->prop_runnable_sum = 0;
  3018. if (runnable_sum >= 0) {
  3019. /*
  3020. * Add runnable; clip at LOAD_AVG_MAX. Reflects that until
  3021. * the CPU is saturated running == runnable.
  3022. */
  3023. runnable_sum += se->avg.load_sum;
  3024. runnable_sum = min(runnable_sum, (long)LOAD_AVG_MAX);
  3025. } else {
  3026. /*
  3027. * Estimate the new unweighted runnable_sum of the gcfs_rq by
  3028. * assuming all tasks are equally runnable.
  3029. */
  3030. if (scale_load_down(gcfs_rq->load.weight)) {
  3031. load_sum = div_s64(gcfs_rq->avg.load_sum,
  3032. scale_load_down(gcfs_rq->load.weight));
  3033. }
  3034. /* But make sure to not inflate se's runnable */
  3035. runnable_sum = min(se->avg.load_sum, load_sum);
  3036. }
  3037. /*
  3038. * runnable_sum can't be lower than running_sum
  3039. * As running sum is scale with CPU capacity wehreas the runnable sum
  3040. * is not we rescale running_sum 1st
  3041. */
  3042. running_sum = se->avg.util_sum /
  3043. arch_scale_cpu_capacity(NULL, cpu_of(rq_of(cfs_rq)));
  3044. runnable_sum = max(runnable_sum, running_sum);
  3045. load_sum = (s64)se_weight(se) * runnable_sum;
  3046. load_avg = div_s64(load_sum, LOAD_AVG_MAX);
  3047. delta_sum = load_sum - (s64)se_weight(se) * se->avg.load_sum;
  3048. delta_avg = load_avg - se->avg.load_avg;
  3049. se->avg.load_sum = runnable_sum;
  3050. se->avg.load_avg = load_avg;
  3051. add_positive(&cfs_rq->avg.load_avg, delta_avg);
  3052. add_positive(&cfs_rq->avg.load_sum, delta_sum);
  3053. runnable_load_sum = (s64)se_runnable(se) * runnable_sum;
  3054. runnable_load_avg = div_s64(runnable_load_sum, LOAD_AVG_MAX);
  3055. delta_sum = runnable_load_sum - se_weight(se) * se->avg.runnable_load_sum;
  3056. delta_avg = runnable_load_avg - se->avg.runnable_load_avg;
  3057. se->avg.runnable_load_sum = runnable_sum;
  3058. se->avg.runnable_load_avg = runnable_load_avg;
  3059. if (se->on_rq) {
  3060. add_positive(&cfs_rq->avg.runnable_load_avg, delta_avg);
  3061. add_positive(&cfs_rq->avg.runnable_load_sum, delta_sum);
  3062. }
  3063. }
  3064. static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum)
  3065. {
  3066. cfs_rq->propagate = 1;
  3067. cfs_rq->prop_runnable_sum += runnable_sum;
  3068. }
  3069. /* Update task and its cfs_rq load average */
  3070. static inline int propagate_entity_load_avg(struct sched_entity *se)
  3071. {
  3072. struct cfs_rq *cfs_rq, *gcfs_rq;
  3073. if (entity_is_task(se))
  3074. return 0;
  3075. gcfs_rq = group_cfs_rq(se);
  3076. if (!gcfs_rq->propagate)
  3077. return 0;
  3078. gcfs_rq->propagate = 0;
  3079. cfs_rq = cfs_rq_of(se);
  3080. add_tg_cfs_propagate(cfs_rq, gcfs_rq->prop_runnable_sum);
  3081. update_tg_cfs_util(cfs_rq, se, gcfs_rq);
  3082. update_tg_cfs_runnable(cfs_rq, se, gcfs_rq);
  3083. return 1;
  3084. }
  3085. /*
  3086. * Check if we need to update the load and the utilization of a blocked
  3087. * group_entity:
  3088. */
  3089. static inline bool skip_blocked_update(struct sched_entity *se)
  3090. {
  3091. struct cfs_rq *gcfs_rq = group_cfs_rq(se);
  3092. /*
  3093. * If sched_entity still have not zero load or utilization, we have to
  3094. * decay it:
  3095. */
  3096. if (se->avg.load_avg || se->avg.util_avg)
  3097. return false;
  3098. /*
  3099. * If there is a pending propagation, we have to update the load and
  3100. * the utilization of the sched_entity:
  3101. */
  3102. if (gcfs_rq->propagate)
  3103. return false;
  3104. /*
  3105. * Otherwise, the load and the utilization of the sched_entity is
  3106. * already zero and there is no pending propagation, so it will be a
  3107. * waste of time to try to decay it:
  3108. */
  3109. return true;
  3110. }
  3111. #else /* CONFIG_FAIR_GROUP_SCHED */
  3112. static inline void update_tg_load_avg(struct cfs_rq *cfs_rq, int force) {}
  3113. static inline int propagate_entity_load_avg(struct sched_entity *se)
  3114. {
  3115. return 0;
  3116. }
  3117. static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum) {}
  3118. #endif /* CONFIG_FAIR_GROUP_SCHED */
  3119. /**
  3120. * update_cfs_rq_load_avg - update the cfs_rq's load/util averages
  3121. * @now: current time, as per cfs_rq_clock_task()
  3122. * @cfs_rq: cfs_rq to update
  3123. *
  3124. * The cfs_rq avg is the direct sum of all its entities (blocked and runnable)
  3125. * avg. The immediate corollary is that all (fair) tasks must be attached, see
  3126. * post_init_entity_util_avg().
  3127. *
  3128. * cfs_rq->avg is used for task_h_load() and update_cfs_share() for example.
  3129. *
  3130. * Returns true if the load decayed or we removed load.
  3131. *
  3132. * Since both these conditions indicate a changed cfs_rq->avg.load we should
  3133. * call update_tg_load_avg() when this function returns true.
  3134. */
  3135. static inline int
  3136. update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq)
  3137. {
  3138. unsigned long removed_load = 0, removed_util = 0, removed_runnable_sum = 0;
  3139. struct sched_avg *sa = &cfs_rq->avg;
  3140. int decayed = 0;
  3141. if (cfs_rq->removed.nr) {
  3142. unsigned long r;
  3143. u32 divider = LOAD_AVG_MAX - 1024 + sa->period_contrib;
  3144. raw_spin_lock(&cfs_rq->removed.lock);
  3145. swap(cfs_rq->removed.util_avg, removed_util);
  3146. swap(cfs_rq->removed.load_avg, removed_load);
  3147. swap(cfs_rq->removed.runnable_sum, removed_runnable_sum);
  3148. cfs_rq->removed.nr = 0;
  3149. raw_spin_unlock(&cfs_rq->removed.lock);
  3150. r = removed_load;
  3151. sub_positive(&sa->load_avg, r);
  3152. sub_positive(&sa->load_sum, r * divider);
  3153. r = removed_util;
  3154. sub_positive(&sa->util_avg, r);
  3155. sub_positive(&sa->util_sum, r * divider);
  3156. add_tg_cfs_propagate(cfs_rq, -(long)removed_runnable_sum);
  3157. decayed = 1;
  3158. }
  3159. decayed |= __update_load_avg_cfs_rq(now, cpu_of(rq_of(cfs_rq)), cfs_rq);
  3160. #ifndef CONFIG_64BIT
  3161. smp_wmb();
  3162. cfs_rq->load_last_update_time_copy = sa->last_update_time;
  3163. #endif
  3164. if (decayed)
  3165. cfs_rq_util_change(cfs_rq, 0);
  3166. return decayed;
  3167. }
  3168. /**
  3169. * attach_entity_load_avg - attach this entity to its cfs_rq load avg
  3170. * @cfs_rq: cfs_rq to attach to
  3171. * @se: sched_entity to attach
  3172. *
  3173. * Must call update_cfs_rq_load_avg() before this, since we rely on
  3174. * cfs_rq->avg.last_update_time being current.
  3175. */
  3176. static void attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
  3177. {
  3178. u32 divider = LOAD_AVG_MAX - 1024 + cfs_rq->avg.period_contrib;
  3179. /*
  3180. * When we attach the @se to the @cfs_rq, we must align the decay
  3181. * window because without that, really weird and wonderful things can
  3182. * happen.
  3183. *
  3184. * XXX illustrate
  3185. */
  3186. se->avg.last_update_time = cfs_rq->avg.last_update_time;
  3187. se->avg.period_contrib = cfs_rq->avg.period_contrib;
  3188. /*
  3189. * Hell(o) Nasty stuff.. we need to recompute _sum based on the new
  3190. * period_contrib. This isn't strictly correct, but since we're
  3191. * entirely outside of the PELT hierarchy, nobody cares if we truncate
  3192. * _sum a little.
  3193. */
  3194. se->avg.util_sum = se->avg.util_avg * divider;
  3195. se->avg.load_sum = divider;
  3196. if (se_weight(se)) {
  3197. se->avg.load_sum =
  3198. div_u64(se->avg.load_avg * se->avg.load_sum, se_weight(se));
  3199. }
  3200. se->avg.runnable_load_sum = se->avg.load_sum;
  3201. enqueue_load_avg(cfs_rq, se);
  3202. cfs_rq->avg.util_avg += se->avg.util_avg;
  3203. cfs_rq->avg.util_sum += se->avg.util_sum;
  3204. add_tg_cfs_propagate(cfs_rq, se->avg.load_sum);
  3205. cfs_rq_util_change(cfs_rq, flags);
  3206. }
  3207. /**
  3208. * detach_entity_load_avg - detach this entity from its cfs_rq load avg
  3209. * @cfs_rq: cfs_rq to detach from
  3210. * @se: sched_entity to detach
  3211. *
  3212. * Must call update_cfs_rq_load_avg() before this, since we rely on
  3213. * cfs_rq->avg.last_update_time being current.
  3214. */
  3215. static void detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
  3216. {
  3217. dequeue_load_avg(cfs_rq, se);
  3218. sub_positive(&cfs_rq->avg.util_avg, se->avg.util_avg);
  3219. sub_positive(&cfs_rq->avg.util_sum, se->avg.util_sum);
  3220. add_tg_cfs_propagate(cfs_rq, -se->avg.load_sum);
  3221. cfs_rq_util_change(cfs_rq, 0);
  3222. }
  3223. /*
  3224. * Optional action to be done while updating the load average
  3225. */
  3226. #define UPDATE_TG 0x1
  3227. #define SKIP_AGE_LOAD 0x2
  3228. #define DO_ATTACH 0x4
  3229. /* Update task and its cfs_rq load average */
  3230. static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
  3231. {
  3232. u64 now = cfs_rq_clock_task(cfs_rq);
  3233. struct rq *rq = rq_of(cfs_rq);
  3234. int cpu = cpu_of(rq);
  3235. int decayed;
  3236. /*
  3237. * Track task load average for carrying it to new CPU after migrated, and
  3238. * track group sched_entity load average for task_h_load calc in migration
  3239. */
  3240. if (se->avg.last_update_time && !(flags & SKIP_AGE_LOAD))
  3241. __update_load_avg_se(now, cpu, cfs_rq, se);
  3242. decayed = update_cfs_rq_load_avg(now, cfs_rq);
  3243. decayed |= propagate_entity_load_avg(se);
  3244. if (!se->avg.last_update_time && (flags & DO_ATTACH)) {
  3245. /*
  3246. * DO_ATTACH means we're here from enqueue_entity().
  3247. * !last_update_time means we've passed through
  3248. * migrate_task_rq_fair() indicating we migrated.
  3249. *
  3250. * IOW we're enqueueing a task on a new CPU.
  3251. */
  3252. attach_entity_load_avg(cfs_rq, se, SCHED_CPUFREQ_MIGRATION);
  3253. update_tg_load_avg(cfs_rq, 0);
  3254. } else if (decayed && (flags & UPDATE_TG))
  3255. update_tg_load_avg(cfs_rq, 0);
  3256. }
  3257. #ifndef CONFIG_64BIT
  3258. static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq)
  3259. {
  3260. u64 last_update_time_copy;
  3261. u64 last_update_time;
  3262. do {
  3263. last_update_time_copy = cfs_rq->load_last_update_time_copy;
  3264. smp_rmb();
  3265. last_update_time = cfs_rq->avg.last_update_time;
  3266. } while (last_update_time != last_update_time_copy);
  3267. return last_update_time;
  3268. }
  3269. #else
  3270. static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq)
  3271. {
  3272. return cfs_rq->avg.last_update_time;
  3273. }
  3274. #endif
  3275. /*
  3276. * Synchronize entity load avg of dequeued entity without locking
  3277. * the previous rq.
  3278. */
  3279. void sync_entity_load_avg(struct sched_entity *se)
  3280. {
  3281. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  3282. u64 last_update_time;
  3283. last_update_time = cfs_rq_last_update_time(cfs_rq);
  3284. __update_load_avg_blocked_se(last_update_time, cpu_of(rq_of(cfs_rq)), se);
  3285. }
  3286. /*
  3287. * Task first catches up with cfs_rq, and then subtract
  3288. * itself from the cfs_rq (task must be off the queue now).
  3289. */
  3290. void remove_entity_load_avg(struct sched_entity *se)
  3291. {
  3292. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  3293. unsigned long flags;
  3294. /*
  3295. * tasks cannot exit without having gone through wake_up_new_task() ->
  3296. * post_init_entity_util_avg() which will have added things to the
  3297. * cfs_rq, so we can remove unconditionally.
  3298. *
  3299. * Similarly for groups, they will have passed through
  3300. * post_init_entity_util_avg() before unregister_sched_fair_group()
  3301. * calls this.
  3302. */
  3303. sync_entity_load_avg(se);
  3304. raw_spin_lock_irqsave(&cfs_rq->removed.lock, flags);
  3305. ++cfs_rq->removed.nr;
  3306. cfs_rq->removed.util_avg += se->avg.util_avg;
  3307. cfs_rq->removed.load_avg += se->avg.load_avg;
  3308. cfs_rq->removed.runnable_sum += se->avg.load_sum; /* == runnable_sum */
  3309. raw_spin_unlock_irqrestore(&cfs_rq->removed.lock, flags);
  3310. }
  3311. static inline unsigned long cfs_rq_runnable_load_avg(struct cfs_rq *cfs_rq)
  3312. {
  3313. return cfs_rq->avg.runnable_load_avg;
  3314. }
  3315. static inline unsigned long cfs_rq_load_avg(struct cfs_rq *cfs_rq)
  3316. {
  3317. return cfs_rq->avg.load_avg;
  3318. }
  3319. static int idle_balance(struct rq *this_rq, struct rq_flags *rf);
  3320. static inline unsigned long task_util(struct task_struct *p)
  3321. {
  3322. return READ_ONCE(p->se.avg.util_avg);
  3323. }
  3324. static inline unsigned long _task_util_est(struct task_struct *p)
  3325. {
  3326. struct util_est ue = READ_ONCE(p->se.avg.util_est);
  3327. return max(ue.ewma, ue.enqueued);
  3328. }
  3329. static inline unsigned long task_util_est(struct task_struct *p)
  3330. {
  3331. return max(task_util(p), _task_util_est(p));
  3332. }
  3333. static inline void util_est_enqueue(struct cfs_rq *cfs_rq,
  3334. struct task_struct *p)
  3335. {
  3336. unsigned int enqueued;
  3337. if (!sched_feat(UTIL_EST))
  3338. return;
  3339. /* Update root cfs_rq's estimated utilization */
  3340. enqueued = cfs_rq->avg.util_est.enqueued;
  3341. enqueued += (_task_util_est(p) | UTIL_AVG_UNCHANGED);
  3342. WRITE_ONCE(cfs_rq->avg.util_est.enqueued, enqueued);
  3343. }
  3344. /*
  3345. * Check if a (signed) value is within a specified (unsigned) margin,
  3346. * based on the observation that:
  3347. *
  3348. * abs(x) < y := (unsigned)(x + y - 1) < (2 * y - 1)
  3349. *
  3350. * NOTE: this only works when value + maring < INT_MAX.
  3351. */
  3352. static inline bool within_margin(int value, int margin)
  3353. {
  3354. return ((unsigned int)(value + margin - 1) < (2 * margin - 1));
  3355. }
  3356. static void
  3357. util_est_dequeue(struct cfs_rq *cfs_rq, struct task_struct *p, bool task_sleep)
  3358. {
  3359. long last_ewma_diff;
  3360. struct util_est ue;
  3361. if (!sched_feat(UTIL_EST))
  3362. return;
  3363. /*
  3364. * Update root cfs_rq's estimated utilization
  3365. *
  3366. * If *p is the last task then the root cfs_rq's estimated utilization
  3367. * of a CPU is 0 by definition.
  3368. */
  3369. ue.enqueued = 0;
  3370. if (cfs_rq->nr_running) {
  3371. ue.enqueued = cfs_rq->avg.util_est.enqueued;
  3372. ue.enqueued -= min_t(unsigned int, ue.enqueued,
  3373. (_task_util_est(p) | UTIL_AVG_UNCHANGED));
  3374. }
  3375. WRITE_ONCE(cfs_rq->avg.util_est.enqueued, ue.enqueued);
  3376. /*
  3377. * Skip update of task's estimated utilization when the task has not
  3378. * yet completed an activation, e.g. being migrated.
  3379. */
  3380. if (!task_sleep)
  3381. return;
  3382. /*
  3383. * If the PELT values haven't changed since enqueue time,
  3384. * skip the util_est update.
  3385. */
  3386. ue = p->se.avg.util_est;
  3387. if (ue.enqueued & UTIL_AVG_UNCHANGED)
  3388. return;
  3389. /*
  3390. * Skip update of task's estimated utilization when its EWMA is
  3391. * already ~1% close to its last activation value.
  3392. */
  3393. ue.enqueued = (task_util(p) | UTIL_AVG_UNCHANGED);
  3394. last_ewma_diff = ue.enqueued - ue.ewma;
  3395. if (within_margin(last_ewma_diff, (SCHED_CAPACITY_SCALE / 100)))
  3396. return;
  3397. /*
  3398. * Update Task's estimated utilization
  3399. *
  3400. * When *p completes an activation we can consolidate another sample
  3401. * of the task size. This is done by storing the current PELT value
  3402. * as ue.enqueued and by using this value to update the Exponential
  3403. * Weighted Moving Average (EWMA):
  3404. *
  3405. * ewma(t) = w * task_util(p) + (1-w) * ewma(t-1)
  3406. * = w * task_util(p) + ewma(t-1) - w * ewma(t-1)
  3407. * = w * (task_util(p) - ewma(t-1)) + ewma(t-1)
  3408. * = w * ( last_ewma_diff ) + ewma(t-1)
  3409. * = w * (last_ewma_diff + ewma(t-1) / w)
  3410. *
  3411. * Where 'w' is the weight of new samples, which is configured to be
  3412. * 0.25, thus making w=1/4 ( >>= UTIL_EST_WEIGHT_SHIFT)
  3413. */
  3414. ue.ewma <<= UTIL_EST_WEIGHT_SHIFT;
  3415. ue.ewma += last_ewma_diff;
  3416. ue.ewma >>= UTIL_EST_WEIGHT_SHIFT;
  3417. WRITE_ONCE(p->se.avg.util_est, ue);
  3418. }
  3419. #else /* CONFIG_SMP */
  3420. static inline int
  3421. update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq)
  3422. {
  3423. return 0;
  3424. }
  3425. #define UPDATE_TG 0x0
  3426. #define SKIP_AGE_LOAD 0x0
  3427. #define DO_ATTACH 0x0
  3428. static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int not_used1)
  3429. {
  3430. cfs_rq_util_change(cfs_rq, 0);
  3431. }
  3432. static inline void remove_entity_load_avg(struct sched_entity *se) {}
  3433. static inline void
  3434. attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) {}
  3435. static inline void
  3436. detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
  3437. static inline int idle_balance(struct rq *rq, struct rq_flags *rf)
  3438. {
  3439. return 0;
  3440. }
  3441. static inline void
  3442. util_est_enqueue(struct cfs_rq *cfs_rq, struct task_struct *p) {}
  3443. static inline void
  3444. util_est_dequeue(struct cfs_rq *cfs_rq, struct task_struct *p,
  3445. bool task_sleep) {}
  3446. #endif /* CONFIG_SMP */
  3447. static void check_spread(struct cfs_rq *cfs_rq, struct sched_entity *se)
  3448. {
  3449. #ifdef CONFIG_SCHED_DEBUG
  3450. s64 d = se->vruntime - cfs_rq->min_vruntime;
  3451. if (d < 0)
  3452. d = -d;
  3453. if (d > 3*sysctl_sched_latency)
  3454. schedstat_inc(cfs_rq->nr_spread_over);
  3455. #endif
  3456. }
  3457. static void
  3458. place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int initial)
  3459. {
  3460. u64 vruntime = cfs_rq->min_vruntime;
  3461. /*
  3462. * The 'current' period is already promised to the current tasks,
  3463. * however the extra weight of the new task will slow them down a
  3464. * little, place the new task so that it fits in the slot that
  3465. * stays open at the end.
  3466. */
  3467. if (initial && sched_feat(START_DEBIT))
  3468. vruntime += sched_vslice(cfs_rq, se);
  3469. /* sleeps up to a single latency don't count. */
  3470. if (!initial) {
  3471. unsigned long thresh = sysctl_sched_latency;
  3472. /*
  3473. * Halve their sleep time's effect, to allow
  3474. * for a gentler effect of sleepers:
  3475. */
  3476. if (sched_feat(GENTLE_FAIR_SLEEPERS))
  3477. thresh >>= 1;
  3478. vruntime -= thresh;
  3479. }
  3480. /* ensure we never gain time by being placed backwards. */
  3481. se->vruntime = max_vruntime(se->vruntime, vruntime);
  3482. }
  3483. static void check_enqueue_throttle(struct cfs_rq *cfs_rq);
  3484. static inline void check_schedstat_required(void)
  3485. {
  3486. #ifdef CONFIG_SCHEDSTATS
  3487. if (schedstat_enabled())
  3488. return;
  3489. /* Force schedstat enabled if a dependent tracepoint is active */
  3490. if (trace_sched_stat_wait_enabled() ||
  3491. trace_sched_stat_sleep_enabled() ||
  3492. trace_sched_stat_iowait_enabled() ||
  3493. trace_sched_stat_blocked_enabled() ||
  3494. trace_sched_stat_runtime_enabled()) {
  3495. printk_deferred_once("Scheduler tracepoints stat_sleep, stat_iowait, "
  3496. "stat_blocked and stat_runtime require the "
  3497. "kernel parameter schedstats=enable or "
  3498. "kernel.sched_schedstats=1\n");
  3499. }
  3500. #endif
  3501. }
  3502. /*
  3503. * MIGRATION
  3504. *
  3505. * dequeue
  3506. * update_curr()
  3507. * update_min_vruntime()
  3508. * vruntime -= min_vruntime
  3509. *
  3510. * enqueue
  3511. * update_curr()
  3512. * update_min_vruntime()
  3513. * vruntime += min_vruntime
  3514. *
  3515. * this way the vruntime transition between RQs is done when both
  3516. * min_vruntime are up-to-date.
  3517. *
  3518. * WAKEUP (remote)
  3519. *
  3520. * ->migrate_task_rq_fair() (p->state == TASK_WAKING)
  3521. * vruntime -= min_vruntime
  3522. *
  3523. * enqueue
  3524. * update_curr()
  3525. * update_min_vruntime()
  3526. * vruntime += min_vruntime
  3527. *
  3528. * this way we don't have the most up-to-date min_vruntime on the originating
  3529. * CPU and an up-to-date min_vruntime on the destination CPU.
  3530. */
  3531. static void
  3532. enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
  3533. {
  3534. bool renorm = !(flags & ENQUEUE_WAKEUP) || (flags & ENQUEUE_MIGRATED);
  3535. bool curr = cfs_rq->curr == se;
  3536. /*
  3537. * If we're the current task, we must renormalise before calling
  3538. * update_curr().
  3539. */
  3540. if (renorm && curr)
  3541. se->vruntime += cfs_rq->min_vruntime;
  3542. update_curr(cfs_rq);
  3543. /*
  3544. * Otherwise, renormalise after, such that we're placed at the current
  3545. * moment in time, instead of some random moment in the past. Being
  3546. * placed in the past could significantly boost this task to the
  3547. * fairness detriment of existing tasks.
  3548. */
  3549. if (renorm && !curr)
  3550. se->vruntime += cfs_rq->min_vruntime;
  3551. /*
  3552. * When enqueuing a sched_entity, we must:
  3553. * - Update loads to have both entity and cfs_rq synced with now.
  3554. * - Add its load to cfs_rq->runnable_avg
  3555. * - For group_entity, update its weight to reflect the new share of
  3556. * its group cfs_rq
  3557. * - Add its new weight to cfs_rq->load.weight
  3558. */
  3559. update_load_avg(cfs_rq, se, UPDATE_TG | DO_ATTACH);
  3560. update_cfs_group(se);
  3561. enqueue_runnable_load_avg(cfs_rq, se);
  3562. account_entity_enqueue(cfs_rq, se);
  3563. if (flags & ENQUEUE_WAKEUP)
  3564. place_entity(cfs_rq, se, 0);
  3565. check_schedstat_required();
  3566. update_stats_enqueue(cfs_rq, se, flags);
  3567. check_spread(cfs_rq, se);
  3568. if (!curr)
  3569. __enqueue_entity(cfs_rq, se);
  3570. se->on_rq = 1;
  3571. if (cfs_rq->nr_running == 1) {
  3572. list_add_leaf_cfs_rq(cfs_rq);
  3573. check_enqueue_throttle(cfs_rq);
  3574. }
  3575. }
  3576. static void __clear_buddies_last(struct sched_entity *se)
  3577. {
  3578. for_each_sched_entity(se) {
  3579. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  3580. if (cfs_rq->last != se)
  3581. break;
  3582. cfs_rq->last = NULL;
  3583. }
  3584. }
  3585. static void __clear_buddies_next(struct sched_entity *se)
  3586. {
  3587. for_each_sched_entity(se) {
  3588. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  3589. if (cfs_rq->next != se)
  3590. break;
  3591. cfs_rq->next = NULL;
  3592. }
  3593. }
  3594. static void __clear_buddies_skip(struct sched_entity *se)
  3595. {
  3596. for_each_sched_entity(se) {
  3597. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  3598. if (cfs_rq->skip != se)
  3599. break;
  3600. cfs_rq->skip = NULL;
  3601. }
  3602. }
  3603. static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
  3604. {
  3605. if (cfs_rq->last == se)
  3606. __clear_buddies_last(se);
  3607. if (cfs_rq->next == se)
  3608. __clear_buddies_next(se);
  3609. if (cfs_rq->skip == se)
  3610. __clear_buddies_skip(se);
  3611. }
  3612. static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq);
  3613. static void
  3614. dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
  3615. {
  3616. /*
  3617. * Update run-time statistics of the 'current'.
  3618. */
  3619. update_curr(cfs_rq);
  3620. /*
  3621. * When dequeuing a sched_entity, we must:
  3622. * - Update loads to have both entity and cfs_rq synced with now.
  3623. * - Substract its load from the cfs_rq->runnable_avg.
  3624. * - Substract its previous weight from cfs_rq->load.weight.
  3625. * - For group entity, update its weight to reflect the new share
  3626. * of its group cfs_rq.
  3627. */
  3628. update_load_avg(cfs_rq, se, UPDATE_TG);
  3629. dequeue_runnable_load_avg(cfs_rq, se);
  3630. update_stats_dequeue(cfs_rq, se, flags);
  3631. clear_buddies(cfs_rq, se);
  3632. if (se != cfs_rq->curr)
  3633. __dequeue_entity(cfs_rq, se);
  3634. se->on_rq = 0;
  3635. account_entity_dequeue(cfs_rq, se);
  3636. /*
  3637. * Normalize after update_curr(); which will also have moved
  3638. * min_vruntime if @se is the one holding it back. But before doing
  3639. * update_min_vruntime() again, which will discount @se's position and
  3640. * can move min_vruntime forward still more.
  3641. */
  3642. if (!(flags & DEQUEUE_SLEEP))
  3643. se->vruntime -= cfs_rq->min_vruntime;
  3644. /* return excess runtime on last dequeue */
  3645. return_cfs_rq_runtime(cfs_rq);
  3646. update_cfs_group(se);
  3647. /*
  3648. * Now advance min_vruntime if @se was the entity holding it back,
  3649. * except when: DEQUEUE_SAVE && !DEQUEUE_MOVE, in this case we'll be
  3650. * put back on, and if we advance min_vruntime, we'll be placed back
  3651. * further than we started -- ie. we'll be penalized.
  3652. */
  3653. if ((flags & (DEQUEUE_SAVE | DEQUEUE_MOVE)) == DEQUEUE_SAVE)
  3654. update_min_vruntime(cfs_rq);
  3655. }
  3656. /*
  3657. * Preempt the current task with a newly woken task if needed:
  3658. */
  3659. static void
  3660. check_preempt_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr)
  3661. {
  3662. unsigned long ideal_runtime, delta_exec;
  3663. struct sched_entity *se;
  3664. s64 delta;
  3665. ideal_runtime = sched_slice(cfs_rq, curr);
  3666. delta_exec = curr->sum_exec_runtime - curr->prev_sum_exec_runtime;
  3667. if (delta_exec > ideal_runtime) {
  3668. resched_curr(rq_of(cfs_rq));
  3669. /*
  3670. * The current task ran long enough, ensure it doesn't get
  3671. * re-elected due to buddy favours.
  3672. */
  3673. clear_buddies(cfs_rq, curr);
  3674. return;
  3675. }
  3676. /*
  3677. * Ensure that a task that missed wakeup preemption by a
  3678. * narrow margin doesn't have to wait for a full slice.
  3679. * This also mitigates buddy induced latencies under load.
  3680. */
  3681. if (delta_exec < sysctl_sched_min_granularity)
  3682. return;
  3683. se = __pick_first_entity(cfs_rq);
  3684. delta = curr->vruntime - se->vruntime;
  3685. if (delta < 0)
  3686. return;
  3687. if (delta > ideal_runtime)
  3688. resched_curr(rq_of(cfs_rq));
  3689. }
  3690. static void
  3691. set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
  3692. {
  3693. /* 'current' is not kept within the tree. */
  3694. if (se->on_rq) {
  3695. /*
  3696. * Any task has to be enqueued before it get to execute on
  3697. * a CPU. So account for the time it spent waiting on the
  3698. * runqueue.
  3699. */
  3700. update_stats_wait_end(cfs_rq, se);
  3701. __dequeue_entity(cfs_rq, se);
  3702. update_load_avg(cfs_rq, se, UPDATE_TG);
  3703. }
  3704. update_stats_curr_start(cfs_rq, se);
  3705. cfs_rq->curr = se;
  3706. /*
  3707. * Track our maximum slice length, if the CPU's load is at
  3708. * least twice that of our own weight (i.e. dont track it
  3709. * when there are only lesser-weight tasks around):
  3710. */
  3711. if (schedstat_enabled() && rq_of(cfs_rq)->load.weight >= 2*se->load.weight) {
  3712. schedstat_set(se->statistics.slice_max,
  3713. max((u64)schedstat_val(se->statistics.slice_max),
  3714. se->sum_exec_runtime - se->prev_sum_exec_runtime));
  3715. }
  3716. se->prev_sum_exec_runtime = se->sum_exec_runtime;
  3717. }
  3718. static int
  3719. wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se);
  3720. /*
  3721. * Pick the next process, keeping these things in mind, in this order:
  3722. * 1) keep things fair between processes/task groups
  3723. * 2) pick the "next" process, since someone really wants that to run
  3724. * 3) pick the "last" process, for cache locality
  3725. * 4) do not run the "skip" process, if something else is available
  3726. */
  3727. static struct sched_entity *
  3728. pick_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *curr)
  3729. {
  3730. struct sched_entity *left = __pick_first_entity(cfs_rq);
  3731. struct sched_entity *se;
  3732. /*
  3733. * If curr is set we have to see if its left of the leftmost entity
  3734. * still in the tree, provided there was anything in the tree at all.
  3735. */
  3736. if (!left || (curr && entity_before(curr, left)))
  3737. left = curr;
  3738. se = left; /* ideally we run the leftmost entity */
  3739. /*
  3740. * Avoid running the skip buddy, if running something else can
  3741. * be done without getting too unfair.
  3742. */
  3743. if (cfs_rq->skip == se) {
  3744. struct sched_entity *second;
  3745. if (se == curr) {
  3746. second = __pick_first_entity(cfs_rq);
  3747. } else {
  3748. second = __pick_next_entity(se);
  3749. if (!second || (curr && entity_before(curr, second)))
  3750. second = curr;
  3751. }
  3752. if (second && wakeup_preempt_entity(second, left) < 1)
  3753. se = second;
  3754. }
  3755. /*
  3756. * Prefer last buddy, try to return the CPU to a preempted task.
  3757. */
  3758. if (cfs_rq->last && wakeup_preempt_entity(cfs_rq->last, left) < 1)
  3759. se = cfs_rq->last;
  3760. /*
  3761. * Someone really wants this to run. If it's not unfair, run it.
  3762. */
  3763. if (cfs_rq->next && wakeup_preempt_entity(cfs_rq->next, left) < 1)
  3764. se = cfs_rq->next;
  3765. clear_buddies(cfs_rq, se);
  3766. return se;
  3767. }
  3768. static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq);
  3769. static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
  3770. {
  3771. /*
  3772. * If still on the runqueue then deactivate_task()
  3773. * was not called and update_curr() has to be done:
  3774. */
  3775. if (prev->on_rq)
  3776. update_curr(cfs_rq);
  3777. /* throttle cfs_rqs exceeding runtime */
  3778. check_cfs_rq_runtime(cfs_rq);
  3779. check_spread(cfs_rq, prev);
  3780. if (prev->on_rq) {
  3781. update_stats_wait_start(cfs_rq, prev);
  3782. /* Put 'current' back into the tree. */
  3783. __enqueue_entity(cfs_rq, prev);
  3784. /* in !on_rq case, update occurred at dequeue */
  3785. update_load_avg(cfs_rq, prev, 0);
  3786. }
  3787. cfs_rq->curr = NULL;
  3788. }
  3789. static void
  3790. entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
  3791. {
  3792. /*
  3793. * Update run-time statistics of the 'current'.
  3794. */
  3795. update_curr(cfs_rq);
  3796. /*
  3797. * Ensure that runnable average is periodically updated.
  3798. */
  3799. update_load_avg(cfs_rq, curr, UPDATE_TG);
  3800. update_cfs_group(curr);
  3801. #ifdef CONFIG_SCHED_HRTICK
  3802. /*
  3803. * queued ticks are scheduled to match the slice, so don't bother
  3804. * validating it and just reschedule.
  3805. */
  3806. if (queued) {
  3807. resched_curr(rq_of(cfs_rq));
  3808. return;
  3809. }
  3810. /*
  3811. * don't let the period tick interfere with the hrtick preemption
  3812. */
  3813. if (!sched_feat(DOUBLE_TICK) &&
  3814. hrtimer_active(&rq_of(cfs_rq)->hrtick_timer))
  3815. return;
  3816. #endif
  3817. if (cfs_rq->nr_running > 1)
  3818. check_preempt_tick(cfs_rq, curr);
  3819. }
  3820. /**************************************************
  3821. * CFS bandwidth control machinery
  3822. */
  3823. #ifdef CONFIG_CFS_BANDWIDTH
  3824. #ifdef HAVE_JUMP_LABEL
  3825. static struct static_key __cfs_bandwidth_used;
  3826. static inline bool cfs_bandwidth_used(void)
  3827. {
  3828. return static_key_false(&__cfs_bandwidth_used);
  3829. }
  3830. void cfs_bandwidth_usage_inc(void)
  3831. {
  3832. static_key_slow_inc_cpuslocked(&__cfs_bandwidth_used);
  3833. }
  3834. void cfs_bandwidth_usage_dec(void)
  3835. {
  3836. static_key_slow_dec_cpuslocked(&__cfs_bandwidth_used);
  3837. }
  3838. #else /* HAVE_JUMP_LABEL */
  3839. static bool cfs_bandwidth_used(void)
  3840. {
  3841. return true;
  3842. }
  3843. void cfs_bandwidth_usage_inc(void) {}
  3844. void cfs_bandwidth_usage_dec(void) {}
  3845. #endif /* HAVE_JUMP_LABEL */
  3846. /*
  3847. * default period for cfs group bandwidth.
  3848. * default: 0.1s, units: nanoseconds
  3849. */
  3850. static inline u64 default_cfs_period(void)
  3851. {
  3852. return 100000000ULL;
  3853. }
  3854. static inline u64 sched_cfs_bandwidth_slice(void)
  3855. {
  3856. return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC;
  3857. }
  3858. /*
  3859. * Replenish runtime according to assigned quota and update expiration time.
  3860. * We use sched_clock_cpu directly instead of rq->clock to avoid adding
  3861. * additional synchronization around rq->lock.
  3862. *
  3863. * requires cfs_b->lock
  3864. */
  3865. void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
  3866. {
  3867. u64 now;
  3868. if (cfs_b->quota == RUNTIME_INF)
  3869. return;
  3870. now = sched_clock_cpu(smp_processor_id());
  3871. cfs_b->runtime = cfs_b->quota;
  3872. cfs_b->runtime_expires = now + ktime_to_ns(cfs_b->period);
  3873. }
  3874. static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
  3875. {
  3876. return &tg->cfs_bandwidth;
  3877. }
  3878. /* rq->task_clock normalized against any time this cfs_rq has spent throttled */
  3879. static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq)
  3880. {
  3881. if (unlikely(cfs_rq->throttle_count))
  3882. return cfs_rq->throttled_clock_task - cfs_rq->throttled_clock_task_time;
  3883. return rq_clock_task(rq_of(cfs_rq)) - cfs_rq->throttled_clock_task_time;
  3884. }
  3885. /* returns 0 on failure to allocate runtime */
  3886. static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  3887. {
  3888. struct task_group *tg = cfs_rq->tg;
  3889. struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(tg);
  3890. u64 amount = 0, min_amount, expires;
  3891. /* note: this is a positive sum as runtime_remaining <= 0 */
  3892. min_amount = sched_cfs_bandwidth_slice() - cfs_rq->runtime_remaining;
  3893. raw_spin_lock(&cfs_b->lock);
  3894. if (cfs_b->quota == RUNTIME_INF)
  3895. amount = min_amount;
  3896. else {
  3897. start_cfs_bandwidth(cfs_b);
  3898. if (cfs_b->runtime > 0) {
  3899. amount = min(cfs_b->runtime, min_amount);
  3900. cfs_b->runtime -= amount;
  3901. cfs_b->idle = 0;
  3902. }
  3903. }
  3904. expires = cfs_b->runtime_expires;
  3905. raw_spin_unlock(&cfs_b->lock);
  3906. cfs_rq->runtime_remaining += amount;
  3907. /*
  3908. * we may have advanced our local expiration to account for allowed
  3909. * spread between our sched_clock and the one on which runtime was
  3910. * issued.
  3911. */
  3912. if ((s64)(expires - cfs_rq->runtime_expires) > 0)
  3913. cfs_rq->runtime_expires = expires;
  3914. return cfs_rq->runtime_remaining > 0;
  3915. }
  3916. /*
  3917. * Note: This depends on the synchronization provided by sched_clock and the
  3918. * fact that rq->clock snapshots this value.
  3919. */
  3920. static void expire_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  3921. {
  3922. struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
  3923. /* if the deadline is ahead of our clock, nothing to do */
  3924. if (likely((s64)(rq_clock(rq_of(cfs_rq)) - cfs_rq->runtime_expires) < 0))
  3925. return;
  3926. if (cfs_rq->runtime_remaining < 0)
  3927. return;
  3928. /*
  3929. * If the local deadline has passed we have to consider the
  3930. * possibility that our sched_clock is 'fast' and the global deadline
  3931. * has not truly expired.
  3932. *
  3933. * Fortunately we can check determine whether this the case by checking
  3934. * whether the global deadline has advanced. It is valid to compare
  3935. * cfs_b->runtime_expires without any locks since we only care about
  3936. * exact equality, so a partial write will still work.
  3937. */
  3938. if (cfs_rq->runtime_expires != cfs_b->runtime_expires) {
  3939. /* extend local deadline, drift is bounded above by 2 ticks */
  3940. cfs_rq->runtime_expires += TICK_NSEC;
  3941. } else {
  3942. /* global deadline is ahead, expiration has passed */
  3943. cfs_rq->runtime_remaining = 0;
  3944. }
  3945. }
  3946. static void __account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
  3947. {
  3948. /* dock delta_exec before expiring quota (as it could span periods) */
  3949. cfs_rq->runtime_remaining -= delta_exec;
  3950. expire_cfs_rq_runtime(cfs_rq);
  3951. if (likely(cfs_rq->runtime_remaining > 0))
  3952. return;
  3953. /*
  3954. * if we're unable to extend our runtime we resched so that the active
  3955. * hierarchy can be throttled
  3956. */
  3957. if (!assign_cfs_rq_runtime(cfs_rq) && likely(cfs_rq->curr))
  3958. resched_curr(rq_of(cfs_rq));
  3959. }
  3960. static __always_inline
  3961. void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
  3962. {
  3963. if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled)
  3964. return;
  3965. __account_cfs_rq_runtime(cfs_rq, delta_exec);
  3966. }
  3967. static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
  3968. {
  3969. return cfs_bandwidth_used() && cfs_rq->throttled;
  3970. }
  3971. /* check whether cfs_rq, or any parent, is throttled */
  3972. static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
  3973. {
  3974. return cfs_bandwidth_used() && cfs_rq->throttle_count;
  3975. }
  3976. /*
  3977. * Ensure that neither of the group entities corresponding to src_cpu or
  3978. * dest_cpu are members of a throttled hierarchy when performing group
  3979. * load-balance operations.
  3980. */
  3981. static inline int throttled_lb_pair(struct task_group *tg,
  3982. int src_cpu, int dest_cpu)
  3983. {
  3984. struct cfs_rq *src_cfs_rq, *dest_cfs_rq;
  3985. src_cfs_rq = tg->cfs_rq[src_cpu];
  3986. dest_cfs_rq = tg->cfs_rq[dest_cpu];
  3987. return throttled_hierarchy(src_cfs_rq) ||
  3988. throttled_hierarchy(dest_cfs_rq);
  3989. }
  3990. /* updated child weight may affect parent so we have to do this bottom up */
  3991. static int tg_unthrottle_up(struct task_group *tg, void *data)
  3992. {
  3993. struct rq *rq = data;
  3994. struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
  3995. cfs_rq->throttle_count--;
  3996. if (!cfs_rq->throttle_count) {
  3997. /* adjust cfs_rq_clock_task() */
  3998. cfs_rq->throttled_clock_task_time += rq_clock_task(rq) -
  3999. cfs_rq->throttled_clock_task;
  4000. }
  4001. return 0;
  4002. }
  4003. static int tg_throttle_down(struct task_group *tg, void *data)
  4004. {
  4005. struct rq *rq = data;
  4006. struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
  4007. /* group is entering throttled state, stop time */
  4008. if (!cfs_rq->throttle_count)
  4009. cfs_rq->throttled_clock_task = rq_clock_task(rq);
  4010. cfs_rq->throttle_count++;
  4011. return 0;
  4012. }
  4013. static void throttle_cfs_rq(struct cfs_rq *cfs_rq)
  4014. {
  4015. struct rq *rq = rq_of(cfs_rq);
  4016. struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
  4017. struct sched_entity *se;
  4018. long task_delta, dequeue = 1;
  4019. bool empty;
  4020. se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))];
  4021. /* freeze hierarchy runnable averages while throttled */
  4022. rcu_read_lock();
  4023. walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq);
  4024. rcu_read_unlock();
  4025. task_delta = cfs_rq->h_nr_running;
  4026. for_each_sched_entity(se) {
  4027. struct cfs_rq *qcfs_rq = cfs_rq_of(se);
  4028. /* throttled entity or throttle-on-deactivate */
  4029. if (!se->on_rq)
  4030. break;
  4031. if (dequeue)
  4032. dequeue_entity(qcfs_rq, se, DEQUEUE_SLEEP);
  4033. qcfs_rq->h_nr_running -= task_delta;
  4034. if (qcfs_rq->load.weight)
  4035. dequeue = 0;
  4036. }
  4037. if (!se)
  4038. sub_nr_running(rq, task_delta);
  4039. cfs_rq->throttled = 1;
  4040. cfs_rq->throttled_clock = rq_clock(rq);
  4041. raw_spin_lock(&cfs_b->lock);
  4042. empty = list_empty(&cfs_b->throttled_cfs_rq);
  4043. /*
  4044. * Add to the _head_ of the list, so that an already-started
  4045. * distribute_cfs_runtime will not see us
  4046. */
  4047. list_add_rcu(&cfs_rq->throttled_list, &cfs_b->throttled_cfs_rq);
  4048. /*
  4049. * If we're the first throttled task, make sure the bandwidth
  4050. * timer is running.
  4051. */
  4052. if (empty)
  4053. start_cfs_bandwidth(cfs_b);
  4054. raw_spin_unlock(&cfs_b->lock);
  4055. }
  4056. void unthrottle_cfs_rq(struct cfs_rq *cfs_rq)
  4057. {
  4058. struct rq *rq = rq_of(cfs_rq);
  4059. struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
  4060. struct sched_entity *se;
  4061. int enqueue = 1;
  4062. long task_delta;
  4063. se = cfs_rq->tg->se[cpu_of(rq)];
  4064. cfs_rq->throttled = 0;
  4065. update_rq_clock(rq);
  4066. raw_spin_lock(&cfs_b->lock);
  4067. cfs_b->throttled_time += rq_clock(rq) - cfs_rq->throttled_clock;
  4068. list_del_rcu(&cfs_rq->throttled_list);
  4069. raw_spin_unlock(&cfs_b->lock);
  4070. /* update hierarchical throttle state */
  4071. walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq);
  4072. if (!cfs_rq->load.weight)
  4073. return;
  4074. task_delta = cfs_rq->h_nr_running;
  4075. for_each_sched_entity(se) {
  4076. if (se->on_rq)
  4077. enqueue = 0;
  4078. cfs_rq = cfs_rq_of(se);
  4079. if (enqueue)
  4080. enqueue_entity(cfs_rq, se, ENQUEUE_WAKEUP);
  4081. cfs_rq->h_nr_running += task_delta;
  4082. if (cfs_rq_throttled(cfs_rq))
  4083. break;
  4084. }
  4085. if (!se)
  4086. add_nr_running(rq, task_delta);
  4087. /* Determine whether we need to wake up potentially idle CPU: */
  4088. if (rq->curr == rq->idle && rq->cfs.nr_running)
  4089. resched_curr(rq);
  4090. }
  4091. static u64 distribute_cfs_runtime(struct cfs_bandwidth *cfs_b,
  4092. u64 remaining, u64 expires)
  4093. {
  4094. struct cfs_rq *cfs_rq;
  4095. u64 runtime;
  4096. u64 starting_runtime = remaining;
  4097. rcu_read_lock();
  4098. list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
  4099. throttled_list) {
  4100. struct rq *rq = rq_of(cfs_rq);
  4101. struct rq_flags rf;
  4102. rq_lock(rq, &rf);
  4103. if (!cfs_rq_throttled(cfs_rq))
  4104. goto next;
  4105. runtime = -cfs_rq->runtime_remaining + 1;
  4106. if (runtime > remaining)
  4107. runtime = remaining;
  4108. remaining -= runtime;
  4109. cfs_rq->runtime_remaining += runtime;
  4110. cfs_rq->runtime_expires = expires;
  4111. /* we check whether we're throttled above */
  4112. if (cfs_rq->runtime_remaining > 0)
  4113. unthrottle_cfs_rq(cfs_rq);
  4114. next:
  4115. rq_unlock(rq, &rf);
  4116. if (!remaining)
  4117. break;
  4118. }
  4119. rcu_read_unlock();
  4120. return starting_runtime - remaining;
  4121. }
  4122. /*
  4123. * Responsible for refilling a task_group's bandwidth and unthrottling its
  4124. * cfs_rqs as appropriate. If there has been no activity within the last
  4125. * period the timer is deactivated until scheduling resumes; cfs_b->idle is
  4126. * used to track this state.
  4127. */
  4128. static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun)
  4129. {
  4130. u64 runtime, runtime_expires;
  4131. int throttled;
  4132. /* no need to continue the timer with no bandwidth constraint */
  4133. if (cfs_b->quota == RUNTIME_INF)
  4134. goto out_deactivate;
  4135. throttled = !list_empty(&cfs_b->throttled_cfs_rq);
  4136. cfs_b->nr_periods += overrun;
  4137. /*
  4138. * idle depends on !throttled (for the case of a large deficit), and if
  4139. * we're going inactive then everything else can be deferred
  4140. */
  4141. if (cfs_b->idle && !throttled)
  4142. goto out_deactivate;
  4143. __refill_cfs_bandwidth_runtime(cfs_b);
  4144. if (!throttled) {
  4145. /* mark as potentially idle for the upcoming period */
  4146. cfs_b->idle = 1;
  4147. return 0;
  4148. }
  4149. /* account preceding periods in which throttling occurred */
  4150. cfs_b->nr_throttled += overrun;
  4151. runtime_expires = cfs_b->runtime_expires;
  4152. /*
  4153. * This check is repeated as we are holding onto the new bandwidth while
  4154. * we unthrottle. This can potentially race with an unthrottled group
  4155. * trying to acquire new bandwidth from the global pool. This can result
  4156. * in us over-using our runtime if it is all used during this loop, but
  4157. * only by limited amounts in that extreme case.
  4158. */
  4159. while (throttled && cfs_b->runtime > 0) {
  4160. runtime = cfs_b->runtime;
  4161. raw_spin_unlock(&cfs_b->lock);
  4162. /* we can't nest cfs_b->lock while distributing bandwidth */
  4163. runtime = distribute_cfs_runtime(cfs_b, runtime,
  4164. runtime_expires);
  4165. raw_spin_lock(&cfs_b->lock);
  4166. throttled = !list_empty(&cfs_b->throttled_cfs_rq);
  4167. cfs_b->runtime -= min(runtime, cfs_b->runtime);
  4168. }
  4169. /*
  4170. * While we are ensured activity in the period following an
  4171. * unthrottle, this also covers the case in which the new bandwidth is
  4172. * insufficient to cover the existing bandwidth deficit. (Forcing the
  4173. * timer to remain active while there are any throttled entities.)
  4174. */
  4175. cfs_b->idle = 0;
  4176. return 0;
  4177. out_deactivate:
  4178. return 1;
  4179. }
  4180. /* a cfs_rq won't donate quota below this amount */
  4181. static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC;
  4182. /* minimum remaining period time to redistribute slack quota */
  4183. static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC;
  4184. /* how long we wait to gather additional slack before distributing */
  4185. static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC;
  4186. /*
  4187. * Are we near the end of the current quota period?
  4188. *
  4189. * Requires cfs_b->lock for hrtimer_expires_remaining to be safe against the
  4190. * hrtimer base being cleared by hrtimer_start. In the case of
  4191. * migrate_hrtimers, base is never cleared, so we are fine.
  4192. */
  4193. static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire)
  4194. {
  4195. struct hrtimer *refresh_timer = &cfs_b->period_timer;
  4196. u64 remaining;
  4197. /* if the call-back is running a quota refresh is already occurring */
  4198. if (hrtimer_callback_running(refresh_timer))
  4199. return 1;
  4200. /* is a quota refresh about to occur? */
  4201. remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer));
  4202. if (remaining < min_expire)
  4203. return 1;
  4204. return 0;
  4205. }
  4206. static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b)
  4207. {
  4208. u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration;
  4209. /* if there's a quota refresh soon don't bother with slack */
  4210. if (runtime_refresh_within(cfs_b, min_left))
  4211. return;
  4212. hrtimer_start(&cfs_b->slack_timer,
  4213. ns_to_ktime(cfs_bandwidth_slack_period),
  4214. HRTIMER_MODE_REL);
  4215. }
  4216. /* we know any runtime found here is valid as update_curr() precedes return */
  4217. static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  4218. {
  4219. struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
  4220. s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;
  4221. if (slack_runtime <= 0)
  4222. return;
  4223. raw_spin_lock(&cfs_b->lock);
  4224. if (cfs_b->quota != RUNTIME_INF &&
  4225. cfs_rq->runtime_expires == cfs_b->runtime_expires) {
  4226. cfs_b->runtime += slack_runtime;
  4227. /* we are under rq->lock, defer unthrottling using a timer */
  4228. if (cfs_b->runtime > sched_cfs_bandwidth_slice() &&
  4229. !list_empty(&cfs_b->throttled_cfs_rq))
  4230. start_cfs_slack_bandwidth(cfs_b);
  4231. }
  4232. raw_spin_unlock(&cfs_b->lock);
  4233. /* even if it's not valid for return we don't want to try again */
  4234. cfs_rq->runtime_remaining -= slack_runtime;
  4235. }
  4236. static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  4237. {
  4238. if (!cfs_bandwidth_used())
  4239. return;
  4240. if (!cfs_rq->runtime_enabled || cfs_rq->nr_running)
  4241. return;
  4242. __return_cfs_rq_runtime(cfs_rq);
  4243. }
  4244. /*
  4245. * This is done with a timer (instead of inline with bandwidth return) since
  4246. * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
  4247. */
  4248. static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)
  4249. {
  4250. u64 runtime = 0, slice = sched_cfs_bandwidth_slice();
  4251. u64 expires;
  4252. /* confirm we're still not at a refresh boundary */
  4253. raw_spin_lock(&cfs_b->lock);
  4254. if (runtime_refresh_within(cfs_b, min_bandwidth_expiration)) {
  4255. raw_spin_unlock(&cfs_b->lock);
  4256. return;
  4257. }
  4258. if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice)
  4259. runtime = cfs_b->runtime;
  4260. expires = cfs_b->runtime_expires;
  4261. raw_spin_unlock(&cfs_b->lock);
  4262. if (!runtime)
  4263. return;
  4264. runtime = distribute_cfs_runtime(cfs_b, runtime, expires);
  4265. raw_spin_lock(&cfs_b->lock);
  4266. if (expires == cfs_b->runtime_expires)
  4267. cfs_b->runtime -= min(runtime, cfs_b->runtime);
  4268. raw_spin_unlock(&cfs_b->lock);
  4269. }
  4270. /*
  4271. * When a group wakes up we want to make sure that its quota is not already
  4272. * expired/exceeded, otherwise it may be allowed to steal additional ticks of
  4273. * runtime as update_curr() throttling can not not trigger until it's on-rq.
  4274. */
  4275. static void check_enqueue_throttle(struct cfs_rq *cfs_rq)
  4276. {
  4277. if (!cfs_bandwidth_used())
  4278. return;
  4279. /* an active group must be handled by the update_curr()->put() path */
  4280. if (!cfs_rq->runtime_enabled || cfs_rq->curr)
  4281. return;
  4282. /* ensure the group is not already throttled */
  4283. if (cfs_rq_throttled(cfs_rq))
  4284. return;
  4285. /* update runtime allocation */
  4286. account_cfs_rq_runtime(cfs_rq, 0);
  4287. if (cfs_rq->runtime_remaining <= 0)
  4288. throttle_cfs_rq(cfs_rq);
  4289. }
  4290. static void sync_throttle(struct task_group *tg, int cpu)
  4291. {
  4292. struct cfs_rq *pcfs_rq, *cfs_rq;
  4293. if (!cfs_bandwidth_used())
  4294. return;
  4295. if (!tg->parent)
  4296. return;
  4297. cfs_rq = tg->cfs_rq[cpu];
  4298. pcfs_rq = tg->parent->cfs_rq[cpu];
  4299. cfs_rq->throttle_count = pcfs_rq->throttle_count;
  4300. cfs_rq->throttled_clock_task = rq_clock_task(cpu_rq(cpu));
  4301. }
  4302. /* conditionally throttle active cfs_rq's from put_prev_entity() */
  4303. static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  4304. {
  4305. if (!cfs_bandwidth_used())
  4306. return false;
  4307. if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0))
  4308. return false;
  4309. /*
  4310. * it's possible for a throttled entity to be forced into a running
  4311. * state (e.g. set_curr_task), in this case we're finished.
  4312. */
  4313. if (cfs_rq_throttled(cfs_rq))
  4314. return true;
  4315. throttle_cfs_rq(cfs_rq);
  4316. return true;
  4317. }
  4318. static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer)
  4319. {
  4320. struct cfs_bandwidth *cfs_b =
  4321. container_of(timer, struct cfs_bandwidth, slack_timer);
  4322. do_sched_cfs_slack_timer(cfs_b);
  4323. return HRTIMER_NORESTART;
  4324. }
  4325. static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)
  4326. {
  4327. struct cfs_bandwidth *cfs_b =
  4328. container_of(timer, struct cfs_bandwidth, period_timer);
  4329. int overrun;
  4330. int idle = 0;
  4331. raw_spin_lock(&cfs_b->lock);
  4332. for (;;) {
  4333. overrun = hrtimer_forward_now(timer, cfs_b->period);
  4334. if (!overrun)
  4335. break;
  4336. idle = do_sched_cfs_period_timer(cfs_b, overrun);
  4337. }
  4338. if (idle)
  4339. cfs_b->period_active = 0;
  4340. raw_spin_unlock(&cfs_b->lock);
  4341. return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
  4342. }
  4343. void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
  4344. {
  4345. raw_spin_lock_init(&cfs_b->lock);
  4346. cfs_b->runtime = 0;
  4347. cfs_b->quota = RUNTIME_INF;
  4348. cfs_b->period = ns_to_ktime(default_cfs_period());
  4349. INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq);
  4350. hrtimer_init(&cfs_b->period_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED);
  4351. cfs_b->period_timer.function = sched_cfs_period_timer;
  4352. hrtimer_init(&cfs_b->slack_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
  4353. cfs_b->slack_timer.function = sched_cfs_slack_timer;
  4354. }
  4355. static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
  4356. {
  4357. cfs_rq->runtime_enabled = 0;
  4358. INIT_LIST_HEAD(&cfs_rq->throttled_list);
  4359. }
  4360. void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
  4361. {
  4362. lockdep_assert_held(&cfs_b->lock);
  4363. if (!cfs_b->period_active) {
  4364. cfs_b->period_active = 1;
  4365. hrtimer_forward_now(&cfs_b->period_timer, cfs_b->period);
  4366. hrtimer_start_expires(&cfs_b->period_timer, HRTIMER_MODE_ABS_PINNED);
  4367. }
  4368. }
  4369. static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
  4370. {
  4371. /* init_cfs_bandwidth() was not called */
  4372. if (!cfs_b->throttled_cfs_rq.next)
  4373. return;
  4374. hrtimer_cancel(&cfs_b->period_timer);
  4375. hrtimer_cancel(&cfs_b->slack_timer);
  4376. }
  4377. /*
  4378. * Both these CPU hotplug callbacks race against unregister_fair_sched_group()
  4379. *
  4380. * The race is harmless, since modifying bandwidth settings of unhooked group
  4381. * bits doesn't do much.
  4382. */
  4383. /* cpu online calback */
  4384. static void __maybe_unused update_runtime_enabled(struct rq *rq)
  4385. {
  4386. struct task_group *tg;
  4387. lockdep_assert_held(&rq->lock);
  4388. rcu_read_lock();
  4389. list_for_each_entry_rcu(tg, &task_groups, list) {
  4390. struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
  4391. struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
  4392. raw_spin_lock(&cfs_b->lock);
  4393. cfs_rq->runtime_enabled = cfs_b->quota != RUNTIME_INF;
  4394. raw_spin_unlock(&cfs_b->lock);
  4395. }
  4396. rcu_read_unlock();
  4397. }
  4398. /* cpu offline callback */
  4399. static void __maybe_unused unthrottle_offline_cfs_rqs(struct rq *rq)
  4400. {
  4401. struct task_group *tg;
  4402. lockdep_assert_held(&rq->lock);
  4403. rcu_read_lock();
  4404. list_for_each_entry_rcu(tg, &task_groups, list) {
  4405. struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
  4406. if (!cfs_rq->runtime_enabled)
  4407. continue;
  4408. /*
  4409. * clock_task is not advancing so we just need to make sure
  4410. * there's some valid quota amount
  4411. */
  4412. cfs_rq->runtime_remaining = 1;
  4413. /*
  4414. * Offline rq is schedulable till CPU is completely disabled
  4415. * in take_cpu_down(), so we prevent new cfs throttling here.
  4416. */
  4417. cfs_rq->runtime_enabled = 0;
  4418. if (cfs_rq_throttled(cfs_rq))
  4419. unthrottle_cfs_rq(cfs_rq);
  4420. }
  4421. rcu_read_unlock();
  4422. }
  4423. #else /* CONFIG_CFS_BANDWIDTH */
  4424. static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq)
  4425. {
  4426. return rq_clock_task(rq_of(cfs_rq));
  4427. }
  4428. static void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) {}
  4429. static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq) { return false; }
  4430. static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {}
  4431. static inline void sync_throttle(struct task_group *tg, int cpu) {}
  4432. static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
  4433. static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
  4434. {
  4435. return 0;
  4436. }
  4437. static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
  4438. {
  4439. return 0;
  4440. }
  4441. static inline int throttled_lb_pair(struct task_group *tg,
  4442. int src_cpu, int dest_cpu)
  4443. {
  4444. return 0;
  4445. }
  4446. void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
  4447. #ifdef CONFIG_FAIR_GROUP_SCHED
  4448. static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
  4449. #endif
  4450. static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
  4451. {
  4452. return NULL;
  4453. }
  4454. static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
  4455. static inline void update_runtime_enabled(struct rq *rq) {}
  4456. static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {}
  4457. #endif /* CONFIG_CFS_BANDWIDTH */
  4458. /**************************************************
  4459. * CFS operations on tasks:
  4460. */
  4461. #ifdef CONFIG_SCHED_HRTICK
  4462. static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
  4463. {
  4464. struct sched_entity *se = &p->se;
  4465. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  4466. SCHED_WARN_ON(task_rq(p) != rq);
  4467. if (rq->cfs.h_nr_running > 1) {
  4468. u64 slice = sched_slice(cfs_rq, se);
  4469. u64 ran = se->sum_exec_runtime - se->prev_sum_exec_runtime;
  4470. s64 delta = slice - ran;
  4471. if (delta < 0) {
  4472. if (rq->curr == p)
  4473. resched_curr(rq);
  4474. return;
  4475. }
  4476. hrtick_start(rq, delta);
  4477. }
  4478. }
  4479. /*
  4480. * called from enqueue/dequeue and updates the hrtick when the
  4481. * current task is from our class and nr_running is low enough
  4482. * to matter.
  4483. */
  4484. static void hrtick_update(struct rq *rq)
  4485. {
  4486. struct task_struct *curr = rq->curr;
  4487. if (!hrtick_enabled(rq) || curr->sched_class != &fair_sched_class)
  4488. return;
  4489. if (cfs_rq_of(&curr->se)->nr_running < sched_nr_latency)
  4490. hrtick_start_fair(rq, curr);
  4491. }
  4492. #else /* !CONFIG_SCHED_HRTICK */
  4493. static inline void
  4494. hrtick_start_fair(struct rq *rq, struct task_struct *p)
  4495. {
  4496. }
  4497. static inline void hrtick_update(struct rq *rq)
  4498. {
  4499. }
  4500. #endif
  4501. /*
  4502. * The enqueue_task method is called before nr_running is
  4503. * increased. Here we update the fair scheduling stats and
  4504. * then put the task into the rbtree:
  4505. */
  4506. static void
  4507. enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
  4508. {
  4509. struct cfs_rq *cfs_rq;
  4510. struct sched_entity *se = &p->se;
  4511. /*
  4512. * The code below (indirectly) updates schedutil which looks at
  4513. * the cfs_rq utilization to select a frequency.
  4514. * Let's add the task's estimated utilization to the cfs_rq's
  4515. * estimated utilization, before we update schedutil.
  4516. */
  4517. util_est_enqueue(&rq->cfs, p);
  4518. /*
  4519. * If in_iowait is set, the code below may not trigger any cpufreq
  4520. * utilization updates, so do it here explicitly with the IOWAIT flag
  4521. * passed.
  4522. */
  4523. if (p->in_iowait)
  4524. cpufreq_update_util(rq, SCHED_CPUFREQ_IOWAIT);
  4525. for_each_sched_entity(se) {
  4526. if (se->on_rq)
  4527. break;
  4528. cfs_rq = cfs_rq_of(se);
  4529. enqueue_entity(cfs_rq, se, flags);
  4530. /*
  4531. * end evaluation on encountering a throttled cfs_rq
  4532. *
  4533. * note: in the case of encountering a throttled cfs_rq we will
  4534. * post the final h_nr_running increment below.
  4535. */
  4536. if (cfs_rq_throttled(cfs_rq))
  4537. break;
  4538. cfs_rq->h_nr_running++;
  4539. flags = ENQUEUE_WAKEUP;
  4540. }
  4541. for_each_sched_entity(se) {
  4542. cfs_rq = cfs_rq_of(se);
  4543. cfs_rq->h_nr_running++;
  4544. if (cfs_rq_throttled(cfs_rq))
  4545. break;
  4546. update_load_avg(cfs_rq, se, UPDATE_TG);
  4547. update_cfs_group(se);
  4548. }
  4549. if (!se)
  4550. add_nr_running(rq, 1);
  4551. hrtick_update(rq);
  4552. }
  4553. static void set_next_buddy(struct sched_entity *se);
  4554. /*
  4555. * The dequeue_task method is called before nr_running is
  4556. * decreased. We remove the task from the rbtree and
  4557. * update the fair scheduling stats:
  4558. */
  4559. static void dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
  4560. {
  4561. struct cfs_rq *cfs_rq;
  4562. struct sched_entity *se = &p->se;
  4563. int task_sleep = flags & DEQUEUE_SLEEP;
  4564. for_each_sched_entity(se) {
  4565. cfs_rq = cfs_rq_of(se);
  4566. dequeue_entity(cfs_rq, se, flags);
  4567. /*
  4568. * end evaluation on encountering a throttled cfs_rq
  4569. *
  4570. * note: in the case of encountering a throttled cfs_rq we will
  4571. * post the final h_nr_running decrement below.
  4572. */
  4573. if (cfs_rq_throttled(cfs_rq))
  4574. break;
  4575. cfs_rq->h_nr_running--;
  4576. /* Don't dequeue parent if it has other entities besides us */
  4577. if (cfs_rq->load.weight) {
  4578. /* Avoid re-evaluating load for this entity: */
  4579. se = parent_entity(se);
  4580. /*
  4581. * Bias pick_next to pick a task from this cfs_rq, as
  4582. * p is sleeping when it is within its sched_slice.
  4583. */
  4584. if (task_sleep && se && !throttled_hierarchy(cfs_rq))
  4585. set_next_buddy(se);
  4586. break;
  4587. }
  4588. flags |= DEQUEUE_SLEEP;
  4589. }
  4590. for_each_sched_entity(se) {
  4591. cfs_rq = cfs_rq_of(se);
  4592. cfs_rq->h_nr_running--;
  4593. if (cfs_rq_throttled(cfs_rq))
  4594. break;
  4595. update_load_avg(cfs_rq, se, UPDATE_TG);
  4596. update_cfs_group(se);
  4597. }
  4598. if (!se)
  4599. sub_nr_running(rq, 1);
  4600. util_est_dequeue(&rq->cfs, p, task_sleep);
  4601. hrtick_update(rq);
  4602. }
  4603. #ifdef CONFIG_SMP
  4604. /* Working cpumask for: load_balance, load_balance_newidle. */
  4605. DEFINE_PER_CPU(cpumask_var_t, load_balance_mask);
  4606. DEFINE_PER_CPU(cpumask_var_t, select_idle_mask);
  4607. #ifdef CONFIG_NO_HZ_COMMON
  4608. /*
  4609. * per rq 'load' arrray crap; XXX kill this.
  4610. */
  4611. /*
  4612. * The exact cpuload calculated at every tick would be:
  4613. *
  4614. * load' = (1 - 1/2^i) * load + (1/2^i) * cur_load
  4615. *
  4616. * If a CPU misses updates for n ticks (as it was idle) and update gets
  4617. * called on the n+1-th tick when CPU may be busy, then we have:
  4618. *
  4619. * load_n = (1 - 1/2^i)^n * load_0
  4620. * load_n+1 = (1 - 1/2^i) * load_n + (1/2^i) * cur_load
  4621. *
  4622. * decay_load_missed() below does efficient calculation of
  4623. *
  4624. * load' = (1 - 1/2^i)^n * load
  4625. *
  4626. * Because x^(n+m) := x^n * x^m we can decompose any x^n in power-of-2 factors.
  4627. * This allows us to precompute the above in said factors, thereby allowing the
  4628. * reduction of an arbitrary n in O(log_2 n) steps. (See also
  4629. * fixed_power_int())
  4630. *
  4631. * The calculation is approximated on a 128 point scale.
  4632. */
  4633. #define DEGRADE_SHIFT 7
  4634. static const u8 degrade_zero_ticks[CPU_LOAD_IDX_MAX] = {0, 8, 32, 64, 128};
  4635. static const u8 degrade_factor[CPU_LOAD_IDX_MAX][DEGRADE_SHIFT + 1] = {
  4636. { 0, 0, 0, 0, 0, 0, 0, 0 },
  4637. { 64, 32, 8, 0, 0, 0, 0, 0 },
  4638. { 96, 72, 40, 12, 1, 0, 0, 0 },
  4639. { 112, 98, 75, 43, 15, 1, 0, 0 },
  4640. { 120, 112, 98, 76, 45, 16, 2, 0 }
  4641. };
  4642. /*
  4643. * Update cpu_load for any missed ticks, due to tickless idle. The backlog
  4644. * would be when CPU is idle and so we just decay the old load without
  4645. * adding any new load.
  4646. */
  4647. static unsigned long
  4648. decay_load_missed(unsigned long load, unsigned long missed_updates, int idx)
  4649. {
  4650. int j = 0;
  4651. if (!missed_updates)
  4652. return load;
  4653. if (missed_updates >= degrade_zero_ticks[idx])
  4654. return 0;
  4655. if (idx == 1)
  4656. return load >> missed_updates;
  4657. while (missed_updates) {
  4658. if (missed_updates % 2)
  4659. load = (load * degrade_factor[idx][j]) >> DEGRADE_SHIFT;
  4660. missed_updates >>= 1;
  4661. j++;
  4662. }
  4663. return load;
  4664. }
  4665. static struct {
  4666. cpumask_var_t idle_cpus_mask;
  4667. atomic_t nr_cpus;
  4668. int has_blocked; /* Idle CPUS has blocked load */
  4669. unsigned long next_balance; /* in jiffy units */
  4670. unsigned long next_blocked; /* Next update of blocked load in jiffies */
  4671. } nohz ____cacheline_aligned;
  4672. #endif /* CONFIG_NO_HZ_COMMON */
  4673. /**
  4674. * __cpu_load_update - update the rq->cpu_load[] statistics
  4675. * @this_rq: The rq to update statistics for
  4676. * @this_load: The current load
  4677. * @pending_updates: The number of missed updates
  4678. *
  4679. * Update rq->cpu_load[] statistics. This function is usually called every
  4680. * scheduler tick (TICK_NSEC).
  4681. *
  4682. * This function computes a decaying average:
  4683. *
  4684. * load[i]' = (1 - 1/2^i) * load[i] + (1/2^i) * load
  4685. *
  4686. * Because of NOHZ it might not get called on every tick which gives need for
  4687. * the @pending_updates argument.
  4688. *
  4689. * load[i]_n = (1 - 1/2^i) * load[i]_n-1 + (1/2^i) * load_n-1
  4690. * = A * load[i]_n-1 + B ; A := (1 - 1/2^i), B := (1/2^i) * load
  4691. * = A * (A * load[i]_n-2 + B) + B
  4692. * = A * (A * (A * load[i]_n-3 + B) + B) + B
  4693. * = A^3 * load[i]_n-3 + (A^2 + A + 1) * B
  4694. * = A^n * load[i]_0 + (A^(n-1) + A^(n-2) + ... + 1) * B
  4695. * = A^n * load[i]_0 + ((1 - A^n) / (1 - A)) * B
  4696. * = (1 - 1/2^i)^n * (load[i]_0 - load) + load
  4697. *
  4698. * In the above we've assumed load_n := load, which is true for NOHZ_FULL as
  4699. * any change in load would have resulted in the tick being turned back on.
  4700. *
  4701. * For regular NOHZ, this reduces to:
  4702. *
  4703. * load[i]_n = (1 - 1/2^i)^n * load[i]_0
  4704. *
  4705. * see decay_load_misses(). For NOHZ_FULL we get to subtract and add the extra
  4706. * term.
  4707. */
  4708. static void cpu_load_update(struct rq *this_rq, unsigned long this_load,
  4709. unsigned long pending_updates)
  4710. {
  4711. unsigned long __maybe_unused tickless_load = this_rq->cpu_load[0];
  4712. int i, scale;
  4713. this_rq->nr_load_updates++;
  4714. /* Update our load: */
  4715. this_rq->cpu_load[0] = this_load; /* Fasttrack for idx 0 */
  4716. for (i = 1, scale = 2; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
  4717. unsigned long old_load, new_load;
  4718. /* scale is effectively 1 << i now, and >> i divides by scale */
  4719. old_load = this_rq->cpu_load[i];
  4720. #ifdef CONFIG_NO_HZ_COMMON
  4721. old_load = decay_load_missed(old_load, pending_updates - 1, i);
  4722. if (tickless_load) {
  4723. old_load -= decay_load_missed(tickless_load, pending_updates - 1, i);
  4724. /*
  4725. * old_load can never be a negative value because a
  4726. * decayed tickless_load cannot be greater than the
  4727. * original tickless_load.
  4728. */
  4729. old_load += tickless_load;
  4730. }
  4731. #endif
  4732. new_load = this_load;
  4733. /*
  4734. * Round up the averaging division if load is increasing. This
  4735. * prevents us from getting stuck on 9 if the load is 10, for
  4736. * example.
  4737. */
  4738. if (new_load > old_load)
  4739. new_load += scale - 1;
  4740. this_rq->cpu_load[i] = (old_load * (scale - 1) + new_load) >> i;
  4741. }
  4742. sched_avg_update(this_rq);
  4743. }
  4744. /* Used instead of source_load when we know the type == 0 */
  4745. static unsigned long weighted_cpuload(struct rq *rq)
  4746. {
  4747. return cfs_rq_runnable_load_avg(&rq->cfs);
  4748. }
  4749. #ifdef CONFIG_NO_HZ_COMMON
  4750. /*
  4751. * There is no sane way to deal with nohz on smp when using jiffies because the
  4752. * CPU doing the jiffies update might drift wrt the CPU doing the jiffy reading
  4753. * causing off-by-one errors in observed deltas; {0,2} instead of {1,1}.
  4754. *
  4755. * Therefore we need to avoid the delta approach from the regular tick when
  4756. * possible since that would seriously skew the load calculation. This is why we
  4757. * use cpu_load_update_periodic() for CPUs out of nohz. However we'll rely on
  4758. * jiffies deltas for updates happening while in nohz mode (idle ticks, idle
  4759. * loop exit, nohz_idle_balance, nohz full exit...)
  4760. *
  4761. * This means we might still be one tick off for nohz periods.
  4762. */
  4763. static void cpu_load_update_nohz(struct rq *this_rq,
  4764. unsigned long curr_jiffies,
  4765. unsigned long load)
  4766. {
  4767. unsigned long pending_updates;
  4768. pending_updates = curr_jiffies - this_rq->last_load_update_tick;
  4769. if (pending_updates) {
  4770. this_rq->last_load_update_tick = curr_jiffies;
  4771. /*
  4772. * In the regular NOHZ case, we were idle, this means load 0.
  4773. * In the NOHZ_FULL case, we were non-idle, we should consider
  4774. * its weighted load.
  4775. */
  4776. cpu_load_update(this_rq, load, pending_updates);
  4777. }
  4778. }
  4779. /*
  4780. * Called from nohz_idle_balance() to update the load ratings before doing the
  4781. * idle balance.
  4782. */
  4783. static void cpu_load_update_idle(struct rq *this_rq)
  4784. {
  4785. /*
  4786. * bail if there's load or we're actually up-to-date.
  4787. */
  4788. if (weighted_cpuload(this_rq))
  4789. return;
  4790. cpu_load_update_nohz(this_rq, READ_ONCE(jiffies), 0);
  4791. }
  4792. /*
  4793. * Record CPU load on nohz entry so we know the tickless load to account
  4794. * on nohz exit. cpu_load[0] happens then to be updated more frequently
  4795. * than other cpu_load[idx] but it should be fine as cpu_load readers
  4796. * shouldn't rely into synchronized cpu_load[*] updates.
  4797. */
  4798. void cpu_load_update_nohz_start(void)
  4799. {
  4800. struct rq *this_rq = this_rq();
  4801. /*
  4802. * This is all lockless but should be fine. If weighted_cpuload changes
  4803. * concurrently we'll exit nohz. And cpu_load write can race with
  4804. * cpu_load_update_idle() but both updater would be writing the same.
  4805. */
  4806. this_rq->cpu_load[0] = weighted_cpuload(this_rq);
  4807. }
  4808. /*
  4809. * Account the tickless load in the end of a nohz frame.
  4810. */
  4811. void cpu_load_update_nohz_stop(void)
  4812. {
  4813. unsigned long curr_jiffies = READ_ONCE(jiffies);
  4814. struct rq *this_rq = this_rq();
  4815. unsigned long load;
  4816. struct rq_flags rf;
  4817. if (curr_jiffies == this_rq->last_load_update_tick)
  4818. return;
  4819. load = weighted_cpuload(this_rq);
  4820. rq_lock(this_rq, &rf);
  4821. update_rq_clock(this_rq);
  4822. cpu_load_update_nohz(this_rq, curr_jiffies, load);
  4823. rq_unlock(this_rq, &rf);
  4824. }
  4825. #else /* !CONFIG_NO_HZ_COMMON */
  4826. static inline void cpu_load_update_nohz(struct rq *this_rq,
  4827. unsigned long curr_jiffies,
  4828. unsigned long load) { }
  4829. #endif /* CONFIG_NO_HZ_COMMON */
  4830. static void cpu_load_update_periodic(struct rq *this_rq, unsigned long load)
  4831. {
  4832. #ifdef CONFIG_NO_HZ_COMMON
  4833. /* See the mess around cpu_load_update_nohz(). */
  4834. this_rq->last_load_update_tick = READ_ONCE(jiffies);
  4835. #endif
  4836. cpu_load_update(this_rq, load, 1);
  4837. }
  4838. /*
  4839. * Called from scheduler_tick()
  4840. */
  4841. void cpu_load_update_active(struct rq *this_rq)
  4842. {
  4843. unsigned long load = weighted_cpuload(this_rq);
  4844. if (tick_nohz_tick_stopped())
  4845. cpu_load_update_nohz(this_rq, READ_ONCE(jiffies), load);
  4846. else
  4847. cpu_load_update_periodic(this_rq, load);
  4848. }
  4849. /*
  4850. * Return a low guess at the load of a migration-source CPU weighted
  4851. * according to the scheduling class and "nice" value.
  4852. *
  4853. * We want to under-estimate the load of migration sources, to
  4854. * balance conservatively.
  4855. */
  4856. static unsigned long source_load(int cpu, int type)
  4857. {
  4858. struct rq *rq = cpu_rq(cpu);
  4859. unsigned long total = weighted_cpuload(rq);
  4860. if (type == 0 || !sched_feat(LB_BIAS))
  4861. return total;
  4862. return min(rq->cpu_load[type-1], total);
  4863. }
  4864. /*
  4865. * Return a high guess at the load of a migration-target CPU weighted
  4866. * according to the scheduling class and "nice" value.
  4867. */
  4868. static unsigned long target_load(int cpu, int type)
  4869. {
  4870. struct rq *rq = cpu_rq(cpu);
  4871. unsigned long total = weighted_cpuload(rq);
  4872. if (type == 0 || !sched_feat(LB_BIAS))
  4873. return total;
  4874. return max(rq->cpu_load[type-1], total);
  4875. }
  4876. static unsigned long capacity_of(int cpu)
  4877. {
  4878. return cpu_rq(cpu)->cpu_capacity;
  4879. }
  4880. static unsigned long capacity_orig_of(int cpu)
  4881. {
  4882. return cpu_rq(cpu)->cpu_capacity_orig;
  4883. }
  4884. static unsigned long cpu_avg_load_per_task(int cpu)
  4885. {
  4886. struct rq *rq = cpu_rq(cpu);
  4887. unsigned long nr_running = READ_ONCE(rq->cfs.h_nr_running);
  4888. unsigned long load_avg = weighted_cpuload(rq);
  4889. if (nr_running)
  4890. return load_avg / nr_running;
  4891. return 0;
  4892. }
  4893. static void record_wakee(struct task_struct *p)
  4894. {
  4895. /*
  4896. * Only decay a single time; tasks that have less then 1 wakeup per
  4897. * jiffy will not have built up many flips.
  4898. */
  4899. if (time_after(jiffies, current->wakee_flip_decay_ts + HZ)) {
  4900. current->wakee_flips >>= 1;
  4901. current->wakee_flip_decay_ts = jiffies;
  4902. }
  4903. if (current->last_wakee != p) {
  4904. current->last_wakee = p;
  4905. current->wakee_flips++;
  4906. }
  4907. }
  4908. /*
  4909. * Detect M:N waker/wakee relationships via a switching-frequency heuristic.
  4910. *
  4911. * A waker of many should wake a different task than the one last awakened
  4912. * at a frequency roughly N times higher than one of its wakees.
  4913. *
  4914. * In order to determine whether we should let the load spread vs consolidating
  4915. * to shared cache, we look for a minimum 'flip' frequency of llc_size in one
  4916. * partner, and a factor of lls_size higher frequency in the other.
  4917. *
  4918. * With both conditions met, we can be relatively sure that the relationship is
  4919. * non-monogamous, with partner count exceeding socket size.
  4920. *
  4921. * Waker/wakee being client/server, worker/dispatcher, interrupt source or
  4922. * whatever is irrelevant, spread criteria is apparent partner count exceeds
  4923. * socket size.
  4924. */
  4925. static int wake_wide(struct task_struct *p)
  4926. {
  4927. unsigned int master = current->wakee_flips;
  4928. unsigned int slave = p->wakee_flips;
  4929. int factor = this_cpu_read(sd_llc_size);
  4930. if (master < slave)
  4931. swap(master, slave);
  4932. if (slave < factor || master < slave * factor)
  4933. return 0;
  4934. return 1;
  4935. }
  4936. /*
  4937. * The purpose of wake_affine() is to quickly determine on which CPU we can run
  4938. * soonest. For the purpose of speed we only consider the waking and previous
  4939. * CPU.
  4940. *
  4941. * wake_affine_idle() - only considers 'now', it check if the waking CPU is
  4942. * cache-affine and is (or will be) idle.
  4943. *
  4944. * wake_affine_weight() - considers the weight to reflect the average
  4945. * scheduling latency of the CPUs. This seems to work
  4946. * for the overloaded case.
  4947. */
  4948. static int
  4949. wake_affine_idle(int this_cpu, int prev_cpu, int sync)
  4950. {
  4951. /*
  4952. * If this_cpu is idle, it implies the wakeup is from interrupt
  4953. * context. Only allow the move if cache is shared. Otherwise an
  4954. * interrupt intensive workload could force all tasks onto one
  4955. * node depending on the IO topology or IRQ affinity settings.
  4956. *
  4957. * If the prev_cpu is idle and cache affine then avoid a migration.
  4958. * There is no guarantee that the cache hot data from an interrupt
  4959. * is more important than cache hot data on the prev_cpu and from
  4960. * a cpufreq perspective, it's better to have higher utilisation
  4961. * on one CPU.
  4962. */
  4963. if (available_idle_cpu(this_cpu) && cpus_share_cache(this_cpu, prev_cpu))
  4964. return available_idle_cpu(prev_cpu) ? prev_cpu : this_cpu;
  4965. if (sync && cpu_rq(this_cpu)->nr_running == 1)
  4966. return this_cpu;
  4967. return nr_cpumask_bits;
  4968. }
  4969. static int
  4970. wake_affine_weight(struct sched_domain *sd, struct task_struct *p,
  4971. int this_cpu, int prev_cpu, int sync)
  4972. {
  4973. s64 this_eff_load, prev_eff_load;
  4974. unsigned long task_load;
  4975. this_eff_load = target_load(this_cpu, sd->wake_idx);
  4976. if (sync) {
  4977. unsigned long current_load = task_h_load(current);
  4978. if (current_load > this_eff_load)
  4979. return this_cpu;
  4980. this_eff_load -= current_load;
  4981. }
  4982. task_load = task_h_load(p);
  4983. this_eff_load += task_load;
  4984. if (sched_feat(WA_BIAS))
  4985. this_eff_load *= 100;
  4986. this_eff_load *= capacity_of(prev_cpu);
  4987. prev_eff_load = source_load(prev_cpu, sd->wake_idx);
  4988. prev_eff_load -= task_load;
  4989. if (sched_feat(WA_BIAS))
  4990. prev_eff_load *= 100 + (sd->imbalance_pct - 100) / 2;
  4991. prev_eff_load *= capacity_of(this_cpu);
  4992. /*
  4993. * If sync, adjust the weight of prev_eff_load such that if
  4994. * prev_eff == this_eff that select_idle_sibling() will consider
  4995. * stacking the wakee on top of the waker if no other CPU is
  4996. * idle.
  4997. */
  4998. if (sync)
  4999. prev_eff_load += 1;
  5000. return this_eff_load < prev_eff_load ? this_cpu : nr_cpumask_bits;
  5001. }
  5002. static int wake_affine(struct sched_domain *sd, struct task_struct *p,
  5003. int this_cpu, int prev_cpu, int sync)
  5004. {
  5005. int target = nr_cpumask_bits;
  5006. if (sched_feat(WA_IDLE))
  5007. target = wake_affine_idle(this_cpu, prev_cpu, sync);
  5008. if (sched_feat(WA_WEIGHT) && target == nr_cpumask_bits)
  5009. target = wake_affine_weight(sd, p, this_cpu, prev_cpu, sync);
  5010. schedstat_inc(p->se.statistics.nr_wakeups_affine_attempts);
  5011. if (target == nr_cpumask_bits)
  5012. return prev_cpu;
  5013. schedstat_inc(sd->ttwu_move_affine);
  5014. schedstat_inc(p->se.statistics.nr_wakeups_affine);
  5015. return target;
  5016. }
  5017. static unsigned long cpu_util_wake(int cpu, struct task_struct *p);
  5018. static unsigned long capacity_spare_wake(int cpu, struct task_struct *p)
  5019. {
  5020. return max_t(long, capacity_of(cpu) - cpu_util_wake(cpu, p), 0);
  5021. }
  5022. /*
  5023. * find_idlest_group finds and returns the least busy CPU group within the
  5024. * domain.
  5025. *
  5026. * Assumes p is allowed on at least one CPU in sd.
  5027. */
  5028. static struct sched_group *
  5029. find_idlest_group(struct sched_domain *sd, struct task_struct *p,
  5030. int this_cpu, int sd_flag)
  5031. {
  5032. struct sched_group *idlest = NULL, *group = sd->groups;
  5033. struct sched_group *most_spare_sg = NULL;
  5034. unsigned long min_runnable_load = ULONG_MAX;
  5035. unsigned long this_runnable_load = ULONG_MAX;
  5036. unsigned long min_avg_load = ULONG_MAX, this_avg_load = ULONG_MAX;
  5037. unsigned long most_spare = 0, this_spare = 0;
  5038. int load_idx = sd->forkexec_idx;
  5039. int imbalance_scale = 100 + (sd->imbalance_pct-100)/2;
  5040. unsigned long imbalance = scale_load_down(NICE_0_LOAD) *
  5041. (sd->imbalance_pct-100) / 100;
  5042. if (sd_flag & SD_BALANCE_WAKE)
  5043. load_idx = sd->wake_idx;
  5044. do {
  5045. unsigned long load, avg_load, runnable_load;
  5046. unsigned long spare_cap, max_spare_cap;
  5047. int local_group;
  5048. int i;
  5049. /* Skip over this group if it has no CPUs allowed */
  5050. if (!cpumask_intersects(sched_group_span(group),
  5051. &p->cpus_allowed))
  5052. continue;
  5053. local_group = cpumask_test_cpu(this_cpu,
  5054. sched_group_span(group));
  5055. /*
  5056. * Tally up the load of all CPUs in the group and find
  5057. * the group containing the CPU with most spare capacity.
  5058. */
  5059. avg_load = 0;
  5060. runnable_load = 0;
  5061. max_spare_cap = 0;
  5062. for_each_cpu(i, sched_group_span(group)) {
  5063. /* Bias balancing toward CPUs of our domain */
  5064. if (local_group)
  5065. load = source_load(i, load_idx);
  5066. else
  5067. load = target_load(i, load_idx);
  5068. runnable_load += load;
  5069. avg_load += cfs_rq_load_avg(&cpu_rq(i)->cfs);
  5070. spare_cap = capacity_spare_wake(i, p);
  5071. if (spare_cap > max_spare_cap)
  5072. max_spare_cap = spare_cap;
  5073. }
  5074. /* Adjust by relative CPU capacity of the group */
  5075. avg_load = (avg_load * SCHED_CAPACITY_SCALE) /
  5076. group->sgc->capacity;
  5077. runnable_load = (runnable_load * SCHED_CAPACITY_SCALE) /
  5078. group->sgc->capacity;
  5079. if (local_group) {
  5080. this_runnable_load = runnable_load;
  5081. this_avg_load = avg_load;
  5082. this_spare = max_spare_cap;
  5083. } else {
  5084. if (min_runnable_load > (runnable_load + imbalance)) {
  5085. /*
  5086. * The runnable load is significantly smaller
  5087. * so we can pick this new CPU:
  5088. */
  5089. min_runnable_load = runnable_load;
  5090. min_avg_load = avg_load;
  5091. idlest = group;
  5092. } else if ((runnable_load < (min_runnable_load + imbalance)) &&
  5093. (100*min_avg_load > imbalance_scale*avg_load)) {
  5094. /*
  5095. * The runnable loads are close so take the
  5096. * blocked load into account through avg_load:
  5097. */
  5098. min_avg_load = avg_load;
  5099. idlest = group;
  5100. }
  5101. if (most_spare < max_spare_cap) {
  5102. most_spare = max_spare_cap;
  5103. most_spare_sg = group;
  5104. }
  5105. }
  5106. } while (group = group->next, group != sd->groups);
  5107. /*
  5108. * The cross-over point between using spare capacity or least load
  5109. * is too conservative for high utilization tasks on partially
  5110. * utilized systems if we require spare_capacity > task_util(p),
  5111. * so we allow for some task stuffing by using
  5112. * spare_capacity > task_util(p)/2.
  5113. *
  5114. * Spare capacity can't be used for fork because the utilization has
  5115. * not been set yet, we must first select a rq to compute the initial
  5116. * utilization.
  5117. */
  5118. if (sd_flag & SD_BALANCE_FORK)
  5119. goto skip_spare;
  5120. if (this_spare > task_util(p) / 2 &&
  5121. imbalance_scale*this_spare > 100*most_spare)
  5122. return NULL;
  5123. if (most_spare > task_util(p) / 2)
  5124. return most_spare_sg;
  5125. skip_spare:
  5126. if (!idlest)
  5127. return NULL;
  5128. /*
  5129. * When comparing groups across NUMA domains, it's possible for the
  5130. * local domain to be very lightly loaded relative to the remote
  5131. * domains but "imbalance" skews the comparison making remote CPUs
  5132. * look much more favourable. When considering cross-domain, add
  5133. * imbalance to the runnable load on the remote node and consider
  5134. * staying local.
  5135. */
  5136. if ((sd->flags & SD_NUMA) &&
  5137. min_runnable_load + imbalance >= this_runnable_load)
  5138. return NULL;
  5139. if (min_runnable_load > (this_runnable_load + imbalance))
  5140. return NULL;
  5141. if ((this_runnable_load < (min_runnable_load + imbalance)) &&
  5142. (100*this_avg_load < imbalance_scale*min_avg_load))
  5143. return NULL;
  5144. return idlest;
  5145. }
  5146. /*
  5147. * find_idlest_group_cpu - find the idlest CPU among the CPUs in the group.
  5148. */
  5149. static int
  5150. find_idlest_group_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
  5151. {
  5152. unsigned long load, min_load = ULONG_MAX;
  5153. unsigned int min_exit_latency = UINT_MAX;
  5154. u64 latest_idle_timestamp = 0;
  5155. int least_loaded_cpu = this_cpu;
  5156. int shallowest_idle_cpu = -1;
  5157. int i;
  5158. /* Check if we have any choice: */
  5159. if (group->group_weight == 1)
  5160. return cpumask_first(sched_group_span(group));
  5161. /* Traverse only the allowed CPUs */
  5162. for_each_cpu_and(i, sched_group_span(group), &p->cpus_allowed) {
  5163. if (available_idle_cpu(i)) {
  5164. struct rq *rq = cpu_rq(i);
  5165. struct cpuidle_state *idle = idle_get_state(rq);
  5166. if (idle && idle->exit_latency < min_exit_latency) {
  5167. /*
  5168. * We give priority to a CPU whose idle state
  5169. * has the smallest exit latency irrespective
  5170. * of any idle timestamp.
  5171. */
  5172. min_exit_latency = idle->exit_latency;
  5173. latest_idle_timestamp = rq->idle_stamp;
  5174. shallowest_idle_cpu = i;
  5175. } else if ((!idle || idle->exit_latency == min_exit_latency) &&
  5176. rq->idle_stamp > latest_idle_timestamp) {
  5177. /*
  5178. * If equal or no active idle state, then
  5179. * the most recently idled CPU might have
  5180. * a warmer cache.
  5181. */
  5182. latest_idle_timestamp = rq->idle_stamp;
  5183. shallowest_idle_cpu = i;
  5184. }
  5185. } else if (shallowest_idle_cpu == -1) {
  5186. load = weighted_cpuload(cpu_rq(i));
  5187. if (load < min_load) {
  5188. min_load = load;
  5189. least_loaded_cpu = i;
  5190. }
  5191. }
  5192. }
  5193. return shallowest_idle_cpu != -1 ? shallowest_idle_cpu : least_loaded_cpu;
  5194. }
  5195. static inline int find_idlest_cpu(struct sched_domain *sd, struct task_struct *p,
  5196. int cpu, int prev_cpu, int sd_flag)
  5197. {
  5198. int new_cpu = cpu;
  5199. if (!cpumask_intersects(sched_domain_span(sd), &p->cpus_allowed))
  5200. return prev_cpu;
  5201. /*
  5202. * We need task's util for capacity_spare_wake, sync it up to prev_cpu's
  5203. * last_update_time.
  5204. */
  5205. if (!(sd_flag & SD_BALANCE_FORK))
  5206. sync_entity_load_avg(&p->se);
  5207. while (sd) {
  5208. struct sched_group *group;
  5209. struct sched_domain *tmp;
  5210. int weight;
  5211. if (!(sd->flags & sd_flag)) {
  5212. sd = sd->child;
  5213. continue;
  5214. }
  5215. group = find_idlest_group(sd, p, cpu, sd_flag);
  5216. if (!group) {
  5217. sd = sd->child;
  5218. continue;
  5219. }
  5220. new_cpu = find_idlest_group_cpu(group, p, cpu);
  5221. if (new_cpu == cpu) {
  5222. /* Now try balancing at a lower domain level of 'cpu': */
  5223. sd = sd->child;
  5224. continue;
  5225. }
  5226. /* Now try balancing at a lower domain level of 'new_cpu': */
  5227. cpu = new_cpu;
  5228. weight = sd->span_weight;
  5229. sd = NULL;
  5230. for_each_domain(cpu, tmp) {
  5231. if (weight <= tmp->span_weight)
  5232. break;
  5233. if (tmp->flags & sd_flag)
  5234. sd = tmp;
  5235. }
  5236. }
  5237. return new_cpu;
  5238. }
  5239. #ifdef CONFIG_SCHED_SMT
  5240. static inline void set_idle_cores(int cpu, int val)
  5241. {
  5242. struct sched_domain_shared *sds;
  5243. sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
  5244. if (sds)
  5245. WRITE_ONCE(sds->has_idle_cores, val);
  5246. }
  5247. static inline bool test_idle_cores(int cpu, bool def)
  5248. {
  5249. struct sched_domain_shared *sds;
  5250. sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
  5251. if (sds)
  5252. return READ_ONCE(sds->has_idle_cores);
  5253. return def;
  5254. }
  5255. /*
  5256. * Scans the local SMT mask to see if the entire core is idle, and records this
  5257. * information in sd_llc_shared->has_idle_cores.
  5258. *
  5259. * Since SMT siblings share all cache levels, inspecting this limited remote
  5260. * state should be fairly cheap.
  5261. */
  5262. void __update_idle_core(struct rq *rq)
  5263. {
  5264. int core = cpu_of(rq);
  5265. int cpu;
  5266. rcu_read_lock();
  5267. if (test_idle_cores(core, true))
  5268. goto unlock;
  5269. for_each_cpu(cpu, cpu_smt_mask(core)) {
  5270. if (cpu == core)
  5271. continue;
  5272. if (!available_idle_cpu(cpu))
  5273. goto unlock;
  5274. }
  5275. set_idle_cores(core, 1);
  5276. unlock:
  5277. rcu_read_unlock();
  5278. }
  5279. /*
  5280. * Scan the entire LLC domain for idle cores; this dynamically switches off if
  5281. * there are no idle cores left in the system; tracked through
  5282. * sd_llc->shared->has_idle_cores and enabled through update_idle_core() above.
  5283. */
  5284. static int select_idle_core(struct task_struct *p, struct sched_domain *sd, int target)
  5285. {
  5286. struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_idle_mask);
  5287. int core, cpu;
  5288. if (!static_branch_likely(&sched_smt_present))
  5289. return -1;
  5290. if (!test_idle_cores(target, false))
  5291. return -1;
  5292. cpumask_and(cpus, sched_domain_span(sd), &p->cpus_allowed);
  5293. for_each_cpu_wrap(core, cpus, target) {
  5294. bool idle = true;
  5295. for_each_cpu(cpu, cpu_smt_mask(core)) {
  5296. cpumask_clear_cpu(cpu, cpus);
  5297. if (!available_idle_cpu(cpu))
  5298. idle = false;
  5299. }
  5300. if (idle)
  5301. return core;
  5302. }
  5303. /*
  5304. * Failed to find an idle core; stop looking for one.
  5305. */
  5306. set_idle_cores(target, 0);
  5307. return -1;
  5308. }
  5309. /*
  5310. * Scan the local SMT mask for idle CPUs.
  5311. */
  5312. static int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target)
  5313. {
  5314. int cpu;
  5315. if (!static_branch_likely(&sched_smt_present))
  5316. return -1;
  5317. for_each_cpu(cpu, cpu_smt_mask(target)) {
  5318. if (!cpumask_test_cpu(cpu, &p->cpus_allowed))
  5319. continue;
  5320. if (available_idle_cpu(cpu))
  5321. return cpu;
  5322. }
  5323. return -1;
  5324. }
  5325. #else /* CONFIG_SCHED_SMT */
  5326. static inline int select_idle_core(struct task_struct *p, struct sched_domain *sd, int target)
  5327. {
  5328. return -1;
  5329. }
  5330. static inline int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target)
  5331. {
  5332. return -1;
  5333. }
  5334. #endif /* CONFIG_SCHED_SMT */
  5335. /*
  5336. * Scan the LLC domain for idle CPUs; this is dynamically regulated by
  5337. * comparing the average scan cost (tracked in sd->avg_scan_cost) against the
  5338. * average idle time for this rq (as found in rq->avg_idle).
  5339. */
  5340. static int select_idle_cpu(struct task_struct *p, struct sched_domain *sd, int target)
  5341. {
  5342. struct sched_domain *this_sd;
  5343. u64 avg_cost, avg_idle;
  5344. u64 time, cost;
  5345. s64 delta;
  5346. int cpu, nr = INT_MAX;
  5347. this_sd = rcu_dereference(*this_cpu_ptr(&sd_llc));
  5348. if (!this_sd)
  5349. return -1;
  5350. /*
  5351. * Due to large variance we need a large fuzz factor; hackbench in
  5352. * particularly is sensitive here.
  5353. */
  5354. avg_idle = this_rq()->avg_idle / 512;
  5355. avg_cost = this_sd->avg_scan_cost + 1;
  5356. if (sched_feat(SIS_AVG_CPU) && avg_idle < avg_cost)
  5357. return -1;
  5358. if (sched_feat(SIS_PROP)) {
  5359. u64 span_avg = sd->span_weight * avg_idle;
  5360. if (span_avg > 4*avg_cost)
  5361. nr = div_u64(span_avg, avg_cost);
  5362. else
  5363. nr = 4;
  5364. }
  5365. time = local_clock();
  5366. for_each_cpu_wrap(cpu, sched_domain_span(sd), target) {
  5367. if (!--nr)
  5368. return -1;
  5369. if (!cpumask_test_cpu(cpu, &p->cpus_allowed))
  5370. continue;
  5371. if (available_idle_cpu(cpu))
  5372. break;
  5373. }
  5374. time = local_clock() - time;
  5375. cost = this_sd->avg_scan_cost;
  5376. delta = (s64)(time - cost) / 8;
  5377. this_sd->avg_scan_cost += delta;
  5378. return cpu;
  5379. }
  5380. /*
  5381. * Try and locate an idle core/thread in the LLC cache domain.
  5382. */
  5383. static int select_idle_sibling(struct task_struct *p, int prev, int target)
  5384. {
  5385. struct sched_domain *sd;
  5386. int i, recent_used_cpu;
  5387. if (available_idle_cpu(target))
  5388. return target;
  5389. /*
  5390. * If the previous CPU is cache affine and idle, don't be stupid:
  5391. */
  5392. if (prev != target && cpus_share_cache(prev, target) && available_idle_cpu(prev))
  5393. return prev;
  5394. /* Check a recently used CPU as a potential idle candidate: */
  5395. recent_used_cpu = p->recent_used_cpu;
  5396. if (recent_used_cpu != prev &&
  5397. recent_used_cpu != target &&
  5398. cpus_share_cache(recent_used_cpu, target) &&
  5399. available_idle_cpu(recent_used_cpu) &&
  5400. cpumask_test_cpu(p->recent_used_cpu, &p->cpus_allowed)) {
  5401. /*
  5402. * Replace recent_used_cpu with prev as it is a potential
  5403. * candidate for the next wake:
  5404. */
  5405. p->recent_used_cpu = prev;
  5406. return recent_used_cpu;
  5407. }
  5408. sd = rcu_dereference(per_cpu(sd_llc, target));
  5409. if (!sd)
  5410. return target;
  5411. i = select_idle_core(p, sd, target);
  5412. if ((unsigned)i < nr_cpumask_bits)
  5413. return i;
  5414. i = select_idle_cpu(p, sd, target);
  5415. if ((unsigned)i < nr_cpumask_bits)
  5416. return i;
  5417. i = select_idle_smt(p, sd, target);
  5418. if ((unsigned)i < nr_cpumask_bits)
  5419. return i;
  5420. return target;
  5421. }
  5422. /**
  5423. * Amount of capacity of a CPU that is (estimated to be) used by CFS tasks
  5424. * @cpu: the CPU to get the utilization of
  5425. *
  5426. * The unit of the return value must be the one of capacity so we can compare
  5427. * the utilization with the capacity of the CPU that is available for CFS task
  5428. * (ie cpu_capacity).
  5429. *
  5430. * cfs_rq.avg.util_avg is the sum of running time of runnable tasks plus the
  5431. * recent utilization of currently non-runnable tasks on a CPU. It represents
  5432. * the amount of utilization of a CPU in the range [0..capacity_orig] where
  5433. * capacity_orig is the cpu_capacity available at the highest frequency
  5434. * (arch_scale_freq_capacity()).
  5435. * The utilization of a CPU converges towards a sum equal to or less than the
  5436. * current capacity (capacity_curr <= capacity_orig) of the CPU because it is
  5437. * the running time on this CPU scaled by capacity_curr.
  5438. *
  5439. * The estimated utilization of a CPU is defined to be the maximum between its
  5440. * cfs_rq.avg.util_avg and the sum of the estimated utilization of the tasks
  5441. * currently RUNNABLE on that CPU.
  5442. * This allows to properly represent the expected utilization of a CPU which
  5443. * has just got a big task running since a long sleep period. At the same time
  5444. * however it preserves the benefits of the "blocked utilization" in
  5445. * describing the potential for other tasks waking up on the same CPU.
  5446. *
  5447. * Nevertheless, cfs_rq.avg.util_avg can be higher than capacity_curr or even
  5448. * higher than capacity_orig because of unfortunate rounding in
  5449. * cfs.avg.util_avg or just after migrating tasks and new task wakeups until
  5450. * the average stabilizes with the new running time. We need to check that the
  5451. * utilization stays within the range of [0..capacity_orig] and cap it if
  5452. * necessary. Without utilization capping, a group could be seen as overloaded
  5453. * (CPU0 utilization at 121% + CPU1 utilization at 80%) whereas CPU1 has 20% of
  5454. * available capacity. We allow utilization to overshoot capacity_curr (but not
  5455. * capacity_orig) as it useful for predicting the capacity required after task
  5456. * migrations (scheduler-driven DVFS).
  5457. *
  5458. * Return: the (estimated) utilization for the specified CPU
  5459. */
  5460. static inline unsigned long cpu_util(int cpu)
  5461. {
  5462. struct cfs_rq *cfs_rq;
  5463. unsigned int util;
  5464. cfs_rq = &cpu_rq(cpu)->cfs;
  5465. util = READ_ONCE(cfs_rq->avg.util_avg);
  5466. if (sched_feat(UTIL_EST))
  5467. util = max(util, READ_ONCE(cfs_rq->avg.util_est.enqueued));
  5468. return min_t(unsigned long, util, capacity_orig_of(cpu));
  5469. }
  5470. /*
  5471. * cpu_util_wake: Compute CPU utilization with any contributions from
  5472. * the waking task p removed.
  5473. */
  5474. static unsigned long cpu_util_wake(int cpu, struct task_struct *p)
  5475. {
  5476. struct cfs_rq *cfs_rq;
  5477. unsigned int util;
  5478. /* Task has no contribution or is new */
  5479. if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
  5480. return cpu_util(cpu);
  5481. cfs_rq = &cpu_rq(cpu)->cfs;
  5482. util = READ_ONCE(cfs_rq->avg.util_avg);
  5483. /* Discount task's blocked util from CPU's util */
  5484. util -= min_t(unsigned int, util, task_util(p));
  5485. /*
  5486. * Covered cases:
  5487. *
  5488. * a) if *p is the only task sleeping on this CPU, then:
  5489. * cpu_util (== task_util) > util_est (== 0)
  5490. * and thus we return:
  5491. * cpu_util_wake = (cpu_util - task_util) = 0
  5492. *
  5493. * b) if other tasks are SLEEPING on this CPU, which is now exiting
  5494. * IDLE, then:
  5495. * cpu_util >= task_util
  5496. * cpu_util > util_est (== 0)
  5497. * and thus we discount *p's blocked utilization to return:
  5498. * cpu_util_wake = (cpu_util - task_util) >= 0
  5499. *
  5500. * c) if other tasks are RUNNABLE on that CPU and
  5501. * util_est > cpu_util
  5502. * then we use util_est since it returns a more restrictive
  5503. * estimation of the spare capacity on that CPU, by just
  5504. * considering the expected utilization of tasks already
  5505. * runnable on that CPU.
  5506. *
  5507. * Cases a) and b) are covered by the above code, while case c) is
  5508. * covered by the following code when estimated utilization is
  5509. * enabled.
  5510. */
  5511. if (sched_feat(UTIL_EST))
  5512. util = max(util, READ_ONCE(cfs_rq->avg.util_est.enqueued));
  5513. /*
  5514. * Utilization (estimated) can exceed the CPU capacity, thus let's
  5515. * clamp to the maximum CPU capacity to ensure consistency with
  5516. * the cpu_util call.
  5517. */
  5518. return min_t(unsigned long, util, capacity_orig_of(cpu));
  5519. }
  5520. /*
  5521. * Disable WAKE_AFFINE in the case where task @p doesn't fit in the
  5522. * capacity of either the waking CPU @cpu or the previous CPU @prev_cpu.
  5523. *
  5524. * In that case WAKE_AFFINE doesn't make sense and we'll let
  5525. * BALANCE_WAKE sort things out.
  5526. */
  5527. static int wake_cap(struct task_struct *p, int cpu, int prev_cpu)
  5528. {
  5529. long min_cap, max_cap;
  5530. min_cap = min(capacity_orig_of(prev_cpu), capacity_orig_of(cpu));
  5531. max_cap = cpu_rq(cpu)->rd->max_cpu_capacity;
  5532. /* Minimum capacity is close to max, no need to abort wake_affine */
  5533. if (max_cap - min_cap < max_cap >> 3)
  5534. return 0;
  5535. /* Bring task utilization in sync with prev_cpu */
  5536. sync_entity_load_avg(&p->se);
  5537. return min_cap * 1024 < task_util(p) * capacity_margin;
  5538. }
  5539. /*
  5540. * select_task_rq_fair: Select target runqueue for the waking task in domains
  5541. * that have the 'sd_flag' flag set. In practice, this is SD_BALANCE_WAKE,
  5542. * SD_BALANCE_FORK, or SD_BALANCE_EXEC.
  5543. *
  5544. * Balances load by selecting the idlest CPU in the idlest group, or under
  5545. * certain conditions an idle sibling CPU if the domain has SD_WAKE_AFFINE set.
  5546. *
  5547. * Returns the target CPU number.
  5548. *
  5549. * preempt must be disabled.
  5550. */
  5551. static int
  5552. select_task_rq_fair(struct task_struct *p, int prev_cpu, int sd_flag, int wake_flags)
  5553. {
  5554. struct sched_domain *tmp, *sd = NULL;
  5555. int cpu = smp_processor_id();
  5556. int new_cpu = prev_cpu;
  5557. int want_affine = 0;
  5558. int sync = (wake_flags & WF_SYNC) && !(current->flags & PF_EXITING);
  5559. if (sd_flag & SD_BALANCE_WAKE) {
  5560. record_wakee(p);
  5561. want_affine = !wake_wide(p) && !wake_cap(p, cpu, prev_cpu)
  5562. && cpumask_test_cpu(cpu, &p->cpus_allowed);
  5563. }
  5564. rcu_read_lock();
  5565. for_each_domain(cpu, tmp) {
  5566. if (!(tmp->flags & SD_LOAD_BALANCE))
  5567. break;
  5568. /*
  5569. * If both 'cpu' and 'prev_cpu' are part of this domain,
  5570. * cpu is a valid SD_WAKE_AFFINE target.
  5571. */
  5572. if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
  5573. cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
  5574. if (cpu != prev_cpu)
  5575. new_cpu = wake_affine(tmp, p, cpu, prev_cpu, sync);
  5576. sd = NULL; /* Prefer wake_affine over balance flags */
  5577. break;
  5578. }
  5579. if (tmp->flags & sd_flag)
  5580. sd = tmp;
  5581. else if (!want_affine)
  5582. break;
  5583. }
  5584. if (unlikely(sd)) {
  5585. /* Slow path */
  5586. new_cpu = find_idlest_cpu(sd, p, cpu, prev_cpu, sd_flag);
  5587. } else if (sd_flag & SD_BALANCE_WAKE) { /* XXX always ? */
  5588. /* Fast path */
  5589. new_cpu = select_idle_sibling(p, prev_cpu, new_cpu);
  5590. if (want_affine)
  5591. current->recent_used_cpu = cpu;
  5592. }
  5593. rcu_read_unlock();
  5594. return new_cpu;
  5595. }
  5596. static void detach_entity_cfs_rq(struct sched_entity *se);
  5597. /*
  5598. * Called immediately before a task is migrated to a new CPU; task_cpu(p) and
  5599. * cfs_rq_of(p) references at time of call are still valid and identify the
  5600. * previous CPU. The caller guarantees p->pi_lock or task_rq(p)->lock is held.
  5601. */
  5602. static void migrate_task_rq_fair(struct task_struct *p)
  5603. {
  5604. /*
  5605. * As blocked tasks retain absolute vruntime the migration needs to
  5606. * deal with this by subtracting the old and adding the new
  5607. * min_vruntime -- the latter is done by enqueue_entity() when placing
  5608. * the task on the new runqueue.
  5609. */
  5610. if (p->state == TASK_WAKING) {
  5611. struct sched_entity *se = &p->se;
  5612. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  5613. u64 min_vruntime;
  5614. #ifndef CONFIG_64BIT
  5615. u64 min_vruntime_copy;
  5616. do {
  5617. min_vruntime_copy = cfs_rq->min_vruntime_copy;
  5618. smp_rmb();
  5619. min_vruntime = cfs_rq->min_vruntime;
  5620. } while (min_vruntime != min_vruntime_copy);
  5621. #else
  5622. min_vruntime = cfs_rq->min_vruntime;
  5623. #endif
  5624. se->vruntime -= min_vruntime;
  5625. }
  5626. if (p->on_rq == TASK_ON_RQ_MIGRATING) {
  5627. /*
  5628. * In case of TASK_ON_RQ_MIGRATING we in fact hold the 'old'
  5629. * rq->lock and can modify state directly.
  5630. */
  5631. lockdep_assert_held(&task_rq(p)->lock);
  5632. detach_entity_cfs_rq(&p->se);
  5633. } else {
  5634. /*
  5635. * We are supposed to update the task to "current" time, then
  5636. * its up to date and ready to go to new CPU/cfs_rq. But we
  5637. * have difficulty in getting what current time is, so simply
  5638. * throw away the out-of-date time. This will result in the
  5639. * wakee task is less decayed, but giving the wakee more load
  5640. * sounds not bad.
  5641. */
  5642. remove_entity_load_avg(&p->se);
  5643. }
  5644. /* Tell new CPU we are migrated */
  5645. p->se.avg.last_update_time = 0;
  5646. /* We have migrated, no longer consider this task hot */
  5647. p->se.exec_start = 0;
  5648. }
  5649. static void task_dead_fair(struct task_struct *p)
  5650. {
  5651. remove_entity_load_avg(&p->se);
  5652. }
  5653. #endif /* CONFIG_SMP */
  5654. static unsigned long wakeup_gran(struct sched_entity *se)
  5655. {
  5656. unsigned long gran = sysctl_sched_wakeup_granularity;
  5657. /*
  5658. * Since its curr running now, convert the gran from real-time
  5659. * to virtual-time in his units.
  5660. *
  5661. * By using 'se' instead of 'curr' we penalize light tasks, so
  5662. * they get preempted easier. That is, if 'se' < 'curr' then
  5663. * the resulting gran will be larger, therefore penalizing the
  5664. * lighter, if otoh 'se' > 'curr' then the resulting gran will
  5665. * be smaller, again penalizing the lighter task.
  5666. *
  5667. * This is especially important for buddies when the leftmost
  5668. * task is higher priority than the buddy.
  5669. */
  5670. return calc_delta_fair(gran, se);
  5671. }
  5672. /*
  5673. * Should 'se' preempt 'curr'.
  5674. *
  5675. * |s1
  5676. * |s2
  5677. * |s3
  5678. * g
  5679. * |<--->|c
  5680. *
  5681. * w(c, s1) = -1
  5682. * w(c, s2) = 0
  5683. * w(c, s3) = 1
  5684. *
  5685. */
  5686. static int
  5687. wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se)
  5688. {
  5689. s64 gran, vdiff = curr->vruntime - se->vruntime;
  5690. if (vdiff <= 0)
  5691. return -1;
  5692. gran = wakeup_gran(se);
  5693. if (vdiff > gran)
  5694. return 1;
  5695. return 0;
  5696. }
  5697. static void set_last_buddy(struct sched_entity *se)
  5698. {
  5699. if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE))
  5700. return;
  5701. for_each_sched_entity(se) {
  5702. if (SCHED_WARN_ON(!se->on_rq))
  5703. return;
  5704. cfs_rq_of(se)->last = se;
  5705. }
  5706. }
  5707. static void set_next_buddy(struct sched_entity *se)
  5708. {
  5709. if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE))
  5710. return;
  5711. for_each_sched_entity(se) {
  5712. if (SCHED_WARN_ON(!se->on_rq))
  5713. return;
  5714. cfs_rq_of(se)->next = se;
  5715. }
  5716. }
  5717. static void set_skip_buddy(struct sched_entity *se)
  5718. {
  5719. for_each_sched_entity(se)
  5720. cfs_rq_of(se)->skip = se;
  5721. }
  5722. /*
  5723. * Preempt the current task with a newly woken task if needed:
  5724. */
  5725. static void check_preempt_wakeup(struct rq *rq, struct task_struct *p, int wake_flags)
  5726. {
  5727. struct task_struct *curr = rq->curr;
  5728. struct sched_entity *se = &curr->se, *pse = &p->se;
  5729. struct cfs_rq *cfs_rq = task_cfs_rq(curr);
  5730. int scale = cfs_rq->nr_running >= sched_nr_latency;
  5731. int next_buddy_marked = 0;
  5732. if (unlikely(se == pse))
  5733. return;
  5734. /*
  5735. * This is possible from callers such as attach_tasks(), in which we
  5736. * unconditionally check_prempt_curr() after an enqueue (which may have
  5737. * lead to a throttle). This both saves work and prevents false
  5738. * next-buddy nomination below.
  5739. */
  5740. if (unlikely(throttled_hierarchy(cfs_rq_of(pse))))
  5741. return;
  5742. if (sched_feat(NEXT_BUDDY) && scale && !(wake_flags & WF_FORK)) {
  5743. set_next_buddy(pse);
  5744. next_buddy_marked = 1;
  5745. }
  5746. /*
  5747. * We can come here with TIF_NEED_RESCHED already set from new task
  5748. * wake up path.
  5749. *
  5750. * Note: this also catches the edge-case of curr being in a throttled
  5751. * group (e.g. via set_curr_task), since update_curr() (in the
  5752. * enqueue of curr) will have resulted in resched being set. This
  5753. * prevents us from potentially nominating it as a false LAST_BUDDY
  5754. * below.
  5755. */
  5756. if (test_tsk_need_resched(curr))
  5757. return;
  5758. /* Idle tasks are by definition preempted by non-idle tasks. */
  5759. if (unlikely(curr->policy == SCHED_IDLE) &&
  5760. likely(p->policy != SCHED_IDLE))
  5761. goto preempt;
  5762. /*
  5763. * Batch and idle tasks do not preempt non-idle tasks (their preemption
  5764. * is driven by the tick):
  5765. */
  5766. if (unlikely(p->policy != SCHED_NORMAL) || !sched_feat(WAKEUP_PREEMPTION))
  5767. return;
  5768. find_matching_se(&se, &pse);
  5769. update_curr(cfs_rq_of(se));
  5770. BUG_ON(!pse);
  5771. if (wakeup_preempt_entity(se, pse) == 1) {
  5772. /*
  5773. * Bias pick_next to pick the sched entity that is
  5774. * triggering this preemption.
  5775. */
  5776. if (!next_buddy_marked)
  5777. set_next_buddy(pse);
  5778. goto preempt;
  5779. }
  5780. return;
  5781. preempt:
  5782. resched_curr(rq);
  5783. /*
  5784. * Only set the backward buddy when the current task is still
  5785. * on the rq. This can happen when a wakeup gets interleaved
  5786. * with schedule on the ->pre_schedule() or idle_balance()
  5787. * point, either of which can * drop the rq lock.
  5788. *
  5789. * Also, during early boot the idle thread is in the fair class,
  5790. * for obvious reasons its a bad idea to schedule back to it.
  5791. */
  5792. if (unlikely(!se->on_rq || curr == rq->idle))
  5793. return;
  5794. if (sched_feat(LAST_BUDDY) && scale && entity_is_task(se))
  5795. set_last_buddy(se);
  5796. }
  5797. static struct task_struct *
  5798. pick_next_task_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
  5799. {
  5800. struct cfs_rq *cfs_rq = &rq->cfs;
  5801. struct sched_entity *se;
  5802. struct task_struct *p;
  5803. int new_tasks;
  5804. again:
  5805. if (!cfs_rq->nr_running)
  5806. goto idle;
  5807. #ifdef CONFIG_FAIR_GROUP_SCHED
  5808. if (prev->sched_class != &fair_sched_class)
  5809. goto simple;
  5810. /*
  5811. * Because of the set_next_buddy() in dequeue_task_fair() it is rather
  5812. * likely that a next task is from the same cgroup as the current.
  5813. *
  5814. * Therefore attempt to avoid putting and setting the entire cgroup
  5815. * hierarchy, only change the part that actually changes.
  5816. */
  5817. do {
  5818. struct sched_entity *curr = cfs_rq->curr;
  5819. /*
  5820. * Since we got here without doing put_prev_entity() we also
  5821. * have to consider cfs_rq->curr. If it is still a runnable
  5822. * entity, update_curr() will update its vruntime, otherwise
  5823. * forget we've ever seen it.
  5824. */
  5825. if (curr) {
  5826. if (curr->on_rq)
  5827. update_curr(cfs_rq);
  5828. else
  5829. curr = NULL;
  5830. /*
  5831. * This call to check_cfs_rq_runtime() will do the
  5832. * throttle and dequeue its entity in the parent(s).
  5833. * Therefore the nr_running test will indeed
  5834. * be correct.
  5835. */
  5836. if (unlikely(check_cfs_rq_runtime(cfs_rq))) {
  5837. cfs_rq = &rq->cfs;
  5838. if (!cfs_rq->nr_running)
  5839. goto idle;
  5840. goto simple;
  5841. }
  5842. }
  5843. se = pick_next_entity(cfs_rq, curr);
  5844. cfs_rq = group_cfs_rq(se);
  5845. } while (cfs_rq);
  5846. p = task_of(se);
  5847. /*
  5848. * Since we haven't yet done put_prev_entity and if the selected task
  5849. * is a different task than we started out with, try and touch the
  5850. * least amount of cfs_rqs.
  5851. */
  5852. if (prev != p) {
  5853. struct sched_entity *pse = &prev->se;
  5854. while (!(cfs_rq = is_same_group(se, pse))) {
  5855. int se_depth = se->depth;
  5856. int pse_depth = pse->depth;
  5857. if (se_depth <= pse_depth) {
  5858. put_prev_entity(cfs_rq_of(pse), pse);
  5859. pse = parent_entity(pse);
  5860. }
  5861. if (se_depth >= pse_depth) {
  5862. set_next_entity(cfs_rq_of(se), se);
  5863. se = parent_entity(se);
  5864. }
  5865. }
  5866. put_prev_entity(cfs_rq, pse);
  5867. set_next_entity(cfs_rq, se);
  5868. }
  5869. goto done;
  5870. simple:
  5871. #endif
  5872. put_prev_task(rq, prev);
  5873. do {
  5874. se = pick_next_entity(cfs_rq, NULL);
  5875. set_next_entity(cfs_rq, se);
  5876. cfs_rq = group_cfs_rq(se);
  5877. } while (cfs_rq);
  5878. p = task_of(se);
  5879. done: __maybe_unused;
  5880. #ifdef CONFIG_SMP
  5881. /*
  5882. * Move the next running task to the front of
  5883. * the list, so our cfs_tasks list becomes MRU
  5884. * one.
  5885. */
  5886. list_move(&p->se.group_node, &rq->cfs_tasks);
  5887. #endif
  5888. if (hrtick_enabled(rq))
  5889. hrtick_start_fair(rq, p);
  5890. return p;
  5891. idle:
  5892. new_tasks = idle_balance(rq, rf);
  5893. /*
  5894. * Because idle_balance() releases (and re-acquires) rq->lock, it is
  5895. * possible for any higher priority task to appear. In that case we
  5896. * must re-start the pick_next_entity() loop.
  5897. */
  5898. if (new_tasks < 0)
  5899. return RETRY_TASK;
  5900. if (new_tasks > 0)
  5901. goto again;
  5902. return NULL;
  5903. }
  5904. /*
  5905. * Account for a descheduled task:
  5906. */
  5907. static void put_prev_task_fair(struct rq *rq, struct task_struct *prev)
  5908. {
  5909. struct sched_entity *se = &prev->se;
  5910. struct cfs_rq *cfs_rq;
  5911. for_each_sched_entity(se) {
  5912. cfs_rq = cfs_rq_of(se);
  5913. put_prev_entity(cfs_rq, se);
  5914. }
  5915. }
  5916. /*
  5917. * sched_yield() is very simple
  5918. *
  5919. * The magic of dealing with the ->skip buddy is in pick_next_entity.
  5920. */
  5921. static void yield_task_fair(struct rq *rq)
  5922. {
  5923. struct task_struct *curr = rq->curr;
  5924. struct cfs_rq *cfs_rq = task_cfs_rq(curr);
  5925. struct sched_entity *se = &curr->se;
  5926. /*
  5927. * Are we the only task in the tree?
  5928. */
  5929. if (unlikely(rq->nr_running == 1))
  5930. return;
  5931. clear_buddies(cfs_rq, se);
  5932. if (curr->policy != SCHED_BATCH) {
  5933. update_rq_clock(rq);
  5934. /*
  5935. * Update run-time statistics of the 'current'.
  5936. */
  5937. update_curr(cfs_rq);
  5938. /*
  5939. * Tell update_rq_clock() that we've just updated,
  5940. * so we don't do microscopic update in schedule()
  5941. * and double the fastpath cost.
  5942. */
  5943. rq_clock_skip_update(rq);
  5944. }
  5945. set_skip_buddy(se);
  5946. }
  5947. static bool yield_to_task_fair(struct rq *rq, struct task_struct *p, bool preempt)
  5948. {
  5949. struct sched_entity *se = &p->se;
  5950. /* throttled hierarchies are not runnable */
  5951. if (!se->on_rq || throttled_hierarchy(cfs_rq_of(se)))
  5952. return false;
  5953. /* Tell the scheduler that we'd really like pse to run next. */
  5954. set_next_buddy(se);
  5955. yield_task_fair(rq);
  5956. return true;
  5957. }
  5958. #ifdef CONFIG_SMP
  5959. /**************************************************
  5960. * Fair scheduling class load-balancing methods.
  5961. *
  5962. * BASICS
  5963. *
  5964. * The purpose of load-balancing is to achieve the same basic fairness the
  5965. * per-CPU scheduler provides, namely provide a proportional amount of compute
  5966. * time to each task. This is expressed in the following equation:
  5967. *
  5968. * W_i,n/P_i == W_j,n/P_j for all i,j (1)
  5969. *
  5970. * Where W_i,n is the n-th weight average for CPU i. The instantaneous weight
  5971. * W_i,0 is defined as:
  5972. *
  5973. * W_i,0 = \Sum_j w_i,j (2)
  5974. *
  5975. * Where w_i,j is the weight of the j-th runnable task on CPU i. This weight
  5976. * is derived from the nice value as per sched_prio_to_weight[].
  5977. *
  5978. * The weight average is an exponential decay average of the instantaneous
  5979. * weight:
  5980. *
  5981. * W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0 (3)
  5982. *
  5983. * C_i is the compute capacity of CPU i, typically it is the
  5984. * fraction of 'recent' time available for SCHED_OTHER task execution. But it
  5985. * can also include other factors [XXX].
  5986. *
  5987. * To achieve this balance we define a measure of imbalance which follows
  5988. * directly from (1):
  5989. *
  5990. * imb_i,j = max{ avg(W/C), W_i/C_i } - min{ avg(W/C), W_j/C_j } (4)
  5991. *
  5992. * We them move tasks around to minimize the imbalance. In the continuous
  5993. * function space it is obvious this converges, in the discrete case we get
  5994. * a few fun cases generally called infeasible weight scenarios.
  5995. *
  5996. * [XXX expand on:
  5997. * - infeasible weights;
  5998. * - local vs global optima in the discrete case. ]
  5999. *
  6000. *
  6001. * SCHED DOMAINS
  6002. *
  6003. * In order to solve the imbalance equation (4), and avoid the obvious O(n^2)
  6004. * for all i,j solution, we create a tree of CPUs that follows the hardware
  6005. * topology where each level pairs two lower groups (or better). This results
  6006. * in O(log n) layers. Furthermore we reduce the number of CPUs going up the
  6007. * tree to only the first of the previous level and we decrease the frequency
  6008. * of load-balance at each level inv. proportional to the number of CPUs in
  6009. * the groups.
  6010. *
  6011. * This yields:
  6012. *
  6013. * log_2 n 1 n
  6014. * \Sum { --- * --- * 2^i } = O(n) (5)
  6015. * i = 0 2^i 2^i
  6016. * `- size of each group
  6017. * | | `- number of CPUs doing load-balance
  6018. * | `- freq
  6019. * `- sum over all levels
  6020. *
  6021. * Coupled with a limit on how many tasks we can migrate every balance pass,
  6022. * this makes (5) the runtime complexity of the balancer.
  6023. *
  6024. * An important property here is that each CPU is still (indirectly) connected
  6025. * to every other CPU in at most O(log n) steps:
  6026. *
  6027. * The adjacency matrix of the resulting graph is given by:
  6028. *
  6029. * log_2 n
  6030. * A_i,j = \Union (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1) (6)
  6031. * k = 0
  6032. *
  6033. * And you'll find that:
  6034. *
  6035. * A^(log_2 n)_i,j != 0 for all i,j (7)
  6036. *
  6037. * Showing there's indeed a path between every CPU in at most O(log n) steps.
  6038. * The task movement gives a factor of O(m), giving a convergence complexity
  6039. * of:
  6040. *
  6041. * O(nm log n), n := nr_cpus, m := nr_tasks (8)
  6042. *
  6043. *
  6044. * WORK CONSERVING
  6045. *
  6046. * In order to avoid CPUs going idle while there's still work to do, new idle
  6047. * balancing is more aggressive and has the newly idle CPU iterate up the domain
  6048. * tree itself instead of relying on other CPUs to bring it work.
  6049. *
  6050. * This adds some complexity to both (5) and (8) but it reduces the total idle
  6051. * time.
  6052. *
  6053. * [XXX more?]
  6054. *
  6055. *
  6056. * CGROUPS
  6057. *
  6058. * Cgroups make a horror show out of (2), instead of a simple sum we get:
  6059. *
  6060. * s_k,i
  6061. * W_i,0 = \Sum_j \Prod_k w_k * ----- (9)
  6062. * S_k
  6063. *
  6064. * Where
  6065. *
  6066. * s_k,i = \Sum_j w_i,j,k and S_k = \Sum_i s_k,i (10)
  6067. *
  6068. * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on CPU i.
  6069. *
  6070. * The big problem is S_k, its a global sum needed to compute a local (W_i)
  6071. * property.
  6072. *
  6073. * [XXX write more on how we solve this.. _after_ merging pjt's patches that
  6074. * rewrite all of this once again.]
  6075. */
  6076. static unsigned long __read_mostly max_load_balance_interval = HZ/10;
  6077. enum fbq_type { regular, remote, all };
  6078. #define LBF_ALL_PINNED 0x01
  6079. #define LBF_NEED_BREAK 0x02
  6080. #define LBF_DST_PINNED 0x04
  6081. #define LBF_SOME_PINNED 0x08
  6082. #define LBF_NOHZ_STATS 0x10
  6083. #define LBF_NOHZ_AGAIN 0x20
  6084. struct lb_env {
  6085. struct sched_domain *sd;
  6086. struct rq *src_rq;
  6087. int src_cpu;
  6088. int dst_cpu;
  6089. struct rq *dst_rq;
  6090. struct cpumask *dst_grpmask;
  6091. int new_dst_cpu;
  6092. enum cpu_idle_type idle;
  6093. long imbalance;
  6094. /* The set of CPUs under consideration for load-balancing */
  6095. struct cpumask *cpus;
  6096. unsigned int flags;
  6097. unsigned int loop;
  6098. unsigned int loop_break;
  6099. unsigned int loop_max;
  6100. enum fbq_type fbq_type;
  6101. struct list_head tasks;
  6102. };
  6103. /*
  6104. * Is this task likely cache-hot:
  6105. */
  6106. static int task_hot(struct task_struct *p, struct lb_env *env)
  6107. {
  6108. s64 delta;
  6109. lockdep_assert_held(&env->src_rq->lock);
  6110. if (p->sched_class != &fair_sched_class)
  6111. return 0;
  6112. if (unlikely(p->policy == SCHED_IDLE))
  6113. return 0;
  6114. /*
  6115. * Buddy candidates are cache hot:
  6116. */
  6117. if (sched_feat(CACHE_HOT_BUDDY) && env->dst_rq->nr_running &&
  6118. (&p->se == cfs_rq_of(&p->se)->next ||
  6119. &p->se == cfs_rq_of(&p->se)->last))
  6120. return 1;
  6121. if (sysctl_sched_migration_cost == -1)
  6122. return 1;
  6123. if (sysctl_sched_migration_cost == 0)
  6124. return 0;
  6125. delta = rq_clock_task(env->src_rq) - p->se.exec_start;
  6126. return delta < (s64)sysctl_sched_migration_cost;
  6127. }
  6128. #ifdef CONFIG_NUMA_BALANCING
  6129. /*
  6130. * Returns 1, if task migration degrades locality
  6131. * Returns 0, if task migration improves locality i.e migration preferred.
  6132. * Returns -1, if task migration is not affected by locality.
  6133. */
  6134. static int migrate_degrades_locality(struct task_struct *p, struct lb_env *env)
  6135. {
  6136. struct numa_group *numa_group = rcu_dereference(p->numa_group);
  6137. unsigned long src_faults, dst_faults;
  6138. int src_nid, dst_nid;
  6139. if (!static_branch_likely(&sched_numa_balancing))
  6140. return -1;
  6141. if (!p->numa_faults || !(env->sd->flags & SD_NUMA))
  6142. return -1;
  6143. src_nid = cpu_to_node(env->src_cpu);
  6144. dst_nid = cpu_to_node(env->dst_cpu);
  6145. if (src_nid == dst_nid)
  6146. return -1;
  6147. /* Migrating away from the preferred node is always bad. */
  6148. if (src_nid == p->numa_preferred_nid) {
  6149. if (env->src_rq->nr_running > env->src_rq->nr_preferred_running)
  6150. return 1;
  6151. else
  6152. return -1;
  6153. }
  6154. /* Encourage migration to the preferred node. */
  6155. if (dst_nid == p->numa_preferred_nid)
  6156. return 0;
  6157. /* Leaving a core idle is often worse than degrading locality. */
  6158. if (env->idle != CPU_NOT_IDLE)
  6159. return -1;
  6160. if (numa_group) {
  6161. src_faults = group_faults(p, src_nid);
  6162. dst_faults = group_faults(p, dst_nid);
  6163. } else {
  6164. src_faults = task_faults(p, src_nid);
  6165. dst_faults = task_faults(p, dst_nid);
  6166. }
  6167. return dst_faults < src_faults;
  6168. }
  6169. #else
  6170. static inline int migrate_degrades_locality(struct task_struct *p,
  6171. struct lb_env *env)
  6172. {
  6173. return -1;
  6174. }
  6175. #endif
  6176. /*
  6177. * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
  6178. */
  6179. static
  6180. int can_migrate_task(struct task_struct *p, struct lb_env *env)
  6181. {
  6182. int tsk_cache_hot;
  6183. lockdep_assert_held(&env->src_rq->lock);
  6184. /*
  6185. * We do not migrate tasks that are:
  6186. * 1) throttled_lb_pair, or
  6187. * 2) cannot be migrated to this CPU due to cpus_allowed, or
  6188. * 3) running (obviously), or
  6189. * 4) are cache-hot on their current CPU.
  6190. */
  6191. if (throttled_lb_pair(task_group(p), env->src_cpu, env->dst_cpu))
  6192. return 0;
  6193. if (!cpumask_test_cpu(env->dst_cpu, &p->cpus_allowed)) {
  6194. int cpu;
  6195. schedstat_inc(p->se.statistics.nr_failed_migrations_affine);
  6196. env->flags |= LBF_SOME_PINNED;
  6197. /*
  6198. * Remember if this task can be migrated to any other CPU in
  6199. * our sched_group. We may want to revisit it if we couldn't
  6200. * meet load balance goals by pulling other tasks on src_cpu.
  6201. *
  6202. * Avoid computing new_dst_cpu for NEWLY_IDLE or if we have
  6203. * already computed one in current iteration.
  6204. */
  6205. if (env->idle == CPU_NEWLY_IDLE || (env->flags & LBF_DST_PINNED))
  6206. return 0;
  6207. /* Prevent to re-select dst_cpu via env's CPUs: */
  6208. for_each_cpu_and(cpu, env->dst_grpmask, env->cpus) {
  6209. if (cpumask_test_cpu(cpu, &p->cpus_allowed)) {
  6210. env->flags |= LBF_DST_PINNED;
  6211. env->new_dst_cpu = cpu;
  6212. break;
  6213. }
  6214. }
  6215. return 0;
  6216. }
  6217. /* Record that we found atleast one task that could run on dst_cpu */
  6218. env->flags &= ~LBF_ALL_PINNED;
  6219. if (task_running(env->src_rq, p)) {
  6220. schedstat_inc(p->se.statistics.nr_failed_migrations_running);
  6221. return 0;
  6222. }
  6223. /*
  6224. * Aggressive migration if:
  6225. * 1) destination numa is preferred
  6226. * 2) task is cache cold, or
  6227. * 3) too many balance attempts have failed.
  6228. */
  6229. tsk_cache_hot = migrate_degrades_locality(p, env);
  6230. if (tsk_cache_hot == -1)
  6231. tsk_cache_hot = task_hot(p, env);
  6232. if (tsk_cache_hot <= 0 ||
  6233. env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
  6234. if (tsk_cache_hot == 1) {
  6235. schedstat_inc(env->sd->lb_hot_gained[env->idle]);
  6236. schedstat_inc(p->se.statistics.nr_forced_migrations);
  6237. }
  6238. return 1;
  6239. }
  6240. schedstat_inc(p->se.statistics.nr_failed_migrations_hot);
  6241. return 0;
  6242. }
  6243. /*
  6244. * detach_task() -- detach the task for the migration specified in env
  6245. */
  6246. static void detach_task(struct task_struct *p, struct lb_env *env)
  6247. {
  6248. lockdep_assert_held(&env->src_rq->lock);
  6249. p->on_rq = TASK_ON_RQ_MIGRATING;
  6250. deactivate_task(env->src_rq, p, DEQUEUE_NOCLOCK);
  6251. set_task_cpu(p, env->dst_cpu);
  6252. }
  6253. /*
  6254. * detach_one_task() -- tries to dequeue exactly one task from env->src_rq, as
  6255. * part of active balancing operations within "domain".
  6256. *
  6257. * Returns a task if successful and NULL otherwise.
  6258. */
  6259. static struct task_struct *detach_one_task(struct lb_env *env)
  6260. {
  6261. struct task_struct *p;
  6262. lockdep_assert_held(&env->src_rq->lock);
  6263. list_for_each_entry_reverse(p,
  6264. &env->src_rq->cfs_tasks, se.group_node) {
  6265. if (!can_migrate_task(p, env))
  6266. continue;
  6267. detach_task(p, env);
  6268. /*
  6269. * Right now, this is only the second place where
  6270. * lb_gained[env->idle] is updated (other is detach_tasks)
  6271. * so we can safely collect stats here rather than
  6272. * inside detach_tasks().
  6273. */
  6274. schedstat_inc(env->sd->lb_gained[env->idle]);
  6275. return p;
  6276. }
  6277. return NULL;
  6278. }
  6279. static const unsigned int sched_nr_migrate_break = 32;
  6280. /*
  6281. * detach_tasks() -- tries to detach up to imbalance weighted load from
  6282. * busiest_rq, as part of a balancing operation within domain "sd".
  6283. *
  6284. * Returns number of detached tasks if successful and 0 otherwise.
  6285. */
  6286. static int detach_tasks(struct lb_env *env)
  6287. {
  6288. struct list_head *tasks = &env->src_rq->cfs_tasks;
  6289. struct task_struct *p;
  6290. unsigned long load;
  6291. int detached = 0;
  6292. lockdep_assert_held(&env->src_rq->lock);
  6293. if (env->imbalance <= 0)
  6294. return 0;
  6295. while (!list_empty(tasks)) {
  6296. /*
  6297. * We don't want to steal all, otherwise we may be treated likewise,
  6298. * which could at worst lead to a livelock crash.
  6299. */
  6300. if (env->idle != CPU_NOT_IDLE && env->src_rq->nr_running <= 1)
  6301. break;
  6302. p = list_last_entry(tasks, struct task_struct, se.group_node);
  6303. env->loop++;
  6304. /* We've more or less seen every task there is, call it quits */
  6305. if (env->loop > env->loop_max)
  6306. break;
  6307. /* take a breather every nr_migrate tasks */
  6308. if (env->loop > env->loop_break) {
  6309. env->loop_break += sched_nr_migrate_break;
  6310. env->flags |= LBF_NEED_BREAK;
  6311. break;
  6312. }
  6313. if (!can_migrate_task(p, env))
  6314. goto next;
  6315. load = task_h_load(p);
  6316. if (sched_feat(LB_MIN) && load < 16 && !env->sd->nr_balance_failed)
  6317. goto next;
  6318. if ((load / 2) > env->imbalance)
  6319. goto next;
  6320. detach_task(p, env);
  6321. list_add(&p->se.group_node, &env->tasks);
  6322. detached++;
  6323. env->imbalance -= load;
  6324. #ifdef CONFIG_PREEMPT
  6325. /*
  6326. * NEWIDLE balancing is a source of latency, so preemptible
  6327. * kernels will stop after the first task is detached to minimize
  6328. * the critical section.
  6329. */
  6330. if (env->idle == CPU_NEWLY_IDLE)
  6331. break;
  6332. #endif
  6333. /*
  6334. * We only want to steal up to the prescribed amount of
  6335. * weighted load.
  6336. */
  6337. if (env->imbalance <= 0)
  6338. break;
  6339. continue;
  6340. next:
  6341. list_move(&p->se.group_node, tasks);
  6342. }
  6343. /*
  6344. * Right now, this is one of only two places we collect this stat
  6345. * so we can safely collect detach_one_task() stats here rather
  6346. * than inside detach_one_task().
  6347. */
  6348. schedstat_add(env->sd->lb_gained[env->idle], detached);
  6349. return detached;
  6350. }
  6351. /*
  6352. * attach_task() -- attach the task detached by detach_task() to its new rq.
  6353. */
  6354. static void attach_task(struct rq *rq, struct task_struct *p)
  6355. {
  6356. lockdep_assert_held(&rq->lock);
  6357. BUG_ON(task_rq(p) != rq);
  6358. activate_task(rq, p, ENQUEUE_NOCLOCK);
  6359. p->on_rq = TASK_ON_RQ_QUEUED;
  6360. check_preempt_curr(rq, p, 0);
  6361. }
  6362. /*
  6363. * attach_one_task() -- attaches the task returned from detach_one_task() to
  6364. * its new rq.
  6365. */
  6366. static void attach_one_task(struct rq *rq, struct task_struct *p)
  6367. {
  6368. struct rq_flags rf;
  6369. rq_lock(rq, &rf);
  6370. update_rq_clock(rq);
  6371. attach_task(rq, p);
  6372. rq_unlock(rq, &rf);
  6373. }
  6374. /*
  6375. * attach_tasks() -- attaches all tasks detached by detach_tasks() to their
  6376. * new rq.
  6377. */
  6378. static void attach_tasks(struct lb_env *env)
  6379. {
  6380. struct list_head *tasks = &env->tasks;
  6381. struct task_struct *p;
  6382. struct rq_flags rf;
  6383. rq_lock(env->dst_rq, &rf);
  6384. update_rq_clock(env->dst_rq);
  6385. while (!list_empty(tasks)) {
  6386. p = list_first_entry(tasks, struct task_struct, se.group_node);
  6387. list_del_init(&p->se.group_node);
  6388. attach_task(env->dst_rq, p);
  6389. }
  6390. rq_unlock(env->dst_rq, &rf);
  6391. }
  6392. static inline bool cfs_rq_has_blocked(struct cfs_rq *cfs_rq)
  6393. {
  6394. if (cfs_rq->avg.load_avg)
  6395. return true;
  6396. if (cfs_rq->avg.util_avg)
  6397. return true;
  6398. return false;
  6399. }
  6400. #ifdef CONFIG_FAIR_GROUP_SCHED
  6401. static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq)
  6402. {
  6403. if (cfs_rq->load.weight)
  6404. return false;
  6405. if (cfs_rq->avg.load_sum)
  6406. return false;
  6407. if (cfs_rq->avg.util_sum)
  6408. return false;
  6409. if (cfs_rq->avg.runnable_load_sum)
  6410. return false;
  6411. return true;
  6412. }
  6413. static void update_blocked_averages(int cpu)
  6414. {
  6415. struct rq *rq = cpu_rq(cpu);
  6416. struct cfs_rq *cfs_rq, *pos;
  6417. struct rq_flags rf;
  6418. bool done = true;
  6419. rq_lock_irqsave(rq, &rf);
  6420. update_rq_clock(rq);
  6421. /*
  6422. * Iterates the task_group tree in a bottom up fashion, see
  6423. * list_add_leaf_cfs_rq() for details.
  6424. */
  6425. for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) {
  6426. struct sched_entity *se;
  6427. /* throttled entities do not contribute to load */
  6428. if (throttled_hierarchy(cfs_rq))
  6429. continue;
  6430. if (update_cfs_rq_load_avg(cfs_rq_clock_task(cfs_rq), cfs_rq))
  6431. update_tg_load_avg(cfs_rq, 0);
  6432. /* Propagate pending load changes to the parent, if any: */
  6433. se = cfs_rq->tg->se[cpu];
  6434. if (se && !skip_blocked_update(se))
  6435. update_load_avg(cfs_rq_of(se), se, 0);
  6436. /*
  6437. * There can be a lot of idle CPU cgroups. Don't let fully
  6438. * decayed cfs_rqs linger on the list.
  6439. */
  6440. if (cfs_rq_is_decayed(cfs_rq))
  6441. list_del_leaf_cfs_rq(cfs_rq);
  6442. /* Don't need periodic decay once load/util_avg are null */
  6443. if (cfs_rq_has_blocked(cfs_rq))
  6444. done = false;
  6445. }
  6446. #ifdef CONFIG_NO_HZ_COMMON
  6447. rq->last_blocked_load_update_tick = jiffies;
  6448. if (done)
  6449. rq->has_blocked_load = 0;
  6450. #endif
  6451. rq_unlock_irqrestore(rq, &rf);
  6452. }
  6453. /*
  6454. * Compute the hierarchical load factor for cfs_rq and all its ascendants.
  6455. * This needs to be done in a top-down fashion because the load of a child
  6456. * group is a fraction of its parents load.
  6457. */
  6458. static void update_cfs_rq_h_load(struct cfs_rq *cfs_rq)
  6459. {
  6460. struct rq *rq = rq_of(cfs_rq);
  6461. struct sched_entity *se = cfs_rq->tg->se[cpu_of(rq)];
  6462. unsigned long now = jiffies;
  6463. unsigned long load;
  6464. if (cfs_rq->last_h_load_update == now)
  6465. return;
  6466. cfs_rq->h_load_next = NULL;
  6467. for_each_sched_entity(se) {
  6468. cfs_rq = cfs_rq_of(se);
  6469. cfs_rq->h_load_next = se;
  6470. if (cfs_rq->last_h_load_update == now)
  6471. break;
  6472. }
  6473. if (!se) {
  6474. cfs_rq->h_load = cfs_rq_load_avg(cfs_rq);
  6475. cfs_rq->last_h_load_update = now;
  6476. }
  6477. while ((se = cfs_rq->h_load_next) != NULL) {
  6478. load = cfs_rq->h_load;
  6479. load = div64_ul(load * se->avg.load_avg,
  6480. cfs_rq_load_avg(cfs_rq) + 1);
  6481. cfs_rq = group_cfs_rq(se);
  6482. cfs_rq->h_load = load;
  6483. cfs_rq->last_h_load_update = now;
  6484. }
  6485. }
  6486. static unsigned long task_h_load(struct task_struct *p)
  6487. {
  6488. struct cfs_rq *cfs_rq = task_cfs_rq(p);
  6489. update_cfs_rq_h_load(cfs_rq);
  6490. return div64_ul(p->se.avg.load_avg * cfs_rq->h_load,
  6491. cfs_rq_load_avg(cfs_rq) + 1);
  6492. }
  6493. #else
  6494. static inline void update_blocked_averages(int cpu)
  6495. {
  6496. struct rq *rq = cpu_rq(cpu);
  6497. struct cfs_rq *cfs_rq = &rq->cfs;
  6498. struct rq_flags rf;
  6499. rq_lock_irqsave(rq, &rf);
  6500. update_rq_clock(rq);
  6501. update_cfs_rq_load_avg(cfs_rq_clock_task(cfs_rq), cfs_rq);
  6502. #ifdef CONFIG_NO_HZ_COMMON
  6503. rq->last_blocked_load_update_tick = jiffies;
  6504. if (!cfs_rq_has_blocked(cfs_rq))
  6505. rq->has_blocked_load = 0;
  6506. #endif
  6507. rq_unlock_irqrestore(rq, &rf);
  6508. }
  6509. static unsigned long task_h_load(struct task_struct *p)
  6510. {
  6511. return p->se.avg.load_avg;
  6512. }
  6513. #endif
  6514. /********** Helpers for find_busiest_group ************************/
  6515. enum group_type {
  6516. group_other = 0,
  6517. group_imbalanced,
  6518. group_overloaded,
  6519. };
  6520. /*
  6521. * sg_lb_stats - stats of a sched_group required for load_balancing
  6522. */
  6523. struct sg_lb_stats {
  6524. unsigned long avg_load; /*Avg load across the CPUs of the group */
  6525. unsigned long group_load; /* Total load over the CPUs of the group */
  6526. unsigned long sum_weighted_load; /* Weighted load of group's tasks */
  6527. unsigned long load_per_task;
  6528. unsigned long group_capacity;
  6529. unsigned long group_util; /* Total utilization of the group */
  6530. unsigned int sum_nr_running; /* Nr tasks running in the group */
  6531. unsigned int idle_cpus;
  6532. unsigned int group_weight;
  6533. enum group_type group_type;
  6534. int group_no_capacity;
  6535. #ifdef CONFIG_NUMA_BALANCING
  6536. unsigned int nr_numa_running;
  6537. unsigned int nr_preferred_running;
  6538. #endif
  6539. };
  6540. /*
  6541. * sd_lb_stats - Structure to store the statistics of a sched_domain
  6542. * during load balancing.
  6543. */
  6544. struct sd_lb_stats {
  6545. struct sched_group *busiest; /* Busiest group in this sd */
  6546. struct sched_group *local; /* Local group in this sd */
  6547. unsigned long total_running;
  6548. unsigned long total_load; /* Total load of all groups in sd */
  6549. unsigned long total_capacity; /* Total capacity of all groups in sd */
  6550. unsigned long avg_load; /* Average load across all groups in sd */
  6551. struct sg_lb_stats busiest_stat;/* Statistics of the busiest group */
  6552. struct sg_lb_stats local_stat; /* Statistics of the local group */
  6553. };
  6554. static inline void init_sd_lb_stats(struct sd_lb_stats *sds)
  6555. {
  6556. /*
  6557. * Skimp on the clearing to avoid duplicate work. We can avoid clearing
  6558. * local_stat because update_sg_lb_stats() does a full clear/assignment.
  6559. * We must however clear busiest_stat::avg_load because
  6560. * update_sd_pick_busiest() reads this before assignment.
  6561. */
  6562. *sds = (struct sd_lb_stats){
  6563. .busiest = NULL,
  6564. .local = NULL,
  6565. .total_running = 0UL,
  6566. .total_load = 0UL,
  6567. .total_capacity = 0UL,
  6568. .busiest_stat = {
  6569. .avg_load = 0UL,
  6570. .sum_nr_running = 0,
  6571. .group_type = group_other,
  6572. },
  6573. };
  6574. }
  6575. /**
  6576. * get_sd_load_idx - Obtain the load index for a given sched domain.
  6577. * @sd: The sched_domain whose load_idx is to be obtained.
  6578. * @idle: The idle status of the CPU for whose sd load_idx is obtained.
  6579. *
  6580. * Return: The load index.
  6581. */
  6582. static inline int get_sd_load_idx(struct sched_domain *sd,
  6583. enum cpu_idle_type idle)
  6584. {
  6585. int load_idx;
  6586. switch (idle) {
  6587. case CPU_NOT_IDLE:
  6588. load_idx = sd->busy_idx;
  6589. break;
  6590. case CPU_NEWLY_IDLE:
  6591. load_idx = sd->newidle_idx;
  6592. break;
  6593. default:
  6594. load_idx = sd->idle_idx;
  6595. break;
  6596. }
  6597. return load_idx;
  6598. }
  6599. static unsigned long scale_rt_capacity(int cpu)
  6600. {
  6601. struct rq *rq = cpu_rq(cpu);
  6602. u64 total, used, age_stamp, avg;
  6603. s64 delta;
  6604. /*
  6605. * Since we're reading these variables without serialization make sure
  6606. * we read them once before doing sanity checks on them.
  6607. */
  6608. age_stamp = READ_ONCE(rq->age_stamp);
  6609. avg = READ_ONCE(rq->rt_avg);
  6610. delta = __rq_clock_broken(rq) - age_stamp;
  6611. if (unlikely(delta < 0))
  6612. delta = 0;
  6613. total = sched_avg_period() + delta;
  6614. used = div_u64(avg, total);
  6615. if (likely(used < SCHED_CAPACITY_SCALE))
  6616. return SCHED_CAPACITY_SCALE - used;
  6617. return 1;
  6618. }
  6619. static void update_cpu_capacity(struct sched_domain *sd, int cpu)
  6620. {
  6621. unsigned long capacity = arch_scale_cpu_capacity(sd, cpu);
  6622. struct sched_group *sdg = sd->groups;
  6623. cpu_rq(cpu)->cpu_capacity_orig = capacity;
  6624. capacity *= scale_rt_capacity(cpu);
  6625. capacity >>= SCHED_CAPACITY_SHIFT;
  6626. if (!capacity)
  6627. capacity = 1;
  6628. cpu_rq(cpu)->cpu_capacity = capacity;
  6629. sdg->sgc->capacity = capacity;
  6630. sdg->sgc->min_capacity = capacity;
  6631. }
  6632. void update_group_capacity(struct sched_domain *sd, int cpu)
  6633. {
  6634. struct sched_domain *child = sd->child;
  6635. struct sched_group *group, *sdg = sd->groups;
  6636. unsigned long capacity, min_capacity;
  6637. unsigned long interval;
  6638. interval = msecs_to_jiffies(sd->balance_interval);
  6639. interval = clamp(interval, 1UL, max_load_balance_interval);
  6640. sdg->sgc->next_update = jiffies + interval;
  6641. if (!child) {
  6642. update_cpu_capacity(sd, cpu);
  6643. return;
  6644. }
  6645. capacity = 0;
  6646. min_capacity = ULONG_MAX;
  6647. if (child->flags & SD_OVERLAP) {
  6648. /*
  6649. * SD_OVERLAP domains cannot assume that child groups
  6650. * span the current group.
  6651. */
  6652. for_each_cpu(cpu, sched_group_span(sdg)) {
  6653. struct sched_group_capacity *sgc;
  6654. struct rq *rq = cpu_rq(cpu);
  6655. /*
  6656. * build_sched_domains() -> init_sched_groups_capacity()
  6657. * gets here before we've attached the domains to the
  6658. * runqueues.
  6659. *
  6660. * Use capacity_of(), which is set irrespective of domains
  6661. * in update_cpu_capacity().
  6662. *
  6663. * This avoids capacity from being 0 and
  6664. * causing divide-by-zero issues on boot.
  6665. */
  6666. if (unlikely(!rq->sd)) {
  6667. capacity += capacity_of(cpu);
  6668. } else {
  6669. sgc = rq->sd->groups->sgc;
  6670. capacity += sgc->capacity;
  6671. }
  6672. min_capacity = min(capacity, min_capacity);
  6673. }
  6674. } else {
  6675. /*
  6676. * !SD_OVERLAP domains can assume that child groups
  6677. * span the current group.
  6678. */
  6679. group = child->groups;
  6680. do {
  6681. struct sched_group_capacity *sgc = group->sgc;
  6682. capacity += sgc->capacity;
  6683. min_capacity = min(sgc->min_capacity, min_capacity);
  6684. group = group->next;
  6685. } while (group != child->groups);
  6686. }
  6687. sdg->sgc->capacity = capacity;
  6688. sdg->sgc->min_capacity = min_capacity;
  6689. }
  6690. /*
  6691. * Check whether the capacity of the rq has been noticeably reduced by side
  6692. * activity. The imbalance_pct is used for the threshold.
  6693. * Return true is the capacity is reduced
  6694. */
  6695. static inline int
  6696. check_cpu_capacity(struct rq *rq, struct sched_domain *sd)
  6697. {
  6698. return ((rq->cpu_capacity * sd->imbalance_pct) <
  6699. (rq->cpu_capacity_orig * 100));
  6700. }
  6701. /*
  6702. * Group imbalance indicates (and tries to solve) the problem where balancing
  6703. * groups is inadequate due to ->cpus_allowed constraints.
  6704. *
  6705. * Imagine a situation of two groups of 4 CPUs each and 4 tasks each with a
  6706. * cpumask covering 1 CPU of the first group and 3 CPUs of the second group.
  6707. * Something like:
  6708. *
  6709. * { 0 1 2 3 } { 4 5 6 7 }
  6710. * * * * *
  6711. *
  6712. * If we were to balance group-wise we'd place two tasks in the first group and
  6713. * two tasks in the second group. Clearly this is undesired as it will overload
  6714. * cpu 3 and leave one of the CPUs in the second group unused.
  6715. *
  6716. * The current solution to this issue is detecting the skew in the first group
  6717. * by noticing the lower domain failed to reach balance and had difficulty
  6718. * moving tasks due to affinity constraints.
  6719. *
  6720. * When this is so detected; this group becomes a candidate for busiest; see
  6721. * update_sd_pick_busiest(). And calculate_imbalance() and
  6722. * find_busiest_group() avoid some of the usual balance conditions to allow it
  6723. * to create an effective group imbalance.
  6724. *
  6725. * This is a somewhat tricky proposition since the next run might not find the
  6726. * group imbalance and decide the groups need to be balanced again. A most
  6727. * subtle and fragile situation.
  6728. */
  6729. static inline int sg_imbalanced(struct sched_group *group)
  6730. {
  6731. return group->sgc->imbalance;
  6732. }
  6733. /*
  6734. * group_has_capacity returns true if the group has spare capacity that could
  6735. * be used by some tasks.
  6736. * We consider that a group has spare capacity if the * number of task is
  6737. * smaller than the number of CPUs or if the utilization is lower than the
  6738. * available capacity for CFS tasks.
  6739. * For the latter, we use a threshold to stabilize the state, to take into
  6740. * account the variance of the tasks' load and to return true if the available
  6741. * capacity in meaningful for the load balancer.
  6742. * As an example, an available capacity of 1% can appear but it doesn't make
  6743. * any benefit for the load balance.
  6744. */
  6745. static inline bool
  6746. group_has_capacity(struct lb_env *env, struct sg_lb_stats *sgs)
  6747. {
  6748. if (sgs->sum_nr_running < sgs->group_weight)
  6749. return true;
  6750. if ((sgs->group_capacity * 100) >
  6751. (sgs->group_util * env->sd->imbalance_pct))
  6752. return true;
  6753. return false;
  6754. }
  6755. /*
  6756. * group_is_overloaded returns true if the group has more tasks than it can
  6757. * handle.
  6758. * group_is_overloaded is not equals to !group_has_capacity because a group
  6759. * with the exact right number of tasks, has no more spare capacity but is not
  6760. * overloaded so both group_has_capacity and group_is_overloaded return
  6761. * false.
  6762. */
  6763. static inline bool
  6764. group_is_overloaded(struct lb_env *env, struct sg_lb_stats *sgs)
  6765. {
  6766. if (sgs->sum_nr_running <= sgs->group_weight)
  6767. return false;
  6768. if ((sgs->group_capacity * 100) <
  6769. (sgs->group_util * env->sd->imbalance_pct))
  6770. return true;
  6771. return false;
  6772. }
  6773. /*
  6774. * group_smaller_cpu_capacity: Returns true if sched_group sg has smaller
  6775. * per-CPU capacity than sched_group ref.
  6776. */
  6777. static inline bool
  6778. group_smaller_cpu_capacity(struct sched_group *sg, struct sched_group *ref)
  6779. {
  6780. return sg->sgc->min_capacity * capacity_margin <
  6781. ref->sgc->min_capacity * 1024;
  6782. }
  6783. static inline enum
  6784. group_type group_classify(struct sched_group *group,
  6785. struct sg_lb_stats *sgs)
  6786. {
  6787. if (sgs->group_no_capacity)
  6788. return group_overloaded;
  6789. if (sg_imbalanced(group))
  6790. return group_imbalanced;
  6791. return group_other;
  6792. }
  6793. static bool update_nohz_stats(struct rq *rq, bool force)
  6794. {
  6795. #ifdef CONFIG_NO_HZ_COMMON
  6796. unsigned int cpu = rq->cpu;
  6797. if (!rq->has_blocked_load)
  6798. return false;
  6799. if (!cpumask_test_cpu(cpu, nohz.idle_cpus_mask))
  6800. return false;
  6801. if (!force && !time_after(jiffies, rq->last_blocked_load_update_tick))
  6802. return true;
  6803. update_blocked_averages(cpu);
  6804. return rq->has_blocked_load;
  6805. #else
  6806. return false;
  6807. #endif
  6808. }
  6809. /**
  6810. * update_sg_lb_stats - Update sched_group's statistics for load balancing.
  6811. * @env: The load balancing environment.
  6812. * @group: sched_group whose statistics are to be updated.
  6813. * @load_idx: Load index of sched_domain of this_cpu for load calc.
  6814. * @local_group: Does group contain this_cpu.
  6815. * @sgs: variable to hold the statistics for this group.
  6816. * @overload: Indicate more than one runnable task for any CPU.
  6817. */
  6818. static inline void update_sg_lb_stats(struct lb_env *env,
  6819. struct sched_group *group, int load_idx,
  6820. int local_group, struct sg_lb_stats *sgs,
  6821. bool *overload)
  6822. {
  6823. unsigned long load;
  6824. int i, nr_running;
  6825. memset(sgs, 0, sizeof(*sgs));
  6826. for_each_cpu_and(i, sched_group_span(group), env->cpus) {
  6827. struct rq *rq = cpu_rq(i);
  6828. if ((env->flags & LBF_NOHZ_STATS) && update_nohz_stats(rq, false))
  6829. env->flags |= LBF_NOHZ_AGAIN;
  6830. /* Bias balancing toward CPUs of our domain: */
  6831. if (local_group)
  6832. load = target_load(i, load_idx);
  6833. else
  6834. load = source_load(i, load_idx);
  6835. sgs->group_load += load;
  6836. sgs->group_util += cpu_util(i);
  6837. sgs->sum_nr_running += rq->cfs.h_nr_running;
  6838. nr_running = rq->nr_running;
  6839. if (nr_running > 1)
  6840. *overload = true;
  6841. #ifdef CONFIG_NUMA_BALANCING
  6842. sgs->nr_numa_running += rq->nr_numa_running;
  6843. sgs->nr_preferred_running += rq->nr_preferred_running;
  6844. #endif
  6845. sgs->sum_weighted_load += weighted_cpuload(rq);
  6846. /*
  6847. * No need to call idle_cpu() if nr_running is not 0
  6848. */
  6849. if (!nr_running && idle_cpu(i))
  6850. sgs->idle_cpus++;
  6851. }
  6852. /* Adjust by relative CPU capacity of the group */
  6853. sgs->group_capacity = group->sgc->capacity;
  6854. sgs->avg_load = (sgs->group_load*SCHED_CAPACITY_SCALE) / sgs->group_capacity;
  6855. if (sgs->sum_nr_running)
  6856. sgs->load_per_task = sgs->sum_weighted_load / sgs->sum_nr_running;
  6857. sgs->group_weight = group->group_weight;
  6858. sgs->group_no_capacity = group_is_overloaded(env, sgs);
  6859. sgs->group_type = group_classify(group, sgs);
  6860. }
  6861. /**
  6862. * update_sd_pick_busiest - return 1 on busiest group
  6863. * @env: The load balancing environment.
  6864. * @sds: sched_domain statistics
  6865. * @sg: sched_group candidate to be checked for being the busiest
  6866. * @sgs: sched_group statistics
  6867. *
  6868. * Determine if @sg is a busier group than the previously selected
  6869. * busiest group.
  6870. *
  6871. * Return: %true if @sg is a busier group than the previously selected
  6872. * busiest group. %false otherwise.
  6873. */
  6874. static bool update_sd_pick_busiest(struct lb_env *env,
  6875. struct sd_lb_stats *sds,
  6876. struct sched_group *sg,
  6877. struct sg_lb_stats *sgs)
  6878. {
  6879. struct sg_lb_stats *busiest = &sds->busiest_stat;
  6880. if (sgs->group_type > busiest->group_type)
  6881. return true;
  6882. if (sgs->group_type < busiest->group_type)
  6883. return false;
  6884. if (sgs->avg_load <= busiest->avg_load)
  6885. return false;
  6886. if (!(env->sd->flags & SD_ASYM_CPUCAPACITY))
  6887. goto asym_packing;
  6888. /*
  6889. * Candidate sg has no more than one task per CPU and
  6890. * has higher per-CPU capacity. Migrating tasks to less
  6891. * capable CPUs may harm throughput. Maximize throughput,
  6892. * power/energy consequences are not considered.
  6893. */
  6894. if (sgs->sum_nr_running <= sgs->group_weight &&
  6895. group_smaller_cpu_capacity(sds->local, sg))
  6896. return false;
  6897. asym_packing:
  6898. /* This is the busiest node in its class. */
  6899. if (!(env->sd->flags & SD_ASYM_PACKING))
  6900. return true;
  6901. /* No ASYM_PACKING if target CPU is already busy */
  6902. if (env->idle == CPU_NOT_IDLE)
  6903. return true;
  6904. /*
  6905. * ASYM_PACKING needs to move all the work to the highest
  6906. * prority CPUs in the group, therefore mark all groups
  6907. * of lower priority than ourself as busy.
  6908. */
  6909. if (sgs->sum_nr_running &&
  6910. sched_asym_prefer(env->dst_cpu, sg->asym_prefer_cpu)) {
  6911. if (!sds->busiest)
  6912. return true;
  6913. /* Prefer to move from lowest priority CPU's work */
  6914. if (sched_asym_prefer(sds->busiest->asym_prefer_cpu,
  6915. sg->asym_prefer_cpu))
  6916. return true;
  6917. }
  6918. return false;
  6919. }
  6920. #ifdef CONFIG_NUMA_BALANCING
  6921. static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
  6922. {
  6923. if (sgs->sum_nr_running > sgs->nr_numa_running)
  6924. return regular;
  6925. if (sgs->sum_nr_running > sgs->nr_preferred_running)
  6926. return remote;
  6927. return all;
  6928. }
  6929. static inline enum fbq_type fbq_classify_rq(struct rq *rq)
  6930. {
  6931. if (rq->nr_running > rq->nr_numa_running)
  6932. return regular;
  6933. if (rq->nr_running > rq->nr_preferred_running)
  6934. return remote;
  6935. return all;
  6936. }
  6937. #else
  6938. static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
  6939. {
  6940. return all;
  6941. }
  6942. static inline enum fbq_type fbq_classify_rq(struct rq *rq)
  6943. {
  6944. return regular;
  6945. }
  6946. #endif /* CONFIG_NUMA_BALANCING */
  6947. /**
  6948. * update_sd_lb_stats - Update sched_domain's statistics for load balancing.
  6949. * @env: The load balancing environment.
  6950. * @sds: variable to hold the statistics for this sched_domain.
  6951. */
  6952. static inline void update_sd_lb_stats(struct lb_env *env, struct sd_lb_stats *sds)
  6953. {
  6954. struct sched_domain *child = env->sd->child;
  6955. struct sched_group *sg = env->sd->groups;
  6956. struct sg_lb_stats *local = &sds->local_stat;
  6957. struct sg_lb_stats tmp_sgs;
  6958. int load_idx, prefer_sibling = 0;
  6959. bool overload = false;
  6960. if (child && child->flags & SD_PREFER_SIBLING)
  6961. prefer_sibling = 1;
  6962. #ifdef CONFIG_NO_HZ_COMMON
  6963. if (env->idle == CPU_NEWLY_IDLE && READ_ONCE(nohz.has_blocked))
  6964. env->flags |= LBF_NOHZ_STATS;
  6965. #endif
  6966. load_idx = get_sd_load_idx(env->sd, env->idle);
  6967. do {
  6968. struct sg_lb_stats *sgs = &tmp_sgs;
  6969. int local_group;
  6970. local_group = cpumask_test_cpu(env->dst_cpu, sched_group_span(sg));
  6971. if (local_group) {
  6972. sds->local = sg;
  6973. sgs = local;
  6974. if (env->idle != CPU_NEWLY_IDLE ||
  6975. time_after_eq(jiffies, sg->sgc->next_update))
  6976. update_group_capacity(env->sd, env->dst_cpu);
  6977. }
  6978. update_sg_lb_stats(env, sg, load_idx, local_group, sgs,
  6979. &overload);
  6980. if (local_group)
  6981. goto next_group;
  6982. /*
  6983. * In case the child domain prefers tasks go to siblings
  6984. * first, lower the sg capacity so that we'll try
  6985. * and move all the excess tasks away. We lower the capacity
  6986. * of a group only if the local group has the capacity to fit
  6987. * these excess tasks. The extra check prevents the case where
  6988. * you always pull from the heaviest group when it is already
  6989. * under-utilized (possible with a large weight task outweighs
  6990. * the tasks on the system).
  6991. */
  6992. if (prefer_sibling && sds->local &&
  6993. group_has_capacity(env, local) &&
  6994. (sgs->sum_nr_running > local->sum_nr_running + 1)) {
  6995. sgs->group_no_capacity = 1;
  6996. sgs->group_type = group_classify(sg, sgs);
  6997. }
  6998. if (update_sd_pick_busiest(env, sds, sg, sgs)) {
  6999. sds->busiest = sg;
  7000. sds->busiest_stat = *sgs;
  7001. }
  7002. next_group:
  7003. /* Now, start updating sd_lb_stats */
  7004. sds->total_running += sgs->sum_nr_running;
  7005. sds->total_load += sgs->group_load;
  7006. sds->total_capacity += sgs->group_capacity;
  7007. sg = sg->next;
  7008. } while (sg != env->sd->groups);
  7009. #ifdef CONFIG_NO_HZ_COMMON
  7010. if ((env->flags & LBF_NOHZ_AGAIN) &&
  7011. cpumask_subset(nohz.idle_cpus_mask, sched_domain_span(env->sd))) {
  7012. WRITE_ONCE(nohz.next_blocked,
  7013. jiffies + msecs_to_jiffies(LOAD_AVG_PERIOD));
  7014. }
  7015. #endif
  7016. if (env->sd->flags & SD_NUMA)
  7017. env->fbq_type = fbq_classify_group(&sds->busiest_stat);
  7018. if (!env->sd->parent) {
  7019. /* update overload indicator if we are at root domain */
  7020. if (env->dst_rq->rd->overload != overload)
  7021. env->dst_rq->rd->overload = overload;
  7022. }
  7023. }
  7024. /**
  7025. * check_asym_packing - Check to see if the group is packed into the
  7026. * sched domain.
  7027. *
  7028. * This is primarily intended to used at the sibling level. Some
  7029. * cores like POWER7 prefer to use lower numbered SMT threads. In the
  7030. * case of POWER7, it can move to lower SMT modes only when higher
  7031. * threads are idle. When in lower SMT modes, the threads will
  7032. * perform better since they share less core resources. Hence when we
  7033. * have idle threads, we want them to be the higher ones.
  7034. *
  7035. * This packing function is run on idle threads. It checks to see if
  7036. * the busiest CPU in this domain (core in the P7 case) has a higher
  7037. * CPU number than the packing function is being run on. Here we are
  7038. * assuming lower CPU number will be equivalent to lower a SMT thread
  7039. * number.
  7040. *
  7041. * Return: 1 when packing is required and a task should be moved to
  7042. * this CPU. The amount of the imbalance is returned in env->imbalance.
  7043. *
  7044. * @env: The load balancing environment.
  7045. * @sds: Statistics of the sched_domain which is to be packed
  7046. */
  7047. static int check_asym_packing(struct lb_env *env, struct sd_lb_stats *sds)
  7048. {
  7049. int busiest_cpu;
  7050. if (!(env->sd->flags & SD_ASYM_PACKING))
  7051. return 0;
  7052. if (env->idle == CPU_NOT_IDLE)
  7053. return 0;
  7054. if (!sds->busiest)
  7055. return 0;
  7056. busiest_cpu = sds->busiest->asym_prefer_cpu;
  7057. if (sched_asym_prefer(busiest_cpu, env->dst_cpu))
  7058. return 0;
  7059. env->imbalance = DIV_ROUND_CLOSEST(
  7060. sds->busiest_stat.avg_load * sds->busiest_stat.group_capacity,
  7061. SCHED_CAPACITY_SCALE);
  7062. return 1;
  7063. }
  7064. /**
  7065. * fix_small_imbalance - Calculate the minor imbalance that exists
  7066. * amongst the groups of a sched_domain, during
  7067. * load balancing.
  7068. * @env: The load balancing environment.
  7069. * @sds: Statistics of the sched_domain whose imbalance is to be calculated.
  7070. */
  7071. static inline
  7072. void fix_small_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
  7073. {
  7074. unsigned long tmp, capa_now = 0, capa_move = 0;
  7075. unsigned int imbn = 2;
  7076. unsigned long scaled_busy_load_per_task;
  7077. struct sg_lb_stats *local, *busiest;
  7078. local = &sds->local_stat;
  7079. busiest = &sds->busiest_stat;
  7080. if (!local->sum_nr_running)
  7081. local->load_per_task = cpu_avg_load_per_task(env->dst_cpu);
  7082. else if (busiest->load_per_task > local->load_per_task)
  7083. imbn = 1;
  7084. scaled_busy_load_per_task =
  7085. (busiest->load_per_task * SCHED_CAPACITY_SCALE) /
  7086. busiest->group_capacity;
  7087. if (busiest->avg_load + scaled_busy_load_per_task >=
  7088. local->avg_load + (scaled_busy_load_per_task * imbn)) {
  7089. env->imbalance = busiest->load_per_task;
  7090. return;
  7091. }
  7092. /*
  7093. * OK, we don't have enough imbalance to justify moving tasks,
  7094. * however we may be able to increase total CPU capacity used by
  7095. * moving them.
  7096. */
  7097. capa_now += busiest->group_capacity *
  7098. min(busiest->load_per_task, busiest->avg_load);
  7099. capa_now += local->group_capacity *
  7100. min(local->load_per_task, local->avg_load);
  7101. capa_now /= SCHED_CAPACITY_SCALE;
  7102. /* Amount of load we'd subtract */
  7103. if (busiest->avg_load > scaled_busy_load_per_task) {
  7104. capa_move += busiest->group_capacity *
  7105. min(busiest->load_per_task,
  7106. busiest->avg_load - scaled_busy_load_per_task);
  7107. }
  7108. /* Amount of load we'd add */
  7109. if (busiest->avg_load * busiest->group_capacity <
  7110. busiest->load_per_task * SCHED_CAPACITY_SCALE) {
  7111. tmp = (busiest->avg_load * busiest->group_capacity) /
  7112. local->group_capacity;
  7113. } else {
  7114. tmp = (busiest->load_per_task * SCHED_CAPACITY_SCALE) /
  7115. local->group_capacity;
  7116. }
  7117. capa_move += local->group_capacity *
  7118. min(local->load_per_task, local->avg_load + tmp);
  7119. capa_move /= SCHED_CAPACITY_SCALE;
  7120. /* Move if we gain throughput */
  7121. if (capa_move > capa_now)
  7122. env->imbalance = busiest->load_per_task;
  7123. }
  7124. /**
  7125. * calculate_imbalance - Calculate the amount of imbalance present within the
  7126. * groups of a given sched_domain during load balance.
  7127. * @env: load balance environment
  7128. * @sds: statistics of the sched_domain whose imbalance is to be calculated.
  7129. */
  7130. static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
  7131. {
  7132. unsigned long max_pull, load_above_capacity = ~0UL;
  7133. struct sg_lb_stats *local, *busiest;
  7134. local = &sds->local_stat;
  7135. busiest = &sds->busiest_stat;
  7136. if (busiest->group_type == group_imbalanced) {
  7137. /*
  7138. * In the group_imb case we cannot rely on group-wide averages
  7139. * to ensure CPU-load equilibrium, look at wider averages. XXX
  7140. */
  7141. busiest->load_per_task =
  7142. min(busiest->load_per_task, sds->avg_load);
  7143. }
  7144. /*
  7145. * Avg load of busiest sg can be less and avg load of local sg can
  7146. * be greater than avg load across all sgs of sd because avg load
  7147. * factors in sg capacity and sgs with smaller group_type are
  7148. * skipped when updating the busiest sg:
  7149. */
  7150. if (busiest->avg_load <= sds->avg_load ||
  7151. local->avg_load >= sds->avg_load) {
  7152. env->imbalance = 0;
  7153. return fix_small_imbalance(env, sds);
  7154. }
  7155. /*
  7156. * If there aren't any idle CPUs, avoid creating some.
  7157. */
  7158. if (busiest->group_type == group_overloaded &&
  7159. local->group_type == group_overloaded) {
  7160. load_above_capacity = busiest->sum_nr_running * SCHED_CAPACITY_SCALE;
  7161. if (load_above_capacity > busiest->group_capacity) {
  7162. load_above_capacity -= busiest->group_capacity;
  7163. load_above_capacity *= scale_load_down(NICE_0_LOAD);
  7164. load_above_capacity /= busiest->group_capacity;
  7165. } else
  7166. load_above_capacity = ~0UL;
  7167. }
  7168. /*
  7169. * We're trying to get all the CPUs to the average_load, so we don't
  7170. * want to push ourselves above the average load, nor do we wish to
  7171. * reduce the max loaded CPU below the average load. At the same time,
  7172. * we also don't want to reduce the group load below the group
  7173. * capacity. Thus we look for the minimum possible imbalance.
  7174. */
  7175. max_pull = min(busiest->avg_load - sds->avg_load, load_above_capacity);
  7176. /* How much load to actually move to equalise the imbalance */
  7177. env->imbalance = min(
  7178. max_pull * busiest->group_capacity,
  7179. (sds->avg_load - local->avg_load) * local->group_capacity
  7180. ) / SCHED_CAPACITY_SCALE;
  7181. /*
  7182. * if *imbalance is less than the average load per runnable task
  7183. * there is no guarantee that any tasks will be moved so we'll have
  7184. * a think about bumping its value to force at least one task to be
  7185. * moved
  7186. */
  7187. if (env->imbalance < busiest->load_per_task)
  7188. return fix_small_imbalance(env, sds);
  7189. }
  7190. /******* find_busiest_group() helpers end here *********************/
  7191. /**
  7192. * find_busiest_group - Returns the busiest group within the sched_domain
  7193. * if there is an imbalance.
  7194. *
  7195. * Also calculates the amount of weighted load which should be moved
  7196. * to restore balance.
  7197. *
  7198. * @env: The load balancing environment.
  7199. *
  7200. * Return: - The busiest group if imbalance exists.
  7201. */
  7202. static struct sched_group *find_busiest_group(struct lb_env *env)
  7203. {
  7204. struct sg_lb_stats *local, *busiest;
  7205. struct sd_lb_stats sds;
  7206. init_sd_lb_stats(&sds);
  7207. /*
  7208. * Compute the various statistics relavent for load balancing at
  7209. * this level.
  7210. */
  7211. update_sd_lb_stats(env, &sds);
  7212. local = &sds.local_stat;
  7213. busiest = &sds.busiest_stat;
  7214. /* ASYM feature bypasses nice load balance check */
  7215. if (check_asym_packing(env, &sds))
  7216. return sds.busiest;
  7217. /* There is no busy sibling group to pull tasks from */
  7218. if (!sds.busiest || busiest->sum_nr_running == 0)
  7219. goto out_balanced;
  7220. /* XXX broken for overlapping NUMA groups */
  7221. sds.avg_load = (SCHED_CAPACITY_SCALE * sds.total_load)
  7222. / sds.total_capacity;
  7223. /*
  7224. * If the busiest group is imbalanced the below checks don't
  7225. * work because they assume all things are equal, which typically
  7226. * isn't true due to cpus_allowed constraints and the like.
  7227. */
  7228. if (busiest->group_type == group_imbalanced)
  7229. goto force_balance;
  7230. /*
  7231. * When dst_cpu is idle, prevent SMP nice and/or asymmetric group
  7232. * capacities from resulting in underutilization due to avg_load.
  7233. */
  7234. if (env->idle != CPU_NOT_IDLE && group_has_capacity(env, local) &&
  7235. busiest->group_no_capacity)
  7236. goto force_balance;
  7237. /*
  7238. * If the local group is busier than the selected busiest group
  7239. * don't try and pull any tasks.
  7240. */
  7241. if (local->avg_load >= busiest->avg_load)
  7242. goto out_balanced;
  7243. /*
  7244. * Don't pull any tasks if this group is already above the domain
  7245. * average load.
  7246. */
  7247. if (local->avg_load >= sds.avg_load)
  7248. goto out_balanced;
  7249. if (env->idle == CPU_IDLE) {
  7250. /*
  7251. * This CPU is idle. If the busiest group is not overloaded
  7252. * and there is no imbalance between this and busiest group
  7253. * wrt idle CPUs, it is balanced. The imbalance becomes
  7254. * significant if the diff is greater than 1 otherwise we
  7255. * might end up to just move the imbalance on another group
  7256. */
  7257. if ((busiest->group_type != group_overloaded) &&
  7258. (local->idle_cpus <= (busiest->idle_cpus + 1)))
  7259. goto out_balanced;
  7260. } else {
  7261. /*
  7262. * In the CPU_NEWLY_IDLE, CPU_NOT_IDLE cases, use
  7263. * imbalance_pct to be conservative.
  7264. */
  7265. if (100 * busiest->avg_load <=
  7266. env->sd->imbalance_pct * local->avg_load)
  7267. goto out_balanced;
  7268. }
  7269. force_balance:
  7270. /* Looks like there is an imbalance. Compute it */
  7271. calculate_imbalance(env, &sds);
  7272. return sds.busiest;
  7273. out_balanced:
  7274. env->imbalance = 0;
  7275. return NULL;
  7276. }
  7277. /*
  7278. * find_busiest_queue - find the busiest runqueue among the CPUs in the group.
  7279. */
  7280. static struct rq *find_busiest_queue(struct lb_env *env,
  7281. struct sched_group *group)
  7282. {
  7283. struct rq *busiest = NULL, *rq;
  7284. unsigned long busiest_load = 0, busiest_capacity = 1;
  7285. int i;
  7286. for_each_cpu_and(i, sched_group_span(group), env->cpus) {
  7287. unsigned long capacity, wl;
  7288. enum fbq_type rt;
  7289. rq = cpu_rq(i);
  7290. rt = fbq_classify_rq(rq);
  7291. /*
  7292. * We classify groups/runqueues into three groups:
  7293. * - regular: there are !numa tasks
  7294. * - remote: there are numa tasks that run on the 'wrong' node
  7295. * - all: there is no distinction
  7296. *
  7297. * In order to avoid migrating ideally placed numa tasks,
  7298. * ignore those when there's better options.
  7299. *
  7300. * If we ignore the actual busiest queue to migrate another
  7301. * task, the next balance pass can still reduce the busiest
  7302. * queue by moving tasks around inside the node.
  7303. *
  7304. * If we cannot move enough load due to this classification
  7305. * the next pass will adjust the group classification and
  7306. * allow migration of more tasks.
  7307. *
  7308. * Both cases only affect the total convergence complexity.
  7309. */
  7310. if (rt > env->fbq_type)
  7311. continue;
  7312. capacity = capacity_of(i);
  7313. wl = weighted_cpuload(rq);
  7314. /*
  7315. * When comparing with imbalance, use weighted_cpuload()
  7316. * which is not scaled with the CPU capacity.
  7317. */
  7318. if (rq->nr_running == 1 && wl > env->imbalance &&
  7319. !check_cpu_capacity(rq, env->sd))
  7320. continue;
  7321. /*
  7322. * For the load comparisons with the other CPU's, consider
  7323. * the weighted_cpuload() scaled with the CPU capacity, so
  7324. * that the load can be moved away from the CPU that is
  7325. * potentially running at a lower capacity.
  7326. *
  7327. * Thus we're looking for max(wl_i / capacity_i), crosswise
  7328. * multiplication to rid ourselves of the division works out
  7329. * to: wl_i * capacity_j > wl_j * capacity_i; where j is
  7330. * our previous maximum.
  7331. */
  7332. if (wl * busiest_capacity > busiest_load * capacity) {
  7333. busiest_load = wl;
  7334. busiest_capacity = capacity;
  7335. busiest = rq;
  7336. }
  7337. }
  7338. return busiest;
  7339. }
  7340. /*
  7341. * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
  7342. * so long as it is large enough.
  7343. */
  7344. #define MAX_PINNED_INTERVAL 512
  7345. static int need_active_balance(struct lb_env *env)
  7346. {
  7347. struct sched_domain *sd = env->sd;
  7348. if (env->idle == CPU_NEWLY_IDLE) {
  7349. /*
  7350. * ASYM_PACKING needs to force migrate tasks from busy but
  7351. * lower priority CPUs in order to pack all tasks in the
  7352. * highest priority CPUs.
  7353. */
  7354. if ((sd->flags & SD_ASYM_PACKING) &&
  7355. sched_asym_prefer(env->dst_cpu, env->src_cpu))
  7356. return 1;
  7357. }
  7358. /*
  7359. * The dst_cpu is idle and the src_cpu CPU has only 1 CFS task.
  7360. * It's worth migrating the task if the src_cpu's capacity is reduced
  7361. * because of other sched_class or IRQs if more capacity stays
  7362. * available on dst_cpu.
  7363. */
  7364. if ((env->idle != CPU_NOT_IDLE) &&
  7365. (env->src_rq->cfs.h_nr_running == 1)) {
  7366. if ((check_cpu_capacity(env->src_rq, sd)) &&
  7367. (capacity_of(env->src_cpu)*sd->imbalance_pct < capacity_of(env->dst_cpu)*100))
  7368. return 1;
  7369. }
  7370. return unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2);
  7371. }
  7372. static int active_load_balance_cpu_stop(void *data);
  7373. static int should_we_balance(struct lb_env *env)
  7374. {
  7375. struct sched_group *sg = env->sd->groups;
  7376. int cpu, balance_cpu = -1;
  7377. /*
  7378. * Ensure the balancing environment is consistent; can happen
  7379. * when the softirq triggers 'during' hotplug.
  7380. */
  7381. if (!cpumask_test_cpu(env->dst_cpu, env->cpus))
  7382. return 0;
  7383. /*
  7384. * In the newly idle case, we will allow all the CPUs
  7385. * to do the newly idle load balance.
  7386. */
  7387. if (env->idle == CPU_NEWLY_IDLE)
  7388. return 1;
  7389. /* Try to find first idle CPU */
  7390. for_each_cpu_and(cpu, group_balance_mask(sg), env->cpus) {
  7391. if (!idle_cpu(cpu))
  7392. continue;
  7393. balance_cpu = cpu;
  7394. break;
  7395. }
  7396. if (balance_cpu == -1)
  7397. balance_cpu = group_balance_cpu(sg);
  7398. /*
  7399. * First idle CPU or the first CPU(busiest) in this sched group
  7400. * is eligible for doing load balancing at this and above domains.
  7401. */
  7402. return balance_cpu == env->dst_cpu;
  7403. }
  7404. /*
  7405. * Check this_cpu to ensure it is balanced within domain. Attempt to move
  7406. * tasks if there is an imbalance.
  7407. */
  7408. static int load_balance(int this_cpu, struct rq *this_rq,
  7409. struct sched_domain *sd, enum cpu_idle_type idle,
  7410. int *continue_balancing)
  7411. {
  7412. int ld_moved, cur_ld_moved, active_balance = 0;
  7413. struct sched_domain *sd_parent = sd->parent;
  7414. struct sched_group *group;
  7415. struct rq *busiest;
  7416. struct rq_flags rf;
  7417. struct cpumask *cpus = this_cpu_cpumask_var_ptr(load_balance_mask);
  7418. struct lb_env env = {
  7419. .sd = sd,
  7420. .dst_cpu = this_cpu,
  7421. .dst_rq = this_rq,
  7422. .dst_grpmask = sched_group_span(sd->groups),
  7423. .idle = idle,
  7424. .loop_break = sched_nr_migrate_break,
  7425. .cpus = cpus,
  7426. .fbq_type = all,
  7427. .tasks = LIST_HEAD_INIT(env.tasks),
  7428. };
  7429. cpumask_and(cpus, sched_domain_span(sd), cpu_active_mask);
  7430. schedstat_inc(sd->lb_count[idle]);
  7431. redo:
  7432. if (!should_we_balance(&env)) {
  7433. *continue_balancing = 0;
  7434. goto out_balanced;
  7435. }
  7436. group = find_busiest_group(&env);
  7437. if (!group) {
  7438. schedstat_inc(sd->lb_nobusyg[idle]);
  7439. goto out_balanced;
  7440. }
  7441. busiest = find_busiest_queue(&env, group);
  7442. if (!busiest) {
  7443. schedstat_inc(sd->lb_nobusyq[idle]);
  7444. goto out_balanced;
  7445. }
  7446. BUG_ON(busiest == env.dst_rq);
  7447. schedstat_add(sd->lb_imbalance[idle], env.imbalance);
  7448. env.src_cpu = busiest->cpu;
  7449. env.src_rq = busiest;
  7450. ld_moved = 0;
  7451. if (busiest->nr_running > 1) {
  7452. /*
  7453. * Attempt to move tasks. If find_busiest_group has found
  7454. * an imbalance but busiest->nr_running <= 1, the group is
  7455. * still unbalanced. ld_moved simply stays zero, so it is
  7456. * correctly treated as an imbalance.
  7457. */
  7458. env.flags |= LBF_ALL_PINNED;
  7459. env.loop_max = min(sysctl_sched_nr_migrate, busiest->nr_running);
  7460. more_balance:
  7461. rq_lock_irqsave(busiest, &rf);
  7462. update_rq_clock(busiest);
  7463. /*
  7464. * cur_ld_moved - load moved in current iteration
  7465. * ld_moved - cumulative load moved across iterations
  7466. */
  7467. cur_ld_moved = detach_tasks(&env);
  7468. /*
  7469. * We've detached some tasks from busiest_rq. Every
  7470. * task is masked "TASK_ON_RQ_MIGRATING", so we can safely
  7471. * unlock busiest->lock, and we are able to be sure
  7472. * that nobody can manipulate the tasks in parallel.
  7473. * See task_rq_lock() family for the details.
  7474. */
  7475. rq_unlock(busiest, &rf);
  7476. if (cur_ld_moved) {
  7477. attach_tasks(&env);
  7478. ld_moved += cur_ld_moved;
  7479. }
  7480. local_irq_restore(rf.flags);
  7481. if (env.flags & LBF_NEED_BREAK) {
  7482. env.flags &= ~LBF_NEED_BREAK;
  7483. goto more_balance;
  7484. }
  7485. /*
  7486. * Revisit (affine) tasks on src_cpu that couldn't be moved to
  7487. * us and move them to an alternate dst_cpu in our sched_group
  7488. * where they can run. The upper limit on how many times we
  7489. * iterate on same src_cpu is dependent on number of CPUs in our
  7490. * sched_group.
  7491. *
  7492. * This changes load balance semantics a bit on who can move
  7493. * load to a given_cpu. In addition to the given_cpu itself
  7494. * (or a ilb_cpu acting on its behalf where given_cpu is
  7495. * nohz-idle), we now have balance_cpu in a position to move
  7496. * load to given_cpu. In rare situations, this may cause
  7497. * conflicts (balance_cpu and given_cpu/ilb_cpu deciding
  7498. * _independently_ and at _same_ time to move some load to
  7499. * given_cpu) causing exceess load to be moved to given_cpu.
  7500. * This however should not happen so much in practice and
  7501. * moreover subsequent load balance cycles should correct the
  7502. * excess load moved.
  7503. */
  7504. if ((env.flags & LBF_DST_PINNED) && env.imbalance > 0) {
  7505. /* Prevent to re-select dst_cpu via env's CPUs */
  7506. cpumask_clear_cpu(env.dst_cpu, env.cpus);
  7507. env.dst_rq = cpu_rq(env.new_dst_cpu);
  7508. env.dst_cpu = env.new_dst_cpu;
  7509. env.flags &= ~LBF_DST_PINNED;
  7510. env.loop = 0;
  7511. env.loop_break = sched_nr_migrate_break;
  7512. /*
  7513. * Go back to "more_balance" rather than "redo" since we
  7514. * need to continue with same src_cpu.
  7515. */
  7516. goto more_balance;
  7517. }
  7518. /*
  7519. * We failed to reach balance because of affinity.
  7520. */
  7521. if (sd_parent) {
  7522. int *group_imbalance = &sd_parent->groups->sgc->imbalance;
  7523. if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0)
  7524. *group_imbalance = 1;
  7525. }
  7526. /* All tasks on this runqueue were pinned by CPU affinity */
  7527. if (unlikely(env.flags & LBF_ALL_PINNED)) {
  7528. cpumask_clear_cpu(cpu_of(busiest), cpus);
  7529. /*
  7530. * Attempting to continue load balancing at the current
  7531. * sched_domain level only makes sense if there are
  7532. * active CPUs remaining as possible busiest CPUs to
  7533. * pull load from which are not contained within the
  7534. * destination group that is receiving any migrated
  7535. * load.
  7536. */
  7537. if (!cpumask_subset(cpus, env.dst_grpmask)) {
  7538. env.loop = 0;
  7539. env.loop_break = sched_nr_migrate_break;
  7540. goto redo;
  7541. }
  7542. goto out_all_pinned;
  7543. }
  7544. }
  7545. if (!ld_moved) {
  7546. schedstat_inc(sd->lb_failed[idle]);
  7547. /*
  7548. * Increment the failure counter only on periodic balance.
  7549. * We do not want newidle balance, which can be very
  7550. * frequent, pollute the failure counter causing
  7551. * excessive cache_hot migrations and active balances.
  7552. */
  7553. if (idle != CPU_NEWLY_IDLE)
  7554. sd->nr_balance_failed++;
  7555. if (need_active_balance(&env)) {
  7556. unsigned long flags;
  7557. raw_spin_lock_irqsave(&busiest->lock, flags);
  7558. /*
  7559. * Don't kick the active_load_balance_cpu_stop,
  7560. * if the curr task on busiest CPU can't be
  7561. * moved to this_cpu:
  7562. */
  7563. if (!cpumask_test_cpu(this_cpu, &busiest->curr->cpus_allowed)) {
  7564. raw_spin_unlock_irqrestore(&busiest->lock,
  7565. flags);
  7566. env.flags |= LBF_ALL_PINNED;
  7567. goto out_one_pinned;
  7568. }
  7569. /*
  7570. * ->active_balance synchronizes accesses to
  7571. * ->active_balance_work. Once set, it's cleared
  7572. * only after active load balance is finished.
  7573. */
  7574. if (!busiest->active_balance) {
  7575. busiest->active_balance = 1;
  7576. busiest->push_cpu = this_cpu;
  7577. active_balance = 1;
  7578. }
  7579. raw_spin_unlock_irqrestore(&busiest->lock, flags);
  7580. if (active_balance) {
  7581. stop_one_cpu_nowait(cpu_of(busiest),
  7582. active_load_balance_cpu_stop, busiest,
  7583. &busiest->active_balance_work);
  7584. }
  7585. /* We've kicked active balancing, force task migration. */
  7586. sd->nr_balance_failed = sd->cache_nice_tries+1;
  7587. }
  7588. } else
  7589. sd->nr_balance_failed = 0;
  7590. if (likely(!active_balance)) {
  7591. /* We were unbalanced, so reset the balancing interval */
  7592. sd->balance_interval = sd->min_interval;
  7593. } else {
  7594. /*
  7595. * If we've begun active balancing, start to back off. This
  7596. * case may not be covered by the all_pinned logic if there
  7597. * is only 1 task on the busy runqueue (because we don't call
  7598. * detach_tasks).
  7599. */
  7600. if (sd->balance_interval < sd->max_interval)
  7601. sd->balance_interval *= 2;
  7602. }
  7603. goto out;
  7604. out_balanced:
  7605. /*
  7606. * We reach balance although we may have faced some affinity
  7607. * constraints. Clear the imbalance flag if it was set.
  7608. */
  7609. if (sd_parent) {
  7610. int *group_imbalance = &sd_parent->groups->sgc->imbalance;
  7611. if (*group_imbalance)
  7612. *group_imbalance = 0;
  7613. }
  7614. out_all_pinned:
  7615. /*
  7616. * We reach balance because all tasks are pinned at this level so
  7617. * we can't migrate them. Let the imbalance flag set so parent level
  7618. * can try to migrate them.
  7619. */
  7620. schedstat_inc(sd->lb_balanced[idle]);
  7621. sd->nr_balance_failed = 0;
  7622. out_one_pinned:
  7623. /* tune up the balancing interval */
  7624. if (((env.flags & LBF_ALL_PINNED) &&
  7625. sd->balance_interval < MAX_PINNED_INTERVAL) ||
  7626. (sd->balance_interval < sd->max_interval))
  7627. sd->balance_interval *= 2;
  7628. ld_moved = 0;
  7629. out:
  7630. return ld_moved;
  7631. }
  7632. static inline unsigned long
  7633. get_sd_balance_interval(struct sched_domain *sd, int cpu_busy)
  7634. {
  7635. unsigned long interval = sd->balance_interval;
  7636. if (cpu_busy)
  7637. interval *= sd->busy_factor;
  7638. /* scale ms to jiffies */
  7639. interval = msecs_to_jiffies(interval);
  7640. interval = clamp(interval, 1UL, max_load_balance_interval);
  7641. return interval;
  7642. }
  7643. static inline void
  7644. update_next_balance(struct sched_domain *sd, unsigned long *next_balance)
  7645. {
  7646. unsigned long interval, next;
  7647. /* used by idle balance, so cpu_busy = 0 */
  7648. interval = get_sd_balance_interval(sd, 0);
  7649. next = sd->last_balance + interval;
  7650. if (time_after(*next_balance, next))
  7651. *next_balance = next;
  7652. }
  7653. /*
  7654. * active_load_balance_cpu_stop is run by the CPU stopper. It pushes
  7655. * running tasks off the busiest CPU onto idle CPUs. It requires at
  7656. * least 1 task to be running on each physical CPU where possible, and
  7657. * avoids physical / logical imbalances.
  7658. */
  7659. static int active_load_balance_cpu_stop(void *data)
  7660. {
  7661. struct rq *busiest_rq = data;
  7662. int busiest_cpu = cpu_of(busiest_rq);
  7663. int target_cpu = busiest_rq->push_cpu;
  7664. struct rq *target_rq = cpu_rq(target_cpu);
  7665. struct sched_domain *sd;
  7666. struct task_struct *p = NULL;
  7667. struct rq_flags rf;
  7668. rq_lock_irq(busiest_rq, &rf);
  7669. /*
  7670. * Between queueing the stop-work and running it is a hole in which
  7671. * CPUs can become inactive. We should not move tasks from or to
  7672. * inactive CPUs.
  7673. */
  7674. if (!cpu_active(busiest_cpu) || !cpu_active(target_cpu))
  7675. goto out_unlock;
  7676. /* Make sure the requested CPU hasn't gone down in the meantime: */
  7677. if (unlikely(busiest_cpu != smp_processor_id() ||
  7678. !busiest_rq->active_balance))
  7679. goto out_unlock;
  7680. /* Is there any task to move? */
  7681. if (busiest_rq->nr_running <= 1)
  7682. goto out_unlock;
  7683. /*
  7684. * This condition is "impossible", if it occurs
  7685. * we need to fix it. Originally reported by
  7686. * Bjorn Helgaas on a 128-CPU setup.
  7687. */
  7688. BUG_ON(busiest_rq == target_rq);
  7689. /* Search for an sd spanning us and the target CPU. */
  7690. rcu_read_lock();
  7691. for_each_domain(target_cpu, sd) {
  7692. if ((sd->flags & SD_LOAD_BALANCE) &&
  7693. cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
  7694. break;
  7695. }
  7696. if (likely(sd)) {
  7697. struct lb_env env = {
  7698. .sd = sd,
  7699. .dst_cpu = target_cpu,
  7700. .dst_rq = target_rq,
  7701. .src_cpu = busiest_rq->cpu,
  7702. .src_rq = busiest_rq,
  7703. .idle = CPU_IDLE,
  7704. /*
  7705. * can_migrate_task() doesn't need to compute new_dst_cpu
  7706. * for active balancing. Since we have CPU_IDLE, but no
  7707. * @dst_grpmask we need to make that test go away with lying
  7708. * about DST_PINNED.
  7709. */
  7710. .flags = LBF_DST_PINNED,
  7711. };
  7712. schedstat_inc(sd->alb_count);
  7713. update_rq_clock(busiest_rq);
  7714. p = detach_one_task(&env);
  7715. if (p) {
  7716. schedstat_inc(sd->alb_pushed);
  7717. /* Active balancing done, reset the failure counter. */
  7718. sd->nr_balance_failed = 0;
  7719. } else {
  7720. schedstat_inc(sd->alb_failed);
  7721. }
  7722. }
  7723. rcu_read_unlock();
  7724. out_unlock:
  7725. busiest_rq->active_balance = 0;
  7726. rq_unlock(busiest_rq, &rf);
  7727. if (p)
  7728. attach_one_task(target_rq, p);
  7729. local_irq_enable();
  7730. return 0;
  7731. }
  7732. static DEFINE_SPINLOCK(balancing);
  7733. /*
  7734. * Scale the max load_balance interval with the number of CPUs in the system.
  7735. * This trades load-balance latency on larger machines for less cross talk.
  7736. */
  7737. void update_max_interval(void)
  7738. {
  7739. max_load_balance_interval = HZ*num_online_cpus()/10;
  7740. }
  7741. /*
  7742. * It checks each scheduling domain to see if it is due to be balanced,
  7743. * and initiates a balancing operation if so.
  7744. *
  7745. * Balancing parameters are set up in init_sched_domains.
  7746. */
  7747. static void rebalance_domains(struct rq *rq, enum cpu_idle_type idle)
  7748. {
  7749. int continue_balancing = 1;
  7750. int cpu = rq->cpu;
  7751. unsigned long interval;
  7752. struct sched_domain *sd;
  7753. /* Earliest time when we have to do rebalance again */
  7754. unsigned long next_balance = jiffies + 60*HZ;
  7755. int update_next_balance = 0;
  7756. int need_serialize, need_decay = 0;
  7757. u64 max_cost = 0;
  7758. rcu_read_lock();
  7759. for_each_domain(cpu, sd) {
  7760. /*
  7761. * Decay the newidle max times here because this is a regular
  7762. * visit to all the domains. Decay ~1% per second.
  7763. */
  7764. if (time_after(jiffies, sd->next_decay_max_lb_cost)) {
  7765. sd->max_newidle_lb_cost =
  7766. (sd->max_newidle_lb_cost * 253) / 256;
  7767. sd->next_decay_max_lb_cost = jiffies + HZ;
  7768. need_decay = 1;
  7769. }
  7770. max_cost += sd->max_newidle_lb_cost;
  7771. if (!(sd->flags & SD_LOAD_BALANCE))
  7772. continue;
  7773. /*
  7774. * Stop the load balance at this level. There is another
  7775. * CPU in our sched group which is doing load balancing more
  7776. * actively.
  7777. */
  7778. if (!continue_balancing) {
  7779. if (need_decay)
  7780. continue;
  7781. break;
  7782. }
  7783. interval = get_sd_balance_interval(sd, idle != CPU_IDLE);
  7784. need_serialize = sd->flags & SD_SERIALIZE;
  7785. if (need_serialize) {
  7786. if (!spin_trylock(&balancing))
  7787. goto out;
  7788. }
  7789. if (time_after_eq(jiffies, sd->last_balance + interval)) {
  7790. if (load_balance(cpu, rq, sd, idle, &continue_balancing)) {
  7791. /*
  7792. * The LBF_DST_PINNED logic could have changed
  7793. * env->dst_cpu, so we can't know our idle
  7794. * state even if we migrated tasks. Update it.
  7795. */
  7796. idle = idle_cpu(cpu) ? CPU_IDLE : CPU_NOT_IDLE;
  7797. }
  7798. sd->last_balance = jiffies;
  7799. interval = get_sd_balance_interval(sd, idle != CPU_IDLE);
  7800. }
  7801. if (need_serialize)
  7802. spin_unlock(&balancing);
  7803. out:
  7804. if (time_after(next_balance, sd->last_balance + interval)) {
  7805. next_balance = sd->last_balance + interval;
  7806. update_next_balance = 1;
  7807. }
  7808. }
  7809. if (need_decay) {
  7810. /*
  7811. * Ensure the rq-wide value also decays but keep it at a
  7812. * reasonable floor to avoid funnies with rq->avg_idle.
  7813. */
  7814. rq->max_idle_balance_cost =
  7815. max((u64)sysctl_sched_migration_cost, max_cost);
  7816. }
  7817. rcu_read_unlock();
  7818. /*
  7819. * next_balance will be updated only when there is a need.
  7820. * When the cpu is attached to null domain for ex, it will not be
  7821. * updated.
  7822. */
  7823. if (likely(update_next_balance)) {
  7824. rq->next_balance = next_balance;
  7825. #ifdef CONFIG_NO_HZ_COMMON
  7826. /*
  7827. * If this CPU has been elected to perform the nohz idle
  7828. * balance. Other idle CPUs have already rebalanced with
  7829. * nohz_idle_balance() and nohz.next_balance has been
  7830. * updated accordingly. This CPU is now running the idle load
  7831. * balance for itself and we need to update the
  7832. * nohz.next_balance accordingly.
  7833. */
  7834. if ((idle == CPU_IDLE) && time_after(nohz.next_balance, rq->next_balance))
  7835. nohz.next_balance = rq->next_balance;
  7836. #endif
  7837. }
  7838. }
  7839. static inline int on_null_domain(struct rq *rq)
  7840. {
  7841. return unlikely(!rcu_dereference_sched(rq->sd));
  7842. }
  7843. #ifdef CONFIG_NO_HZ_COMMON
  7844. /*
  7845. * idle load balancing details
  7846. * - When one of the busy CPUs notice that there may be an idle rebalancing
  7847. * needed, they will kick the idle load balancer, which then does idle
  7848. * load balancing for all the idle CPUs.
  7849. */
  7850. static inline int find_new_ilb(void)
  7851. {
  7852. int ilb = cpumask_first(nohz.idle_cpus_mask);
  7853. if (ilb < nr_cpu_ids && idle_cpu(ilb))
  7854. return ilb;
  7855. return nr_cpu_ids;
  7856. }
  7857. /*
  7858. * Kick a CPU to do the nohz balancing, if it is time for it. We pick the
  7859. * nohz_load_balancer CPU (if there is one) otherwise fallback to any idle
  7860. * CPU (if there is one).
  7861. */
  7862. static void kick_ilb(unsigned int flags)
  7863. {
  7864. int ilb_cpu;
  7865. nohz.next_balance++;
  7866. ilb_cpu = find_new_ilb();
  7867. if (ilb_cpu >= nr_cpu_ids)
  7868. return;
  7869. flags = atomic_fetch_or(flags, nohz_flags(ilb_cpu));
  7870. if (flags & NOHZ_KICK_MASK)
  7871. return;
  7872. /*
  7873. * Use smp_send_reschedule() instead of resched_cpu().
  7874. * This way we generate a sched IPI on the target CPU which
  7875. * is idle. And the softirq performing nohz idle load balance
  7876. * will be run before returning from the IPI.
  7877. */
  7878. smp_send_reschedule(ilb_cpu);
  7879. }
  7880. /*
  7881. * Current heuristic for kicking the idle load balancer in the presence
  7882. * of an idle cpu in the system.
  7883. * - This rq has more than one task.
  7884. * - This rq has at least one CFS task and the capacity of the CPU is
  7885. * significantly reduced because of RT tasks or IRQs.
  7886. * - At parent of LLC scheduler domain level, this cpu's scheduler group has
  7887. * multiple busy cpu.
  7888. * - For SD_ASYM_PACKING, if the lower numbered cpu's in the scheduler
  7889. * domain span are idle.
  7890. */
  7891. static void nohz_balancer_kick(struct rq *rq)
  7892. {
  7893. unsigned long now = jiffies;
  7894. struct sched_domain_shared *sds;
  7895. struct sched_domain *sd;
  7896. int nr_busy, i, cpu = rq->cpu;
  7897. unsigned int flags = 0;
  7898. if (unlikely(rq->idle_balance))
  7899. return;
  7900. /*
  7901. * We may be recently in ticked or tickless idle mode. At the first
  7902. * busy tick after returning from idle, we will update the busy stats.
  7903. */
  7904. nohz_balance_exit_idle(rq);
  7905. /*
  7906. * None are in tickless mode and hence no need for NOHZ idle load
  7907. * balancing.
  7908. */
  7909. if (likely(!atomic_read(&nohz.nr_cpus)))
  7910. return;
  7911. if (READ_ONCE(nohz.has_blocked) &&
  7912. time_after(now, READ_ONCE(nohz.next_blocked)))
  7913. flags = NOHZ_STATS_KICK;
  7914. if (time_before(now, nohz.next_balance))
  7915. goto out;
  7916. if (rq->nr_running >= 2) {
  7917. flags = NOHZ_KICK_MASK;
  7918. goto out;
  7919. }
  7920. rcu_read_lock();
  7921. sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
  7922. if (sds) {
  7923. /*
  7924. * XXX: write a coherent comment on why we do this.
  7925. * See also: http://lkml.kernel.org/r/20111202010832.602203411@sbsiddha-desk.sc.intel.com
  7926. */
  7927. nr_busy = atomic_read(&sds->nr_busy_cpus);
  7928. if (nr_busy > 1) {
  7929. flags = NOHZ_KICK_MASK;
  7930. goto unlock;
  7931. }
  7932. }
  7933. sd = rcu_dereference(rq->sd);
  7934. if (sd) {
  7935. if ((rq->cfs.h_nr_running >= 1) &&
  7936. check_cpu_capacity(rq, sd)) {
  7937. flags = NOHZ_KICK_MASK;
  7938. goto unlock;
  7939. }
  7940. }
  7941. sd = rcu_dereference(per_cpu(sd_asym, cpu));
  7942. if (sd) {
  7943. for_each_cpu(i, sched_domain_span(sd)) {
  7944. if (i == cpu ||
  7945. !cpumask_test_cpu(i, nohz.idle_cpus_mask))
  7946. continue;
  7947. if (sched_asym_prefer(i, cpu)) {
  7948. flags = NOHZ_KICK_MASK;
  7949. goto unlock;
  7950. }
  7951. }
  7952. }
  7953. unlock:
  7954. rcu_read_unlock();
  7955. out:
  7956. if (flags)
  7957. kick_ilb(flags);
  7958. }
  7959. static void set_cpu_sd_state_busy(int cpu)
  7960. {
  7961. struct sched_domain *sd;
  7962. rcu_read_lock();
  7963. sd = rcu_dereference(per_cpu(sd_llc, cpu));
  7964. if (!sd || !sd->nohz_idle)
  7965. goto unlock;
  7966. sd->nohz_idle = 0;
  7967. atomic_inc(&sd->shared->nr_busy_cpus);
  7968. unlock:
  7969. rcu_read_unlock();
  7970. }
  7971. void nohz_balance_exit_idle(struct rq *rq)
  7972. {
  7973. SCHED_WARN_ON(rq != this_rq());
  7974. if (likely(!rq->nohz_tick_stopped))
  7975. return;
  7976. rq->nohz_tick_stopped = 0;
  7977. cpumask_clear_cpu(rq->cpu, nohz.idle_cpus_mask);
  7978. atomic_dec(&nohz.nr_cpus);
  7979. set_cpu_sd_state_busy(rq->cpu);
  7980. }
  7981. static void set_cpu_sd_state_idle(int cpu)
  7982. {
  7983. struct sched_domain *sd;
  7984. rcu_read_lock();
  7985. sd = rcu_dereference(per_cpu(sd_llc, cpu));
  7986. if (!sd || sd->nohz_idle)
  7987. goto unlock;
  7988. sd->nohz_idle = 1;
  7989. atomic_dec(&sd->shared->nr_busy_cpus);
  7990. unlock:
  7991. rcu_read_unlock();
  7992. }
  7993. /*
  7994. * This routine will record that the CPU is going idle with tick stopped.
  7995. * This info will be used in performing idle load balancing in the future.
  7996. */
  7997. void nohz_balance_enter_idle(int cpu)
  7998. {
  7999. struct rq *rq = cpu_rq(cpu);
  8000. SCHED_WARN_ON(cpu != smp_processor_id());
  8001. /* If this CPU is going down, then nothing needs to be done: */
  8002. if (!cpu_active(cpu))
  8003. return;
  8004. /* Spare idle load balancing on CPUs that don't want to be disturbed: */
  8005. if (!housekeeping_cpu(cpu, HK_FLAG_SCHED))
  8006. return;
  8007. /*
  8008. * Can be set safely without rq->lock held
  8009. * If a clear happens, it will have evaluated last additions because
  8010. * rq->lock is held during the check and the clear
  8011. */
  8012. rq->has_blocked_load = 1;
  8013. /*
  8014. * The tick is still stopped but load could have been added in the
  8015. * meantime. We set the nohz.has_blocked flag to trig a check of the
  8016. * *_avg. The CPU is already part of nohz.idle_cpus_mask so the clear
  8017. * of nohz.has_blocked can only happen after checking the new load
  8018. */
  8019. if (rq->nohz_tick_stopped)
  8020. goto out;
  8021. /* If we're a completely isolated CPU, we don't play: */
  8022. if (on_null_domain(rq))
  8023. return;
  8024. rq->nohz_tick_stopped = 1;
  8025. cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
  8026. atomic_inc(&nohz.nr_cpus);
  8027. /*
  8028. * Ensures that if nohz_idle_balance() fails to observe our
  8029. * @idle_cpus_mask store, it must observe the @has_blocked
  8030. * store.
  8031. */
  8032. smp_mb__after_atomic();
  8033. set_cpu_sd_state_idle(cpu);
  8034. out:
  8035. /*
  8036. * Each time a cpu enter idle, we assume that it has blocked load and
  8037. * enable the periodic update of the load of idle cpus
  8038. */
  8039. WRITE_ONCE(nohz.has_blocked, 1);
  8040. }
  8041. /*
  8042. * Internal function that runs load balance for all idle cpus. The load balance
  8043. * can be a simple update of blocked load or a complete load balance with
  8044. * tasks movement depending of flags.
  8045. * The function returns false if the loop has stopped before running
  8046. * through all idle CPUs.
  8047. */
  8048. static bool _nohz_idle_balance(struct rq *this_rq, unsigned int flags,
  8049. enum cpu_idle_type idle)
  8050. {
  8051. /* Earliest time when we have to do rebalance again */
  8052. unsigned long now = jiffies;
  8053. unsigned long next_balance = now + 60*HZ;
  8054. bool has_blocked_load = false;
  8055. int update_next_balance = 0;
  8056. int this_cpu = this_rq->cpu;
  8057. int balance_cpu;
  8058. int ret = false;
  8059. struct rq *rq;
  8060. SCHED_WARN_ON((flags & NOHZ_KICK_MASK) == NOHZ_BALANCE_KICK);
  8061. /*
  8062. * We assume there will be no idle load after this update and clear
  8063. * the has_blocked flag. If a cpu enters idle in the mean time, it will
  8064. * set the has_blocked flag and trig another update of idle load.
  8065. * Because a cpu that becomes idle, is added to idle_cpus_mask before
  8066. * setting the flag, we are sure to not clear the state and not
  8067. * check the load of an idle cpu.
  8068. */
  8069. WRITE_ONCE(nohz.has_blocked, 0);
  8070. /*
  8071. * Ensures that if we miss the CPU, we must see the has_blocked
  8072. * store from nohz_balance_enter_idle().
  8073. */
  8074. smp_mb();
  8075. for_each_cpu(balance_cpu, nohz.idle_cpus_mask) {
  8076. if (balance_cpu == this_cpu || !idle_cpu(balance_cpu))
  8077. continue;
  8078. /*
  8079. * If this CPU gets work to do, stop the load balancing
  8080. * work being done for other CPUs. Next load
  8081. * balancing owner will pick it up.
  8082. */
  8083. if (need_resched()) {
  8084. has_blocked_load = true;
  8085. goto abort;
  8086. }
  8087. rq = cpu_rq(balance_cpu);
  8088. has_blocked_load |= update_nohz_stats(rq, true);
  8089. /*
  8090. * If time for next balance is due,
  8091. * do the balance.
  8092. */
  8093. if (time_after_eq(jiffies, rq->next_balance)) {
  8094. struct rq_flags rf;
  8095. rq_lock_irqsave(rq, &rf);
  8096. update_rq_clock(rq);
  8097. cpu_load_update_idle(rq);
  8098. rq_unlock_irqrestore(rq, &rf);
  8099. if (flags & NOHZ_BALANCE_KICK)
  8100. rebalance_domains(rq, CPU_IDLE);
  8101. }
  8102. if (time_after(next_balance, rq->next_balance)) {
  8103. next_balance = rq->next_balance;
  8104. update_next_balance = 1;
  8105. }
  8106. }
  8107. /* Newly idle CPU doesn't need an update */
  8108. if (idle != CPU_NEWLY_IDLE) {
  8109. update_blocked_averages(this_cpu);
  8110. has_blocked_load |= this_rq->has_blocked_load;
  8111. }
  8112. if (flags & NOHZ_BALANCE_KICK)
  8113. rebalance_domains(this_rq, CPU_IDLE);
  8114. WRITE_ONCE(nohz.next_blocked,
  8115. now + msecs_to_jiffies(LOAD_AVG_PERIOD));
  8116. /* The full idle balance loop has been done */
  8117. ret = true;
  8118. abort:
  8119. /* There is still blocked load, enable periodic update */
  8120. if (has_blocked_load)
  8121. WRITE_ONCE(nohz.has_blocked, 1);
  8122. /*
  8123. * next_balance will be updated only when there is a need.
  8124. * When the CPU is attached to null domain for ex, it will not be
  8125. * updated.
  8126. */
  8127. if (likely(update_next_balance))
  8128. nohz.next_balance = next_balance;
  8129. return ret;
  8130. }
  8131. /*
  8132. * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the
  8133. * rebalancing for all the cpus for whom scheduler ticks are stopped.
  8134. */
  8135. static bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
  8136. {
  8137. int this_cpu = this_rq->cpu;
  8138. unsigned int flags;
  8139. if (!(atomic_read(nohz_flags(this_cpu)) & NOHZ_KICK_MASK))
  8140. return false;
  8141. if (idle != CPU_IDLE) {
  8142. atomic_andnot(NOHZ_KICK_MASK, nohz_flags(this_cpu));
  8143. return false;
  8144. }
  8145. /*
  8146. * barrier, pairs with nohz_balance_enter_idle(), ensures ...
  8147. */
  8148. flags = atomic_fetch_andnot(NOHZ_KICK_MASK, nohz_flags(this_cpu));
  8149. if (!(flags & NOHZ_KICK_MASK))
  8150. return false;
  8151. _nohz_idle_balance(this_rq, flags, idle);
  8152. return true;
  8153. }
  8154. static void nohz_newidle_balance(struct rq *this_rq)
  8155. {
  8156. int this_cpu = this_rq->cpu;
  8157. /*
  8158. * This CPU doesn't want to be disturbed by scheduler
  8159. * housekeeping
  8160. */
  8161. if (!housekeeping_cpu(this_cpu, HK_FLAG_SCHED))
  8162. return;
  8163. /* Will wake up very soon. No time for doing anything else*/
  8164. if (this_rq->avg_idle < sysctl_sched_migration_cost)
  8165. return;
  8166. /* Don't need to update blocked load of idle CPUs*/
  8167. if (!READ_ONCE(nohz.has_blocked) ||
  8168. time_before(jiffies, READ_ONCE(nohz.next_blocked)))
  8169. return;
  8170. raw_spin_unlock(&this_rq->lock);
  8171. /*
  8172. * This CPU is going to be idle and blocked load of idle CPUs
  8173. * need to be updated. Run the ilb locally as it is a good
  8174. * candidate for ilb instead of waking up another idle CPU.
  8175. * Kick an normal ilb if we failed to do the update.
  8176. */
  8177. if (!_nohz_idle_balance(this_rq, NOHZ_STATS_KICK, CPU_NEWLY_IDLE))
  8178. kick_ilb(NOHZ_STATS_KICK);
  8179. raw_spin_lock(&this_rq->lock);
  8180. }
  8181. #else /* !CONFIG_NO_HZ_COMMON */
  8182. static inline void nohz_balancer_kick(struct rq *rq) { }
  8183. static inline bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
  8184. {
  8185. return false;
  8186. }
  8187. static inline void nohz_newidle_balance(struct rq *this_rq) { }
  8188. #endif /* CONFIG_NO_HZ_COMMON */
  8189. /*
  8190. * idle_balance is called by schedule() if this_cpu is about to become
  8191. * idle. Attempts to pull tasks from other CPUs.
  8192. */
  8193. static int idle_balance(struct rq *this_rq, struct rq_flags *rf)
  8194. {
  8195. unsigned long next_balance = jiffies + HZ;
  8196. int this_cpu = this_rq->cpu;
  8197. struct sched_domain *sd;
  8198. int pulled_task = 0;
  8199. u64 curr_cost = 0;
  8200. /*
  8201. * We must set idle_stamp _before_ calling idle_balance(), such that we
  8202. * measure the duration of idle_balance() as idle time.
  8203. */
  8204. this_rq->idle_stamp = rq_clock(this_rq);
  8205. /*
  8206. * Do not pull tasks towards !active CPUs...
  8207. */
  8208. if (!cpu_active(this_cpu))
  8209. return 0;
  8210. /*
  8211. * This is OK, because current is on_cpu, which avoids it being picked
  8212. * for load-balance and preemption/IRQs are still disabled avoiding
  8213. * further scheduler activity on it and we're being very careful to
  8214. * re-start the picking loop.
  8215. */
  8216. rq_unpin_lock(this_rq, rf);
  8217. if (this_rq->avg_idle < sysctl_sched_migration_cost ||
  8218. !this_rq->rd->overload) {
  8219. rcu_read_lock();
  8220. sd = rcu_dereference_check_sched_domain(this_rq->sd);
  8221. if (sd)
  8222. update_next_balance(sd, &next_balance);
  8223. rcu_read_unlock();
  8224. nohz_newidle_balance(this_rq);
  8225. goto out;
  8226. }
  8227. raw_spin_unlock(&this_rq->lock);
  8228. update_blocked_averages(this_cpu);
  8229. rcu_read_lock();
  8230. for_each_domain(this_cpu, sd) {
  8231. int continue_balancing = 1;
  8232. u64 t0, domain_cost;
  8233. if (!(sd->flags & SD_LOAD_BALANCE))
  8234. continue;
  8235. if (this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost) {
  8236. update_next_balance(sd, &next_balance);
  8237. break;
  8238. }
  8239. if (sd->flags & SD_BALANCE_NEWIDLE) {
  8240. t0 = sched_clock_cpu(this_cpu);
  8241. pulled_task = load_balance(this_cpu, this_rq,
  8242. sd, CPU_NEWLY_IDLE,
  8243. &continue_balancing);
  8244. domain_cost = sched_clock_cpu(this_cpu) - t0;
  8245. if (domain_cost > sd->max_newidle_lb_cost)
  8246. sd->max_newidle_lb_cost = domain_cost;
  8247. curr_cost += domain_cost;
  8248. }
  8249. update_next_balance(sd, &next_balance);
  8250. /*
  8251. * Stop searching for tasks to pull if there are
  8252. * now runnable tasks on this rq.
  8253. */
  8254. if (pulled_task || this_rq->nr_running > 0)
  8255. break;
  8256. }
  8257. rcu_read_unlock();
  8258. raw_spin_lock(&this_rq->lock);
  8259. if (curr_cost > this_rq->max_idle_balance_cost)
  8260. this_rq->max_idle_balance_cost = curr_cost;
  8261. out:
  8262. /*
  8263. * While browsing the domains, we released the rq lock, a task could
  8264. * have been enqueued in the meantime. Since we're not going idle,
  8265. * pretend we pulled a task.
  8266. */
  8267. if (this_rq->cfs.h_nr_running && !pulled_task)
  8268. pulled_task = 1;
  8269. /* Move the next balance forward */
  8270. if (time_after(this_rq->next_balance, next_balance))
  8271. this_rq->next_balance = next_balance;
  8272. /* Is there a task of a high priority class? */
  8273. if (this_rq->nr_running != this_rq->cfs.h_nr_running)
  8274. pulled_task = -1;
  8275. if (pulled_task)
  8276. this_rq->idle_stamp = 0;
  8277. rq_repin_lock(this_rq, rf);
  8278. return pulled_task;
  8279. }
  8280. /*
  8281. * run_rebalance_domains is triggered when needed from the scheduler tick.
  8282. * Also triggered for nohz idle balancing (with nohz_balancing_kick set).
  8283. */
  8284. static __latent_entropy void run_rebalance_domains(struct softirq_action *h)
  8285. {
  8286. struct rq *this_rq = this_rq();
  8287. enum cpu_idle_type idle = this_rq->idle_balance ?
  8288. CPU_IDLE : CPU_NOT_IDLE;
  8289. /*
  8290. * If this CPU has a pending nohz_balance_kick, then do the
  8291. * balancing on behalf of the other idle CPUs whose ticks are
  8292. * stopped. Do nohz_idle_balance *before* rebalance_domains to
  8293. * give the idle CPUs a chance to load balance. Else we may
  8294. * load balance only within the local sched_domain hierarchy
  8295. * and abort nohz_idle_balance altogether if we pull some load.
  8296. */
  8297. if (nohz_idle_balance(this_rq, idle))
  8298. return;
  8299. /* normal load balance */
  8300. update_blocked_averages(this_rq->cpu);
  8301. rebalance_domains(this_rq, idle);
  8302. }
  8303. /*
  8304. * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
  8305. */
  8306. void trigger_load_balance(struct rq *rq)
  8307. {
  8308. /* Don't need to rebalance while attached to NULL domain */
  8309. if (unlikely(on_null_domain(rq)))
  8310. return;
  8311. if (time_after_eq(jiffies, rq->next_balance))
  8312. raise_softirq(SCHED_SOFTIRQ);
  8313. nohz_balancer_kick(rq);
  8314. }
  8315. static void rq_online_fair(struct rq *rq)
  8316. {
  8317. update_sysctl();
  8318. update_runtime_enabled(rq);
  8319. }
  8320. static void rq_offline_fair(struct rq *rq)
  8321. {
  8322. update_sysctl();
  8323. /* Ensure any throttled groups are reachable by pick_next_task */
  8324. unthrottle_offline_cfs_rqs(rq);
  8325. }
  8326. #endif /* CONFIG_SMP */
  8327. /*
  8328. * scheduler tick hitting a task of our scheduling class.
  8329. *
  8330. * NOTE: This function can be called remotely by the tick offload that
  8331. * goes along full dynticks. Therefore no local assumption can be made
  8332. * and everything must be accessed through the @rq and @curr passed in
  8333. * parameters.
  8334. */
  8335. static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)
  8336. {
  8337. struct cfs_rq *cfs_rq;
  8338. struct sched_entity *se = &curr->se;
  8339. for_each_sched_entity(se) {
  8340. cfs_rq = cfs_rq_of(se);
  8341. entity_tick(cfs_rq, se, queued);
  8342. }
  8343. if (static_branch_unlikely(&sched_numa_balancing))
  8344. task_tick_numa(rq, curr);
  8345. }
  8346. /*
  8347. * called on fork with the child task as argument from the parent's context
  8348. * - child not yet on the tasklist
  8349. * - preemption disabled
  8350. */
  8351. static void task_fork_fair(struct task_struct *p)
  8352. {
  8353. struct cfs_rq *cfs_rq;
  8354. struct sched_entity *se = &p->se, *curr;
  8355. struct rq *rq = this_rq();
  8356. struct rq_flags rf;
  8357. rq_lock(rq, &rf);
  8358. update_rq_clock(rq);
  8359. cfs_rq = task_cfs_rq(current);
  8360. curr = cfs_rq->curr;
  8361. if (curr) {
  8362. update_curr(cfs_rq);
  8363. se->vruntime = curr->vruntime;
  8364. }
  8365. place_entity(cfs_rq, se, 1);
  8366. if (sysctl_sched_child_runs_first && curr && entity_before(curr, se)) {
  8367. /*
  8368. * Upon rescheduling, sched_class::put_prev_task() will place
  8369. * 'current' within the tree based on its new key value.
  8370. */
  8371. swap(curr->vruntime, se->vruntime);
  8372. resched_curr(rq);
  8373. }
  8374. se->vruntime -= cfs_rq->min_vruntime;
  8375. rq_unlock(rq, &rf);
  8376. }
  8377. /*
  8378. * Priority of the task has changed. Check to see if we preempt
  8379. * the current task.
  8380. */
  8381. static void
  8382. prio_changed_fair(struct rq *rq, struct task_struct *p, int oldprio)
  8383. {
  8384. if (!task_on_rq_queued(p))
  8385. return;
  8386. /*
  8387. * Reschedule if we are currently running on this runqueue and
  8388. * our priority decreased, or if we are not currently running on
  8389. * this runqueue and our priority is higher than the current's
  8390. */
  8391. if (rq->curr == p) {
  8392. if (p->prio > oldprio)
  8393. resched_curr(rq);
  8394. } else
  8395. check_preempt_curr(rq, p, 0);
  8396. }
  8397. static inline bool vruntime_normalized(struct task_struct *p)
  8398. {
  8399. struct sched_entity *se = &p->se;
  8400. /*
  8401. * In both the TASK_ON_RQ_QUEUED and TASK_ON_RQ_MIGRATING cases,
  8402. * the dequeue_entity(.flags=0) will already have normalized the
  8403. * vruntime.
  8404. */
  8405. if (p->on_rq)
  8406. return true;
  8407. /*
  8408. * When !on_rq, vruntime of the task has usually NOT been normalized.
  8409. * But there are some cases where it has already been normalized:
  8410. *
  8411. * - A forked child which is waiting for being woken up by
  8412. * wake_up_new_task().
  8413. * - A task which has been woken up by try_to_wake_up() and
  8414. * waiting for actually being woken up by sched_ttwu_pending().
  8415. */
  8416. if (!se->sum_exec_runtime || p->state == TASK_WAKING)
  8417. return true;
  8418. return false;
  8419. }
  8420. #ifdef CONFIG_FAIR_GROUP_SCHED
  8421. /*
  8422. * Propagate the changes of the sched_entity across the tg tree to make it
  8423. * visible to the root
  8424. */
  8425. static void propagate_entity_cfs_rq(struct sched_entity *se)
  8426. {
  8427. struct cfs_rq *cfs_rq;
  8428. /* Start to propagate at parent */
  8429. se = se->parent;
  8430. for_each_sched_entity(se) {
  8431. cfs_rq = cfs_rq_of(se);
  8432. if (cfs_rq_throttled(cfs_rq))
  8433. break;
  8434. update_load_avg(cfs_rq, se, UPDATE_TG);
  8435. }
  8436. }
  8437. #else
  8438. static void propagate_entity_cfs_rq(struct sched_entity *se) { }
  8439. #endif
  8440. static void detach_entity_cfs_rq(struct sched_entity *se)
  8441. {
  8442. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  8443. /* Catch up with the cfs_rq and remove our load when we leave */
  8444. update_load_avg(cfs_rq, se, 0);
  8445. detach_entity_load_avg(cfs_rq, se);
  8446. update_tg_load_avg(cfs_rq, false);
  8447. propagate_entity_cfs_rq(se);
  8448. }
  8449. static void attach_entity_cfs_rq(struct sched_entity *se)
  8450. {
  8451. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  8452. #ifdef CONFIG_FAIR_GROUP_SCHED
  8453. /*
  8454. * Since the real-depth could have been changed (only FAIR
  8455. * class maintain depth value), reset depth properly.
  8456. */
  8457. se->depth = se->parent ? se->parent->depth + 1 : 0;
  8458. #endif
  8459. /* Synchronize entity with its cfs_rq */
  8460. update_load_avg(cfs_rq, se, sched_feat(ATTACH_AGE_LOAD) ? 0 : SKIP_AGE_LOAD);
  8461. attach_entity_load_avg(cfs_rq, se, 0);
  8462. update_tg_load_avg(cfs_rq, false);
  8463. propagate_entity_cfs_rq(se);
  8464. }
  8465. static void detach_task_cfs_rq(struct task_struct *p)
  8466. {
  8467. struct sched_entity *se = &p->se;
  8468. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  8469. if (!vruntime_normalized(p)) {
  8470. /*
  8471. * Fix up our vruntime so that the current sleep doesn't
  8472. * cause 'unlimited' sleep bonus.
  8473. */
  8474. place_entity(cfs_rq, se, 0);
  8475. se->vruntime -= cfs_rq->min_vruntime;
  8476. }
  8477. detach_entity_cfs_rq(se);
  8478. }
  8479. static void attach_task_cfs_rq(struct task_struct *p)
  8480. {
  8481. struct sched_entity *se = &p->se;
  8482. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  8483. attach_entity_cfs_rq(se);
  8484. if (!vruntime_normalized(p))
  8485. se->vruntime += cfs_rq->min_vruntime;
  8486. }
  8487. static void switched_from_fair(struct rq *rq, struct task_struct *p)
  8488. {
  8489. detach_task_cfs_rq(p);
  8490. }
  8491. static void switched_to_fair(struct rq *rq, struct task_struct *p)
  8492. {
  8493. attach_task_cfs_rq(p);
  8494. if (task_on_rq_queued(p)) {
  8495. /*
  8496. * We were most likely switched from sched_rt, so
  8497. * kick off the schedule if running, otherwise just see
  8498. * if we can still preempt the current task.
  8499. */
  8500. if (rq->curr == p)
  8501. resched_curr(rq);
  8502. else
  8503. check_preempt_curr(rq, p, 0);
  8504. }
  8505. }
  8506. /* Account for a task changing its policy or group.
  8507. *
  8508. * This routine is mostly called to set cfs_rq->curr field when a task
  8509. * migrates between groups/classes.
  8510. */
  8511. static void set_curr_task_fair(struct rq *rq)
  8512. {
  8513. struct sched_entity *se = &rq->curr->se;
  8514. for_each_sched_entity(se) {
  8515. struct cfs_rq *cfs_rq = cfs_rq_of(se);
  8516. set_next_entity(cfs_rq, se);
  8517. /* ensure bandwidth has been allocated on our new cfs_rq */
  8518. account_cfs_rq_runtime(cfs_rq, 0);
  8519. }
  8520. }
  8521. void init_cfs_rq(struct cfs_rq *cfs_rq)
  8522. {
  8523. cfs_rq->tasks_timeline = RB_ROOT_CACHED;
  8524. cfs_rq->min_vruntime = (u64)(-(1LL << 20));
  8525. #ifndef CONFIG_64BIT
  8526. cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
  8527. #endif
  8528. #ifdef CONFIG_SMP
  8529. raw_spin_lock_init(&cfs_rq->removed.lock);
  8530. #endif
  8531. }
  8532. #ifdef CONFIG_FAIR_GROUP_SCHED
  8533. static void task_set_group_fair(struct task_struct *p)
  8534. {
  8535. struct sched_entity *se = &p->se;
  8536. set_task_rq(p, task_cpu(p));
  8537. se->depth = se->parent ? se->parent->depth + 1 : 0;
  8538. }
  8539. static void task_move_group_fair(struct task_struct *p)
  8540. {
  8541. detach_task_cfs_rq(p);
  8542. set_task_rq(p, task_cpu(p));
  8543. #ifdef CONFIG_SMP
  8544. /* Tell se's cfs_rq has been changed -- migrated */
  8545. p->se.avg.last_update_time = 0;
  8546. #endif
  8547. attach_task_cfs_rq(p);
  8548. }
  8549. static void task_change_group_fair(struct task_struct *p, int type)
  8550. {
  8551. switch (type) {
  8552. case TASK_SET_GROUP:
  8553. task_set_group_fair(p);
  8554. break;
  8555. case TASK_MOVE_GROUP:
  8556. task_move_group_fair(p);
  8557. break;
  8558. }
  8559. }
  8560. void free_fair_sched_group(struct task_group *tg)
  8561. {
  8562. int i;
  8563. destroy_cfs_bandwidth(tg_cfs_bandwidth(tg));
  8564. for_each_possible_cpu(i) {
  8565. if (tg->cfs_rq)
  8566. kfree(tg->cfs_rq[i]);
  8567. if (tg->se)
  8568. kfree(tg->se[i]);
  8569. }
  8570. kfree(tg->cfs_rq);
  8571. kfree(tg->se);
  8572. }
  8573. int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
  8574. {
  8575. struct sched_entity *se;
  8576. struct cfs_rq *cfs_rq;
  8577. int i;
  8578. tg->cfs_rq = kcalloc(nr_cpu_ids, sizeof(cfs_rq), GFP_KERNEL);
  8579. if (!tg->cfs_rq)
  8580. goto err;
  8581. tg->se = kcalloc(nr_cpu_ids, sizeof(se), GFP_KERNEL);
  8582. if (!tg->se)
  8583. goto err;
  8584. tg->shares = NICE_0_LOAD;
  8585. init_cfs_bandwidth(tg_cfs_bandwidth(tg));
  8586. for_each_possible_cpu(i) {
  8587. cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
  8588. GFP_KERNEL, cpu_to_node(i));
  8589. if (!cfs_rq)
  8590. goto err;
  8591. se = kzalloc_node(sizeof(struct sched_entity),
  8592. GFP_KERNEL, cpu_to_node(i));
  8593. if (!se)
  8594. goto err_free_rq;
  8595. init_cfs_rq(cfs_rq);
  8596. init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
  8597. init_entity_runnable_average(se);
  8598. }
  8599. return 1;
  8600. err_free_rq:
  8601. kfree(cfs_rq);
  8602. err:
  8603. return 0;
  8604. }
  8605. void online_fair_sched_group(struct task_group *tg)
  8606. {
  8607. struct sched_entity *se;
  8608. struct rq *rq;
  8609. int i;
  8610. for_each_possible_cpu(i) {
  8611. rq = cpu_rq(i);
  8612. se = tg->se[i];
  8613. raw_spin_lock_irq(&rq->lock);
  8614. update_rq_clock(rq);
  8615. attach_entity_cfs_rq(se);
  8616. sync_throttle(tg, i);
  8617. raw_spin_unlock_irq(&rq->lock);
  8618. }
  8619. }
  8620. void unregister_fair_sched_group(struct task_group *tg)
  8621. {
  8622. unsigned long flags;
  8623. struct rq *rq;
  8624. int cpu;
  8625. for_each_possible_cpu(cpu) {
  8626. if (tg->se[cpu])
  8627. remove_entity_load_avg(tg->se[cpu]);
  8628. /*
  8629. * Only empty task groups can be destroyed; so we can speculatively
  8630. * check on_list without danger of it being re-added.
  8631. */
  8632. if (!tg->cfs_rq[cpu]->on_list)
  8633. continue;
  8634. rq = cpu_rq(cpu);
  8635. raw_spin_lock_irqsave(&rq->lock, flags);
  8636. list_del_leaf_cfs_rq(tg->cfs_rq[cpu]);
  8637. raw_spin_unlock_irqrestore(&rq->lock, flags);
  8638. }
  8639. }
  8640. void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
  8641. struct sched_entity *se, int cpu,
  8642. struct sched_entity *parent)
  8643. {
  8644. struct rq *rq = cpu_rq(cpu);
  8645. cfs_rq->tg = tg;
  8646. cfs_rq->rq = rq;
  8647. init_cfs_rq_runtime(cfs_rq);
  8648. tg->cfs_rq[cpu] = cfs_rq;
  8649. tg->se[cpu] = se;
  8650. /* se could be NULL for root_task_group */
  8651. if (!se)
  8652. return;
  8653. if (!parent) {
  8654. se->cfs_rq = &rq->cfs;
  8655. se->depth = 0;
  8656. } else {
  8657. se->cfs_rq = parent->my_q;
  8658. se->depth = parent->depth + 1;
  8659. }
  8660. se->my_q = cfs_rq;
  8661. /* guarantee group entities always have weight */
  8662. update_load_set(&se->load, NICE_0_LOAD);
  8663. se->parent = parent;
  8664. }
  8665. static DEFINE_MUTEX(shares_mutex);
  8666. int sched_group_set_shares(struct task_group *tg, unsigned long shares)
  8667. {
  8668. int i;
  8669. /*
  8670. * We can't change the weight of the root cgroup.
  8671. */
  8672. if (!tg->se[0])
  8673. return -EINVAL;
  8674. shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
  8675. mutex_lock(&shares_mutex);
  8676. if (tg->shares == shares)
  8677. goto done;
  8678. tg->shares = shares;
  8679. for_each_possible_cpu(i) {
  8680. struct rq *rq = cpu_rq(i);
  8681. struct sched_entity *se = tg->se[i];
  8682. struct rq_flags rf;
  8683. /* Propagate contribution to hierarchy */
  8684. rq_lock_irqsave(rq, &rf);
  8685. update_rq_clock(rq);
  8686. for_each_sched_entity(se) {
  8687. update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
  8688. update_cfs_group(se);
  8689. }
  8690. rq_unlock_irqrestore(rq, &rf);
  8691. }
  8692. done:
  8693. mutex_unlock(&shares_mutex);
  8694. return 0;
  8695. }
  8696. #else /* CONFIG_FAIR_GROUP_SCHED */
  8697. void free_fair_sched_group(struct task_group *tg) { }
  8698. int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
  8699. {
  8700. return 1;
  8701. }
  8702. void online_fair_sched_group(struct task_group *tg) { }
  8703. void unregister_fair_sched_group(struct task_group *tg) { }
  8704. #endif /* CONFIG_FAIR_GROUP_SCHED */
  8705. static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task)
  8706. {
  8707. struct sched_entity *se = &task->se;
  8708. unsigned int rr_interval = 0;
  8709. /*
  8710. * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
  8711. * idle runqueue:
  8712. */
  8713. if (rq->cfs.load.weight)
  8714. rr_interval = NS_TO_JIFFIES(sched_slice(cfs_rq_of(se), se));
  8715. return rr_interval;
  8716. }
  8717. /*
  8718. * All the scheduling class methods:
  8719. */
  8720. const struct sched_class fair_sched_class = {
  8721. .next = &idle_sched_class,
  8722. .enqueue_task = enqueue_task_fair,
  8723. .dequeue_task = dequeue_task_fair,
  8724. .yield_task = yield_task_fair,
  8725. .yield_to_task = yield_to_task_fair,
  8726. .check_preempt_curr = check_preempt_wakeup,
  8727. .pick_next_task = pick_next_task_fair,
  8728. .put_prev_task = put_prev_task_fair,
  8729. #ifdef CONFIG_SMP
  8730. .select_task_rq = select_task_rq_fair,
  8731. .migrate_task_rq = migrate_task_rq_fair,
  8732. .rq_online = rq_online_fair,
  8733. .rq_offline = rq_offline_fair,
  8734. .task_dead = task_dead_fair,
  8735. .set_cpus_allowed = set_cpus_allowed_common,
  8736. #endif
  8737. .set_curr_task = set_curr_task_fair,
  8738. .task_tick = task_tick_fair,
  8739. .task_fork = task_fork_fair,
  8740. .prio_changed = prio_changed_fair,
  8741. .switched_from = switched_from_fair,
  8742. .switched_to = switched_to_fair,
  8743. .get_rr_interval = get_rr_interval_fair,
  8744. .update_curr = update_curr_fair,
  8745. #ifdef CONFIG_FAIR_GROUP_SCHED
  8746. .task_change_group = task_change_group_fair,
  8747. #endif
  8748. };
  8749. #ifdef CONFIG_SCHED_DEBUG
  8750. void print_cfs_stats(struct seq_file *m, int cpu)
  8751. {
  8752. struct cfs_rq *cfs_rq, *pos;
  8753. rcu_read_lock();
  8754. for_each_leaf_cfs_rq_safe(cpu_rq(cpu), cfs_rq, pos)
  8755. print_cfs_rq(m, cpu, cfs_rq);
  8756. rcu_read_unlock();
  8757. }
  8758. #ifdef CONFIG_NUMA_BALANCING
  8759. void show_numa_stats(struct task_struct *p, struct seq_file *m)
  8760. {
  8761. int node;
  8762. unsigned long tsf = 0, tpf = 0, gsf = 0, gpf = 0;
  8763. for_each_online_node(node) {
  8764. if (p->numa_faults) {
  8765. tsf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 0)];
  8766. tpf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 1)];
  8767. }
  8768. if (p->numa_group) {
  8769. gsf = p->numa_group->faults[task_faults_idx(NUMA_MEM, node, 0)],
  8770. gpf = p->numa_group->faults[task_faults_idx(NUMA_MEM, node, 1)];
  8771. }
  8772. print_numa_stats(m, node, tsf, tpf, gsf, gpf);
  8773. }
  8774. }
  8775. #endif /* CONFIG_NUMA_BALANCING */
  8776. #endif /* CONFIG_SCHED_DEBUG */
  8777. __init void init_sched_fair_class(void)
  8778. {
  8779. #ifdef CONFIG_SMP
  8780. open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
  8781. #ifdef CONFIG_NO_HZ_COMMON
  8782. nohz.next_balance = jiffies;
  8783. nohz.next_blocked = jiffies;
  8784. zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);
  8785. #endif
  8786. #endif /* SMP */
  8787. }