fair.c 212 KB

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