fair.c 198 KB

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