fair.c 221 KB

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