fair.c 247 KB

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