fair.c 206 KB

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