fair.c 188 KB

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