bfq-iosched.c 264 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682
  1. // SPDX-License-Identifier: GPL-2.0-or-later
  2. /*
  3. * Budget Fair Queueing (BFQ) I/O scheduler.
  4. *
  5. * Based on ideas and code from CFQ:
  6. * Copyright (C) 2003 Jens Axboe <axboe@kernel.dk>
  7. *
  8. * Copyright (C) 2008 Fabio Checconi <fabio@gandalf.sssup.it>
  9. * Paolo Valente <paolo.valente@unimore.it>
  10. *
  11. * Copyright (C) 2010 Paolo Valente <paolo.valente@unimore.it>
  12. * Arianna Avanzini <avanzini@google.com>
  13. *
  14. * Copyright (C) 2017 Paolo Valente <paolo.valente@linaro.org>
  15. *
  16. * BFQ is a proportional-share I/O scheduler, with some extra
  17. * low-latency capabilities. BFQ also supports full hierarchical
  18. * scheduling through cgroups. Next paragraphs provide an introduction
  19. * on BFQ inner workings. Details on BFQ benefits, usage and
  20. * limitations can be found in Documentation/block/bfq-iosched.rst.
  21. *
  22. * BFQ is a proportional-share storage-I/O scheduling algorithm based
  23. * on the slice-by-slice service scheme of CFQ. But BFQ assigns
  24. * budgets, measured in number of sectors, to processes instead of
  25. * time slices. The device is not granted to the in-service process
  26. * for a given time slice, but until it has exhausted its assigned
  27. * budget. This change from the time to the service domain enables BFQ
  28. * to distribute the device throughput among processes as desired,
  29. * without any distortion due to throughput fluctuations, or to device
  30. * internal queueing. BFQ uses an ad hoc internal scheduler, called
  31. * B-WF2Q+, to schedule processes according to their budgets. More
  32. * precisely, BFQ schedules queues associated with processes. Each
  33. * process/queue is assigned a user-configurable weight, and B-WF2Q+
  34. * guarantees that each queue receives a fraction of the throughput
  35. * proportional to its weight. Thanks to the accurate policy of
  36. * B-WF2Q+, BFQ can afford to assign high budgets to I/O-bound
  37. * processes issuing sequential requests (to boost the throughput),
  38. * and yet guarantee a low latency to interactive and soft real-time
  39. * applications.
  40. *
  41. * In particular, to provide these low-latency guarantees, BFQ
  42. * explicitly privileges the I/O of two classes of time-sensitive
  43. * applications: interactive and soft real-time. In more detail, BFQ
  44. * behaves this way if the low_latency parameter is set (default
  45. * configuration). This feature enables BFQ to provide applications in
  46. * these classes with a very low latency.
  47. *
  48. * To implement this feature, BFQ constantly tries to detect whether
  49. * the I/O requests in a bfq_queue come from an interactive or a soft
  50. * real-time application. For brevity, in these cases, the queue is
  51. * said to be interactive or soft real-time. In both cases, BFQ
  52. * privileges the service of the queue, over that of non-interactive
  53. * and non-soft-real-time queues. This privileging is performed,
  54. * mainly, by raising the weight of the queue. So, for brevity, we
  55. * call just weight-raising periods the time periods during which a
  56. * queue is privileged, because deemed interactive or soft real-time.
  57. *
  58. * The detection of soft real-time queues/applications is described in
  59. * detail in the comments on the function
  60. * bfq_bfqq_softrt_next_start. On the other hand, the detection of an
  61. * interactive queue works as follows: a queue is deemed interactive
  62. * if it is constantly non empty only for a limited time interval,
  63. * after which it does become empty. The queue may be deemed
  64. * interactive again (for a limited time), if it restarts being
  65. * constantly non empty, provided that this happens only after the
  66. * queue has remained empty for a given minimum idle time.
  67. *
  68. * By default, BFQ computes automatically the above maximum time
  69. * interval, i.e., the time interval after which a constantly
  70. * non-empty queue stops being deemed interactive. Since a queue is
  71. * weight-raised while it is deemed interactive, this maximum time
  72. * interval happens to coincide with the (maximum) duration of the
  73. * weight-raising for interactive queues.
  74. *
  75. * Finally, BFQ also features additional heuristics for
  76. * preserving both a low latency and a high throughput on NCQ-capable,
  77. * rotational or flash-based devices, and to get the job done quickly
  78. * for applications consisting in many I/O-bound processes.
  79. *
  80. * NOTE: if the main or only goal, with a given device, is to achieve
  81. * the maximum-possible throughput at all times, then do switch off
  82. * all low-latency heuristics for that device, by setting low_latency
  83. * to 0.
  84. *
  85. * BFQ is described in [1], where also a reference to the initial,
  86. * more theoretical paper on BFQ can be found. The interested reader
  87. * can find in the latter paper full details on the main algorithm, as
  88. * well as formulas of the guarantees and formal proofs of all the
  89. * properties. With respect to the version of BFQ presented in these
  90. * papers, this implementation adds a few more heuristics, such as the
  91. * ones that guarantee a low latency to interactive and soft real-time
  92. * applications, and a hierarchical extension based on H-WF2Q+.
  93. *
  94. * B-WF2Q+ is based on WF2Q+, which is described in [2], together with
  95. * H-WF2Q+, while the augmented tree used here to implement B-WF2Q+
  96. * with O(log N) complexity derives from the one introduced with EEVDF
  97. * in [3].
  98. *
  99. * [1] P. Valente, A. Avanzini, "Evolution of the BFQ Storage I/O
  100. * Scheduler", Proceedings of the First Workshop on Mobile System
  101. * Technologies (MST-2015), May 2015.
  102. * http://algogroup.unimore.it/people/paolo/disk_sched/mst-2015.pdf
  103. *
  104. * [2] Jon C.R. Bennett and H. Zhang, "Hierarchical Packet Fair Queueing
  105. * Algorithms", IEEE/ACM Transactions on Networking, 5(5):675-689,
  106. * Oct 1997.
  107. *
  108. * http://www.cs.cmu.edu/~hzhang/papers/TON-97-Oct.ps.gz
  109. *
  110. * [3] I. Stoica and H. Abdel-Wahab, "Earliest Eligible Virtual Deadline
  111. * First: A Flexible and Accurate Mechanism for Proportional Share
  112. * Resource Allocation", technical report.
  113. *
  114. * http://www.cs.berkeley.edu/~istoica/papers/eevdf-tr-95.pdf
  115. */
  116. #include <linux/module.h>
  117. #include <linux/slab.h>
  118. #include <linux/blkdev.h>
  119. #include <linux/cgroup.h>
  120. #include <linux/ktime.h>
  121. #include <linux/rbtree.h>
  122. #include <linux/ioprio.h>
  123. #include <linux/sbitmap.h>
  124. #include <linux/delay.h>
  125. #include <linux/backing-dev.h>
  126. #include <trace/events/block.h>
  127. #include "elevator.h"
  128. #include "blk.h"
  129. #include "blk-mq.h"
  130. #include "blk-mq-sched.h"
  131. #include "bfq-iosched.h"
  132. #include "blk-wbt.h"
  133. #define BFQ_BFQQ_FNS(name) \
  134. void bfq_mark_bfqq_##name(struct bfq_queue *bfqq) \
  135. { \
  136. __set_bit(BFQQF_##name, &(bfqq)->flags); \
  137. } \
  138. void bfq_clear_bfqq_##name(struct bfq_queue *bfqq) \
  139. { \
  140. __clear_bit(BFQQF_##name, &(bfqq)->flags); \
  141. } \
  142. int bfq_bfqq_##name(const struct bfq_queue *bfqq) \
  143. { \
  144. return test_bit(BFQQF_##name, &(bfqq)->flags); \
  145. }
  146. BFQ_BFQQ_FNS(just_created);
  147. BFQ_BFQQ_FNS(busy);
  148. BFQ_BFQQ_FNS(wait_request);
  149. BFQ_BFQQ_FNS(non_blocking_wait_rq);
  150. BFQ_BFQQ_FNS(fifo_expire);
  151. BFQ_BFQQ_FNS(has_short_ttime);
  152. BFQ_BFQQ_FNS(sync);
  153. BFQ_BFQQ_FNS(IO_bound);
  154. BFQ_BFQQ_FNS(in_large_burst);
  155. BFQ_BFQQ_FNS(coop);
  156. BFQ_BFQQ_FNS(split_coop);
  157. BFQ_BFQQ_FNS(softrt_update);
  158. #undef BFQ_BFQQ_FNS \
  159. /* Expiration time of async (0) and sync (1) requests, in ns. */
  160. static const u64 bfq_fifo_expire[2] = { NSEC_PER_SEC / 4, NSEC_PER_SEC / 8 };
  161. /* Maximum backwards seek (magic number lifted from CFQ), in KiB. */
  162. static const int bfq_back_max = 16 * 1024;
  163. /* Penalty of a backwards seek, in number of sectors. */
  164. static const int bfq_back_penalty = 2;
  165. /* Idling period duration, in ns. */
  166. static u64 bfq_slice_idle = NSEC_PER_SEC / 125;
  167. /* Minimum number of assigned budgets for which stats are safe to compute. */
  168. static const int bfq_stats_min_budgets = 194;
  169. /* Default maximum budget values, in sectors and number of requests. */
  170. static const int bfq_default_max_budget = 16 * 1024;
  171. /*
  172. * When a sync request is dispatched, the queue that contains that
  173. * request, and all the ancestor entities of that queue, are charged
  174. * with the number of sectors of the request. In contrast, if the
  175. * request is async, then the queue and its ancestor entities are
  176. * charged with the number of sectors of the request, multiplied by
  177. * the factor below. This throttles the bandwidth for async I/O,
  178. * w.r.t. to sync I/O, and it is done to counter the tendency of async
  179. * writes to steal I/O throughput to reads.
  180. *
  181. * The current value of this parameter is the result of a tuning with
  182. * several hardware and software configurations. We tried to find the
  183. * lowest value for which writes do not cause noticeable problems to
  184. * reads. In fact, the lower this parameter, the stabler I/O control,
  185. * in the following respect. The lower this parameter is, the less
  186. * the bandwidth enjoyed by a group decreases
  187. * - when the group does writes, w.r.t. to when it does reads;
  188. * - when other groups do reads, w.r.t. to when they do writes.
  189. */
  190. static const int bfq_async_charge_factor = 3;
  191. /* Default timeout values, in jiffies, approximating CFQ defaults. */
  192. const int bfq_timeout = HZ / 8;
  193. /*
  194. * Time limit for merging (see comments in bfq_setup_cooperator). Set
  195. * to the slowest value that, in our tests, proved to be effective in
  196. * removing false positives, while not causing true positives to miss
  197. * queue merging.
  198. *
  199. * As can be deduced from the low time limit below, queue merging, if
  200. * successful, happens at the very beginning of the I/O of the involved
  201. * cooperating processes, as a consequence of the arrival of the very
  202. * first requests from each cooperator. After that, there is very
  203. * little chance to find cooperators.
  204. */
  205. static const unsigned long bfq_merge_time_limit = HZ/10;
  206. static struct kmem_cache *bfq_pool;
  207. /* Below this threshold (in ns), we consider thinktime immediate. */
  208. #define BFQ_MIN_TT (2 * NSEC_PER_MSEC)
  209. /* hw_tag detection: parallel requests threshold and min samples needed. */
  210. #define BFQ_HW_QUEUE_THRESHOLD 3
  211. #define BFQ_HW_QUEUE_SAMPLES 32
  212. #define BFQQ_SEEK_THR (sector_t)(8 * 100)
  213. #define BFQQ_SECT_THR_NONROT (sector_t)(2 * 32)
  214. #define BFQ_RQ_SEEKY(bfqd, last_pos, rq) \
  215. (get_sdist(last_pos, rq) > \
  216. BFQQ_SEEK_THR && \
  217. (blk_queue_rot(bfqd->queue) || \
  218. blk_rq_sectors(rq) < BFQQ_SECT_THR_NONROT))
  219. #define BFQQ_CLOSE_THR (sector_t)(8 * 1024)
  220. #define BFQQ_SEEKY(bfqq) (hweight32(bfqq->seek_history) > 19)
  221. /*
  222. * Sync random I/O is likely to be confused with soft real-time I/O,
  223. * because it is characterized by limited throughput and apparently
  224. * isochronous arrival pattern. To avoid false positives, queues
  225. * containing only random (seeky) I/O are prevented from being tagged
  226. * as soft real-time.
  227. */
  228. #define BFQQ_TOTALLY_SEEKY(bfqq) (bfqq->seek_history == -1)
  229. /* Min number of samples required to perform peak-rate update */
  230. #define BFQ_RATE_MIN_SAMPLES 32
  231. /* Min observation time interval required to perform a peak-rate update (ns) */
  232. #define BFQ_RATE_MIN_INTERVAL (300*NSEC_PER_MSEC)
  233. /* Target observation time interval for a peak-rate update (ns) */
  234. #define BFQ_RATE_REF_INTERVAL NSEC_PER_SEC
  235. /*
  236. * Shift used for peak-rate fixed precision calculations.
  237. * With
  238. * - the current shift: 16 positions
  239. * - the current type used to store rate: u32
  240. * - the current unit of measure for rate: [sectors/usec], or, more precisely,
  241. * [(sectors/usec) / 2^BFQ_RATE_SHIFT] to take into account the shift,
  242. * the range of rates that can be stored is
  243. * [1 / 2^BFQ_RATE_SHIFT, 2^(32 - BFQ_RATE_SHIFT)] sectors/usec =
  244. * [1 / 2^16, 2^16] sectors/usec = [15e-6, 65536] sectors/usec =
  245. * [15, 65G] sectors/sec
  246. * Which, assuming a sector size of 512B, corresponds to a range of
  247. * [7.5K, 33T] B/sec
  248. */
  249. #define BFQ_RATE_SHIFT 16
  250. /*
  251. * When configured for computing the duration of the weight-raising
  252. * for interactive queues automatically (see the comments at the
  253. * beginning of this file), BFQ does it using the following formula:
  254. * duration = (ref_rate / r) * ref_wr_duration,
  255. * where r is the peak rate of the device, and ref_rate and
  256. * ref_wr_duration are two reference parameters. In particular,
  257. * ref_rate is the peak rate of the reference storage device (see
  258. * below), and ref_wr_duration is about the maximum time needed, with
  259. * BFQ and while reading two files in parallel, to load typical large
  260. * applications on the reference device (see the comments on
  261. * max_service_from_wr below, for more details on how ref_wr_duration
  262. * is obtained). In practice, the slower/faster the device at hand
  263. * is, the more/less it takes to load applications with respect to the
  264. * reference device. Accordingly, the longer/shorter BFQ grants
  265. * weight raising to interactive applications.
  266. *
  267. * BFQ uses two different reference pairs (ref_rate, ref_wr_duration),
  268. * depending on whether the device is rotational or non-rotational.
  269. *
  270. * In the following definitions, ref_rate[0] and ref_wr_duration[0]
  271. * are the reference values for a rotational device, whereas
  272. * ref_rate[1] and ref_wr_duration[1] are the reference values for a
  273. * non-rotational device. The reference rates are not the actual peak
  274. * rates of the devices used as a reference, but slightly lower
  275. * values. The reason for using slightly lower values is that the
  276. * peak-rate estimator tends to yield slightly lower values than the
  277. * actual peak rate (it can yield the actual peak rate only if there
  278. * is only one process doing I/O, and the process does sequential
  279. * I/O).
  280. *
  281. * The reference peak rates are measured in sectors/usec, left-shifted
  282. * by BFQ_RATE_SHIFT.
  283. */
  284. static int ref_rate[2] = {14000, 33000};
  285. /*
  286. * To improve readability, a conversion function is used to initialize
  287. * the following array, which entails that the array can be
  288. * initialized only in a function.
  289. */
  290. static int ref_wr_duration[2];
  291. /*
  292. * BFQ uses the above-detailed, time-based weight-raising mechanism to
  293. * privilege interactive tasks. This mechanism is vulnerable to the
  294. * following false positives: I/O-bound applications that will go on
  295. * doing I/O for much longer than the duration of weight
  296. * raising. These applications have basically no benefit from being
  297. * weight-raised at the beginning of their I/O. On the opposite end,
  298. * while being weight-raised, these applications
  299. * a) unjustly steal throughput to applications that may actually need
  300. * low latency;
  301. * b) make BFQ uselessly perform device idling; device idling results
  302. * in loss of device throughput with most flash-based storage, and may
  303. * increase latencies when used purposelessly.
  304. *
  305. * BFQ tries to reduce these problems, by adopting the following
  306. * countermeasure. To introduce this countermeasure, we need first to
  307. * finish explaining how the duration of weight-raising for
  308. * interactive tasks is computed.
  309. *
  310. * For a bfq_queue deemed as interactive, the duration of weight
  311. * raising is dynamically adjusted, as a function of the estimated
  312. * peak rate of the device, so as to be equal to the time needed to
  313. * execute the 'largest' interactive task we benchmarked so far. By
  314. * largest task, we mean the task for which each involved process has
  315. * to do more I/O than for any of the other tasks we benchmarked. This
  316. * reference interactive task is the start-up of LibreOffice Writer,
  317. * and in this task each process/bfq_queue needs to have at most ~110K
  318. * sectors transferred.
  319. *
  320. * This last piece of information enables BFQ to reduce the actual
  321. * duration of weight-raising for at least one class of I/O-bound
  322. * applications: those doing sequential or quasi-sequential I/O. An
  323. * example is file copy. In fact, once started, the main I/O-bound
  324. * processes of these applications usually consume the above 110K
  325. * sectors in much less time than the processes of an application that
  326. * is starting, because these I/O-bound processes will greedily devote
  327. * almost all their CPU cycles only to their target,
  328. * throughput-friendly I/O operations. This is even more true if BFQ
  329. * happens to be underestimating the device peak rate, and thus
  330. * overestimating the duration of weight raising. But, according to
  331. * our measurements, once transferred 110K sectors, these processes
  332. * have no right to be weight-raised any longer.
  333. *
  334. * Basing on the last consideration, BFQ ends weight-raising for a
  335. * bfq_queue if the latter happens to have received an amount of
  336. * service at least equal to the following constant. The constant is
  337. * set to slightly more than 110K, to have a minimum safety margin.
  338. *
  339. * This early ending of weight-raising reduces the amount of time
  340. * during which interactive false positives cause the two problems
  341. * described at the beginning of these comments.
  342. */
  343. static const unsigned long max_service_from_wr = 120000;
  344. /*
  345. * Maximum time between the creation of two queues, for stable merge
  346. * to be activated (in ms)
  347. */
  348. static const unsigned long bfq_activation_stable_merging = 600;
  349. /*
  350. * Minimum time to be waited before evaluating delayed stable merge (in ms)
  351. */
  352. static const unsigned long bfq_late_stable_merging = 600;
  353. #define RQ_BIC(rq) ((struct bfq_io_cq *)((rq)->elv.priv[0]))
  354. #define RQ_BFQQ(rq) ((rq)->elv.priv[1])
  355. struct bfq_queue *bic_to_bfqq(struct bfq_io_cq *bic, bool is_sync,
  356. unsigned int actuator_idx)
  357. {
  358. if (is_sync)
  359. return bic->bfqq[1][actuator_idx];
  360. return bic->bfqq[0][actuator_idx];
  361. }
  362. static void bfq_put_stable_ref(struct bfq_queue *bfqq);
  363. void bic_set_bfqq(struct bfq_io_cq *bic,
  364. struct bfq_queue *bfqq,
  365. bool is_sync,
  366. unsigned int actuator_idx)
  367. {
  368. struct bfq_queue *old_bfqq = bic->bfqq[is_sync][actuator_idx];
  369. /*
  370. * If bfqq != NULL, then a non-stable queue merge between
  371. * bic->bfqq and bfqq is happening here. This causes troubles
  372. * in the following case: bic->bfqq has also been scheduled
  373. * for a possible stable merge with bic->stable_merge_bfqq,
  374. * and bic->stable_merge_bfqq == bfqq happens to
  375. * hold. Troubles occur because bfqq may then undergo a split,
  376. * thereby becoming eligible for a stable merge. Yet, if
  377. * bic->stable_merge_bfqq points exactly to bfqq, then bfqq
  378. * would be stably merged with itself. To avoid this anomaly,
  379. * we cancel the stable merge if
  380. * bic->stable_merge_bfqq == bfqq.
  381. */
  382. struct bfq_iocq_bfqq_data *bfqq_data = &bic->bfqq_data[actuator_idx];
  383. /* Clear bic pointer if bfqq is detached from this bic */
  384. if (old_bfqq && old_bfqq->bic == bic)
  385. old_bfqq->bic = NULL;
  386. if (is_sync)
  387. bic->bfqq[1][actuator_idx] = bfqq;
  388. else
  389. bic->bfqq[0][actuator_idx] = bfqq;
  390. if (bfqq && bfqq_data->stable_merge_bfqq == bfqq) {
  391. /*
  392. * Actually, these same instructions are executed also
  393. * in bfq_setup_cooperator, in case of abort or actual
  394. * execution of a stable merge. We could avoid
  395. * repeating these instructions there too, but if we
  396. * did so, we would nest even more complexity in this
  397. * function.
  398. */
  399. bfq_put_stable_ref(bfqq_data->stable_merge_bfqq);
  400. bfqq_data->stable_merge_bfqq = NULL;
  401. }
  402. }
  403. struct bfq_data *bic_to_bfqd(struct bfq_io_cq *bic)
  404. {
  405. return bic->icq.q->elevator->elevator_data;
  406. }
  407. /**
  408. * icq_to_bic - convert iocontext queue structure to bfq_io_cq.
  409. * @icq: the iocontext queue.
  410. */
  411. static struct bfq_io_cq *icq_to_bic(struct io_cq *icq)
  412. {
  413. /* bic->icq is the first member, %NULL will convert to %NULL */
  414. return container_of(icq, struct bfq_io_cq, icq);
  415. }
  416. /**
  417. * bfq_bic_lookup - search into @ioc a bic associated to @bfqd.
  418. * @q: the request queue.
  419. */
  420. static struct bfq_io_cq *bfq_bic_lookup(struct request_queue *q)
  421. {
  422. if (!current->io_context)
  423. return NULL;
  424. return icq_to_bic(ioc_lookup_icq(q));
  425. }
  426. /*
  427. * Scheduler run of queue, if there are requests pending and no one in the
  428. * driver that will restart queueing.
  429. */
  430. void bfq_schedule_dispatch(struct bfq_data *bfqd)
  431. {
  432. lockdep_assert_held(&bfqd->lock);
  433. if (bfqd->queued != 0) {
  434. bfq_log(bfqd, "schedule dispatch");
  435. blk_mq_run_hw_queues(bfqd->queue, true);
  436. }
  437. }
  438. #define bfq_class_idle(bfqq) ((bfqq)->ioprio_class == IOPRIO_CLASS_IDLE)
  439. #define bfq_sample_valid(samples) ((samples) > 80)
  440. /*
  441. * Lifted from AS - choose which of rq1 and rq2 that is best served now.
  442. * We choose the request that is closer to the head right now. Distance
  443. * behind the head is penalized and only allowed to a certain extent.
  444. */
  445. static struct request *bfq_choose_req(struct bfq_data *bfqd,
  446. struct request *rq1,
  447. struct request *rq2,
  448. sector_t last)
  449. {
  450. sector_t s1, s2, d1 = 0, d2 = 0;
  451. unsigned long back_max;
  452. #define BFQ_RQ1_WRAP 0x01 /* request 1 wraps */
  453. #define BFQ_RQ2_WRAP 0x02 /* request 2 wraps */
  454. unsigned int wrap = 0; /* bit mask: requests behind the disk head? */
  455. if (!rq1 || rq1 == rq2)
  456. return rq2;
  457. if (!rq2)
  458. return rq1;
  459. if (rq_is_sync(rq1) && !rq_is_sync(rq2))
  460. return rq1;
  461. else if (rq_is_sync(rq2) && !rq_is_sync(rq1))
  462. return rq2;
  463. if ((rq1->cmd_flags & REQ_META) && !(rq2->cmd_flags & REQ_META))
  464. return rq1;
  465. else if ((rq2->cmd_flags & REQ_META) && !(rq1->cmd_flags & REQ_META))
  466. return rq2;
  467. s1 = blk_rq_pos(rq1);
  468. s2 = blk_rq_pos(rq2);
  469. /*
  470. * By definition, 1KiB is 2 sectors.
  471. */
  472. back_max = bfqd->bfq_back_max * 2;
  473. /*
  474. * Strict one way elevator _except_ in the case where we allow
  475. * short backward seeks which are biased as twice the cost of a
  476. * similar forward seek.
  477. */
  478. if (s1 >= last)
  479. d1 = s1 - last;
  480. else if (s1 + back_max >= last)
  481. d1 = (last - s1) * bfqd->bfq_back_penalty;
  482. else
  483. wrap |= BFQ_RQ1_WRAP;
  484. if (s2 >= last)
  485. d2 = s2 - last;
  486. else if (s2 + back_max >= last)
  487. d2 = (last - s2) * bfqd->bfq_back_penalty;
  488. else
  489. wrap |= BFQ_RQ2_WRAP;
  490. /* Found required data */
  491. /*
  492. * By doing switch() on the bit mask "wrap" we avoid having to
  493. * check two variables for all permutations: --> faster!
  494. */
  495. switch (wrap) {
  496. case 0: /* common case for CFQ: rq1 and rq2 not wrapped */
  497. if (d1 < d2)
  498. return rq1;
  499. else if (d2 < d1)
  500. return rq2;
  501. if (s1 >= s2)
  502. return rq1;
  503. else
  504. return rq2;
  505. case BFQ_RQ2_WRAP:
  506. return rq1;
  507. case BFQ_RQ1_WRAP:
  508. return rq2;
  509. case BFQ_RQ1_WRAP|BFQ_RQ2_WRAP: /* both rqs wrapped */
  510. default:
  511. /*
  512. * Since both rqs are wrapped,
  513. * start with the one that's further behind head
  514. * (--> only *one* back seek required),
  515. * since back seek takes more time than forward.
  516. */
  517. if (s1 <= s2)
  518. return rq1;
  519. else
  520. return rq2;
  521. }
  522. }
  523. #define BFQ_LIMIT_INLINE_DEPTH 16
  524. #ifdef CONFIG_BFQ_GROUP_IOSCHED
  525. static bool bfqq_request_over_limit(struct bfq_data *bfqd,
  526. struct bfq_io_cq *bic, blk_opf_t opf,
  527. unsigned int act_idx, int limit)
  528. {
  529. struct bfq_entity *inline_entities[BFQ_LIMIT_INLINE_DEPTH];
  530. struct bfq_entity **entities = inline_entities;
  531. int alloc_depth = BFQ_LIMIT_INLINE_DEPTH;
  532. struct bfq_sched_data *sched_data;
  533. struct bfq_entity *entity;
  534. struct bfq_queue *bfqq;
  535. unsigned long wsum;
  536. bool ret = false;
  537. int depth;
  538. int level;
  539. retry:
  540. spin_lock_irq(&bfqd->lock);
  541. bfqq = bic_to_bfqq(bic, op_is_sync(opf), act_idx);
  542. if (!bfqq)
  543. goto out;
  544. entity = &bfqq->entity;
  545. if (!entity->on_st_or_in_serv)
  546. goto out;
  547. /* +1 for bfqq entity, root cgroup not included */
  548. depth = bfqg_to_blkg(bfqq_group(bfqq))->blkcg->css.cgroup->level + 1;
  549. if (depth > alloc_depth) {
  550. spin_unlock_irq(&bfqd->lock);
  551. if (entities != inline_entities)
  552. kfree(entities);
  553. entities = kmalloc_objs(*entities, depth, GFP_NOIO);
  554. if (!entities)
  555. return false;
  556. alloc_depth = depth;
  557. goto retry;
  558. }
  559. sched_data = entity->sched_data;
  560. /* Gather our ancestors as we need to traverse them in reverse order */
  561. level = 0;
  562. for_each_entity(entity) {
  563. /*
  564. * If at some level entity is not even active, allow request
  565. * queueing so that BFQ knows there's work to do and activate
  566. * entities.
  567. */
  568. if (!entity->on_st_or_in_serv)
  569. goto out;
  570. /* Uh, more parents than cgroup subsystem thinks? */
  571. if (WARN_ON_ONCE(level >= depth))
  572. break;
  573. entities[level++] = entity;
  574. }
  575. WARN_ON_ONCE(level != depth);
  576. for (level--; level >= 0; level--) {
  577. entity = entities[level];
  578. if (level > 0) {
  579. wsum = bfq_entity_service_tree(entity)->wsum;
  580. } else {
  581. int i;
  582. /*
  583. * For bfqq itself we take into account service trees
  584. * of all higher priority classes and multiply their
  585. * weights so that low prio queue from higher class
  586. * gets more requests than high prio queue from lower
  587. * class.
  588. */
  589. wsum = 0;
  590. for (i = 0; i <= bfqq->ioprio_class - 1; i++) {
  591. wsum = wsum * IOPRIO_BE_NR +
  592. sched_data->service_tree[i].wsum;
  593. }
  594. }
  595. if (!wsum)
  596. continue;
  597. limit = DIV_ROUND_CLOSEST(limit * entity->weight, wsum);
  598. if (entity->allocated >= limit) {
  599. bfq_log_bfqq(bfqq->bfqd, bfqq,
  600. "too many requests: allocated %d limit %d level %d",
  601. entity->allocated, limit, level);
  602. ret = true;
  603. break;
  604. }
  605. }
  606. out:
  607. spin_unlock_irq(&bfqd->lock);
  608. if (entities != inline_entities)
  609. kfree(entities);
  610. return ret;
  611. }
  612. #else
  613. static bool bfqq_request_over_limit(struct bfq_data *bfqd,
  614. struct bfq_io_cq *bic, blk_opf_t opf,
  615. unsigned int act_idx, int limit)
  616. {
  617. return false;
  618. }
  619. #endif
  620. /*
  621. * Async I/O can easily starve sync I/O (both sync reads and sync
  622. * writes), by consuming all tags. Similarly, storms of sync writes,
  623. * such as those that sync(2) may trigger, can starve sync reads.
  624. * Limit depths of async I/O and sync writes so as to counter both
  625. * problems.
  626. *
  627. * Also if a bfq queue or its parent cgroup consume more tags than would be
  628. * appropriate for their weight, we trim the available tag depth to 1. This
  629. * avoids a situation where one cgroup can starve another cgroup from tags and
  630. * thus block service differentiation among cgroups. Note that because the
  631. * queue / cgroup already has many requests allocated and queued, this does not
  632. * significantly affect service guarantees coming from the BFQ scheduling
  633. * algorithm.
  634. */
  635. static void bfq_limit_depth(blk_opf_t opf, struct blk_mq_alloc_data *data)
  636. {
  637. struct bfq_data *bfqd = data->q->elevator->elevator_data;
  638. struct bfq_io_cq *bic = bfq_bic_lookup(data->q);
  639. unsigned int limit, act_idx;
  640. /* Sync reads have full depth available */
  641. if (blk_mq_is_sync_read(opf))
  642. limit = data->q->nr_requests;
  643. else
  644. limit = bfqd->async_depths[!!bfqd->wr_busy_queues][op_is_sync(opf)];
  645. for (act_idx = 0; bic && act_idx < bfqd->num_actuators; act_idx++) {
  646. /* Fast path to check if bfqq is already allocated. */
  647. if (!bic_to_bfqq(bic, op_is_sync(opf), act_idx))
  648. continue;
  649. /*
  650. * Does queue (or any parent entity) exceed number of
  651. * requests that should be available to it? Heavily
  652. * limit depth so that it cannot consume more
  653. * available requests and thus starve other entities.
  654. */
  655. if (bfqq_request_over_limit(bfqd, bic, opf, act_idx, limit)) {
  656. limit = 1;
  657. break;
  658. }
  659. }
  660. bfq_log(bfqd, "[%s] wr_busy %d sync %d depth %u",
  661. __func__, bfqd->wr_busy_queues, op_is_sync(opf), limit);
  662. if (limit < data->q->nr_requests)
  663. data->shallow_depth = limit;
  664. }
  665. static struct bfq_queue *
  666. bfq_rq_pos_tree_lookup(struct bfq_data *bfqd, struct rb_root *root,
  667. sector_t sector, struct rb_node **ret_parent,
  668. struct rb_node ***rb_link)
  669. {
  670. struct rb_node **p, *parent;
  671. struct bfq_queue *bfqq = NULL;
  672. parent = NULL;
  673. p = &root->rb_node;
  674. while (*p) {
  675. struct rb_node **n;
  676. parent = *p;
  677. bfqq = rb_entry(parent, struct bfq_queue, pos_node);
  678. /*
  679. * Sort strictly based on sector. Smallest to the left,
  680. * largest to the right.
  681. */
  682. if (sector > blk_rq_pos(bfqq->next_rq))
  683. n = &(*p)->rb_right;
  684. else if (sector < blk_rq_pos(bfqq->next_rq))
  685. n = &(*p)->rb_left;
  686. else
  687. break;
  688. p = n;
  689. bfqq = NULL;
  690. }
  691. *ret_parent = parent;
  692. if (rb_link)
  693. *rb_link = p;
  694. bfq_log(bfqd, "rq_pos_tree_lookup %llu: returning %d",
  695. (unsigned long long)sector,
  696. bfqq ? bfqq->pid : 0);
  697. return bfqq;
  698. }
  699. static bool bfq_too_late_for_merging(struct bfq_queue *bfqq)
  700. {
  701. return bfqq->service_from_backlogged > 0 &&
  702. time_is_before_jiffies(bfqq->first_IO_time +
  703. bfq_merge_time_limit);
  704. }
  705. /*
  706. * The following function is not marked as __cold because it is
  707. * actually cold, but for the same performance goal described in the
  708. * comments on the likely() at the beginning of
  709. * bfq_setup_cooperator(). Unexpectedly, to reach an even lower
  710. * execution time for the case where this function is not invoked, we
  711. * had to add an unlikely() in each involved if().
  712. */
  713. void __cold
  714. bfq_pos_tree_add_move(struct bfq_data *bfqd, struct bfq_queue *bfqq)
  715. {
  716. struct rb_node **p, *parent;
  717. struct bfq_queue *__bfqq;
  718. if (bfqq->pos_root) {
  719. rb_erase(&bfqq->pos_node, bfqq->pos_root);
  720. bfqq->pos_root = NULL;
  721. }
  722. /* oom_bfqq does not participate in queue merging */
  723. if (bfqq == &bfqd->oom_bfqq)
  724. return;
  725. /*
  726. * bfqq cannot be merged any longer (see comments in
  727. * bfq_setup_cooperator): no point in adding bfqq into the
  728. * position tree.
  729. */
  730. if (bfq_too_late_for_merging(bfqq))
  731. return;
  732. if (bfq_class_idle(bfqq))
  733. return;
  734. if (!bfqq->next_rq)
  735. return;
  736. bfqq->pos_root = &bfqq_group(bfqq)->rq_pos_tree;
  737. __bfqq = bfq_rq_pos_tree_lookup(bfqd, bfqq->pos_root,
  738. blk_rq_pos(bfqq->next_rq), &parent, &p);
  739. if (!__bfqq) {
  740. rb_link_node(&bfqq->pos_node, parent, p);
  741. rb_insert_color(&bfqq->pos_node, bfqq->pos_root);
  742. } else
  743. bfqq->pos_root = NULL;
  744. }
  745. /*
  746. * The following function returns false either if every active queue
  747. * must receive the same share of the throughput (symmetric scenario),
  748. * or, as a special case, if bfqq must receive a share of the
  749. * throughput lower than or equal to the share that every other active
  750. * queue must receive. If bfqq does sync I/O, then these are the only
  751. * two cases where bfqq happens to be guaranteed its share of the
  752. * throughput even if I/O dispatching is not plugged when bfqq remains
  753. * temporarily empty (for more details, see the comments in the
  754. * function bfq_better_to_idle()). For this reason, the return value
  755. * of this function is used to check whether I/O-dispatch plugging can
  756. * be avoided.
  757. *
  758. * The above first case (symmetric scenario) occurs when:
  759. * 1) all active queues have the same weight,
  760. * 2) all active queues belong to the same I/O-priority class,
  761. * 3) all active groups at the same level in the groups tree have the same
  762. * weight,
  763. * 4) all active groups at the same level in the groups tree have the same
  764. * number of children.
  765. *
  766. * Unfortunately, keeping the necessary state for evaluating exactly
  767. * the last two symmetry sub-conditions above would be quite complex
  768. * and time consuming. Therefore this function evaluates, instead,
  769. * only the following stronger three sub-conditions, for which it is
  770. * much easier to maintain the needed state:
  771. * 1) all active queues have the same weight,
  772. * 2) all active queues belong to the same I/O-priority class,
  773. * 3) there is at most one active group.
  774. * In particular, the last condition is always true if hierarchical
  775. * support or the cgroups interface are not enabled, thus no state
  776. * needs to be maintained in this case.
  777. */
  778. static bool bfq_asymmetric_scenario(struct bfq_data *bfqd,
  779. struct bfq_queue *bfqq)
  780. {
  781. bool smallest_weight = bfqq &&
  782. bfqq->weight_counter &&
  783. bfqq->weight_counter ==
  784. container_of(
  785. rb_first_cached(&bfqd->queue_weights_tree),
  786. struct bfq_weight_counter,
  787. weights_node);
  788. /*
  789. * For queue weights to differ, queue_weights_tree must contain
  790. * at least two nodes.
  791. */
  792. bool varied_queue_weights = !smallest_weight &&
  793. !RB_EMPTY_ROOT(&bfqd->queue_weights_tree.rb_root) &&
  794. (bfqd->queue_weights_tree.rb_root.rb_node->rb_left ||
  795. bfqd->queue_weights_tree.rb_root.rb_node->rb_right);
  796. bool multiple_classes_busy =
  797. (bfqd->busy_queues[0] && bfqd->busy_queues[1]) ||
  798. (bfqd->busy_queues[0] && bfqd->busy_queues[2]) ||
  799. (bfqd->busy_queues[1] && bfqd->busy_queues[2]);
  800. return varied_queue_weights || multiple_classes_busy
  801. #ifdef CONFIG_BFQ_GROUP_IOSCHED
  802. || bfqd->num_groups_with_pending_reqs > 1
  803. #endif
  804. ;
  805. }
  806. /*
  807. * If the weight-counter tree passed as input contains no counter for
  808. * the weight of the input queue, then add that counter; otherwise just
  809. * increment the existing counter.
  810. *
  811. * Note that weight-counter trees contain few nodes in mostly symmetric
  812. * scenarios. For example, if all queues have the same weight, then the
  813. * weight-counter tree for the queues may contain at most one node.
  814. * This holds even if low_latency is on, because weight-raised queues
  815. * are not inserted in the tree.
  816. * In most scenarios, the rate at which nodes are created/destroyed
  817. * should be low too.
  818. */
  819. void bfq_weights_tree_add(struct bfq_queue *bfqq)
  820. {
  821. struct rb_root_cached *root = &bfqq->bfqd->queue_weights_tree;
  822. struct bfq_entity *entity = &bfqq->entity;
  823. struct rb_node **new = &(root->rb_root.rb_node), *parent = NULL;
  824. bool leftmost = true;
  825. /*
  826. * Do not insert if the queue is already associated with a
  827. * counter, which happens if:
  828. * 1) a request arrival has caused the queue to become both
  829. * non-weight-raised, and hence change its weight, and
  830. * backlogged; in this respect, each of the two events
  831. * causes an invocation of this function,
  832. * 2) this is the invocation of this function caused by the
  833. * second event. This second invocation is actually useless,
  834. * and we handle this fact by exiting immediately. More
  835. * efficient or clearer solutions might possibly be adopted.
  836. */
  837. if (bfqq->weight_counter)
  838. return;
  839. while (*new) {
  840. struct bfq_weight_counter *__counter = container_of(*new,
  841. struct bfq_weight_counter,
  842. weights_node);
  843. parent = *new;
  844. if (entity->weight == __counter->weight) {
  845. bfqq->weight_counter = __counter;
  846. goto inc_counter;
  847. }
  848. if (entity->weight < __counter->weight)
  849. new = &((*new)->rb_left);
  850. else {
  851. new = &((*new)->rb_right);
  852. leftmost = false;
  853. }
  854. }
  855. bfqq->weight_counter = kzalloc_obj(struct bfq_weight_counter,
  856. GFP_ATOMIC);
  857. /*
  858. * In the unlucky event of an allocation failure, we just
  859. * exit. This will cause the weight of queue to not be
  860. * considered in bfq_asymmetric_scenario, which, in its turn,
  861. * causes the scenario to be deemed wrongly symmetric in case
  862. * bfqq's weight would have been the only weight making the
  863. * scenario asymmetric. On the bright side, no unbalance will
  864. * however occur when bfqq becomes inactive again (the
  865. * invocation of this function is triggered by an activation
  866. * of queue). In fact, bfq_weights_tree_remove does nothing
  867. * if !bfqq->weight_counter.
  868. */
  869. if (unlikely(!bfqq->weight_counter))
  870. return;
  871. bfqq->weight_counter->weight = entity->weight;
  872. rb_link_node(&bfqq->weight_counter->weights_node, parent, new);
  873. rb_insert_color_cached(&bfqq->weight_counter->weights_node, root,
  874. leftmost);
  875. inc_counter:
  876. bfqq->weight_counter->num_active++;
  877. bfqq->ref++;
  878. }
  879. /*
  880. * Decrement the weight counter associated with the queue, and, if the
  881. * counter reaches 0, remove the counter from the tree.
  882. * See the comments to the function bfq_weights_tree_add() for considerations
  883. * about overhead.
  884. */
  885. void bfq_weights_tree_remove(struct bfq_queue *bfqq)
  886. {
  887. struct rb_root_cached *root;
  888. if (!bfqq->weight_counter)
  889. return;
  890. root = &bfqq->bfqd->queue_weights_tree;
  891. bfqq->weight_counter->num_active--;
  892. if (bfqq->weight_counter->num_active > 0)
  893. goto reset_entity_pointer;
  894. rb_erase_cached(&bfqq->weight_counter->weights_node, root);
  895. kfree(bfqq->weight_counter);
  896. reset_entity_pointer:
  897. bfqq->weight_counter = NULL;
  898. bfq_put_queue(bfqq);
  899. }
  900. /*
  901. * Return expired entry, or NULL to just start from scratch in rbtree.
  902. */
  903. static struct request *bfq_check_fifo(struct bfq_queue *bfqq,
  904. struct request *last)
  905. {
  906. struct request *rq;
  907. if (bfq_bfqq_fifo_expire(bfqq))
  908. return NULL;
  909. bfq_mark_bfqq_fifo_expire(bfqq);
  910. rq = rq_entry_fifo(bfqq->fifo.next);
  911. if (rq == last || blk_time_get_ns() < rq->fifo_time)
  912. return NULL;
  913. bfq_log_bfqq(bfqq->bfqd, bfqq, "check_fifo: returned %p", rq);
  914. return rq;
  915. }
  916. static struct request *bfq_find_next_rq(struct bfq_data *bfqd,
  917. struct bfq_queue *bfqq,
  918. struct request *last)
  919. {
  920. struct rb_node *rbnext = rb_next(&last->rb_node);
  921. struct rb_node *rbprev = rb_prev(&last->rb_node);
  922. struct request *next, *prev = NULL;
  923. /* Follow expired path, else get first next available. */
  924. next = bfq_check_fifo(bfqq, last);
  925. if (next)
  926. return next;
  927. if (rbprev)
  928. prev = rb_entry_rq(rbprev);
  929. if (rbnext)
  930. next = rb_entry_rq(rbnext);
  931. else {
  932. rbnext = rb_first(&bfqq->sort_list);
  933. if (rbnext && rbnext != &last->rb_node)
  934. next = rb_entry_rq(rbnext);
  935. }
  936. return bfq_choose_req(bfqd, next, prev, blk_rq_pos(last));
  937. }
  938. /* see the definition of bfq_async_charge_factor for details */
  939. static unsigned long bfq_serv_to_charge(struct request *rq,
  940. struct bfq_queue *bfqq)
  941. {
  942. if (bfq_bfqq_sync(bfqq) || bfqq->wr_coeff > 1 ||
  943. bfq_asymmetric_scenario(bfqq->bfqd, bfqq))
  944. return blk_rq_sectors(rq);
  945. return blk_rq_sectors(rq) * bfq_async_charge_factor;
  946. }
  947. /**
  948. * bfq_updated_next_req - update the queue after a new next_rq selection.
  949. * @bfqd: the device data the queue belongs to.
  950. * @bfqq: the queue to update.
  951. *
  952. * If the first request of a queue changes we make sure that the queue
  953. * has enough budget to serve at least its first request (if the
  954. * request has grown). We do this because if the queue has not enough
  955. * budget for its first request, it has to go through two dispatch
  956. * rounds to actually get it dispatched.
  957. */
  958. static void bfq_updated_next_req(struct bfq_data *bfqd,
  959. struct bfq_queue *bfqq)
  960. {
  961. struct bfq_entity *entity = &bfqq->entity;
  962. struct request *next_rq = bfqq->next_rq;
  963. unsigned long new_budget;
  964. if (!next_rq)
  965. return;
  966. if (bfqq == bfqd->in_service_queue)
  967. /*
  968. * In order not to break guarantees, budgets cannot be
  969. * changed after an entity has been selected.
  970. */
  971. return;
  972. new_budget = max_t(unsigned long,
  973. max_t(unsigned long, bfqq->max_budget,
  974. bfq_serv_to_charge(next_rq, bfqq)),
  975. entity->service);
  976. if (entity->budget != new_budget) {
  977. entity->budget = new_budget;
  978. bfq_log_bfqq(bfqd, bfqq, "updated next rq: new budget %lu",
  979. new_budget);
  980. bfq_requeue_bfqq(bfqd, bfqq, false);
  981. }
  982. }
  983. static unsigned int bfq_wr_duration(struct bfq_data *bfqd)
  984. {
  985. u64 dur;
  986. dur = bfqd->rate_dur_prod;
  987. do_div(dur, bfqd->peak_rate);
  988. /*
  989. * Limit duration between 3 and 25 seconds. The upper limit
  990. * has been conservatively set after the following worst case:
  991. * on a QEMU/KVM virtual machine
  992. * - running in a slow PC
  993. * - with a virtual disk stacked on a slow low-end 5400rpm HDD
  994. * - serving a heavy I/O workload, such as the sequential reading
  995. * of several files
  996. * mplayer took 23 seconds to start, if constantly weight-raised.
  997. *
  998. * As for higher values than that accommodating the above bad
  999. * scenario, tests show that higher values would often yield
  1000. * the opposite of the desired result, i.e., would worsen
  1001. * responsiveness by allowing non-interactive applications to
  1002. * preserve weight raising for too long.
  1003. *
  1004. * On the other end, lower values than 3 seconds make it
  1005. * difficult for most interactive tasks to complete their jobs
  1006. * before weight-raising finishes.
  1007. */
  1008. return clamp_val(dur, msecs_to_jiffies(3000), msecs_to_jiffies(25000));
  1009. }
  1010. /* switch back from soft real-time to interactive weight raising */
  1011. static void switch_back_to_interactive_wr(struct bfq_queue *bfqq,
  1012. struct bfq_data *bfqd)
  1013. {
  1014. bfqq->wr_coeff = bfqd->bfq_wr_coeff;
  1015. bfqq->wr_cur_max_time = bfq_wr_duration(bfqd);
  1016. bfqq->last_wr_start_finish = bfqq->wr_start_at_switch_to_srt;
  1017. }
  1018. static void
  1019. bfq_bfqq_resume_state(struct bfq_queue *bfqq, struct bfq_data *bfqd,
  1020. struct bfq_io_cq *bic, bool bfq_already_existing)
  1021. {
  1022. unsigned int old_wr_coeff = 1;
  1023. bool busy = bfq_already_existing && bfq_bfqq_busy(bfqq);
  1024. unsigned int a_idx = bfqq->actuator_idx;
  1025. struct bfq_iocq_bfqq_data *bfqq_data = &bic->bfqq_data[a_idx];
  1026. if (bfqq_data->saved_has_short_ttime)
  1027. bfq_mark_bfqq_has_short_ttime(bfqq);
  1028. else
  1029. bfq_clear_bfqq_has_short_ttime(bfqq);
  1030. if (bfqq_data->saved_IO_bound)
  1031. bfq_mark_bfqq_IO_bound(bfqq);
  1032. else
  1033. bfq_clear_bfqq_IO_bound(bfqq);
  1034. bfqq->last_serv_time_ns = bfqq_data->saved_last_serv_time_ns;
  1035. bfqq->inject_limit = bfqq_data->saved_inject_limit;
  1036. bfqq->decrease_time_jif = bfqq_data->saved_decrease_time_jif;
  1037. bfqq->entity.new_weight = bfqq_data->saved_weight;
  1038. bfqq->ttime = bfqq_data->saved_ttime;
  1039. bfqq->io_start_time = bfqq_data->saved_io_start_time;
  1040. bfqq->tot_idle_time = bfqq_data->saved_tot_idle_time;
  1041. /*
  1042. * Restore weight coefficient only if low_latency is on
  1043. */
  1044. if (bfqd->low_latency) {
  1045. old_wr_coeff = bfqq->wr_coeff;
  1046. bfqq->wr_coeff = bfqq_data->saved_wr_coeff;
  1047. }
  1048. bfqq->service_from_wr = bfqq_data->saved_service_from_wr;
  1049. bfqq->wr_start_at_switch_to_srt =
  1050. bfqq_data->saved_wr_start_at_switch_to_srt;
  1051. bfqq->last_wr_start_finish = bfqq_data->saved_last_wr_start_finish;
  1052. bfqq->wr_cur_max_time = bfqq_data->saved_wr_cur_max_time;
  1053. if (bfqq->wr_coeff > 1 && (bfq_bfqq_in_large_burst(bfqq) ||
  1054. time_is_before_jiffies(bfqq->last_wr_start_finish +
  1055. bfqq->wr_cur_max_time))) {
  1056. if (bfqq->wr_cur_max_time == bfqd->bfq_wr_rt_max_time &&
  1057. !bfq_bfqq_in_large_burst(bfqq) &&
  1058. time_is_after_eq_jiffies(bfqq->wr_start_at_switch_to_srt +
  1059. bfq_wr_duration(bfqd))) {
  1060. switch_back_to_interactive_wr(bfqq, bfqd);
  1061. } else {
  1062. bfqq->wr_coeff = 1;
  1063. bfq_log_bfqq(bfqq->bfqd, bfqq,
  1064. "resume state: switching off wr");
  1065. }
  1066. }
  1067. /* make sure weight will be updated, however we got here */
  1068. bfqq->entity.prio_changed = 1;
  1069. if (likely(!busy))
  1070. return;
  1071. if (old_wr_coeff == 1 && bfqq->wr_coeff > 1)
  1072. bfqd->wr_busy_queues++;
  1073. else if (old_wr_coeff > 1 && bfqq->wr_coeff == 1)
  1074. bfqd->wr_busy_queues--;
  1075. }
  1076. static int bfqq_process_refs(struct bfq_queue *bfqq)
  1077. {
  1078. return bfqq->ref - bfqq->entity.allocated -
  1079. bfqq->entity.on_st_or_in_serv -
  1080. (bfqq->weight_counter != NULL) - bfqq->stable_ref;
  1081. }
  1082. /* Empty burst list and add just bfqq (see comments on bfq_handle_burst) */
  1083. static void bfq_reset_burst_list(struct bfq_data *bfqd, struct bfq_queue *bfqq)
  1084. {
  1085. struct bfq_queue *item;
  1086. struct hlist_node *n;
  1087. hlist_for_each_entry_safe(item, n, &bfqd->burst_list, burst_list_node)
  1088. hlist_del_init(&item->burst_list_node);
  1089. /*
  1090. * Start the creation of a new burst list only if there is no
  1091. * active queue. See comments on the conditional invocation of
  1092. * bfq_handle_burst().
  1093. */
  1094. if (bfq_tot_busy_queues(bfqd) == 0) {
  1095. hlist_add_head(&bfqq->burst_list_node, &bfqd->burst_list);
  1096. bfqd->burst_size = 1;
  1097. } else
  1098. bfqd->burst_size = 0;
  1099. bfqd->burst_parent_entity = bfqq->entity.parent;
  1100. }
  1101. /* Add bfqq to the list of queues in current burst (see bfq_handle_burst) */
  1102. static void bfq_add_to_burst(struct bfq_data *bfqd, struct bfq_queue *bfqq)
  1103. {
  1104. /* Increment burst size to take into account also bfqq */
  1105. bfqd->burst_size++;
  1106. if (bfqd->burst_size == bfqd->bfq_large_burst_thresh) {
  1107. struct bfq_queue *pos, *bfqq_item;
  1108. struct hlist_node *n;
  1109. /*
  1110. * Enough queues have been activated shortly after each
  1111. * other to consider this burst as large.
  1112. */
  1113. bfqd->large_burst = true;
  1114. /*
  1115. * We can now mark all queues in the burst list as
  1116. * belonging to a large burst.
  1117. */
  1118. hlist_for_each_entry(bfqq_item, &bfqd->burst_list,
  1119. burst_list_node)
  1120. bfq_mark_bfqq_in_large_burst(bfqq_item);
  1121. bfq_mark_bfqq_in_large_burst(bfqq);
  1122. /*
  1123. * From now on, and until the current burst finishes, any
  1124. * new queue being activated shortly after the last queue
  1125. * was inserted in the burst can be immediately marked as
  1126. * belonging to a large burst. So the burst list is not
  1127. * needed any more. Remove it.
  1128. */
  1129. hlist_for_each_entry_safe(pos, n, &bfqd->burst_list,
  1130. burst_list_node)
  1131. hlist_del_init(&pos->burst_list_node);
  1132. } else /*
  1133. * Burst not yet large: add bfqq to the burst list. Do
  1134. * not increment the ref counter for bfqq, because bfqq
  1135. * is removed from the burst list before freeing bfqq
  1136. * in put_queue.
  1137. */
  1138. hlist_add_head(&bfqq->burst_list_node, &bfqd->burst_list);
  1139. }
  1140. /*
  1141. * If many queues belonging to the same group happen to be created
  1142. * shortly after each other, then the processes associated with these
  1143. * queues have typically a common goal. In particular, bursts of queue
  1144. * creations are usually caused by services or applications that spawn
  1145. * many parallel threads/processes. Examples are systemd during boot,
  1146. * or git grep. To help these processes get their job done as soon as
  1147. * possible, it is usually better to not grant either weight-raising
  1148. * or device idling to their queues, unless these queues must be
  1149. * protected from the I/O flowing through other active queues.
  1150. *
  1151. * In this comment we describe, firstly, the reasons why this fact
  1152. * holds, and, secondly, the next function, which implements the main
  1153. * steps needed to properly mark these queues so that they can then be
  1154. * treated in a different way.
  1155. *
  1156. * The above services or applications benefit mostly from a high
  1157. * throughput: the quicker the requests of the activated queues are
  1158. * cumulatively served, the sooner the target job of these queues gets
  1159. * completed. As a consequence, weight-raising any of these queues,
  1160. * which also implies idling the device for it, is almost always
  1161. * counterproductive, unless there are other active queues to isolate
  1162. * these new queues from. If there no other active queues, then
  1163. * weight-raising these new queues just lowers throughput in most
  1164. * cases.
  1165. *
  1166. * On the other hand, a burst of queue creations may be caused also by
  1167. * the start of an application that does not consist of a lot of
  1168. * parallel I/O-bound threads. In fact, with a complex application,
  1169. * several short processes may need to be executed to start-up the
  1170. * application. In this respect, to start an application as quickly as
  1171. * possible, the best thing to do is in any case to privilege the I/O
  1172. * related to the application with respect to all other
  1173. * I/O. Therefore, the best strategy to start as quickly as possible
  1174. * an application that causes a burst of queue creations is to
  1175. * weight-raise all the queues created during the burst. This is the
  1176. * exact opposite of the best strategy for the other type of bursts.
  1177. *
  1178. * In the end, to take the best action for each of the two cases, the
  1179. * two types of bursts need to be distinguished. Fortunately, this
  1180. * seems relatively easy, by looking at the sizes of the bursts. In
  1181. * particular, we found a threshold such that only bursts with a
  1182. * larger size than that threshold are apparently caused by
  1183. * services or commands such as systemd or git grep. For brevity,
  1184. * hereafter we call just 'large' these bursts. BFQ *does not*
  1185. * weight-raise queues whose creation occurs in a large burst. In
  1186. * addition, for each of these queues BFQ performs or does not perform
  1187. * idling depending on which choice boosts the throughput more. The
  1188. * exact choice depends on the device and request pattern at
  1189. * hand.
  1190. *
  1191. * Unfortunately, false positives may occur while an interactive task
  1192. * is starting (e.g., an application is being started). The
  1193. * consequence is that the queues associated with the task do not
  1194. * enjoy weight raising as expected. Fortunately these false positives
  1195. * are very rare. They typically occur if some service happens to
  1196. * start doing I/O exactly when the interactive task starts.
  1197. *
  1198. * Turning back to the next function, it is invoked only if there are
  1199. * no active queues (apart from active queues that would belong to the
  1200. * same, possible burst bfqq would belong to), and it implements all
  1201. * the steps needed to detect the occurrence of a large burst and to
  1202. * properly mark all the queues belonging to it (so that they can then
  1203. * be treated in a different way). This goal is achieved by
  1204. * maintaining a "burst list" that holds, temporarily, the queues that
  1205. * belong to the burst in progress. The list is then used to mark
  1206. * these queues as belonging to a large burst if the burst does become
  1207. * large. The main steps are the following.
  1208. *
  1209. * . when the very first queue is created, the queue is inserted into the
  1210. * list (as it could be the first queue in a possible burst)
  1211. *
  1212. * . if the current burst has not yet become large, and a queue Q that does
  1213. * not yet belong to the burst is activated shortly after the last time
  1214. * at which a new queue entered the burst list, then the function appends
  1215. * Q to the burst list
  1216. *
  1217. * . if, as a consequence of the previous step, the burst size reaches
  1218. * the large-burst threshold, then
  1219. *
  1220. * . all the queues in the burst list are marked as belonging to a
  1221. * large burst
  1222. *
  1223. * . the burst list is deleted; in fact, the burst list already served
  1224. * its purpose (keeping temporarily track of the queues in a burst,
  1225. * so as to be able to mark them as belonging to a large burst in the
  1226. * previous sub-step), and now is not needed any more
  1227. *
  1228. * . the device enters a large-burst mode
  1229. *
  1230. * . if a queue Q that does not belong to the burst is created while
  1231. * the device is in large-burst mode and shortly after the last time
  1232. * at which a queue either entered the burst list or was marked as
  1233. * belonging to the current large burst, then Q is immediately marked
  1234. * as belonging to a large burst.
  1235. *
  1236. * . if a queue Q that does not belong to the burst is created a while
  1237. * later, i.e., not shortly after, than the last time at which a queue
  1238. * either entered the burst list or was marked as belonging to the
  1239. * current large burst, then the current burst is deemed as finished and:
  1240. *
  1241. * . the large-burst mode is reset if set
  1242. *
  1243. * . the burst list is emptied
  1244. *
  1245. * . Q is inserted in the burst list, as Q may be the first queue
  1246. * in a possible new burst (then the burst list contains just Q
  1247. * after this step).
  1248. */
  1249. static void bfq_handle_burst(struct bfq_data *bfqd, struct bfq_queue *bfqq)
  1250. {
  1251. /*
  1252. * If bfqq is already in the burst list or is part of a large
  1253. * burst, or finally has just been split, then there is
  1254. * nothing else to do.
  1255. */
  1256. if (!hlist_unhashed(&bfqq->burst_list_node) ||
  1257. bfq_bfqq_in_large_burst(bfqq) ||
  1258. time_is_after_eq_jiffies(bfqq->split_time +
  1259. msecs_to_jiffies(10)))
  1260. return;
  1261. /*
  1262. * If bfqq's creation happens late enough, or bfqq belongs to
  1263. * a different group than the burst group, then the current
  1264. * burst is finished, and related data structures must be
  1265. * reset.
  1266. *
  1267. * In this respect, consider the special case where bfqq is
  1268. * the very first queue created after BFQ is selected for this
  1269. * device. In this case, last_ins_in_burst and
  1270. * burst_parent_entity are not yet significant when we get
  1271. * here. But it is easy to verify that, whether or not the
  1272. * following condition is true, bfqq will end up being
  1273. * inserted into the burst list. In particular the list will
  1274. * happen to contain only bfqq. And this is exactly what has
  1275. * to happen, as bfqq may be the first queue of the first
  1276. * burst.
  1277. */
  1278. if (time_is_before_jiffies(bfqd->last_ins_in_burst +
  1279. bfqd->bfq_burst_interval) ||
  1280. bfqq->entity.parent != bfqd->burst_parent_entity) {
  1281. bfqd->large_burst = false;
  1282. bfq_reset_burst_list(bfqd, bfqq);
  1283. goto end;
  1284. }
  1285. /*
  1286. * If we get here, then bfqq is being activated shortly after the
  1287. * last queue. So, if the current burst is also large, we can mark
  1288. * bfqq as belonging to this large burst immediately.
  1289. */
  1290. if (bfqd->large_burst) {
  1291. bfq_mark_bfqq_in_large_burst(bfqq);
  1292. goto end;
  1293. }
  1294. /*
  1295. * If we get here, then a large-burst state has not yet been
  1296. * reached, but bfqq is being activated shortly after the last
  1297. * queue. Then we add bfqq to the burst.
  1298. */
  1299. bfq_add_to_burst(bfqd, bfqq);
  1300. end:
  1301. /*
  1302. * At this point, bfqq either has been added to the current
  1303. * burst or has caused the current burst to terminate and a
  1304. * possible new burst to start. In particular, in the second
  1305. * case, bfqq has become the first queue in the possible new
  1306. * burst. In both cases last_ins_in_burst needs to be moved
  1307. * forward.
  1308. */
  1309. bfqd->last_ins_in_burst = jiffies;
  1310. }
  1311. static int bfq_bfqq_budget_left(struct bfq_queue *bfqq)
  1312. {
  1313. struct bfq_entity *entity = &bfqq->entity;
  1314. return entity->budget - entity->service;
  1315. }
  1316. /*
  1317. * If enough samples have been computed, return the current max budget
  1318. * stored in bfqd, which is dynamically updated according to the
  1319. * estimated disk peak rate; otherwise return the default max budget
  1320. */
  1321. static int bfq_max_budget(struct bfq_data *bfqd)
  1322. {
  1323. if (bfqd->budgets_assigned < bfq_stats_min_budgets)
  1324. return bfq_default_max_budget;
  1325. else
  1326. return bfqd->bfq_max_budget;
  1327. }
  1328. /*
  1329. * Return min budget, which is a fraction of the current or default
  1330. * max budget (trying with 1/32)
  1331. */
  1332. static int bfq_min_budget(struct bfq_data *bfqd)
  1333. {
  1334. if (bfqd->budgets_assigned < bfq_stats_min_budgets)
  1335. return bfq_default_max_budget / 32;
  1336. else
  1337. return bfqd->bfq_max_budget / 32;
  1338. }
  1339. /*
  1340. * The next function, invoked after the input queue bfqq switches from
  1341. * idle to busy, updates the budget of bfqq. The function also tells
  1342. * whether the in-service queue should be expired, by returning
  1343. * true. The purpose of expiring the in-service queue is to give bfqq
  1344. * the chance to possibly preempt the in-service queue, and the reason
  1345. * for preempting the in-service queue is to achieve one of the two
  1346. * goals below.
  1347. *
  1348. * 1. Guarantee to bfqq its reserved bandwidth even if bfqq has
  1349. * expired because it has remained idle. In particular, bfqq may have
  1350. * expired for one of the following two reasons:
  1351. *
  1352. * - BFQQE_NO_MORE_REQUESTS bfqq did not enjoy any device idling
  1353. * and did not make it to issue a new request before its last
  1354. * request was served;
  1355. *
  1356. * - BFQQE_TOO_IDLE bfqq did enjoy device idling, but did not issue
  1357. * a new request before the expiration of the idling-time.
  1358. *
  1359. * Even if bfqq has expired for one of the above reasons, the process
  1360. * associated with the queue may be however issuing requests greedily,
  1361. * and thus be sensitive to the bandwidth it receives (bfqq may have
  1362. * remained idle for other reasons: CPU high load, bfqq not enjoying
  1363. * idling, I/O throttling somewhere in the path from the process to
  1364. * the I/O scheduler, ...). But if, after every expiration for one of
  1365. * the above two reasons, bfqq has to wait for the service of at least
  1366. * one full budget of another queue before being served again, then
  1367. * bfqq is likely to get a much lower bandwidth or resource time than
  1368. * its reserved ones. To address this issue, two countermeasures need
  1369. * to be taken.
  1370. *
  1371. * First, the budget and the timestamps of bfqq need to be updated in
  1372. * a special way on bfqq reactivation: they need to be updated as if
  1373. * bfqq did not remain idle and did not expire. In fact, if they are
  1374. * computed as if bfqq expired and remained idle until reactivation,
  1375. * then the process associated with bfqq is treated as if, instead of
  1376. * being greedy, it stopped issuing requests when bfqq remained idle,
  1377. * and restarts issuing requests only on this reactivation. In other
  1378. * words, the scheduler does not help the process recover the "service
  1379. * hole" between bfqq expiration and reactivation. As a consequence,
  1380. * the process receives a lower bandwidth than its reserved one. In
  1381. * contrast, to recover this hole, the budget must be updated as if
  1382. * bfqq was not expired at all before this reactivation, i.e., it must
  1383. * be set to the value of the remaining budget when bfqq was
  1384. * expired. Along the same line, timestamps need to be assigned the
  1385. * value they had the last time bfqq was selected for service, i.e.,
  1386. * before last expiration. Thus timestamps need to be back-shifted
  1387. * with respect to their normal computation (see [1] for more details
  1388. * on this tricky aspect).
  1389. *
  1390. * Secondly, to allow the process to recover the hole, the in-service
  1391. * queue must be expired too, to give bfqq the chance to preempt it
  1392. * immediately. In fact, if bfqq has to wait for a full budget of the
  1393. * in-service queue to be completed, then it may become impossible to
  1394. * let the process recover the hole, even if the back-shifted
  1395. * timestamps of bfqq are lower than those of the in-service queue. If
  1396. * this happens for most or all of the holes, then the process may not
  1397. * receive its reserved bandwidth. In this respect, it is worth noting
  1398. * that, being the service of outstanding requests unpreemptible, a
  1399. * little fraction of the holes may however be unrecoverable, thereby
  1400. * causing a little loss of bandwidth.
  1401. *
  1402. * The last important point is detecting whether bfqq does need this
  1403. * bandwidth recovery. In this respect, the next function deems the
  1404. * process associated with bfqq greedy, and thus allows it to recover
  1405. * the hole, if: 1) the process is waiting for the arrival of a new
  1406. * request (which implies that bfqq expired for one of the above two
  1407. * reasons), and 2) such a request has arrived soon. The first
  1408. * condition is controlled through the flag non_blocking_wait_rq,
  1409. * while the second through the flag arrived_in_time. If both
  1410. * conditions hold, then the function computes the budget in the
  1411. * above-described special way, and signals that the in-service queue
  1412. * should be expired. Timestamp back-shifting is done later in
  1413. * __bfq_activate_entity.
  1414. *
  1415. * 2. Reduce latency. Even if timestamps are not backshifted to let
  1416. * the process associated with bfqq recover a service hole, bfqq may
  1417. * however happen to have, after being (re)activated, a lower finish
  1418. * timestamp than the in-service queue. That is, the next budget of
  1419. * bfqq may have to be completed before the one of the in-service
  1420. * queue. If this is the case, then preempting the in-service queue
  1421. * allows this goal to be achieved, apart from the unpreemptible,
  1422. * outstanding requests mentioned above.
  1423. *
  1424. * Unfortunately, regardless of which of the above two goals one wants
  1425. * to achieve, service trees need first to be updated to know whether
  1426. * the in-service queue must be preempted. To have service trees
  1427. * correctly updated, the in-service queue must be expired and
  1428. * rescheduled, and bfqq must be scheduled too. This is one of the
  1429. * most costly operations (in future versions, the scheduling
  1430. * mechanism may be re-designed in such a way to make it possible to
  1431. * know whether preemption is needed without needing to update service
  1432. * trees). In addition, queue preemptions almost always cause random
  1433. * I/O, which may in turn cause loss of throughput. Finally, there may
  1434. * even be no in-service queue when the next function is invoked (so,
  1435. * no queue to compare timestamps with). Because of these facts, the
  1436. * next function adopts the following simple scheme to avoid costly
  1437. * operations, too frequent preemptions and too many dependencies on
  1438. * the state of the scheduler: it requests the expiration of the
  1439. * in-service queue (unconditionally) only for queues that need to
  1440. * recover a hole. Then it delegates to other parts of the code the
  1441. * responsibility of handling the above case 2.
  1442. */
  1443. static bool bfq_bfqq_update_budg_for_activation(struct bfq_data *bfqd,
  1444. struct bfq_queue *bfqq,
  1445. bool arrived_in_time)
  1446. {
  1447. struct bfq_entity *entity = &bfqq->entity;
  1448. /*
  1449. * In the next compound condition, we check also whether there
  1450. * is some budget left, because otherwise there is no point in
  1451. * trying to go on serving bfqq with this same budget: bfqq
  1452. * would be expired immediately after being selected for
  1453. * service. This would only cause useless overhead.
  1454. */
  1455. if (bfq_bfqq_non_blocking_wait_rq(bfqq) && arrived_in_time &&
  1456. bfq_bfqq_budget_left(bfqq) > 0) {
  1457. /*
  1458. * We do not clear the flag non_blocking_wait_rq here, as
  1459. * the latter is used in bfq_activate_bfqq to signal
  1460. * that timestamps need to be back-shifted (and is
  1461. * cleared right after).
  1462. */
  1463. /*
  1464. * In next assignment we rely on that either
  1465. * entity->service or entity->budget are not updated
  1466. * on expiration if bfqq is empty (see
  1467. * __bfq_bfqq_recalc_budget). Thus both quantities
  1468. * remain unchanged after such an expiration, and the
  1469. * following statement therefore assigns to
  1470. * entity->budget the remaining budget on such an
  1471. * expiration.
  1472. */
  1473. entity->budget = min_t(unsigned long,
  1474. bfq_bfqq_budget_left(bfqq),
  1475. bfqq->max_budget);
  1476. /*
  1477. * At this point, we have used entity->service to get
  1478. * the budget left (needed for updating
  1479. * entity->budget). Thus we finally can, and have to,
  1480. * reset entity->service. The latter must be reset
  1481. * because bfqq would otherwise be charged again for
  1482. * the service it has received during its previous
  1483. * service slot(s).
  1484. */
  1485. entity->service = 0;
  1486. return true;
  1487. }
  1488. /*
  1489. * We can finally complete expiration, by setting service to 0.
  1490. */
  1491. entity->service = 0;
  1492. entity->budget = max_t(unsigned long, bfqq->max_budget,
  1493. bfq_serv_to_charge(bfqq->next_rq, bfqq));
  1494. bfq_clear_bfqq_non_blocking_wait_rq(bfqq);
  1495. return false;
  1496. }
  1497. /*
  1498. * Return the farthest past time instant according to jiffies
  1499. * macros.
  1500. */
  1501. static unsigned long bfq_smallest_from_now(void)
  1502. {
  1503. return jiffies - MAX_JIFFY_OFFSET;
  1504. }
  1505. static void bfq_update_bfqq_wr_on_rq_arrival(struct bfq_data *bfqd,
  1506. struct bfq_queue *bfqq,
  1507. unsigned int old_wr_coeff,
  1508. bool wr_or_deserves_wr,
  1509. bool interactive,
  1510. bool in_burst,
  1511. bool soft_rt)
  1512. {
  1513. if (old_wr_coeff == 1 && wr_or_deserves_wr) {
  1514. /* start a weight-raising period */
  1515. if (interactive) {
  1516. bfqq->service_from_wr = 0;
  1517. bfqq->wr_coeff = bfqd->bfq_wr_coeff;
  1518. bfqq->wr_cur_max_time = bfq_wr_duration(bfqd);
  1519. } else {
  1520. /*
  1521. * No interactive weight raising in progress
  1522. * here: assign minus infinity to
  1523. * wr_start_at_switch_to_srt, to make sure
  1524. * that, at the end of the soft-real-time
  1525. * weight raising periods that is starting
  1526. * now, no interactive weight-raising period
  1527. * may be wrongly considered as still in
  1528. * progress (and thus actually started by
  1529. * mistake).
  1530. */
  1531. bfqq->wr_start_at_switch_to_srt =
  1532. bfq_smallest_from_now();
  1533. bfqq->wr_coeff = bfqd->bfq_wr_coeff *
  1534. BFQ_SOFTRT_WEIGHT_FACTOR;
  1535. bfqq->wr_cur_max_time =
  1536. bfqd->bfq_wr_rt_max_time;
  1537. }
  1538. /*
  1539. * If needed, further reduce budget to make sure it is
  1540. * close to bfqq's backlog, so as to reduce the
  1541. * scheduling-error component due to a too large
  1542. * budget. Do not care about throughput consequences,
  1543. * but only about latency. Finally, do not assign a
  1544. * too small budget either, to avoid increasing
  1545. * latency by causing too frequent expirations.
  1546. */
  1547. bfqq->entity.budget = min_t(unsigned long,
  1548. bfqq->entity.budget,
  1549. 2 * bfq_min_budget(bfqd));
  1550. } else if (old_wr_coeff > 1) {
  1551. if (interactive) { /* update wr coeff and duration */
  1552. bfqq->wr_coeff = bfqd->bfq_wr_coeff;
  1553. bfqq->wr_cur_max_time = bfq_wr_duration(bfqd);
  1554. } else if (in_burst)
  1555. bfqq->wr_coeff = 1;
  1556. else if (soft_rt) {
  1557. /*
  1558. * The application is now or still meeting the
  1559. * requirements for being deemed soft rt. We
  1560. * can then correctly and safely (re)charge
  1561. * the weight-raising duration for the
  1562. * application with the weight-raising
  1563. * duration for soft rt applications.
  1564. *
  1565. * In particular, doing this recharge now, i.e.,
  1566. * before the weight-raising period for the
  1567. * application finishes, reduces the probability
  1568. * of the following negative scenario:
  1569. * 1) the weight of a soft rt application is
  1570. * raised at startup (as for any newly
  1571. * created application),
  1572. * 2) since the application is not interactive,
  1573. * at a certain time weight-raising is
  1574. * stopped for the application,
  1575. * 3) at that time the application happens to
  1576. * still have pending requests, and hence
  1577. * is destined to not have a chance to be
  1578. * deemed soft rt before these requests are
  1579. * completed (see the comments to the
  1580. * function bfq_bfqq_softrt_next_start()
  1581. * for details on soft rt detection),
  1582. * 4) these pending requests experience a high
  1583. * latency because the application is not
  1584. * weight-raised while they are pending.
  1585. */
  1586. if (bfqq->wr_cur_max_time !=
  1587. bfqd->bfq_wr_rt_max_time) {
  1588. bfqq->wr_start_at_switch_to_srt =
  1589. bfqq->last_wr_start_finish;
  1590. bfqq->wr_cur_max_time =
  1591. bfqd->bfq_wr_rt_max_time;
  1592. bfqq->wr_coeff = bfqd->bfq_wr_coeff *
  1593. BFQ_SOFTRT_WEIGHT_FACTOR;
  1594. }
  1595. bfqq->last_wr_start_finish = jiffies;
  1596. }
  1597. }
  1598. }
  1599. static bool bfq_bfqq_idle_for_long_time(struct bfq_data *bfqd,
  1600. struct bfq_queue *bfqq)
  1601. {
  1602. return bfqq->dispatched == 0 &&
  1603. time_is_before_jiffies(
  1604. bfqq->budget_timeout +
  1605. bfqd->bfq_wr_min_idle_time);
  1606. }
  1607. /*
  1608. * Return true if bfqq is in a higher priority class, or has a higher
  1609. * weight than the in-service queue.
  1610. */
  1611. static bool bfq_bfqq_higher_class_or_weight(struct bfq_queue *bfqq,
  1612. struct bfq_queue *in_serv_bfqq)
  1613. {
  1614. int bfqq_weight, in_serv_weight;
  1615. if (bfqq->ioprio_class < in_serv_bfqq->ioprio_class)
  1616. return true;
  1617. if (in_serv_bfqq->entity.parent == bfqq->entity.parent) {
  1618. bfqq_weight = bfqq->entity.weight;
  1619. in_serv_weight = in_serv_bfqq->entity.weight;
  1620. } else {
  1621. if (bfqq->entity.parent)
  1622. bfqq_weight = bfqq->entity.parent->weight;
  1623. else
  1624. bfqq_weight = bfqq->entity.weight;
  1625. if (in_serv_bfqq->entity.parent)
  1626. in_serv_weight = in_serv_bfqq->entity.parent->weight;
  1627. else
  1628. in_serv_weight = in_serv_bfqq->entity.weight;
  1629. }
  1630. return bfqq_weight > in_serv_weight;
  1631. }
  1632. /*
  1633. * Get the index of the actuator that will serve bio.
  1634. */
  1635. static unsigned int bfq_actuator_index(struct bfq_data *bfqd, struct bio *bio)
  1636. {
  1637. unsigned int i;
  1638. sector_t end;
  1639. /* no search needed if one or zero ranges present */
  1640. if (bfqd->num_actuators == 1)
  1641. return 0;
  1642. /* bio_end_sector(bio) gives the sector after the last one */
  1643. end = bio_end_sector(bio) - 1;
  1644. for (i = 0; i < bfqd->num_actuators; i++) {
  1645. if (end >= bfqd->sector[i] &&
  1646. end < bfqd->sector[i] + bfqd->nr_sectors[i])
  1647. return i;
  1648. }
  1649. WARN_ONCE(true,
  1650. "bfq_actuator_index: bio sector out of ranges: end=%llu\n",
  1651. end);
  1652. return 0;
  1653. }
  1654. static bool bfq_better_to_idle(struct bfq_queue *bfqq);
  1655. static void bfq_bfqq_handle_idle_busy_switch(struct bfq_data *bfqd,
  1656. struct bfq_queue *bfqq,
  1657. int old_wr_coeff,
  1658. struct request *rq,
  1659. bool *interactive)
  1660. {
  1661. bool soft_rt, in_burst, wr_or_deserves_wr,
  1662. bfqq_wants_to_preempt,
  1663. idle_for_long_time = bfq_bfqq_idle_for_long_time(bfqd, bfqq),
  1664. /*
  1665. * See the comments on
  1666. * bfq_bfqq_update_budg_for_activation for
  1667. * details on the usage of the next variable.
  1668. */
  1669. arrived_in_time = blk_time_get_ns() <=
  1670. bfqq->ttime.last_end_request +
  1671. bfqd->bfq_slice_idle * 3;
  1672. unsigned int act_idx = bfq_actuator_index(bfqd, rq->bio);
  1673. bool bfqq_non_merged_or_stably_merged =
  1674. bfqq->bic || RQ_BIC(rq)->bfqq_data[act_idx].stably_merged;
  1675. /*
  1676. * bfqq deserves to be weight-raised if:
  1677. * - it is sync,
  1678. * - it does not belong to a large burst,
  1679. * - it has been idle for enough time or is soft real-time,
  1680. * - is linked to a bfq_io_cq (it is not shared in any sense),
  1681. * - has a default weight (otherwise we assume the user wanted
  1682. * to control its weight explicitly)
  1683. */
  1684. in_burst = bfq_bfqq_in_large_burst(bfqq);
  1685. soft_rt = bfqd->bfq_wr_max_softrt_rate > 0 &&
  1686. !BFQQ_TOTALLY_SEEKY(bfqq) &&
  1687. !in_burst &&
  1688. time_is_before_jiffies(bfqq->soft_rt_next_start) &&
  1689. bfqq->dispatched == 0 &&
  1690. bfqq->entity.new_weight == 40;
  1691. *interactive = !in_burst && idle_for_long_time &&
  1692. bfqq->entity.new_weight == 40;
  1693. /*
  1694. * Merged bfq_queues are kept out of weight-raising
  1695. * (low-latency) mechanisms. The reason is that these queues
  1696. * are usually created for non-interactive and
  1697. * non-soft-real-time tasks. Yet this is not the case for
  1698. * stably-merged queues. These queues are merged just because
  1699. * they are created shortly after each other. So they may
  1700. * easily serve the I/O of an interactive or soft-real time
  1701. * application, if the application happens to spawn multiple
  1702. * processes. So let also stably-merged queued enjoy weight
  1703. * raising.
  1704. */
  1705. wr_or_deserves_wr = bfqd->low_latency &&
  1706. (bfqq->wr_coeff > 1 ||
  1707. (bfq_bfqq_sync(bfqq) && bfqq_non_merged_or_stably_merged &&
  1708. (*interactive || soft_rt)));
  1709. /*
  1710. * Using the last flag, update budget and check whether bfqq
  1711. * may want to preempt the in-service queue.
  1712. */
  1713. bfqq_wants_to_preempt =
  1714. bfq_bfqq_update_budg_for_activation(bfqd, bfqq,
  1715. arrived_in_time);
  1716. /*
  1717. * If bfqq happened to be activated in a burst, but has been
  1718. * idle for much more than an interactive queue, then we
  1719. * assume that, in the overall I/O initiated in the burst, the
  1720. * I/O associated with bfqq is finished. So bfqq does not need
  1721. * to be treated as a queue belonging to a burst
  1722. * anymore. Accordingly, we reset bfqq's in_large_burst flag
  1723. * if set, and remove bfqq from the burst list if it's
  1724. * there. We do not decrement burst_size, because the fact
  1725. * that bfqq does not need to belong to the burst list any
  1726. * more does not invalidate the fact that bfqq was created in
  1727. * a burst.
  1728. */
  1729. if (likely(!bfq_bfqq_just_created(bfqq)) &&
  1730. idle_for_long_time &&
  1731. time_is_before_jiffies(
  1732. bfqq->budget_timeout +
  1733. msecs_to_jiffies(10000))) {
  1734. hlist_del_init(&bfqq->burst_list_node);
  1735. bfq_clear_bfqq_in_large_burst(bfqq);
  1736. }
  1737. bfq_clear_bfqq_just_created(bfqq);
  1738. if (bfqd->low_latency) {
  1739. if (unlikely(time_is_after_jiffies(bfqq->split_time)))
  1740. /* wraparound */
  1741. bfqq->split_time =
  1742. jiffies - bfqd->bfq_wr_min_idle_time - 1;
  1743. if (time_is_before_jiffies(bfqq->split_time +
  1744. bfqd->bfq_wr_min_idle_time)) {
  1745. bfq_update_bfqq_wr_on_rq_arrival(bfqd, bfqq,
  1746. old_wr_coeff,
  1747. wr_or_deserves_wr,
  1748. *interactive,
  1749. in_burst,
  1750. soft_rt);
  1751. if (old_wr_coeff != bfqq->wr_coeff)
  1752. bfqq->entity.prio_changed = 1;
  1753. }
  1754. }
  1755. bfqq->last_idle_bklogged = jiffies;
  1756. bfqq->service_from_backlogged = 0;
  1757. bfq_clear_bfqq_softrt_update(bfqq);
  1758. bfq_add_bfqq_busy(bfqq);
  1759. /*
  1760. * Expire in-service queue if preemption may be needed for
  1761. * guarantees or throughput. As for guarantees, we care
  1762. * explicitly about two cases. The first is that bfqq has to
  1763. * recover a service hole, as explained in the comments on
  1764. * bfq_bfqq_update_budg_for_activation(), i.e., that
  1765. * bfqq_wants_to_preempt is true. However, if bfqq does not
  1766. * carry time-critical I/O, then bfqq's bandwidth is less
  1767. * important than that of queues that carry time-critical I/O.
  1768. * So, as a further constraint, we consider this case only if
  1769. * bfqq is at least as weight-raised, i.e., at least as time
  1770. * critical, as the in-service queue.
  1771. *
  1772. * The second case is that bfqq is in a higher priority class,
  1773. * or has a higher weight than the in-service queue. If this
  1774. * condition does not hold, we don't care because, even if
  1775. * bfqq does not start to be served immediately, the resulting
  1776. * delay for bfqq's I/O is however lower or much lower than
  1777. * the ideal completion time to be guaranteed to bfqq's I/O.
  1778. *
  1779. * In both cases, preemption is needed only if, according to
  1780. * the timestamps of both bfqq and of the in-service queue,
  1781. * bfqq actually is the next queue to serve. So, to reduce
  1782. * useless preemptions, the return value of
  1783. * next_queue_may_preempt() is considered in the next compound
  1784. * condition too. Yet next_queue_may_preempt() just checks a
  1785. * simple, necessary condition for bfqq to be the next queue
  1786. * to serve. In fact, to evaluate a sufficient condition, the
  1787. * timestamps of the in-service queue would need to be
  1788. * updated, and this operation is quite costly (see the
  1789. * comments on bfq_bfqq_update_budg_for_activation()).
  1790. *
  1791. * As for throughput, we ask bfq_better_to_idle() whether we
  1792. * still need to plug I/O dispatching. If bfq_better_to_idle()
  1793. * says no, then plugging is not needed any longer, either to
  1794. * boost throughput or to perserve service guarantees. Then
  1795. * the best option is to stop plugging I/O, as not doing so
  1796. * would certainly lower throughput. We may end up in this
  1797. * case if: (1) upon a dispatch attempt, we detected that it
  1798. * was better to plug I/O dispatch, and to wait for a new
  1799. * request to arrive for the currently in-service queue, but
  1800. * (2) this switch of bfqq to busy changes the scenario.
  1801. */
  1802. if (bfqd->in_service_queue &&
  1803. ((bfqq_wants_to_preempt &&
  1804. bfqq->wr_coeff >= bfqd->in_service_queue->wr_coeff) ||
  1805. bfq_bfqq_higher_class_or_weight(bfqq, bfqd->in_service_queue) ||
  1806. !bfq_better_to_idle(bfqd->in_service_queue)) &&
  1807. next_queue_may_preempt(bfqd))
  1808. bfq_bfqq_expire(bfqd, bfqd->in_service_queue,
  1809. false, BFQQE_PREEMPTED);
  1810. }
  1811. static void bfq_reset_inject_limit(struct bfq_data *bfqd,
  1812. struct bfq_queue *bfqq)
  1813. {
  1814. /* invalidate baseline total service time */
  1815. bfqq->last_serv_time_ns = 0;
  1816. /*
  1817. * Reset pointer in case we are waiting for
  1818. * some request completion.
  1819. */
  1820. bfqd->waited_rq = NULL;
  1821. /*
  1822. * If bfqq has a short think time, then start by setting the
  1823. * inject limit to 0 prudentially, because the service time of
  1824. * an injected I/O request may be higher than the think time
  1825. * of bfqq, and therefore, if one request was injected when
  1826. * bfqq remains empty, this injected request might delay the
  1827. * service of the next I/O request for bfqq significantly. In
  1828. * case bfqq can actually tolerate some injection, then the
  1829. * adaptive update will however raise the limit soon. This
  1830. * lucky circumstance holds exactly because bfqq has a short
  1831. * think time, and thus, after remaining empty, is likely to
  1832. * get new I/O enqueued---and then completed---before being
  1833. * expired. This is the very pattern that gives the
  1834. * limit-update algorithm the chance to measure the effect of
  1835. * injection on request service times, and then to update the
  1836. * limit accordingly.
  1837. *
  1838. * However, in the following special case, the inject limit is
  1839. * left to 1 even if the think time is short: bfqq's I/O is
  1840. * synchronized with that of some other queue, i.e., bfqq may
  1841. * receive new I/O only after the I/O of the other queue is
  1842. * completed. Keeping the inject limit to 1 allows the
  1843. * blocking I/O to be served while bfqq is in service. And
  1844. * this is very convenient both for bfqq and for overall
  1845. * throughput, as explained in detail in the comments in
  1846. * bfq_update_has_short_ttime().
  1847. *
  1848. * On the opposite end, if bfqq has a long think time, then
  1849. * start directly by 1, because:
  1850. * a) on the bright side, keeping at most one request in
  1851. * service in the drive is unlikely to cause any harm to the
  1852. * latency of bfqq's requests, as the service time of a single
  1853. * request is likely to be lower than the think time of bfqq;
  1854. * b) on the downside, after becoming empty, bfqq is likely to
  1855. * expire before getting its next request. With this request
  1856. * arrival pattern, it is very hard to sample total service
  1857. * times and update the inject limit accordingly (see comments
  1858. * on bfq_update_inject_limit()). So the limit is likely to be
  1859. * never, or at least seldom, updated. As a consequence, by
  1860. * setting the limit to 1, we avoid that no injection ever
  1861. * occurs with bfqq. On the downside, this proactive step
  1862. * further reduces chances to actually compute the baseline
  1863. * total service time. Thus it reduces chances to execute the
  1864. * limit-update algorithm and possibly raise the limit to more
  1865. * than 1.
  1866. */
  1867. if (bfq_bfqq_has_short_ttime(bfqq))
  1868. bfqq->inject_limit = 0;
  1869. else
  1870. bfqq->inject_limit = 1;
  1871. bfqq->decrease_time_jif = jiffies;
  1872. }
  1873. static void bfq_update_io_intensity(struct bfq_queue *bfqq, u64 now_ns)
  1874. {
  1875. u64 tot_io_time = now_ns - bfqq->io_start_time;
  1876. if (RB_EMPTY_ROOT(&bfqq->sort_list) && bfqq->dispatched == 0)
  1877. bfqq->tot_idle_time +=
  1878. now_ns - bfqq->ttime.last_end_request;
  1879. if (unlikely(bfq_bfqq_just_created(bfqq)))
  1880. return;
  1881. /*
  1882. * Must be busy for at least about 80% of the time to be
  1883. * considered I/O bound.
  1884. */
  1885. if (bfqq->tot_idle_time * 5 > tot_io_time)
  1886. bfq_clear_bfqq_IO_bound(bfqq);
  1887. else
  1888. bfq_mark_bfqq_IO_bound(bfqq);
  1889. /*
  1890. * Keep an observation window of at most 200 ms in the past
  1891. * from now.
  1892. */
  1893. if (tot_io_time > 200 * NSEC_PER_MSEC) {
  1894. bfqq->io_start_time = now_ns - (tot_io_time>>1);
  1895. bfqq->tot_idle_time >>= 1;
  1896. }
  1897. }
  1898. /*
  1899. * Detect whether bfqq's I/O seems synchronized with that of some
  1900. * other queue, i.e., whether bfqq, after remaining empty, happens to
  1901. * receive new I/O only right after some I/O request of the other
  1902. * queue has been completed. We call waker queue the other queue, and
  1903. * we assume, for simplicity, that bfqq may have at most one waker
  1904. * queue.
  1905. *
  1906. * A remarkable throughput boost can be reached by unconditionally
  1907. * injecting the I/O of the waker queue, every time a new
  1908. * bfq_dispatch_request happens to be invoked while I/O is being
  1909. * plugged for bfqq. In addition to boosting throughput, this
  1910. * unblocks bfqq's I/O, thereby improving bandwidth and latency for
  1911. * bfqq. Note that these same results may be achieved with the general
  1912. * injection mechanism, but less effectively. For details on this
  1913. * aspect, see the comments on the choice of the queue for injection
  1914. * in bfq_select_queue().
  1915. *
  1916. * Turning back to the detection of a waker queue, a queue Q is deemed as a
  1917. * waker queue for bfqq if, for three consecutive times, bfqq happens to become
  1918. * non empty right after a request of Q has been completed within given
  1919. * timeout. In this respect, even if bfqq is empty, we do not check for a waker
  1920. * if it still has some in-flight I/O. In fact, in this case bfqq is actually
  1921. * still being served by the drive, and may receive new I/O on the completion
  1922. * of some of the in-flight requests. In particular, on the first time, Q is
  1923. * tentatively set as a candidate waker queue, while on the third consecutive
  1924. * time that Q is detected, the field waker_bfqq is set to Q, to confirm that Q
  1925. * is a waker queue for bfqq. These detection steps are performed only if bfqq
  1926. * has a long think time, so as to make it more likely that bfqq's I/O is
  1927. * actually being blocked by a synchronization. This last filter, plus the
  1928. * above three-times requirement and time limit for detection, make false
  1929. * positives less likely.
  1930. *
  1931. * NOTE
  1932. *
  1933. * The sooner a waker queue is detected, the sooner throughput can be
  1934. * boosted by injecting I/O from the waker queue. Fortunately,
  1935. * detection is likely to be actually fast, for the following
  1936. * reasons. While blocked by synchronization, bfqq has a long think
  1937. * time. This implies that bfqq's inject limit is at least equal to 1
  1938. * (see the comments in bfq_update_inject_limit()). So, thanks to
  1939. * injection, the waker queue is likely to be served during the very
  1940. * first I/O-plugging time interval for bfqq. This triggers the first
  1941. * step of the detection mechanism. Thanks again to injection, the
  1942. * candidate waker queue is then likely to be confirmed no later than
  1943. * during the next I/O-plugging interval for bfqq.
  1944. *
  1945. * ISSUE
  1946. *
  1947. * On queue merging all waker information is lost.
  1948. */
  1949. static void bfq_check_waker(struct bfq_data *bfqd, struct bfq_queue *bfqq,
  1950. u64 now_ns)
  1951. {
  1952. char waker_name[MAX_BFQQ_NAME_LENGTH];
  1953. if (!bfqd->last_completed_rq_bfqq ||
  1954. bfqd->last_completed_rq_bfqq == bfqq ||
  1955. bfq_bfqq_has_short_ttime(bfqq) ||
  1956. now_ns - bfqd->last_completion >= 4 * NSEC_PER_MSEC ||
  1957. bfqd->last_completed_rq_bfqq == &bfqd->oom_bfqq ||
  1958. bfqq == &bfqd->oom_bfqq)
  1959. return;
  1960. /*
  1961. * We reset waker detection logic also if too much time has passed
  1962. * since the first detection. If wakeups are rare, pointless idling
  1963. * doesn't hurt throughput that much. The condition below makes sure
  1964. * we do not uselessly idle blocking waker in more than 1/64 cases.
  1965. */
  1966. if (bfqd->last_completed_rq_bfqq !=
  1967. bfqq->tentative_waker_bfqq ||
  1968. now_ns > bfqq->waker_detection_started +
  1969. 128 * (u64)bfqd->bfq_slice_idle) {
  1970. /*
  1971. * First synchronization detected with a
  1972. * candidate waker queue, or with a different
  1973. * candidate waker queue from the current one.
  1974. */
  1975. bfqq->tentative_waker_bfqq =
  1976. bfqd->last_completed_rq_bfqq;
  1977. bfqq->num_waker_detections = 1;
  1978. bfqq->waker_detection_started = now_ns;
  1979. bfq_bfqq_name(bfqq->tentative_waker_bfqq, waker_name,
  1980. MAX_BFQQ_NAME_LENGTH);
  1981. bfq_log_bfqq(bfqd, bfqq, "set tentative waker %s", waker_name);
  1982. } else /* Same tentative waker queue detected again */
  1983. bfqq->num_waker_detections++;
  1984. if (bfqq->num_waker_detections == 3) {
  1985. bfqq->waker_bfqq = bfqd->last_completed_rq_bfqq;
  1986. bfqq->tentative_waker_bfqq = NULL;
  1987. bfq_bfqq_name(bfqq->waker_bfqq, waker_name,
  1988. MAX_BFQQ_NAME_LENGTH);
  1989. bfq_log_bfqq(bfqd, bfqq, "set waker %s", waker_name);
  1990. /*
  1991. * If the waker queue disappears, then
  1992. * bfqq->waker_bfqq must be reset. To
  1993. * this goal, we maintain in each
  1994. * waker queue a list, woken_list, of
  1995. * all the queues that reference the
  1996. * waker queue through their
  1997. * waker_bfqq pointer. When the waker
  1998. * queue exits, the waker_bfqq pointer
  1999. * of all the queues in the woken_list
  2000. * is reset.
  2001. *
  2002. * In addition, if bfqq is already in
  2003. * the woken_list of a waker queue,
  2004. * then, before being inserted into
  2005. * the woken_list of a new waker
  2006. * queue, bfqq must be removed from
  2007. * the woken_list of the old waker
  2008. * queue.
  2009. */
  2010. if (!hlist_unhashed(&bfqq->woken_list_node))
  2011. hlist_del_init(&bfqq->woken_list_node);
  2012. hlist_add_head(&bfqq->woken_list_node,
  2013. &bfqd->last_completed_rq_bfqq->woken_list);
  2014. }
  2015. }
  2016. static void bfq_add_request(struct request *rq)
  2017. {
  2018. struct bfq_queue *bfqq = RQ_BFQQ(rq);
  2019. struct bfq_data *bfqd = bfqq->bfqd;
  2020. struct request *next_rq, *prev;
  2021. unsigned int old_wr_coeff = bfqq->wr_coeff;
  2022. bool interactive = false;
  2023. u64 now_ns = blk_time_get_ns();
  2024. bfq_log_bfqq(bfqd, bfqq, "add_request %d", rq_is_sync(rq));
  2025. bfqq->queued[rq_is_sync(rq)]++;
  2026. /*
  2027. * Updating of 'bfqd->queued' is protected by 'bfqd->lock', however, it
  2028. * may be read without holding the lock in bfq_has_work().
  2029. */
  2030. WRITE_ONCE(bfqd->queued, bfqd->queued + 1);
  2031. if (bfq_bfqq_sync(bfqq) && RQ_BIC(rq)->requests <= 1) {
  2032. bfq_check_waker(bfqd, bfqq, now_ns);
  2033. /*
  2034. * Periodically reset inject limit, to make sure that
  2035. * the latter eventually drops in case workload
  2036. * changes, see step (3) in the comments on
  2037. * bfq_update_inject_limit().
  2038. */
  2039. if (time_is_before_eq_jiffies(bfqq->decrease_time_jif +
  2040. msecs_to_jiffies(1000)))
  2041. bfq_reset_inject_limit(bfqd, bfqq);
  2042. /*
  2043. * The following conditions must hold to setup a new
  2044. * sampling of total service time, and then a new
  2045. * update of the inject limit:
  2046. * - bfqq is in service, because the total service
  2047. * time is evaluated only for the I/O requests of
  2048. * the queues in service;
  2049. * - this is the right occasion to compute or to
  2050. * lower the baseline total service time, because
  2051. * there are actually no requests in the drive,
  2052. * or
  2053. * the baseline total service time is available, and
  2054. * this is the right occasion to compute the other
  2055. * quantity needed to update the inject limit, i.e.,
  2056. * the total service time caused by the amount of
  2057. * injection allowed by the current value of the
  2058. * limit. It is the right occasion because injection
  2059. * has actually been performed during the service
  2060. * hole, and there are still in-flight requests,
  2061. * which are very likely to be exactly the injected
  2062. * requests, or part of them;
  2063. * - the minimum interval for sampling the total
  2064. * service time and updating the inject limit has
  2065. * elapsed.
  2066. */
  2067. if (bfqq == bfqd->in_service_queue &&
  2068. (bfqd->tot_rq_in_driver == 0 ||
  2069. (bfqq->last_serv_time_ns > 0 &&
  2070. bfqd->rqs_injected && bfqd->tot_rq_in_driver > 0)) &&
  2071. time_is_before_eq_jiffies(bfqq->decrease_time_jif +
  2072. msecs_to_jiffies(10))) {
  2073. bfqd->last_empty_occupied_ns = blk_time_get_ns();
  2074. /*
  2075. * Start the state machine for measuring the
  2076. * total service time of rq: setting
  2077. * wait_dispatch will cause bfqd->waited_rq to
  2078. * be set when rq will be dispatched.
  2079. */
  2080. bfqd->wait_dispatch = true;
  2081. /*
  2082. * If there is no I/O in service in the drive,
  2083. * then possible injection occurred before the
  2084. * arrival of rq will not affect the total
  2085. * service time of rq. So the injection limit
  2086. * must not be updated as a function of such
  2087. * total service time, unless new injection
  2088. * occurs before rq is completed. To have the
  2089. * injection limit updated only in the latter
  2090. * case, reset rqs_injected here (rqs_injected
  2091. * will be set in case injection is performed
  2092. * on bfqq before rq is completed).
  2093. */
  2094. if (bfqd->tot_rq_in_driver == 0)
  2095. bfqd->rqs_injected = false;
  2096. }
  2097. }
  2098. if (bfq_bfqq_sync(bfqq))
  2099. bfq_update_io_intensity(bfqq, now_ns);
  2100. elv_rb_add(&bfqq->sort_list, rq);
  2101. /*
  2102. * Check if this request is a better next-serve candidate.
  2103. */
  2104. prev = bfqq->next_rq;
  2105. next_rq = bfq_choose_req(bfqd, bfqq->next_rq, rq, bfqd->last_position);
  2106. bfqq->next_rq = next_rq;
  2107. /*
  2108. * Adjust priority tree position, if next_rq changes.
  2109. * See comments on bfq_pos_tree_add_move() for the unlikely().
  2110. */
  2111. if (unlikely(!bfqd->nonrot_with_queueing && prev != bfqq->next_rq))
  2112. bfq_pos_tree_add_move(bfqd, bfqq);
  2113. if (!bfq_bfqq_busy(bfqq)) /* switching to busy ... */
  2114. bfq_bfqq_handle_idle_busy_switch(bfqd, bfqq, old_wr_coeff,
  2115. rq, &interactive);
  2116. else {
  2117. if (bfqd->low_latency && old_wr_coeff == 1 && !rq_is_sync(rq) &&
  2118. time_is_before_jiffies(
  2119. bfqq->last_wr_start_finish +
  2120. bfqd->bfq_wr_min_inter_arr_async)) {
  2121. bfqq->wr_coeff = bfqd->bfq_wr_coeff;
  2122. bfqq->wr_cur_max_time = bfq_wr_duration(bfqd);
  2123. bfqd->wr_busy_queues++;
  2124. bfqq->entity.prio_changed = 1;
  2125. }
  2126. if (prev != bfqq->next_rq)
  2127. bfq_updated_next_req(bfqd, bfqq);
  2128. }
  2129. /*
  2130. * Assign jiffies to last_wr_start_finish in the following
  2131. * cases:
  2132. *
  2133. * . if bfqq is not going to be weight-raised, because, for
  2134. * non weight-raised queues, last_wr_start_finish stores the
  2135. * arrival time of the last request; as of now, this piece
  2136. * of information is used only for deciding whether to
  2137. * weight-raise async queues
  2138. *
  2139. * . if bfqq is not weight-raised, because, if bfqq is now
  2140. * switching to weight-raised, then last_wr_start_finish
  2141. * stores the time when weight-raising starts
  2142. *
  2143. * . if bfqq is interactive, because, regardless of whether
  2144. * bfqq is currently weight-raised, the weight-raising
  2145. * period must start or restart (this case is considered
  2146. * separately because it is not detected by the above
  2147. * conditions, if bfqq is already weight-raised)
  2148. *
  2149. * last_wr_start_finish has to be updated also if bfqq is soft
  2150. * real-time, because the weight-raising period is constantly
  2151. * restarted on idle-to-busy transitions for these queues, but
  2152. * this is already done in bfq_bfqq_handle_idle_busy_switch if
  2153. * needed.
  2154. */
  2155. if (bfqd->low_latency &&
  2156. (old_wr_coeff == 1 || bfqq->wr_coeff == 1 || interactive))
  2157. bfqq->last_wr_start_finish = jiffies;
  2158. }
  2159. static struct request *bfq_find_rq_fmerge(struct bfq_data *bfqd,
  2160. struct bio *bio,
  2161. struct request_queue *q)
  2162. {
  2163. struct bfq_queue *bfqq = bfqd->bio_bfqq;
  2164. if (bfqq)
  2165. return elv_rb_find(&bfqq->sort_list, bio_end_sector(bio));
  2166. return NULL;
  2167. }
  2168. static sector_t get_sdist(sector_t last_pos, struct request *rq)
  2169. {
  2170. if (last_pos)
  2171. return abs(blk_rq_pos(rq) - last_pos);
  2172. return 0;
  2173. }
  2174. static void bfq_remove_request(struct request_queue *q,
  2175. struct request *rq)
  2176. {
  2177. struct bfq_queue *bfqq = RQ_BFQQ(rq);
  2178. struct bfq_data *bfqd = bfqq->bfqd;
  2179. const int sync = rq_is_sync(rq);
  2180. if (bfqq->next_rq == rq) {
  2181. bfqq->next_rq = bfq_find_next_rq(bfqd, bfqq, rq);
  2182. bfq_updated_next_req(bfqd, bfqq);
  2183. }
  2184. if (rq->queuelist.prev != &rq->queuelist)
  2185. list_del_init(&rq->queuelist);
  2186. bfqq->queued[sync]--;
  2187. /*
  2188. * Updating of 'bfqd->queued' is protected by 'bfqd->lock', however, it
  2189. * may be read without holding the lock in bfq_has_work().
  2190. */
  2191. WRITE_ONCE(bfqd->queued, bfqd->queued - 1);
  2192. elv_rb_del(&bfqq->sort_list, rq);
  2193. elv_rqhash_del(q, rq);
  2194. if (q->last_merge == rq)
  2195. q->last_merge = NULL;
  2196. if (RB_EMPTY_ROOT(&bfqq->sort_list)) {
  2197. bfqq->next_rq = NULL;
  2198. if (bfq_bfqq_busy(bfqq) && bfqq != bfqd->in_service_queue) {
  2199. bfq_del_bfqq_busy(bfqq, false);
  2200. /*
  2201. * bfqq emptied. In normal operation, when
  2202. * bfqq is empty, bfqq->entity.service and
  2203. * bfqq->entity.budget must contain,
  2204. * respectively, the service received and the
  2205. * budget used last time bfqq emptied. These
  2206. * facts do not hold in this case, as at least
  2207. * this last removal occurred while bfqq is
  2208. * not in service. To avoid inconsistencies,
  2209. * reset both bfqq->entity.service and
  2210. * bfqq->entity.budget, if bfqq has still a
  2211. * process that may issue I/O requests to it.
  2212. */
  2213. bfqq->entity.budget = bfqq->entity.service = 0;
  2214. }
  2215. /*
  2216. * Remove queue from request-position tree as it is empty.
  2217. */
  2218. if (bfqq->pos_root) {
  2219. rb_erase(&bfqq->pos_node, bfqq->pos_root);
  2220. bfqq->pos_root = NULL;
  2221. }
  2222. } else {
  2223. /* see comments on bfq_pos_tree_add_move() for the unlikely() */
  2224. if (unlikely(!bfqd->nonrot_with_queueing))
  2225. bfq_pos_tree_add_move(bfqd, bfqq);
  2226. }
  2227. if (rq->cmd_flags & REQ_META)
  2228. bfqq->meta_pending--;
  2229. }
  2230. static bool bfq_bio_merge(struct request_queue *q, struct bio *bio,
  2231. unsigned int nr_segs)
  2232. {
  2233. struct bfq_data *bfqd = q->elevator->elevator_data;
  2234. struct bfq_io_cq *bic = bfq_bic_lookup(q);
  2235. struct request *free = NULL;
  2236. bool ret;
  2237. spin_lock_irq(&bfqd->lock);
  2238. if (bic) {
  2239. /*
  2240. * Make sure cgroup info is uptodate for current process before
  2241. * considering the merge.
  2242. */
  2243. bfq_bic_update_cgroup(bic, bio);
  2244. bfqd->bio_bfqq = bic_to_bfqq(bic, op_is_sync(bio->bi_opf),
  2245. bfq_actuator_index(bfqd, bio));
  2246. } else {
  2247. bfqd->bio_bfqq = NULL;
  2248. }
  2249. bfqd->bio_bic = bic;
  2250. ret = blk_mq_sched_try_merge(q, bio, nr_segs, &free);
  2251. spin_unlock_irq(&bfqd->lock);
  2252. if (free)
  2253. blk_mq_free_request(free);
  2254. return ret;
  2255. }
  2256. static int bfq_request_merge(struct request_queue *q, struct request **req,
  2257. struct bio *bio)
  2258. {
  2259. struct bfq_data *bfqd = q->elevator->elevator_data;
  2260. struct request *__rq;
  2261. __rq = bfq_find_rq_fmerge(bfqd, bio, q);
  2262. if (__rq && elv_bio_merge_ok(__rq, bio)) {
  2263. *req = __rq;
  2264. if (blk_discard_mergable(__rq))
  2265. return ELEVATOR_DISCARD_MERGE;
  2266. return ELEVATOR_FRONT_MERGE;
  2267. }
  2268. return ELEVATOR_NO_MERGE;
  2269. }
  2270. static void bfq_request_merged(struct request_queue *q, struct request *req,
  2271. enum elv_merge type)
  2272. {
  2273. if (type == ELEVATOR_FRONT_MERGE &&
  2274. rb_prev(&req->rb_node) &&
  2275. blk_rq_pos(req) <
  2276. blk_rq_pos(container_of(rb_prev(&req->rb_node),
  2277. struct request, rb_node))) {
  2278. struct bfq_queue *bfqq = RQ_BFQQ(req);
  2279. struct bfq_data *bfqd;
  2280. struct request *prev, *next_rq;
  2281. if (!bfqq)
  2282. return;
  2283. bfqd = bfqq->bfqd;
  2284. /* Reposition request in its sort_list */
  2285. elv_rb_del(&bfqq->sort_list, req);
  2286. elv_rb_add(&bfqq->sort_list, req);
  2287. /* Choose next request to be served for bfqq */
  2288. prev = bfqq->next_rq;
  2289. next_rq = bfq_choose_req(bfqd, bfqq->next_rq, req,
  2290. bfqd->last_position);
  2291. bfqq->next_rq = next_rq;
  2292. /*
  2293. * If next_rq changes, update both the queue's budget to
  2294. * fit the new request and the queue's position in its
  2295. * rq_pos_tree.
  2296. */
  2297. if (prev != bfqq->next_rq) {
  2298. bfq_updated_next_req(bfqd, bfqq);
  2299. /*
  2300. * See comments on bfq_pos_tree_add_move() for
  2301. * the unlikely().
  2302. */
  2303. if (unlikely(!bfqd->nonrot_with_queueing))
  2304. bfq_pos_tree_add_move(bfqd, bfqq);
  2305. }
  2306. }
  2307. }
  2308. /*
  2309. * This function is called to notify the scheduler that the requests
  2310. * rq and 'next' have been merged, with 'next' going away. BFQ
  2311. * exploits this hook to address the following issue: if 'next' has a
  2312. * fifo_time lower that rq, then the fifo_time of rq must be set to
  2313. * the value of 'next', to not forget the greater age of 'next'.
  2314. *
  2315. * NOTE: in this function we assume that rq is in a bfq_queue, basing
  2316. * on that rq is picked from the hash table q->elevator->hash, which,
  2317. * in its turn, is filled only with I/O requests present in
  2318. * bfq_queues, while BFQ is in use for the request queue q. In fact,
  2319. * the function that fills this hash table (elv_rqhash_add) is called
  2320. * only by bfq_insert_request.
  2321. */
  2322. static void bfq_requests_merged(struct request_queue *q, struct request *rq,
  2323. struct request *next)
  2324. {
  2325. struct bfq_queue *bfqq = RQ_BFQQ(rq),
  2326. *next_bfqq = RQ_BFQQ(next);
  2327. if (!bfqq)
  2328. goto remove;
  2329. /*
  2330. * If next and rq belong to the same bfq_queue and next is older
  2331. * than rq, then reposition rq in the fifo (by substituting next
  2332. * with rq). Otherwise, if next and rq belong to different
  2333. * bfq_queues, never reposition rq: in fact, we would have to
  2334. * reposition it with respect to next's position in its own fifo,
  2335. * which would most certainly be too expensive with respect to
  2336. * the benefits.
  2337. */
  2338. if (bfqq == next_bfqq &&
  2339. !list_empty(&rq->queuelist) && !list_empty(&next->queuelist) &&
  2340. next->fifo_time < rq->fifo_time) {
  2341. list_del_init(&rq->queuelist);
  2342. list_replace_init(&next->queuelist, &rq->queuelist);
  2343. rq->fifo_time = next->fifo_time;
  2344. }
  2345. if (bfqq->next_rq == next)
  2346. bfqq->next_rq = rq;
  2347. bfqg_stats_update_io_merged(bfqq_group(bfqq), next->cmd_flags);
  2348. remove:
  2349. /* Merged request may be in the IO scheduler. Remove it. */
  2350. if (!RB_EMPTY_NODE(&next->rb_node)) {
  2351. bfq_remove_request(next->q, next);
  2352. if (next_bfqq)
  2353. bfqg_stats_update_io_remove(bfqq_group(next_bfqq),
  2354. next->cmd_flags);
  2355. }
  2356. }
  2357. /* Must be called with bfqq != NULL */
  2358. static void bfq_bfqq_end_wr(struct bfq_queue *bfqq)
  2359. {
  2360. /*
  2361. * If bfqq has been enjoying interactive weight-raising, then
  2362. * reset soft_rt_next_start. We do it for the following
  2363. * reason. bfqq may have been conveying the I/O needed to load
  2364. * a soft real-time application. Such an application actually
  2365. * exhibits a soft real-time I/O pattern after it finishes
  2366. * loading, and finally starts doing its job. But, if bfqq has
  2367. * been receiving a lot of bandwidth so far (likely to happen
  2368. * on a fast device), then soft_rt_next_start now contains a
  2369. * high value that. So, without this reset, bfqq would be
  2370. * prevented from being possibly considered as soft_rt for a
  2371. * very long time.
  2372. */
  2373. if (bfqq->wr_cur_max_time !=
  2374. bfqq->bfqd->bfq_wr_rt_max_time)
  2375. bfqq->soft_rt_next_start = jiffies;
  2376. if (bfq_bfqq_busy(bfqq))
  2377. bfqq->bfqd->wr_busy_queues--;
  2378. bfqq->wr_coeff = 1;
  2379. bfqq->wr_cur_max_time = 0;
  2380. bfqq->last_wr_start_finish = jiffies;
  2381. /*
  2382. * Trigger a weight change on the next invocation of
  2383. * __bfq_entity_update_weight_prio.
  2384. */
  2385. bfqq->entity.prio_changed = 1;
  2386. }
  2387. void bfq_end_wr_async_queues(struct bfq_data *bfqd,
  2388. struct bfq_group *bfqg)
  2389. {
  2390. int i, j, k;
  2391. for (k = 0; k < bfqd->num_actuators; k++) {
  2392. for (i = 0; i < 2; i++)
  2393. for (j = 0; j < IOPRIO_NR_LEVELS; j++)
  2394. if (bfqg->async_bfqq[i][j][k])
  2395. bfq_bfqq_end_wr(bfqg->async_bfqq[i][j][k]);
  2396. if (bfqg->async_idle_bfqq[k])
  2397. bfq_bfqq_end_wr(bfqg->async_idle_bfqq[k]);
  2398. }
  2399. }
  2400. static void bfq_end_wr(struct bfq_data *bfqd)
  2401. {
  2402. struct bfq_queue *bfqq;
  2403. int i;
  2404. spin_lock_irq(&bfqd->lock);
  2405. for (i = 0; i < bfqd->num_actuators; i++) {
  2406. list_for_each_entry(bfqq, &bfqd->active_list[i], bfqq_list)
  2407. bfq_bfqq_end_wr(bfqq);
  2408. }
  2409. list_for_each_entry(bfqq, &bfqd->idle_list, bfqq_list)
  2410. bfq_bfqq_end_wr(bfqq);
  2411. bfq_end_wr_async(bfqd);
  2412. spin_unlock_irq(&bfqd->lock);
  2413. }
  2414. static sector_t bfq_io_struct_pos(void *io_struct, bool request)
  2415. {
  2416. if (request)
  2417. return blk_rq_pos(io_struct);
  2418. else
  2419. return ((struct bio *)io_struct)->bi_iter.bi_sector;
  2420. }
  2421. static int bfq_rq_close_to_sector(void *io_struct, bool request,
  2422. sector_t sector)
  2423. {
  2424. return abs(bfq_io_struct_pos(io_struct, request) - sector) <=
  2425. BFQQ_CLOSE_THR;
  2426. }
  2427. static struct bfq_queue *bfqq_find_close(struct bfq_data *bfqd,
  2428. struct bfq_queue *bfqq,
  2429. sector_t sector)
  2430. {
  2431. struct rb_root *root = &bfqq_group(bfqq)->rq_pos_tree;
  2432. struct rb_node *parent, *node;
  2433. struct bfq_queue *__bfqq;
  2434. if (RB_EMPTY_ROOT(root))
  2435. return NULL;
  2436. /*
  2437. * First, if we find a request starting at the end of the last
  2438. * request, choose it.
  2439. */
  2440. __bfqq = bfq_rq_pos_tree_lookup(bfqd, root, sector, &parent, NULL);
  2441. if (__bfqq)
  2442. return __bfqq;
  2443. /*
  2444. * If the exact sector wasn't found, the parent of the NULL leaf
  2445. * will contain the closest sector (rq_pos_tree sorted by
  2446. * next_request position).
  2447. */
  2448. __bfqq = rb_entry(parent, struct bfq_queue, pos_node);
  2449. if (bfq_rq_close_to_sector(__bfqq->next_rq, true, sector))
  2450. return __bfqq;
  2451. if (blk_rq_pos(__bfqq->next_rq) < sector)
  2452. node = rb_next(&__bfqq->pos_node);
  2453. else
  2454. node = rb_prev(&__bfqq->pos_node);
  2455. if (!node)
  2456. return NULL;
  2457. __bfqq = rb_entry(node, struct bfq_queue, pos_node);
  2458. if (bfq_rq_close_to_sector(__bfqq->next_rq, true, sector))
  2459. return __bfqq;
  2460. return NULL;
  2461. }
  2462. static struct bfq_queue *bfq_find_close_cooperator(struct bfq_data *bfqd,
  2463. struct bfq_queue *cur_bfqq,
  2464. sector_t sector)
  2465. {
  2466. struct bfq_queue *bfqq;
  2467. /*
  2468. * We shall notice if some of the queues are cooperating,
  2469. * e.g., working closely on the same area of the device. In
  2470. * that case, we can group them together and: 1) don't waste
  2471. * time idling, and 2) serve the union of their requests in
  2472. * the best possible order for throughput.
  2473. */
  2474. bfqq = bfqq_find_close(bfqd, cur_bfqq, sector);
  2475. if (!bfqq || bfqq == cur_bfqq)
  2476. return NULL;
  2477. return bfqq;
  2478. }
  2479. static struct bfq_queue *
  2480. bfq_setup_merge(struct bfq_queue *bfqq, struct bfq_queue *new_bfqq)
  2481. {
  2482. int process_refs, new_process_refs;
  2483. struct bfq_queue *__bfqq;
  2484. /*
  2485. * If there are no process references on the new_bfqq, then it is
  2486. * unsafe to follow the ->new_bfqq chain as other bfqq's in the chain
  2487. * may have dropped their last reference (not just their last process
  2488. * reference).
  2489. */
  2490. if (!bfqq_process_refs(new_bfqq))
  2491. return NULL;
  2492. /* Avoid a circular list and skip interim queue merges. */
  2493. while ((__bfqq = new_bfqq->new_bfqq)) {
  2494. if (__bfqq == bfqq)
  2495. return NULL;
  2496. new_bfqq = __bfqq;
  2497. }
  2498. process_refs = bfqq_process_refs(bfqq);
  2499. new_process_refs = bfqq_process_refs(new_bfqq);
  2500. /*
  2501. * If the process for the bfqq has gone away, there is no
  2502. * sense in merging the queues.
  2503. */
  2504. if (process_refs == 0 || new_process_refs == 0)
  2505. return NULL;
  2506. /*
  2507. * Make sure merged queues belong to the same parent. Parents could
  2508. * have changed since the time we decided the two queues are suitable
  2509. * for merging.
  2510. */
  2511. if (new_bfqq->entity.parent != bfqq->entity.parent)
  2512. return NULL;
  2513. bfq_log_bfqq(bfqq->bfqd, bfqq, "scheduling merge with queue %d",
  2514. new_bfqq->pid);
  2515. /*
  2516. * Merging is just a redirection: the requests of the process
  2517. * owning one of the two queues are redirected to the other queue.
  2518. * The latter queue, in its turn, is set as shared if this is the
  2519. * first time that the requests of some process are redirected to
  2520. * it.
  2521. *
  2522. * We redirect bfqq to new_bfqq and not the opposite, because
  2523. * we are in the context of the process owning bfqq, thus we
  2524. * have the io_cq of this process. So we can immediately
  2525. * configure this io_cq to redirect the requests of the
  2526. * process to new_bfqq. In contrast, the io_cq of new_bfqq is
  2527. * not available any more (new_bfqq->bic == NULL).
  2528. *
  2529. * Anyway, even in case new_bfqq coincides with the in-service
  2530. * queue, redirecting requests the in-service queue is the
  2531. * best option, as we feed the in-service queue with new
  2532. * requests close to the last request served and, by doing so,
  2533. * are likely to increase the throughput.
  2534. */
  2535. bfqq->new_bfqq = new_bfqq;
  2536. /*
  2537. * The above assignment schedules the following redirections:
  2538. * each time some I/O for bfqq arrives, the process that
  2539. * generated that I/O is disassociated from bfqq and
  2540. * associated with new_bfqq. Here we increases new_bfqq->ref
  2541. * in advance, adding the number of processes that are
  2542. * expected to be associated with new_bfqq as they happen to
  2543. * issue I/O.
  2544. */
  2545. new_bfqq->ref += process_refs;
  2546. return new_bfqq;
  2547. }
  2548. static bool bfq_may_be_close_cooperator(struct bfq_queue *bfqq,
  2549. struct bfq_queue *new_bfqq)
  2550. {
  2551. if (bfq_too_late_for_merging(new_bfqq))
  2552. return false;
  2553. if (bfq_class_idle(bfqq) || bfq_class_idle(new_bfqq) ||
  2554. (bfqq->ioprio_class != new_bfqq->ioprio_class))
  2555. return false;
  2556. /*
  2557. * If either of the queues has already been detected as seeky,
  2558. * then merging it with the other queue is unlikely to lead to
  2559. * sequential I/O.
  2560. */
  2561. if (BFQQ_SEEKY(bfqq) || BFQQ_SEEKY(new_bfqq))
  2562. return false;
  2563. /*
  2564. * Interleaved I/O is known to be done by (some) applications
  2565. * only for reads, so it does not make sense to merge async
  2566. * queues.
  2567. */
  2568. if (!bfq_bfqq_sync(bfqq) || !bfq_bfqq_sync(new_bfqq))
  2569. return false;
  2570. return true;
  2571. }
  2572. static bool idling_boosts_thr_without_issues(struct bfq_data *bfqd,
  2573. struct bfq_queue *bfqq);
  2574. static struct bfq_queue *
  2575. bfq_setup_stable_merge(struct bfq_data *bfqd, struct bfq_queue *bfqq,
  2576. struct bfq_queue *stable_merge_bfqq,
  2577. struct bfq_iocq_bfqq_data *bfqq_data)
  2578. {
  2579. int proc_ref = min(bfqq_process_refs(bfqq),
  2580. bfqq_process_refs(stable_merge_bfqq));
  2581. struct bfq_queue *new_bfqq = NULL;
  2582. bfqq_data->stable_merge_bfqq = NULL;
  2583. if (idling_boosts_thr_without_issues(bfqd, bfqq) || proc_ref == 0)
  2584. goto out;
  2585. /* next function will take at least one ref */
  2586. new_bfqq = bfq_setup_merge(bfqq, stable_merge_bfqq);
  2587. if (new_bfqq) {
  2588. bfqq_data->stably_merged = true;
  2589. if (new_bfqq->bic) {
  2590. unsigned int new_a_idx = new_bfqq->actuator_idx;
  2591. struct bfq_iocq_bfqq_data *new_bfqq_data =
  2592. &new_bfqq->bic->bfqq_data[new_a_idx];
  2593. new_bfqq_data->stably_merged = true;
  2594. }
  2595. }
  2596. out:
  2597. /* deschedule stable merge, because done or aborted here */
  2598. bfq_put_stable_ref(stable_merge_bfqq);
  2599. return new_bfqq;
  2600. }
  2601. /*
  2602. * Attempt to schedule a merge of bfqq with the currently in-service
  2603. * queue or with a close queue among the scheduled queues. Return
  2604. * NULL if no merge was scheduled, a pointer to the shared bfq_queue
  2605. * structure otherwise.
  2606. *
  2607. * The OOM queue is not allowed to participate to cooperation: in fact, since
  2608. * the requests temporarily redirected to the OOM queue could be redirected
  2609. * again to dedicated queues at any time, the state needed to correctly
  2610. * handle merging with the OOM queue would be quite complex and expensive
  2611. * to maintain. Besides, in such a critical condition as an out of memory,
  2612. * the benefits of queue merging may be little relevant, or even negligible.
  2613. *
  2614. * WARNING: queue merging may impair fairness among non-weight raised
  2615. * queues, for at least two reasons: 1) the original weight of a
  2616. * merged queue may change during the merged state, 2) even being the
  2617. * weight the same, a merged queue may be bloated with many more
  2618. * requests than the ones produced by its originally-associated
  2619. * process.
  2620. */
  2621. static struct bfq_queue *
  2622. bfq_setup_cooperator(struct bfq_data *bfqd, struct bfq_queue *bfqq,
  2623. void *io_struct, bool request, struct bfq_io_cq *bic)
  2624. {
  2625. struct bfq_queue *in_service_bfqq, *new_bfqq;
  2626. unsigned int a_idx = bfqq->actuator_idx;
  2627. struct bfq_iocq_bfqq_data *bfqq_data = &bic->bfqq_data[a_idx];
  2628. /* if a merge has already been setup, then proceed with that first */
  2629. new_bfqq = bfqq->new_bfqq;
  2630. if (new_bfqq) {
  2631. while (new_bfqq->new_bfqq)
  2632. new_bfqq = new_bfqq->new_bfqq;
  2633. return new_bfqq;
  2634. }
  2635. /*
  2636. * Check delayed stable merge for rotational or non-queueing
  2637. * devs. For this branch to be executed, bfqq must not be
  2638. * currently merged with some other queue (i.e., bfqq->bic
  2639. * must be non null). If we considered also merged queues,
  2640. * then we should also check whether bfqq has already been
  2641. * merged with bic->stable_merge_bfqq. But this would be
  2642. * costly and complicated.
  2643. */
  2644. if (unlikely(!bfqd->nonrot_with_queueing)) {
  2645. /*
  2646. * Make sure also that bfqq is sync, because
  2647. * bic->stable_merge_bfqq may point to some queue (for
  2648. * stable merging) also if bic is associated with a
  2649. * sync queue, but this bfqq is async
  2650. */
  2651. if (bfq_bfqq_sync(bfqq) && bfqq_data->stable_merge_bfqq &&
  2652. !bfq_bfqq_just_created(bfqq) &&
  2653. time_is_before_jiffies(bfqq->split_time +
  2654. msecs_to_jiffies(bfq_late_stable_merging)) &&
  2655. time_is_before_jiffies(bfqq->creation_time +
  2656. msecs_to_jiffies(bfq_late_stable_merging))) {
  2657. struct bfq_queue *stable_merge_bfqq =
  2658. bfqq_data->stable_merge_bfqq;
  2659. return bfq_setup_stable_merge(bfqd, bfqq,
  2660. stable_merge_bfqq,
  2661. bfqq_data);
  2662. }
  2663. }
  2664. /*
  2665. * Do not perform queue merging if the device is non
  2666. * rotational and performs internal queueing. In fact, such a
  2667. * device reaches a high speed through internal parallelism
  2668. * and pipelining. This means that, to reach a high
  2669. * throughput, it must have many requests enqueued at the same
  2670. * time. But, in this configuration, the internal scheduling
  2671. * algorithm of the device does exactly the job of queue
  2672. * merging: it reorders requests so as to obtain as much as
  2673. * possible a sequential I/O pattern. As a consequence, with
  2674. * the workload generated by processes doing interleaved I/O,
  2675. * the throughput reached by the device is likely to be the
  2676. * same, with and without queue merging.
  2677. *
  2678. * Disabling merging also provides a remarkable benefit in
  2679. * terms of throughput. Merging tends to make many workloads
  2680. * artificially more uneven, because of shared queues
  2681. * remaining non empty for incomparably more time than
  2682. * non-merged queues. This may accentuate workload
  2683. * asymmetries. For example, if one of the queues in a set of
  2684. * merged queues has a higher weight than a normal queue, then
  2685. * the shared queue may inherit such a high weight and, by
  2686. * staying almost always active, may force BFQ to perform I/O
  2687. * plugging most of the time. This evidently makes it harder
  2688. * for BFQ to let the device reach a high throughput.
  2689. *
  2690. * Finally, the likely() macro below is not used because one
  2691. * of the two branches is more likely than the other, but to
  2692. * have the code path after the following if() executed as
  2693. * fast as possible for the case of a non rotational device
  2694. * with queueing. We want it because this is the fastest kind
  2695. * of device. On the opposite end, the likely() may lengthen
  2696. * the execution time of BFQ for the case of slower devices
  2697. * (rotational or at least without queueing). But in this case
  2698. * the execution time of BFQ matters very little, if not at
  2699. * all.
  2700. */
  2701. if (likely(bfqd->nonrot_with_queueing))
  2702. return NULL;
  2703. /*
  2704. * Prevent bfqq from being merged if it has been created too
  2705. * long ago. The idea is that true cooperating processes, and
  2706. * thus their associated bfq_queues, are supposed to be
  2707. * created shortly after each other. This is the case, e.g.,
  2708. * for KVM/QEMU and dump I/O threads. Basing on this
  2709. * assumption, the following filtering greatly reduces the
  2710. * probability that two non-cooperating processes, which just
  2711. * happen to do close I/O for some short time interval, have
  2712. * their queues merged by mistake.
  2713. */
  2714. if (bfq_too_late_for_merging(bfqq))
  2715. return NULL;
  2716. if (!io_struct || unlikely(bfqq == &bfqd->oom_bfqq))
  2717. return NULL;
  2718. /* If there is only one backlogged queue, don't search. */
  2719. if (bfq_tot_busy_queues(bfqd) == 1)
  2720. return NULL;
  2721. in_service_bfqq = bfqd->in_service_queue;
  2722. if (in_service_bfqq && in_service_bfqq != bfqq &&
  2723. likely(in_service_bfqq != &bfqd->oom_bfqq) &&
  2724. bfq_rq_close_to_sector(io_struct, request,
  2725. bfqd->in_serv_last_pos) &&
  2726. bfqq->entity.parent == in_service_bfqq->entity.parent &&
  2727. bfq_may_be_close_cooperator(bfqq, in_service_bfqq)) {
  2728. new_bfqq = bfq_setup_merge(bfqq, in_service_bfqq);
  2729. if (new_bfqq)
  2730. return new_bfqq;
  2731. }
  2732. /*
  2733. * Check whether there is a cooperator among currently scheduled
  2734. * queues. The only thing we need is that the bio/request is not
  2735. * NULL, as we need it to establish whether a cooperator exists.
  2736. */
  2737. new_bfqq = bfq_find_close_cooperator(bfqd, bfqq,
  2738. bfq_io_struct_pos(io_struct, request));
  2739. if (new_bfqq && likely(new_bfqq != &bfqd->oom_bfqq) &&
  2740. bfq_may_be_close_cooperator(bfqq, new_bfqq))
  2741. return bfq_setup_merge(bfqq, new_bfqq);
  2742. return NULL;
  2743. }
  2744. static void bfq_bfqq_save_state(struct bfq_queue *bfqq)
  2745. {
  2746. struct bfq_io_cq *bic = bfqq->bic;
  2747. unsigned int a_idx = bfqq->actuator_idx;
  2748. struct bfq_iocq_bfqq_data *bfqq_data = &bic->bfqq_data[a_idx];
  2749. /*
  2750. * If !bfqq->bic, the queue is already shared or its requests
  2751. * have already been redirected to a shared queue; both idle window
  2752. * and weight raising state have already been saved. Do nothing.
  2753. */
  2754. if (!bic)
  2755. return;
  2756. bfqq_data->saved_last_serv_time_ns = bfqq->last_serv_time_ns;
  2757. bfqq_data->saved_inject_limit = bfqq->inject_limit;
  2758. bfqq_data->saved_decrease_time_jif = bfqq->decrease_time_jif;
  2759. bfqq_data->saved_weight = bfqq->entity.orig_weight;
  2760. bfqq_data->saved_ttime = bfqq->ttime;
  2761. bfqq_data->saved_has_short_ttime =
  2762. bfq_bfqq_has_short_ttime(bfqq);
  2763. bfqq_data->saved_IO_bound = bfq_bfqq_IO_bound(bfqq);
  2764. bfqq_data->saved_io_start_time = bfqq->io_start_time;
  2765. bfqq_data->saved_tot_idle_time = bfqq->tot_idle_time;
  2766. bfqq_data->saved_in_large_burst = bfq_bfqq_in_large_burst(bfqq);
  2767. bfqq_data->was_in_burst_list =
  2768. !hlist_unhashed(&bfqq->burst_list_node);
  2769. if (unlikely(bfq_bfqq_just_created(bfqq) &&
  2770. !bfq_bfqq_in_large_burst(bfqq) &&
  2771. bfqq->bfqd->low_latency)) {
  2772. /*
  2773. * bfqq being merged right after being created: bfqq
  2774. * would have deserved interactive weight raising, but
  2775. * did not make it to be set in a weight-raised state,
  2776. * because of this early merge. Store directly the
  2777. * weight-raising state that would have been assigned
  2778. * to bfqq, so that to avoid that bfqq unjustly fails
  2779. * to enjoy weight raising if split soon.
  2780. */
  2781. bfqq_data->saved_wr_coeff = bfqq->bfqd->bfq_wr_coeff;
  2782. bfqq_data->saved_wr_start_at_switch_to_srt =
  2783. bfq_smallest_from_now();
  2784. bfqq_data->saved_wr_cur_max_time =
  2785. bfq_wr_duration(bfqq->bfqd);
  2786. bfqq_data->saved_last_wr_start_finish = jiffies;
  2787. } else {
  2788. bfqq_data->saved_wr_coeff = bfqq->wr_coeff;
  2789. bfqq_data->saved_wr_start_at_switch_to_srt =
  2790. bfqq->wr_start_at_switch_to_srt;
  2791. bfqq_data->saved_service_from_wr =
  2792. bfqq->service_from_wr;
  2793. bfqq_data->saved_last_wr_start_finish =
  2794. bfqq->last_wr_start_finish;
  2795. bfqq_data->saved_wr_cur_max_time = bfqq->wr_cur_max_time;
  2796. }
  2797. }
  2798. void bfq_reassign_last_bfqq(struct bfq_queue *cur_bfqq,
  2799. struct bfq_queue *new_bfqq)
  2800. {
  2801. if (cur_bfqq->entity.parent &&
  2802. cur_bfqq->entity.parent->last_bfqq_created == cur_bfqq)
  2803. cur_bfqq->entity.parent->last_bfqq_created = new_bfqq;
  2804. else if (cur_bfqq->bfqd && cur_bfqq->bfqd->last_bfqq_created == cur_bfqq)
  2805. cur_bfqq->bfqd->last_bfqq_created = new_bfqq;
  2806. }
  2807. void bfq_release_process_ref(struct bfq_data *bfqd, struct bfq_queue *bfqq)
  2808. {
  2809. /*
  2810. * To prevent bfqq's service guarantees from being violated,
  2811. * bfqq may be left busy, i.e., queued for service, even if
  2812. * empty (see comments in __bfq_bfqq_expire() for
  2813. * details). But, if no process will send requests to bfqq any
  2814. * longer, then there is no point in keeping bfqq queued for
  2815. * service. In addition, keeping bfqq queued for service, but
  2816. * with no process ref any longer, may have caused bfqq to be
  2817. * freed when dequeued from service. But this is assumed to
  2818. * never happen.
  2819. */
  2820. if (bfq_bfqq_busy(bfqq) && RB_EMPTY_ROOT(&bfqq->sort_list) &&
  2821. bfqq != bfqd->in_service_queue)
  2822. bfq_del_bfqq_busy(bfqq, false);
  2823. bfq_reassign_last_bfqq(bfqq, NULL);
  2824. bfq_put_queue(bfqq);
  2825. }
  2826. static struct bfq_queue *bfq_merge_bfqqs(struct bfq_data *bfqd,
  2827. struct bfq_io_cq *bic,
  2828. struct bfq_queue *bfqq)
  2829. {
  2830. struct bfq_queue *new_bfqq = bfqq->new_bfqq;
  2831. bfq_log_bfqq(bfqd, bfqq, "merging with queue %lu",
  2832. (unsigned long)new_bfqq->pid);
  2833. /* Save weight raising and idle window of the merged queues */
  2834. bfq_bfqq_save_state(bfqq);
  2835. bfq_bfqq_save_state(new_bfqq);
  2836. if (bfq_bfqq_IO_bound(bfqq))
  2837. bfq_mark_bfqq_IO_bound(new_bfqq);
  2838. bfq_clear_bfqq_IO_bound(bfqq);
  2839. /*
  2840. * The processes associated with bfqq are cooperators of the
  2841. * processes associated with new_bfqq. So, if bfqq has a
  2842. * waker, then assume that all these processes will be happy
  2843. * to let bfqq's waker freely inject I/O when they have no
  2844. * I/O.
  2845. */
  2846. if (bfqq->waker_bfqq && !new_bfqq->waker_bfqq &&
  2847. bfqq->waker_bfqq != new_bfqq) {
  2848. new_bfqq->waker_bfqq = bfqq->waker_bfqq;
  2849. new_bfqq->tentative_waker_bfqq = NULL;
  2850. /*
  2851. * If the waker queue disappears, then
  2852. * new_bfqq->waker_bfqq must be reset. So insert
  2853. * new_bfqq into the woken_list of the waker. See
  2854. * bfq_check_waker for details.
  2855. */
  2856. hlist_add_head(&new_bfqq->woken_list_node,
  2857. &new_bfqq->waker_bfqq->woken_list);
  2858. }
  2859. /*
  2860. * If bfqq is weight-raised, then let new_bfqq inherit
  2861. * weight-raising. To reduce false positives, neglect the case
  2862. * where bfqq has just been created, but has not yet made it
  2863. * to be weight-raised (which may happen because EQM may merge
  2864. * bfqq even before bfq_add_request is executed for the first
  2865. * time for bfqq). Handling this case would however be very
  2866. * easy, thanks to the flag just_created.
  2867. */
  2868. if (new_bfqq->wr_coeff == 1 && bfqq->wr_coeff > 1) {
  2869. new_bfqq->wr_coeff = bfqq->wr_coeff;
  2870. new_bfqq->wr_cur_max_time = bfqq->wr_cur_max_time;
  2871. new_bfqq->last_wr_start_finish = bfqq->last_wr_start_finish;
  2872. new_bfqq->wr_start_at_switch_to_srt =
  2873. bfqq->wr_start_at_switch_to_srt;
  2874. if (bfq_bfqq_busy(new_bfqq))
  2875. bfqd->wr_busy_queues++;
  2876. new_bfqq->entity.prio_changed = 1;
  2877. }
  2878. if (bfqq->wr_coeff > 1) { /* bfqq has given its wr to new_bfqq */
  2879. bfqq->wr_coeff = 1;
  2880. bfqq->entity.prio_changed = 1;
  2881. if (bfq_bfqq_busy(bfqq))
  2882. bfqd->wr_busy_queues--;
  2883. }
  2884. bfq_log_bfqq(bfqd, new_bfqq, "merge_bfqqs: wr_busy %d",
  2885. bfqd->wr_busy_queues);
  2886. /*
  2887. * Merge queues (that is, let bic redirect its requests to new_bfqq)
  2888. */
  2889. bic_set_bfqq(bic, new_bfqq, true, bfqq->actuator_idx);
  2890. bfq_mark_bfqq_coop(new_bfqq);
  2891. /*
  2892. * new_bfqq now belongs to at least two bics (it is a shared queue):
  2893. * set new_bfqq->bic to NULL. bfqq either:
  2894. * - does not belong to any bic any more, and hence bfqq->bic must
  2895. * be set to NULL, or
  2896. * - is a queue whose owning bics have already been redirected to a
  2897. * different queue, hence the queue is destined to not belong to
  2898. * any bic soon and bfqq->bic is already NULL (therefore the next
  2899. * assignment causes no harm).
  2900. */
  2901. new_bfqq->bic = NULL;
  2902. /*
  2903. * If the queue is shared, the pid is the pid of one of the associated
  2904. * processes. Which pid depends on the exact sequence of merge events
  2905. * the queue underwent. So printing such a pid is useless and confusing
  2906. * because it reports a random pid between those of the associated
  2907. * processes.
  2908. * We mark such a queue with a pid -1, and then print SHARED instead of
  2909. * a pid in logging messages.
  2910. */
  2911. new_bfqq->pid = -1;
  2912. bfqq->bic = NULL;
  2913. bfq_reassign_last_bfqq(bfqq, new_bfqq);
  2914. bfq_release_process_ref(bfqd, bfqq);
  2915. return new_bfqq;
  2916. }
  2917. static bool bfq_allow_bio_merge(struct request_queue *q, struct request *rq,
  2918. struct bio *bio)
  2919. {
  2920. struct bfq_data *bfqd = q->elevator->elevator_data;
  2921. bool is_sync = op_is_sync(bio->bi_opf);
  2922. struct bfq_queue *bfqq = bfqd->bio_bfqq, *new_bfqq;
  2923. /*
  2924. * Disallow merge of a sync bio into an async request.
  2925. */
  2926. if (is_sync && !rq_is_sync(rq))
  2927. return false;
  2928. /*
  2929. * Lookup the bfqq that this bio will be queued with. Allow
  2930. * merge only if rq is queued there.
  2931. */
  2932. if (!bfqq)
  2933. return false;
  2934. /*
  2935. * We take advantage of this function to perform an early merge
  2936. * of the queues of possible cooperating processes.
  2937. */
  2938. new_bfqq = bfq_setup_cooperator(bfqd, bfqq, bio, false, bfqd->bio_bic);
  2939. if (new_bfqq) {
  2940. /*
  2941. * bic still points to bfqq, then it has not yet been
  2942. * redirected to some other bfq_queue, and a queue
  2943. * merge between bfqq and new_bfqq can be safely
  2944. * fulfilled, i.e., bic can be redirected to new_bfqq
  2945. * and bfqq can be put.
  2946. */
  2947. while (bfqq != new_bfqq)
  2948. bfqq = bfq_merge_bfqqs(bfqd, bfqd->bio_bic, bfqq);
  2949. /*
  2950. * Change also bqfd->bio_bfqq, as
  2951. * bfqd->bio_bic now points to new_bfqq, and
  2952. * this function may be invoked again (and then may
  2953. * use again bqfd->bio_bfqq).
  2954. */
  2955. bfqd->bio_bfqq = bfqq;
  2956. }
  2957. return bfqq == RQ_BFQQ(rq);
  2958. }
  2959. /*
  2960. * Set the maximum time for the in-service queue to consume its
  2961. * budget. This prevents seeky processes from lowering the throughput.
  2962. * In practice, a time-slice service scheme is used with seeky
  2963. * processes.
  2964. */
  2965. static void bfq_set_budget_timeout(struct bfq_data *bfqd,
  2966. struct bfq_queue *bfqq)
  2967. {
  2968. unsigned int timeout_coeff;
  2969. if (bfqq->wr_cur_max_time == bfqd->bfq_wr_rt_max_time)
  2970. timeout_coeff = 1;
  2971. else
  2972. timeout_coeff = bfqq->entity.weight / bfqq->entity.orig_weight;
  2973. bfqd->last_budget_start = blk_time_get();
  2974. bfqq->budget_timeout = jiffies +
  2975. bfqd->bfq_timeout * timeout_coeff;
  2976. }
  2977. static void __bfq_set_in_service_queue(struct bfq_data *bfqd,
  2978. struct bfq_queue *bfqq)
  2979. {
  2980. if (bfqq) {
  2981. bfq_clear_bfqq_fifo_expire(bfqq);
  2982. bfqd->budgets_assigned = (bfqd->budgets_assigned * 7 + 256) / 8;
  2983. if (time_is_before_jiffies(bfqq->last_wr_start_finish) &&
  2984. bfqq->wr_coeff > 1 &&
  2985. bfqq->wr_cur_max_time == bfqd->bfq_wr_rt_max_time &&
  2986. time_is_before_jiffies(bfqq->budget_timeout)) {
  2987. /*
  2988. * For soft real-time queues, move the start
  2989. * of the weight-raising period forward by the
  2990. * time the queue has not received any
  2991. * service. Otherwise, a relatively long
  2992. * service delay is likely to cause the
  2993. * weight-raising period of the queue to end,
  2994. * because of the short duration of the
  2995. * weight-raising period of a soft real-time
  2996. * queue. It is worth noting that this move
  2997. * is not so dangerous for the other queues,
  2998. * because soft real-time queues are not
  2999. * greedy.
  3000. *
  3001. * To not add a further variable, we use the
  3002. * overloaded field budget_timeout to
  3003. * determine for how long the queue has not
  3004. * received service, i.e., how much time has
  3005. * elapsed since the queue expired. However,
  3006. * this is a little imprecise, because
  3007. * budget_timeout is set to jiffies if bfqq
  3008. * not only expires, but also remains with no
  3009. * request.
  3010. */
  3011. if (time_after(bfqq->budget_timeout,
  3012. bfqq->last_wr_start_finish))
  3013. bfqq->last_wr_start_finish +=
  3014. jiffies - bfqq->budget_timeout;
  3015. else
  3016. bfqq->last_wr_start_finish = jiffies;
  3017. }
  3018. bfq_set_budget_timeout(bfqd, bfqq);
  3019. bfq_log_bfqq(bfqd, bfqq,
  3020. "set_in_service_queue, cur-budget = %d",
  3021. bfqq->entity.budget);
  3022. }
  3023. bfqd->in_service_queue = bfqq;
  3024. bfqd->in_serv_last_pos = 0;
  3025. }
  3026. /*
  3027. * Get and set a new queue for service.
  3028. */
  3029. static struct bfq_queue *bfq_set_in_service_queue(struct bfq_data *bfqd)
  3030. {
  3031. struct bfq_queue *bfqq = bfq_get_next_queue(bfqd);
  3032. __bfq_set_in_service_queue(bfqd, bfqq);
  3033. return bfqq;
  3034. }
  3035. static void bfq_arm_slice_timer(struct bfq_data *bfqd)
  3036. {
  3037. struct bfq_queue *bfqq = bfqd->in_service_queue;
  3038. u32 sl;
  3039. bfq_mark_bfqq_wait_request(bfqq);
  3040. /*
  3041. * We don't want to idle for seeks, but we do want to allow
  3042. * fair distribution of slice time for a process doing back-to-back
  3043. * seeks. So allow a little bit of time for him to submit a new rq.
  3044. */
  3045. sl = bfqd->bfq_slice_idle;
  3046. /*
  3047. * Unless the queue is being weight-raised or the scenario is
  3048. * asymmetric, grant only minimum idle time if the queue
  3049. * is seeky. A long idling is preserved for a weight-raised
  3050. * queue, or, more in general, in an asymmetric scenario,
  3051. * because a long idling is needed for guaranteeing to a queue
  3052. * its reserved share of the throughput (in particular, it is
  3053. * needed if the queue has a higher weight than some other
  3054. * queue).
  3055. */
  3056. if (BFQQ_SEEKY(bfqq) && bfqq->wr_coeff == 1 &&
  3057. !bfq_asymmetric_scenario(bfqd, bfqq))
  3058. sl = min_t(u64, sl, BFQ_MIN_TT);
  3059. else if (bfqq->wr_coeff > 1)
  3060. sl = max_t(u32, sl, 20ULL * NSEC_PER_MSEC);
  3061. bfqd->last_idling_start = blk_time_get();
  3062. bfqd->last_idling_start_jiffies = jiffies;
  3063. hrtimer_start(&bfqd->idle_slice_timer, ns_to_ktime(sl),
  3064. HRTIMER_MODE_REL);
  3065. bfqg_stats_set_start_idle_time(bfqq_group(bfqq));
  3066. }
  3067. /*
  3068. * In autotuning mode, max_budget is dynamically recomputed as the
  3069. * amount of sectors transferred in timeout at the estimated peak
  3070. * rate. This enables BFQ to utilize a full timeslice with a full
  3071. * budget, even if the in-service queue is served at peak rate. And
  3072. * this maximises throughput with sequential workloads.
  3073. */
  3074. static unsigned long bfq_calc_max_budget(struct bfq_data *bfqd)
  3075. {
  3076. return (u64)bfqd->peak_rate * USEC_PER_MSEC *
  3077. jiffies_to_msecs(bfqd->bfq_timeout)>>BFQ_RATE_SHIFT;
  3078. }
  3079. /*
  3080. * Update parameters related to throughput and responsiveness, as a
  3081. * function of the estimated peak rate. See comments on
  3082. * bfq_calc_max_budget(), and on the ref_wr_duration array.
  3083. */
  3084. static void update_thr_responsiveness_params(struct bfq_data *bfqd)
  3085. {
  3086. if (bfqd->bfq_user_max_budget == 0) {
  3087. bfqd->bfq_max_budget =
  3088. bfq_calc_max_budget(bfqd);
  3089. bfq_log(bfqd, "new max_budget = %d", bfqd->bfq_max_budget);
  3090. }
  3091. }
  3092. static void bfq_reset_rate_computation(struct bfq_data *bfqd,
  3093. struct request *rq)
  3094. {
  3095. if (rq != NULL) { /* new rq dispatch now, reset accordingly */
  3096. bfqd->last_dispatch = bfqd->first_dispatch = blk_time_get_ns();
  3097. bfqd->peak_rate_samples = 1;
  3098. bfqd->sequential_samples = 0;
  3099. bfqd->tot_sectors_dispatched = bfqd->last_rq_max_size =
  3100. blk_rq_sectors(rq);
  3101. } else /* no new rq dispatched, just reset the number of samples */
  3102. bfqd->peak_rate_samples = 0; /* full re-init on next disp. */
  3103. bfq_log(bfqd,
  3104. "reset_rate_computation at end, sample %u/%u tot_sects %llu",
  3105. bfqd->peak_rate_samples, bfqd->sequential_samples,
  3106. bfqd->tot_sectors_dispatched);
  3107. }
  3108. static void bfq_update_rate_reset(struct bfq_data *bfqd, struct request *rq)
  3109. {
  3110. u32 rate, weight, divisor;
  3111. /*
  3112. * For the convergence property to hold (see comments on
  3113. * bfq_update_peak_rate()) and for the assessment to be
  3114. * reliable, a minimum number of samples must be present, and
  3115. * a minimum amount of time must have elapsed. If not so, do
  3116. * not compute new rate. Just reset parameters, to get ready
  3117. * for a new evaluation attempt.
  3118. */
  3119. if (bfqd->peak_rate_samples < BFQ_RATE_MIN_SAMPLES ||
  3120. bfqd->delta_from_first < BFQ_RATE_MIN_INTERVAL)
  3121. goto reset_computation;
  3122. /*
  3123. * If a new request completion has occurred after last
  3124. * dispatch, then, to approximate the rate at which requests
  3125. * have been served by the device, it is more precise to
  3126. * extend the observation interval to the last completion.
  3127. */
  3128. bfqd->delta_from_first =
  3129. max_t(u64, bfqd->delta_from_first,
  3130. bfqd->last_completion - bfqd->first_dispatch);
  3131. /*
  3132. * Rate computed in sects/usec, and not sects/nsec, for
  3133. * precision issues.
  3134. */
  3135. rate = div64_ul(bfqd->tot_sectors_dispatched<<BFQ_RATE_SHIFT,
  3136. div_u64(bfqd->delta_from_first, NSEC_PER_USEC));
  3137. /*
  3138. * Peak rate not updated if:
  3139. * - the percentage of sequential dispatches is below 3/4 of the
  3140. * total, and rate is below the current estimated peak rate
  3141. * - rate is unreasonably high (> 20M sectors/sec)
  3142. */
  3143. if ((bfqd->sequential_samples < (3 * bfqd->peak_rate_samples)>>2 &&
  3144. rate <= bfqd->peak_rate) ||
  3145. rate > 20<<BFQ_RATE_SHIFT)
  3146. goto reset_computation;
  3147. /*
  3148. * We have to update the peak rate, at last! To this purpose,
  3149. * we use a low-pass filter. We compute the smoothing constant
  3150. * of the filter as a function of the 'weight' of the new
  3151. * measured rate.
  3152. *
  3153. * As can be seen in next formulas, we define this weight as a
  3154. * quantity proportional to how sequential the workload is,
  3155. * and to how long the observation time interval is.
  3156. *
  3157. * The weight runs from 0 to 8. The maximum value of the
  3158. * weight, 8, yields the minimum value for the smoothing
  3159. * constant. At this minimum value for the smoothing constant,
  3160. * the measured rate contributes for half of the next value of
  3161. * the estimated peak rate.
  3162. *
  3163. * So, the first step is to compute the weight as a function
  3164. * of how sequential the workload is. Note that the weight
  3165. * cannot reach 9, because bfqd->sequential_samples cannot
  3166. * become equal to bfqd->peak_rate_samples, which, in its
  3167. * turn, holds true because bfqd->sequential_samples is not
  3168. * incremented for the first sample.
  3169. */
  3170. weight = (9 * bfqd->sequential_samples) / bfqd->peak_rate_samples;
  3171. /*
  3172. * Second step: further refine the weight as a function of the
  3173. * duration of the observation interval.
  3174. */
  3175. weight = min_t(u32, 8,
  3176. div_u64(weight * bfqd->delta_from_first,
  3177. BFQ_RATE_REF_INTERVAL));
  3178. /*
  3179. * Divisor ranging from 10, for minimum weight, to 2, for
  3180. * maximum weight.
  3181. */
  3182. divisor = 10 - weight;
  3183. /*
  3184. * Finally, update peak rate:
  3185. *
  3186. * peak_rate = peak_rate * (divisor-1) / divisor + rate / divisor
  3187. */
  3188. bfqd->peak_rate *= divisor-1;
  3189. bfqd->peak_rate /= divisor;
  3190. rate /= divisor; /* smoothing constant alpha = 1/divisor */
  3191. bfqd->peak_rate += rate;
  3192. /*
  3193. * For a very slow device, bfqd->peak_rate can reach 0 (see
  3194. * the minimum representable values reported in the comments
  3195. * on BFQ_RATE_SHIFT). Push to 1 if this happens, to avoid
  3196. * divisions by zero where bfqd->peak_rate is used as a
  3197. * divisor.
  3198. */
  3199. bfqd->peak_rate = max_t(u32, 1, bfqd->peak_rate);
  3200. update_thr_responsiveness_params(bfqd);
  3201. reset_computation:
  3202. bfq_reset_rate_computation(bfqd, rq);
  3203. }
  3204. /*
  3205. * Update the read/write peak rate (the main quantity used for
  3206. * auto-tuning, see update_thr_responsiveness_params()).
  3207. *
  3208. * It is not trivial to estimate the peak rate (correctly): because of
  3209. * the presence of sw and hw queues between the scheduler and the
  3210. * device components that finally serve I/O requests, it is hard to
  3211. * say exactly when a given dispatched request is served inside the
  3212. * device, and for how long. As a consequence, it is hard to know
  3213. * precisely at what rate a given set of requests is actually served
  3214. * by the device.
  3215. *
  3216. * On the opposite end, the dispatch time of any request is trivially
  3217. * available, and, from this piece of information, the "dispatch rate"
  3218. * of requests can be immediately computed. So, the idea in the next
  3219. * function is to use what is known, namely request dispatch times
  3220. * (plus, when useful, request completion times), to estimate what is
  3221. * unknown, namely in-device request service rate.
  3222. *
  3223. * The main issue is that, because of the above facts, the rate at
  3224. * which a certain set of requests is dispatched over a certain time
  3225. * interval can vary greatly with respect to the rate at which the
  3226. * same requests are then served. But, since the size of any
  3227. * intermediate queue is limited, and the service scheme is lossless
  3228. * (no request is silently dropped), the following obvious convergence
  3229. * property holds: the number of requests dispatched MUST become
  3230. * closer and closer to the number of requests completed as the
  3231. * observation interval grows. This is the key property used in
  3232. * the next function to estimate the peak service rate as a function
  3233. * of the observed dispatch rate. The function assumes to be invoked
  3234. * on every request dispatch.
  3235. */
  3236. static void bfq_update_peak_rate(struct bfq_data *bfqd, struct request *rq)
  3237. {
  3238. u64 now_ns = blk_time_get_ns();
  3239. if (bfqd->peak_rate_samples == 0) { /* first dispatch */
  3240. bfq_log(bfqd, "update_peak_rate: goto reset, samples %d",
  3241. bfqd->peak_rate_samples);
  3242. bfq_reset_rate_computation(bfqd, rq);
  3243. goto update_last_values; /* will add one sample */
  3244. }
  3245. /*
  3246. * Device idle for very long: the observation interval lasting
  3247. * up to this dispatch cannot be a valid observation interval
  3248. * for computing a new peak rate (similarly to the late-
  3249. * completion event in bfq_completed_request()). Go to
  3250. * update_rate_and_reset to have the following three steps
  3251. * taken:
  3252. * - close the observation interval at the last (previous)
  3253. * request dispatch or completion
  3254. * - compute rate, if possible, for that observation interval
  3255. * - start a new observation interval with this dispatch
  3256. */
  3257. if (now_ns - bfqd->last_dispatch > 100*NSEC_PER_MSEC &&
  3258. bfqd->tot_rq_in_driver == 0)
  3259. goto update_rate_and_reset;
  3260. /* Update sampling information */
  3261. bfqd->peak_rate_samples++;
  3262. if ((bfqd->tot_rq_in_driver > 0 ||
  3263. now_ns - bfqd->last_completion < BFQ_MIN_TT)
  3264. && !BFQ_RQ_SEEKY(bfqd, bfqd->last_position, rq))
  3265. bfqd->sequential_samples++;
  3266. bfqd->tot_sectors_dispatched += blk_rq_sectors(rq);
  3267. /* Reset max observed rq size every 32 dispatches */
  3268. if (likely(bfqd->peak_rate_samples % 32))
  3269. bfqd->last_rq_max_size =
  3270. max_t(u32, blk_rq_sectors(rq), bfqd->last_rq_max_size);
  3271. else
  3272. bfqd->last_rq_max_size = blk_rq_sectors(rq);
  3273. bfqd->delta_from_first = now_ns - bfqd->first_dispatch;
  3274. /* Target observation interval not yet reached, go on sampling */
  3275. if (bfqd->delta_from_first < BFQ_RATE_REF_INTERVAL)
  3276. goto update_last_values;
  3277. update_rate_and_reset:
  3278. bfq_update_rate_reset(bfqd, rq);
  3279. update_last_values:
  3280. bfqd->last_position = blk_rq_pos(rq) + blk_rq_sectors(rq);
  3281. if (RQ_BFQQ(rq) == bfqd->in_service_queue)
  3282. bfqd->in_serv_last_pos = bfqd->last_position;
  3283. bfqd->last_dispatch = now_ns;
  3284. }
  3285. /*
  3286. * Remove request from internal lists.
  3287. */
  3288. static void bfq_dispatch_remove(struct request_queue *q, struct request *rq)
  3289. {
  3290. struct bfq_queue *bfqq = RQ_BFQQ(rq);
  3291. /*
  3292. * For consistency, the next instruction should have been
  3293. * executed after removing the request from the queue and
  3294. * dispatching it. We execute instead this instruction before
  3295. * bfq_remove_request() (and hence introduce a temporary
  3296. * inconsistency), for efficiency. In fact, should this
  3297. * dispatch occur for a non in-service bfqq, this anticipated
  3298. * increment prevents two counters related to bfqq->dispatched
  3299. * from risking to be, first, uselessly decremented, and then
  3300. * incremented again when the (new) value of bfqq->dispatched
  3301. * happens to be taken into account.
  3302. */
  3303. bfqq->dispatched++;
  3304. bfq_update_peak_rate(q->elevator->elevator_data, rq);
  3305. bfq_remove_request(q, rq);
  3306. }
  3307. /*
  3308. * There is a case where idling does not have to be performed for
  3309. * throughput concerns, but to preserve the throughput share of
  3310. * the process associated with bfqq.
  3311. *
  3312. * To introduce this case, we can note that allowing the drive
  3313. * to enqueue more than one request at a time, and hence
  3314. * delegating de facto final scheduling decisions to the
  3315. * drive's internal scheduler, entails loss of control on the
  3316. * actual request service order. In particular, the critical
  3317. * situation is when requests from different processes happen
  3318. * to be present, at the same time, in the internal queue(s)
  3319. * of the drive. In such a situation, the drive, by deciding
  3320. * the service order of the internally-queued requests, does
  3321. * determine also the actual throughput distribution among
  3322. * these processes. But the drive typically has no notion or
  3323. * concern about per-process throughput distribution, and
  3324. * makes its decisions only on a per-request basis. Therefore,
  3325. * the service distribution enforced by the drive's internal
  3326. * scheduler is likely to coincide with the desired throughput
  3327. * distribution only in a completely symmetric, or favorably
  3328. * skewed scenario where:
  3329. * (i-a) each of these processes must get the same throughput as
  3330. * the others,
  3331. * (i-b) in case (i-a) does not hold, it holds that the process
  3332. * associated with bfqq must receive a lower or equal
  3333. * throughput than any of the other processes;
  3334. * (ii) the I/O of each process has the same properties, in
  3335. * terms of locality (sequential or random), direction
  3336. * (reads or writes), request sizes, greediness
  3337. * (from I/O-bound to sporadic), and so on;
  3338. * In fact, in such a scenario, the drive tends to treat the requests
  3339. * of each process in about the same way as the requests of the
  3340. * others, and thus to provide each of these processes with about the
  3341. * same throughput. This is exactly the desired throughput
  3342. * distribution if (i-a) holds, or, if (i-b) holds instead, this is an
  3343. * even more convenient distribution for (the process associated with)
  3344. * bfqq.
  3345. *
  3346. * In contrast, in any asymmetric or unfavorable scenario, device
  3347. * idling (I/O-dispatch plugging) is certainly needed to guarantee
  3348. * that bfqq receives its assigned fraction of the device throughput
  3349. * (see [1] for details).
  3350. *
  3351. * The problem is that idling may significantly reduce throughput with
  3352. * certain combinations of types of I/O and devices. An important
  3353. * example is sync random I/O on flash storage with command
  3354. * queueing. So, unless bfqq falls in cases where idling also boosts
  3355. * throughput, it is important to check conditions (i-a), i(-b) and
  3356. * (ii) accurately, so as to avoid idling when not strictly needed for
  3357. * service guarantees.
  3358. *
  3359. * Unfortunately, it is extremely difficult to thoroughly check
  3360. * condition (ii). And, in case there are active groups, it becomes
  3361. * very difficult to check conditions (i-a) and (i-b) too. In fact,
  3362. * if there are active groups, then, for conditions (i-a) or (i-b) to
  3363. * become false 'indirectly', it is enough that an active group
  3364. * contains more active processes or sub-groups than some other active
  3365. * group. More precisely, for conditions (i-a) or (i-b) to become
  3366. * false because of such a group, it is not even necessary that the
  3367. * group is (still) active: it is sufficient that, even if the group
  3368. * has become inactive, some of its descendant processes still have
  3369. * some request already dispatched but still waiting for
  3370. * completion. In fact, requests have still to be guaranteed their
  3371. * share of the throughput even after being dispatched. In this
  3372. * respect, it is easy to show that, if a group frequently becomes
  3373. * inactive while still having in-flight requests, and if, when this
  3374. * happens, the group is not considered in the calculation of whether
  3375. * the scenario is asymmetric, then the group may fail to be
  3376. * guaranteed its fair share of the throughput (basically because
  3377. * idling may not be performed for the descendant processes of the
  3378. * group, but it had to be). We address this issue with the following
  3379. * bi-modal behavior, implemented in the function
  3380. * bfq_asymmetric_scenario().
  3381. *
  3382. * If there are groups with requests waiting for completion
  3383. * (as commented above, some of these groups may even be
  3384. * already inactive), then the scenario is tagged as
  3385. * asymmetric, conservatively, without checking any of the
  3386. * conditions (i-a), (i-b) or (ii). So the device is idled for bfqq.
  3387. * This behavior matches also the fact that groups are created
  3388. * exactly if controlling I/O is a primary concern (to
  3389. * preserve bandwidth and latency guarantees).
  3390. *
  3391. * On the opposite end, if there are no groups with requests waiting
  3392. * for completion, then only conditions (i-a) and (i-b) are actually
  3393. * controlled, i.e., provided that conditions (i-a) or (i-b) holds,
  3394. * idling is not performed, regardless of whether condition (ii)
  3395. * holds. In other words, only if conditions (i-a) and (i-b) do not
  3396. * hold, then idling is allowed, and the device tends to be prevented
  3397. * from queueing many requests, possibly of several processes. Since
  3398. * there are no groups with requests waiting for completion, then, to
  3399. * control conditions (i-a) and (i-b) it is enough to check just
  3400. * whether all the queues with requests waiting for completion also
  3401. * have the same weight.
  3402. *
  3403. * Not checking condition (ii) evidently exposes bfqq to the
  3404. * risk of getting less throughput than its fair share.
  3405. * However, for queues with the same weight, a further
  3406. * mechanism, preemption, mitigates or even eliminates this
  3407. * problem. And it does so without consequences on overall
  3408. * throughput. This mechanism and its benefits are explained
  3409. * in the next three paragraphs.
  3410. *
  3411. * Even if a queue, say Q, is expired when it remains idle, Q
  3412. * can still preempt the new in-service queue if the next
  3413. * request of Q arrives soon (see the comments on
  3414. * bfq_bfqq_update_budg_for_activation). If all queues and
  3415. * groups have the same weight, this form of preemption,
  3416. * combined with the hole-recovery heuristic described in the
  3417. * comments on function bfq_bfqq_update_budg_for_activation,
  3418. * are enough to preserve a correct bandwidth distribution in
  3419. * the mid term, even without idling. In fact, even if not
  3420. * idling allows the internal queues of the device to contain
  3421. * many requests, and thus to reorder requests, we can rather
  3422. * safely assume that the internal scheduler still preserves a
  3423. * minimum of mid-term fairness.
  3424. *
  3425. * More precisely, this preemption-based, idleless approach
  3426. * provides fairness in terms of IOPS, and not sectors per
  3427. * second. This can be seen with a simple example. Suppose
  3428. * that there are two queues with the same weight, but that
  3429. * the first queue receives requests of 8 sectors, while the
  3430. * second queue receives requests of 1024 sectors. In
  3431. * addition, suppose that each of the two queues contains at
  3432. * most one request at a time, which implies that each queue
  3433. * always remains idle after it is served. Finally, after
  3434. * remaining idle, each queue receives very quickly a new
  3435. * request. It follows that the two queues are served
  3436. * alternatively, preempting each other if needed. This
  3437. * implies that, although both queues have the same weight,
  3438. * the queue with large requests receives a service that is
  3439. * 1024/8 times as high as the service received by the other
  3440. * queue.
  3441. *
  3442. * The motivation for using preemption instead of idling (for
  3443. * queues with the same weight) is that, by not idling,
  3444. * service guarantees are preserved (completely or at least in
  3445. * part) without minimally sacrificing throughput. And, if
  3446. * there is no active group, then the primary expectation for
  3447. * this device is probably a high throughput.
  3448. *
  3449. * We are now left only with explaining the two sub-conditions in the
  3450. * additional compound condition that is checked below for deciding
  3451. * whether the scenario is asymmetric. To explain the first
  3452. * sub-condition, we need to add that the function
  3453. * bfq_asymmetric_scenario checks the weights of only
  3454. * non-weight-raised queues, for efficiency reasons (see comments on
  3455. * bfq_weights_tree_add()). Then the fact that bfqq is weight-raised
  3456. * is checked explicitly here. More precisely, the compound condition
  3457. * below takes into account also the fact that, even if bfqq is being
  3458. * weight-raised, the scenario is still symmetric if all queues with
  3459. * requests waiting for completion happen to be
  3460. * weight-raised. Actually, we should be even more precise here, and
  3461. * differentiate between interactive weight raising and soft real-time
  3462. * weight raising.
  3463. *
  3464. * The second sub-condition checked in the compound condition is
  3465. * whether there is a fair amount of already in-flight I/O not
  3466. * belonging to bfqq. If so, I/O dispatching is to be plugged, for the
  3467. * following reason. The drive may decide to serve in-flight
  3468. * non-bfqq's I/O requests before bfqq's ones, thereby delaying the
  3469. * arrival of new I/O requests for bfqq (recall that bfqq is sync). If
  3470. * I/O-dispatching is not plugged, then, while bfqq remains empty, a
  3471. * basically uncontrolled amount of I/O from other queues may be
  3472. * dispatched too, possibly causing the service of bfqq's I/O to be
  3473. * delayed even longer in the drive. This problem gets more and more
  3474. * serious as the speed and the queue depth of the drive grow,
  3475. * because, as these two quantities grow, the probability to find no
  3476. * queue busy but many requests in flight grows too. By contrast,
  3477. * plugging I/O dispatching minimizes the delay induced by already
  3478. * in-flight I/O, and enables bfqq to recover the bandwidth it may
  3479. * lose because of this delay.
  3480. *
  3481. * As a side note, it is worth considering that the above
  3482. * device-idling countermeasures may however fail in the following
  3483. * unlucky scenario: if I/O-dispatch plugging is (correctly) disabled
  3484. * in a time period during which all symmetry sub-conditions hold, and
  3485. * therefore the device is allowed to enqueue many requests, but at
  3486. * some later point in time some sub-condition stops to hold, then it
  3487. * may become impossible to make requests be served in the desired
  3488. * order until all the requests already queued in the device have been
  3489. * served. The last sub-condition commented above somewhat mitigates
  3490. * this problem for weight-raised queues.
  3491. *
  3492. * However, as an additional mitigation for this problem, we preserve
  3493. * plugging for a special symmetric case that may suddenly turn into
  3494. * asymmetric: the case where only bfqq is busy. In this case, not
  3495. * expiring bfqq does not cause any harm to any other queues in terms
  3496. * of service guarantees. In contrast, it avoids the following unlucky
  3497. * sequence of events: (1) bfqq is expired, (2) a new queue with a
  3498. * lower weight than bfqq becomes busy (or more queues), (3) the new
  3499. * queue is served until a new request arrives for bfqq, (4) when bfqq
  3500. * is finally served, there are so many requests of the new queue in
  3501. * the drive that the pending requests for bfqq take a lot of time to
  3502. * be served. In particular, event (2) may case even already
  3503. * dispatched requests of bfqq to be delayed, inside the drive. So, to
  3504. * avoid this series of events, the scenario is preventively declared
  3505. * as asymmetric also if bfqq is the only busy queues
  3506. */
  3507. static bool idling_needed_for_service_guarantees(struct bfq_data *bfqd,
  3508. struct bfq_queue *bfqq)
  3509. {
  3510. int tot_busy_queues = bfq_tot_busy_queues(bfqd);
  3511. /* No point in idling for bfqq if it won't get requests any longer */
  3512. if (unlikely(!bfqq_process_refs(bfqq)))
  3513. return false;
  3514. return (bfqq->wr_coeff > 1 &&
  3515. (bfqd->wr_busy_queues < tot_busy_queues ||
  3516. bfqd->tot_rq_in_driver >= bfqq->dispatched + 4)) ||
  3517. bfq_asymmetric_scenario(bfqd, bfqq) ||
  3518. tot_busy_queues == 1;
  3519. }
  3520. static bool __bfq_bfqq_expire(struct bfq_data *bfqd, struct bfq_queue *bfqq,
  3521. enum bfqq_expiration reason)
  3522. {
  3523. /*
  3524. * If this bfqq is shared between multiple processes, check
  3525. * to make sure that those processes are still issuing I/Os
  3526. * within the mean seek distance. If not, it may be time to
  3527. * break the queues apart again.
  3528. */
  3529. if (bfq_bfqq_coop(bfqq) && BFQQ_SEEKY(bfqq))
  3530. bfq_mark_bfqq_split_coop(bfqq);
  3531. /*
  3532. * Consider queues with a higher finish virtual time than
  3533. * bfqq. If idling_needed_for_service_guarantees(bfqq) returns
  3534. * true, then bfqq's bandwidth would be violated if an
  3535. * uncontrolled amount of I/O from these queues were
  3536. * dispatched while bfqq is waiting for its new I/O to
  3537. * arrive. This is exactly what may happen if this is a forced
  3538. * expiration caused by a preemption attempt, and if bfqq is
  3539. * not re-scheduled. To prevent this from happening, re-queue
  3540. * bfqq if it needs I/O-dispatch plugging, even if it is
  3541. * empty. By doing so, bfqq is granted to be served before the
  3542. * above queues (provided that bfqq is of course eligible).
  3543. */
  3544. if (RB_EMPTY_ROOT(&bfqq->sort_list) &&
  3545. !(reason == BFQQE_PREEMPTED &&
  3546. idling_needed_for_service_guarantees(bfqd, bfqq))) {
  3547. if (bfqq->dispatched == 0)
  3548. /*
  3549. * Overloading budget_timeout field to store
  3550. * the time at which the queue remains with no
  3551. * backlog and no outstanding request; used by
  3552. * the weight-raising mechanism.
  3553. */
  3554. bfqq->budget_timeout = jiffies;
  3555. bfq_del_bfqq_busy(bfqq, true);
  3556. } else {
  3557. bfq_requeue_bfqq(bfqd, bfqq, true);
  3558. /*
  3559. * Resort priority tree of potential close cooperators.
  3560. * See comments on bfq_pos_tree_add_move() for the unlikely().
  3561. */
  3562. if (unlikely(!bfqd->nonrot_with_queueing &&
  3563. !RB_EMPTY_ROOT(&bfqq->sort_list)))
  3564. bfq_pos_tree_add_move(bfqd, bfqq);
  3565. }
  3566. /*
  3567. * All in-service entities must have been properly deactivated
  3568. * or requeued before executing the next function, which
  3569. * resets all in-service entities as no more in service. This
  3570. * may cause bfqq to be freed. If this happens, the next
  3571. * function returns true.
  3572. */
  3573. return __bfq_bfqd_reset_in_service(bfqd);
  3574. }
  3575. /**
  3576. * __bfq_bfqq_recalc_budget - try to adapt the budget to the @bfqq behavior.
  3577. * @bfqd: device data.
  3578. * @bfqq: queue to update.
  3579. * @reason: reason for expiration.
  3580. *
  3581. * Handle the feedback on @bfqq budget at queue expiration.
  3582. * See the body for detailed comments.
  3583. */
  3584. static void __bfq_bfqq_recalc_budget(struct bfq_data *bfqd,
  3585. struct bfq_queue *bfqq,
  3586. enum bfqq_expiration reason)
  3587. {
  3588. struct request *next_rq;
  3589. int budget, min_budget;
  3590. min_budget = bfq_min_budget(bfqd);
  3591. if (bfqq->wr_coeff == 1)
  3592. budget = bfqq->max_budget;
  3593. else /*
  3594. * Use a constant, low budget for weight-raised queues,
  3595. * to help achieve a low latency. Keep it slightly higher
  3596. * than the minimum possible budget, to cause a little
  3597. * bit fewer expirations.
  3598. */
  3599. budget = 2 * min_budget;
  3600. bfq_log_bfqq(bfqd, bfqq, "recalc_budg: last budg %d, budg left %d",
  3601. bfqq->entity.budget, bfq_bfqq_budget_left(bfqq));
  3602. bfq_log_bfqq(bfqd, bfqq, "recalc_budg: last max_budg %d, min budg %d",
  3603. budget, bfq_min_budget(bfqd));
  3604. bfq_log_bfqq(bfqd, bfqq, "recalc_budg: sync %d, seeky %d",
  3605. bfq_bfqq_sync(bfqq), BFQQ_SEEKY(bfqd->in_service_queue));
  3606. if (bfq_bfqq_sync(bfqq) && bfqq->wr_coeff == 1) {
  3607. switch (reason) {
  3608. /*
  3609. * Caveat: in all the following cases we trade latency
  3610. * for throughput.
  3611. */
  3612. case BFQQE_TOO_IDLE:
  3613. /*
  3614. * This is the only case where we may reduce
  3615. * the budget: if there is no request of the
  3616. * process still waiting for completion, then
  3617. * we assume (tentatively) that the timer has
  3618. * expired because the batch of requests of
  3619. * the process could have been served with a
  3620. * smaller budget. Hence, betting that
  3621. * process will behave in the same way when it
  3622. * becomes backlogged again, we reduce its
  3623. * next budget. As long as we guess right,
  3624. * this budget cut reduces the latency
  3625. * experienced by the process.
  3626. *
  3627. * However, if there are still outstanding
  3628. * requests, then the process may have not yet
  3629. * issued its next request just because it is
  3630. * still waiting for the completion of some of
  3631. * the still outstanding ones. So in this
  3632. * subcase we do not reduce its budget, on the
  3633. * contrary we increase it to possibly boost
  3634. * the throughput, as discussed in the
  3635. * comments to the BUDGET_TIMEOUT case.
  3636. */
  3637. if (bfqq->dispatched > 0) /* still outstanding reqs */
  3638. budget = min(budget * 2, bfqd->bfq_max_budget);
  3639. else {
  3640. if (budget > 5 * min_budget)
  3641. budget -= 4 * min_budget;
  3642. else
  3643. budget = min_budget;
  3644. }
  3645. break;
  3646. case BFQQE_BUDGET_TIMEOUT:
  3647. /*
  3648. * We double the budget here because it gives
  3649. * the chance to boost the throughput if this
  3650. * is not a seeky process (and has bumped into
  3651. * this timeout because of, e.g., ZBR).
  3652. */
  3653. budget = min(budget * 2, bfqd->bfq_max_budget);
  3654. break;
  3655. case BFQQE_BUDGET_EXHAUSTED:
  3656. /*
  3657. * The process still has backlog, and did not
  3658. * let either the budget timeout or the disk
  3659. * idling timeout expire. Hence it is not
  3660. * seeky, has a short thinktime and may be
  3661. * happy with a higher budget too. So
  3662. * definitely increase the budget of this good
  3663. * candidate to boost the disk throughput.
  3664. */
  3665. budget = min(budget * 4, bfqd->bfq_max_budget);
  3666. break;
  3667. case BFQQE_NO_MORE_REQUESTS:
  3668. /*
  3669. * For queues that expire for this reason, it
  3670. * is particularly important to keep the
  3671. * budget close to the actual service they
  3672. * need. Doing so reduces the timestamp
  3673. * misalignment problem described in the
  3674. * comments in the body of
  3675. * __bfq_activate_entity. In fact, suppose
  3676. * that a queue systematically expires for
  3677. * BFQQE_NO_MORE_REQUESTS and presents a
  3678. * new request in time to enjoy timestamp
  3679. * back-shifting. The larger the budget of the
  3680. * queue is with respect to the service the
  3681. * queue actually requests in each service
  3682. * slot, the more times the queue can be
  3683. * reactivated with the same virtual finish
  3684. * time. It follows that, even if this finish
  3685. * time is pushed to the system virtual time
  3686. * to reduce the consequent timestamp
  3687. * misalignment, the queue unjustly enjoys for
  3688. * many re-activations a lower finish time
  3689. * than all newly activated queues.
  3690. *
  3691. * The service needed by bfqq is measured
  3692. * quite precisely by bfqq->entity.service.
  3693. * Since bfqq does not enjoy device idling,
  3694. * bfqq->entity.service is equal to the number
  3695. * of sectors that the process associated with
  3696. * bfqq requested to read/write before waiting
  3697. * for request completions, or blocking for
  3698. * other reasons.
  3699. */
  3700. budget = max_t(int, bfqq->entity.service, min_budget);
  3701. break;
  3702. default:
  3703. return;
  3704. }
  3705. } else if (!bfq_bfqq_sync(bfqq)) {
  3706. /*
  3707. * Async queues get always the maximum possible
  3708. * budget, as for them we do not care about latency
  3709. * (in addition, their ability to dispatch is limited
  3710. * by the charging factor).
  3711. */
  3712. budget = bfqd->bfq_max_budget;
  3713. }
  3714. bfqq->max_budget = budget;
  3715. if (bfqd->budgets_assigned >= bfq_stats_min_budgets &&
  3716. !bfqd->bfq_user_max_budget)
  3717. bfqq->max_budget = min(bfqq->max_budget, bfqd->bfq_max_budget);
  3718. /*
  3719. * If there is still backlog, then assign a new budget, making
  3720. * sure that it is large enough for the next request. Since
  3721. * the finish time of bfqq must be kept in sync with the
  3722. * budget, be sure to call __bfq_bfqq_expire() *after* this
  3723. * update.
  3724. *
  3725. * If there is no backlog, then no need to update the budget;
  3726. * it will be updated on the arrival of a new request.
  3727. */
  3728. next_rq = bfqq->next_rq;
  3729. if (next_rq)
  3730. bfqq->entity.budget = max_t(unsigned long, bfqq->max_budget,
  3731. bfq_serv_to_charge(next_rq, bfqq));
  3732. bfq_log_bfqq(bfqd, bfqq, "head sect: %u, new budget %d",
  3733. next_rq ? blk_rq_sectors(next_rq) : 0,
  3734. bfqq->entity.budget);
  3735. }
  3736. /*
  3737. * Return true if the process associated with bfqq is "slow". The slow
  3738. * flag is used, in addition to the budget timeout, to reduce the
  3739. * amount of service provided to seeky processes, and thus reduce
  3740. * their chances to lower the throughput. More details in the comments
  3741. * on the function bfq_bfqq_expire().
  3742. *
  3743. * An important observation is in order: as discussed in the comments
  3744. * on the function bfq_update_peak_rate(), with devices with internal
  3745. * queues, it is hard if ever possible to know when and for how long
  3746. * an I/O request is processed by the device (apart from the trivial
  3747. * I/O pattern where a new request is dispatched only after the
  3748. * previous one has been completed). This makes it hard to evaluate
  3749. * the real rate at which the I/O requests of each bfq_queue are
  3750. * served. In fact, for an I/O scheduler like BFQ, serving a
  3751. * bfq_queue means just dispatching its requests during its service
  3752. * slot (i.e., until the budget of the queue is exhausted, or the
  3753. * queue remains idle, or, finally, a timeout fires). But, during the
  3754. * service slot of a bfq_queue, around 100 ms at most, the device may
  3755. * be even still processing requests of bfq_queues served in previous
  3756. * service slots. On the opposite end, the requests of the in-service
  3757. * bfq_queue may be completed after the service slot of the queue
  3758. * finishes.
  3759. *
  3760. * Anyway, unless more sophisticated solutions are used
  3761. * (where possible), the sum of the sizes of the requests dispatched
  3762. * during the service slot of a bfq_queue is probably the only
  3763. * approximation available for the service received by the bfq_queue
  3764. * during its service slot. And this sum is the quantity used in this
  3765. * function to evaluate the I/O speed of a process.
  3766. */
  3767. static bool bfq_bfqq_is_slow(struct bfq_data *bfqd, struct bfq_queue *bfqq,
  3768. bool compensate, unsigned long *delta_ms)
  3769. {
  3770. ktime_t delta_ktime;
  3771. u32 delta_usecs;
  3772. bool slow = BFQQ_SEEKY(bfqq); /* if delta too short, use seekyness */
  3773. if (!bfq_bfqq_sync(bfqq))
  3774. return false;
  3775. if (compensate)
  3776. delta_ktime = bfqd->last_idling_start;
  3777. else
  3778. delta_ktime = blk_time_get();
  3779. delta_ktime = ktime_sub(delta_ktime, bfqd->last_budget_start);
  3780. delta_usecs = ktime_to_us(delta_ktime);
  3781. /* don't use too short time intervals */
  3782. if (delta_usecs < 1000) {
  3783. if (!blk_queue_rot(bfqd->queue))
  3784. /*
  3785. * give same worst-case guarantees as idling
  3786. * for seeky
  3787. */
  3788. *delta_ms = BFQ_MIN_TT / NSEC_PER_MSEC;
  3789. else /* charge at least one seek */
  3790. *delta_ms = bfq_slice_idle / NSEC_PER_MSEC;
  3791. return slow;
  3792. }
  3793. *delta_ms = delta_usecs / USEC_PER_MSEC;
  3794. /*
  3795. * Use only long (> 20ms) intervals to filter out excessive
  3796. * spikes in service rate estimation.
  3797. */
  3798. if (delta_usecs > 20000) {
  3799. /*
  3800. * Caveat for rotational devices: processes doing I/O
  3801. * in the slower disk zones tend to be slow(er) even
  3802. * if not seeky. In this respect, the estimated peak
  3803. * rate is likely to be an average over the disk
  3804. * surface. Accordingly, to not be too harsh with
  3805. * unlucky processes, a process is deemed slow only if
  3806. * its rate has been lower than half of the estimated
  3807. * peak rate.
  3808. */
  3809. slow = bfqq->entity.service < bfqd->bfq_max_budget / 2;
  3810. }
  3811. bfq_log_bfqq(bfqd, bfqq, "bfq_bfqq_is_slow: slow %d", slow);
  3812. return slow;
  3813. }
  3814. /*
  3815. * To be deemed as soft real-time, an application must meet two
  3816. * requirements. First, the application must not require an average
  3817. * bandwidth higher than the approximate bandwidth required to playback or
  3818. * record a compressed high-definition video.
  3819. * The next function is invoked on the completion of the last request of a
  3820. * batch, to compute the next-start time instant, soft_rt_next_start, such
  3821. * that, if the next request of the application does not arrive before
  3822. * soft_rt_next_start, then the above requirement on the bandwidth is met.
  3823. *
  3824. * The second requirement is that the request pattern of the application is
  3825. * isochronous, i.e., that, after issuing a request or a batch of requests,
  3826. * the application stops issuing new requests until all its pending requests
  3827. * have been completed. After that, the application may issue a new batch,
  3828. * and so on.
  3829. * For this reason the next function is invoked to compute
  3830. * soft_rt_next_start only for applications that meet this requirement,
  3831. * whereas soft_rt_next_start is set to infinity for applications that do
  3832. * not.
  3833. *
  3834. * Unfortunately, even a greedy (i.e., I/O-bound) application may
  3835. * happen to meet, occasionally or systematically, both the above
  3836. * bandwidth and isochrony requirements. This may happen at least in
  3837. * the following circumstances. First, if the CPU load is high. The
  3838. * application may stop issuing requests while the CPUs are busy
  3839. * serving other processes, then restart, then stop again for a while,
  3840. * and so on. The other circumstances are related to the storage
  3841. * device: the storage device is highly loaded or reaches a low-enough
  3842. * throughput with the I/O of the application (e.g., because the I/O
  3843. * is random and/or the device is slow). In all these cases, the
  3844. * I/O of the application may be simply slowed down enough to meet
  3845. * the bandwidth and isochrony requirements. To reduce the probability
  3846. * that greedy applications are deemed as soft real-time in these
  3847. * corner cases, a further rule is used in the computation of
  3848. * soft_rt_next_start: the return value of this function is forced to
  3849. * be higher than the maximum between the following two quantities.
  3850. *
  3851. * (a) Current time plus: (1) the maximum time for which the arrival
  3852. * of a request is waited for when a sync queue becomes idle,
  3853. * namely bfqd->bfq_slice_idle, and (2) a few extra jiffies. We
  3854. * postpone for a moment the reason for adding a few extra
  3855. * jiffies; we get back to it after next item (b). Lower-bounding
  3856. * the return value of this function with the current time plus
  3857. * bfqd->bfq_slice_idle tends to filter out greedy applications,
  3858. * because the latter issue their next request as soon as possible
  3859. * after the last one has been completed. In contrast, a soft
  3860. * real-time application spends some time processing data, after a
  3861. * batch of its requests has been completed.
  3862. *
  3863. * (b) Current value of bfqq->soft_rt_next_start. As pointed out
  3864. * above, greedy applications may happen to meet both the
  3865. * bandwidth and isochrony requirements under heavy CPU or
  3866. * storage-device load. In more detail, in these scenarios, these
  3867. * applications happen, only for limited time periods, to do I/O
  3868. * slowly enough to meet all the requirements described so far,
  3869. * including the filtering in above item (a). These slow-speed
  3870. * time intervals are usually interspersed between other time
  3871. * intervals during which these applications do I/O at a very high
  3872. * speed. Fortunately, exactly because of the high speed of the
  3873. * I/O in the high-speed intervals, the values returned by this
  3874. * function happen to be so high, near the end of any such
  3875. * high-speed interval, to be likely to fall *after* the end of
  3876. * the low-speed time interval that follows. These high values are
  3877. * stored in bfqq->soft_rt_next_start after each invocation of
  3878. * this function. As a consequence, if the last value of
  3879. * bfqq->soft_rt_next_start is constantly used to lower-bound the
  3880. * next value that this function may return, then, from the very
  3881. * beginning of a low-speed interval, bfqq->soft_rt_next_start is
  3882. * likely to be constantly kept so high that any I/O request
  3883. * issued during the low-speed interval is considered as arriving
  3884. * to soon for the application to be deemed as soft
  3885. * real-time. Then, in the high-speed interval that follows, the
  3886. * application will not be deemed as soft real-time, just because
  3887. * it will do I/O at a high speed. And so on.
  3888. *
  3889. * Getting back to the filtering in item (a), in the following two
  3890. * cases this filtering might be easily passed by a greedy
  3891. * application, if the reference quantity was just
  3892. * bfqd->bfq_slice_idle:
  3893. * 1) HZ is so low that the duration of a jiffy is comparable to or
  3894. * higher than bfqd->bfq_slice_idle. This happens, e.g., on slow
  3895. * devices with HZ=100. The time granularity may be so coarse
  3896. * that the approximation, in jiffies, of bfqd->bfq_slice_idle
  3897. * is rather lower than the exact value.
  3898. * 2) jiffies, instead of increasing at a constant rate, may stop increasing
  3899. * for a while, then suddenly 'jump' by several units to recover the lost
  3900. * increments. This seems to happen, e.g., inside virtual machines.
  3901. * To address this issue, in the filtering in (a) we do not use as a
  3902. * reference time interval just bfqd->bfq_slice_idle, but
  3903. * bfqd->bfq_slice_idle plus a few jiffies. In particular, we add the
  3904. * minimum number of jiffies for which the filter seems to be quite
  3905. * precise also in embedded systems and KVM/QEMU virtual machines.
  3906. */
  3907. static unsigned long bfq_bfqq_softrt_next_start(struct bfq_data *bfqd,
  3908. struct bfq_queue *bfqq)
  3909. {
  3910. return max3(bfqq->soft_rt_next_start,
  3911. bfqq->last_idle_bklogged +
  3912. HZ * bfqq->service_from_backlogged /
  3913. bfqd->bfq_wr_max_softrt_rate,
  3914. jiffies + nsecs_to_jiffies(bfqq->bfqd->bfq_slice_idle) + 4);
  3915. }
  3916. /**
  3917. * bfq_bfqq_expire - expire a queue.
  3918. * @bfqd: device owning the queue.
  3919. * @bfqq: the queue to expire.
  3920. * @compensate: if true, compensate for the time spent idling.
  3921. * @reason: the reason causing the expiration.
  3922. *
  3923. * If the process associated with bfqq does slow I/O (e.g., because it
  3924. * issues random requests), we charge bfqq with the time it has been
  3925. * in service instead of the service it has received (see
  3926. * bfq_bfqq_charge_time for details on how this goal is achieved). As
  3927. * a consequence, bfqq will typically get higher timestamps upon
  3928. * reactivation, and hence it will be rescheduled as if it had
  3929. * received more service than what it has actually received. In the
  3930. * end, bfqq receives less service in proportion to how slowly its
  3931. * associated process consumes its budgets (and hence how seriously it
  3932. * tends to lower the throughput). In addition, this time-charging
  3933. * strategy guarantees time fairness among slow processes. In
  3934. * contrast, if the process associated with bfqq is not slow, we
  3935. * charge bfqq exactly with the service it has received.
  3936. *
  3937. * Charging time to the first type of queues and the exact service to
  3938. * the other has the effect of using the WF2Q+ policy to schedule the
  3939. * former on a timeslice basis, without violating service domain
  3940. * guarantees among the latter.
  3941. */
  3942. void bfq_bfqq_expire(struct bfq_data *bfqd,
  3943. struct bfq_queue *bfqq,
  3944. bool compensate,
  3945. enum bfqq_expiration reason)
  3946. {
  3947. bool slow;
  3948. unsigned long delta = 0;
  3949. struct bfq_entity *entity = &bfqq->entity;
  3950. /*
  3951. * Check whether the process is slow (see bfq_bfqq_is_slow).
  3952. */
  3953. slow = bfq_bfqq_is_slow(bfqd, bfqq, compensate, &delta);
  3954. /*
  3955. * As above explained, charge slow (typically seeky) and
  3956. * timed-out queues with the time and not the service
  3957. * received, to favor sequential workloads.
  3958. *
  3959. * Processes doing I/O in the slower disk zones will tend to
  3960. * be slow(er) even if not seeky. Therefore, since the
  3961. * estimated peak rate is actually an average over the disk
  3962. * surface, these processes may timeout just for bad luck. To
  3963. * avoid punishing them, do not charge time to processes that
  3964. * succeeded in consuming at least 2/3 of their budget. This
  3965. * allows BFQ to preserve enough elasticity to still perform
  3966. * bandwidth, and not time, distribution with little unlucky
  3967. * or quasi-sequential processes.
  3968. */
  3969. if (bfqq->wr_coeff == 1 &&
  3970. (slow ||
  3971. (reason == BFQQE_BUDGET_TIMEOUT &&
  3972. bfq_bfqq_budget_left(bfqq) >= entity->budget / 3)))
  3973. bfq_bfqq_charge_time(bfqd, bfqq, delta);
  3974. if (bfqd->low_latency && bfqq->wr_coeff == 1)
  3975. bfqq->last_wr_start_finish = jiffies;
  3976. if (bfqd->low_latency && bfqd->bfq_wr_max_softrt_rate > 0 &&
  3977. RB_EMPTY_ROOT(&bfqq->sort_list)) {
  3978. /*
  3979. * If we get here, and there are no outstanding
  3980. * requests, then the request pattern is isochronous
  3981. * (see the comments on the function
  3982. * bfq_bfqq_softrt_next_start()). Therefore we can
  3983. * compute soft_rt_next_start.
  3984. *
  3985. * If, instead, the queue still has outstanding
  3986. * requests, then we have to wait for the completion
  3987. * of all the outstanding requests to discover whether
  3988. * the request pattern is actually isochronous.
  3989. */
  3990. if (bfqq->dispatched == 0)
  3991. bfqq->soft_rt_next_start =
  3992. bfq_bfqq_softrt_next_start(bfqd, bfqq);
  3993. else if (bfqq->dispatched > 0) {
  3994. /*
  3995. * Schedule an update of soft_rt_next_start to when
  3996. * the task may be discovered to be isochronous.
  3997. */
  3998. bfq_mark_bfqq_softrt_update(bfqq);
  3999. }
  4000. }
  4001. bfq_log_bfqq(bfqd, bfqq,
  4002. "expire (%d, slow %d, num_disp %d, short_ttime %d)", reason,
  4003. slow, bfqq->dispatched, bfq_bfqq_has_short_ttime(bfqq));
  4004. /*
  4005. * bfqq expired, so no total service time needs to be computed
  4006. * any longer: reset state machine for measuring total service
  4007. * times.
  4008. */
  4009. bfqd->rqs_injected = bfqd->wait_dispatch = false;
  4010. bfqd->waited_rq = NULL;
  4011. /*
  4012. * Increase, decrease or leave budget unchanged according to
  4013. * reason.
  4014. */
  4015. __bfq_bfqq_recalc_budget(bfqd, bfqq, reason);
  4016. if (__bfq_bfqq_expire(bfqd, bfqq, reason))
  4017. /* bfqq is gone, no more actions on it */
  4018. return;
  4019. /* mark bfqq as waiting a request only if a bic still points to it */
  4020. if (!bfq_bfqq_busy(bfqq) &&
  4021. reason != BFQQE_BUDGET_TIMEOUT &&
  4022. reason != BFQQE_BUDGET_EXHAUSTED) {
  4023. bfq_mark_bfqq_non_blocking_wait_rq(bfqq);
  4024. /*
  4025. * Not setting service to 0, because, if the next rq
  4026. * arrives in time, the queue will go on receiving
  4027. * service with this same budget (as if it never expired)
  4028. */
  4029. } else
  4030. entity->service = 0;
  4031. /*
  4032. * Reset the received-service counter for every parent entity.
  4033. * Differently from what happens with bfqq->entity.service,
  4034. * the resetting of this counter never needs to be postponed
  4035. * for parent entities. In fact, in case bfqq may have a
  4036. * chance to go on being served using the last, partially
  4037. * consumed budget, bfqq->entity.service needs to be kept,
  4038. * because if bfqq then actually goes on being served using
  4039. * the same budget, the last value of bfqq->entity.service is
  4040. * needed to properly decrement bfqq->entity.budget by the
  4041. * portion already consumed. In contrast, it is not necessary
  4042. * to keep entity->service for parent entities too, because
  4043. * the bubble up of the new value of bfqq->entity.budget will
  4044. * make sure that the budgets of parent entities are correct,
  4045. * even in case bfqq and thus parent entities go on receiving
  4046. * service with the same budget.
  4047. */
  4048. entity = entity->parent;
  4049. for_each_entity(entity)
  4050. entity->service = 0;
  4051. }
  4052. /*
  4053. * Budget timeout is not implemented through a dedicated timer, but
  4054. * just checked on request arrivals and completions, as well as on
  4055. * idle timer expirations.
  4056. */
  4057. static bool bfq_bfqq_budget_timeout(struct bfq_queue *bfqq)
  4058. {
  4059. return time_is_before_eq_jiffies(bfqq->budget_timeout);
  4060. }
  4061. /*
  4062. * If we expire a queue that is actively waiting (i.e., with the
  4063. * device idled) for the arrival of a new request, then we may incur
  4064. * the timestamp misalignment problem described in the body of the
  4065. * function __bfq_activate_entity. Hence we return true only if this
  4066. * condition does not hold, or if the queue is slow enough to deserve
  4067. * only to be kicked off for preserving a high throughput.
  4068. */
  4069. static bool bfq_may_expire_for_budg_timeout(struct bfq_queue *bfqq)
  4070. {
  4071. bfq_log_bfqq(bfqq->bfqd, bfqq,
  4072. "may_budget_timeout: wait_request %d left %d timeout %d",
  4073. bfq_bfqq_wait_request(bfqq),
  4074. bfq_bfqq_budget_left(bfqq) >= bfqq->entity.budget / 3,
  4075. bfq_bfqq_budget_timeout(bfqq));
  4076. return (!bfq_bfqq_wait_request(bfqq) ||
  4077. bfq_bfqq_budget_left(bfqq) >= bfqq->entity.budget / 3)
  4078. &&
  4079. bfq_bfqq_budget_timeout(bfqq);
  4080. }
  4081. static bool idling_boosts_thr_without_issues(struct bfq_data *bfqd,
  4082. struct bfq_queue *bfqq)
  4083. {
  4084. bool rot_without_queueing =
  4085. blk_queue_rot(bfqd->queue) && !bfqd->hw_tag,
  4086. bfqq_sequential_and_IO_bound,
  4087. idling_boosts_thr;
  4088. /* No point in idling for bfqq if it won't get requests any longer */
  4089. if (unlikely(!bfqq_process_refs(bfqq)))
  4090. return false;
  4091. bfqq_sequential_and_IO_bound = !BFQQ_SEEKY(bfqq) &&
  4092. bfq_bfqq_IO_bound(bfqq) && bfq_bfqq_has_short_ttime(bfqq);
  4093. /*
  4094. * The next variable takes into account the cases where idling
  4095. * boosts the throughput.
  4096. *
  4097. * The value of the variable is computed considering, first, that
  4098. * idling is virtually always beneficial for the throughput if:
  4099. * (a) the device is not NCQ-capable and rotational, or
  4100. * (b) regardless of the presence of NCQ, the device is rotational and
  4101. * the request pattern for bfqq is I/O-bound and sequential, or
  4102. * (c) regardless of whether it is rotational, the device is
  4103. * not NCQ-capable and the request pattern for bfqq is
  4104. * I/O-bound and sequential.
  4105. *
  4106. * Secondly, and in contrast to the above item (b), idling an
  4107. * NCQ-capable flash-based device would not boost the
  4108. * throughput even with sequential I/O; rather it would lower
  4109. * the throughput in proportion to how fast the device
  4110. * is. Accordingly, the next variable is true if any of the
  4111. * above conditions (a), (b) or (c) is true, and, in
  4112. * particular, happens to be false if bfqd is an NCQ-capable
  4113. * flash-based device.
  4114. */
  4115. idling_boosts_thr = rot_without_queueing ||
  4116. ((blk_queue_rot(bfqd->queue) || !bfqd->hw_tag) &&
  4117. bfqq_sequential_and_IO_bound);
  4118. /*
  4119. * The return value of this function is equal to that of
  4120. * idling_boosts_thr, unless a special case holds. In this
  4121. * special case, described below, idling may cause problems to
  4122. * weight-raised queues.
  4123. *
  4124. * When the request pool is saturated (e.g., in the presence
  4125. * of write hogs), if the processes associated with
  4126. * non-weight-raised queues ask for requests at a lower rate,
  4127. * then processes associated with weight-raised queues have a
  4128. * higher probability to get a request from the pool
  4129. * immediately (or at least soon) when they need one. Thus
  4130. * they have a higher probability to actually get a fraction
  4131. * of the device throughput proportional to their high
  4132. * weight. This is especially true with NCQ-capable drives,
  4133. * which enqueue several requests in advance, and further
  4134. * reorder internally-queued requests.
  4135. *
  4136. * For this reason, we force to false the return value if
  4137. * there are weight-raised busy queues. In this case, and if
  4138. * bfqq is not weight-raised, this guarantees that the device
  4139. * is not idled for bfqq (if, instead, bfqq is weight-raised,
  4140. * then idling will be guaranteed by another variable, see
  4141. * below). Combined with the timestamping rules of BFQ (see
  4142. * [1] for details), this behavior causes bfqq, and hence any
  4143. * sync non-weight-raised queue, to get a lower number of
  4144. * requests served, and thus to ask for a lower number of
  4145. * requests from the request pool, before the busy
  4146. * weight-raised queues get served again. This often mitigates
  4147. * starvation problems in the presence of heavy write
  4148. * workloads and NCQ, thereby guaranteeing a higher
  4149. * application and system responsiveness in these hostile
  4150. * scenarios.
  4151. */
  4152. return idling_boosts_thr &&
  4153. bfqd->wr_busy_queues == 0;
  4154. }
  4155. /*
  4156. * For a queue that becomes empty, device idling is allowed only if
  4157. * this function returns true for that queue. As a consequence, since
  4158. * device idling plays a critical role for both throughput boosting
  4159. * and service guarantees, the return value of this function plays a
  4160. * critical role as well.
  4161. *
  4162. * In a nutshell, this function returns true only if idling is
  4163. * beneficial for throughput or, even if detrimental for throughput,
  4164. * idling is however necessary to preserve service guarantees (low
  4165. * latency, desired throughput distribution, ...). In particular, on
  4166. * NCQ-capable devices, this function tries to return false, so as to
  4167. * help keep the drives' internal queues full, whenever this helps the
  4168. * device boost the throughput without causing any service-guarantee
  4169. * issue.
  4170. *
  4171. * Most of the issues taken into account to get the return value of
  4172. * this function are not trivial. We discuss these issues in the two
  4173. * functions providing the main pieces of information needed by this
  4174. * function.
  4175. */
  4176. static bool bfq_better_to_idle(struct bfq_queue *bfqq)
  4177. {
  4178. struct bfq_data *bfqd = bfqq->bfqd;
  4179. bool idling_boosts_thr_with_no_issue, idling_needed_for_service_guar;
  4180. /* No point in idling for bfqq if it won't get requests any longer */
  4181. if (unlikely(!bfqq_process_refs(bfqq)))
  4182. return false;
  4183. if (unlikely(bfqd->strict_guarantees))
  4184. return true;
  4185. /*
  4186. * Idling is performed only if slice_idle > 0. In addition, we
  4187. * do not idle if
  4188. * (a) bfqq is async
  4189. * (b) bfqq is in the idle io prio class: in this case we do
  4190. * not idle because we want to minimize the bandwidth that
  4191. * queues in this class can steal to higher-priority queues
  4192. */
  4193. if (bfqd->bfq_slice_idle == 0 || !bfq_bfqq_sync(bfqq) ||
  4194. bfq_class_idle(bfqq))
  4195. return false;
  4196. idling_boosts_thr_with_no_issue =
  4197. idling_boosts_thr_without_issues(bfqd, bfqq);
  4198. idling_needed_for_service_guar =
  4199. idling_needed_for_service_guarantees(bfqd, bfqq);
  4200. /*
  4201. * We have now the two components we need to compute the
  4202. * return value of the function, which is true only if idling
  4203. * either boosts the throughput (without issues), or is
  4204. * necessary to preserve service guarantees.
  4205. */
  4206. return idling_boosts_thr_with_no_issue ||
  4207. idling_needed_for_service_guar;
  4208. }
  4209. /*
  4210. * If the in-service queue is empty but the function bfq_better_to_idle
  4211. * returns true, then:
  4212. * 1) the queue must remain in service and cannot be expired, and
  4213. * 2) the device must be idled to wait for the possible arrival of a new
  4214. * request for the queue.
  4215. * See the comments on the function bfq_better_to_idle for the reasons
  4216. * why performing device idling is the best choice to boost the throughput
  4217. * and preserve service guarantees when bfq_better_to_idle itself
  4218. * returns true.
  4219. */
  4220. static bool bfq_bfqq_must_idle(struct bfq_queue *bfqq)
  4221. {
  4222. return RB_EMPTY_ROOT(&bfqq->sort_list) && bfq_better_to_idle(bfqq);
  4223. }
  4224. /*
  4225. * This function chooses the queue from which to pick the next extra
  4226. * I/O request to inject, if it finds a compatible queue. See the
  4227. * comments on bfq_update_inject_limit() for details on the injection
  4228. * mechanism, and for the definitions of the quantities mentioned
  4229. * below.
  4230. */
  4231. static struct bfq_queue *
  4232. bfq_choose_bfqq_for_injection(struct bfq_data *bfqd)
  4233. {
  4234. struct bfq_queue *bfqq, *in_serv_bfqq = bfqd->in_service_queue;
  4235. unsigned int limit = in_serv_bfqq->inject_limit;
  4236. int i;
  4237. /*
  4238. * If
  4239. * - bfqq is not weight-raised and therefore does not carry
  4240. * time-critical I/O,
  4241. * or
  4242. * - regardless of whether bfqq is weight-raised, bfqq has
  4243. * however a long think time, during which it can absorb the
  4244. * effect of an appropriate number of extra I/O requests
  4245. * from other queues (see bfq_update_inject_limit for
  4246. * details on the computation of this number);
  4247. * then injection can be performed without restrictions.
  4248. */
  4249. bool in_serv_always_inject = in_serv_bfqq->wr_coeff == 1 ||
  4250. !bfq_bfqq_has_short_ttime(in_serv_bfqq);
  4251. /*
  4252. * If
  4253. * - the baseline total service time could not be sampled yet,
  4254. * so the inject limit happens to be still 0, and
  4255. * - a lot of time has elapsed since the plugging of I/O
  4256. * dispatching started, so drive speed is being wasted
  4257. * significantly;
  4258. * then temporarily raise inject limit to one request.
  4259. */
  4260. if (limit == 0 && in_serv_bfqq->last_serv_time_ns == 0 &&
  4261. bfq_bfqq_wait_request(in_serv_bfqq) &&
  4262. time_is_before_eq_jiffies(bfqd->last_idling_start_jiffies +
  4263. bfqd->bfq_slice_idle)
  4264. )
  4265. limit = 1;
  4266. if (bfqd->tot_rq_in_driver >= limit)
  4267. return NULL;
  4268. /*
  4269. * Linear search of the source queue for injection; but, with
  4270. * a high probability, very few steps are needed to find a
  4271. * candidate queue, i.e., a queue with enough budget left for
  4272. * its next request. In fact:
  4273. * - BFQ dynamically updates the budget of every queue so as
  4274. * to accommodate the expected backlog of the queue;
  4275. * - if a queue gets all its requests dispatched as injected
  4276. * service, then the queue is removed from the active list
  4277. * (and re-added only if it gets new requests, but then it
  4278. * is assigned again enough budget for its new backlog).
  4279. */
  4280. for (i = 0; i < bfqd->num_actuators; i++) {
  4281. list_for_each_entry(bfqq, &bfqd->active_list[i], bfqq_list)
  4282. if (!RB_EMPTY_ROOT(&bfqq->sort_list) &&
  4283. (in_serv_always_inject || bfqq->wr_coeff > 1) &&
  4284. bfq_serv_to_charge(bfqq->next_rq, bfqq) <=
  4285. bfq_bfqq_budget_left(bfqq)) {
  4286. /*
  4287. * Allow for only one large in-flight request
  4288. * on non-rotational devices, for the
  4289. * following reason. On non-rotationl drives,
  4290. * large requests take much longer than
  4291. * smaller requests to be served. In addition,
  4292. * the drive prefers to serve large requests
  4293. * w.r.t. to small ones, if it can choose. So,
  4294. * having more than one large requests queued
  4295. * in the drive may easily make the next first
  4296. * request of the in-service queue wait for so
  4297. * long to break bfqq's service guarantees. On
  4298. * the bright side, large requests let the
  4299. * drive reach a very high throughput, even if
  4300. * there is only one in-flight large request
  4301. * at a time.
  4302. */
  4303. if (!blk_queue_rot(bfqd->queue) &&
  4304. blk_rq_sectors(bfqq->next_rq) >=
  4305. BFQQ_SECT_THR_NONROT &&
  4306. bfqd->tot_rq_in_driver >= 1)
  4307. continue;
  4308. else {
  4309. bfqd->rqs_injected = true;
  4310. return bfqq;
  4311. }
  4312. }
  4313. }
  4314. return NULL;
  4315. }
  4316. static struct bfq_queue *
  4317. bfq_find_active_bfqq_for_actuator(struct bfq_data *bfqd, int idx)
  4318. {
  4319. struct bfq_queue *bfqq;
  4320. if (bfqd->in_service_queue &&
  4321. bfqd->in_service_queue->actuator_idx == idx)
  4322. return bfqd->in_service_queue;
  4323. list_for_each_entry(bfqq, &bfqd->active_list[idx], bfqq_list) {
  4324. if (!RB_EMPTY_ROOT(&bfqq->sort_list) &&
  4325. bfq_serv_to_charge(bfqq->next_rq, bfqq) <=
  4326. bfq_bfqq_budget_left(bfqq)) {
  4327. return bfqq;
  4328. }
  4329. }
  4330. return NULL;
  4331. }
  4332. /*
  4333. * Perform a linear scan of each actuator, until an actuator is found
  4334. * for which the following three conditions hold: the load of the
  4335. * actuator is below the threshold (see comments on
  4336. * actuator_load_threshold for details) and lower than that of the
  4337. * next actuator (comments on this extra condition below), and there
  4338. * is a queue that contains I/O for that actuator. On success, return
  4339. * that queue.
  4340. *
  4341. * Performing a plain linear scan entails a prioritization among
  4342. * actuators. The extra condition above breaks this prioritization and
  4343. * tends to distribute injection uniformly across actuators.
  4344. */
  4345. static struct bfq_queue *
  4346. bfq_find_bfqq_for_underused_actuator(struct bfq_data *bfqd)
  4347. {
  4348. int i;
  4349. for (i = 0 ; i < bfqd->num_actuators; i++) {
  4350. if (bfqd->rq_in_driver[i] < bfqd->actuator_load_threshold &&
  4351. (i == bfqd->num_actuators - 1 ||
  4352. bfqd->rq_in_driver[i] < bfqd->rq_in_driver[i+1])) {
  4353. struct bfq_queue *bfqq =
  4354. bfq_find_active_bfqq_for_actuator(bfqd, i);
  4355. if (bfqq)
  4356. return bfqq;
  4357. }
  4358. }
  4359. return NULL;
  4360. }
  4361. /*
  4362. * Select a queue for service. If we have a current queue in service,
  4363. * check whether to continue servicing it, or retrieve and set a new one.
  4364. */
  4365. static struct bfq_queue *bfq_select_queue(struct bfq_data *bfqd)
  4366. {
  4367. struct bfq_queue *bfqq, *inject_bfqq;
  4368. struct request *next_rq;
  4369. enum bfqq_expiration reason = BFQQE_BUDGET_TIMEOUT;
  4370. bfqq = bfqd->in_service_queue;
  4371. if (!bfqq)
  4372. goto new_queue;
  4373. bfq_log_bfqq(bfqd, bfqq, "select_queue: already in-service queue");
  4374. /*
  4375. * Do not expire bfqq for budget timeout if bfqq may be about
  4376. * to enjoy device idling. The reason why, in this case, we
  4377. * prevent bfqq from expiring is the same as in the comments
  4378. * on the case where bfq_bfqq_must_idle() returns true, in
  4379. * bfq_completed_request().
  4380. */
  4381. if (bfq_may_expire_for_budg_timeout(bfqq) &&
  4382. !bfq_bfqq_must_idle(bfqq))
  4383. goto expire;
  4384. check_queue:
  4385. /*
  4386. * If some actuator is underutilized, but the in-service
  4387. * queue does not contain I/O for that actuator, then try to
  4388. * inject I/O for that actuator.
  4389. */
  4390. inject_bfqq = bfq_find_bfqq_for_underused_actuator(bfqd);
  4391. if (inject_bfqq && inject_bfqq != bfqq)
  4392. return inject_bfqq;
  4393. /*
  4394. * This loop is rarely executed more than once. Even when it
  4395. * happens, it is much more convenient to re-execute this loop
  4396. * than to return NULL and trigger a new dispatch to get a
  4397. * request served.
  4398. */
  4399. next_rq = bfqq->next_rq;
  4400. /*
  4401. * If bfqq has requests queued and it has enough budget left to
  4402. * serve them, keep the queue, otherwise expire it.
  4403. */
  4404. if (next_rq) {
  4405. if (bfq_serv_to_charge(next_rq, bfqq) >
  4406. bfq_bfqq_budget_left(bfqq)) {
  4407. /*
  4408. * Expire the queue for budget exhaustion,
  4409. * which makes sure that the next budget is
  4410. * enough to serve the next request, even if
  4411. * it comes from the fifo expired path.
  4412. */
  4413. reason = BFQQE_BUDGET_EXHAUSTED;
  4414. goto expire;
  4415. } else {
  4416. /*
  4417. * The idle timer may be pending because we may
  4418. * not disable disk idling even when a new request
  4419. * arrives.
  4420. */
  4421. if (bfq_bfqq_wait_request(bfqq)) {
  4422. /*
  4423. * If we get here: 1) at least a new request
  4424. * has arrived but we have not disabled the
  4425. * timer because the request was too small,
  4426. * 2) then the block layer has unplugged
  4427. * the device, causing the dispatch to be
  4428. * invoked.
  4429. *
  4430. * Since the device is unplugged, now the
  4431. * requests are probably large enough to
  4432. * provide a reasonable throughput.
  4433. * So we disable idling.
  4434. */
  4435. bfq_clear_bfqq_wait_request(bfqq);
  4436. hrtimer_try_to_cancel(&bfqd->idle_slice_timer);
  4437. }
  4438. goto keep_queue;
  4439. }
  4440. }
  4441. /*
  4442. * No requests pending. However, if the in-service queue is idling
  4443. * for a new request, or has requests waiting for a completion and
  4444. * may idle after their completion, then keep it anyway.
  4445. *
  4446. * Yet, inject service from other queues if it boosts
  4447. * throughput and is possible.
  4448. */
  4449. if (bfq_bfqq_wait_request(bfqq) ||
  4450. (bfqq->dispatched != 0 && bfq_better_to_idle(bfqq))) {
  4451. unsigned int act_idx = bfqq->actuator_idx;
  4452. struct bfq_queue *async_bfqq = NULL;
  4453. struct bfq_queue *blocked_bfqq =
  4454. !hlist_empty(&bfqq->woken_list) ?
  4455. container_of(bfqq->woken_list.first,
  4456. struct bfq_queue,
  4457. woken_list_node)
  4458. : NULL;
  4459. if (bfqq->bic && bfqq->bic->bfqq[0][act_idx] &&
  4460. bfq_bfqq_busy(bfqq->bic->bfqq[0][act_idx]) &&
  4461. bfqq->bic->bfqq[0][act_idx]->next_rq)
  4462. async_bfqq = bfqq->bic->bfqq[0][act_idx];
  4463. /*
  4464. * The next four mutually-exclusive ifs decide
  4465. * whether to try injection, and choose the queue to
  4466. * pick an I/O request from.
  4467. *
  4468. * The first if checks whether the process associated
  4469. * with bfqq has also async I/O pending. If so, it
  4470. * injects such I/O unconditionally. Injecting async
  4471. * I/O from the same process can cause no harm to the
  4472. * process. On the contrary, it can only increase
  4473. * bandwidth and reduce latency for the process.
  4474. *
  4475. * The second if checks whether there happens to be a
  4476. * non-empty waker queue for bfqq, i.e., a queue whose
  4477. * I/O needs to be completed for bfqq to receive new
  4478. * I/O. This happens, e.g., if bfqq is associated with
  4479. * a process that does some sync. A sync generates
  4480. * extra blocking I/O, which must be completed before
  4481. * the process associated with bfqq can go on with its
  4482. * I/O. If the I/O of the waker queue is not served,
  4483. * then bfqq remains empty, and no I/O is dispatched,
  4484. * until the idle timeout fires for bfqq. This is
  4485. * likely to result in lower bandwidth and higher
  4486. * latencies for bfqq, and in a severe loss of total
  4487. * throughput. The best action to take is therefore to
  4488. * serve the waker queue as soon as possible. So do it
  4489. * (without relying on the third alternative below for
  4490. * eventually serving waker_bfqq's I/O; see the last
  4491. * paragraph for further details). This systematic
  4492. * injection of I/O from the waker queue does not
  4493. * cause any delay to bfqq's I/O. On the contrary,
  4494. * next bfqq's I/O is brought forward dramatically,
  4495. * for it is not blocked for milliseconds.
  4496. *
  4497. * The third if checks whether there is a queue woken
  4498. * by bfqq, and currently with pending I/O. Such a
  4499. * woken queue does not steal bandwidth from bfqq,
  4500. * because it remains soon without I/O if bfqq is not
  4501. * served. So there is virtually no risk of loss of
  4502. * bandwidth for bfqq if this woken queue has I/O
  4503. * dispatched while bfqq is waiting for new I/O.
  4504. *
  4505. * The fourth if checks whether bfqq is a queue for
  4506. * which it is better to avoid injection. It is so if
  4507. * bfqq delivers more throughput when served without
  4508. * any further I/O from other queues in the middle, or
  4509. * if the service times of bfqq's I/O requests both
  4510. * count more than overall throughput, and may be
  4511. * easily increased by injection (this happens if bfqq
  4512. * has a short think time). If none of these
  4513. * conditions holds, then a candidate queue for
  4514. * injection is looked for through
  4515. * bfq_choose_bfqq_for_injection(). Note that the
  4516. * latter may return NULL (for example if the inject
  4517. * limit for bfqq is currently 0).
  4518. *
  4519. * NOTE: motivation for the second alternative
  4520. *
  4521. * Thanks to the way the inject limit is updated in
  4522. * bfq_update_has_short_ttime(), it is rather likely
  4523. * that, if I/O is being plugged for bfqq and the
  4524. * waker queue has pending I/O requests that are
  4525. * blocking bfqq's I/O, then the fourth alternative
  4526. * above lets the waker queue get served before the
  4527. * I/O-plugging timeout fires. So one may deem the
  4528. * second alternative superfluous. It is not, because
  4529. * the fourth alternative may be way less effective in
  4530. * case of a synchronization. For two main
  4531. * reasons. First, throughput may be low because the
  4532. * inject limit may be too low to guarantee the same
  4533. * amount of injected I/O, from the waker queue or
  4534. * other queues, that the second alternative
  4535. * guarantees (the second alternative unconditionally
  4536. * injects a pending I/O request of the waker queue
  4537. * for each bfq_dispatch_request()). Second, with the
  4538. * fourth alternative, the duration of the plugging,
  4539. * i.e., the time before bfqq finally receives new I/O,
  4540. * may not be minimized, because the waker queue may
  4541. * happen to be served only after other queues.
  4542. */
  4543. if (async_bfqq &&
  4544. icq_to_bic(async_bfqq->next_rq->elv.icq) == bfqq->bic &&
  4545. bfq_serv_to_charge(async_bfqq->next_rq, async_bfqq) <=
  4546. bfq_bfqq_budget_left(async_bfqq))
  4547. bfqq = async_bfqq;
  4548. else if (bfqq->waker_bfqq &&
  4549. bfq_bfqq_busy(bfqq->waker_bfqq) &&
  4550. bfqq->waker_bfqq->next_rq &&
  4551. bfq_serv_to_charge(bfqq->waker_bfqq->next_rq,
  4552. bfqq->waker_bfqq) <=
  4553. bfq_bfqq_budget_left(bfqq->waker_bfqq)
  4554. )
  4555. bfqq = bfqq->waker_bfqq;
  4556. else if (blocked_bfqq &&
  4557. bfq_bfqq_busy(blocked_bfqq) &&
  4558. blocked_bfqq->next_rq &&
  4559. bfq_serv_to_charge(blocked_bfqq->next_rq,
  4560. blocked_bfqq) <=
  4561. bfq_bfqq_budget_left(blocked_bfqq)
  4562. )
  4563. bfqq = blocked_bfqq;
  4564. else if (!idling_boosts_thr_without_issues(bfqd, bfqq) &&
  4565. (bfqq->wr_coeff == 1 || bfqd->wr_busy_queues > 1 ||
  4566. !bfq_bfqq_has_short_ttime(bfqq)))
  4567. bfqq = bfq_choose_bfqq_for_injection(bfqd);
  4568. else
  4569. bfqq = NULL;
  4570. goto keep_queue;
  4571. }
  4572. reason = BFQQE_NO_MORE_REQUESTS;
  4573. expire:
  4574. bfq_bfqq_expire(bfqd, bfqq, false, reason);
  4575. new_queue:
  4576. bfqq = bfq_set_in_service_queue(bfqd);
  4577. if (bfqq) {
  4578. bfq_log_bfqq(bfqd, bfqq, "select_queue: checking new queue");
  4579. goto check_queue;
  4580. }
  4581. keep_queue:
  4582. if (bfqq)
  4583. bfq_log_bfqq(bfqd, bfqq, "select_queue: returned this queue");
  4584. else
  4585. bfq_log(bfqd, "select_queue: no queue returned");
  4586. return bfqq;
  4587. }
  4588. static void bfq_update_wr_data(struct bfq_data *bfqd, struct bfq_queue *bfqq)
  4589. {
  4590. struct bfq_entity *entity = &bfqq->entity;
  4591. if (bfqq->wr_coeff > 1) { /* queue is being weight-raised */
  4592. bfq_log_bfqq(bfqd, bfqq,
  4593. "raising period dur %u/%u msec, old coeff %u, w %d(%d)",
  4594. jiffies_to_msecs(jiffies - bfqq->last_wr_start_finish),
  4595. jiffies_to_msecs(bfqq->wr_cur_max_time),
  4596. bfqq->wr_coeff,
  4597. bfqq->entity.weight, bfqq->entity.orig_weight);
  4598. if (entity->prio_changed)
  4599. bfq_log_bfqq(bfqd, bfqq, "WARN: pending prio change");
  4600. /*
  4601. * If the queue was activated in a burst, or too much
  4602. * time has elapsed from the beginning of this
  4603. * weight-raising period, then end weight raising.
  4604. */
  4605. if (bfq_bfqq_in_large_burst(bfqq))
  4606. bfq_bfqq_end_wr(bfqq);
  4607. else if (time_is_before_jiffies(bfqq->last_wr_start_finish +
  4608. bfqq->wr_cur_max_time)) {
  4609. if (bfqq->wr_cur_max_time != bfqd->bfq_wr_rt_max_time ||
  4610. time_is_before_jiffies(bfqq->wr_start_at_switch_to_srt +
  4611. bfq_wr_duration(bfqd))) {
  4612. /*
  4613. * Either in interactive weight
  4614. * raising, or in soft_rt weight
  4615. * raising with the
  4616. * interactive-weight-raising period
  4617. * elapsed (so no switch back to
  4618. * interactive weight raising).
  4619. */
  4620. bfq_bfqq_end_wr(bfqq);
  4621. } else { /*
  4622. * soft_rt finishing while still in
  4623. * interactive period, switch back to
  4624. * interactive weight raising
  4625. */
  4626. switch_back_to_interactive_wr(bfqq, bfqd);
  4627. bfqq->entity.prio_changed = 1;
  4628. }
  4629. }
  4630. if (bfqq->wr_coeff > 1 &&
  4631. bfqq->wr_cur_max_time != bfqd->bfq_wr_rt_max_time &&
  4632. bfqq->service_from_wr > max_service_from_wr) {
  4633. /* see comments on max_service_from_wr */
  4634. bfq_bfqq_end_wr(bfqq);
  4635. }
  4636. }
  4637. /*
  4638. * To improve latency (for this or other queues), immediately
  4639. * update weight both if it must be raised and if it must be
  4640. * lowered. Since, entity may be on some active tree here, and
  4641. * might have a pending change of its ioprio class, invoke
  4642. * next function with the last parameter unset (see the
  4643. * comments on the function).
  4644. */
  4645. if ((entity->weight > entity->orig_weight) != (bfqq->wr_coeff > 1))
  4646. __bfq_entity_update_weight_prio(bfq_entity_service_tree(entity),
  4647. entity, false);
  4648. }
  4649. /*
  4650. * Dispatch next request from bfqq.
  4651. */
  4652. static struct request *bfq_dispatch_rq_from_bfqq(struct bfq_data *bfqd,
  4653. struct bfq_queue *bfqq)
  4654. {
  4655. struct request *rq = bfqq->next_rq;
  4656. unsigned long service_to_charge;
  4657. service_to_charge = bfq_serv_to_charge(rq, bfqq);
  4658. bfq_bfqq_served(bfqq, service_to_charge);
  4659. if (bfqq == bfqd->in_service_queue && bfqd->wait_dispatch) {
  4660. bfqd->wait_dispatch = false;
  4661. bfqd->waited_rq = rq;
  4662. }
  4663. bfq_dispatch_remove(bfqd->queue, rq);
  4664. if (bfqq != bfqd->in_service_queue)
  4665. return rq;
  4666. /*
  4667. * If weight raising has to terminate for bfqq, then next
  4668. * function causes an immediate update of bfqq's weight,
  4669. * without waiting for next activation. As a consequence, on
  4670. * expiration, bfqq will be timestamped as if has never been
  4671. * weight-raised during this service slot, even if it has
  4672. * received part or even most of the service as a
  4673. * weight-raised queue. This inflates bfqq's timestamps, which
  4674. * is beneficial, as bfqq is then more willing to leave the
  4675. * device immediately to possible other weight-raised queues.
  4676. */
  4677. bfq_update_wr_data(bfqd, bfqq);
  4678. /*
  4679. * Expire bfqq, pretending that its budget expired, if bfqq
  4680. * belongs to CLASS_IDLE and other queues are waiting for
  4681. * service.
  4682. */
  4683. if (bfq_tot_busy_queues(bfqd) > 1 && bfq_class_idle(bfqq))
  4684. bfq_bfqq_expire(bfqd, bfqq, false, BFQQE_BUDGET_EXHAUSTED);
  4685. return rq;
  4686. }
  4687. static bool bfq_has_work(struct blk_mq_hw_ctx *hctx)
  4688. {
  4689. struct bfq_data *bfqd = hctx->queue->elevator->elevator_data;
  4690. /*
  4691. * Avoiding lock: a race on bfqd->queued should cause at
  4692. * most a call to dispatch for nothing
  4693. */
  4694. return !list_empty_careful(&bfqd->dispatch) ||
  4695. READ_ONCE(bfqd->queued);
  4696. }
  4697. static struct request *__bfq_dispatch_request(struct blk_mq_hw_ctx *hctx)
  4698. {
  4699. struct bfq_data *bfqd = hctx->queue->elevator->elevator_data;
  4700. struct request *rq = NULL;
  4701. struct bfq_queue *bfqq = NULL;
  4702. if (!list_empty(&bfqd->dispatch)) {
  4703. rq = list_first_entry(&bfqd->dispatch, struct request,
  4704. queuelist);
  4705. list_del_init(&rq->queuelist);
  4706. bfqq = RQ_BFQQ(rq);
  4707. if (bfqq) {
  4708. /*
  4709. * Increment counters here, because this
  4710. * dispatch does not follow the standard
  4711. * dispatch flow (where counters are
  4712. * incremented)
  4713. */
  4714. bfqq->dispatched++;
  4715. goto inc_in_driver_start_rq;
  4716. }
  4717. /*
  4718. * We exploit the bfq_finish_requeue_request hook to
  4719. * decrement tot_rq_in_driver, but
  4720. * bfq_finish_requeue_request will not be invoked on
  4721. * this request. So, to avoid unbalance, just start
  4722. * this request, without incrementing tot_rq_in_driver. As
  4723. * a negative consequence, tot_rq_in_driver is deceptively
  4724. * lower than it should be while this request is in
  4725. * service. This may cause bfq_schedule_dispatch to be
  4726. * invoked uselessly.
  4727. *
  4728. * As for implementing an exact solution, the
  4729. * bfq_finish_requeue_request hook, if defined, is
  4730. * probably invoked also on this request. So, by
  4731. * exploiting this hook, we could 1) increment
  4732. * tot_rq_in_driver here, and 2) decrement it in
  4733. * bfq_finish_requeue_request. Such a solution would
  4734. * let the value of the counter be always accurate,
  4735. * but it would entail using an extra interface
  4736. * function. This cost seems higher than the benefit,
  4737. * being the frequency of non-elevator-private
  4738. * requests very low.
  4739. */
  4740. goto start_rq;
  4741. }
  4742. bfq_log(bfqd, "dispatch requests: %d busy queues",
  4743. bfq_tot_busy_queues(bfqd));
  4744. if (bfq_tot_busy_queues(bfqd) == 0)
  4745. goto exit;
  4746. /*
  4747. * Force device to serve one request at a time if
  4748. * strict_guarantees is true. Forcing this service scheme is
  4749. * currently the ONLY way to guarantee that the request
  4750. * service order enforced by the scheduler is respected by a
  4751. * queueing device. Otherwise the device is free even to make
  4752. * some unlucky request wait for as long as the device
  4753. * wishes.
  4754. *
  4755. * Of course, serving one request at a time may cause loss of
  4756. * throughput.
  4757. */
  4758. if (bfqd->strict_guarantees && bfqd->tot_rq_in_driver > 0)
  4759. goto exit;
  4760. bfqq = bfq_select_queue(bfqd);
  4761. if (!bfqq)
  4762. goto exit;
  4763. rq = bfq_dispatch_rq_from_bfqq(bfqd, bfqq);
  4764. if (rq) {
  4765. inc_in_driver_start_rq:
  4766. bfqd->rq_in_driver[bfqq->actuator_idx]++;
  4767. bfqd->tot_rq_in_driver++;
  4768. start_rq:
  4769. rq->rq_flags |= RQF_STARTED;
  4770. }
  4771. exit:
  4772. return rq;
  4773. }
  4774. #ifdef CONFIG_BFQ_CGROUP_DEBUG
  4775. static void bfq_update_dispatch_stats(struct request_queue *q,
  4776. struct request *rq,
  4777. struct bfq_queue *in_serv_queue,
  4778. bool idle_timer_disabled)
  4779. {
  4780. struct bfq_queue *bfqq = rq ? RQ_BFQQ(rq) : NULL;
  4781. if (!idle_timer_disabled && !bfqq)
  4782. return;
  4783. /*
  4784. * rq and bfqq are guaranteed to exist until this function
  4785. * ends, for the following reasons. First, rq can be
  4786. * dispatched to the device, and then can be completed and
  4787. * freed, only after this function ends. Second, rq cannot be
  4788. * merged (and thus freed because of a merge) any longer,
  4789. * because it has already started. Thus rq cannot be freed
  4790. * before this function ends, and, since rq has a reference to
  4791. * bfqq, the same guarantee holds for bfqq too.
  4792. *
  4793. * In addition, the following queue lock guarantees that
  4794. * bfqq_group(bfqq) exists as well.
  4795. */
  4796. spin_lock_irq(&q->queue_lock);
  4797. if (idle_timer_disabled)
  4798. /*
  4799. * Since the idle timer has been disabled,
  4800. * in_serv_queue contained some request when
  4801. * __bfq_dispatch_request was invoked above, which
  4802. * implies that rq was picked exactly from
  4803. * in_serv_queue. Thus in_serv_queue == bfqq, and is
  4804. * therefore guaranteed to exist because of the above
  4805. * arguments.
  4806. */
  4807. bfqg_stats_update_idle_time(bfqq_group(in_serv_queue));
  4808. if (bfqq) {
  4809. struct bfq_group *bfqg = bfqq_group(bfqq);
  4810. bfqg_stats_update_avg_queue_size(bfqg);
  4811. bfqg_stats_set_start_empty_time(bfqg);
  4812. bfqg_stats_update_io_remove(bfqg, rq->cmd_flags);
  4813. }
  4814. spin_unlock_irq(&q->queue_lock);
  4815. }
  4816. #else
  4817. static inline void bfq_update_dispatch_stats(struct request_queue *q,
  4818. struct request *rq,
  4819. struct bfq_queue *in_serv_queue,
  4820. bool idle_timer_disabled) {}
  4821. #endif /* CONFIG_BFQ_CGROUP_DEBUG */
  4822. static struct request *bfq_dispatch_request(struct blk_mq_hw_ctx *hctx)
  4823. {
  4824. struct bfq_data *bfqd = hctx->queue->elevator->elevator_data;
  4825. struct request *rq;
  4826. struct bfq_queue *in_serv_queue;
  4827. bool waiting_rq, idle_timer_disabled = false;
  4828. spin_lock_irq(&bfqd->lock);
  4829. in_serv_queue = bfqd->in_service_queue;
  4830. waiting_rq = in_serv_queue && bfq_bfqq_wait_request(in_serv_queue);
  4831. rq = __bfq_dispatch_request(hctx);
  4832. if (in_serv_queue == bfqd->in_service_queue) {
  4833. idle_timer_disabled =
  4834. waiting_rq && !bfq_bfqq_wait_request(in_serv_queue);
  4835. }
  4836. spin_unlock_irq(&bfqd->lock);
  4837. bfq_update_dispatch_stats(hctx->queue, rq,
  4838. idle_timer_disabled ? in_serv_queue : NULL,
  4839. idle_timer_disabled);
  4840. return rq;
  4841. }
  4842. /*
  4843. * Task holds one reference to the queue, dropped when task exits. Each rq
  4844. * in-flight on this queue also holds a reference, dropped when rq is freed.
  4845. *
  4846. * Scheduler lock must be held here. Recall not to use bfqq after calling
  4847. * this function on it.
  4848. */
  4849. void bfq_put_queue(struct bfq_queue *bfqq)
  4850. {
  4851. struct bfq_queue *item;
  4852. struct hlist_node *n;
  4853. struct bfq_group *bfqg = bfqq_group(bfqq);
  4854. bfq_log_bfqq(bfqq->bfqd, bfqq, "put_queue: %p %d", bfqq, bfqq->ref);
  4855. bfqq->ref--;
  4856. if (bfqq->ref)
  4857. return;
  4858. if (!hlist_unhashed(&bfqq->burst_list_node)) {
  4859. hlist_del_init(&bfqq->burst_list_node);
  4860. /*
  4861. * Decrement also burst size after the removal, if the
  4862. * process associated with bfqq is exiting, and thus
  4863. * does not contribute to the burst any longer. This
  4864. * decrement helps filter out false positives of large
  4865. * bursts, when some short-lived process (often due to
  4866. * the execution of commands by some service) happens
  4867. * to start and exit while a complex application is
  4868. * starting, and thus spawning several processes that
  4869. * do I/O (and that *must not* be treated as a large
  4870. * burst, see comments on bfq_handle_burst).
  4871. *
  4872. * In particular, the decrement is performed only if:
  4873. * 1) bfqq is not a merged queue, because, if it is,
  4874. * then this free of bfqq is not triggered by the exit
  4875. * of the process bfqq is associated with, but exactly
  4876. * by the fact that bfqq has just been merged.
  4877. * 2) burst_size is greater than 0, to handle
  4878. * unbalanced decrements. Unbalanced decrements may
  4879. * happen in te following case: bfqq is inserted into
  4880. * the current burst list--without incrementing
  4881. * bust_size--because of a split, but the current
  4882. * burst list is not the burst list bfqq belonged to
  4883. * (see comments on the case of a split in
  4884. * bfq_set_request).
  4885. */
  4886. if (bfqq->bic && bfqq->bfqd->burst_size > 0)
  4887. bfqq->bfqd->burst_size--;
  4888. }
  4889. /*
  4890. * bfqq does not exist any longer, so it cannot be woken by
  4891. * any other queue, and cannot wake any other queue. Then bfqq
  4892. * must be removed from the woken list of its possible waker
  4893. * queue, and all queues in the woken list of bfqq must stop
  4894. * having a waker queue. Strictly speaking, these updates
  4895. * should be performed when bfqq remains with no I/O source
  4896. * attached to it, which happens before bfqq gets freed. In
  4897. * particular, this happens when the last process associated
  4898. * with bfqq exits or gets associated with a different
  4899. * queue. However, both events lead to bfqq being freed soon,
  4900. * and dangling references would come out only after bfqq gets
  4901. * freed. So these updates are done here, as a simple and safe
  4902. * way to handle all cases.
  4903. */
  4904. /* remove bfqq from woken list */
  4905. if (!hlist_unhashed(&bfqq->woken_list_node))
  4906. hlist_del_init(&bfqq->woken_list_node);
  4907. /* reset waker for all queues in woken list */
  4908. hlist_for_each_entry_safe(item, n, &bfqq->woken_list,
  4909. woken_list_node) {
  4910. item->waker_bfqq = NULL;
  4911. hlist_del_init(&item->woken_list_node);
  4912. }
  4913. if (bfqq->bfqd->last_completed_rq_bfqq == bfqq)
  4914. bfqq->bfqd->last_completed_rq_bfqq = NULL;
  4915. WARN_ON_ONCE(!list_empty(&bfqq->fifo));
  4916. WARN_ON_ONCE(!RB_EMPTY_ROOT(&bfqq->sort_list));
  4917. WARN_ON_ONCE(bfqq->dispatched);
  4918. kmem_cache_free(bfq_pool, bfqq);
  4919. bfqg_and_blkg_put(bfqg);
  4920. }
  4921. static void bfq_put_stable_ref(struct bfq_queue *bfqq)
  4922. {
  4923. bfqq->stable_ref--;
  4924. bfq_put_queue(bfqq);
  4925. }
  4926. void bfq_put_cooperator(struct bfq_queue *bfqq)
  4927. {
  4928. struct bfq_queue *__bfqq, *next;
  4929. /*
  4930. * If this queue was scheduled to merge with another queue, be
  4931. * sure to drop the reference taken on that queue (and others in
  4932. * the merge chain). See bfq_setup_merge and bfq_merge_bfqqs.
  4933. */
  4934. __bfqq = bfqq->new_bfqq;
  4935. while (__bfqq) {
  4936. next = __bfqq->new_bfqq;
  4937. bfq_put_queue(__bfqq);
  4938. __bfqq = next;
  4939. }
  4940. }
  4941. static void bfq_exit_bfqq(struct bfq_data *bfqd, struct bfq_queue *bfqq)
  4942. {
  4943. if (bfqq == bfqd->in_service_queue) {
  4944. __bfq_bfqq_expire(bfqd, bfqq, BFQQE_BUDGET_TIMEOUT);
  4945. bfq_schedule_dispatch(bfqd);
  4946. }
  4947. bfq_log_bfqq(bfqd, bfqq, "exit_bfqq: %p, %d", bfqq, bfqq->ref);
  4948. bfq_put_cooperator(bfqq);
  4949. bfq_release_process_ref(bfqd, bfqq);
  4950. }
  4951. static void bfq_exit_icq_bfqq(struct bfq_io_cq *bic, bool is_sync,
  4952. unsigned int actuator_idx)
  4953. {
  4954. struct bfq_queue *bfqq = bic_to_bfqq(bic, is_sync, actuator_idx);
  4955. struct bfq_data *bfqd;
  4956. if (bfqq)
  4957. bfqd = bfqq->bfqd; /* NULL if scheduler already exited */
  4958. if (bfqq && bfqd) {
  4959. bic_set_bfqq(bic, NULL, is_sync, actuator_idx);
  4960. bfq_exit_bfqq(bfqd, bfqq);
  4961. }
  4962. }
  4963. static void _bfq_exit_icq(struct bfq_io_cq *bic, unsigned int num_actuators)
  4964. {
  4965. struct bfq_iocq_bfqq_data *bfqq_data = bic->bfqq_data;
  4966. unsigned int act_idx;
  4967. for (act_idx = 0; act_idx < num_actuators; act_idx++) {
  4968. if (bfqq_data[act_idx].stable_merge_bfqq)
  4969. bfq_put_stable_ref(bfqq_data[act_idx].stable_merge_bfqq);
  4970. bfq_exit_icq_bfqq(bic, true, act_idx);
  4971. bfq_exit_icq_bfqq(bic, false, act_idx);
  4972. }
  4973. }
  4974. static void bfq_exit_icq(struct io_cq *icq)
  4975. {
  4976. struct bfq_io_cq *bic = icq_to_bic(icq);
  4977. struct bfq_data *bfqd = bic_to_bfqd(bic);
  4978. unsigned long flags;
  4979. /*
  4980. * If bfqd and thus bfqd->num_actuators is not available any
  4981. * longer, then cycle over all possible per-actuator bfqqs in
  4982. * next loop. We rely on bic being zeroed on creation, and
  4983. * therefore on its unused per-actuator fields being NULL.
  4984. *
  4985. * bfqd is NULL if scheduler already exited, and in that case
  4986. * this is the last time these queues are accessed.
  4987. */
  4988. if (bfqd) {
  4989. spin_lock_irqsave(&bfqd->lock, flags);
  4990. _bfq_exit_icq(bic, bfqd->num_actuators);
  4991. spin_unlock_irqrestore(&bfqd->lock, flags);
  4992. } else {
  4993. _bfq_exit_icq(bic, BFQ_MAX_ACTUATORS);
  4994. }
  4995. }
  4996. /*
  4997. * Update the entity prio values; note that the new values will not
  4998. * be used until the next (re)activation.
  4999. */
  5000. static void
  5001. bfq_set_next_ioprio_data(struct bfq_queue *bfqq, struct bfq_io_cq *bic)
  5002. {
  5003. struct task_struct *tsk = current;
  5004. int ioprio_class;
  5005. struct bfq_data *bfqd = bfqq->bfqd;
  5006. if (!bfqd)
  5007. return;
  5008. ioprio_class = IOPRIO_PRIO_CLASS(bic->ioprio);
  5009. switch (ioprio_class) {
  5010. default:
  5011. pr_err("bdi %s: bfq: bad prio class %d\n",
  5012. bdi_dev_name(bfqq->bfqd->queue->disk->bdi),
  5013. ioprio_class);
  5014. fallthrough;
  5015. case IOPRIO_CLASS_NONE:
  5016. /*
  5017. * No prio set, inherit CPU scheduling settings.
  5018. */
  5019. bfqq->new_ioprio = task_nice_ioprio(tsk);
  5020. bfqq->new_ioprio_class = task_nice_ioclass(tsk);
  5021. break;
  5022. case IOPRIO_CLASS_RT:
  5023. bfqq->new_ioprio = IOPRIO_PRIO_LEVEL(bic->ioprio);
  5024. bfqq->new_ioprio_class = IOPRIO_CLASS_RT;
  5025. break;
  5026. case IOPRIO_CLASS_BE:
  5027. bfqq->new_ioprio = IOPRIO_PRIO_LEVEL(bic->ioprio);
  5028. bfqq->new_ioprio_class = IOPRIO_CLASS_BE;
  5029. break;
  5030. case IOPRIO_CLASS_IDLE:
  5031. bfqq->new_ioprio_class = IOPRIO_CLASS_IDLE;
  5032. bfqq->new_ioprio = IOPRIO_NR_LEVELS - 1;
  5033. break;
  5034. }
  5035. if (bfqq->new_ioprio >= IOPRIO_NR_LEVELS) {
  5036. pr_crit("bfq_set_next_ioprio_data: new_ioprio %d\n",
  5037. bfqq->new_ioprio);
  5038. bfqq->new_ioprio = IOPRIO_NR_LEVELS - 1;
  5039. }
  5040. bfqq->entity.new_weight = bfq_ioprio_to_weight(bfqq->new_ioprio);
  5041. bfq_log_bfqq(bfqd, bfqq, "new_ioprio %d new_weight %d",
  5042. bfqq->new_ioprio, bfqq->entity.new_weight);
  5043. bfqq->entity.prio_changed = 1;
  5044. }
  5045. static struct bfq_queue *bfq_get_queue(struct bfq_data *bfqd,
  5046. struct bio *bio, bool is_sync,
  5047. struct bfq_io_cq *bic,
  5048. bool respawn);
  5049. static void bfq_check_ioprio_change(struct bfq_io_cq *bic, struct bio *bio)
  5050. {
  5051. struct bfq_data *bfqd = bic_to_bfqd(bic);
  5052. struct bfq_queue *bfqq;
  5053. int ioprio = bic->icq.ioc->ioprio;
  5054. /*
  5055. * This condition may trigger on a newly created bic, be sure to
  5056. * drop the lock before returning.
  5057. */
  5058. if (unlikely(!bfqd) || likely(bic->ioprio == ioprio))
  5059. return;
  5060. bic->ioprio = ioprio;
  5061. bfqq = bic_to_bfqq(bic, false, bfq_actuator_index(bfqd, bio));
  5062. if (bfqq) {
  5063. struct bfq_queue *old_bfqq = bfqq;
  5064. bfqq = bfq_get_queue(bfqd, bio, false, bic, true);
  5065. bic_set_bfqq(bic, bfqq, false, bfq_actuator_index(bfqd, bio));
  5066. bfq_release_process_ref(bfqd, old_bfqq);
  5067. }
  5068. bfqq = bic_to_bfqq(bic, true, bfq_actuator_index(bfqd, bio));
  5069. if (bfqq)
  5070. bfq_set_next_ioprio_data(bfqq, bic);
  5071. }
  5072. static void bfq_init_bfqq(struct bfq_data *bfqd, struct bfq_queue *bfqq,
  5073. struct bfq_io_cq *bic, pid_t pid, int is_sync,
  5074. unsigned int act_idx)
  5075. {
  5076. u64 now_ns = blk_time_get_ns();
  5077. bfqq->actuator_idx = act_idx;
  5078. RB_CLEAR_NODE(&bfqq->entity.rb_node);
  5079. INIT_LIST_HEAD(&bfqq->fifo);
  5080. INIT_HLIST_NODE(&bfqq->burst_list_node);
  5081. INIT_HLIST_NODE(&bfqq->woken_list_node);
  5082. INIT_HLIST_HEAD(&bfqq->woken_list);
  5083. bfqq->ref = 0;
  5084. bfqq->bfqd = bfqd;
  5085. if (bic)
  5086. bfq_set_next_ioprio_data(bfqq, bic);
  5087. if (is_sync) {
  5088. /*
  5089. * No need to mark as has_short_ttime if in
  5090. * idle_class, because no device idling is performed
  5091. * for queues in idle class
  5092. */
  5093. if (!bfq_class_idle(bfqq))
  5094. /* tentatively mark as has_short_ttime */
  5095. bfq_mark_bfqq_has_short_ttime(bfqq);
  5096. bfq_mark_bfqq_sync(bfqq);
  5097. bfq_mark_bfqq_just_created(bfqq);
  5098. } else
  5099. bfq_clear_bfqq_sync(bfqq);
  5100. /* set end request to minus infinity from now */
  5101. bfqq->ttime.last_end_request = now_ns + 1;
  5102. bfqq->creation_time = jiffies;
  5103. bfqq->io_start_time = now_ns;
  5104. bfq_mark_bfqq_IO_bound(bfqq);
  5105. bfqq->pid = pid;
  5106. /* Tentative initial value to trade off between thr and lat */
  5107. bfqq->max_budget = (2 * bfq_max_budget(bfqd)) / 3;
  5108. bfqq->budget_timeout = bfq_smallest_from_now();
  5109. bfqq->wr_coeff = 1;
  5110. bfqq->last_wr_start_finish = jiffies;
  5111. bfqq->wr_start_at_switch_to_srt = bfq_smallest_from_now();
  5112. bfqq->split_time = bfq_smallest_from_now();
  5113. /*
  5114. * To not forget the possibly high bandwidth consumed by a
  5115. * process/queue in the recent past,
  5116. * bfq_bfqq_softrt_next_start() returns a value at least equal
  5117. * to the current value of bfqq->soft_rt_next_start (see
  5118. * comments on bfq_bfqq_softrt_next_start). Set
  5119. * soft_rt_next_start to now, to mean that bfqq has consumed
  5120. * no bandwidth so far.
  5121. */
  5122. bfqq->soft_rt_next_start = jiffies;
  5123. /* first request is almost certainly seeky */
  5124. bfqq->seek_history = 1;
  5125. bfqq->decrease_time_jif = jiffies;
  5126. }
  5127. static struct bfq_queue **bfq_async_queue_prio(struct bfq_data *bfqd,
  5128. struct bfq_group *bfqg,
  5129. int ioprio_class, int ioprio, int act_idx)
  5130. {
  5131. switch (ioprio_class) {
  5132. case IOPRIO_CLASS_RT:
  5133. return &bfqg->async_bfqq[0][ioprio][act_idx];
  5134. case IOPRIO_CLASS_NONE:
  5135. ioprio = IOPRIO_BE_NORM;
  5136. fallthrough;
  5137. case IOPRIO_CLASS_BE:
  5138. return &bfqg->async_bfqq[1][ioprio][act_idx];
  5139. case IOPRIO_CLASS_IDLE:
  5140. return &bfqg->async_idle_bfqq[act_idx];
  5141. default:
  5142. return NULL;
  5143. }
  5144. }
  5145. static struct bfq_queue *
  5146. bfq_do_early_stable_merge(struct bfq_data *bfqd, struct bfq_queue *bfqq,
  5147. struct bfq_io_cq *bic,
  5148. struct bfq_queue *last_bfqq_created)
  5149. {
  5150. unsigned int a_idx = last_bfqq_created->actuator_idx;
  5151. struct bfq_queue *new_bfqq =
  5152. bfq_setup_merge(bfqq, last_bfqq_created);
  5153. if (!new_bfqq)
  5154. return bfqq;
  5155. if (new_bfqq->bic)
  5156. new_bfqq->bic->bfqq_data[a_idx].stably_merged = true;
  5157. bic->bfqq_data[a_idx].stably_merged = true;
  5158. /*
  5159. * Reusing merge functions. This implies that
  5160. * bfqq->bic must be set too, for
  5161. * bfq_merge_bfqqs to correctly save bfqq's
  5162. * state before killing it.
  5163. */
  5164. bfqq->bic = bic;
  5165. return bfq_merge_bfqqs(bfqd, bic, bfqq);
  5166. }
  5167. /*
  5168. * Many throughput-sensitive workloads are made of several parallel
  5169. * I/O flows, with all flows generated by the same application, or
  5170. * more generically by the same task (e.g., system boot). The most
  5171. * counterproductive action with these workloads is plugging I/O
  5172. * dispatch when one of the bfq_queues associated with these flows
  5173. * remains temporarily empty.
  5174. *
  5175. * To avoid this plugging, BFQ has been using a burst-handling
  5176. * mechanism for years now. This mechanism has proven effective for
  5177. * throughput, and not detrimental for service guarantees. The
  5178. * following function pushes this mechanism a little bit further,
  5179. * basing on the following two facts.
  5180. *
  5181. * First, all the I/O flows of a the same application or task
  5182. * contribute to the execution/completion of that common application
  5183. * or task. So the performance figures that matter are total
  5184. * throughput of the flows and task-wide I/O latency. In particular,
  5185. * these flows do not need to be protected from each other, in terms
  5186. * of individual bandwidth or latency.
  5187. *
  5188. * Second, the above fact holds regardless of the number of flows.
  5189. *
  5190. * Putting these two facts together, this commits merges stably the
  5191. * bfq_queues associated with these I/O flows, i.e., with the
  5192. * processes that generate these IO/ flows, regardless of how many the
  5193. * involved processes are.
  5194. *
  5195. * To decide whether a set of bfq_queues is actually associated with
  5196. * the I/O flows of a common application or task, and to merge these
  5197. * queues stably, this function operates as follows: given a bfq_queue,
  5198. * say Q2, currently being created, and the last bfq_queue, say Q1,
  5199. * created before Q2, Q2 is merged stably with Q1 if
  5200. * - very little time has elapsed since when Q1 was created
  5201. * - Q2 has the same ioprio as Q1
  5202. * - Q2 belongs to the same group as Q1
  5203. *
  5204. * Merging bfq_queues also reduces scheduling overhead. A fio test
  5205. * with ten random readers on /dev/nullb shows a throughput boost of
  5206. * 40%, with a quadcore. Since BFQ's execution time amounts to ~50% of
  5207. * the total per-request processing time, the above throughput boost
  5208. * implies that BFQ's overhead is reduced by more than 50%.
  5209. *
  5210. * This new mechanism most certainly obsoletes the current
  5211. * burst-handling heuristics. We keep those heuristics for the moment.
  5212. */
  5213. static struct bfq_queue *bfq_do_or_sched_stable_merge(struct bfq_data *bfqd,
  5214. struct bfq_queue *bfqq,
  5215. struct bfq_io_cq *bic)
  5216. {
  5217. struct bfq_queue **source_bfqq = bfqq->entity.parent ?
  5218. &bfqq->entity.parent->last_bfqq_created :
  5219. &bfqd->last_bfqq_created;
  5220. struct bfq_queue *last_bfqq_created = *source_bfqq;
  5221. /*
  5222. * If last_bfqq_created has not been set yet, then init it. If
  5223. * it has been set already, but too long ago, then move it
  5224. * forward to bfqq. Finally, move also if bfqq belongs to a
  5225. * different group than last_bfqq_created, or if bfqq has a
  5226. * different ioprio, ioprio_class or actuator_idx. If none of
  5227. * these conditions holds true, then try an early stable merge
  5228. * or schedule a delayed stable merge. As for the condition on
  5229. * actuator_idx, the reason is that, if queues associated with
  5230. * different actuators are merged, then control is lost on
  5231. * each actuator. Therefore some actuator may be
  5232. * underutilized, and throughput may decrease.
  5233. *
  5234. * A delayed merge is scheduled (instead of performing an
  5235. * early merge), in case bfqq might soon prove to be more
  5236. * throughput-beneficial if not merged. Currently this is
  5237. * possible only if bfqd is rotational with no queueing. For
  5238. * such a drive, not merging bfqq is better for throughput if
  5239. * bfqq happens to contain sequential I/O. So, we wait a
  5240. * little bit for enough I/O to flow through bfqq. After that,
  5241. * if such an I/O is sequential, then the merge is
  5242. * canceled. Otherwise the merge is finally performed.
  5243. */
  5244. if (!last_bfqq_created ||
  5245. time_before(last_bfqq_created->creation_time +
  5246. msecs_to_jiffies(bfq_activation_stable_merging),
  5247. bfqq->creation_time) ||
  5248. bfqq->entity.parent != last_bfqq_created->entity.parent ||
  5249. bfqq->ioprio != last_bfqq_created->ioprio ||
  5250. bfqq->ioprio_class != last_bfqq_created->ioprio_class ||
  5251. bfqq->actuator_idx != last_bfqq_created->actuator_idx)
  5252. *source_bfqq = bfqq;
  5253. else if (time_after_eq(last_bfqq_created->creation_time +
  5254. bfqd->bfq_burst_interval,
  5255. bfqq->creation_time)) {
  5256. if (likely(bfqd->nonrot_with_queueing))
  5257. /*
  5258. * With this type of drive, leaving
  5259. * bfqq alone may provide no
  5260. * throughput benefits compared with
  5261. * merging bfqq. So merge bfqq now.
  5262. */
  5263. bfqq = bfq_do_early_stable_merge(bfqd, bfqq,
  5264. bic,
  5265. last_bfqq_created);
  5266. else { /* schedule tentative stable merge */
  5267. /*
  5268. * get reference on last_bfqq_created,
  5269. * to prevent it from being freed,
  5270. * until we decide whether to merge
  5271. */
  5272. last_bfqq_created->ref++;
  5273. /*
  5274. * need to keep track of stable refs, to
  5275. * compute process refs correctly
  5276. */
  5277. last_bfqq_created->stable_ref++;
  5278. /*
  5279. * Record the bfqq to merge to.
  5280. */
  5281. bic->bfqq_data[last_bfqq_created->actuator_idx].stable_merge_bfqq =
  5282. last_bfqq_created;
  5283. }
  5284. }
  5285. return bfqq;
  5286. }
  5287. static struct bfq_queue *bfq_get_queue(struct bfq_data *bfqd,
  5288. struct bio *bio, bool is_sync,
  5289. struct bfq_io_cq *bic,
  5290. bool respawn)
  5291. {
  5292. const int ioprio = IOPRIO_PRIO_LEVEL(bic->ioprio);
  5293. const int ioprio_class = IOPRIO_PRIO_CLASS(bic->ioprio);
  5294. struct bfq_queue **async_bfqq = NULL;
  5295. struct bfq_queue *bfqq;
  5296. struct bfq_group *bfqg;
  5297. bfqg = bfq_bio_bfqg(bfqd, bio);
  5298. if (!is_sync) {
  5299. async_bfqq = bfq_async_queue_prio(bfqd, bfqg, ioprio_class,
  5300. ioprio,
  5301. bfq_actuator_index(bfqd, bio));
  5302. bfqq = *async_bfqq;
  5303. if (bfqq)
  5304. goto out;
  5305. }
  5306. bfqq = kmem_cache_alloc_node(bfq_pool, GFP_NOWAIT | __GFP_ZERO,
  5307. bfqd->queue->node);
  5308. if (bfqq) {
  5309. bfq_init_bfqq(bfqd, bfqq, bic, current->pid,
  5310. is_sync, bfq_actuator_index(bfqd, bio));
  5311. bfq_init_entity(&bfqq->entity, bfqg);
  5312. bfq_log_bfqq(bfqd, bfqq, "allocated");
  5313. } else {
  5314. bfqq = &bfqd->oom_bfqq;
  5315. bfq_log_bfqq(bfqd, bfqq, "using oom bfqq");
  5316. goto out;
  5317. }
  5318. /*
  5319. * Pin the queue now that it's allocated, scheduler exit will
  5320. * prune it.
  5321. */
  5322. if (async_bfqq) {
  5323. bfqq->ref++; /*
  5324. * Extra group reference, w.r.t. sync
  5325. * queue. This extra reference is removed
  5326. * only if bfqq->bfqg disappears, to
  5327. * guarantee that this queue is not freed
  5328. * until its group goes away.
  5329. */
  5330. bfq_log_bfqq(bfqd, bfqq, "get_queue, bfqq not in async: %p, %d",
  5331. bfqq, bfqq->ref);
  5332. *async_bfqq = bfqq;
  5333. }
  5334. out:
  5335. bfqq->ref++; /* get a process reference to this queue */
  5336. if (bfqq != &bfqd->oom_bfqq && is_sync && !respawn)
  5337. bfqq = bfq_do_or_sched_stable_merge(bfqd, bfqq, bic);
  5338. return bfqq;
  5339. }
  5340. static void bfq_update_io_thinktime(struct bfq_data *bfqd,
  5341. struct bfq_queue *bfqq)
  5342. {
  5343. struct bfq_ttime *ttime = &bfqq->ttime;
  5344. u64 elapsed;
  5345. /*
  5346. * We are really interested in how long it takes for the queue to
  5347. * become busy when there is no outstanding IO for this queue. So
  5348. * ignore cases when the bfq queue has already IO queued.
  5349. */
  5350. if (bfqq->dispatched || bfq_bfqq_busy(bfqq))
  5351. return;
  5352. elapsed = blk_time_get_ns() - bfqq->ttime.last_end_request;
  5353. elapsed = min_t(u64, elapsed, 2ULL * bfqd->bfq_slice_idle);
  5354. ttime->ttime_samples = (7*ttime->ttime_samples + 256) / 8;
  5355. ttime->ttime_total = div_u64(7*ttime->ttime_total + 256*elapsed, 8);
  5356. ttime->ttime_mean = div64_ul(ttime->ttime_total + 128,
  5357. ttime->ttime_samples);
  5358. }
  5359. static void
  5360. bfq_update_io_seektime(struct bfq_data *bfqd, struct bfq_queue *bfqq,
  5361. struct request *rq)
  5362. {
  5363. bfqq->seek_history <<= 1;
  5364. bfqq->seek_history |= BFQ_RQ_SEEKY(bfqd, bfqq->last_request_pos, rq);
  5365. if (bfqq->wr_coeff > 1 &&
  5366. bfqq->wr_cur_max_time == bfqd->bfq_wr_rt_max_time &&
  5367. BFQQ_TOTALLY_SEEKY(bfqq)) {
  5368. if (time_is_before_jiffies(bfqq->wr_start_at_switch_to_srt +
  5369. bfq_wr_duration(bfqd))) {
  5370. /*
  5371. * In soft_rt weight raising with the
  5372. * interactive-weight-raising period
  5373. * elapsed (so no switch back to
  5374. * interactive weight raising).
  5375. */
  5376. bfq_bfqq_end_wr(bfqq);
  5377. } else { /*
  5378. * stopping soft_rt weight raising
  5379. * while still in interactive period,
  5380. * switch back to interactive weight
  5381. * raising
  5382. */
  5383. switch_back_to_interactive_wr(bfqq, bfqd);
  5384. bfqq->entity.prio_changed = 1;
  5385. }
  5386. }
  5387. }
  5388. static void bfq_update_has_short_ttime(struct bfq_data *bfqd,
  5389. struct bfq_queue *bfqq,
  5390. struct bfq_io_cq *bic)
  5391. {
  5392. bool has_short_ttime = true, state_changed;
  5393. /*
  5394. * No need to update has_short_ttime if bfqq is async or in
  5395. * idle io prio class, or if bfq_slice_idle is zero, because
  5396. * no device idling is performed for bfqq in this case.
  5397. */
  5398. if (!bfq_bfqq_sync(bfqq) || bfq_class_idle(bfqq) ||
  5399. bfqd->bfq_slice_idle == 0)
  5400. return;
  5401. /* Idle window just restored, statistics are meaningless. */
  5402. if (time_is_after_eq_jiffies(bfqq->split_time +
  5403. bfqd->bfq_wr_min_idle_time))
  5404. return;
  5405. /* Think time is infinite if no process is linked to
  5406. * bfqq. Otherwise check average think time to decide whether
  5407. * to mark as has_short_ttime. To this goal, compare average
  5408. * think time with half the I/O-plugging timeout.
  5409. */
  5410. if (atomic_read(&bic->icq.ioc->active_ref) == 0 ||
  5411. (bfq_sample_valid(bfqq->ttime.ttime_samples) &&
  5412. bfqq->ttime.ttime_mean > bfqd->bfq_slice_idle>>1))
  5413. has_short_ttime = false;
  5414. state_changed = has_short_ttime != bfq_bfqq_has_short_ttime(bfqq);
  5415. if (has_short_ttime)
  5416. bfq_mark_bfqq_has_short_ttime(bfqq);
  5417. else
  5418. bfq_clear_bfqq_has_short_ttime(bfqq);
  5419. /*
  5420. * Until the base value for the total service time gets
  5421. * finally computed for bfqq, the inject limit does depend on
  5422. * the think-time state (short|long). In particular, the limit
  5423. * is 0 or 1 if the think time is deemed, respectively, as
  5424. * short or long (details in the comments in
  5425. * bfq_update_inject_limit()). Accordingly, the next
  5426. * instructions reset the inject limit if the think-time state
  5427. * has changed and the above base value is still to be
  5428. * computed.
  5429. *
  5430. * However, the reset is performed only if more than 100 ms
  5431. * have elapsed since the last update of the inject limit, or
  5432. * (inclusive) if the change is from short to long think
  5433. * time. The reason for this waiting is as follows.
  5434. *
  5435. * bfqq may have a long think time because of a
  5436. * synchronization with some other queue, i.e., because the
  5437. * I/O of some other queue may need to be completed for bfqq
  5438. * to receive new I/O. Details in the comments on the choice
  5439. * of the queue for injection in bfq_select_queue().
  5440. *
  5441. * As stressed in those comments, if such a synchronization is
  5442. * actually in place, then, without injection on bfqq, the
  5443. * blocking I/O cannot happen to served while bfqq is in
  5444. * service. As a consequence, if bfqq is granted
  5445. * I/O-dispatch-plugging, then bfqq remains empty, and no I/O
  5446. * is dispatched, until the idle timeout fires. This is likely
  5447. * to result in lower bandwidth and higher latencies for bfqq,
  5448. * and in a severe loss of total throughput.
  5449. *
  5450. * On the opposite end, a non-zero inject limit may allow the
  5451. * I/O that blocks bfqq to be executed soon, and therefore
  5452. * bfqq to receive new I/O soon.
  5453. *
  5454. * But, if the blocking gets actually eliminated, then the
  5455. * next think-time sample for bfqq may be very low. This in
  5456. * turn may cause bfqq's think time to be deemed
  5457. * short. Without the 100 ms barrier, this new state change
  5458. * would cause the body of the next if to be executed
  5459. * immediately. But this would set to 0 the inject
  5460. * limit. Without injection, the blocking I/O would cause the
  5461. * think time of bfqq to become long again, and therefore the
  5462. * inject limit to be raised again, and so on. The only effect
  5463. * of such a steady oscillation between the two think-time
  5464. * states would be to prevent effective injection on bfqq.
  5465. *
  5466. * In contrast, if the inject limit is not reset during such a
  5467. * long time interval as 100 ms, then the number of short
  5468. * think time samples can grow significantly before the reset
  5469. * is performed. As a consequence, the think time state can
  5470. * become stable before the reset. Therefore there will be no
  5471. * state change when the 100 ms elapse, and no reset of the
  5472. * inject limit. The inject limit remains steadily equal to 1
  5473. * both during and after the 100 ms. So injection can be
  5474. * performed at all times, and throughput gets boosted.
  5475. *
  5476. * An inject limit equal to 1 is however in conflict, in
  5477. * general, with the fact that the think time of bfqq is
  5478. * short, because injection may be likely to delay bfqq's I/O
  5479. * (as explained in the comments in
  5480. * bfq_update_inject_limit()). But this does not happen in
  5481. * this special case, because bfqq's low think time is due to
  5482. * an effective handling of a synchronization, through
  5483. * injection. In this special case, bfqq's I/O does not get
  5484. * delayed by injection; on the contrary, bfqq's I/O is
  5485. * brought forward, because it is not blocked for
  5486. * milliseconds.
  5487. *
  5488. * In addition, serving the blocking I/O much sooner, and much
  5489. * more frequently than once per I/O-plugging timeout, makes
  5490. * it much quicker to detect a waker queue (the concept of
  5491. * waker queue is defined in the comments in
  5492. * bfq_add_request()). This makes it possible to start sooner
  5493. * to boost throughput more effectively, by injecting the I/O
  5494. * of the waker queue unconditionally on every
  5495. * bfq_dispatch_request().
  5496. *
  5497. * One last, important benefit of not resetting the inject
  5498. * limit before 100 ms is that, during this time interval, the
  5499. * base value for the total service time is likely to get
  5500. * finally computed for bfqq, freeing the inject limit from
  5501. * its relation with the think time.
  5502. */
  5503. if (state_changed && bfqq->last_serv_time_ns == 0 &&
  5504. (time_is_before_eq_jiffies(bfqq->decrease_time_jif +
  5505. msecs_to_jiffies(100)) ||
  5506. !has_short_ttime))
  5507. bfq_reset_inject_limit(bfqd, bfqq);
  5508. }
  5509. /*
  5510. * Called when a new fs request (rq) is added to bfqq. Check if there's
  5511. * something we should do about it.
  5512. */
  5513. static void bfq_rq_enqueued(struct bfq_data *bfqd, struct bfq_queue *bfqq,
  5514. struct request *rq)
  5515. {
  5516. if (rq->cmd_flags & REQ_META)
  5517. bfqq->meta_pending++;
  5518. bfqq->last_request_pos = blk_rq_pos(rq) + blk_rq_sectors(rq);
  5519. if (bfqq == bfqd->in_service_queue && bfq_bfqq_wait_request(bfqq)) {
  5520. bool small_req = bfqq->queued[rq_is_sync(rq)] == 1 &&
  5521. blk_rq_sectors(rq) < 32;
  5522. bool budget_timeout = bfq_bfqq_budget_timeout(bfqq);
  5523. /*
  5524. * There is just this request queued: if
  5525. * - the request is small, and
  5526. * - we are idling to boost throughput, and
  5527. * - the queue is not to be expired,
  5528. * then just exit.
  5529. *
  5530. * In this way, if the device is being idled to wait
  5531. * for a new request from the in-service queue, we
  5532. * avoid unplugging the device and committing the
  5533. * device to serve just a small request. In contrast
  5534. * we wait for the block layer to decide when to
  5535. * unplug the device: hopefully, new requests will be
  5536. * merged to this one quickly, then the device will be
  5537. * unplugged and larger requests will be dispatched.
  5538. */
  5539. if (small_req && idling_boosts_thr_without_issues(bfqd, bfqq) &&
  5540. !budget_timeout)
  5541. return;
  5542. /*
  5543. * A large enough request arrived, or idling is being
  5544. * performed to preserve service guarantees, or
  5545. * finally the queue is to be expired: in all these
  5546. * cases disk idling is to be stopped, so clear
  5547. * wait_request flag and reset timer.
  5548. */
  5549. bfq_clear_bfqq_wait_request(bfqq);
  5550. hrtimer_try_to_cancel(&bfqd->idle_slice_timer);
  5551. /*
  5552. * The queue is not empty, because a new request just
  5553. * arrived. Hence we can safely expire the queue, in
  5554. * case of budget timeout, without risking that the
  5555. * timestamps of the queue are not updated correctly.
  5556. * See [1] for more details.
  5557. */
  5558. if (budget_timeout)
  5559. bfq_bfqq_expire(bfqd, bfqq, false,
  5560. BFQQE_BUDGET_TIMEOUT);
  5561. }
  5562. }
  5563. static void bfqq_request_allocated(struct bfq_queue *bfqq)
  5564. {
  5565. struct bfq_entity *entity = &bfqq->entity;
  5566. for_each_entity(entity)
  5567. entity->allocated++;
  5568. }
  5569. static void bfqq_request_freed(struct bfq_queue *bfqq)
  5570. {
  5571. struct bfq_entity *entity = &bfqq->entity;
  5572. for_each_entity(entity)
  5573. entity->allocated--;
  5574. }
  5575. /* returns true if it causes the idle timer to be disabled */
  5576. static bool __bfq_insert_request(struct bfq_data *bfqd, struct request *rq)
  5577. {
  5578. struct bfq_queue *bfqq = RQ_BFQQ(rq),
  5579. *new_bfqq = bfq_setup_cooperator(bfqd, bfqq, rq, true,
  5580. RQ_BIC(rq));
  5581. bool waiting, idle_timer_disabled = false;
  5582. if (new_bfqq) {
  5583. struct bfq_queue *old_bfqq = bfqq;
  5584. /*
  5585. * Release the request's reference to the old bfqq
  5586. * and make sure one is taken to the shared queue.
  5587. */
  5588. bfqq_request_allocated(new_bfqq);
  5589. bfqq_request_freed(bfqq);
  5590. new_bfqq->ref++;
  5591. /*
  5592. * If the bic associated with the process
  5593. * issuing this request still points to bfqq
  5594. * (and thus has not been already redirected
  5595. * to new_bfqq or even some other bfq_queue),
  5596. * then complete the merge and redirect it to
  5597. * new_bfqq.
  5598. */
  5599. if (bic_to_bfqq(RQ_BIC(rq), true,
  5600. bfq_actuator_index(bfqd, rq->bio)) == bfqq) {
  5601. while (bfqq != new_bfqq)
  5602. bfqq = bfq_merge_bfqqs(bfqd, RQ_BIC(rq), bfqq);
  5603. }
  5604. bfq_clear_bfqq_just_created(old_bfqq);
  5605. /*
  5606. * rq is about to be enqueued into new_bfqq,
  5607. * release rq reference on bfqq
  5608. */
  5609. bfq_put_queue(old_bfqq);
  5610. rq->elv.priv[1] = new_bfqq;
  5611. }
  5612. bfq_update_io_thinktime(bfqd, bfqq);
  5613. bfq_update_has_short_ttime(bfqd, bfqq, RQ_BIC(rq));
  5614. bfq_update_io_seektime(bfqd, bfqq, rq);
  5615. waiting = bfqq && bfq_bfqq_wait_request(bfqq);
  5616. bfq_add_request(rq);
  5617. idle_timer_disabled = waiting && !bfq_bfqq_wait_request(bfqq);
  5618. rq->fifo_time = blk_time_get_ns() + bfqd->bfq_fifo_expire[rq_is_sync(rq)];
  5619. list_add_tail(&rq->queuelist, &bfqq->fifo);
  5620. bfq_rq_enqueued(bfqd, bfqq, rq);
  5621. return idle_timer_disabled;
  5622. }
  5623. #ifdef CONFIG_BFQ_CGROUP_DEBUG
  5624. static void bfq_update_insert_stats(struct request_queue *q,
  5625. struct bfq_queue *bfqq,
  5626. bool idle_timer_disabled,
  5627. blk_opf_t cmd_flags)
  5628. {
  5629. if (!bfqq)
  5630. return;
  5631. /*
  5632. * bfqq still exists, because it can disappear only after
  5633. * either it is merged with another queue, or the process it
  5634. * is associated with exits. But both actions must be taken by
  5635. * the same process currently executing this flow of
  5636. * instructions.
  5637. *
  5638. * In addition, the following queue lock guarantees that
  5639. * bfqq_group(bfqq) exists as well.
  5640. */
  5641. spin_lock_irq(&q->queue_lock);
  5642. bfqg_stats_update_io_add(bfqq_group(bfqq), bfqq, cmd_flags);
  5643. if (idle_timer_disabled)
  5644. bfqg_stats_update_idle_time(bfqq_group(bfqq));
  5645. spin_unlock_irq(&q->queue_lock);
  5646. }
  5647. #else
  5648. static inline void bfq_update_insert_stats(struct request_queue *q,
  5649. struct bfq_queue *bfqq,
  5650. bool idle_timer_disabled,
  5651. blk_opf_t cmd_flags) {}
  5652. #endif /* CONFIG_BFQ_CGROUP_DEBUG */
  5653. static struct bfq_queue *bfq_init_rq(struct request *rq);
  5654. static void bfq_insert_request(struct blk_mq_hw_ctx *hctx, struct request *rq,
  5655. blk_insert_t flags)
  5656. {
  5657. struct request_queue *q = hctx->queue;
  5658. struct bfq_data *bfqd = q->elevator->elevator_data;
  5659. struct bfq_queue *bfqq;
  5660. bool idle_timer_disabled = false;
  5661. blk_opf_t cmd_flags;
  5662. LIST_HEAD(free);
  5663. #ifdef CONFIG_BFQ_GROUP_IOSCHED
  5664. if (!cgroup_subsys_on_dfl(io_cgrp_subsys) && rq->bio)
  5665. bfqg_stats_update_legacy_io(q, rq);
  5666. #endif
  5667. spin_lock_irq(&bfqd->lock);
  5668. bfqq = bfq_init_rq(rq);
  5669. if (blk_mq_sched_try_insert_merge(q, rq, &free)) {
  5670. spin_unlock_irq(&bfqd->lock);
  5671. blk_mq_free_requests(&free);
  5672. return;
  5673. }
  5674. trace_block_rq_insert(rq);
  5675. if (flags & BLK_MQ_INSERT_AT_HEAD) {
  5676. list_add(&rq->queuelist, &bfqd->dispatch);
  5677. } else if (!bfqq) {
  5678. list_add_tail(&rq->queuelist, &bfqd->dispatch);
  5679. } else {
  5680. idle_timer_disabled = __bfq_insert_request(bfqd, rq);
  5681. /*
  5682. * Update bfqq, because, if a queue merge has occurred
  5683. * in __bfq_insert_request, then rq has been
  5684. * redirected into a new queue.
  5685. */
  5686. bfqq = RQ_BFQQ(rq);
  5687. if (rq_mergeable(rq)) {
  5688. elv_rqhash_add(q, rq);
  5689. if (!q->last_merge)
  5690. q->last_merge = rq;
  5691. }
  5692. }
  5693. /*
  5694. * Cache cmd_flags before releasing scheduler lock, because rq
  5695. * may disappear afterwards (for example, because of a request
  5696. * merge).
  5697. */
  5698. cmd_flags = rq->cmd_flags;
  5699. spin_unlock_irq(&bfqd->lock);
  5700. bfq_update_insert_stats(q, bfqq, idle_timer_disabled,
  5701. cmd_flags);
  5702. }
  5703. static void bfq_insert_requests(struct blk_mq_hw_ctx *hctx,
  5704. struct list_head *list,
  5705. blk_insert_t flags)
  5706. {
  5707. while (!list_empty(list)) {
  5708. struct request *rq;
  5709. rq = list_first_entry(list, struct request, queuelist);
  5710. list_del_init(&rq->queuelist);
  5711. bfq_insert_request(hctx, rq, flags);
  5712. }
  5713. }
  5714. static void bfq_update_hw_tag(struct bfq_data *bfqd)
  5715. {
  5716. struct bfq_queue *bfqq = bfqd->in_service_queue;
  5717. bfqd->max_rq_in_driver = max_t(int, bfqd->max_rq_in_driver,
  5718. bfqd->tot_rq_in_driver);
  5719. if (bfqd->hw_tag == 1)
  5720. return;
  5721. /*
  5722. * This sample is valid if the number of outstanding requests
  5723. * is large enough to allow a queueing behavior. Note that the
  5724. * sum is not exact, as it's not taking into account deactivated
  5725. * requests.
  5726. */
  5727. if (bfqd->tot_rq_in_driver + bfqd->queued <= BFQ_HW_QUEUE_THRESHOLD)
  5728. return;
  5729. /*
  5730. * If active queue hasn't enough requests and can idle, bfq might not
  5731. * dispatch sufficient requests to hardware. Don't zero hw_tag in this
  5732. * case
  5733. */
  5734. if (bfqq && bfq_bfqq_has_short_ttime(bfqq) &&
  5735. bfqq->dispatched + bfqq->queued[0] + bfqq->queued[1] <
  5736. BFQ_HW_QUEUE_THRESHOLD &&
  5737. bfqd->tot_rq_in_driver < BFQ_HW_QUEUE_THRESHOLD)
  5738. return;
  5739. if (bfqd->hw_tag_samples++ < BFQ_HW_QUEUE_SAMPLES)
  5740. return;
  5741. bfqd->hw_tag = bfqd->max_rq_in_driver > BFQ_HW_QUEUE_THRESHOLD;
  5742. bfqd->max_rq_in_driver = 0;
  5743. bfqd->hw_tag_samples = 0;
  5744. bfqd->nonrot_with_queueing =
  5745. !blk_queue_rot(bfqd->queue) && bfqd->hw_tag;
  5746. }
  5747. static void bfq_completed_request(struct bfq_queue *bfqq, struct bfq_data *bfqd)
  5748. {
  5749. u64 now_ns;
  5750. u32 delta_us;
  5751. bfq_update_hw_tag(bfqd);
  5752. bfqd->rq_in_driver[bfqq->actuator_idx]--;
  5753. bfqd->tot_rq_in_driver--;
  5754. bfqq->dispatched--;
  5755. if (!bfqq->dispatched && !bfq_bfqq_busy(bfqq)) {
  5756. /*
  5757. * Set budget_timeout (which we overload to store the
  5758. * time at which the queue remains with no backlog and
  5759. * no outstanding request; used by the weight-raising
  5760. * mechanism).
  5761. */
  5762. bfqq->budget_timeout = jiffies;
  5763. bfq_del_bfqq_in_groups_with_pending_reqs(bfqq);
  5764. bfq_weights_tree_remove(bfqq);
  5765. }
  5766. now_ns = blk_time_get_ns();
  5767. bfqq->ttime.last_end_request = now_ns;
  5768. /*
  5769. * Using us instead of ns, to get a reasonable precision in
  5770. * computing rate in next check.
  5771. */
  5772. delta_us = div_u64(now_ns - bfqd->last_completion, NSEC_PER_USEC);
  5773. /*
  5774. * If the request took rather long to complete, and, according
  5775. * to the maximum request size recorded, this completion latency
  5776. * implies that the request was certainly served at a very low
  5777. * rate (less than 1M sectors/sec), then the whole observation
  5778. * interval that lasts up to this time instant cannot be a
  5779. * valid time interval for computing a new peak rate. Invoke
  5780. * bfq_update_rate_reset to have the following three steps
  5781. * taken:
  5782. * - close the observation interval at the last (previous)
  5783. * request dispatch or completion
  5784. * - compute rate, if possible, for that observation interval
  5785. * - reset to zero samples, which will trigger a proper
  5786. * re-initialization of the observation interval on next
  5787. * dispatch
  5788. */
  5789. if (delta_us > BFQ_MIN_TT/NSEC_PER_USEC &&
  5790. (bfqd->last_rq_max_size<<BFQ_RATE_SHIFT)/delta_us <
  5791. 1UL<<(BFQ_RATE_SHIFT - 10))
  5792. bfq_update_rate_reset(bfqd, NULL);
  5793. bfqd->last_completion = now_ns;
  5794. /*
  5795. * Shared queues are likely to receive I/O at a high
  5796. * rate. This may deceptively let them be considered as wakers
  5797. * of other queues. But a false waker will unjustly steal
  5798. * bandwidth to its supposedly woken queue. So considering
  5799. * also shared queues in the waking mechanism may cause more
  5800. * control troubles than throughput benefits. Then reset
  5801. * last_completed_rq_bfqq if bfqq is a shared queue.
  5802. */
  5803. if (!bfq_bfqq_coop(bfqq))
  5804. bfqd->last_completed_rq_bfqq = bfqq;
  5805. else
  5806. bfqd->last_completed_rq_bfqq = NULL;
  5807. /*
  5808. * If we are waiting to discover whether the request pattern
  5809. * of the task associated with the queue is actually
  5810. * isochronous, and both requisites for this condition to hold
  5811. * are now satisfied, then compute soft_rt_next_start (see the
  5812. * comments on the function bfq_bfqq_softrt_next_start()). We
  5813. * do not compute soft_rt_next_start if bfqq is in interactive
  5814. * weight raising (see the comments in bfq_bfqq_expire() for
  5815. * an explanation). We schedule this delayed update when bfqq
  5816. * expires, if it still has in-flight requests.
  5817. */
  5818. if (bfq_bfqq_softrt_update(bfqq) && bfqq->dispatched == 0 &&
  5819. RB_EMPTY_ROOT(&bfqq->sort_list) &&
  5820. bfqq->wr_coeff != bfqd->bfq_wr_coeff)
  5821. bfqq->soft_rt_next_start =
  5822. bfq_bfqq_softrt_next_start(bfqd, bfqq);
  5823. /*
  5824. * If this is the in-service queue, check if it needs to be expired,
  5825. * or if we want to idle in case it has no pending requests.
  5826. */
  5827. if (bfqd->in_service_queue == bfqq) {
  5828. if (bfq_bfqq_must_idle(bfqq)) {
  5829. if (bfqq->dispatched == 0)
  5830. bfq_arm_slice_timer(bfqd);
  5831. /*
  5832. * If we get here, we do not expire bfqq, even
  5833. * if bfqq was in budget timeout or had no
  5834. * more requests (as controlled in the next
  5835. * conditional instructions). The reason for
  5836. * not expiring bfqq is as follows.
  5837. *
  5838. * Here bfqq->dispatched > 0 holds, but
  5839. * bfq_bfqq_must_idle() returned true. This
  5840. * implies that, even if no request arrives
  5841. * for bfqq before bfqq->dispatched reaches 0,
  5842. * bfqq will, however, not be expired on the
  5843. * completion event that causes bfqq->dispatch
  5844. * to reach zero. In contrast, on this event,
  5845. * bfqq will start enjoying device idling
  5846. * (I/O-dispatch plugging).
  5847. *
  5848. * But, if we expired bfqq here, bfqq would
  5849. * not have the chance to enjoy device idling
  5850. * when bfqq->dispatched finally reaches
  5851. * zero. This would expose bfqq to violation
  5852. * of its reserved service guarantees.
  5853. */
  5854. return;
  5855. } else if (bfq_may_expire_for_budg_timeout(bfqq))
  5856. bfq_bfqq_expire(bfqd, bfqq, false,
  5857. BFQQE_BUDGET_TIMEOUT);
  5858. else if (RB_EMPTY_ROOT(&bfqq->sort_list) &&
  5859. (bfqq->dispatched == 0 ||
  5860. !bfq_better_to_idle(bfqq)))
  5861. bfq_bfqq_expire(bfqd, bfqq, false,
  5862. BFQQE_NO_MORE_REQUESTS);
  5863. }
  5864. if (!bfqd->tot_rq_in_driver)
  5865. bfq_schedule_dispatch(bfqd);
  5866. }
  5867. /*
  5868. * The processes associated with bfqq may happen to generate their
  5869. * cumulative I/O at a lower rate than the rate at which the device
  5870. * could serve the same I/O. This is rather probable, e.g., if only
  5871. * one process is associated with bfqq and the device is an SSD. It
  5872. * results in bfqq becoming often empty while in service. In this
  5873. * respect, if BFQ is allowed to switch to another queue when bfqq
  5874. * remains empty, then the device goes on being fed with I/O requests,
  5875. * and the throughput is not affected. In contrast, if BFQ is not
  5876. * allowed to switch to another queue---because bfqq is sync and
  5877. * I/O-dispatch needs to be plugged while bfqq is temporarily
  5878. * empty---then, during the service of bfqq, there will be frequent
  5879. * "service holes", i.e., time intervals during which bfqq gets empty
  5880. * and the device can only consume the I/O already queued in its
  5881. * hardware queues. During service holes, the device may even get to
  5882. * remaining idle. In the end, during the service of bfqq, the device
  5883. * is driven at a lower speed than the one it can reach with the kind
  5884. * of I/O flowing through bfqq.
  5885. *
  5886. * To counter this loss of throughput, BFQ implements a "request
  5887. * injection mechanism", which tries to fill the above service holes
  5888. * with I/O requests taken from other queues. The hard part in this
  5889. * mechanism is finding the right amount of I/O to inject, so as to
  5890. * both boost throughput and not break bfqq's bandwidth and latency
  5891. * guarantees. In this respect, the mechanism maintains a per-queue
  5892. * inject limit, computed as below. While bfqq is empty, the injection
  5893. * mechanism dispatches extra I/O requests only until the total number
  5894. * of I/O requests in flight---i.e., already dispatched but not yet
  5895. * completed---remains lower than this limit.
  5896. *
  5897. * A first definition comes in handy to introduce the algorithm by
  5898. * which the inject limit is computed. We define as first request for
  5899. * bfqq, an I/O request for bfqq that arrives while bfqq is in
  5900. * service, and causes bfqq to switch from empty to non-empty. The
  5901. * algorithm updates the limit as a function of the effect of
  5902. * injection on the service times of only the first requests of
  5903. * bfqq. The reason for this restriction is that these are the
  5904. * requests whose service time is affected most, because they are the
  5905. * first to arrive after injection possibly occurred.
  5906. *
  5907. * To evaluate the effect of injection, the algorithm measures the
  5908. * "total service time" of first requests. We define as total service
  5909. * time of an I/O request, the time that elapses since when the
  5910. * request is enqueued into bfqq, to when it is completed. This
  5911. * quantity allows the whole effect of injection to be measured. It is
  5912. * easy to see why. Suppose that some requests of other queues are
  5913. * actually injected while bfqq is empty, and that a new request R
  5914. * then arrives for bfqq. If the device does start to serve all or
  5915. * part of the injected requests during the service hole, then,
  5916. * because of this extra service, it may delay the next invocation of
  5917. * the dispatch hook of BFQ. Then, even after R gets eventually
  5918. * dispatched, the device may delay the actual service of R if it is
  5919. * still busy serving the extra requests, or if it decides to serve,
  5920. * before R, some extra request still present in its queues. As a
  5921. * conclusion, the cumulative extra delay caused by injection can be
  5922. * easily evaluated by just comparing the total service time of first
  5923. * requests with and without injection.
  5924. *
  5925. * The limit-update algorithm works as follows. On the arrival of a
  5926. * first request of bfqq, the algorithm measures the total time of the
  5927. * request only if one of the three cases below holds, and, for each
  5928. * case, it updates the limit as described below:
  5929. *
  5930. * (1) If there is no in-flight request. This gives a baseline for the
  5931. * total service time of the requests of bfqq. If the baseline has
  5932. * not been computed yet, then, after computing it, the limit is
  5933. * set to 1, to start boosting throughput, and to prepare the
  5934. * ground for the next case. If the baseline has already been
  5935. * computed, then it is updated, in case it results to be lower
  5936. * than the previous value.
  5937. *
  5938. * (2) If the limit is higher than 0 and there are in-flight
  5939. * requests. By comparing the total service time in this case with
  5940. * the above baseline, it is possible to know at which extent the
  5941. * current value of the limit is inflating the total service
  5942. * time. If the inflation is below a certain threshold, then bfqq
  5943. * is assumed to be suffering from no perceivable loss of its
  5944. * service guarantees, and the limit is even tentatively
  5945. * increased. If the inflation is above the threshold, then the
  5946. * limit is decreased. Due to the lack of any hysteresis, this
  5947. * logic makes the limit oscillate even in steady workload
  5948. * conditions. Yet we opted for it, because it is fast in reaching
  5949. * the best value for the limit, as a function of the current I/O
  5950. * workload. To reduce oscillations, this step is disabled for a
  5951. * short time interval after the limit happens to be decreased.
  5952. *
  5953. * (3) Periodically, after resetting the limit, to make sure that the
  5954. * limit eventually drops in case the workload changes. This is
  5955. * needed because, after the limit has gone safely up for a
  5956. * certain workload, it is impossible to guess whether the
  5957. * baseline total service time may have changed, without measuring
  5958. * it again without injection. A more effective version of this
  5959. * step might be to just sample the baseline, by interrupting
  5960. * injection only once, and then to reset/lower the limit only if
  5961. * the total service time with the current limit does happen to be
  5962. * too large.
  5963. *
  5964. * More details on each step are provided in the comments on the
  5965. * pieces of code that implement these steps: the branch handling the
  5966. * transition from empty to non empty in bfq_add_request(), the branch
  5967. * handling injection in bfq_select_queue(), and the function
  5968. * bfq_choose_bfqq_for_injection(). These comments also explain some
  5969. * exceptions, made by the injection mechanism in some special cases.
  5970. */
  5971. static void bfq_update_inject_limit(struct bfq_data *bfqd,
  5972. struct bfq_queue *bfqq)
  5973. {
  5974. u64 tot_time_ns = blk_time_get_ns() - bfqd->last_empty_occupied_ns;
  5975. unsigned int old_limit = bfqq->inject_limit;
  5976. if (bfqq->last_serv_time_ns > 0 && bfqd->rqs_injected) {
  5977. u64 threshold = (bfqq->last_serv_time_ns * 3)>>1;
  5978. if (tot_time_ns >= threshold && old_limit > 0) {
  5979. bfqq->inject_limit--;
  5980. bfqq->decrease_time_jif = jiffies;
  5981. } else if (tot_time_ns < threshold &&
  5982. old_limit <= bfqd->max_rq_in_driver)
  5983. bfqq->inject_limit++;
  5984. }
  5985. /*
  5986. * Either we still have to compute the base value for the
  5987. * total service time, and there seem to be the right
  5988. * conditions to do it, or we can lower the last base value
  5989. * computed.
  5990. *
  5991. * NOTE: (bfqd->tot_rq_in_driver == 1) means that there is no I/O
  5992. * request in flight, because this function is in the code
  5993. * path that handles the completion of a request of bfqq, and,
  5994. * in particular, this function is executed before
  5995. * bfqd->tot_rq_in_driver is decremented in such a code path.
  5996. */
  5997. if ((bfqq->last_serv_time_ns == 0 && bfqd->tot_rq_in_driver == 1) ||
  5998. tot_time_ns < bfqq->last_serv_time_ns) {
  5999. if (bfqq->last_serv_time_ns == 0) {
  6000. /*
  6001. * Now we certainly have a base value: make sure we
  6002. * start trying injection.
  6003. */
  6004. bfqq->inject_limit = max_t(unsigned int, 1, old_limit);
  6005. }
  6006. bfqq->last_serv_time_ns = tot_time_ns;
  6007. } else if (!bfqd->rqs_injected && bfqd->tot_rq_in_driver == 1)
  6008. /*
  6009. * No I/O injected and no request still in service in
  6010. * the drive: these are the exact conditions for
  6011. * computing the base value of the total service time
  6012. * for bfqq. So let's update this value, because it is
  6013. * rather variable. For example, it varies if the size
  6014. * or the spatial locality of the I/O requests in bfqq
  6015. * change.
  6016. */
  6017. bfqq->last_serv_time_ns = tot_time_ns;
  6018. /* update complete, not waiting for any request completion any longer */
  6019. bfqd->waited_rq = NULL;
  6020. bfqd->rqs_injected = false;
  6021. }
  6022. /*
  6023. * Handle either a requeue or a finish for rq. The things to do are
  6024. * the same in both cases: all references to rq are to be dropped. In
  6025. * particular, rq is considered completed from the point of view of
  6026. * the scheduler.
  6027. */
  6028. static void bfq_finish_requeue_request(struct request *rq)
  6029. {
  6030. struct bfq_queue *bfqq = RQ_BFQQ(rq);
  6031. struct bfq_data *bfqd;
  6032. unsigned long flags;
  6033. /*
  6034. * rq either is not associated with any icq, or is an already
  6035. * requeued request that has not (yet) been re-inserted into
  6036. * a bfq_queue.
  6037. */
  6038. if (!rq->elv.icq || !bfqq)
  6039. return;
  6040. bfqd = bfqq->bfqd;
  6041. if (rq->rq_flags & RQF_STARTED)
  6042. bfqg_stats_update_completion(bfqq_group(bfqq),
  6043. rq->start_time_ns,
  6044. rq->io_start_time_ns,
  6045. rq->cmd_flags);
  6046. spin_lock_irqsave(&bfqd->lock, flags);
  6047. if (likely(rq->rq_flags & RQF_STARTED)) {
  6048. if (rq == bfqd->waited_rq)
  6049. bfq_update_inject_limit(bfqd, bfqq);
  6050. bfq_completed_request(bfqq, bfqd);
  6051. }
  6052. bfqq_request_freed(bfqq);
  6053. bfq_put_queue(bfqq);
  6054. RQ_BIC(rq)->requests--;
  6055. spin_unlock_irqrestore(&bfqd->lock, flags);
  6056. /*
  6057. * Reset private fields. In case of a requeue, this allows
  6058. * this function to correctly do nothing if it is spuriously
  6059. * invoked again on this same request (see the check at the
  6060. * beginning of the function). Probably, a better general
  6061. * design would be to prevent blk-mq from invoking the requeue
  6062. * or finish hooks of an elevator, for a request that is not
  6063. * referred by that elevator.
  6064. *
  6065. * Resetting the following fields would break the
  6066. * request-insertion logic if rq is re-inserted into a bfq
  6067. * internal queue, without a re-preparation. Here we assume
  6068. * that re-insertions of requeued requests, without
  6069. * re-preparation, can happen only for pass_through or at_head
  6070. * requests (which are not re-inserted into bfq internal
  6071. * queues).
  6072. */
  6073. rq->elv.priv[0] = NULL;
  6074. rq->elv.priv[1] = NULL;
  6075. }
  6076. static void bfq_finish_request(struct request *rq)
  6077. {
  6078. bfq_finish_requeue_request(rq);
  6079. if (rq->elv.icq) {
  6080. put_io_context(rq->elv.icq->ioc);
  6081. rq->elv.icq = NULL;
  6082. }
  6083. }
  6084. /*
  6085. * Removes the association between the current task and bfqq, assuming
  6086. * that bic points to the bfq iocontext of the task.
  6087. * Returns NULL if a new bfqq should be allocated, or the old bfqq if this
  6088. * was the last process referring to that bfqq.
  6089. */
  6090. static struct bfq_queue *
  6091. bfq_split_bfqq(struct bfq_io_cq *bic, struct bfq_queue *bfqq)
  6092. {
  6093. bfq_log_bfqq(bfqq->bfqd, bfqq, "splitting queue");
  6094. if (bfqq_process_refs(bfqq) == 1 && !bfqq->new_bfqq) {
  6095. bfqq->pid = current->pid;
  6096. bfq_clear_bfqq_coop(bfqq);
  6097. bfq_clear_bfqq_split_coop(bfqq);
  6098. return bfqq;
  6099. }
  6100. bic_set_bfqq(bic, NULL, true, bfqq->actuator_idx);
  6101. bfq_put_cooperator(bfqq);
  6102. bfq_release_process_ref(bfqq->bfqd, bfqq);
  6103. return NULL;
  6104. }
  6105. static struct bfq_queue *
  6106. __bfq_get_bfqq_handle_split(struct bfq_data *bfqd, struct bfq_io_cq *bic,
  6107. struct bio *bio, bool split, bool is_sync,
  6108. bool *new_queue)
  6109. {
  6110. unsigned int act_idx = bfq_actuator_index(bfqd, bio);
  6111. struct bfq_queue *bfqq = bic_to_bfqq(bic, is_sync, act_idx);
  6112. struct bfq_iocq_bfqq_data *bfqq_data = &bic->bfqq_data[act_idx];
  6113. if (likely(bfqq && bfqq != &bfqd->oom_bfqq))
  6114. return bfqq;
  6115. if (new_queue)
  6116. *new_queue = true;
  6117. if (bfqq)
  6118. bfq_put_queue(bfqq);
  6119. bfqq = bfq_get_queue(bfqd, bio, is_sync, bic, split);
  6120. bic_set_bfqq(bic, bfqq, is_sync, act_idx);
  6121. if (split && is_sync) {
  6122. if ((bfqq_data->was_in_burst_list && bfqd->large_burst) ||
  6123. bfqq_data->saved_in_large_burst)
  6124. bfq_mark_bfqq_in_large_burst(bfqq);
  6125. else {
  6126. bfq_clear_bfqq_in_large_burst(bfqq);
  6127. if (bfqq_data->was_in_burst_list)
  6128. /*
  6129. * If bfqq was in the current
  6130. * burst list before being
  6131. * merged, then we have to add
  6132. * it back. And we do not need
  6133. * to increase burst_size, as
  6134. * we did not decrement
  6135. * burst_size when we removed
  6136. * bfqq from the burst list as
  6137. * a consequence of a merge
  6138. * (see comments in
  6139. * bfq_put_queue). In this
  6140. * respect, it would be rather
  6141. * costly to know whether the
  6142. * current burst list is still
  6143. * the same burst list from
  6144. * which bfqq was removed on
  6145. * the merge. To avoid this
  6146. * cost, if bfqq was in a
  6147. * burst list, then we add
  6148. * bfqq to the current burst
  6149. * list without any further
  6150. * check. This can cause
  6151. * inappropriate insertions,
  6152. * but rarely enough to not
  6153. * harm the detection of large
  6154. * bursts significantly.
  6155. */
  6156. hlist_add_head(&bfqq->burst_list_node,
  6157. &bfqd->burst_list);
  6158. }
  6159. bfqq->split_time = jiffies;
  6160. }
  6161. return bfqq;
  6162. }
  6163. /*
  6164. * Only reset private fields. The actual request preparation will be
  6165. * performed by bfq_init_rq, when rq is either inserted or merged. See
  6166. * comments on bfq_init_rq for the reason behind this delayed
  6167. * preparation.
  6168. */
  6169. static void bfq_prepare_request(struct request *rq)
  6170. {
  6171. rq->elv.icq = ioc_find_get_icq(rq->q);
  6172. /*
  6173. * Regardless of whether we have an icq attached, we have to
  6174. * clear the scheduler pointers, as they might point to
  6175. * previously allocated bic/bfqq structs.
  6176. */
  6177. rq->elv.priv[0] = rq->elv.priv[1] = NULL;
  6178. }
  6179. static struct bfq_queue *bfq_waker_bfqq(struct bfq_queue *bfqq)
  6180. {
  6181. struct bfq_queue *new_bfqq = bfqq->new_bfqq;
  6182. struct bfq_queue *waker_bfqq = bfqq->waker_bfqq;
  6183. if (!waker_bfqq)
  6184. return NULL;
  6185. while (new_bfqq) {
  6186. if (new_bfqq == waker_bfqq) {
  6187. /*
  6188. * If waker_bfqq is in the merge chain, and current
  6189. * is the only process, waker_bfqq can be freed.
  6190. */
  6191. if (bfqq_process_refs(waker_bfqq) == 1)
  6192. return NULL;
  6193. return waker_bfqq;
  6194. }
  6195. new_bfqq = new_bfqq->new_bfqq;
  6196. }
  6197. /*
  6198. * If waker_bfqq is not in the merge chain, and it's procress reference
  6199. * is 0, waker_bfqq can be freed.
  6200. */
  6201. if (bfqq_process_refs(waker_bfqq) == 0)
  6202. return NULL;
  6203. return waker_bfqq;
  6204. }
  6205. static struct bfq_queue *bfq_get_bfqq_handle_split(struct bfq_data *bfqd,
  6206. struct bfq_io_cq *bic,
  6207. struct bio *bio,
  6208. unsigned int idx,
  6209. bool is_sync)
  6210. {
  6211. struct bfq_queue *waker_bfqq;
  6212. struct bfq_queue *bfqq;
  6213. bool new_queue = false;
  6214. bfqq = __bfq_get_bfqq_handle_split(bfqd, bic, bio, false, is_sync,
  6215. &new_queue);
  6216. if (unlikely(new_queue))
  6217. return bfqq;
  6218. /* If the queue was seeky for too long, break it apart. */
  6219. if (!bfq_bfqq_coop(bfqq) || !bfq_bfqq_split_coop(bfqq) ||
  6220. bic->bfqq_data[idx].stably_merged)
  6221. return bfqq;
  6222. waker_bfqq = bfq_waker_bfqq(bfqq);
  6223. /* Update bic before losing reference to bfqq */
  6224. if (bfq_bfqq_in_large_burst(bfqq))
  6225. bic->bfqq_data[idx].saved_in_large_burst = true;
  6226. bfqq = bfq_split_bfqq(bic, bfqq);
  6227. if (bfqq) {
  6228. bfq_bfqq_resume_state(bfqq, bfqd, bic, true);
  6229. return bfqq;
  6230. }
  6231. bfqq = __bfq_get_bfqq_handle_split(bfqd, bic, bio, true, is_sync, NULL);
  6232. if (unlikely(bfqq == &bfqd->oom_bfqq))
  6233. return bfqq;
  6234. bfq_bfqq_resume_state(bfqq, bfqd, bic, false);
  6235. bfqq->waker_bfqq = waker_bfqq;
  6236. bfqq->tentative_waker_bfqq = NULL;
  6237. /*
  6238. * If the waker queue disappears, then new_bfqq->waker_bfqq must be
  6239. * reset. So insert new_bfqq into the
  6240. * woken_list of the waker. See
  6241. * bfq_check_waker for details.
  6242. */
  6243. if (waker_bfqq)
  6244. hlist_add_head(&bfqq->woken_list_node,
  6245. &bfqq->waker_bfqq->woken_list);
  6246. return bfqq;
  6247. }
  6248. /*
  6249. * If needed, init rq, allocate bfq data structures associated with
  6250. * rq, and increment reference counters in the destination bfq_queue
  6251. * for rq. Return the destination bfq_queue for rq, or NULL is rq is
  6252. * not associated with any bfq_queue.
  6253. *
  6254. * This function is invoked by the functions that perform rq insertion
  6255. * or merging. One may have expected the above preparation operations
  6256. * to be performed in bfq_prepare_request, and not delayed to when rq
  6257. * is inserted or merged. The rationale behind this delayed
  6258. * preparation is that, after the prepare_request hook is invoked for
  6259. * rq, rq may still be transformed into a request with no icq, i.e., a
  6260. * request not associated with any queue. No bfq hook is invoked to
  6261. * signal this transformation. As a consequence, should these
  6262. * preparation operations be performed when the prepare_request hook
  6263. * is invoked, and should rq be transformed one moment later, bfq
  6264. * would end up in an inconsistent state, because it would have
  6265. * incremented some queue counters for an rq destined to
  6266. * transformation, without any chance to correctly lower these
  6267. * counters back. In contrast, no transformation can still happen for
  6268. * rq after rq has been inserted or merged. So, it is safe to execute
  6269. * these preparation operations when rq is finally inserted or merged.
  6270. */
  6271. static struct bfq_queue *bfq_init_rq(struct request *rq)
  6272. {
  6273. struct request_queue *q = rq->q;
  6274. struct bio *bio = rq->bio;
  6275. struct bfq_data *bfqd = q->elevator->elevator_data;
  6276. struct bfq_io_cq *bic;
  6277. const int is_sync = rq_is_sync(rq);
  6278. struct bfq_queue *bfqq;
  6279. unsigned int a_idx = bfq_actuator_index(bfqd, bio);
  6280. if (unlikely(!rq->elv.icq))
  6281. return NULL;
  6282. /*
  6283. * Assuming that RQ_BFQQ(rq) is set only if everything is set
  6284. * for this rq. This holds true, because this function is
  6285. * invoked only for insertion or merging, and, after such
  6286. * events, a request cannot be manipulated any longer before
  6287. * being removed from bfq.
  6288. */
  6289. if (RQ_BFQQ(rq))
  6290. return RQ_BFQQ(rq);
  6291. bic = icq_to_bic(rq->elv.icq);
  6292. bfq_check_ioprio_change(bic, bio);
  6293. bfq_bic_update_cgroup(bic, bio);
  6294. bfqq = bfq_get_bfqq_handle_split(bfqd, bic, bio, a_idx, is_sync);
  6295. bfqq_request_allocated(bfqq);
  6296. bfqq->ref++;
  6297. bic->requests++;
  6298. bfq_log_bfqq(bfqd, bfqq, "get_request %p: bfqq %p, %d",
  6299. rq, bfqq, bfqq->ref);
  6300. rq->elv.priv[0] = bic;
  6301. rq->elv.priv[1] = bfqq;
  6302. /*
  6303. * If a bfq_queue has only one process reference, it is owned
  6304. * by only this bic: we can then set bfqq->bic = bic. in
  6305. * addition, if the queue has also just been split, we have to
  6306. * resume its state.
  6307. */
  6308. if (likely(bfqq != &bfqd->oom_bfqq) && !bfqq->new_bfqq &&
  6309. bfqq_process_refs(bfqq) == 1)
  6310. bfqq->bic = bic;
  6311. /*
  6312. * Consider bfqq as possibly belonging to a burst of newly
  6313. * created queues only if:
  6314. * 1) A burst is actually happening (bfqd->burst_size > 0)
  6315. * or
  6316. * 2) There is no other active queue. In fact, if, in
  6317. * contrast, there are active queues not belonging to the
  6318. * possible burst bfqq may belong to, then there is no gain
  6319. * in considering bfqq as belonging to a burst, and
  6320. * therefore in not weight-raising bfqq. See comments on
  6321. * bfq_handle_burst().
  6322. *
  6323. * This filtering also helps eliminating false positives,
  6324. * occurring when bfqq does not belong to an actual large
  6325. * burst, but some background task (e.g., a service) happens
  6326. * to trigger the creation of new queues very close to when
  6327. * bfqq and its possible companion queues are created. See
  6328. * comments on bfq_handle_burst() for further details also on
  6329. * this issue.
  6330. */
  6331. if (unlikely(bfq_bfqq_just_created(bfqq) &&
  6332. (bfqd->burst_size > 0 ||
  6333. bfq_tot_busy_queues(bfqd) == 0)))
  6334. bfq_handle_burst(bfqd, bfqq);
  6335. return bfqq;
  6336. }
  6337. static void
  6338. bfq_idle_slice_timer_body(struct bfq_data *bfqd, struct bfq_queue *bfqq)
  6339. {
  6340. enum bfqq_expiration reason;
  6341. unsigned long flags;
  6342. spin_lock_irqsave(&bfqd->lock, flags);
  6343. /*
  6344. * Considering that bfqq may be in race, we should firstly check
  6345. * whether bfqq is in service before doing something on it. If
  6346. * the bfqq in race is not in service, it has already been expired
  6347. * through __bfq_bfqq_expire func and its wait_request flags has
  6348. * been cleared in __bfq_bfqd_reset_in_service func.
  6349. */
  6350. if (bfqq != bfqd->in_service_queue) {
  6351. spin_unlock_irqrestore(&bfqd->lock, flags);
  6352. return;
  6353. }
  6354. bfq_clear_bfqq_wait_request(bfqq);
  6355. if (bfq_bfqq_budget_timeout(bfqq))
  6356. /*
  6357. * Also here the queue can be safely expired
  6358. * for budget timeout without wasting
  6359. * guarantees
  6360. */
  6361. reason = BFQQE_BUDGET_TIMEOUT;
  6362. else if (bfqq->queued[0] == 0 && bfqq->queued[1] == 0)
  6363. /*
  6364. * The queue may not be empty upon timer expiration,
  6365. * because we may not disable the timer when the
  6366. * first request of the in-service queue arrives
  6367. * during disk idling.
  6368. */
  6369. reason = BFQQE_TOO_IDLE;
  6370. else
  6371. goto schedule_dispatch;
  6372. bfq_bfqq_expire(bfqd, bfqq, true, reason);
  6373. schedule_dispatch:
  6374. bfq_schedule_dispatch(bfqd);
  6375. spin_unlock_irqrestore(&bfqd->lock, flags);
  6376. }
  6377. /*
  6378. * Handler of the expiration of the timer running if the in-service queue
  6379. * is idling inside its time slice.
  6380. */
  6381. static enum hrtimer_restart bfq_idle_slice_timer(struct hrtimer *timer)
  6382. {
  6383. struct bfq_data *bfqd = container_of(timer, struct bfq_data,
  6384. idle_slice_timer);
  6385. struct bfq_queue *bfqq = bfqd->in_service_queue;
  6386. /*
  6387. * Theoretical race here: the in-service queue can be NULL or
  6388. * different from the queue that was idling if a new request
  6389. * arrives for the current queue and there is a full dispatch
  6390. * cycle that changes the in-service queue. This can hardly
  6391. * happen, but in the worst case we just expire a queue too
  6392. * early.
  6393. */
  6394. if (bfqq)
  6395. bfq_idle_slice_timer_body(bfqd, bfqq);
  6396. return HRTIMER_NORESTART;
  6397. }
  6398. static void __bfq_put_async_bfqq(struct bfq_data *bfqd,
  6399. struct bfq_queue **bfqq_ptr)
  6400. {
  6401. struct bfq_queue *bfqq = *bfqq_ptr;
  6402. bfq_log(bfqd, "put_async_bfqq: %p", bfqq);
  6403. if (bfqq) {
  6404. bfq_bfqq_move(bfqd, bfqq, bfqd->root_group);
  6405. bfq_log_bfqq(bfqd, bfqq, "put_async_bfqq: putting %p, %d",
  6406. bfqq, bfqq->ref);
  6407. bfq_put_queue(bfqq);
  6408. *bfqq_ptr = NULL;
  6409. }
  6410. }
  6411. /*
  6412. * Release all the bfqg references to its async queues. If we are
  6413. * deallocating the group these queues may still contain requests, so
  6414. * we reparent them to the root cgroup (i.e., the only one that will
  6415. * exist for sure until all the requests on a device are gone).
  6416. */
  6417. void bfq_put_async_queues(struct bfq_data *bfqd, struct bfq_group *bfqg)
  6418. {
  6419. int i, j, k;
  6420. for (k = 0; k < bfqd->num_actuators; k++) {
  6421. for (i = 0; i < 2; i++)
  6422. for (j = 0; j < IOPRIO_NR_LEVELS; j++)
  6423. __bfq_put_async_bfqq(bfqd, &bfqg->async_bfqq[i][j][k]);
  6424. __bfq_put_async_bfqq(bfqd, &bfqg->async_idle_bfqq[k]);
  6425. }
  6426. }
  6427. /*
  6428. * See the comments on bfq_limit_depth for the purpose of
  6429. * the depths set in the function. Return minimum shallow depth we'll use.
  6430. */
  6431. static void bfq_depth_updated(struct request_queue *q)
  6432. {
  6433. struct bfq_data *bfqd = q->elevator->elevator_data;
  6434. unsigned int async_depth = q->async_depth;
  6435. /*
  6436. * By default:
  6437. * - sync reads are not limited
  6438. * If bfqq is not being weight-raised:
  6439. * - sync writes are limited to 75%(async depth default value)
  6440. * - async IO are limited to 50%
  6441. * If bfqq is being weight-raised:
  6442. * - sync writes are limited to ~37%
  6443. * - async IO are limited to ~18
  6444. *
  6445. * If request_queue->async_depth is updated by user, all limit are
  6446. * updated relatively.
  6447. */
  6448. bfqd->async_depths[0][1] = async_depth;
  6449. bfqd->async_depths[0][0] = max(async_depth * 2 / 3, 1U);
  6450. bfqd->async_depths[1][1] = max(async_depth >> 1, 1U);
  6451. bfqd->async_depths[1][0] = max(async_depth >> 2, 1U);
  6452. /*
  6453. * Due to cgroup qos, the allowed request for bfqq might be 1
  6454. */
  6455. blk_mq_set_min_shallow_depth(q, 1);
  6456. }
  6457. static void bfq_exit_queue(struct elevator_queue *e)
  6458. {
  6459. struct bfq_data *bfqd = e->elevator_data;
  6460. struct bfq_queue *bfqq, *n;
  6461. unsigned int actuator;
  6462. hrtimer_cancel(&bfqd->idle_slice_timer);
  6463. spin_lock_irq(&bfqd->lock);
  6464. list_for_each_entry_safe(bfqq, n, &bfqd->idle_list, bfqq_list)
  6465. bfq_deactivate_bfqq(bfqd, bfqq, false, false);
  6466. spin_unlock_irq(&bfqd->lock);
  6467. for (actuator = 0; actuator < bfqd->num_actuators; actuator++)
  6468. WARN_ON_ONCE(bfqd->rq_in_driver[actuator]);
  6469. WARN_ON_ONCE(bfqd->tot_rq_in_driver);
  6470. hrtimer_cancel(&bfqd->idle_slice_timer);
  6471. /* release oom-queue reference to root group */
  6472. bfqg_and_blkg_put(bfqd->root_group);
  6473. #ifdef CONFIG_BFQ_GROUP_IOSCHED
  6474. blkcg_deactivate_policy(bfqd->queue->disk, &blkcg_policy_bfq);
  6475. #else
  6476. spin_lock_irq(&bfqd->lock);
  6477. bfq_put_async_queues(bfqd, bfqd->root_group);
  6478. kfree(bfqd->root_group);
  6479. spin_unlock_irq(&bfqd->lock);
  6480. #endif
  6481. blk_stat_disable_accounting(bfqd->queue);
  6482. blk_queue_flag_clear(QUEUE_FLAG_DISABLE_WBT_DEF, bfqd->queue);
  6483. wbt_enable_default(bfqd->queue->disk);
  6484. kfree(bfqd);
  6485. }
  6486. static void bfq_init_root_group(struct bfq_group *root_group,
  6487. struct bfq_data *bfqd)
  6488. {
  6489. int i;
  6490. #ifdef CONFIG_BFQ_GROUP_IOSCHED
  6491. root_group->entity.parent = NULL;
  6492. root_group->my_entity = NULL;
  6493. root_group->bfqd = bfqd;
  6494. #endif
  6495. root_group->rq_pos_tree = RB_ROOT;
  6496. for (i = 0; i < BFQ_IOPRIO_CLASSES; i++)
  6497. root_group->sched_data.service_tree[i] = BFQ_SERVICE_TREE_INIT;
  6498. root_group->sched_data.bfq_class_idle_last_service = jiffies;
  6499. }
  6500. static int bfq_init_queue(struct request_queue *q, struct elevator_queue *eq)
  6501. {
  6502. struct bfq_data *bfqd;
  6503. unsigned int i;
  6504. struct blk_independent_access_ranges *ia_ranges = q->disk->ia_ranges;
  6505. bfqd = kzalloc_node(sizeof(*bfqd), GFP_KERNEL, q->node);
  6506. if (!bfqd)
  6507. return -ENOMEM;
  6508. eq->elevator_data = bfqd;
  6509. spin_lock_irq(&q->queue_lock);
  6510. q->elevator = eq;
  6511. spin_unlock_irq(&q->queue_lock);
  6512. /*
  6513. * Our fallback bfqq if bfq_find_alloc_queue() runs into OOM issues.
  6514. * Grab a permanent reference to it, so that the normal code flow
  6515. * will not attempt to free it.
  6516. * Set zero as actuator index: we will pretend that
  6517. * all I/O requests are for the same actuator.
  6518. */
  6519. bfq_init_bfqq(bfqd, &bfqd->oom_bfqq, NULL, 1, 0, 0);
  6520. bfqd->oom_bfqq.ref++;
  6521. bfqd->oom_bfqq.new_ioprio = BFQ_DEFAULT_QUEUE_IOPRIO;
  6522. bfqd->oom_bfqq.new_ioprio_class = IOPRIO_CLASS_BE;
  6523. bfqd->oom_bfqq.entity.new_weight =
  6524. bfq_ioprio_to_weight(bfqd->oom_bfqq.new_ioprio);
  6525. /* oom_bfqq does not participate to bursts */
  6526. bfq_clear_bfqq_just_created(&bfqd->oom_bfqq);
  6527. /*
  6528. * Trigger weight initialization, according to ioprio, at the
  6529. * oom_bfqq's first activation. The oom_bfqq's ioprio and ioprio
  6530. * class won't be changed any more.
  6531. */
  6532. bfqd->oom_bfqq.entity.prio_changed = 1;
  6533. bfqd->queue = q;
  6534. bfqd->num_actuators = 1;
  6535. /*
  6536. * If the disk supports multiple actuators, copy independent
  6537. * access ranges from the request queue structure.
  6538. */
  6539. spin_lock_irq(&q->queue_lock);
  6540. if (ia_ranges) {
  6541. /*
  6542. * Check if the disk ia_ranges size exceeds the current bfq
  6543. * actuator limit.
  6544. */
  6545. if (ia_ranges->nr_ia_ranges > BFQ_MAX_ACTUATORS) {
  6546. pr_crit("nr_ia_ranges higher than act limit: iars=%d, max=%d.\n",
  6547. ia_ranges->nr_ia_ranges, BFQ_MAX_ACTUATORS);
  6548. pr_crit("Falling back to single actuator mode.\n");
  6549. } else {
  6550. bfqd->num_actuators = ia_ranges->nr_ia_ranges;
  6551. for (i = 0; i < bfqd->num_actuators; i++) {
  6552. bfqd->sector[i] = ia_ranges->ia_range[i].sector;
  6553. bfqd->nr_sectors[i] =
  6554. ia_ranges->ia_range[i].nr_sectors;
  6555. }
  6556. }
  6557. }
  6558. /* Otherwise use single-actuator dev info */
  6559. if (bfqd->num_actuators == 1) {
  6560. bfqd->sector[0] = 0;
  6561. bfqd->nr_sectors[0] = get_capacity(q->disk);
  6562. }
  6563. spin_unlock_irq(&q->queue_lock);
  6564. INIT_LIST_HEAD(&bfqd->dispatch);
  6565. hrtimer_setup(&bfqd->idle_slice_timer, bfq_idle_slice_timer, CLOCK_MONOTONIC,
  6566. HRTIMER_MODE_REL);
  6567. bfqd->queue_weights_tree = RB_ROOT_CACHED;
  6568. #ifdef CONFIG_BFQ_GROUP_IOSCHED
  6569. bfqd->num_groups_with_pending_reqs = 0;
  6570. #endif
  6571. INIT_LIST_HEAD(&bfqd->active_list[0]);
  6572. INIT_LIST_HEAD(&bfqd->active_list[1]);
  6573. INIT_LIST_HEAD(&bfqd->idle_list);
  6574. INIT_HLIST_HEAD(&bfqd->burst_list);
  6575. bfqd->hw_tag = -1;
  6576. bfqd->nonrot_with_queueing = !blk_queue_rot(bfqd->queue);
  6577. bfqd->bfq_max_budget = bfq_default_max_budget;
  6578. bfqd->bfq_fifo_expire[0] = bfq_fifo_expire[0];
  6579. bfqd->bfq_fifo_expire[1] = bfq_fifo_expire[1];
  6580. bfqd->bfq_back_max = bfq_back_max;
  6581. bfqd->bfq_back_penalty = bfq_back_penalty;
  6582. bfqd->bfq_slice_idle = bfq_slice_idle;
  6583. bfqd->bfq_timeout = bfq_timeout;
  6584. bfqd->bfq_large_burst_thresh = 8;
  6585. bfqd->bfq_burst_interval = msecs_to_jiffies(180);
  6586. bfqd->low_latency = true;
  6587. /*
  6588. * Trade-off between responsiveness and fairness.
  6589. */
  6590. bfqd->bfq_wr_coeff = 30;
  6591. bfqd->bfq_wr_rt_max_time = msecs_to_jiffies(300);
  6592. bfqd->bfq_wr_min_idle_time = msecs_to_jiffies(2000);
  6593. bfqd->bfq_wr_min_inter_arr_async = msecs_to_jiffies(500);
  6594. bfqd->bfq_wr_max_softrt_rate = 7000; /*
  6595. * Approximate rate required
  6596. * to playback or record a
  6597. * high-definition compressed
  6598. * video.
  6599. */
  6600. bfqd->wr_busy_queues = 0;
  6601. /*
  6602. * Begin by assuming, optimistically, that the device peak
  6603. * rate is equal to 2/3 of the highest reference rate.
  6604. */
  6605. bfqd->rate_dur_prod = ref_rate[!blk_queue_rot(bfqd->queue)] *
  6606. ref_wr_duration[!blk_queue_rot(bfqd->queue)];
  6607. bfqd->peak_rate = ref_rate[!blk_queue_rot(bfqd->queue)] * 2 / 3;
  6608. /* see comments on the definition of next field inside bfq_data */
  6609. bfqd->actuator_load_threshold = 4;
  6610. spin_lock_init(&bfqd->lock);
  6611. /*
  6612. * The invocation of the next bfq_create_group_hierarchy
  6613. * function is the head of a chain of function calls
  6614. * (bfq_create_group_hierarchy->blkcg_activate_policy->
  6615. * blk_mq_freeze_queue) that may lead to the invocation of the
  6616. * has_work hook function. For this reason,
  6617. * bfq_create_group_hierarchy is invoked only after all
  6618. * scheduler data has been initialized, apart from the fields
  6619. * that can be initialized only after invoking
  6620. * bfq_create_group_hierarchy. This, in particular, enables
  6621. * has_work to correctly return false. Of course, to avoid
  6622. * other inconsistencies, the blk-mq stack must then refrain
  6623. * from invoking further scheduler hooks before this init
  6624. * function is finished.
  6625. */
  6626. bfqd->root_group = bfq_create_group_hierarchy(bfqd, q->node);
  6627. if (!bfqd->root_group)
  6628. goto out_free;
  6629. bfq_init_root_group(bfqd->root_group, bfqd);
  6630. bfq_init_entity(&bfqd->oom_bfqq.entity, bfqd->root_group);
  6631. bfq_depth_updated(q);
  6632. /* We dispatch from request queue wide instead of hw queue */
  6633. blk_queue_flag_set(QUEUE_FLAG_SQ_SCHED, q);
  6634. blk_queue_flag_set(QUEUE_FLAG_DISABLE_WBT_DEF, q);
  6635. wbt_disable_default(q->disk);
  6636. blk_stat_enable_accounting(q);
  6637. q->async_depth = (q->nr_requests * 3) >> 2;
  6638. return 0;
  6639. out_free:
  6640. kfree(bfqd);
  6641. return -ENOMEM;
  6642. }
  6643. static void bfq_slab_kill(void)
  6644. {
  6645. kmem_cache_destroy(bfq_pool);
  6646. }
  6647. static int __init bfq_slab_setup(void)
  6648. {
  6649. bfq_pool = KMEM_CACHE(bfq_queue, 0);
  6650. if (!bfq_pool)
  6651. return -ENOMEM;
  6652. return 0;
  6653. }
  6654. static ssize_t bfq_var_show(unsigned int var, char *page)
  6655. {
  6656. return sprintf(page, "%u\n", var);
  6657. }
  6658. static int bfq_var_store(unsigned long *var, const char *page)
  6659. {
  6660. unsigned long new_val;
  6661. int ret = kstrtoul(page, 10, &new_val);
  6662. if (ret)
  6663. return ret;
  6664. *var = new_val;
  6665. return 0;
  6666. }
  6667. #define SHOW_FUNCTION(__FUNC, __VAR, __CONV) \
  6668. static ssize_t __FUNC(struct elevator_queue *e, char *page) \
  6669. { \
  6670. struct bfq_data *bfqd = e->elevator_data; \
  6671. u64 __data = __VAR; \
  6672. if (__CONV == 1) \
  6673. __data = jiffies_to_msecs(__data); \
  6674. else if (__CONV == 2) \
  6675. __data = div_u64(__data, NSEC_PER_MSEC); \
  6676. return bfq_var_show(__data, (page)); \
  6677. }
  6678. SHOW_FUNCTION(bfq_fifo_expire_sync_show, bfqd->bfq_fifo_expire[1], 2);
  6679. SHOW_FUNCTION(bfq_fifo_expire_async_show, bfqd->bfq_fifo_expire[0], 2);
  6680. SHOW_FUNCTION(bfq_back_seek_max_show, bfqd->bfq_back_max, 0);
  6681. SHOW_FUNCTION(bfq_back_seek_penalty_show, bfqd->bfq_back_penalty, 0);
  6682. SHOW_FUNCTION(bfq_slice_idle_show, bfqd->bfq_slice_idle, 2);
  6683. SHOW_FUNCTION(bfq_max_budget_show, bfqd->bfq_user_max_budget, 0);
  6684. SHOW_FUNCTION(bfq_timeout_sync_show, bfqd->bfq_timeout, 1);
  6685. SHOW_FUNCTION(bfq_strict_guarantees_show, bfqd->strict_guarantees, 0);
  6686. SHOW_FUNCTION(bfq_low_latency_show, bfqd->low_latency, 0);
  6687. #undef SHOW_FUNCTION
  6688. #define USEC_SHOW_FUNCTION(__FUNC, __VAR) \
  6689. static ssize_t __FUNC(struct elevator_queue *e, char *page) \
  6690. { \
  6691. struct bfq_data *bfqd = e->elevator_data; \
  6692. u64 __data = __VAR; \
  6693. __data = div_u64(__data, NSEC_PER_USEC); \
  6694. return bfq_var_show(__data, (page)); \
  6695. }
  6696. USEC_SHOW_FUNCTION(bfq_slice_idle_us_show, bfqd->bfq_slice_idle);
  6697. #undef USEC_SHOW_FUNCTION
  6698. #define STORE_FUNCTION(__FUNC, __PTR, MIN, MAX, __CONV) \
  6699. static ssize_t \
  6700. __FUNC(struct elevator_queue *e, const char *page, size_t count) \
  6701. { \
  6702. struct bfq_data *bfqd = e->elevator_data; \
  6703. unsigned long __data, __min = (MIN), __max = (MAX); \
  6704. int ret; \
  6705. \
  6706. ret = bfq_var_store(&__data, (page)); \
  6707. if (ret) \
  6708. return ret; \
  6709. if (__data < __min) \
  6710. __data = __min; \
  6711. else if (__data > __max) \
  6712. __data = __max; \
  6713. if (__CONV == 1) \
  6714. *(__PTR) = msecs_to_jiffies(__data); \
  6715. else if (__CONV == 2) \
  6716. *(__PTR) = (u64)__data * NSEC_PER_MSEC; \
  6717. else \
  6718. *(__PTR) = __data; \
  6719. return count; \
  6720. }
  6721. STORE_FUNCTION(bfq_fifo_expire_sync_store, &bfqd->bfq_fifo_expire[1], 1,
  6722. INT_MAX, 2);
  6723. STORE_FUNCTION(bfq_fifo_expire_async_store, &bfqd->bfq_fifo_expire[0], 1,
  6724. INT_MAX, 2);
  6725. STORE_FUNCTION(bfq_back_seek_max_store, &bfqd->bfq_back_max, 0, INT_MAX, 0);
  6726. STORE_FUNCTION(bfq_back_seek_penalty_store, &bfqd->bfq_back_penalty, 1,
  6727. INT_MAX, 0);
  6728. STORE_FUNCTION(bfq_slice_idle_store, &bfqd->bfq_slice_idle, 0, INT_MAX, 2);
  6729. #undef STORE_FUNCTION
  6730. #define USEC_STORE_FUNCTION(__FUNC, __PTR, MIN, MAX) \
  6731. static ssize_t __FUNC(struct elevator_queue *e, const char *page, size_t count)\
  6732. { \
  6733. struct bfq_data *bfqd = e->elevator_data; \
  6734. unsigned long __data, __min = (MIN), __max = (MAX); \
  6735. int ret; \
  6736. \
  6737. ret = bfq_var_store(&__data, (page)); \
  6738. if (ret) \
  6739. return ret; \
  6740. if (__data < __min) \
  6741. __data = __min; \
  6742. else if (__data > __max) \
  6743. __data = __max; \
  6744. *(__PTR) = (u64)__data * NSEC_PER_USEC; \
  6745. return count; \
  6746. }
  6747. USEC_STORE_FUNCTION(bfq_slice_idle_us_store, &bfqd->bfq_slice_idle, 0,
  6748. UINT_MAX);
  6749. #undef USEC_STORE_FUNCTION
  6750. static ssize_t bfq_max_budget_store(struct elevator_queue *e,
  6751. const char *page, size_t count)
  6752. {
  6753. struct bfq_data *bfqd = e->elevator_data;
  6754. unsigned long __data;
  6755. int ret;
  6756. ret = bfq_var_store(&__data, (page));
  6757. if (ret)
  6758. return ret;
  6759. if (__data == 0)
  6760. bfqd->bfq_max_budget = bfq_calc_max_budget(bfqd);
  6761. else {
  6762. if (__data > INT_MAX)
  6763. __data = INT_MAX;
  6764. bfqd->bfq_max_budget = __data;
  6765. }
  6766. bfqd->bfq_user_max_budget = __data;
  6767. return count;
  6768. }
  6769. /*
  6770. * Leaving this name to preserve name compatibility with cfq
  6771. * parameters, but this timeout is used for both sync and async.
  6772. */
  6773. static ssize_t bfq_timeout_sync_store(struct elevator_queue *e,
  6774. const char *page, size_t count)
  6775. {
  6776. struct bfq_data *bfqd = e->elevator_data;
  6777. unsigned long __data;
  6778. int ret;
  6779. ret = bfq_var_store(&__data, (page));
  6780. if (ret)
  6781. return ret;
  6782. if (__data < 1)
  6783. __data = 1;
  6784. else if (__data > INT_MAX)
  6785. __data = INT_MAX;
  6786. bfqd->bfq_timeout = msecs_to_jiffies(__data);
  6787. if (bfqd->bfq_user_max_budget == 0)
  6788. bfqd->bfq_max_budget = bfq_calc_max_budget(bfqd);
  6789. return count;
  6790. }
  6791. static ssize_t bfq_strict_guarantees_store(struct elevator_queue *e,
  6792. const char *page, size_t count)
  6793. {
  6794. struct bfq_data *bfqd = e->elevator_data;
  6795. unsigned long __data;
  6796. int ret;
  6797. ret = bfq_var_store(&__data, (page));
  6798. if (ret)
  6799. return ret;
  6800. if (__data > 1)
  6801. __data = 1;
  6802. if (!bfqd->strict_guarantees && __data == 1
  6803. && bfqd->bfq_slice_idle < 8 * NSEC_PER_MSEC)
  6804. bfqd->bfq_slice_idle = 8 * NSEC_PER_MSEC;
  6805. bfqd->strict_guarantees = __data;
  6806. return count;
  6807. }
  6808. static ssize_t bfq_low_latency_store(struct elevator_queue *e,
  6809. const char *page, size_t count)
  6810. {
  6811. struct bfq_data *bfqd = e->elevator_data;
  6812. unsigned long __data;
  6813. int ret;
  6814. ret = bfq_var_store(&__data, (page));
  6815. if (ret)
  6816. return ret;
  6817. if (__data > 1)
  6818. __data = 1;
  6819. if (__data == 0 && bfqd->low_latency != 0)
  6820. bfq_end_wr(bfqd);
  6821. bfqd->low_latency = __data;
  6822. return count;
  6823. }
  6824. #define BFQ_ATTR(name) \
  6825. __ATTR(name, 0644, bfq_##name##_show, bfq_##name##_store)
  6826. static const struct elv_fs_entry bfq_attrs[] = {
  6827. BFQ_ATTR(fifo_expire_sync),
  6828. BFQ_ATTR(fifo_expire_async),
  6829. BFQ_ATTR(back_seek_max),
  6830. BFQ_ATTR(back_seek_penalty),
  6831. BFQ_ATTR(slice_idle),
  6832. BFQ_ATTR(slice_idle_us),
  6833. BFQ_ATTR(max_budget),
  6834. BFQ_ATTR(timeout_sync),
  6835. BFQ_ATTR(strict_guarantees),
  6836. BFQ_ATTR(low_latency),
  6837. __ATTR_NULL
  6838. };
  6839. static struct elevator_type iosched_bfq_mq = {
  6840. .ops = {
  6841. .limit_depth = bfq_limit_depth,
  6842. .prepare_request = bfq_prepare_request,
  6843. .requeue_request = bfq_finish_requeue_request,
  6844. .finish_request = bfq_finish_request,
  6845. .exit_icq = bfq_exit_icq,
  6846. .insert_requests = bfq_insert_requests,
  6847. .dispatch_request = bfq_dispatch_request,
  6848. .next_request = elv_rb_latter_request,
  6849. .former_request = elv_rb_former_request,
  6850. .allow_merge = bfq_allow_bio_merge,
  6851. .bio_merge = bfq_bio_merge,
  6852. .request_merge = bfq_request_merge,
  6853. .requests_merged = bfq_requests_merged,
  6854. .request_merged = bfq_request_merged,
  6855. .has_work = bfq_has_work,
  6856. .depth_updated = bfq_depth_updated,
  6857. .init_sched = bfq_init_queue,
  6858. .exit_sched = bfq_exit_queue,
  6859. },
  6860. .icq_size = sizeof(struct bfq_io_cq),
  6861. .icq_align = __alignof__(struct bfq_io_cq),
  6862. .elevator_attrs = bfq_attrs,
  6863. .elevator_name = "bfq",
  6864. .elevator_owner = THIS_MODULE,
  6865. };
  6866. MODULE_ALIAS("bfq-iosched");
  6867. static int __init bfq_init(void)
  6868. {
  6869. int ret;
  6870. #ifdef CONFIG_BFQ_GROUP_IOSCHED
  6871. ret = blkcg_policy_register(&blkcg_policy_bfq);
  6872. if (ret)
  6873. return ret;
  6874. #endif
  6875. ret = -ENOMEM;
  6876. if (bfq_slab_setup())
  6877. goto err_pol_unreg;
  6878. /*
  6879. * Times to load large popular applications for the typical
  6880. * systems installed on the reference devices (see the
  6881. * comments before the definition of the next
  6882. * array). Actually, we use slightly lower values, as the
  6883. * estimated peak rate tends to be smaller than the actual
  6884. * peak rate. The reason for this last fact is that estimates
  6885. * are computed over much shorter time intervals than the long
  6886. * intervals typically used for benchmarking. Why? First, to
  6887. * adapt more quickly to variations. Second, because an I/O
  6888. * scheduler cannot rely on a peak-rate-evaluation workload to
  6889. * be run for a long time.
  6890. */
  6891. ref_wr_duration[0] = msecs_to_jiffies(7000); /* actually 8 sec */
  6892. ref_wr_duration[1] = msecs_to_jiffies(2500); /* actually 3 sec */
  6893. ret = elv_register(&iosched_bfq_mq);
  6894. if (ret)
  6895. goto slab_kill;
  6896. return 0;
  6897. slab_kill:
  6898. bfq_slab_kill();
  6899. err_pol_unreg:
  6900. #ifdef CONFIG_BFQ_GROUP_IOSCHED
  6901. blkcg_policy_unregister(&blkcg_policy_bfq);
  6902. #endif
  6903. return ret;
  6904. }
  6905. static void __exit bfq_exit(void)
  6906. {
  6907. elv_unregister(&iosched_bfq_mq);
  6908. #ifdef CONFIG_BFQ_GROUP_IOSCHED
  6909. blkcg_policy_unregister(&blkcg_policy_bfq);
  6910. #endif
  6911. bfq_slab_kill();
  6912. }
  6913. module_init(bfq_init);
  6914. module_exit(bfq_exit);
  6915. MODULE_AUTHOR("Paolo Valente");
  6916. MODULE_LICENSE("GPL");
  6917. MODULE_DESCRIPTION("MQ Budget Fair Queueing I/O Scheduler");