fair.c 202 KB

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