fair.c 231 KB

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