fair.c 182 KB

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