fair.c 188 KB

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