fair.c 171 KB

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