fair.c 189 KB

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