bfq-iosched.c 164 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117
  1. /*
  2. * Budget Fair Queueing (BFQ) I/O scheduler.
  3. *
  4. * Based on ideas and code from CFQ:
  5. * Copyright (C) 2003 Jens Axboe <axboe@kernel.dk>
  6. *
  7. * Copyright (C) 2008 Fabio Checconi <fabio@gandalf.sssup.it>
  8. * Paolo Valente <paolo.valente@unimore.it>
  9. *
  10. * Copyright (C) 2010 Paolo Valente <paolo.valente@unimore.it>
  11. * Arianna Avanzini <avanzini@google.com>
  12. *
  13. * Copyright (C) 2017 Paolo Valente <paolo.valente@linaro.org>
  14. *
  15. * This program is free software; you can redistribute it and/or
  16. * modify it under the terms of the GNU General Public License as
  17. * published by the Free Software Foundation; either version 2 of the
  18. * License, or (at your option) any later version.
  19. *
  20. * This program is distributed in the hope that it will be useful,
  21. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  22. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  23. * General Public License for more details.
  24. *
  25. * BFQ is a proportional-share I/O scheduler, with some extra
  26. * low-latency capabilities. BFQ also supports full hierarchical
  27. * scheduling through cgroups. Next paragraphs provide an introduction
  28. * on BFQ inner workings. Details on BFQ benefits, usage and
  29. * limitations can be found in Documentation/block/bfq-iosched.txt.
  30. *
  31. * BFQ is a proportional-share storage-I/O scheduling algorithm based
  32. * on the slice-by-slice service scheme of CFQ. But BFQ assigns
  33. * budgets, measured in number of sectors, to processes instead of
  34. * time slices. The device is not granted to the in-service process
  35. * for a given time slice, but until it has exhausted its assigned
  36. * budget. This change from the time to the service domain enables BFQ
  37. * to distribute the device throughput among processes as desired,
  38. * without any distortion due to throughput fluctuations, or to device
  39. * internal queueing. BFQ uses an ad hoc internal scheduler, called
  40. * B-WF2Q+, to schedule processes according to their budgets. More
  41. * precisely, BFQ schedules queues associated with processes. Each
  42. * process/queue is assigned a user-configurable weight, and B-WF2Q+
  43. * guarantees that each queue receives a fraction of the throughput
  44. * proportional to its weight. Thanks to the accurate policy of
  45. * B-WF2Q+, BFQ can afford to assign high budgets to I/O-bound
  46. * processes issuing sequential requests (to boost the throughput),
  47. * and yet guarantee a low latency to interactive and soft real-time
  48. * applications.
  49. *
  50. * In particular, to provide these low-latency guarantees, BFQ
  51. * explicitly privileges the I/O of two classes of time-sensitive
  52. * applications: interactive and soft real-time. This feature enables
  53. * BFQ to provide applications in these classes with a very low
  54. * latency. Finally, BFQ also features additional heuristics for
  55. * preserving both a low latency and a high throughput on NCQ-capable,
  56. * rotational or flash-based devices, and to get the job done quickly
  57. * for applications consisting in many I/O-bound processes.
  58. *
  59. * NOTE: if the main or only goal, with a given device, is to achieve
  60. * the maximum-possible throughput at all times, then do switch off
  61. * all low-latency heuristics for that device, by setting low_latency
  62. * to 0.
  63. *
  64. * BFQ is described in [1], where also a reference to the initial, more
  65. * theoretical paper on BFQ can be found. The interested reader can find
  66. * in the latter paper full details on the main algorithm, as well as
  67. * formulas of the guarantees and formal proofs of all the properties.
  68. * With respect to the version of BFQ presented in these papers, this
  69. * implementation adds a few more heuristics, such as the one that
  70. * guarantees a low latency to soft real-time applications, and a
  71. * hierarchical extension based on H-WF2Q+.
  72. *
  73. * B-WF2Q+ is based on WF2Q+, which is described in [2], together with
  74. * H-WF2Q+, while the augmented tree used here to implement B-WF2Q+
  75. * with O(log N) complexity derives from the one introduced with EEVDF
  76. * in [3].
  77. *
  78. * [1] P. Valente, A. Avanzini, "Evolution of the BFQ Storage I/O
  79. * Scheduler", Proceedings of the First Workshop on Mobile System
  80. * Technologies (MST-2015), May 2015.
  81. * http://algogroup.unimore.it/people/paolo/disk_sched/mst-2015.pdf
  82. *
  83. * [2] Jon C.R. Bennett and H. Zhang, "Hierarchical Packet Fair Queueing
  84. * Algorithms", IEEE/ACM Transactions on Networking, 5(5):675-689,
  85. * Oct 1997.
  86. *
  87. * http://www.cs.cmu.edu/~hzhang/papers/TON-97-Oct.ps.gz
  88. *
  89. * [3] I. Stoica and H. Abdel-Wahab, "Earliest Eligible Virtual Deadline
  90. * First: A Flexible and Accurate Mechanism for Proportional Share
  91. * Resource Allocation", technical report.
  92. *
  93. * http://www.cs.berkeley.edu/~istoica/papers/eevdf-tr-95.pdf
  94. */
  95. #include <linux/module.h>
  96. #include <linux/slab.h>
  97. #include <linux/blkdev.h>
  98. #include <linux/cgroup.h>
  99. #include <linux/elevator.h>
  100. #include <linux/ktime.h>
  101. #include <linux/rbtree.h>
  102. #include <linux/ioprio.h>
  103. #include <linux/sbitmap.h>
  104. #include <linux/delay.h>
  105. #include "blk.h"
  106. #include "blk-mq.h"
  107. #include "blk-mq-tag.h"
  108. #include "blk-mq-sched.h"
  109. #include "bfq-iosched.h"
  110. #define BFQ_BFQQ_FNS(name) \
  111. void bfq_mark_bfqq_##name(struct bfq_queue *bfqq) \
  112. { \
  113. __set_bit(BFQQF_##name, &(bfqq)->flags); \
  114. } \
  115. void bfq_clear_bfqq_##name(struct bfq_queue *bfqq) \
  116. { \
  117. __clear_bit(BFQQF_##name, &(bfqq)->flags); \
  118. } \
  119. int bfq_bfqq_##name(const struct bfq_queue *bfqq) \
  120. { \
  121. return test_bit(BFQQF_##name, &(bfqq)->flags); \
  122. }
  123. BFQ_BFQQ_FNS(just_created);
  124. BFQ_BFQQ_FNS(busy);
  125. BFQ_BFQQ_FNS(wait_request);
  126. BFQ_BFQQ_FNS(non_blocking_wait_rq);
  127. BFQ_BFQQ_FNS(fifo_expire);
  128. BFQ_BFQQ_FNS(has_short_ttime);
  129. BFQ_BFQQ_FNS(sync);
  130. BFQ_BFQQ_FNS(IO_bound);
  131. BFQ_BFQQ_FNS(in_large_burst);
  132. BFQ_BFQQ_FNS(coop);
  133. BFQ_BFQQ_FNS(split_coop);
  134. BFQ_BFQQ_FNS(softrt_update);
  135. #undef BFQ_BFQQ_FNS \
  136. /* Expiration time of sync (0) and async (1) requests, in ns. */
  137. static const u64 bfq_fifo_expire[2] = { NSEC_PER_SEC / 4, NSEC_PER_SEC / 8 };
  138. /* Maximum backwards seek (magic number lifted from CFQ), in KiB. */
  139. static const int bfq_back_max = 16 * 1024;
  140. /* Penalty of a backwards seek, in number of sectors. */
  141. static const int bfq_back_penalty = 2;
  142. /* Idling period duration, in ns. */
  143. static u64 bfq_slice_idle = NSEC_PER_SEC / 125;
  144. /* Minimum number of assigned budgets for which stats are safe to compute. */
  145. static const int bfq_stats_min_budgets = 194;
  146. /* Default maximum budget values, in sectors and number of requests. */
  147. static const int bfq_default_max_budget = 16 * 1024;
  148. /*
  149. * Async to sync throughput distribution is controlled as follows:
  150. * when an async request is served, the entity is charged the number
  151. * of sectors of the request, multiplied by the factor below
  152. */
  153. static const int bfq_async_charge_factor = 10;
  154. /* Default timeout values, in jiffies, approximating CFQ defaults. */
  155. const int bfq_timeout = HZ / 8;
  156. static struct kmem_cache *bfq_pool;
  157. /* Below this threshold (in ns), we consider thinktime immediate. */
  158. #define BFQ_MIN_TT (2 * NSEC_PER_MSEC)
  159. /* hw_tag detection: parallel requests threshold and min samples needed. */
  160. #define BFQ_HW_QUEUE_THRESHOLD 4
  161. #define BFQ_HW_QUEUE_SAMPLES 32
  162. #define BFQQ_SEEK_THR (sector_t)(8 * 100)
  163. #define BFQQ_SECT_THR_NONROT (sector_t)(2 * 32)
  164. #define BFQQ_CLOSE_THR (sector_t)(8 * 1024)
  165. #define BFQQ_SEEKY(bfqq) (hweight32(bfqq->seek_history) > 32/8)
  166. /* Min number of samples required to perform peak-rate update */
  167. #define BFQ_RATE_MIN_SAMPLES 32
  168. /* Min observation time interval required to perform a peak-rate update (ns) */
  169. #define BFQ_RATE_MIN_INTERVAL (300*NSEC_PER_MSEC)
  170. /* Target observation time interval for a peak-rate update (ns) */
  171. #define BFQ_RATE_REF_INTERVAL NSEC_PER_SEC
  172. /* Shift used for peak rate fixed precision calculations. */
  173. #define BFQ_RATE_SHIFT 16
  174. /*
  175. * By default, BFQ computes the duration of the weight raising for
  176. * interactive applications automatically, using the following formula:
  177. * duration = (R / r) * T, where r is the peak rate of the device, and
  178. * R and T are two reference parameters.
  179. * In particular, R is the peak rate of the reference device (see below),
  180. * and T is a reference time: given the systems that are likely to be
  181. * installed on the reference device according to its speed class, T is
  182. * about the maximum time needed, under BFQ and while reading two files in
  183. * parallel, to load typical large applications on these systems.
  184. * In practice, the slower/faster the device at hand is, the more/less it
  185. * takes to load applications with respect to the reference device.
  186. * Accordingly, the longer/shorter BFQ grants weight raising to interactive
  187. * applications.
  188. *
  189. * BFQ uses four different reference pairs (R, T), depending on:
  190. * . whether the device is rotational or non-rotational;
  191. * . whether the device is slow, such as old or portable HDDs, as well as
  192. * SD cards, or fast, such as newer HDDs and SSDs.
  193. *
  194. * The device's speed class is dynamically (re)detected in
  195. * bfq_update_peak_rate() every time the estimated peak rate is updated.
  196. *
  197. * In the following definitions, R_slow[0]/R_fast[0] and
  198. * T_slow[0]/T_fast[0] are the reference values for a slow/fast
  199. * rotational device, whereas R_slow[1]/R_fast[1] and
  200. * T_slow[1]/T_fast[1] are the reference values for a slow/fast
  201. * non-rotational device. Finally, device_speed_thresh are the
  202. * thresholds used to switch between speed classes. The reference
  203. * rates are not the actual peak rates of the devices used as a
  204. * reference, but slightly lower values. The reason for using these
  205. * slightly lower values is that the peak-rate estimator tends to
  206. * yield slightly lower values than the actual peak rate (it can yield
  207. * the actual peak rate only if there is only one process doing I/O,
  208. * and the process does sequential I/O).
  209. *
  210. * Both the reference peak rates and the thresholds are measured in
  211. * sectors/usec, left-shifted by BFQ_RATE_SHIFT.
  212. */
  213. static int R_slow[2] = {1000, 10700};
  214. static int R_fast[2] = {14000, 33000};
  215. /*
  216. * To improve readability, a conversion function is used to initialize the
  217. * following arrays, which entails that they can be initialized only in a
  218. * function.
  219. */
  220. static int T_slow[2];
  221. static int T_fast[2];
  222. static int device_speed_thresh[2];
  223. #define RQ_BIC(rq) icq_to_bic((rq)->elv.priv[0])
  224. #define RQ_BFQQ(rq) ((rq)->elv.priv[1])
  225. struct bfq_queue *bic_to_bfqq(struct bfq_io_cq *bic, bool is_sync)
  226. {
  227. return bic->bfqq[is_sync];
  228. }
  229. void bic_set_bfqq(struct bfq_io_cq *bic, struct bfq_queue *bfqq, bool is_sync)
  230. {
  231. bic->bfqq[is_sync] = bfqq;
  232. }
  233. struct bfq_data *bic_to_bfqd(struct bfq_io_cq *bic)
  234. {
  235. return bic->icq.q->elevator->elevator_data;
  236. }
  237. /**
  238. * icq_to_bic - convert iocontext queue structure to bfq_io_cq.
  239. * @icq: the iocontext queue.
  240. */
  241. static struct bfq_io_cq *icq_to_bic(struct io_cq *icq)
  242. {
  243. /* bic->icq is the first member, %NULL will convert to %NULL */
  244. return container_of(icq, struct bfq_io_cq, icq);
  245. }
  246. /**
  247. * bfq_bic_lookup - search into @ioc a bic associated to @bfqd.
  248. * @bfqd: the lookup key.
  249. * @ioc: the io_context of the process doing I/O.
  250. * @q: the request queue.
  251. */
  252. static struct bfq_io_cq *bfq_bic_lookup(struct bfq_data *bfqd,
  253. struct io_context *ioc,
  254. struct request_queue *q)
  255. {
  256. if (ioc) {
  257. unsigned long flags;
  258. struct bfq_io_cq *icq;
  259. spin_lock_irqsave(q->queue_lock, flags);
  260. icq = icq_to_bic(ioc_lookup_icq(ioc, q));
  261. spin_unlock_irqrestore(q->queue_lock, flags);
  262. return icq;
  263. }
  264. return NULL;
  265. }
  266. /*
  267. * Scheduler run of queue, if there are requests pending and no one in the
  268. * driver that will restart queueing.
  269. */
  270. void bfq_schedule_dispatch(struct bfq_data *bfqd)
  271. {
  272. if (bfqd->queued != 0) {
  273. bfq_log(bfqd, "schedule dispatch");
  274. blk_mq_run_hw_queues(bfqd->queue, true);
  275. }
  276. }
  277. #define bfq_class_idle(bfqq) ((bfqq)->ioprio_class == IOPRIO_CLASS_IDLE)
  278. #define bfq_class_rt(bfqq) ((bfqq)->ioprio_class == IOPRIO_CLASS_RT)
  279. #define bfq_sample_valid(samples) ((samples) > 80)
  280. /*
  281. * Lifted from AS - choose which of rq1 and rq2 that is best served now.
  282. * We choose the request that is closesr to the head right now. Distance
  283. * behind the head is penalized and only allowed to a certain extent.
  284. */
  285. static struct request *bfq_choose_req(struct bfq_data *bfqd,
  286. struct request *rq1,
  287. struct request *rq2,
  288. sector_t last)
  289. {
  290. sector_t s1, s2, d1 = 0, d2 = 0;
  291. unsigned long back_max;
  292. #define BFQ_RQ1_WRAP 0x01 /* request 1 wraps */
  293. #define BFQ_RQ2_WRAP 0x02 /* request 2 wraps */
  294. unsigned int wrap = 0; /* bit mask: requests behind the disk head? */
  295. if (!rq1 || rq1 == rq2)
  296. return rq2;
  297. if (!rq2)
  298. return rq1;
  299. if (rq_is_sync(rq1) && !rq_is_sync(rq2))
  300. return rq1;
  301. else if (rq_is_sync(rq2) && !rq_is_sync(rq1))
  302. return rq2;
  303. if ((rq1->cmd_flags & REQ_META) && !(rq2->cmd_flags & REQ_META))
  304. return rq1;
  305. else if ((rq2->cmd_flags & REQ_META) && !(rq1->cmd_flags & REQ_META))
  306. return rq2;
  307. s1 = blk_rq_pos(rq1);
  308. s2 = blk_rq_pos(rq2);
  309. /*
  310. * By definition, 1KiB is 2 sectors.
  311. */
  312. back_max = bfqd->bfq_back_max * 2;
  313. /*
  314. * Strict one way elevator _except_ in the case where we allow
  315. * short backward seeks which are biased as twice the cost of a
  316. * similar forward seek.
  317. */
  318. if (s1 >= last)
  319. d1 = s1 - last;
  320. else if (s1 + back_max >= last)
  321. d1 = (last - s1) * bfqd->bfq_back_penalty;
  322. else
  323. wrap |= BFQ_RQ1_WRAP;
  324. if (s2 >= last)
  325. d2 = s2 - last;
  326. else if (s2 + back_max >= last)
  327. d2 = (last - s2) * bfqd->bfq_back_penalty;
  328. else
  329. wrap |= BFQ_RQ2_WRAP;
  330. /* Found required data */
  331. /*
  332. * By doing switch() on the bit mask "wrap" we avoid having to
  333. * check two variables for all permutations: --> faster!
  334. */
  335. switch (wrap) {
  336. case 0: /* common case for CFQ: rq1 and rq2 not wrapped */
  337. if (d1 < d2)
  338. return rq1;
  339. else if (d2 < d1)
  340. return rq2;
  341. if (s1 >= s2)
  342. return rq1;
  343. else
  344. return rq2;
  345. case BFQ_RQ2_WRAP:
  346. return rq1;
  347. case BFQ_RQ1_WRAP:
  348. return rq2;
  349. case BFQ_RQ1_WRAP|BFQ_RQ2_WRAP: /* both rqs wrapped */
  350. default:
  351. /*
  352. * Since both rqs are wrapped,
  353. * start with the one that's further behind head
  354. * (--> only *one* back seek required),
  355. * since back seek takes more time than forward.
  356. */
  357. if (s1 <= s2)
  358. return rq1;
  359. else
  360. return rq2;
  361. }
  362. }
  363. static struct bfq_queue *
  364. bfq_rq_pos_tree_lookup(struct bfq_data *bfqd, struct rb_root *root,
  365. sector_t sector, struct rb_node **ret_parent,
  366. struct rb_node ***rb_link)
  367. {
  368. struct rb_node **p, *parent;
  369. struct bfq_queue *bfqq = NULL;
  370. parent = NULL;
  371. p = &root->rb_node;
  372. while (*p) {
  373. struct rb_node **n;
  374. parent = *p;
  375. bfqq = rb_entry(parent, struct bfq_queue, pos_node);
  376. /*
  377. * Sort strictly based on sector. Smallest to the left,
  378. * largest to the right.
  379. */
  380. if (sector > blk_rq_pos(bfqq->next_rq))
  381. n = &(*p)->rb_right;
  382. else if (sector < blk_rq_pos(bfqq->next_rq))
  383. n = &(*p)->rb_left;
  384. else
  385. break;
  386. p = n;
  387. bfqq = NULL;
  388. }
  389. *ret_parent = parent;
  390. if (rb_link)
  391. *rb_link = p;
  392. bfq_log(bfqd, "rq_pos_tree_lookup %llu: returning %d",
  393. (unsigned long long)sector,
  394. bfqq ? bfqq->pid : 0);
  395. return bfqq;
  396. }
  397. void bfq_pos_tree_add_move(struct bfq_data *bfqd, struct bfq_queue *bfqq)
  398. {
  399. struct rb_node **p, *parent;
  400. struct bfq_queue *__bfqq;
  401. if (bfqq->pos_root) {
  402. rb_erase(&bfqq->pos_node, bfqq->pos_root);
  403. bfqq->pos_root = NULL;
  404. }
  405. if (bfq_class_idle(bfqq))
  406. return;
  407. if (!bfqq->next_rq)
  408. return;
  409. bfqq->pos_root = &bfq_bfqq_to_bfqg(bfqq)->rq_pos_tree;
  410. __bfqq = bfq_rq_pos_tree_lookup(bfqd, bfqq->pos_root,
  411. blk_rq_pos(bfqq->next_rq), &parent, &p);
  412. if (!__bfqq) {
  413. rb_link_node(&bfqq->pos_node, parent, p);
  414. rb_insert_color(&bfqq->pos_node, bfqq->pos_root);
  415. } else
  416. bfqq->pos_root = NULL;
  417. }
  418. /*
  419. * Tell whether there are active queues or groups with differentiated weights.
  420. */
  421. static bool bfq_differentiated_weights(struct bfq_data *bfqd)
  422. {
  423. /*
  424. * For weights to differ, at least one of the trees must contain
  425. * at least two nodes.
  426. */
  427. return (!RB_EMPTY_ROOT(&bfqd->queue_weights_tree) &&
  428. (bfqd->queue_weights_tree.rb_node->rb_left ||
  429. bfqd->queue_weights_tree.rb_node->rb_right)
  430. #ifdef CONFIG_BFQ_GROUP_IOSCHED
  431. ) ||
  432. (!RB_EMPTY_ROOT(&bfqd->group_weights_tree) &&
  433. (bfqd->group_weights_tree.rb_node->rb_left ||
  434. bfqd->group_weights_tree.rb_node->rb_right)
  435. #endif
  436. );
  437. }
  438. /*
  439. * The following function returns true if every queue must receive the
  440. * same share of the throughput (this condition is used when deciding
  441. * whether idling may be disabled, see the comments in the function
  442. * bfq_bfqq_may_idle()).
  443. *
  444. * Such a scenario occurs when:
  445. * 1) all active queues have the same weight,
  446. * 2) all active groups at the same level in the groups tree have the same
  447. * weight,
  448. * 3) all active groups at the same level in the groups tree have the same
  449. * number of children.
  450. *
  451. * Unfortunately, keeping the necessary state for evaluating exactly the
  452. * above symmetry conditions would be quite complex and time-consuming.
  453. * Therefore this function evaluates, instead, the following stronger
  454. * sub-conditions, for which it is much easier to maintain the needed
  455. * state:
  456. * 1) all active queues have the same weight,
  457. * 2) all active groups have the same weight,
  458. * 3) all active groups have at most one active child each.
  459. * In particular, the last two conditions are always true if hierarchical
  460. * support and the cgroups interface are not enabled, thus no state needs
  461. * to be maintained in this case.
  462. */
  463. static bool bfq_symmetric_scenario(struct bfq_data *bfqd)
  464. {
  465. return !bfq_differentiated_weights(bfqd);
  466. }
  467. /*
  468. * If the weight-counter tree passed as input contains no counter for
  469. * the weight of the input entity, then add that counter; otherwise just
  470. * increment the existing counter.
  471. *
  472. * Note that weight-counter trees contain few nodes in mostly symmetric
  473. * scenarios. For example, if all queues have the same weight, then the
  474. * weight-counter tree for the queues may contain at most one node.
  475. * This holds even if low_latency is on, because weight-raised queues
  476. * are not inserted in the tree.
  477. * In most scenarios, the rate at which nodes are created/destroyed
  478. * should be low too.
  479. */
  480. void bfq_weights_tree_add(struct bfq_data *bfqd, struct bfq_entity *entity,
  481. struct rb_root *root)
  482. {
  483. struct rb_node **new = &(root->rb_node), *parent = NULL;
  484. /*
  485. * Do not insert if the entity is already associated with a
  486. * counter, which happens if:
  487. * 1) the entity is associated with a queue,
  488. * 2) a request arrival has caused the queue to become both
  489. * non-weight-raised, and hence change its weight, and
  490. * backlogged; in this respect, each of the two events
  491. * causes an invocation of this function,
  492. * 3) this is the invocation of this function caused by the
  493. * second event. This second invocation is actually useless,
  494. * and we handle this fact by exiting immediately. More
  495. * efficient or clearer solutions might possibly be adopted.
  496. */
  497. if (entity->weight_counter)
  498. return;
  499. while (*new) {
  500. struct bfq_weight_counter *__counter = container_of(*new,
  501. struct bfq_weight_counter,
  502. weights_node);
  503. parent = *new;
  504. if (entity->weight == __counter->weight) {
  505. entity->weight_counter = __counter;
  506. goto inc_counter;
  507. }
  508. if (entity->weight < __counter->weight)
  509. new = &((*new)->rb_left);
  510. else
  511. new = &((*new)->rb_right);
  512. }
  513. entity->weight_counter = kzalloc(sizeof(struct bfq_weight_counter),
  514. GFP_ATOMIC);
  515. /*
  516. * In the unlucky event of an allocation failure, we just
  517. * exit. This will cause the weight of entity to not be
  518. * considered in bfq_differentiated_weights, which, in its
  519. * turn, causes the scenario to be deemed wrongly symmetric in
  520. * case entity's weight would have been the only weight making
  521. * the scenario asymmetric. On the bright side, no unbalance
  522. * will however occur when entity becomes inactive again (the
  523. * invocation of this function is triggered by an activation
  524. * of entity). In fact, bfq_weights_tree_remove does nothing
  525. * if !entity->weight_counter.
  526. */
  527. if (unlikely(!entity->weight_counter))
  528. return;
  529. entity->weight_counter->weight = entity->weight;
  530. rb_link_node(&entity->weight_counter->weights_node, parent, new);
  531. rb_insert_color(&entity->weight_counter->weights_node, root);
  532. inc_counter:
  533. entity->weight_counter->num_active++;
  534. }
  535. /*
  536. * Decrement the weight counter associated with the entity, and, if the
  537. * counter reaches 0, remove the counter from the tree.
  538. * See the comments to the function bfq_weights_tree_add() for considerations
  539. * about overhead.
  540. */
  541. void bfq_weights_tree_remove(struct bfq_data *bfqd, struct bfq_entity *entity,
  542. struct rb_root *root)
  543. {
  544. if (!entity->weight_counter)
  545. return;
  546. entity->weight_counter->num_active--;
  547. if (entity->weight_counter->num_active > 0)
  548. goto reset_entity_pointer;
  549. rb_erase(&entity->weight_counter->weights_node, root);
  550. kfree(entity->weight_counter);
  551. reset_entity_pointer:
  552. entity->weight_counter = NULL;
  553. }
  554. /*
  555. * Return expired entry, or NULL to just start from scratch in rbtree.
  556. */
  557. static struct request *bfq_check_fifo(struct bfq_queue *bfqq,
  558. struct request *last)
  559. {
  560. struct request *rq;
  561. if (bfq_bfqq_fifo_expire(bfqq))
  562. return NULL;
  563. bfq_mark_bfqq_fifo_expire(bfqq);
  564. rq = rq_entry_fifo(bfqq->fifo.next);
  565. if (rq == last || ktime_get_ns() < rq->fifo_time)
  566. return NULL;
  567. bfq_log_bfqq(bfqq->bfqd, bfqq, "check_fifo: returned %p", rq);
  568. return rq;
  569. }
  570. static struct request *bfq_find_next_rq(struct bfq_data *bfqd,
  571. struct bfq_queue *bfqq,
  572. struct request *last)
  573. {
  574. struct rb_node *rbnext = rb_next(&last->rb_node);
  575. struct rb_node *rbprev = rb_prev(&last->rb_node);
  576. struct request *next, *prev = NULL;
  577. /* Follow expired path, else get first next available. */
  578. next = bfq_check_fifo(bfqq, last);
  579. if (next)
  580. return next;
  581. if (rbprev)
  582. prev = rb_entry_rq(rbprev);
  583. if (rbnext)
  584. next = rb_entry_rq(rbnext);
  585. else {
  586. rbnext = rb_first(&bfqq->sort_list);
  587. if (rbnext && rbnext != &last->rb_node)
  588. next = rb_entry_rq(rbnext);
  589. }
  590. return bfq_choose_req(bfqd, next, prev, blk_rq_pos(last));
  591. }
  592. /* see the definition of bfq_async_charge_factor for details */
  593. static unsigned long bfq_serv_to_charge(struct request *rq,
  594. struct bfq_queue *bfqq)
  595. {
  596. if (bfq_bfqq_sync(bfqq) || bfqq->wr_coeff > 1)
  597. return blk_rq_sectors(rq);
  598. /*
  599. * If there are no weight-raised queues, then amplify service
  600. * by just the async charge factor; otherwise amplify service
  601. * by twice the async charge factor, to further reduce latency
  602. * for weight-raised queues.
  603. */
  604. if (bfqq->bfqd->wr_busy_queues == 0)
  605. return blk_rq_sectors(rq) * bfq_async_charge_factor;
  606. return blk_rq_sectors(rq) * 2 * bfq_async_charge_factor;
  607. }
  608. /**
  609. * bfq_updated_next_req - update the queue after a new next_rq selection.
  610. * @bfqd: the device data the queue belongs to.
  611. * @bfqq: the queue to update.
  612. *
  613. * If the first request of a queue changes we make sure that the queue
  614. * has enough budget to serve at least its first request (if the
  615. * request has grown). We do this because if the queue has not enough
  616. * budget for its first request, it has to go through two dispatch
  617. * rounds to actually get it dispatched.
  618. */
  619. static void bfq_updated_next_req(struct bfq_data *bfqd,
  620. struct bfq_queue *bfqq)
  621. {
  622. struct bfq_entity *entity = &bfqq->entity;
  623. struct request *next_rq = bfqq->next_rq;
  624. unsigned long new_budget;
  625. if (!next_rq)
  626. return;
  627. if (bfqq == bfqd->in_service_queue)
  628. /*
  629. * In order not to break guarantees, budgets cannot be
  630. * changed after an entity has been selected.
  631. */
  632. return;
  633. new_budget = max_t(unsigned long, bfqq->max_budget,
  634. bfq_serv_to_charge(next_rq, bfqq));
  635. if (entity->budget != new_budget) {
  636. entity->budget = new_budget;
  637. bfq_log_bfqq(bfqd, bfqq, "updated next rq: new budget %lu",
  638. new_budget);
  639. bfq_requeue_bfqq(bfqd, bfqq, false);
  640. }
  641. }
  642. static void
  643. bfq_bfqq_resume_state(struct bfq_queue *bfqq, struct bfq_data *bfqd,
  644. struct bfq_io_cq *bic, bool bfq_already_existing)
  645. {
  646. unsigned int old_wr_coeff = bfqq->wr_coeff;
  647. bool busy = bfq_already_existing && bfq_bfqq_busy(bfqq);
  648. if (bic->saved_has_short_ttime)
  649. bfq_mark_bfqq_has_short_ttime(bfqq);
  650. else
  651. bfq_clear_bfqq_has_short_ttime(bfqq);
  652. if (bic->saved_IO_bound)
  653. bfq_mark_bfqq_IO_bound(bfqq);
  654. else
  655. bfq_clear_bfqq_IO_bound(bfqq);
  656. bfqq->ttime = bic->saved_ttime;
  657. bfqq->wr_coeff = bic->saved_wr_coeff;
  658. bfqq->wr_start_at_switch_to_srt = bic->saved_wr_start_at_switch_to_srt;
  659. bfqq->last_wr_start_finish = bic->saved_last_wr_start_finish;
  660. bfqq->wr_cur_max_time = bic->saved_wr_cur_max_time;
  661. if (bfqq->wr_coeff > 1 && (bfq_bfqq_in_large_burst(bfqq) ||
  662. time_is_before_jiffies(bfqq->last_wr_start_finish +
  663. bfqq->wr_cur_max_time))) {
  664. bfq_log_bfqq(bfqq->bfqd, bfqq,
  665. "resume state: switching off wr");
  666. bfqq->wr_coeff = 1;
  667. }
  668. /* make sure weight will be updated, however we got here */
  669. bfqq->entity.prio_changed = 1;
  670. if (likely(!busy))
  671. return;
  672. if (old_wr_coeff == 1 && bfqq->wr_coeff > 1)
  673. bfqd->wr_busy_queues++;
  674. else if (old_wr_coeff > 1 && bfqq->wr_coeff == 1)
  675. bfqd->wr_busy_queues--;
  676. }
  677. static int bfqq_process_refs(struct bfq_queue *bfqq)
  678. {
  679. return bfqq->ref - bfqq->allocated - bfqq->entity.on_st;
  680. }
  681. /* Empty burst list and add just bfqq (see comments on bfq_handle_burst) */
  682. static void bfq_reset_burst_list(struct bfq_data *bfqd, struct bfq_queue *bfqq)
  683. {
  684. struct bfq_queue *item;
  685. struct hlist_node *n;
  686. hlist_for_each_entry_safe(item, n, &bfqd->burst_list, burst_list_node)
  687. hlist_del_init(&item->burst_list_node);
  688. hlist_add_head(&bfqq->burst_list_node, &bfqd->burst_list);
  689. bfqd->burst_size = 1;
  690. bfqd->burst_parent_entity = bfqq->entity.parent;
  691. }
  692. /* Add bfqq to the list of queues in current burst (see bfq_handle_burst) */
  693. static void bfq_add_to_burst(struct bfq_data *bfqd, struct bfq_queue *bfqq)
  694. {
  695. /* Increment burst size to take into account also bfqq */
  696. bfqd->burst_size++;
  697. if (bfqd->burst_size == bfqd->bfq_large_burst_thresh) {
  698. struct bfq_queue *pos, *bfqq_item;
  699. struct hlist_node *n;
  700. /*
  701. * Enough queues have been activated shortly after each
  702. * other to consider this burst as large.
  703. */
  704. bfqd->large_burst = true;
  705. /*
  706. * We can now mark all queues in the burst list as
  707. * belonging to a large burst.
  708. */
  709. hlist_for_each_entry(bfqq_item, &bfqd->burst_list,
  710. burst_list_node)
  711. bfq_mark_bfqq_in_large_burst(bfqq_item);
  712. bfq_mark_bfqq_in_large_burst(bfqq);
  713. /*
  714. * From now on, and until the current burst finishes, any
  715. * new queue being activated shortly after the last queue
  716. * was inserted in the burst can be immediately marked as
  717. * belonging to a large burst. So the burst list is not
  718. * needed any more. Remove it.
  719. */
  720. hlist_for_each_entry_safe(pos, n, &bfqd->burst_list,
  721. burst_list_node)
  722. hlist_del_init(&pos->burst_list_node);
  723. } else /*
  724. * Burst not yet large: add bfqq to the burst list. Do
  725. * not increment the ref counter for bfqq, because bfqq
  726. * is removed from the burst list before freeing bfqq
  727. * in put_queue.
  728. */
  729. hlist_add_head(&bfqq->burst_list_node, &bfqd->burst_list);
  730. }
  731. /*
  732. * If many queues belonging to the same group happen to be created
  733. * shortly after each other, then the processes associated with these
  734. * queues have typically a common goal. In particular, bursts of queue
  735. * creations are usually caused by services or applications that spawn
  736. * many parallel threads/processes. Examples are systemd during boot,
  737. * or git grep. To help these processes get their job done as soon as
  738. * possible, it is usually better to not grant either weight-raising
  739. * or device idling to their queues.
  740. *
  741. * In this comment we describe, firstly, the reasons why this fact
  742. * holds, and, secondly, the next function, which implements the main
  743. * steps needed to properly mark these queues so that they can then be
  744. * treated in a different way.
  745. *
  746. * The above services or applications benefit mostly from a high
  747. * throughput: the quicker the requests of the activated queues are
  748. * cumulatively served, the sooner the target job of these queues gets
  749. * completed. As a consequence, weight-raising any of these queues,
  750. * which also implies idling the device for it, is almost always
  751. * counterproductive. In most cases it just lowers throughput.
  752. *
  753. * On the other hand, a burst of queue creations may be caused also by
  754. * the start of an application that does not consist of a lot of
  755. * parallel I/O-bound threads. In fact, with a complex application,
  756. * several short processes may need to be executed to start-up the
  757. * application. In this respect, to start an application as quickly as
  758. * possible, the best thing to do is in any case to privilege the I/O
  759. * related to the application with respect to all other
  760. * I/O. Therefore, the best strategy to start as quickly as possible
  761. * an application that causes a burst of queue creations is to
  762. * weight-raise all the queues created during the burst. This is the
  763. * exact opposite of the best strategy for the other type of bursts.
  764. *
  765. * In the end, to take the best action for each of the two cases, the
  766. * two types of bursts need to be distinguished. Fortunately, this
  767. * seems relatively easy, by looking at the sizes of the bursts. In
  768. * particular, we found a threshold such that only bursts with a
  769. * larger size than that threshold are apparently caused by
  770. * services or commands such as systemd or git grep. For brevity,
  771. * hereafter we call just 'large' these bursts. BFQ *does not*
  772. * weight-raise queues whose creation occurs in a large burst. In
  773. * addition, for each of these queues BFQ performs or does not perform
  774. * idling depending on which choice boosts the throughput more. The
  775. * exact choice depends on the device and request pattern at
  776. * hand.
  777. *
  778. * Unfortunately, false positives may occur while an interactive task
  779. * is starting (e.g., an application is being started). The
  780. * consequence is that the queues associated with the task do not
  781. * enjoy weight raising as expected. Fortunately these false positives
  782. * are very rare. They typically occur if some service happens to
  783. * start doing I/O exactly when the interactive task starts.
  784. *
  785. * Turning back to the next function, it implements all the steps
  786. * needed to detect the occurrence of a large burst and to properly
  787. * mark all the queues belonging to it (so that they can then be
  788. * treated in a different way). This goal is achieved by maintaining a
  789. * "burst list" that holds, temporarily, the queues that belong to the
  790. * burst in progress. The list is then used to mark these queues as
  791. * belonging to a large burst if the burst does become large. The main
  792. * steps are the following.
  793. *
  794. * . when the very first queue is created, the queue is inserted into the
  795. * list (as it could be the first queue in a possible burst)
  796. *
  797. * . if the current burst has not yet become large, and a queue Q that does
  798. * not yet belong to the burst is activated shortly after the last time
  799. * at which a new queue entered the burst list, then the function appends
  800. * Q to the burst list
  801. *
  802. * . if, as a consequence of the previous step, the burst size reaches
  803. * the large-burst threshold, then
  804. *
  805. * . all the queues in the burst list are marked as belonging to a
  806. * large burst
  807. *
  808. * . the burst list is deleted; in fact, the burst list already served
  809. * its purpose (keeping temporarily track of the queues in a burst,
  810. * so as to be able to mark them as belonging to a large burst in the
  811. * previous sub-step), and now is not needed any more
  812. *
  813. * . the device enters a large-burst mode
  814. *
  815. * . if a queue Q that does not belong to the burst is created while
  816. * the device is in large-burst mode and shortly after the last time
  817. * at which a queue either entered the burst list or was marked as
  818. * belonging to the current large burst, then Q is immediately marked
  819. * as belonging to a large burst.
  820. *
  821. * . if a queue Q that does not belong to the burst is created a while
  822. * later, i.e., not shortly after, than the last time at which a queue
  823. * either entered the burst list or was marked as belonging to the
  824. * current large burst, then the current burst is deemed as finished and:
  825. *
  826. * . the large-burst mode is reset if set
  827. *
  828. * . the burst list is emptied
  829. *
  830. * . Q is inserted in the burst list, as Q may be the first queue
  831. * in a possible new burst (then the burst list contains just Q
  832. * after this step).
  833. */
  834. static void bfq_handle_burst(struct bfq_data *bfqd, struct bfq_queue *bfqq)
  835. {
  836. /*
  837. * If bfqq is already in the burst list or is part of a large
  838. * burst, or finally has just been split, then there is
  839. * nothing else to do.
  840. */
  841. if (!hlist_unhashed(&bfqq->burst_list_node) ||
  842. bfq_bfqq_in_large_burst(bfqq) ||
  843. time_is_after_eq_jiffies(bfqq->split_time +
  844. msecs_to_jiffies(10)))
  845. return;
  846. /*
  847. * If bfqq's creation happens late enough, or bfqq belongs to
  848. * a different group than the burst group, then the current
  849. * burst is finished, and related data structures must be
  850. * reset.
  851. *
  852. * In this respect, consider the special case where bfqq is
  853. * the very first queue created after BFQ is selected for this
  854. * device. In this case, last_ins_in_burst and
  855. * burst_parent_entity are not yet significant when we get
  856. * here. But it is easy to verify that, whether or not the
  857. * following condition is true, bfqq will end up being
  858. * inserted into the burst list. In particular the list will
  859. * happen to contain only bfqq. And this is exactly what has
  860. * to happen, as bfqq may be the first queue of the first
  861. * burst.
  862. */
  863. if (time_is_before_jiffies(bfqd->last_ins_in_burst +
  864. bfqd->bfq_burst_interval) ||
  865. bfqq->entity.parent != bfqd->burst_parent_entity) {
  866. bfqd->large_burst = false;
  867. bfq_reset_burst_list(bfqd, bfqq);
  868. goto end;
  869. }
  870. /*
  871. * If we get here, then bfqq is being activated shortly after the
  872. * last queue. So, if the current burst is also large, we can mark
  873. * bfqq as belonging to this large burst immediately.
  874. */
  875. if (bfqd->large_burst) {
  876. bfq_mark_bfqq_in_large_burst(bfqq);
  877. goto end;
  878. }
  879. /*
  880. * If we get here, then a large-burst state has not yet been
  881. * reached, but bfqq is being activated shortly after the last
  882. * queue. Then we add bfqq to the burst.
  883. */
  884. bfq_add_to_burst(bfqd, bfqq);
  885. end:
  886. /*
  887. * At this point, bfqq either has been added to the current
  888. * burst or has caused the current burst to terminate and a
  889. * possible new burst to start. In particular, in the second
  890. * case, bfqq has become the first queue in the possible new
  891. * burst. In both cases last_ins_in_burst needs to be moved
  892. * forward.
  893. */
  894. bfqd->last_ins_in_burst = jiffies;
  895. }
  896. static int bfq_bfqq_budget_left(struct bfq_queue *bfqq)
  897. {
  898. struct bfq_entity *entity = &bfqq->entity;
  899. return entity->budget - entity->service;
  900. }
  901. /*
  902. * If enough samples have been computed, return the current max budget
  903. * stored in bfqd, which is dynamically updated according to the
  904. * estimated disk peak rate; otherwise return the default max budget
  905. */
  906. static int bfq_max_budget(struct bfq_data *bfqd)
  907. {
  908. if (bfqd->budgets_assigned < bfq_stats_min_budgets)
  909. return bfq_default_max_budget;
  910. else
  911. return bfqd->bfq_max_budget;
  912. }
  913. /*
  914. * Return min budget, which is a fraction of the current or default
  915. * max budget (trying with 1/32)
  916. */
  917. static int bfq_min_budget(struct bfq_data *bfqd)
  918. {
  919. if (bfqd->budgets_assigned < bfq_stats_min_budgets)
  920. return bfq_default_max_budget / 32;
  921. else
  922. return bfqd->bfq_max_budget / 32;
  923. }
  924. /*
  925. * The next function, invoked after the input queue bfqq switches from
  926. * idle to busy, updates the budget of bfqq. The function also tells
  927. * whether the in-service queue should be expired, by returning
  928. * true. The purpose of expiring the in-service queue is to give bfqq
  929. * the chance to possibly preempt the in-service queue, and the reason
  930. * for preempting the in-service queue is to achieve one of the two
  931. * goals below.
  932. *
  933. * 1. Guarantee to bfqq its reserved bandwidth even if bfqq has
  934. * expired because it has remained idle. In particular, bfqq may have
  935. * expired for one of the following two reasons:
  936. *
  937. * - BFQQE_NO_MORE_REQUESTS bfqq did not enjoy any device idling
  938. * and did not make it to issue a new request before its last
  939. * request was served;
  940. *
  941. * - BFQQE_TOO_IDLE bfqq did enjoy device idling, but did not issue
  942. * a new request before the expiration of the idling-time.
  943. *
  944. * Even if bfqq has expired for one of the above reasons, the process
  945. * associated with the queue may be however issuing requests greedily,
  946. * and thus be sensitive to the bandwidth it receives (bfqq may have
  947. * remained idle for other reasons: CPU high load, bfqq not enjoying
  948. * idling, I/O throttling somewhere in the path from the process to
  949. * the I/O scheduler, ...). But if, after every expiration for one of
  950. * the above two reasons, bfqq has to wait for the service of at least
  951. * one full budget of another queue before being served again, then
  952. * bfqq is likely to get a much lower bandwidth or resource time than
  953. * its reserved ones. To address this issue, two countermeasures need
  954. * to be taken.
  955. *
  956. * First, the budget and the timestamps of bfqq need to be updated in
  957. * a special way on bfqq reactivation: they need to be updated as if
  958. * bfqq did not remain idle and did not expire. In fact, if they are
  959. * computed as if bfqq expired and remained idle until reactivation,
  960. * then the process associated with bfqq is treated as if, instead of
  961. * being greedy, it stopped issuing requests when bfqq remained idle,
  962. * and restarts issuing requests only on this reactivation. In other
  963. * words, the scheduler does not help the process recover the "service
  964. * hole" between bfqq expiration and reactivation. As a consequence,
  965. * the process receives a lower bandwidth than its reserved one. In
  966. * contrast, to recover this hole, the budget must be updated as if
  967. * bfqq was not expired at all before this reactivation, i.e., it must
  968. * be set to the value of the remaining budget when bfqq was
  969. * expired. Along the same line, timestamps need to be assigned the
  970. * value they had the last time bfqq was selected for service, i.e.,
  971. * before last expiration. Thus timestamps need to be back-shifted
  972. * with respect to their normal computation (see [1] for more details
  973. * on this tricky aspect).
  974. *
  975. * Secondly, to allow the process to recover the hole, the in-service
  976. * queue must be expired too, to give bfqq the chance to preempt it
  977. * immediately. In fact, if bfqq has to wait for a full budget of the
  978. * in-service queue to be completed, then it may become impossible to
  979. * let the process recover the hole, even if the back-shifted
  980. * timestamps of bfqq are lower than those of the in-service queue. If
  981. * this happens for most or all of the holes, then the process may not
  982. * receive its reserved bandwidth. In this respect, it is worth noting
  983. * that, being the service of outstanding requests unpreemptible, a
  984. * little fraction of the holes may however be unrecoverable, thereby
  985. * causing a little loss of bandwidth.
  986. *
  987. * The last important point is detecting whether bfqq does need this
  988. * bandwidth recovery. In this respect, the next function deems the
  989. * process associated with bfqq greedy, and thus allows it to recover
  990. * the hole, if: 1) the process is waiting for the arrival of a new
  991. * request (which implies that bfqq expired for one of the above two
  992. * reasons), and 2) such a request has arrived soon. The first
  993. * condition is controlled through the flag non_blocking_wait_rq,
  994. * while the second through the flag arrived_in_time. If both
  995. * conditions hold, then the function computes the budget in the
  996. * above-described special way, and signals that the in-service queue
  997. * should be expired. Timestamp back-shifting is done later in
  998. * __bfq_activate_entity.
  999. *
  1000. * 2. Reduce latency. Even if timestamps are not backshifted to let
  1001. * the process associated with bfqq recover a service hole, bfqq may
  1002. * however happen to have, after being (re)activated, a lower finish
  1003. * timestamp than the in-service queue. That is, the next budget of
  1004. * bfqq may have to be completed before the one of the in-service
  1005. * queue. If this is the case, then preempting the in-service queue
  1006. * allows this goal to be achieved, apart from the unpreemptible,
  1007. * outstanding requests mentioned above.
  1008. *
  1009. * Unfortunately, regardless of which of the above two goals one wants
  1010. * to achieve, service trees need first to be updated to know whether
  1011. * the in-service queue must be preempted. To have service trees
  1012. * correctly updated, the in-service queue must be expired and
  1013. * rescheduled, and bfqq must be scheduled too. This is one of the
  1014. * most costly operations (in future versions, the scheduling
  1015. * mechanism may be re-designed in such a way to make it possible to
  1016. * know whether preemption is needed without needing to update service
  1017. * trees). In addition, queue preemptions almost always cause random
  1018. * I/O, and thus loss of throughput. Because of these facts, the next
  1019. * function adopts the following simple scheme to avoid both costly
  1020. * operations and too frequent preemptions: it requests the expiration
  1021. * of the in-service queue (unconditionally) only for queues that need
  1022. * to recover a hole, or that either are weight-raised or deserve to
  1023. * be weight-raised.
  1024. */
  1025. static bool bfq_bfqq_update_budg_for_activation(struct bfq_data *bfqd,
  1026. struct bfq_queue *bfqq,
  1027. bool arrived_in_time,
  1028. bool wr_or_deserves_wr)
  1029. {
  1030. struct bfq_entity *entity = &bfqq->entity;
  1031. if (bfq_bfqq_non_blocking_wait_rq(bfqq) && arrived_in_time) {
  1032. /*
  1033. * We do not clear the flag non_blocking_wait_rq here, as
  1034. * the latter is used in bfq_activate_bfqq to signal
  1035. * that timestamps need to be back-shifted (and is
  1036. * cleared right after).
  1037. */
  1038. /*
  1039. * In next assignment we rely on that either
  1040. * entity->service or entity->budget are not updated
  1041. * on expiration if bfqq is empty (see
  1042. * __bfq_bfqq_recalc_budget). Thus both quantities
  1043. * remain unchanged after such an expiration, and the
  1044. * following statement therefore assigns to
  1045. * entity->budget the remaining budget on such an
  1046. * expiration. For clarity, entity->service is not
  1047. * updated on expiration in any case, and, in normal
  1048. * operation, is reset only when bfqq is selected for
  1049. * service (see bfq_get_next_queue).
  1050. */
  1051. entity->budget = min_t(unsigned long,
  1052. bfq_bfqq_budget_left(bfqq),
  1053. bfqq->max_budget);
  1054. return true;
  1055. }
  1056. entity->budget = max_t(unsigned long, bfqq->max_budget,
  1057. bfq_serv_to_charge(bfqq->next_rq, bfqq));
  1058. bfq_clear_bfqq_non_blocking_wait_rq(bfqq);
  1059. return wr_or_deserves_wr;
  1060. }
  1061. static unsigned int bfq_wr_duration(struct bfq_data *bfqd)
  1062. {
  1063. u64 dur;
  1064. if (bfqd->bfq_wr_max_time > 0)
  1065. return bfqd->bfq_wr_max_time;
  1066. dur = bfqd->RT_prod;
  1067. do_div(dur, bfqd->peak_rate);
  1068. /*
  1069. * Limit duration between 3 and 13 seconds. Tests show that
  1070. * higher values than 13 seconds often yield the opposite of
  1071. * the desired result, i.e., worsen responsiveness by letting
  1072. * non-interactive and non-soft-real-time applications
  1073. * preserve weight raising for a too long time interval.
  1074. *
  1075. * On the other end, lower values than 3 seconds make it
  1076. * difficult for most interactive tasks to complete their jobs
  1077. * before weight-raising finishes.
  1078. */
  1079. if (dur > msecs_to_jiffies(13000))
  1080. dur = msecs_to_jiffies(13000);
  1081. else if (dur < msecs_to_jiffies(3000))
  1082. dur = msecs_to_jiffies(3000);
  1083. return dur;
  1084. }
  1085. static void bfq_update_bfqq_wr_on_rq_arrival(struct bfq_data *bfqd,
  1086. struct bfq_queue *bfqq,
  1087. unsigned int old_wr_coeff,
  1088. bool wr_or_deserves_wr,
  1089. bool interactive,
  1090. bool in_burst,
  1091. bool soft_rt)
  1092. {
  1093. if (old_wr_coeff == 1 && wr_or_deserves_wr) {
  1094. /* start a weight-raising period */
  1095. if (interactive) {
  1096. bfqq->wr_coeff = bfqd->bfq_wr_coeff;
  1097. bfqq->wr_cur_max_time = bfq_wr_duration(bfqd);
  1098. } else {
  1099. bfqq->wr_start_at_switch_to_srt = jiffies;
  1100. bfqq->wr_coeff = bfqd->bfq_wr_coeff *
  1101. BFQ_SOFTRT_WEIGHT_FACTOR;
  1102. bfqq->wr_cur_max_time =
  1103. bfqd->bfq_wr_rt_max_time;
  1104. }
  1105. /*
  1106. * If needed, further reduce budget to make sure it is
  1107. * close to bfqq's backlog, so as to reduce the
  1108. * scheduling-error component due to a too large
  1109. * budget. Do not care about throughput consequences,
  1110. * but only about latency. Finally, do not assign a
  1111. * too small budget either, to avoid increasing
  1112. * latency by causing too frequent expirations.
  1113. */
  1114. bfqq->entity.budget = min_t(unsigned long,
  1115. bfqq->entity.budget,
  1116. 2 * bfq_min_budget(bfqd));
  1117. } else if (old_wr_coeff > 1) {
  1118. if (interactive) { /* update wr coeff and duration */
  1119. bfqq->wr_coeff = bfqd->bfq_wr_coeff;
  1120. bfqq->wr_cur_max_time = bfq_wr_duration(bfqd);
  1121. } else if (in_burst)
  1122. bfqq->wr_coeff = 1;
  1123. else if (soft_rt) {
  1124. /*
  1125. * The application is now or still meeting the
  1126. * requirements for being deemed soft rt. We
  1127. * can then correctly and safely (re)charge
  1128. * the weight-raising duration for the
  1129. * application with the weight-raising
  1130. * duration for soft rt applications.
  1131. *
  1132. * In particular, doing this recharge now, i.e.,
  1133. * before the weight-raising period for the
  1134. * application finishes, reduces the probability
  1135. * of the following negative scenario:
  1136. * 1) the weight of a soft rt application is
  1137. * raised at startup (as for any newly
  1138. * created application),
  1139. * 2) since the application is not interactive,
  1140. * at a certain time weight-raising is
  1141. * stopped for the application,
  1142. * 3) at that time the application happens to
  1143. * still have pending requests, and hence
  1144. * is destined to not have a chance to be
  1145. * deemed soft rt before these requests are
  1146. * completed (see the comments to the
  1147. * function bfq_bfqq_softrt_next_start()
  1148. * for details on soft rt detection),
  1149. * 4) these pending requests experience a high
  1150. * latency because the application is not
  1151. * weight-raised while they are pending.
  1152. */
  1153. if (bfqq->wr_cur_max_time !=
  1154. bfqd->bfq_wr_rt_max_time) {
  1155. bfqq->wr_start_at_switch_to_srt =
  1156. bfqq->last_wr_start_finish;
  1157. bfqq->wr_cur_max_time =
  1158. bfqd->bfq_wr_rt_max_time;
  1159. bfqq->wr_coeff = bfqd->bfq_wr_coeff *
  1160. BFQ_SOFTRT_WEIGHT_FACTOR;
  1161. }
  1162. bfqq->last_wr_start_finish = jiffies;
  1163. }
  1164. }
  1165. }
  1166. static bool bfq_bfqq_idle_for_long_time(struct bfq_data *bfqd,
  1167. struct bfq_queue *bfqq)
  1168. {
  1169. return bfqq->dispatched == 0 &&
  1170. time_is_before_jiffies(
  1171. bfqq->budget_timeout +
  1172. bfqd->bfq_wr_min_idle_time);
  1173. }
  1174. static void bfq_bfqq_handle_idle_busy_switch(struct bfq_data *bfqd,
  1175. struct bfq_queue *bfqq,
  1176. int old_wr_coeff,
  1177. struct request *rq,
  1178. bool *interactive)
  1179. {
  1180. bool soft_rt, in_burst, wr_or_deserves_wr,
  1181. bfqq_wants_to_preempt,
  1182. idle_for_long_time = bfq_bfqq_idle_for_long_time(bfqd, bfqq),
  1183. /*
  1184. * See the comments on
  1185. * bfq_bfqq_update_budg_for_activation for
  1186. * details on the usage of the next variable.
  1187. */
  1188. arrived_in_time = ktime_get_ns() <=
  1189. bfqq->ttime.last_end_request +
  1190. bfqd->bfq_slice_idle * 3;
  1191. bfqg_stats_update_io_add(bfqq_group(RQ_BFQQ(rq)), bfqq, rq->cmd_flags);
  1192. /*
  1193. * bfqq deserves to be weight-raised if:
  1194. * - it is sync,
  1195. * - it does not belong to a large burst,
  1196. * - it has been idle for enough time or is soft real-time,
  1197. * - is linked to a bfq_io_cq (it is not shared in any sense).
  1198. */
  1199. in_burst = bfq_bfqq_in_large_burst(bfqq);
  1200. soft_rt = bfqd->bfq_wr_max_softrt_rate > 0 &&
  1201. !in_burst &&
  1202. time_is_before_jiffies(bfqq->soft_rt_next_start);
  1203. *interactive = !in_burst && idle_for_long_time;
  1204. wr_or_deserves_wr = bfqd->low_latency &&
  1205. (bfqq->wr_coeff > 1 ||
  1206. (bfq_bfqq_sync(bfqq) &&
  1207. bfqq->bic && (*interactive || soft_rt)));
  1208. /*
  1209. * Using the last flag, update budget and check whether bfqq
  1210. * may want to preempt the in-service queue.
  1211. */
  1212. bfqq_wants_to_preempt =
  1213. bfq_bfqq_update_budg_for_activation(bfqd, bfqq,
  1214. arrived_in_time,
  1215. wr_or_deserves_wr);
  1216. /*
  1217. * If bfqq happened to be activated in a burst, but has been
  1218. * idle for much more than an interactive queue, then we
  1219. * assume that, in the overall I/O initiated in the burst, the
  1220. * I/O associated with bfqq is finished. So bfqq does not need
  1221. * to be treated as a queue belonging to a burst
  1222. * anymore. Accordingly, we reset bfqq's in_large_burst flag
  1223. * if set, and remove bfqq from the burst list if it's
  1224. * there. We do not decrement burst_size, because the fact
  1225. * that bfqq does not need to belong to the burst list any
  1226. * more does not invalidate the fact that bfqq was created in
  1227. * a burst.
  1228. */
  1229. if (likely(!bfq_bfqq_just_created(bfqq)) &&
  1230. idle_for_long_time &&
  1231. time_is_before_jiffies(
  1232. bfqq->budget_timeout +
  1233. msecs_to_jiffies(10000))) {
  1234. hlist_del_init(&bfqq->burst_list_node);
  1235. bfq_clear_bfqq_in_large_burst(bfqq);
  1236. }
  1237. bfq_clear_bfqq_just_created(bfqq);
  1238. if (!bfq_bfqq_IO_bound(bfqq)) {
  1239. if (arrived_in_time) {
  1240. bfqq->requests_within_timer++;
  1241. if (bfqq->requests_within_timer >=
  1242. bfqd->bfq_requests_within_timer)
  1243. bfq_mark_bfqq_IO_bound(bfqq);
  1244. } else
  1245. bfqq->requests_within_timer = 0;
  1246. }
  1247. if (bfqd->low_latency) {
  1248. if (unlikely(time_is_after_jiffies(bfqq->split_time)))
  1249. /* wraparound */
  1250. bfqq->split_time =
  1251. jiffies - bfqd->bfq_wr_min_idle_time - 1;
  1252. if (time_is_before_jiffies(bfqq->split_time +
  1253. bfqd->bfq_wr_min_idle_time)) {
  1254. bfq_update_bfqq_wr_on_rq_arrival(bfqd, bfqq,
  1255. old_wr_coeff,
  1256. wr_or_deserves_wr,
  1257. *interactive,
  1258. in_burst,
  1259. soft_rt);
  1260. if (old_wr_coeff != bfqq->wr_coeff)
  1261. bfqq->entity.prio_changed = 1;
  1262. }
  1263. }
  1264. bfqq->last_idle_bklogged = jiffies;
  1265. bfqq->service_from_backlogged = 0;
  1266. bfq_clear_bfqq_softrt_update(bfqq);
  1267. bfq_add_bfqq_busy(bfqd, bfqq);
  1268. /*
  1269. * Expire in-service queue only if preemption may be needed
  1270. * for guarantees. In this respect, the function
  1271. * next_queue_may_preempt just checks a simple, necessary
  1272. * condition, and not a sufficient condition based on
  1273. * timestamps. In fact, for the latter condition to be
  1274. * evaluated, timestamps would need first to be updated, and
  1275. * this operation is quite costly (see the comments on the
  1276. * function bfq_bfqq_update_budg_for_activation).
  1277. */
  1278. if (bfqd->in_service_queue && bfqq_wants_to_preempt &&
  1279. bfqd->in_service_queue->wr_coeff < bfqq->wr_coeff &&
  1280. next_queue_may_preempt(bfqd))
  1281. bfq_bfqq_expire(bfqd, bfqd->in_service_queue,
  1282. false, BFQQE_PREEMPTED);
  1283. }
  1284. static void bfq_add_request(struct request *rq)
  1285. {
  1286. struct bfq_queue *bfqq = RQ_BFQQ(rq);
  1287. struct bfq_data *bfqd = bfqq->bfqd;
  1288. struct request *next_rq, *prev;
  1289. unsigned int old_wr_coeff = bfqq->wr_coeff;
  1290. bool interactive = false;
  1291. bfq_log_bfqq(bfqd, bfqq, "add_request %d", rq_is_sync(rq));
  1292. bfqq->queued[rq_is_sync(rq)]++;
  1293. bfqd->queued++;
  1294. elv_rb_add(&bfqq->sort_list, rq);
  1295. /*
  1296. * Check if this request is a better next-serve candidate.
  1297. */
  1298. prev = bfqq->next_rq;
  1299. next_rq = bfq_choose_req(bfqd, bfqq->next_rq, rq, bfqd->last_position);
  1300. bfqq->next_rq = next_rq;
  1301. /*
  1302. * Adjust priority tree position, if next_rq changes.
  1303. */
  1304. if (prev != bfqq->next_rq)
  1305. bfq_pos_tree_add_move(bfqd, bfqq);
  1306. if (!bfq_bfqq_busy(bfqq)) /* switching to busy ... */
  1307. bfq_bfqq_handle_idle_busy_switch(bfqd, bfqq, old_wr_coeff,
  1308. rq, &interactive);
  1309. else {
  1310. if (bfqd->low_latency && old_wr_coeff == 1 && !rq_is_sync(rq) &&
  1311. time_is_before_jiffies(
  1312. bfqq->last_wr_start_finish +
  1313. bfqd->bfq_wr_min_inter_arr_async)) {
  1314. bfqq->wr_coeff = bfqd->bfq_wr_coeff;
  1315. bfqq->wr_cur_max_time = bfq_wr_duration(bfqd);
  1316. bfqd->wr_busy_queues++;
  1317. bfqq->entity.prio_changed = 1;
  1318. }
  1319. if (prev != bfqq->next_rq)
  1320. bfq_updated_next_req(bfqd, bfqq);
  1321. }
  1322. /*
  1323. * Assign jiffies to last_wr_start_finish in the following
  1324. * cases:
  1325. *
  1326. * . if bfqq is not going to be weight-raised, because, for
  1327. * non weight-raised queues, last_wr_start_finish stores the
  1328. * arrival time of the last request; as of now, this piece
  1329. * of information is used only for deciding whether to
  1330. * weight-raise async queues
  1331. *
  1332. * . if bfqq is not weight-raised, because, if bfqq is now
  1333. * switching to weight-raised, then last_wr_start_finish
  1334. * stores the time when weight-raising starts
  1335. *
  1336. * . if bfqq is interactive, because, regardless of whether
  1337. * bfqq is currently weight-raised, the weight-raising
  1338. * period must start or restart (this case is considered
  1339. * separately because it is not detected by the above
  1340. * conditions, if bfqq is already weight-raised)
  1341. *
  1342. * last_wr_start_finish has to be updated also if bfqq is soft
  1343. * real-time, because the weight-raising period is constantly
  1344. * restarted on idle-to-busy transitions for these queues, but
  1345. * this is already done in bfq_bfqq_handle_idle_busy_switch if
  1346. * needed.
  1347. */
  1348. if (bfqd->low_latency &&
  1349. (old_wr_coeff == 1 || bfqq->wr_coeff == 1 || interactive))
  1350. bfqq->last_wr_start_finish = jiffies;
  1351. }
  1352. static struct request *bfq_find_rq_fmerge(struct bfq_data *bfqd,
  1353. struct bio *bio,
  1354. struct request_queue *q)
  1355. {
  1356. struct bfq_queue *bfqq = bfqd->bio_bfqq;
  1357. if (bfqq)
  1358. return elv_rb_find(&bfqq->sort_list, bio_end_sector(bio));
  1359. return NULL;
  1360. }
  1361. static sector_t get_sdist(sector_t last_pos, struct request *rq)
  1362. {
  1363. if (last_pos)
  1364. return abs(blk_rq_pos(rq) - last_pos);
  1365. return 0;
  1366. }
  1367. #if 0 /* Still not clear if we can do without next two functions */
  1368. static void bfq_activate_request(struct request_queue *q, struct request *rq)
  1369. {
  1370. struct bfq_data *bfqd = q->elevator->elevator_data;
  1371. bfqd->rq_in_driver++;
  1372. }
  1373. static void bfq_deactivate_request(struct request_queue *q, struct request *rq)
  1374. {
  1375. struct bfq_data *bfqd = q->elevator->elevator_data;
  1376. bfqd->rq_in_driver--;
  1377. }
  1378. #endif
  1379. static void bfq_remove_request(struct request_queue *q,
  1380. struct request *rq)
  1381. {
  1382. struct bfq_queue *bfqq = RQ_BFQQ(rq);
  1383. struct bfq_data *bfqd = bfqq->bfqd;
  1384. const int sync = rq_is_sync(rq);
  1385. if (bfqq->next_rq == rq) {
  1386. bfqq->next_rq = bfq_find_next_rq(bfqd, bfqq, rq);
  1387. bfq_updated_next_req(bfqd, bfqq);
  1388. }
  1389. if (rq->queuelist.prev != &rq->queuelist)
  1390. list_del_init(&rq->queuelist);
  1391. bfqq->queued[sync]--;
  1392. bfqd->queued--;
  1393. elv_rb_del(&bfqq->sort_list, rq);
  1394. elv_rqhash_del(q, rq);
  1395. if (q->last_merge == rq)
  1396. q->last_merge = NULL;
  1397. if (RB_EMPTY_ROOT(&bfqq->sort_list)) {
  1398. bfqq->next_rq = NULL;
  1399. if (bfq_bfqq_busy(bfqq) && bfqq != bfqd->in_service_queue) {
  1400. bfq_del_bfqq_busy(bfqd, bfqq, false);
  1401. /*
  1402. * bfqq emptied. In normal operation, when
  1403. * bfqq is empty, bfqq->entity.service and
  1404. * bfqq->entity.budget must contain,
  1405. * respectively, the service received and the
  1406. * budget used last time bfqq emptied. These
  1407. * facts do not hold in this case, as at least
  1408. * this last removal occurred while bfqq is
  1409. * not in service. To avoid inconsistencies,
  1410. * reset both bfqq->entity.service and
  1411. * bfqq->entity.budget, if bfqq has still a
  1412. * process that may issue I/O requests to it.
  1413. */
  1414. bfqq->entity.budget = bfqq->entity.service = 0;
  1415. }
  1416. /*
  1417. * Remove queue from request-position tree as it is empty.
  1418. */
  1419. if (bfqq->pos_root) {
  1420. rb_erase(&bfqq->pos_node, bfqq->pos_root);
  1421. bfqq->pos_root = NULL;
  1422. }
  1423. }
  1424. if (rq->cmd_flags & REQ_META)
  1425. bfqq->meta_pending--;
  1426. bfqg_stats_update_io_remove(bfqq_group(bfqq), rq->cmd_flags);
  1427. }
  1428. static bool bfq_bio_merge(struct blk_mq_hw_ctx *hctx, struct bio *bio)
  1429. {
  1430. struct request_queue *q = hctx->queue;
  1431. struct bfq_data *bfqd = q->elevator->elevator_data;
  1432. struct request *free = NULL;
  1433. /*
  1434. * bfq_bic_lookup grabs the queue_lock: invoke it now and
  1435. * store its return value for later use, to avoid nesting
  1436. * queue_lock inside the bfqd->lock. We assume that the bic
  1437. * returned by bfq_bic_lookup does not go away before
  1438. * bfqd->lock is taken.
  1439. */
  1440. struct bfq_io_cq *bic = bfq_bic_lookup(bfqd, current->io_context, q);
  1441. bool ret;
  1442. spin_lock_irq(&bfqd->lock);
  1443. if (bic)
  1444. bfqd->bio_bfqq = bic_to_bfqq(bic, op_is_sync(bio->bi_opf));
  1445. else
  1446. bfqd->bio_bfqq = NULL;
  1447. bfqd->bio_bic = bic;
  1448. ret = blk_mq_sched_try_merge(q, bio, &free);
  1449. if (free)
  1450. blk_mq_free_request(free);
  1451. spin_unlock_irq(&bfqd->lock);
  1452. return ret;
  1453. }
  1454. static int bfq_request_merge(struct request_queue *q, struct request **req,
  1455. struct bio *bio)
  1456. {
  1457. struct bfq_data *bfqd = q->elevator->elevator_data;
  1458. struct request *__rq;
  1459. __rq = bfq_find_rq_fmerge(bfqd, bio, q);
  1460. if (__rq && elv_bio_merge_ok(__rq, bio)) {
  1461. *req = __rq;
  1462. return ELEVATOR_FRONT_MERGE;
  1463. }
  1464. return ELEVATOR_NO_MERGE;
  1465. }
  1466. static void bfq_request_merged(struct request_queue *q, struct request *req,
  1467. enum elv_merge type)
  1468. {
  1469. if (type == ELEVATOR_FRONT_MERGE &&
  1470. rb_prev(&req->rb_node) &&
  1471. blk_rq_pos(req) <
  1472. blk_rq_pos(container_of(rb_prev(&req->rb_node),
  1473. struct request, rb_node))) {
  1474. struct bfq_queue *bfqq = RQ_BFQQ(req);
  1475. struct bfq_data *bfqd = bfqq->bfqd;
  1476. struct request *prev, *next_rq;
  1477. /* Reposition request in its sort_list */
  1478. elv_rb_del(&bfqq->sort_list, req);
  1479. elv_rb_add(&bfqq->sort_list, req);
  1480. /* Choose next request to be served for bfqq */
  1481. prev = bfqq->next_rq;
  1482. next_rq = bfq_choose_req(bfqd, bfqq->next_rq, req,
  1483. bfqd->last_position);
  1484. bfqq->next_rq = next_rq;
  1485. /*
  1486. * If next_rq changes, update both the queue's budget to
  1487. * fit the new request and the queue's position in its
  1488. * rq_pos_tree.
  1489. */
  1490. if (prev != bfqq->next_rq) {
  1491. bfq_updated_next_req(bfqd, bfqq);
  1492. bfq_pos_tree_add_move(bfqd, bfqq);
  1493. }
  1494. }
  1495. }
  1496. static void bfq_requests_merged(struct request_queue *q, struct request *rq,
  1497. struct request *next)
  1498. {
  1499. struct bfq_queue *bfqq = RQ_BFQQ(rq), *next_bfqq = RQ_BFQQ(next);
  1500. if (!RB_EMPTY_NODE(&rq->rb_node))
  1501. goto end;
  1502. spin_lock_irq(&bfqq->bfqd->lock);
  1503. /*
  1504. * If next and rq belong to the same bfq_queue and next is older
  1505. * than rq, then reposition rq in the fifo (by substituting next
  1506. * with rq). Otherwise, if next and rq belong to different
  1507. * bfq_queues, never reposition rq: in fact, we would have to
  1508. * reposition it with respect to next's position in its own fifo,
  1509. * which would most certainly be too expensive with respect to
  1510. * the benefits.
  1511. */
  1512. if (bfqq == next_bfqq &&
  1513. !list_empty(&rq->queuelist) && !list_empty(&next->queuelist) &&
  1514. next->fifo_time < rq->fifo_time) {
  1515. list_del_init(&rq->queuelist);
  1516. list_replace_init(&next->queuelist, &rq->queuelist);
  1517. rq->fifo_time = next->fifo_time;
  1518. }
  1519. if (bfqq->next_rq == next)
  1520. bfqq->next_rq = rq;
  1521. bfq_remove_request(q, next);
  1522. spin_unlock_irq(&bfqq->bfqd->lock);
  1523. end:
  1524. bfqg_stats_update_io_merged(bfqq_group(bfqq), next->cmd_flags);
  1525. }
  1526. /* Must be called with bfqq != NULL */
  1527. static void bfq_bfqq_end_wr(struct bfq_queue *bfqq)
  1528. {
  1529. if (bfq_bfqq_busy(bfqq))
  1530. bfqq->bfqd->wr_busy_queues--;
  1531. bfqq->wr_coeff = 1;
  1532. bfqq->wr_cur_max_time = 0;
  1533. bfqq->last_wr_start_finish = jiffies;
  1534. /*
  1535. * Trigger a weight change on the next invocation of
  1536. * __bfq_entity_update_weight_prio.
  1537. */
  1538. bfqq->entity.prio_changed = 1;
  1539. }
  1540. void bfq_end_wr_async_queues(struct bfq_data *bfqd,
  1541. struct bfq_group *bfqg)
  1542. {
  1543. int i, j;
  1544. for (i = 0; i < 2; i++)
  1545. for (j = 0; j < IOPRIO_BE_NR; j++)
  1546. if (bfqg->async_bfqq[i][j])
  1547. bfq_bfqq_end_wr(bfqg->async_bfqq[i][j]);
  1548. if (bfqg->async_idle_bfqq)
  1549. bfq_bfqq_end_wr(bfqg->async_idle_bfqq);
  1550. }
  1551. static void bfq_end_wr(struct bfq_data *bfqd)
  1552. {
  1553. struct bfq_queue *bfqq;
  1554. spin_lock_irq(&bfqd->lock);
  1555. list_for_each_entry(bfqq, &bfqd->active_list, bfqq_list)
  1556. bfq_bfqq_end_wr(bfqq);
  1557. list_for_each_entry(bfqq, &bfqd->idle_list, bfqq_list)
  1558. bfq_bfqq_end_wr(bfqq);
  1559. bfq_end_wr_async(bfqd);
  1560. spin_unlock_irq(&bfqd->lock);
  1561. }
  1562. static sector_t bfq_io_struct_pos(void *io_struct, bool request)
  1563. {
  1564. if (request)
  1565. return blk_rq_pos(io_struct);
  1566. else
  1567. return ((struct bio *)io_struct)->bi_iter.bi_sector;
  1568. }
  1569. static int bfq_rq_close_to_sector(void *io_struct, bool request,
  1570. sector_t sector)
  1571. {
  1572. return abs(bfq_io_struct_pos(io_struct, request) - sector) <=
  1573. BFQQ_CLOSE_THR;
  1574. }
  1575. static struct bfq_queue *bfqq_find_close(struct bfq_data *bfqd,
  1576. struct bfq_queue *bfqq,
  1577. sector_t sector)
  1578. {
  1579. struct rb_root *root = &bfq_bfqq_to_bfqg(bfqq)->rq_pos_tree;
  1580. struct rb_node *parent, *node;
  1581. struct bfq_queue *__bfqq;
  1582. if (RB_EMPTY_ROOT(root))
  1583. return NULL;
  1584. /*
  1585. * First, if we find a request starting at the end of the last
  1586. * request, choose it.
  1587. */
  1588. __bfqq = bfq_rq_pos_tree_lookup(bfqd, root, sector, &parent, NULL);
  1589. if (__bfqq)
  1590. return __bfqq;
  1591. /*
  1592. * If the exact sector wasn't found, the parent of the NULL leaf
  1593. * will contain the closest sector (rq_pos_tree sorted by
  1594. * next_request position).
  1595. */
  1596. __bfqq = rb_entry(parent, struct bfq_queue, pos_node);
  1597. if (bfq_rq_close_to_sector(__bfqq->next_rq, true, sector))
  1598. return __bfqq;
  1599. if (blk_rq_pos(__bfqq->next_rq) < sector)
  1600. node = rb_next(&__bfqq->pos_node);
  1601. else
  1602. node = rb_prev(&__bfqq->pos_node);
  1603. if (!node)
  1604. return NULL;
  1605. __bfqq = rb_entry(node, struct bfq_queue, pos_node);
  1606. if (bfq_rq_close_to_sector(__bfqq->next_rq, true, sector))
  1607. return __bfqq;
  1608. return NULL;
  1609. }
  1610. static struct bfq_queue *bfq_find_close_cooperator(struct bfq_data *bfqd,
  1611. struct bfq_queue *cur_bfqq,
  1612. sector_t sector)
  1613. {
  1614. struct bfq_queue *bfqq;
  1615. /*
  1616. * We shall notice if some of the queues are cooperating,
  1617. * e.g., working closely on the same area of the device. In
  1618. * that case, we can group them together and: 1) don't waste
  1619. * time idling, and 2) serve the union of their requests in
  1620. * the best possible order for throughput.
  1621. */
  1622. bfqq = bfqq_find_close(bfqd, cur_bfqq, sector);
  1623. if (!bfqq || bfqq == cur_bfqq)
  1624. return NULL;
  1625. return bfqq;
  1626. }
  1627. static struct bfq_queue *
  1628. bfq_setup_merge(struct bfq_queue *bfqq, struct bfq_queue *new_bfqq)
  1629. {
  1630. int process_refs, new_process_refs;
  1631. struct bfq_queue *__bfqq;
  1632. /*
  1633. * If there are no process references on the new_bfqq, then it is
  1634. * unsafe to follow the ->new_bfqq chain as other bfqq's in the chain
  1635. * may have dropped their last reference (not just their last process
  1636. * reference).
  1637. */
  1638. if (!bfqq_process_refs(new_bfqq))
  1639. return NULL;
  1640. /* Avoid a circular list and skip interim queue merges. */
  1641. while ((__bfqq = new_bfqq->new_bfqq)) {
  1642. if (__bfqq == bfqq)
  1643. return NULL;
  1644. new_bfqq = __bfqq;
  1645. }
  1646. process_refs = bfqq_process_refs(bfqq);
  1647. new_process_refs = bfqq_process_refs(new_bfqq);
  1648. /*
  1649. * If the process for the bfqq has gone away, there is no
  1650. * sense in merging the queues.
  1651. */
  1652. if (process_refs == 0 || new_process_refs == 0)
  1653. return NULL;
  1654. bfq_log_bfqq(bfqq->bfqd, bfqq, "scheduling merge with queue %d",
  1655. new_bfqq->pid);
  1656. /*
  1657. * Merging is just a redirection: the requests of the process
  1658. * owning one of the two queues are redirected to the other queue.
  1659. * The latter queue, in its turn, is set as shared if this is the
  1660. * first time that the requests of some process are redirected to
  1661. * it.
  1662. *
  1663. * We redirect bfqq to new_bfqq and not the opposite, because
  1664. * we are in the context of the process owning bfqq, thus we
  1665. * have the io_cq of this process. So we can immediately
  1666. * configure this io_cq to redirect the requests of the
  1667. * process to new_bfqq. In contrast, the io_cq of new_bfqq is
  1668. * not available any more (new_bfqq->bic == NULL).
  1669. *
  1670. * Anyway, even in case new_bfqq coincides with the in-service
  1671. * queue, redirecting requests the in-service queue is the
  1672. * best option, as we feed the in-service queue with new
  1673. * requests close to the last request served and, by doing so,
  1674. * are likely to increase the throughput.
  1675. */
  1676. bfqq->new_bfqq = new_bfqq;
  1677. new_bfqq->ref += process_refs;
  1678. return new_bfqq;
  1679. }
  1680. static bool bfq_may_be_close_cooperator(struct bfq_queue *bfqq,
  1681. struct bfq_queue *new_bfqq)
  1682. {
  1683. if (bfq_class_idle(bfqq) || bfq_class_idle(new_bfqq) ||
  1684. (bfqq->ioprio_class != new_bfqq->ioprio_class))
  1685. return false;
  1686. /*
  1687. * If either of the queues has already been detected as seeky,
  1688. * then merging it with the other queue is unlikely to lead to
  1689. * sequential I/O.
  1690. */
  1691. if (BFQQ_SEEKY(bfqq) || BFQQ_SEEKY(new_bfqq))
  1692. return false;
  1693. /*
  1694. * Interleaved I/O is known to be done by (some) applications
  1695. * only for reads, so it does not make sense to merge async
  1696. * queues.
  1697. */
  1698. if (!bfq_bfqq_sync(bfqq) || !bfq_bfqq_sync(new_bfqq))
  1699. return false;
  1700. return true;
  1701. }
  1702. /*
  1703. * If this function returns true, then bfqq cannot be merged. The idea
  1704. * is that true cooperation happens very early after processes start
  1705. * to do I/O. Usually, late cooperations are just accidental false
  1706. * positives. In case bfqq is weight-raised, such false positives
  1707. * would evidently degrade latency guarantees for bfqq.
  1708. */
  1709. static bool wr_from_too_long(struct bfq_queue *bfqq)
  1710. {
  1711. return bfqq->wr_coeff > 1 &&
  1712. time_is_before_jiffies(bfqq->last_wr_start_finish +
  1713. msecs_to_jiffies(100));
  1714. }
  1715. /*
  1716. * Attempt to schedule a merge of bfqq with the currently in-service
  1717. * queue or with a close queue among the scheduled queues. Return
  1718. * NULL if no merge was scheduled, a pointer to the shared bfq_queue
  1719. * structure otherwise.
  1720. *
  1721. * The OOM queue is not allowed to participate to cooperation: in fact, since
  1722. * the requests temporarily redirected to the OOM queue could be redirected
  1723. * again to dedicated queues at any time, the state needed to correctly
  1724. * handle merging with the OOM queue would be quite complex and expensive
  1725. * to maintain. Besides, in such a critical condition as an out of memory,
  1726. * the benefits of queue merging may be little relevant, or even negligible.
  1727. *
  1728. * Weight-raised queues can be merged only if their weight-raising
  1729. * period has just started. In fact cooperating processes are usually
  1730. * started together. Thus, with this filter we avoid false positives
  1731. * that would jeopardize low-latency guarantees.
  1732. *
  1733. * WARNING: queue merging may impair fairness among non-weight raised
  1734. * queues, for at least two reasons: 1) the original weight of a
  1735. * merged queue may change during the merged state, 2) even being the
  1736. * weight the same, a merged queue may be bloated with many more
  1737. * requests than the ones produced by its originally-associated
  1738. * process.
  1739. */
  1740. static struct bfq_queue *
  1741. bfq_setup_cooperator(struct bfq_data *bfqd, struct bfq_queue *bfqq,
  1742. void *io_struct, bool request)
  1743. {
  1744. struct bfq_queue *in_service_bfqq, *new_bfqq;
  1745. if (bfqq->new_bfqq)
  1746. return bfqq->new_bfqq;
  1747. if (!io_struct ||
  1748. wr_from_too_long(bfqq) ||
  1749. unlikely(bfqq == &bfqd->oom_bfqq))
  1750. return NULL;
  1751. /* If there is only one backlogged queue, don't search. */
  1752. if (bfqd->busy_queues == 1)
  1753. return NULL;
  1754. in_service_bfqq = bfqd->in_service_queue;
  1755. if (!in_service_bfqq || in_service_bfqq == bfqq
  1756. || wr_from_too_long(in_service_bfqq) ||
  1757. unlikely(in_service_bfqq == &bfqd->oom_bfqq))
  1758. goto check_scheduled;
  1759. if (bfq_rq_close_to_sector(io_struct, request, bfqd->last_position) &&
  1760. bfqq->entity.parent == in_service_bfqq->entity.parent &&
  1761. bfq_may_be_close_cooperator(bfqq, in_service_bfqq)) {
  1762. new_bfqq = bfq_setup_merge(bfqq, in_service_bfqq);
  1763. if (new_bfqq)
  1764. return new_bfqq;
  1765. }
  1766. /*
  1767. * Check whether there is a cooperator among currently scheduled
  1768. * queues. The only thing we need is that the bio/request is not
  1769. * NULL, as we need it to establish whether a cooperator exists.
  1770. */
  1771. check_scheduled:
  1772. new_bfqq = bfq_find_close_cooperator(bfqd, bfqq,
  1773. bfq_io_struct_pos(io_struct, request));
  1774. if (new_bfqq && !wr_from_too_long(new_bfqq) &&
  1775. likely(new_bfqq != &bfqd->oom_bfqq) &&
  1776. bfq_may_be_close_cooperator(bfqq, new_bfqq))
  1777. return bfq_setup_merge(bfqq, new_bfqq);
  1778. return NULL;
  1779. }
  1780. static void bfq_bfqq_save_state(struct bfq_queue *bfqq)
  1781. {
  1782. struct bfq_io_cq *bic = bfqq->bic;
  1783. /*
  1784. * If !bfqq->bic, the queue is already shared or its requests
  1785. * have already been redirected to a shared queue; both idle window
  1786. * and weight raising state have already been saved. Do nothing.
  1787. */
  1788. if (!bic)
  1789. return;
  1790. bic->saved_ttime = bfqq->ttime;
  1791. bic->saved_has_short_ttime = bfq_bfqq_has_short_ttime(bfqq);
  1792. bic->saved_IO_bound = bfq_bfqq_IO_bound(bfqq);
  1793. bic->saved_in_large_burst = bfq_bfqq_in_large_burst(bfqq);
  1794. bic->was_in_burst_list = !hlist_unhashed(&bfqq->burst_list_node);
  1795. bic->saved_wr_coeff = bfqq->wr_coeff;
  1796. bic->saved_wr_start_at_switch_to_srt = bfqq->wr_start_at_switch_to_srt;
  1797. bic->saved_last_wr_start_finish = bfqq->last_wr_start_finish;
  1798. bic->saved_wr_cur_max_time = bfqq->wr_cur_max_time;
  1799. }
  1800. static void
  1801. bfq_merge_bfqqs(struct bfq_data *bfqd, struct bfq_io_cq *bic,
  1802. struct bfq_queue *bfqq, struct bfq_queue *new_bfqq)
  1803. {
  1804. bfq_log_bfqq(bfqd, bfqq, "merging with queue %lu",
  1805. (unsigned long)new_bfqq->pid);
  1806. /* Save weight raising and idle window of the merged queues */
  1807. bfq_bfqq_save_state(bfqq);
  1808. bfq_bfqq_save_state(new_bfqq);
  1809. if (bfq_bfqq_IO_bound(bfqq))
  1810. bfq_mark_bfqq_IO_bound(new_bfqq);
  1811. bfq_clear_bfqq_IO_bound(bfqq);
  1812. /*
  1813. * If bfqq is weight-raised, then let new_bfqq inherit
  1814. * weight-raising. To reduce false positives, neglect the case
  1815. * where bfqq has just been created, but has not yet made it
  1816. * to be weight-raised (which may happen because EQM may merge
  1817. * bfqq even before bfq_add_request is executed for the first
  1818. * time for bfqq). Handling this case would however be very
  1819. * easy, thanks to the flag just_created.
  1820. */
  1821. if (new_bfqq->wr_coeff == 1 && bfqq->wr_coeff > 1) {
  1822. new_bfqq->wr_coeff = bfqq->wr_coeff;
  1823. new_bfqq->wr_cur_max_time = bfqq->wr_cur_max_time;
  1824. new_bfqq->last_wr_start_finish = bfqq->last_wr_start_finish;
  1825. new_bfqq->wr_start_at_switch_to_srt =
  1826. bfqq->wr_start_at_switch_to_srt;
  1827. if (bfq_bfqq_busy(new_bfqq))
  1828. bfqd->wr_busy_queues++;
  1829. new_bfqq->entity.prio_changed = 1;
  1830. }
  1831. if (bfqq->wr_coeff > 1) { /* bfqq has given its wr to new_bfqq */
  1832. bfqq->wr_coeff = 1;
  1833. bfqq->entity.prio_changed = 1;
  1834. if (bfq_bfqq_busy(bfqq))
  1835. bfqd->wr_busy_queues--;
  1836. }
  1837. bfq_log_bfqq(bfqd, new_bfqq, "merge_bfqqs: wr_busy %d",
  1838. bfqd->wr_busy_queues);
  1839. /*
  1840. * Merge queues (that is, let bic redirect its requests to new_bfqq)
  1841. */
  1842. bic_set_bfqq(bic, new_bfqq, 1);
  1843. bfq_mark_bfqq_coop(new_bfqq);
  1844. /*
  1845. * new_bfqq now belongs to at least two bics (it is a shared queue):
  1846. * set new_bfqq->bic to NULL. bfqq either:
  1847. * - does not belong to any bic any more, and hence bfqq->bic must
  1848. * be set to NULL, or
  1849. * - is a queue whose owning bics have already been redirected to a
  1850. * different queue, hence the queue is destined to not belong to
  1851. * any bic soon and bfqq->bic is already NULL (therefore the next
  1852. * assignment causes no harm).
  1853. */
  1854. new_bfqq->bic = NULL;
  1855. bfqq->bic = NULL;
  1856. /* release process reference to bfqq */
  1857. bfq_put_queue(bfqq);
  1858. }
  1859. static bool bfq_allow_bio_merge(struct request_queue *q, struct request *rq,
  1860. struct bio *bio)
  1861. {
  1862. struct bfq_data *bfqd = q->elevator->elevator_data;
  1863. bool is_sync = op_is_sync(bio->bi_opf);
  1864. struct bfq_queue *bfqq = bfqd->bio_bfqq, *new_bfqq;
  1865. /*
  1866. * Disallow merge of a sync bio into an async request.
  1867. */
  1868. if (is_sync && !rq_is_sync(rq))
  1869. return false;
  1870. /*
  1871. * Lookup the bfqq that this bio will be queued with. Allow
  1872. * merge only if rq is queued there.
  1873. */
  1874. if (!bfqq)
  1875. return false;
  1876. /*
  1877. * We take advantage of this function to perform an early merge
  1878. * of the queues of possible cooperating processes.
  1879. */
  1880. new_bfqq = bfq_setup_cooperator(bfqd, bfqq, bio, false);
  1881. if (new_bfqq) {
  1882. /*
  1883. * bic still points to bfqq, then it has not yet been
  1884. * redirected to some other bfq_queue, and a queue
  1885. * merge beween bfqq and new_bfqq can be safely
  1886. * fulfillled, i.e., bic can be redirected to new_bfqq
  1887. * and bfqq can be put.
  1888. */
  1889. bfq_merge_bfqqs(bfqd, bfqd->bio_bic, bfqq,
  1890. new_bfqq);
  1891. /*
  1892. * If we get here, bio will be queued into new_queue,
  1893. * so use new_bfqq to decide whether bio and rq can be
  1894. * merged.
  1895. */
  1896. bfqq = new_bfqq;
  1897. /*
  1898. * Change also bqfd->bio_bfqq, as
  1899. * bfqd->bio_bic now points to new_bfqq, and
  1900. * this function may be invoked again (and then may
  1901. * use again bqfd->bio_bfqq).
  1902. */
  1903. bfqd->bio_bfqq = bfqq;
  1904. }
  1905. return bfqq == RQ_BFQQ(rq);
  1906. }
  1907. /*
  1908. * Set the maximum time for the in-service queue to consume its
  1909. * budget. This prevents seeky processes from lowering the throughput.
  1910. * In practice, a time-slice service scheme is used with seeky
  1911. * processes.
  1912. */
  1913. static void bfq_set_budget_timeout(struct bfq_data *bfqd,
  1914. struct bfq_queue *bfqq)
  1915. {
  1916. unsigned int timeout_coeff;
  1917. if (bfqq->wr_cur_max_time == bfqd->bfq_wr_rt_max_time)
  1918. timeout_coeff = 1;
  1919. else
  1920. timeout_coeff = bfqq->entity.weight / bfqq->entity.orig_weight;
  1921. bfqd->last_budget_start = ktime_get();
  1922. bfqq->budget_timeout = jiffies +
  1923. bfqd->bfq_timeout * timeout_coeff;
  1924. }
  1925. static void __bfq_set_in_service_queue(struct bfq_data *bfqd,
  1926. struct bfq_queue *bfqq)
  1927. {
  1928. if (bfqq) {
  1929. bfqg_stats_update_avg_queue_size(bfqq_group(bfqq));
  1930. bfq_clear_bfqq_fifo_expire(bfqq);
  1931. bfqd->budgets_assigned = (bfqd->budgets_assigned * 7 + 256) / 8;
  1932. if (time_is_before_jiffies(bfqq->last_wr_start_finish) &&
  1933. bfqq->wr_coeff > 1 &&
  1934. bfqq->wr_cur_max_time == bfqd->bfq_wr_rt_max_time &&
  1935. time_is_before_jiffies(bfqq->budget_timeout)) {
  1936. /*
  1937. * For soft real-time queues, move the start
  1938. * of the weight-raising period forward by the
  1939. * time the queue has not received any
  1940. * service. Otherwise, a relatively long
  1941. * service delay is likely to cause the
  1942. * weight-raising period of the queue to end,
  1943. * because of the short duration of the
  1944. * weight-raising period of a soft real-time
  1945. * queue. It is worth noting that this move
  1946. * is not so dangerous for the other queues,
  1947. * because soft real-time queues are not
  1948. * greedy.
  1949. *
  1950. * To not add a further variable, we use the
  1951. * overloaded field budget_timeout to
  1952. * determine for how long the queue has not
  1953. * received service, i.e., how much time has
  1954. * elapsed since the queue expired. However,
  1955. * this is a little imprecise, because
  1956. * budget_timeout is set to jiffies if bfqq
  1957. * not only expires, but also remains with no
  1958. * request.
  1959. */
  1960. if (time_after(bfqq->budget_timeout,
  1961. bfqq->last_wr_start_finish))
  1962. bfqq->last_wr_start_finish +=
  1963. jiffies - bfqq->budget_timeout;
  1964. else
  1965. bfqq->last_wr_start_finish = jiffies;
  1966. }
  1967. bfq_set_budget_timeout(bfqd, bfqq);
  1968. bfq_log_bfqq(bfqd, bfqq,
  1969. "set_in_service_queue, cur-budget = %d",
  1970. bfqq->entity.budget);
  1971. }
  1972. bfqd->in_service_queue = bfqq;
  1973. }
  1974. /*
  1975. * Get and set a new queue for service.
  1976. */
  1977. static struct bfq_queue *bfq_set_in_service_queue(struct bfq_data *bfqd)
  1978. {
  1979. struct bfq_queue *bfqq = bfq_get_next_queue(bfqd);
  1980. __bfq_set_in_service_queue(bfqd, bfqq);
  1981. return bfqq;
  1982. }
  1983. static void bfq_arm_slice_timer(struct bfq_data *bfqd)
  1984. {
  1985. struct bfq_queue *bfqq = bfqd->in_service_queue;
  1986. u32 sl;
  1987. bfq_mark_bfqq_wait_request(bfqq);
  1988. /*
  1989. * We don't want to idle for seeks, but we do want to allow
  1990. * fair distribution of slice time for a process doing back-to-back
  1991. * seeks. So allow a little bit of time for him to submit a new rq.
  1992. */
  1993. sl = bfqd->bfq_slice_idle;
  1994. /*
  1995. * Unless the queue is being weight-raised or the scenario is
  1996. * asymmetric, grant only minimum idle time if the queue
  1997. * is seeky. A long idling is preserved for a weight-raised
  1998. * queue, or, more in general, in an asymmetric scenario,
  1999. * because a long idling is needed for guaranteeing to a queue
  2000. * its reserved share of the throughput (in particular, it is
  2001. * needed if the queue has a higher weight than some other
  2002. * queue).
  2003. */
  2004. if (BFQQ_SEEKY(bfqq) && bfqq->wr_coeff == 1 &&
  2005. bfq_symmetric_scenario(bfqd))
  2006. sl = min_t(u64, sl, BFQ_MIN_TT);
  2007. bfqd->last_idling_start = ktime_get();
  2008. hrtimer_start(&bfqd->idle_slice_timer, ns_to_ktime(sl),
  2009. HRTIMER_MODE_REL);
  2010. bfqg_stats_set_start_idle_time(bfqq_group(bfqq));
  2011. }
  2012. /*
  2013. * In autotuning mode, max_budget is dynamically recomputed as the
  2014. * amount of sectors transferred in timeout at the estimated peak
  2015. * rate. This enables BFQ to utilize a full timeslice with a full
  2016. * budget, even if the in-service queue is served at peak rate. And
  2017. * this maximises throughput with sequential workloads.
  2018. */
  2019. static unsigned long bfq_calc_max_budget(struct bfq_data *bfqd)
  2020. {
  2021. return (u64)bfqd->peak_rate * USEC_PER_MSEC *
  2022. jiffies_to_msecs(bfqd->bfq_timeout)>>BFQ_RATE_SHIFT;
  2023. }
  2024. /*
  2025. * Update parameters related to throughput and responsiveness, as a
  2026. * function of the estimated peak rate. See comments on
  2027. * bfq_calc_max_budget(), and on T_slow and T_fast arrays.
  2028. */
  2029. static void update_thr_responsiveness_params(struct bfq_data *bfqd)
  2030. {
  2031. int dev_type = blk_queue_nonrot(bfqd->queue);
  2032. if (bfqd->bfq_user_max_budget == 0)
  2033. bfqd->bfq_max_budget =
  2034. bfq_calc_max_budget(bfqd);
  2035. if (bfqd->device_speed == BFQ_BFQD_FAST &&
  2036. bfqd->peak_rate < device_speed_thresh[dev_type]) {
  2037. bfqd->device_speed = BFQ_BFQD_SLOW;
  2038. bfqd->RT_prod = R_slow[dev_type] *
  2039. T_slow[dev_type];
  2040. } else if (bfqd->device_speed == BFQ_BFQD_SLOW &&
  2041. bfqd->peak_rate > device_speed_thresh[dev_type]) {
  2042. bfqd->device_speed = BFQ_BFQD_FAST;
  2043. bfqd->RT_prod = R_fast[dev_type] *
  2044. T_fast[dev_type];
  2045. }
  2046. bfq_log(bfqd,
  2047. "dev_type %s dev_speed_class = %s (%llu sects/sec), thresh %llu setcs/sec",
  2048. dev_type == 0 ? "ROT" : "NONROT",
  2049. bfqd->device_speed == BFQ_BFQD_FAST ? "FAST" : "SLOW",
  2050. bfqd->device_speed == BFQ_BFQD_FAST ?
  2051. (USEC_PER_SEC*(u64)R_fast[dev_type])>>BFQ_RATE_SHIFT :
  2052. (USEC_PER_SEC*(u64)R_slow[dev_type])>>BFQ_RATE_SHIFT,
  2053. (USEC_PER_SEC*(u64)device_speed_thresh[dev_type])>>
  2054. BFQ_RATE_SHIFT);
  2055. }
  2056. static void bfq_reset_rate_computation(struct bfq_data *bfqd,
  2057. struct request *rq)
  2058. {
  2059. if (rq != NULL) { /* new rq dispatch now, reset accordingly */
  2060. bfqd->last_dispatch = bfqd->first_dispatch = ktime_get_ns();
  2061. bfqd->peak_rate_samples = 1;
  2062. bfqd->sequential_samples = 0;
  2063. bfqd->tot_sectors_dispatched = bfqd->last_rq_max_size =
  2064. blk_rq_sectors(rq);
  2065. } else /* no new rq dispatched, just reset the number of samples */
  2066. bfqd->peak_rate_samples = 0; /* full re-init on next disp. */
  2067. bfq_log(bfqd,
  2068. "reset_rate_computation at end, sample %u/%u tot_sects %llu",
  2069. bfqd->peak_rate_samples, bfqd->sequential_samples,
  2070. bfqd->tot_sectors_dispatched);
  2071. }
  2072. static void bfq_update_rate_reset(struct bfq_data *bfqd, struct request *rq)
  2073. {
  2074. u32 rate, weight, divisor;
  2075. /*
  2076. * For the convergence property to hold (see comments on
  2077. * bfq_update_peak_rate()) and for the assessment to be
  2078. * reliable, a minimum number of samples must be present, and
  2079. * a minimum amount of time must have elapsed. If not so, do
  2080. * not compute new rate. Just reset parameters, to get ready
  2081. * for a new evaluation attempt.
  2082. */
  2083. if (bfqd->peak_rate_samples < BFQ_RATE_MIN_SAMPLES ||
  2084. bfqd->delta_from_first < BFQ_RATE_MIN_INTERVAL)
  2085. goto reset_computation;
  2086. /*
  2087. * If a new request completion has occurred after last
  2088. * dispatch, then, to approximate the rate at which requests
  2089. * have been served by the device, it is more precise to
  2090. * extend the observation interval to the last completion.
  2091. */
  2092. bfqd->delta_from_first =
  2093. max_t(u64, bfqd->delta_from_first,
  2094. bfqd->last_completion - bfqd->first_dispatch);
  2095. /*
  2096. * Rate computed in sects/usec, and not sects/nsec, for
  2097. * precision issues.
  2098. */
  2099. rate = div64_ul(bfqd->tot_sectors_dispatched<<BFQ_RATE_SHIFT,
  2100. div_u64(bfqd->delta_from_first, NSEC_PER_USEC));
  2101. /*
  2102. * Peak rate not updated if:
  2103. * - the percentage of sequential dispatches is below 3/4 of the
  2104. * total, and rate is below the current estimated peak rate
  2105. * - rate is unreasonably high (> 20M sectors/sec)
  2106. */
  2107. if ((bfqd->sequential_samples < (3 * bfqd->peak_rate_samples)>>2 &&
  2108. rate <= bfqd->peak_rate) ||
  2109. rate > 20<<BFQ_RATE_SHIFT)
  2110. goto reset_computation;
  2111. /*
  2112. * We have to update the peak rate, at last! To this purpose,
  2113. * we use a low-pass filter. We compute the smoothing constant
  2114. * of the filter as a function of the 'weight' of the new
  2115. * measured rate.
  2116. *
  2117. * As can be seen in next formulas, we define this weight as a
  2118. * quantity proportional to how sequential the workload is,
  2119. * and to how long the observation time interval is.
  2120. *
  2121. * The weight runs from 0 to 8. The maximum value of the
  2122. * weight, 8, yields the minimum value for the smoothing
  2123. * constant. At this minimum value for the smoothing constant,
  2124. * the measured rate contributes for half of the next value of
  2125. * the estimated peak rate.
  2126. *
  2127. * So, the first step is to compute the weight as a function
  2128. * of how sequential the workload is. Note that the weight
  2129. * cannot reach 9, because bfqd->sequential_samples cannot
  2130. * become equal to bfqd->peak_rate_samples, which, in its
  2131. * turn, holds true because bfqd->sequential_samples is not
  2132. * incremented for the first sample.
  2133. */
  2134. weight = (9 * bfqd->sequential_samples) / bfqd->peak_rate_samples;
  2135. /*
  2136. * Second step: further refine the weight as a function of the
  2137. * duration of the observation interval.
  2138. */
  2139. weight = min_t(u32, 8,
  2140. div_u64(weight * bfqd->delta_from_first,
  2141. BFQ_RATE_REF_INTERVAL));
  2142. /*
  2143. * Divisor ranging from 10, for minimum weight, to 2, for
  2144. * maximum weight.
  2145. */
  2146. divisor = 10 - weight;
  2147. /*
  2148. * Finally, update peak rate:
  2149. *
  2150. * peak_rate = peak_rate * (divisor-1) / divisor + rate / divisor
  2151. */
  2152. bfqd->peak_rate *= divisor-1;
  2153. bfqd->peak_rate /= divisor;
  2154. rate /= divisor; /* smoothing constant alpha = 1/divisor */
  2155. bfqd->peak_rate += rate;
  2156. update_thr_responsiveness_params(bfqd);
  2157. reset_computation:
  2158. bfq_reset_rate_computation(bfqd, rq);
  2159. }
  2160. /*
  2161. * Update the read/write peak rate (the main quantity used for
  2162. * auto-tuning, see update_thr_responsiveness_params()).
  2163. *
  2164. * It is not trivial to estimate the peak rate (correctly): because of
  2165. * the presence of sw and hw queues between the scheduler and the
  2166. * device components that finally serve I/O requests, it is hard to
  2167. * say exactly when a given dispatched request is served inside the
  2168. * device, and for how long. As a consequence, it is hard to know
  2169. * precisely at what rate a given set of requests is actually served
  2170. * by the device.
  2171. *
  2172. * On the opposite end, the dispatch time of any request is trivially
  2173. * available, and, from this piece of information, the "dispatch rate"
  2174. * of requests can be immediately computed. So, the idea in the next
  2175. * function is to use what is known, namely request dispatch times
  2176. * (plus, when useful, request completion times), to estimate what is
  2177. * unknown, namely in-device request service rate.
  2178. *
  2179. * The main issue is that, because of the above facts, the rate at
  2180. * which a certain set of requests is dispatched over a certain time
  2181. * interval can vary greatly with respect to the rate at which the
  2182. * same requests are then served. But, since the size of any
  2183. * intermediate queue is limited, and the service scheme is lossless
  2184. * (no request is silently dropped), the following obvious convergence
  2185. * property holds: the number of requests dispatched MUST become
  2186. * closer and closer to the number of requests completed as the
  2187. * observation interval grows. This is the key property used in
  2188. * the next function to estimate the peak service rate as a function
  2189. * of the observed dispatch rate. The function assumes to be invoked
  2190. * on every request dispatch.
  2191. */
  2192. static void bfq_update_peak_rate(struct bfq_data *bfqd, struct request *rq)
  2193. {
  2194. u64 now_ns = ktime_get_ns();
  2195. if (bfqd->peak_rate_samples == 0) { /* first dispatch */
  2196. bfq_log(bfqd, "update_peak_rate: goto reset, samples %d",
  2197. bfqd->peak_rate_samples);
  2198. bfq_reset_rate_computation(bfqd, rq);
  2199. goto update_last_values; /* will add one sample */
  2200. }
  2201. /*
  2202. * Device idle for very long: the observation interval lasting
  2203. * up to this dispatch cannot be a valid observation interval
  2204. * for computing a new peak rate (similarly to the late-
  2205. * completion event in bfq_completed_request()). Go to
  2206. * update_rate_and_reset to have the following three steps
  2207. * taken:
  2208. * - close the observation interval at the last (previous)
  2209. * request dispatch or completion
  2210. * - compute rate, if possible, for that observation interval
  2211. * - start a new observation interval with this dispatch
  2212. */
  2213. if (now_ns - bfqd->last_dispatch > 100*NSEC_PER_MSEC &&
  2214. bfqd->rq_in_driver == 0)
  2215. goto update_rate_and_reset;
  2216. /* Update sampling information */
  2217. bfqd->peak_rate_samples++;
  2218. if ((bfqd->rq_in_driver > 0 ||
  2219. now_ns - bfqd->last_completion < BFQ_MIN_TT)
  2220. && get_sdist(bfqd->last_position, rq) < BFQQ_SEEK_THR)
  2221. bfqd->sequential_samples++;
  2222. bfqd->tot_sectors_dispatched += blk_rq_sectors(rq);
  2223. /* Reset max observed rq size every 32 dispatches */
  2224. if (likely(bfqd->peak_rate_samples % 32))
  2225. bfqd->last_rq_max_size =
  2226. max_t(u32, blk_rq_sectors(rq), bfqd->last_rq_max_size);
  2227. else
  2228. bfqd->last_rq_max_size = blk_rq_sectors(rq);
  2229. bfqd->delta_from_first = now_ns - bfqd->first_dispatch;
  2230. /* Target observation interval not yet reached, go on sampling */
  2231. if (bfqd->delta_from_first < BFQ_RATE_REF_INTERVAL)
  2232. goto update_last_values;
  2233. update_rate_and_reset:
  2234. bfq_update_rate_reset(bfqd, rq);
  2235. update_last_values:
  2236. bfqd->last_position = blk_rq_pos(rq) + blk_rq_sectors(rq);
  2237. bfqd->last_dispatch = now_ns;
  2238. }
  2239. /*
  2240. * Remove request from internal lists.
  2241. */
  2242. static void bfq_dispatch_remove(struct request_queue *q, struct request *rq)
  2243. {
  2244. struct bfq_queue *bfqq = RQ_BFQQ(rq);
  2245. /*
  2246. * For consistency, the next instruction should have been
  2247. * executed after removing the request from the queue and
  2248. * dispatching it. We execute instead this instruction before
  2249. * bfq_remove_request() (and hence introduce a temporary
  2250. * inconsistency), for efficiency. In fact, should this
  2251. * dispatch occur for a non in-service bfqq, this anticipated
  2252. * increment prevents two counters related to bfqq->dispatched
  2253. * from risking to be, first, uselessly decremented, and then
  2254. * incremented again when the (new) value of bfqq->dispatched
  2255. * happens to be taken into account.
  2256. */
  2257. bfqq->dispatched++;
  2258. bfq_update_peak_rate(q->elevator->elevator_data, rq);
  2259. bfq_remove_request(q, rq);
  2260. }
  2261. static void __bfq_bfqq_expire(struct bfq_data *bfqd, struct bfq_queue *bfqq)
  2262. {
  2263. /*
  2264. * If this bfqq is shared between multiple processes, check
  2265. * to make sure that those processes are still issuing I/Os
  2266. * within the mean seek distance. If not, it may be time to
  2267. * break the queues apart again.
  2268. */
  2269. if (bfq_bfqq_coop(bfqq) && BFQQ_SEEKY(bfqq))
  2270. bfq_mark_bfqq_split_coop(bfqq);
  2271. if (RB_EMPTY_ROOT(&bfqq->sort_list)) {
  2272. if (bfqq->dispatched == 0)
  2273. /*
  2274. * Overloading budget_timeout field to store
  2275. * the time at which the queue remains with no
  2276. * backlog and no outstanding request; used by
  2277. * the weight-raising mechanism.
  2278. */
  2279. bfqq->budget_timeout = jiffies;
  2280. bfq_del_bfqq_busy(bfqd, bfqq, true);
  2281. } else {
  2282. bfq_requeue_bfqq(bfqd, bfqq, true);
  2283. /*
  2284. * Resort priority tree of potential close cooperators.
  2285. */
  2286. bfq_pos_tree_add_move(bfqd, bfqq);
  2287. }
  2288. /*
  2289. * All in-service entities must have been properly deactivated
  2290. * or requeued before executing the next function, which
  2291. * resets all in-service entites as no more in service.
  2292. */
  2293. __bfq_bfqd_reset_in_service(bfqd);
  2294. }
  2295. /**
  2296. * __bfq_bfqq_recalc_budget - try to adapt the budget to the @bfqq behavior.
  2297. * @bfqd: device data.
  2298. * @bfqq: queue to update.
  2299. * @reason: reason for expiration.
  2300. *
  2301. * Handle the feedback on @bfqq budget at queue expiration.
  2302. * See the body for detailed comments.
  2303. */
  2304. static void __bfq_bfqq_recalc_budget(struct bfq_data *bfqd,
  2305. struct bfq_queue *bfqq,
  2306. enum bfqq_expiration reason)
  2307. {
  2308. struct request *next_rq;
  2309. int budget, min_budget;
  2310. min_budget = bfq_min_budget(bfqd);
  2311. if (bfqq->wr_coeff == 1)
  2312. budget = bfqq->max_budget;
  2313. else /*
  2314. * Use a constant, low budget for weight-raised queues,
  2315. * to help achieve a low latency. Keep it slightly higher
  2316. * than the minimum possible budget, to cause a little
  2317. * bit fewer expirations.
  2318. */
  2319. budget = 2 * min_budget;
  2320. bfq_log_bfqq(bfqd, bfqq, "recalc_budg: last budg %d, budg left %d",
  2321. bfqq->entity.budget, bfq_bfqq_budget_left(bfqq));
  2322. bfq_log_bfqq(bfqd, bfqq, "recalc_budg: last max_budg %d, min budg %d",
  2323. budget, bfq_min_budget(bfqd));
  2324. bfq_log_bfqq(bfqd, bfqq, "recalc_budg: sync %d, seeky %d",
  2325. bfq_bfqq_sync(bfqq), BFQQ_SEEKY(bfqd->in_service_queue));
  2326. if (bfq_bfqq_sync(bfqq) && bfqq->wr_coeff == 1) {
  2327. switch (reason) {
  2328. /*
  2329. * Caveat: in all the following cases we trade latency
  2330. * for throughput.
  2331. */
  2332. case BFQQE_TOO_IDLE:
  2333. /*
  2334. * This is the only case where we may reduce
  2335. * the budget: if there is no request of the
  2336. * process still waiting for completion, then
  2337. * we assume (tentatively) that the timer has
  2338. * expired because the batch of requests of
  2339. * the process could have been served with a
  2340. * smaller budget. Hence, betting that
  2341. * process will behave in the same way when it
  2342. * becomes backlogged again, we reduce its
  2343. * next budget. As long as we guess right,
  2344. * this budget cut reduces the latency
  2345. * experienced by the process.
  2346. *
  2347. * However, if there are still outstanding
  2348. * requests, then the process may have not yet
  2349. * issued its next request just because it is
  2350. * still waiting for the completion of some of
  2351. * the still outstanding ones. So in this
  2352. * subcase we do not reduce its budget, on the
  2353. * contrary we increase it to possibly boost
  2354. * the throughput, as discussed in the
  2355. * comments to the BUDGET_TIMEOUT case.
  2356. */
  2357. if (bfqq->dispatched > 0) /* still outstanding reqs */
  2358. budget = min(budget * 2, bfqd->bfq_max_budget);
  2359. else {
  2360. if (budget > 5 * min_budget)
  2361. budget -= 4 * min_budget;
  2362. else
  2363. budget = min_budget;
  2364. }
  2365. break;
  2366. case BFQQE_BUDGET_TIMEOUT:
  2367. /*
  2368. * We double the budget here because it gives
  2369. * the chance to boost the throughput if this
  2370. * is not a seeky process (and has bumped into
  2371. * this timeout because of, e.g., ZBR).
  2372. */
  2373. budget = min(budget * 2, bfqd->bfq_max_budget);
  2374. break;
  2375. case BFQQE_BUDGET_EXHAUSTED:
  2376. /*
  2377. * The process still has backlog, and did not
  2378. * let either the budget timeout or the disk
  2379. * idling timeout expire. Hence it is not
  2380. * seeky, has a short thinktime and may be
  2381. * happy with a higher budget too. So
  2382. * definitely increase the budget of this good
  2383. * candidate to boost the disk throughput.
  2384. */
  2385. budget = min(budget * 4, bfqd->bfq_max_budget);
  2386. break;
  2387. case BFQQE_NO_MORE_REQUESTS:
  2388. /*
  2389. * For queues that expire for this reason, it
  2390. * is particularly important to keep the
  2391. * budget close to the actual service they
  2392. * need. Doing so reduces the timestamp
  2393. * misalignment problem described in the
  2394. * comments in the body of
  2395. * __bfq_activate_entity. In fact, suppose
  2396. * that a queue systematically expires for
  2397. * BFQQE_NO_MORE_REQUESTS and presents a
  2398. * new request in time to enjoy timestamp
  2399. * back-shifting. The larger the budget of the
  2400. * queue is with respect to the service the
  2401. * queue actually requests in each service
  2402. * slot, the more times the queue can be
  2403. * reactivated with the same virtual finish
  2404. * time. It follows that, even if this finish
  2405. * time is pushed to the system virtual time
  2406. * to reduce the consequent timestamp
  2407. * misalignment, the queue unjustly enjoys for
  2408. * many re-activations a lower finish time
  2409. * than all newly activated queues.
  2410. *
  2411. * The service needed by bfqq is measured
  2412. * quite precisely by bfqq->entity.service.
  2413. * Since bfqq does not enjoy device idling,
  2414. * bfqq->entity.service is equal to the number
  2415. * of sectors that the process associated with
  2416. * bfqq requested to read/write before waiting
  2417. * for request completions, or blocking for
  2418. * other reasons.
  2419. */
  2420. budget = max_t(int, bfqq->entity.service, min_budget);
  2421. break;
  2422. default:
  2423. return;
  2424. }
  2425. } else if (!bfq_bfqq_sync(bfqq)) {
  2426. /*
  2427. * Async queues get always the maximum possible
  2428. * budget, as for them we do not care about latency
  2429. * (in addition, their ability to dispatch is limited
  2430. * by the charging factor).
  2431. */
  2432. budget = bfqd->bfq_max_budget;
  2433. }
  2434. bfqq->max_budget = budget;
  2435. if (bfqd->budgets_assigned >= bfq_stats_min_budgets &&
  2436. !bfqd->bfq_user_max_budget)
  2437. bfqq->max_budget = min(bfqq->max_budget, bfqd->bfq_max_budget);
  2438. /*
  2439. * If there is still backlog, then assign a new budget, making
  2440. * sure that it is large enough for the next request. Since
  2441. * the finish time of bfqq must be kept in sync with the
  2442. * budget, be sure to call __bfq_bfqq_expire() *after* this
  2443. * update.
  2444. *
  2445. * If there is no backlog, then no need to update the budget;
  2446. * it will be updated on the arrival of a new request.
  2447. */
  2448. next_rq = bfqq->next_rq;
  2449. if (next_rq)
  2450. bfqq->entity.budget = max_t(unsigned long, bfqq->max_budget,
  2451. bfq_serv_to_charge(next_rq, bfqq));
  2452. bfq_log_bfqq(bfqd, bfqq, "head sect: %u, new budget %d",
  2453. next_rq ? blk_rq_sectors(next_rq) : 0,
  2454. bfqq->entity.budget);
  2455. }
  2456. /*
  2457. * Return true if the process associated with bfqq is "slow". The slow
  2458. * flag is used, in addition to the budget timeout, to reduce the
  2459. * amount of service provided to seeky processes, and thus reduce
  2460. * their chances to lower the throughput. More details in the comments
  2461. * on the function bfq_bfqq_expire().
  2462. *
  2463. * An important observation is in order: as discussed in the comments
  2464. * on the function bfq_update_peak_rate(), with devices with internal
  2465. * queues, it is hard if ever possible to know when and for how long
  2466. * an I/O request is processed by the device (apart from the trivial
  2467. * I/O pattern where a new request is dispatched only after the
  2468. * previous one has been completed). This makes it hard to evaluate
  2469. * the real rate at which the I/O requests of each bfq_queue are
  2470. * served. In fact, for an I/O scheduler like BFQ, serving a
  2471. * bfq_queue means just dispatching its requests during its service
  2472. * slot (i.e., until the budget of the queue is exhausted, or the
  2473. * queue remains idle, or, finally, a timeout fires). But, during the
  2474. * service slot of a bfq_queue, around 100 ms at most, the device may
  2475. * be even still processing requests of bfq_queues served in previous
  2476. * service slots. On the opposite end, the requests of the in-service
  2477. * bfq_queue may be completed after the service slot of the queue
  2478. * finishes.
  2479. *
  2480. * Anyway, unless more sophisticated solutions are used
  2481. * (where possible), the sum of the sizes of the requests dispatched
  2482. * during the service slot of a bfq_queue is probably the only
  2483. * approximation available for the service received by the bfq_queue
  2484. * during its service slot. And this sum is the quantity used in this
  2485. * function to evaluate the I/O speed of a process.
  2486. */
  2487. static bool bfq_bfqq_is_slow(struct bfq_data *bfqd, struct bfq_queue *bfqq,
  2488. bool compensate, enum bfqq_expiration reason,
  2489. unsigned long *delta_ms)
  2490. {
  2491. ktime_t delta_ktime;
  2492. u32 delta_usecs;
  2493. bool slow = BFQQ_SEEKY(bfqq); /* if delta too short, use seekyness */
  2494. if (!bfq_bfqq_sync(bfqq))
  2495. return false;
  2496. if (compensate)
  2497. delta_ktime = bfqd->last_idling_start;
  2498. else
  2499. delta_ktime = ktime_get();
  2500. delta_ktime = ktime_sub(delta_ktime, bfqd->last_budget_start);
  2501. delta_usecs = ktime_to_us(delta_ktime);
  2502. /* don't use too short time intervals */
  2503. if (delta_usecs < 1000) {
  2504. if (blk_queue_nonrot(bfqd->queue))
  2505. /*
  2506. * give same worst-case guarantees as idling
  2507. * for seeky
  2508. */
  2509. *delta_ms = BFQ_MIN_TT / NSEC_PER_MSEC;
  2510. else /* charge at least one seek */
  2511. *delta_ms = bfq_slice_idle / NSEC_PER_MSEC;
  2512. return slow;
  2513. }
  2514. *delta_ms = delta_usecs / USEC_PER_MSEC;
  2515. /*
  2516. * Use only long (> 20ms) intervals to filter out excessive
  2517. * spikes in service rate estimation.
  2518. */
  2519. if (delta_usecs > 20000) {
  2520. /*
  2521. * Caveat for rotational devices: processes doing I/O
  2522. * in the slower disk zones tend to be slow(er) even
  2523. * if not seeky. In this respect, the estimated peak
  2524. * rate is likely to be an average over the disk
  2525. * surface. Accordingly, to not be too harsh with
  2526. * unlucky processes, a process is deemed slow only if
  2527. * its rate has been lower than half of the estimated
  2528. * peak rate.
  2529. */
  2530. slow = bfqq->entity.service < bfqd->bfq_max_budget / 2;
  2531. }
  2532. bfq_log_bfqq(bfqd, bfqq, "bfq_bfqq_is_slow: slow %d", slow);
  2533. return slow;
  2534. }
  2535. /*
  2536. * To be deemed as soft real-time, an application must meet two
  2537. * requirements. First, the application must not require an average
  2538. * bandwidth higher than the approximate bandwidth required to playback or
  2539. * record a compressed high-definition video.
  2540. * The next function is invoked on the completion of the last request of a
  2541. * batch, to compute the next-start time instant, soft_rt_next_start, such
  2542. * that, if the next request of the application does not arrive before
  2543. * soft_rt_next_start, then the above requirement on the bandwidth is met.
  2544. *
  2545. * The second requirement is that the request pattern of the application is
  2546. * isochronous, i.e., that, after issuing a request or a batch of requests,
  2547. * the application stops issuing new requests until all its pending requests
  2548. * have been completed. After that, the application may issue a new batch,
  2549. * and so on.
  2550. * For this reason the next function is invoked to compute
  2551. * soft_rt_next_start only for applications that meet this requirement,
  2552. * whereas soft_rt_next_start is set to infinity for applications that do
  2553. * not.
  2554. *
  2555. * Unfortunately, even a greedy application may happen to behave in an
  2556. * isochronous way if the CPU load is high. In fact, the application may
  2557. * stop issuing requests while the CPUs are busy serving other processes,
  2558. * then restart, then stop again for a while, and so on. In addition, if
  2559. * the disk achieves a low enough throughput with the request pattern
  2560. * issued by the application (e.g., because the request pattern is random
  2561. * and/or the device is slow), then the application may meet the above
  2562. * bandwidth requirement too. To prevent such a greedy application to be
  2563. * deemed as soft real-time, a further rule is used in the computation of
  2564. * soft_rt_next_start: soft_rt_next_start must be higher than the current
  2565. * time plus the maximum time for which the arrival of a request is waited
  2566. * for when a sync queue becomes idle, namely bfqd->bfq_slice_idle.
  2567. * This filters out greedy applications, as the latter issue instead their
  2568. * next request as soon as possible after the last one has been completed
  2569. * (in contrast, when a batch of requests is completed, a soft real-time
  2570. * application spends some time processing data).
  2571. *
  2572. * Unfortunately, the last filter may easily generate false positives if
  2573. * only bfqd->bfq_slice_idle is used as a reference time interval and one
  2574. * or both the following cases occur:
  2575. * 1) HZ is so low that the duration of a jiffy is comparable to or higher
  2576. * than bfqd->bfq_slice_idle. This happens, e.g., on slow devices with
  2577. * HZ=100.
  2578. * 2) jiffies, instead of increasing at a constant rate, may stop increasing
  2579. * for a while, then suddenly 'jump' by several units to recover the lost
  2580. * increments. This seems to happen, e.g., inside virtual machines.
  2581. * To address this issue, we do not use as a reference time interval just
  2582. * bfqd->bfq_slice_idle, but bfqd->bfq_slice_idle plus a few jiffies. In
  2583. * particular we add the minimum number of jiffies for which the filter
  2584. * seems to be quite precise also in embedded systems and KVM/QEMU virtual
  2585. * machines.
  2586. */
  2587. static unsigned long bfq_bfqq_softrt_next_start(struct bfq_data *bfqd,
  2588. struct bfq_queue *bfqq)
  2589. {
  2590. return max(bfqq->last_idle_bklogged +
  2591. HZ * bfqq->service_from_backlogged /
  2592. bfqd->bfq_wr_max_softrt_rate,
  2593. jiffies + nsecs_to_jiffies(bfqq->bfqd->bfq_slice_idle) + 4);
  2594. }
  2595. /*
  2596. * Return the farthest future time instant according to jiffies
  2597. * macros.
  2598. */
  2599. static unsigned long bfq_greatest_from_now(void)
  2600. {
  2601. return jiffies + MAX_JIFFY_OFFSET;
  2602. }
  2603. /*
  2604. * Return the farthest past time instant according to jiffies
  2605. * macros.
  2606. */
  2607. static unsigned long bfq_smallest_from_now(void)
  2608. {
  2609. return jiffies - MAX_JIFFY_OFFSET;
  2610. }
  2611. /**
  2612. * bfq_bfqq_expire - expire a queue.
  2613. * @bfqd: device owning the queue.
  2614. * @bfqq: the queue to expire.
  2615. * @compensate: if true, compensate for the time spent idling.
  2616. * @reason: the reason causing the expiration.
  2617. *
  2618. * If the process associated with bfqq does slow I/O (e.g., because it
  2619. * issues random requests), we charge bfqq with the time it has been
  2620. * in service instead of the service it has received (see
  2621. * bfq_bfqq_charge_time for details on how this goal is achieved). As
  2622. * a consequence, bfqq will typically get higher timestamps upon
  2623. * reactivation, and hence it will be rescheduled as if it had
  2624. * received more service than what it has actually received. In the
  2625. * end, bfqq receives less service in proportion to how slowly its
  2626. * associated process consumes its budgets (and hence how seriously it
  2627. * tends to lower the throughput). In addition, this time-charging
  2628. * strategy guarantees time fairness among slow processes. In
  2629. * contrast, if the process associated with bfqq is not slow, we
  2630. * charge bfqq exactly with the service it has received.
  2631. *
  2632. * Charging time to the first type of queues and the exact service to
  2633. * the other has the effect of using the WF2Q+ policy to schedule the
  2634. * former on a timeslice basis, without violating service domain
  2635. * guarantees among the latter.
  2636. */
  2637. void bfq_bfqq_expire(struct bfq_data *bfqd,
  2638. struct bfq_queue *bfqq,
  2639. bool compensate,
  2640. enum bfqq_expiration reason)
  2641. {
  2642. bool slow;
  2643. unsigned long delta = 0;
  2644. struct bfq_entity *entity = &bfqq->entity;
  2645. int ref;
  2646. /*
  2647. * Check whether the process is slow (see bfq_bfqq_is_slow).
  2648. */
  2649. slow = bfq_bfqq_is_slow(bfqd, bfqq, compensate, reason, &delta);
  2650. /*
  2651. * Increase service_from_backlogged before next statement,
  2652. * because the possible next invocation of
  2653. * bfq_bfqq_charge_time would likely inflate
  2654. * entity->service. In contrast, service_from_backlogged must
  2655. * contain real service, to enable the soft real-time
  2656. * heuristic to correctly compute the bandwidth consumed by
  2657. * bfqq.
  2658. */
  2659. bfqq->service_from_backlogged += entity->service;
  2660. /*
  2661. * As above explained, charge slow (typically seeky) and
  2662. * timed-out queues with the time and not the service
  2663. * received, to favor sequential workloads.
  2664. *
  2665. * Processes doing I/O in the slower disk zones will tend to
  2666. * be slow(er) even if not seeky. Therefore, since the
  2667. * estimated peak rate is actually an average over the disk
  2668. * surface, these processes may timeout just for bad luck. To
  2669. * avoid punishing them, do not charge time to processes that
  2670. * succeeded in consuming at least 2/3 of their budget. This
  2671. * allows BFQ to preserve enough elasticity to still perform
  2672. * bandwidth, and not time, distribution with little unlucky
  2673. * or quasi-sequential processes.
  2674. */
  2675. if (bfqq->wr_coeff == 1 &&
  2676. (slow ||
  2677. (reason == BFQQE_BUDGET_TIMEOUT &&
  2678. bfq_bfqq_budget_left(bfqq) >= entity->budget / 3)))
  2679. bfq_bfqq_charge_time(bfqd, bfqq, delta);
  2680. if (reason == BFQQE_TOO_IDLE &&
  2681. entity->service <= 2 * entity->budget / 10)
  2682. bfq_clear_bfqq_IO_bound(bfqq);
  2683. if (bfqd->low_latency && bfqq->wr_coeff == 1)
  2684. bfqq->last_wr_start_finish = jiffies;
  2685. if (bfqd->low_latency && bfqd->bfq_wr_max_softrt_rate > 0 &&
  2686. RB_EMPTY_ROOT(&bfqq->sort_list)) {
  2687. /*
  2688. * If we get here, and there are no outstanding
  2689. * requests, then the request pattern is isochronous
  2690. * (see the comments on the function
  2691. * bfq_bfqq_softrt_next_start()). Thus we can compute
  2692. * soft_rt_next_start. If, instead, the queue still
  2693. * has outstanding requests, then we have to wait for
  2694. * the completion of all the outstanding requests to
  2695. * discover whether the request pattern is actually
  2696. * isochronous.
  2697. */
  2698. if (bfqq->dispatched == 0)
  2699. bfqq->soft_rt_next_start =
  2700. bfq_bfqq_softrt_next_start(bfqd, bfqq);
  2701. else {
  2702. /*
  2703. * The application is still waiting for the
  2704. * completion of one or more requests:
  2705. * prevent it from possibly being incorrectly
  2706. * deemed as soft real-time by setting its
  2707. * soft_rt_next_start to infinity. In fact,
  2708. * without this assignment, the application
  2709. * would be incorrectly deemed as soft
  2710. * real-time if:
  2711. * 1) it issued a new request before the
  2712. * completion of all its in-flight
  2713. * requests, and
  2714. * 2) at that time, its soft_rt_next_start
  2715. * happened to be in the past.
  2716. */
  2717. bfqq->soft_rt_next_start =
  2718. bfq_greatest_from_now();
  2719. /*
  2720. * Schedule an update of soft_rt_next_start to when
  2721. * the task may be discovered to be isochronous.
  2722. */
  2723. bfq_mark_bfqq_softrt_update(bfqq);
  2724. }
  2725. }
  2726. bfq_log_bfqq(bfqd, bfqq,
  2727. "expire (%d, slow %d, num_disp %d, short_ttime %d)", reason,
  2728. slow, bfqq->dispatched, bfq_bfqq_has_short_ttime(bfqq));
  2729. /*
  2730. * Increase, decrease or leave budget unchanged according to
  2731. * reason.
  2732. */
  2733. __bfq_bfqq_recalc_budget(bfqd, bfqq, reason);
  2734. ref = bfqq->ref;
  2735. __bfq_bfqq_expire(bfqd, bfqq);
  2736. /* mark bfqq as waiting a request only if a bic still points to it */
  2737. if (ref > 1 && !bfq_bfqq_busy(bfqq) &&
  2738. reason != BFQQE_BUDGET_TIMEOUT &&
  2739. reason != BFQQE_BUDGET_EXHAUSTED)
  2740. bfq_mark_bfqq_non_blocking_wait_rq(bfqq);
  2741. }
  2742. /*
  2743. * Budget timeout is not implemented through a dedicated timer, but
  2744. * just checked on request arrivals and completions, as well as on
  2745. * idle timer expirations.
  2746. */
  2747. static bool bfq_bfqq_budget_timeout(struct bfq_queue *bfqq)
  2748. {
  2749. return time_is_before_eq_jiffies(bfqq->budget_timeout);
  2750. }
  2751. /*
  2752. * If we expire a queue that is actively waiting (i.e., with the
  2753. * device idled) for the arrival of a new request, then we may incur
  2754. * the timestamp misalignment problem described in the body of the
  2755. * function __bfq_activate_entity. Hence we return true only if this
  2756. * condition does not hold, or if the queue is slow enough to deserve
  2757. * only to be kicked off for preserving a high throughput.
  2758. */
  2759. static bool bfq_may_expire_for_budg_timeout(struct bfq_queue *bfqq)
  2760. {
  2761. bfq_log_bfqq(bfqq->bfqd, bfqq,
  2762. "may_budget_timeout: wait_request %d left %d timeout %d",
  2763. bfq_bfqq_wait_request(bfqq),
  2764. bfq_bfqq_budget_left(bfqq) >= bfqq->entity.budget / 3,
  2765. bfq_bfqq_budget_timeout(bfqq));
  2766. return (!bfq_bfqq_wait_request(bfqq) ||
  2767. bfq_bfqq_budget_left(bfqq) >= bfqq->entity.budget / 3)
  2768. &&
  2769. bfq_bfqq_budget_timeout(bfqq);
  2770. }
  2771. /*
  2772. * For a queue that becomes empty, device idling is allowed only if
  2773. * this function returns true for the queue. As a consequence, since
  2774. * device idling plays a critical role in both throughput boosting and
  2775. * service guarantees, the return value of this function plays a
  2776. * critical role in both these aspects as well.
  2777. *
  2778. * In a nutshell, this function returns true only if idling is
  2779. * beneficial for throughput or, even if detrimental for throughput,
  2780. * idling is however necessary to preserve service guarantees (low
  2781. * latency, desired throughput distribution, ...). In particular, on
  2782. * NCQ-capable devices, this function tries to return false, so as to
  2783. * help keep the drives' internal queues full, whenever this helps the
  2784. * device boost the throughput without causing any service-guarantee
  2785. * issue.
  2786. *
  2787. * In more detail, the return value of this function is obtained by,
  2788. * first, computing a number of boolean variables that take into
  2789. * account throughput and service-guarantee issues, and, then,
  2790. * combining these variables in a logical expression. Most of the
  2791. * issues taken into account are not trivial. We discuss these issues
  2792. * individually while introducing the variables.
  2793. */
  2794. static bool bfq_bfqq_may_idle(struct bfq_queue *bfqq)
  2795. {
  2796. struct bfq_data *bfqd = bfqq->bfqd;
  2797. bool rot_without_queueing =
  2798. !blk_queue_nonrot(bfqd->queue) && !bfqd->hw_tag,
  2799. bfqq_sequential_and_IO_bound,
  2800. idling_boosts_thr, idling_boosts_thr_without_issues,
  2801. idling_needed_for_service_guarantees,
  2802. asymmetric_scenario;
  2803. if (bfqd->strict_guarantees)
  2804. return true;
  2805. /*
  2806. * Idling is performed only if slice_idle > 0. In addition, we
  2807. * do not idle if
  2808. * (a) bfqq is async
  2809. * (b) bfqq is in the idle io prio class: in this case we do
  2810. * not idle because we want to minimize the bandwidth that
  2811. * queues in this class can steal to higher-priority queues
  2812. */
  2813. if (bfqd->bfq_slice_idle == 0 || !bfq_bfqq_sync(bfqq) ||
  2814. bfq_class_idle(bfqq))
  2815. return false;
  2816. bfqq_sequential_and_IO_bound = !BFQQ_SEEKY(bfqq) &&
  2817. bfq_bfqq_IO_bound(bfqq) && bfq_bfqq_has_short_ttime(bfqq);
  2818. /*
  2819. * The next variable takes into account the cases where idling
  2820. * boosts the throughput.
  2821. *
  2822. * The value of the variable is computed considering, first, that
  2823. * idling is virtually always beneficial for the throughput if:
  2824. * (a) the device is not NCQ-capable and rotational, or
  2825. * (b) regardless of the presence of NCQ, the device is rotational and
  2826. * the request pattern for bfqq is I/O-bound and sequential, or
  2827. * (c) regardless of whether it is rotational, the device is
  2828. * not NCQ-capable and the request pattern for bfqq is
  2829. * I/O-bound and sequential.
  2830. *
  2831. * Secondly, and in contrast to the above item (b), idling an
  2832. * NCQ-capable flash-based device would not boost the
  2833. * throughput even with sequential I/O; rather it would lower
  2834. * the throughput in proportion to how fast the device
  2835. * is. Accordingly, the next variable is true if any of the
  2836. * above conditions (a), (b) or (c) is true, and, in
  2837. * particular, happens to be false if bfqd is an NCQ-capable
  2838. * flash-based device.
  2839. */
  2840. idling_boosts_thr = rot_without_queueing ||
  2841. ((!blk_queue_nonrot(bfqd->queue) || !bfqd->hw_tag) &&
  2842. bfqq_sequential_and_IO_bound);
  2843. /*
  2844. * The value of the next variable,
  2845. * idling_boosts_thr_without_issues, is equal to that of
  2846. * idling_boosts_thr, unless a special case holds. In this
  2847. * special case, described below, idling may cause problems to
  2848. * weight-raised queues.
  2849. *
  2850. * When the request pool is saturated (e.g., in the presence
  2851. * of write hogs), if the processes associated with
  2852. * non-weight-raised queues ask for requests at a lower rate,
  2853. * then processes associated with weight-raised queues have a
  2854. * higher probability to get a request from the pool
  2855. * immediately (or at least soon) when they need one. Thus
  2856. * they have a higher probability to actually get a fraction
  2857. * of the device throughput proportional to their high
  2858. * weight. This is especially true with NCQ-capable drives,
  2859. * which enqueue several requests in advance, and further
  2860. * reorder internally-queued requests.
  2861. *
  2862. * For this reason, we force to false the value of
  2863. * idling_boosts_thr_without_issues if there are weight-raised
  2864. * busy queues. In this case, and if bfqq is not weight-raised,
  2865. * this guarantees that the device is not idled for bfqq (if,
  2866. * instead, bfqq is weight-raised, then idling will be
  2867. * guaranteed by another variable, see below). Combined with
  2868. * the timestamping rules of BFQ (see [1] for details), this
  2869. * behavior causes bfqq, and hence any sync non-weight-raised
  2870. * queue, to get a lower number of requests served, and thus
  2871. * to ask for a lower number of requests from the request
  2872. * pool, before the busy weight-raised queues get served
  2873. * again. This often mitigates starvation problems in the
  2874. * presence of heavy write workloads and NCQ, thereby
  2875. * guaranteeing a higher application and system responsiveness
  2876. * in these hostile scenarios.
  2877. */
  2878. idling_boosts_thr_without_issues = idling_boosts_thr &&
  2879. bfqd->wr_busy_queues == 0;
  2880. /*
  2881. * There is then a case where idling must be performed not
  2882. * for throughput concerns, but to preserve service
  2883. * guarantees.
  2884. *
  2885. * To introduce this case, we can note that allowing the drive
  2886. * to enqueue more than one request at a time, and hence
  2887. * delegating de facto final scheduling decisions to the
  2888. * drive's internal scheduler, entails loss of control on the
  2889. * actual request service order. In particular, the critical
  2890. * situation is when requests from different processes happen
  2891. * to be present, at the same time, in the internal queue(s)
  2892. * of the drive. In such a situation, the drive, by deciding
  2893. * the service order of the internally-queued requests, does
  2894. * determine also the actual throughput distribution among
  2895. * these processes. But the drive typically has no notion or
  2896. * concern about per-process throughput distribution, and
  2897. * makes its decisions only on a per-request basis. Therefore,
  2898. * the service distribution enforced by the drive's internal
  2899. * scheduler is likely to coincide with the desired
  2900. * device-throughput distribution only in a completely
  2901. * symmetric scenario where:
  2902. * (i) each of these processes must get the same throughput as
  2903. * the others;
  2904. * (ii) all these processes have the same I/O pattern
  2905. (either sequential or random).
  2906. * In fact, in such a scenario, the drive will tend to treat
  2907. * the requests of each of these processes in about the same
  2908. * way as the requests of the others, and thus to provide
  2909. * each of these processes with about the same throughput
  2910. * (which is exactly the desired throughput distribution). In
  2911. * contrast, in any asymmetric scenario, device idling is
  2912. * certainly needed to guarantee that bfqq receives its
  2913. * assigned fraction of the device throughput (see [1] for
  2914. * details).
  2915. *
  2916. * We address this issue by controlling, actually, only the
  2917. * symmetry sub-condition (i), i.e., provided that
  2918. * sub-condition (i) holds, idling is not performed,
  2919. * regardless of whether sub-condition (ii) holds. In other
  2920. * words, only if sub-condition (i) holds, then idling is
  2921. * allowed, and the device tends to be prevented from queueing
  2922. * many requests, possibly of several processes. The reason
  2923. * for not controlling also sub-condition (ii) is that we
  2924. * exploit preemption to preserve guarantees in case of
  2925. * symmetric scenarios, even if (ii) does not hold, as
  2926. * explained in the next two paragraphs.
  2927. *
  2928. * Even if a queue, say Q, is expired when it remains idle, Q
  2929. * can still preempt the new in-service queue if the next
  2930. * request of Q arrives soon (see the comments on
  2931. * bfq_bfqq_update_budg_for_activation). If all queues and
  2932. * groups have the same weight, this form of preemption,
  2933. * combined with the hole-recovery heuristic described in the
  2934. * comments on function bfq_bfqq_update_budg_for_activation,
  2935. * are enough to preserve a correct bandwidth distribution in
  2936. * the mid term, even without idling. In fact, even if not
  2937. * idling allows the internal queues of the device to contain
  2938. * many requests, and thus to reorder requests, we can rather
  2939. * safely assume that the internal scheduler still preserves a
  2940. * minimum of mid-term fairness. The motivation for using
  2941. * preemption instead of idling is that, by not idling,
  2942. * service guarantees are preserved without minimally
  2943. * sacrificing throughput. In other words, both a high
  2944. * throughput and its desired distribution are obtained.
  2945. *
  2946. * More precisely, this preemption-based, idleless approach
  2947. * provides fairness in terms of IOPS, and not sectors per
  2948. * second. This can be seen with a simple example. Suppose
  2949. * that there are two queues with the same weight, but that
  2950. * the first queue receives requests of 8 sectors, while the
  2951. * second queue receives requests of 1024 sectors. In
  2952. * addition, suppose that each of the two queues contains at
  2953. * most one request at a time, which implies that each queue
  2954. * always remains idle after it is served. Finally, after
  2955. * remaining idle, each queue receives very quickly a new
  2956. * request. It follows that the two queues are served
  2957. * alternatively, preempting each other if needed. This
  2958. * implies that, although both queues have the same weight,
  2959. * the queue with large requests receives a service that is
  2960. * 1024/8 times as high as the service received by the other
  2961. * queue.
  2962. *
  2963. * On the other hand, device idling is performed, and thus
  2964. * pure sector-domain guarantees are provided, for the
  2965. * following queues, which are likely to need stronger
  2966. * throughput guarantees: weight-raised queues, and queues
  2967. * with a higher weight than other queues. When such queues
  2968. * are active, sub-condition (i) is false, which triggers
  2969. * device idling.
  2970. *
  2971. * According to the above considerations, the next variable is
  2972. * true (only) if sub-condition (i) holds. To compute the
  2973. * value of this variable, we not only use the return value of
  2974. * the function bfq_symmetric_scenario(), but also check
  2975. * whether bfqq is being weight-raised, because
  2976. * bfq_symmetric_scenario() does not take into account also
  2977. * weight-raised queues (see comments on
  2978. * bfq_weights_tree_add()).
  2979. *
  2980. * As a side note, it is worth considering that the above
  2981. * device-idling countermeasures may however fail in the
  2982. * following unlucky scenario: if idling is (correctly)
  2983. * disabled in a time period during which all symmetry
  2984. * sub-conditions hold, and hence the device is allowed to
  2985. * enqueue many requests, but at some later point in time some
  2986. * sub-condition stops to hold, then it may become impossible
  2987. * to let requests be served in the desired order until all
  2988. * the requests already queued in the device have been served.
  2989. */
  2990. asymmetric_scenario = bfqq->wr_coeff > 1 ||
  2991. !bfq_symmetric_scenario(bfqd);
  2992. /*
  2993. * Finally, there is a case where maximizing throughput is the
  2994. * best choice even if it may cause unfairness toward
  2995. * bfqq. Such a case is when bfqq became active in a burst of
  2996. * queue activations. Queues that became active during a large
  2997. * burst benefit only from throughput, as discussed in the
  2998. * comments on bfq_handle_burst. Thus, if bfqq became active
  2999. * in a burst and not idling the device maximizes throughput,
  3000. * then the device must no be idled, because not idling the
  3001. * device provides bfqq and all other queues in the burst with
  3002. * maximum benefit. Combining this and the above case, we can
  3003. * now establish when idling is actually needed to preserve
  3004. * service guarantees.
  3005. */
  3006. idling_needed_for_service_guarantees =
  3007. asymmetric_scenario && !bfq_bfqq_in_large_burst(bfqq);
  3008. /*
  3009. * We have now all the components we need to compute the
  3010. * return value of the function, which is true only if idling
  3011. * either boosts the throughput (without issues), or is
  3012. * necessary to preserve service guarantees.
  3013. */
  3014. return idling_boosts_thr_without_issues ||
  3015. idling_needed_for_service_guarantees;
  3016. }
  3017. /*
  3018. * If the in-service queue is empty but the function bfq_bfqq_may_idle
  3019. * returns true, then:
  3020. * 1) the queue must remain in service and cannot be expired, and
  3021. * 2) the device must be idled to wait for the possible arrival of a new
  3022. * request for the queue.
  3023. * See the comments on the function bfq_bfqq_may_idle for the reasons
  3024. * why performing device idling is the best choice to boost the throughput
  3025. * and preserve service guarantees when bfq_bfqq_may_idle itself
  3026. * returns true.
  3027. */
  3028. static bool bfq_bfqq_must_idle(struct bfq_queue *bfqq)
  3029. {
  3030. return RB_EMPTY_ROOT(&bfqq->sort_list) && bfq_bfqq_may_idle(bfqq);
  3031. }
  3032. /*
  3033. * Select a queue for service. If we have a current queue in service,
  3034. * check whether to continue servicing it, or retrieve and set a new one.
  3035. */
  3036. static struct bfq_queue *bfq_select_queue(struct bfq_data *bfqd)
  3037. {
  3038. struct bfq_queue *bfqq;
  3039. struct request *next_rq;
  3040. enum bfqq_expiration reason = BFQQE_BUDGET_TIMEOUT;
  3041. bfqq = bfqd->in_service_queue;
  3042. if (!bfqq)
  3043. goto new_queue;
  3044. bfq_log_bfqq(bfqd, bfqq, "select_queue: already in-service queue");
  3045. if (bfq_may_expire_for_budg_timeout(bfqq) &&
  3046. !bfq_bfqq_wait_request(bfqq) &&
  3047. !bfq_bfqq_must_idle(bfqq))
  3048. goto expire;
  3049. check_queue:
  3050. /*
  3051. * This loop is rarely executed more than once. Even when it
  3052. * happens, it is much more convenient to re-execute this loop
  3053. * than to return NULL and trigger a new dispatch to get a
  3054. * request served.
  3055. */
  3056. next_rq = bfqq->next_rq;
  3057. /*
  3058. * If bfqq has requests queued and it has enough budget left to
  3059. * serve them, keep the queue, otherwise expire it.
  3060. */
  3061. if (next_rq) {
  3062. if (bfq_serv_to_charge(next_rq, bfqq) >
  3063. bfq_bfqq_budget_left(bfqq)) {
  3064. /*
  3065. * Expire the queue for budget exhaustion,
  3066. * which makes sure that the next budget is
  3067. * enough to serve the next request, even if
  3068. * it comes from the fifo expired path.
  3069. */
  3070. reason = BFQQE_BUDGET_EXHAUSTED;
  3071. goto expire;
  3072. } else {
  3073. /*
  3074. * The idle timer may be pending because we may
  3075. * not disable disk idling even when a new request
  3076. * arrives.
  3077. */
  3078. if (bfq_bfqq_wait_request(bfqq)) {
  3079. /*
  3080. * If we get here: 1) at least a new request
  3081. * has arrived but we have not disabled the
  3082. * timer because the request was too small,
  3083. * 2) then the block layer has unplugged
  3084. * the device, causing the dispatch to be
  3085. * invoked.
  3086. *
  3087. * Since the device is unplugged, now the
  3088. * requests are probably large enough to
  3089. * provide a reasonable throughput.
  3090. * So we disable idling.
  3091. */
  3092. bfq_clear_bfqq_wait_request(bfqq);
  3093. hrtimer_try_to_cancel(&bfqd->idle_slice_timer);
  3094. bfqg_stats_update_idle_time(bfqq_group(bfqq));
  3095. }
  3096. goto keep_queue;
  3097. }
  3098. }
  3099. /*
  3100. * No requests pending. However, if the in-service queue is idling
  3101. * for a new request, or has requests waiting for a completion and
  3102. * may idle after their completion, then keep it anyway.
  3103. */
  3104. if (bfq_bfqq_wait_request(bfqq) ||
  3105. (bfqq->dispatched != 0 && bfq_bfqq_may_idle(bfqq))) {
  3106. bfqq = NULL;
  3107. goto keep_queue;
  3108. }
  3109. reason = BFQQE_NO_MORE_REQUESTS;
  3110. expire:
  3111. bfq_bfqq_expire(bfqd, bfqq, false, reason);
  3112. new_queue:
  3113. bfqq = bfq_set_in_service_queue(bfqd);
  3114. if (bfqq) {
  3115. bfq_log_bfqq(bfqd, bfqq, "select_queue: checking new queue");
  3116. goto check_queue;
  3117. }
  3118. keep_queue:
  3119. if (bfqq)
  3120. bfq_log_bfqq(bfqd, bfqq, "select_queue: returned this queue");
  3121. else
  3122. bfq_log(bfqd, "select_queue: no queue returned");
  3123. return bfqq;
  3124. }
  3125. static void bfq_update_wr_data(struct bfq_data *bfqd, struct bfq_queue *bfqq)
  3126. {
  3127. struct bfq_entity *entity = &bfqq->entity;
  3128. if (bfqq->wr_coeff > 1) { /* queue is being weight-raised */
  3129. bfq_log_bfqq(bfqd, bfqq,
  3130. "raising period dur %u/%u msec, old coeff %u, w %d(%d)",
  3131. jiffies_to_msecs(jiffies - bfqq->last_wr_start_finish),
  3132. jiffies_to_msecs(bfqq->wr_cur_max_time),
  3133. bfqq->wr_coeff,
  3134. bfqq->entity.weight, bfqq->entity.orig_weight);
  3135. if (entity->prio_changed)
  3136. bfq_log_bfqq(bfqd, bfqq, "WARN: pending prio change");
  3137. /*
  3138. * If the queue was activated in a burst, or too much
  3139. * time has elapsed from the beginning of this
  3140. * weight-raising period, then end weight raising.
  3141. */
  3142. if (bfq_bfqq_in_large_burst(bfqq))
  3143. bfq_bfqq_end_wr(bfqq);
  3144. else if (time_is_before_jiffies(bfqq->last_wr_start_finish +
  3145. bfqq->wr_cur_max_time)) {
  3146. if (bfqq->wr_cur_max_time != bfqd->bfq_wr_rt_max_time ||
  3147. time_is_before_jiffies(bfqq->wr_start_at_switch_to_srt +
  3148. bfq_wr_duration(bfqd)))
  3149. bfq_bfqq_end_wr(bfqq);
  3150. else {
  3151. /* switch back to interactive wr */
  3152. bfqq->wr_coeff = bfqd->bfq_wr_coeff;
  3153. bfqq->wr_cur_max_time = bfq_wr_duration(bfqd);
  3154. bfqq->last_wr_start_finish =
  3155. bfqq->wr_start_at_switch_to_srt;
  3156. bfqq->entity.prio_changed = 1;
  3157. }
  3158. }
  3159. }
  3160. /*
  3161. * To improve latency (for this or other queues), immediately
  3162. * update weight both if it must be raised and if it must be
  3163. * lowered. Since, entity may be on some active tree here, and
  3164. * might have a pending change of its ioprio class, invoke
  3165. * next function with the last parameter unset (see the
  3166. * comments on the function).
  3167. */
  3168. if ((entity->weight > entity->orig_weight) != (bfqq->wr_coeff > 1))
  3169. __bfq_entity_update_weight_prio(bfq_entity_service_tree(entity),
  3170. entity, false);
  3171. }
  3172. /*
  3173. * Dispatch next request from bfqq.
  3174. */
  3175. static struct request *bfq_dispatch_rq_from_bfqq(struct bfq_data *bfqd,
  3176. struct bfq_queue *bfqq)
  3177. {
  3178. struct request *rq = bfqq->next_rq;
  3179. unsigned long service_to_charge;
  3180. service_to_charge = bfq_serv_to_charge(rq, bfqq);
  3181. bfq_bfqq_served(bfqq, service_to_charge);
  3182. bfq_dispatch_remove(bfqd->queue, rq);
  3183. /*
  3184. * If weight raising has to terminate for bfqq, then next
  3185. * function causes an immediate update of bfqq's weight,
  3186. * without waiting for next activation. As a consequence, on
  3187. * expiration, bfqq will be timestamped as if has never been
  3188. * weight-raised during this service slot, even if it has
  3189. * received part or even most of the service as a
  3190. * weight-raised queue. This inflates bfqq's timestamps, which
  3191. * is beneficial, as bfqq is then more willing to leave the
  3192. * device immediately to possible other weight-raised queues.
  3193. */
  3194. bfq_update_wr_data(bfqd, bfqq);
  3195. /*
  3196. * Expire bfqq, pretending that its budget expired, if bfqq
  3197. * belongs to CLASS_IDLE and other queues are waiting for
  3198. * service.
  3199. */
  3200. if (bfqd->busy_queues > 1 && bfq_class_idle(bfqq))
  3201. goto expire;
  3202. return rq;
  3203. expire:
  3204. bfq_bfqq_expire(bfqd, bfqq, false, BFQQE_BUDGET_EXHAUSTED);
  3205. return rq;
  3206. }
  3207. static bool bfq_has_work(struct blk_mq_hw_ctx *hctx)
  3208. {
  3209. struct bfq_data *bfqd = hctx->queue->elevator->elevator_data;
  3210. /*
  3211. * Avoiding lock: a race on bfqd->busy_queues should cause at
  3212. * most a call to dispatch for nothing
  3213. */
  3214. return !list_empty_careful(&bfqd->dispatch) ||
  3215. bfqd->busy_queues > 0;
  3216. }
  3217. static struct request *__bfq_dispatch_request(struct blk_mq_hw_ctx *hctx)
  3218. {
  3219. struct bfq_data *bfqd = hctx->queue->elevator->elevator_data;
  3220. struct request *rq = NULL;
  3221. struct bfq_queue *bfqq = NULL;
  3222. if (!list_empty(&bfqd->dispatch)) {
  3223. rq = list_first_entry(&bfqd->dispatch, struct request,
  3224. queuelist);
  3225. list_del_init(&rq->queuelist);
  3226. bfqq = RQ_BFQQ(rq);
  3227. if (bfqq) {
  3228. /*
  3229. * Increment counters here, because this
  3230. * dispatch does not follow the standard
  3231. * dispatch flow (where counters are
  3232. * incremented)
  3233. */
  3234. bfqq->dispatched++;
  3235. goto inc_in_driver_start_rq;
  3236. }
  3237. /*
  3238. * We exploit the put_rq_private hook to decrement
  3239. * rq_in_driver, but put_rq_private will not be
  3240. * invoked on this request. So, to avoid unbalance,
  3241. * just start this request, without incrementing
  3242. * rq_in_driver. As a negative consequence,
  3243. * rq_in_driver is deceptively lower than it should be
  3244. * while this request is in service. This may cause
  3245. * bfq_schedule_dispatch to be invoked uselessly.
  3246. *
  3247. * As for implementing an exact solution, the
  3248. * put_request hook, if defined, is probably invoked
  3249. * also on this request. So, by exploiting this hook,
  3250. * we could 1) increment rq_in_driver here, and 2)
  3251. * decrement it in put_request. Such a solution would
  3252. * let the value of the counter be always accurate,
  3253. * but it would entail using an extra interface
  3254. * function. This cost seems higher than the benefit,
  3255. * being the frequency of non-elevator-private
  3256. * requests very low.
  3257. */
  3258. goto start_rq;
  3259. }
  3260. bfq_log(bfqd, "dispatch requests: %d busy queues", bfqd->busy_queues);
  3261. if (bfqd->busy_queues == 0)
  3262. goto exit;
  3263. /*
  3264. * Force device to serve one request at a time if
  3265. * strict_guarantees is true. Forcing this service scheme is
  3266. * currently the ONLY way to guarantee that the request
  3267. * service order enforced by the scheduler is respected by a
  3268. * queueing device. Otherwise the device is free even to make
  3269. * some unlucky request wait for as long as the device
  3270. * wishes.
  3271. *
  3272. * Of course, serving one request at at time may cause loss of
  3273. * throughput.
  3274. */
  3275. if (bfqd->strict_guarantees && bfqd->rq_in_driver > 0)
  3276. goto exit;
  3277. bfqq = bfq_select_queue(bfqd);
  3278. if (!bfqq)
  3279. goto exit;
  3280. rq = bfq_dispatch_rq_from_bfqq(bfqd, bfqq);
  3281. if (rq) {
  3282. inc_in_driver_start_rq:
  3283. bfqd->rq_in_driver++;
  3284. start_rq:
  3285. rq->rq_flags |= RQF_STARTED;
  3286. }
  3287. exit:
  3288. return rq;
  3289. }
  3290. static struct request *bfq_dispatch_request(struct blk_mq_hw_ctx *hctx)
  3291. {
  3292. struct bfq_data *bfqd = hctx->queue->elevator->elevator_data;
  3293. struct request *rq;
  3294. spin_lock_irq(&bfqd->lock);
  3295. rq = __bfq_dispatch_request(hctx);
  3296. spin_unlock_irq(&bfqd->lock);
  3297. return rq;
  3298. }
  3299. /*
  3300. * Task holds one reference to the queue, dropped when task exits. Each rq
  3301. * in-flight on this queue also holds a reference, dropped when rq is freed.
  3302. *
  3303. * Scheduler lock must be held here. Recall not to use bfqq after calling
  3304. * this function on it.
  3305. */
  3306. void bfq_put_queue(struct bfq_queue *bfqq)
  3307. {
  3308. #ifdef CONFIG_BFQ_GROUP_IOSCHED
  3309. struct bfq_group *bfqg = bfqq_group(bfqq);
  3310. #endif
  3311. if (bfqq->bfqd)
  3312. bfq_log_bfqq(bfqq->bfqd, bfqq, "put_queue: %p %d",
  3313. bfqq, bfqq->ref);
  3314. bfqq->ref--;
  3315. if (bfqq->ref)
  3316. return;
  3317. if (bfq_bfqq_sync(bfqq))
  3318. /*
  3319. * The fact that this queue is being destroyed does not
  3320. * invalidate the fact that this queue may have been
  3321. * activated during the current burst. As a consequence,
  3322. * although the queue does not exist anymore, and hence
  3323. * needs to be removed from the burst list if there,
  3324. * the burst size has not to be decremented.
  3325. */
  3326. hlist_del_init(&bfqq->burst_list_node);
  3327. kmem_cache_free(bfq_pool, bfqq);
  3328. #ifdef CONFIG_BFQ_GROUP_IOSCHED
  3329. bfqg_and_blkg_put(bfqg);
  3330. #endif
  3331. }
  3332. static void bfq_put_cooperator(struct bfq_queue *bfqq)
  3333. {
  3334. struct bfq_queue *__bfqq, *next;
  3335. /*
  3336. * If this queue was scheduled to merge with another queue, be
  3337. * sure to drop the reference taken on that queue (and others in
  3338. * the merge chain). See bfq_setup_merge and bfq_merge_bfqqs.
  3339. */
  3340. __bfqq = bfqq->new_bfqq;
  3341. while (__bfqq) {
  3342. if (__bfqq == bfqq)
  3343. break;
  3344. next = __bfqq->new_bfqq;
  3345. bfq_put_queue(__bfqq);
  3346. __bfqq = next;
  3347. }
  3348. }
  3349. static void bfq_exit_bfqq(struct bfq_data *bfqd, struct bfq_queue *bfqq)
  3350. {
  3351. if (bfqq == bfqd->in_service_queue) {
  3352. __bfq_bfqq_expire(bfqd, bfqq);
  3353. bfq_schedule_dispatch(bfqd);
  3354. }
  3355. bfq_log_bfqq(bfqd, bfqq, "exit_bfqq: %p, %d", bfqq, bfqq->ref);
  3356. bfq_put_cooperator(bfqq);
  3357. bfq_put_queue(bfqq); /* release process reference */
  3358. }
  3359. static void bfq_exit_icq_bfqq(struct bfq_io_cq *bic, bool is_sync)
  3360. {
  3361. struct bfq_queue *bfqq = bic_to_bfqq(bic, is_sync);
  3362. struct bfq_data *bfqd;
  3363. if (bfqq)
  3364. bfqd = bfqq->bfqd; /* NULL if scheduler already exited */
  3365. if (bfqq && bfqd) {
  3366. unsigned long flags;
  3367. spin_lock_irqsave(&bfqd->lock, flags);
  3368. bfq_exit_bfqq(bfqd, bfqq);
  3369. bic_set_bfqq(bic, NULL, is_sync);
  3370. spin_unlock_irqrestore(&bfqd->lock, flags);
  3371. }
  3372. }
  3373. static void bfq_exit_icq(struct io_cq *icq)
  3374. {
  3375. struct bfq_io_cq *bic = icq_to_bic(icq);
  3376. bfq_exit_icq_bfqq(bic, true);
  3377. bfq_exit_icq_bfqq(bic, false);
  3378. }
  3379. /*
  3380. * Update the entity prio values; note that the new values will not
  3381. * be used until the next (re)activation.
  3382. */
  3383. static void
  3384. bfq_set_next_ioprio_data(struct bfq_queue *bfqq, struct bfq_io_cq *bic)
  3385. {
  3386. struct task_struct *tsk = current;
  3387. int ioprio_class;
  3388. struct bfq_data *bfqd = bfqq->bfqd;
  3389. if (!bfqd)
  3390. return;
  3391. ioprio_class = IOPRIO_PRIO_CLASS(bic->ioprio);
  3392. switch (ioprio_class) {
  3393. default:
  3394. dev_err(bfqq->bfqd->queue->backing_dev_info->dev,
  3395. "bfq: bad prio class %d\n", ioprio_class);
  3396. /* fall through */
  3397. case IOPRIO_CLASS_NONE:
  3398. /*
  3399. * No prio set, inherit CPU scheduling settings.
  3400. */
  3401. bfqq->new_ioprio = task_nice_ioprio(tsk);
  3402. bfqq->new_ioprio_class = task_nice_ioclass(tsk);
  3403. break;
  3404. case IOPRIO_CLASS_RT:
  3405. bfqq->new_ioprio = IOPRIO_PRIO_DATA(bic->ioprio);
  3406. bfqq->new_ioprio_class = IOPRIO_CLASS_RT;
  3407. break;
  3408. case IOPRIO_CLASS_BE:
  3409. bfqq->new_ioprio = IOPRIO_PRIO_DATA(bic->ioprio);
  3410. bfqq->new_ioprio_class = IOPRIO_CLASS_BE;
  3411. break;
  3412. case IOPRIO_CLASS_IDLE:
  3413. bfqq->new_ioprio_class = IOPRIO_CLASS_IDLE;
  3414. bfqq->new_ioprio = 7;
  3415. break;
  3416. }
  3417. if (bfqq->new_ioprio >= IOPRIO_BE_NR) {
  3418. pr_crit("bfq_set_next_ioprio_data: new_ioprio %d\n",
  3419. bfqq->new_ioprio);
  3420. bfqq->new_ioprio = IOPRIO_BE_NR;
  3421. }
  3422. bfqq->entity.new_weight = bfq_ioprio_to_weight(bfqq->new_ioprio);
  3423. bfqq->entity.prio_changed = 1;
  3424. }
  3425. static struct bfq_queue *bfq_get_queue(struct bfq_data *bfqd,
  3426. struct bio *bio, bool is_sync,
  3427. struct bfq_io_cq *bic);
  3428. static void bfq_check_ioprio_change(struct bfq_io_cq *bic, struct bio *bio)
  3429. {
  3430. struct bfq_data *bfqd = bic_to_bfqd(bic);
  3431. struct bfq_queue *bfqq;
  3432. int ioprio = bic->icq.ioc->ioprio;
  3433. /*
  3434. * This condition may trigger on a newly created bic, be sure to
  3435. * drop the lock before returning.
  3436. */
  3437. if (unlikely(!bfqd) || likely(bic->ioprio == ioprio))
  3438. return;
  3439. bic->ioprio = ioprio;
  3440. bfqq = bic_to_bfqq(bic, false);
  3441. if (bfqq) {
  3442. /* release process reference on this queue */
  3443. bfq_put_queue(bfqq);
  3444. bfqq = bfq_get_queue(bfqd, bio, BLK_RW_ASYNC, bic);
  3445. bic_set_bfqq(bic, bfqq, false);
  3446. }
  3447. bfqq = bic_to_bfqq(bic, true);
  3448. if (bfqq)
  3449. bfq_set_next_ioprio_data(bfqq, bic);
  3450. }
  3451. static void bfq_init_bfqq(struct bfq_data *bfqd, struct bfq_queue *bfqq,
  3452. struct bfq_io_cq *bic, pid_t pid, int is_sync)
  3453. {
  3454. RB_CLEAR_NODE(&bfqq->entity.rb_node);
  3455. INIT_LIST_HEAD(&bfqq->fifo);
  3456. INIT_HLIST_NODE(&bfqq->burst_list_node);
  3457. bfqq->ref = 0;
  3458. bfqq->bfqd = bfqd;
  3459. if (bic)
  3460. bfq_set_next_ioprio_data(bfqq, bic);
  3461. if (is_sync) {
  3462. /*
  3463. * No need to mark as has_short_ttime if in
  3464. * idle_class, because no device idling is performed
  3465. * for queues in idle class
  3466. */
  3467. if (!bfq_class_idle(bfqq))
  3468. /* tentatively mark as has_short_ttime */
  3469. bfq_mark_bfqq_has_short_ttime(bfqq);
  3470. bfq_mark_bfqq_sync(bfqq);
  3471. bfq_mark_bfqq_just_created(bfqq);
  3472. } else
  3473. bfq_clear_bfqq_sync(bfqq);
  3474. /* set end request to minus infinity from now */
  3475. bfqq->ttime.last_end_request = ktime_get_ns() + 1;
  3476. bfq_mark_bfqq_IO_bound(bfqq);
  3477. bfqq->pid = pid;
  3478. /* Tentative initial value to trade off between thr and lat */
  3479. bfqq->max_budget = (2 * bfq_max_budget(bfqd)) / 3;
  3480. bfqq->budget_timeout = bfq_smallest_from_now();
  3481. bfqq->wr_coeff = 1;
  3482. bfqq->last_wr_start_finish = jiffies;
  3483. bfqq->wr_start_at_switch_to_srt = bfq_smallest_from_now();
  3484. bfqq->split_time = bfq_smallest_from_now();
  3485. /*
  3486. * Set to the value for which bfqq will not be deemed as
  3487. * soft rt when it becomes backlogged.
  3488. */
  3489. bfqq->soft_rt_next_start = bfq_greatest_from_now();
  3490. /* first request is almost certainly seeky */
  3491. bfqq->seek_history = 1;
  3492. }
  3493. static struct bfq_queue **bfq_async_queue_prio(struct bfq_data *bfqd,
  3494. struct bfq_group *bfqg,
  3495. int ioprio_class, int ioprio)
  3496. {
  3497. switch (ioprio_class) {
  3498. case IOPRIO_CLASS_RT:
  3499. return &bfqg->async_bfqq[0][ioprio];
  3500. case IOPRIO_CLASS_NONE:
  3501. ioprio = IOPRIO_NORM;
  3502. /* fall through */
  3503. case IOPRIO_CLASS_BE:
  3504. return &bfqg->async_bfqq[1][ioprio];
  3505. case IOPRIO_CLASS_IDLE:
  3506. return &bfqg->async_idle_bfqq;
  3507. default:
  3508. return NULL;
  3509. }
  3510. }
  3511. static struct bfq_queue *bfq_get_queue(struct bfq_data *bfqd,
  3512. struct bio *bio, bool is_sync,
  3513. struct bfq_io_cq *bic)
  3514. {
  3515. const int ioprio = IOPRIO_PRIO_DATA(bic->ioprio);
  3516. const int ioprio_class = IOPRIO_PRIO_CLASS(bic->ioprio);
  3517. struct bfq_queue **async_bfqq = NULL;
  3518. struct bfq_queue *bfqq;
  3519. struct bfq_group *bfqg;
  3520. rcu_read_lock();
  3521. bfqg = bfq_find_set_group(bfqd, bio_blkcg(bio));
  3522. if (!bfqg) {
  3523. bfqq = &bfqd->oom_bfqq;
  3524. goto out;
  3525. }
  3526. if (!is_sync) {
  3527. async_bfqq = bfq_async_queue_prio(bfqd, bfqg, ioprio_class,
  3528. ioprio);
  3529. bfqq = *async_bfqq;
  3530. if (bfqq)
  3531. goto out;
  3532. }
  3533. bfqq = kmem_cache_alloc_node(bfq_pool,
  3534. GFP_NOWAIT | __GFP_ZERO | __GFP_NOWARN,
  3535. bfqd->queue->node);
  3536. if (bfqq) {
  3537. bfq_init_bfqq(bfqd, bfqq, bic, current->pid,
  3538. is_sync);
  3539. bfq_init_entity(&bfqq->entity, bfqg);
  3540. bfq_log_bfqq(bfqd, bfqq, "allocated");
  3541. } else {
  3542. bfqq = &bfqd->oom_bfqq;
  3543. bfq_log_bfqq(bfqd, bfqq, "using oom bfqq");
  3544. goto out;
  3545. }
  3546. /*
  3547. * Pin the queue now that it's allocated, scheduler exit will
  3548. * prune it.
  3549. */
  3550. if (async_bfqq) {
  3551. bfqq->ref++; /*
  3552. * Extra group reference, w.r.t. sync
  3553. * queue. This extra reference is removed
  3554. * only if bfqq->bfqg disappears, to
  3555. * guarantee that this queue is not freed
  3556. * until its group goes away.
  3557. */
  3558. bfq_log_bfqq(bfqd, bfqq, "get_queue, bfqq not in async: %p, %d",
  3559. bfqq, bfqq->ref);
  3560. *async_bfqq = bfqq;
  3561. }
  3562. out:
  3563. bfqq->ref++; /* get a process reference to this queue */
  3564. bfq_log_bfqq(bfqd, bfqq, "get_queue, at end: %p, %d", bfqq, bfqq->ref);
  3565. rcu_read_unlock();
  3566. return bfqq;
  3567. }
  3568. static void bfq_update_io_thinktime(struct bfq_data *bfqd,
  3569. struct bfq_queue *bfqq)
  3570. {
  3571. struct bfq_ttime *ttime = &bfqq->ttime;
  3572. u64 elapsed = ktime_get_ns() - bfqq->ttime.last_end_request;
  3573. elapsed = min_t(u64, elapsed, 2ULL * bfqd->bfq_slice_idle);
  3574. ttime->ttime_samples = (7*bfqq->ttime.ttime_samples + 256) / 8;
  3575. ttime->ttime_total = div_u64(7*ttime->ttime_total + 256*elapsed, 8);
  3576. ttime->ttime_mean = div64_ul(ttime->ttime_total + 128,
  3577. ttime->ttime_samples);
  3578. }
  3579. static void
  3580. bfq_update_io_seektime(struct bfq_data *bfqd, struct bfq_queue *bfqq,
  3581. struct request *rq)
  3582. {
  3583. bfqq->seek_history <<= 1;
  3584. bfqq->seek_history |=
  3585. get_sdist(bfqq->last_request_pos, rq) > BFQQ_SEEK_THR &&
  3586. (!blk_queue_nonrot(bfqd->queue) ||
  3587. blk_rq_sectors(rq) < BFQQ_SECT_THR_NONROT);
  3588. }
  3589. static void bfq_update_has_short_ttime(struct bfq_data *bfqd,
  3590. struct bfq_queue *bfqq,
  3591. struct bfq_io_cq *bic)
  3592. {
  3593. bool has_short_ttime = true;
  3594. /*
  3595. * No need to update has_short_ttime if bfqq is async or in
  3596. * idle io prio class, or if bfq_slice_idle is zero, because
  3597. * no device idling is performed for bfqq in this case.
  3598. */
  3599. if (!bfq_bfqq_sync(bfqq) || bfq_class_idle(bfqq) ||
  3600. bfqd->bfq_slice_idle == 0)
  3601. return;
  3602. /* Idle window just restored, statistics are meaningless. */
  3603. if (time_is_after_eq_jiffies(bfqq->split_time +
  3604. bfqd->bfq_wr_min_idle_time))
  3605. return;
  3606. /* Think time is infinite if no process is linked to
  3607. * bfqq. Otherwise check average think time to
  3608. * decide whether to mark as has_short_ttime
  3609. */
  3610. if (atomic_read(&bic->icq.ioc->active_ref) == 0 ||
  3611. (bfq_sample_valid(bfqq->ttime.ttime_samples) &&
  3612. bfqq->ttime.ttime_mean > bfqd->bfq_slice_idle))
  3613. has_short_ttime = false;
  3614. bfq_log_bfqq(bfqd, bfqq, "update_has_short_ttime: has_short_ttime %d",
  3615. has_short_ttime);
  3616. if (has_short_ttime)
  3617. bfq_mark_bfqq_has_short_ttime(bfqq);
  3618. else
  3619. bfq_clear_bfqq_has_short_ttime(bfqq);
  3620. }
  3621. /*
  3622. * Called when a new fs request (rq) is added to bfqq. Check if there's
  3623. * something we should do about it.
  3624. */
  3625. static void bfq_rq_enqueued(struct bfq_data *bfqd, struct bfq_queue *bfqq,
  3626. struct request *rq)
  3627. {
  3628. struct bfq_io_cq *bic = RQ_BIC(rq);
  3629. if (rq->cmd_flags & REQ_META)
  3630. bfqq->meta_pending++;
  3631. bfq_update_io_thinktime(bfqd, bfqq);
  3632. bfq_update_has_short_ttime(bfqd, bfqq, bic);
  3633. bfq_update_io_seektime(bfqd, bfqq, rq);
  3634. bfq_log_bfqq(bfqd, bfqq,
  3635. "rq_enqueued: has_short_ttime=%d (seeky %d)",
  3636. bfq_bfqq_has_short_ttime(bfqq), BFQQ_SEEKY(bfqq));
  3637. bfqq->last_request_pos = blk_rq_pos(rq) + blk_rq_sectors(rq);
  3638. if (bfqq == bfqd->in_service_queue && bfq_bfqq_wait_request(bfqq)) {
  3639. bool small_req = bfqq->queued[rq_is_sync(rq)] == 1 &&
  3640. blk_rq_sectors(rq) < 32;
  3641. bool budget_timeout = bfq_bfqq_budget_timeout(bfqq);
  3642. /*
  3643. * There is just this request queued: if the request
  3644. * is small and the queue is not to be expired, then
  3645. * just exit.
  3646. *
  3647. * In this way, if the device is being idled to wait
  3648. * for a new request from the in-service queue, we
  3649. * avoid unplugging the device and committing the
  3650. * device to serve just a small request. On the
  3651. * contrary, we wait for the block layer to decide
  3652. * when to unplug the device: hopefully, new requests
  3653. * will be merged to this one quickly, then the device
  3654. * will be unplugged and larger requests will be
  3655. * dispatched.
  3656. */
  3657. if (small_req && !budget_timeout)
  3658. return;
  3659. /*
  3660. * A large enough request arrived, or the queue is to
  3661. * be expired: in both cases disk idling is to be
  3662. * stopped, so clear wait_request flag and reset
  3663. * timer.
  3664. */
  3665. bfq_clear_bfqq_wait_request(bfqq);
  3666. hrtimer_try_to_cancel(&bfqd->idle_slice_timer);
  3667. bfqg_stats_update_idle_time(bfqq_group(bfqq));
  3668. /*
  3669. * The queue is not empty, because a new request just
  3670. * arrived. Hence we can safely expire the queue, in
  3671. * case of budget timeout, without risking that the
  3672. * timestamps of the queue are not updated correctly.
  3673. * See [1] for more details.
  3674. */
  3675. if (budget_timeout)
  3676. bfq_bfqq_expire(bfqd, bfqq, false,
  3677. BFQQE_BUDGET_TIMEOUT);
  3678. }
  3679. }
  3680. static void __bfq_insert_request(struct bfq_data *bfqd, struct request *rq)
  3681. {
  3682. struct bfq_queue *bfqq = RQ_BFQQ(rq),
  3683. *new_bfqq = bfq_setup_cooperator(bfqd, bfqq, rq, true);
  3684. if (new_bfqq) {
  3685. if (bic_to_bfqq(RQ_BIC(rq), 1) != bfqq)
  3686. new_bfqq = bic_to_bfqq(RQ_BIC(rq), 1);
  3687. /*
  3688. * Release the request's reference to the old bfqq
  3689. * and make sure one is taken to the shared queue.
  3690. */
  3691. new_bfqq->allocated++;
  3692. bfqq->allocated--;
  3693. new_bfqq->ref++;
  3694. bfq_clear_bfqq_just_created(bfqq);
  3695. /*
  3696. * If the bic associated with the process
  3697. * issuing this request still points to bfqq
  3698. * (and thus has not been already redirected
  3699. * to new_bfqq or even some other bfq_queue),
  3700. * then complete the merge and redirect it to
  3701. * new_bfqq.
  3702. */
  3703. if (bic_to_bfqq(RQ_BIC(rq), 1) == bfqq)
  3704. bfq_merge_bfqqs(bfqd, RQ_BIC(rq),
  3705. bfqq, new_bfqq);
  3706. /*
  3707. * rq is about to be enqueued into new_bfqq,
  3708. * release rq reference on bfqq
  3709. */
  3710. bfq_put_queue(bfqq);
  3711. rq->elv.priv[1] = new_bfqq;
  3712. bfqq = new_bfqq;
  3713. }
  3714. bfq_add_request(rq);
  3715. rq->fifo_time = ktime_get_ns() + bfqd->bfq_fifo_expire[rq_is_sync(rq)];
  3716. list_add_tail(&rq->queuelist, &bfqq->fifo);
  3717. bfq_rq_enqueued(bfqd, bfqq, rq);
  3718. }
  3719. static void bfq_insert_request(struct blk_mq_hw_ctx *hctx, struct request *rq,
  3720. bool at_head)
  3721. {
  3722. struct request_queue *q = hctx->queue;
  3723. struct bfq_data *bfqd = q->elevator->elevator_data;
  3724. spin_lock_irq(&bfqd->lock);
  3725. if (blk_mq_sched_try_insert_merge(q, rq)) {
  3726. spin_unlock_irq(&bfqd->lock);
  3727. return;
  3728. }
  3729. spin_unlock_irq(&bfqd->lock);
  3730. blk_mq_sched_request_inserted(rq);
  3731. spin_lock_irq(&bfqd->lock);
  3732. if (at_head || blk_rq_is_passthrough(rq)) {
  3733. if (at_head)
  3734. list_add(&rq->queuelist, &bfqd->dispatch);
  3735. else
  3736. list_add_tail(&rq->queuelist, &bfqd->dispatch);
  3737. } else {
  3738. __bfq_insert_request(bfqd, rq);
  3739. if (rq_mergeable(rq)) {
  3740. elv_rqhash_add(q, rq);
  3741. if (!q->last_merge)
  3742. q->last_merge = rq;
  3743. }
  3744. }
  3745. spin_unlock_irq(&bfqd->lock);
  3746. }
  3747. static void bfq_insert_requests(struct blk_mq_hw_ctx *hctx,
  3748. struct list_head *list, bool at_head)
  3749. {
  3750. while (!list_empty(list)) {
  3751. struct request *rq;
  3752. rq = list_first_entry(list, struct request, queuelist);
  3753. list_del_init(&rq->queuelist);
  3754. bfq_insert_request(hctx, rq, at_head);
  3755. }
  3756. }
  3757. static void bfq_update_hw_tag(struct bfq_data *bfqd)
  3758. {
  3759. bfqd->max_rq_in_driver = max_t(int, bfqd->max_rq_in_driver,
  3760. bfqd->rq_in_driver);
  3761. if (bfqd->hw_tag == 1)
  3762. return;
  3763. /*
  3764. * This sample is valid if the number of outstanding requests
  3765. * is large enough to allow a queueing behavior. Note that the
  3766. * sum is not exact, as it's not taking into account deactivated
  3767. * requests.
  3768. */
  3769. if (bfqd->rq_in_driver + bfqd->queued < BFQ_HW_QUEUE_THRESHOLD)
  3770. return;
  3771. if (bfqd->hw_tag_samples++ < BFQ_HW_QUEUE_SAMPLES)
  3772. return;
  3773. bfqd->hw_tag = bfqd->max_rq_in_driver > BFQ_HW_QUEUE_THRESHOLD;
  3774. bfqd->max_rq_in_driver = 0;
  3775. bfqd->hw_tag_samples = 0;
  3776. }
  3777. static void bfq_completed_request(struct bfq_queue *bfqq, struct bfq_data *bfqd)
  3778. {
  3779. u64 now_ns;
  3780. u32 delta_us;
  3781. bfq_update_hw_tag(bfqd);
  3782. bfqd->rq_in_driver--;
  3783. bfqq->dispatched--;
  3784. if (!bfqq->dispatched && !bfq_bfqq_busy(bfqq)) {
  3785. /*
  3786. * Set budget_timeout (which we overload to store the
  3787. * time at which the queue remains with no backlog and
  3788. * no outstanding request; used by the weight-raising
  3789. * mechanism).
  3790. */
  3791. bfqq->budget_timeout = jiffies;
  3792. bfq_weights_tree_remove(bfqd, &bfqq->entity,
  3793. &bfqd->queue_weights_tree);
  3794. }
  3795. now_ns = ktime_get_ns();
  3796. bfqq->ttime.last_end_request = now_ns;
  3797. /*
  3798. * Using us instead of ns, to get a reasonable precision in
  3799. * computing rate in next check.
  3800. */
  3801. delta_us = div_u64(now_ns - bfqd->last_completion, NSEC_PER_USEC);
  3802. /*
  3803. * If the request took rather long to complete, and, according
  3804. * to the maximum request size recorded, this completion latency
  3805. * implies that the request was certainly served at a very low
  3806. * rate (less than 1M sectors/sec), then the whole observation
  3807. * interval that lasts up to this time instant cannot be a
  3808. * valid time interval for computing a new peak rate. Invoke
  3809. * bfq_update_rate_reset to have the following three steps
  3810. * taken:
  3811. * - close the observation interval at the last (previous)
  3812. * request dispatch or completion
  3813. * - compute rate, if possible, for that observation interval
  3814. * - reset to zero samples, which will trigger a proper
  3815. * re-initialization of the observation interval on next
  3816. * dispatch
  3817. */
  3818. if (delta_us > BFQ_MIN_TT/NSEC_PER_USEC &&
  3819. (bfqd->last_rq_max_size<<BFQ_RATE_SHIFT)/delta_us <
  3820. 1UL<<(BFQ_RATE_SHIFT - 10))
  3821. bfq_update_rate_reset(bfqd, NULL);
  3822. bfqd->last_completion = now_ns;
  3823. /*
  3824. * If we are waiting to discover whether the request pattern
  3825. * of the task associated with the queue is actually
  3826. * isochronous, and both requisites for this condition to hold
  3827. * are now satisfied, then compute soft_rt_next_start (see the
  3828. * comments on the function bfq_bfqq_softrt_next_start()). We
  3829. * schedule this delayed check when bfqq expires, if it still
  3830. * has in-flight requests.
  3831. */
  3832. if (bfq_bfqq_softrt_update(bfqq) && bfqq->dispatched == 0 &&
  3833. RB_EMPTY_ROOT(&bfqq->sort_list))
  3834. bfqq->soft_rt_next_start =
  3835. bfq_bfqq_softrt_next_start(bfqd, bfqq);
  3836. /*
  3837. * If this is the in-service queue, check if it needs to be expired,
  3838. * or if we want to idle in case it has no pending requests.
  3839. */
  3840. if (bfqd->in_service_queue == bfqq) {
  3841. if (bfqq->dispatched == 0 && bfq_bfqq_must_idle(bfqq)) {
  3842. bfq_arm_slice_timer(bfqd);
  3843. return;
  3844. } else if (bfq_may_expire_for_budg_timeout(bfqq))
  3845. bfq_bfqq_expire(bfqd, bfqq, false,
  3846. BFQQE_BUDGET_TIMEOUT);
  3847. else if (RB_EMPTY_ROOT(&bfqq->sort_list) &&
  3848. (bfqq->dispatched == 0 ||
  3849. !bfq_bfqq_may_idle(bfqq)))
  3850. bfq_bfqq_expire(bfqd, bfqq, false,
  3851. BFQQE_NO_MORE_REQUESTS);
  3852. }
  3853. if (!bfqd->rq_in_driver)
  3854. bfq_schedule_dispatch(bfqd);
  3855. }
  3856. static void bfq_put_rq_priv_body(struct bfq_queue *bfqq)
  3857. {
  3858. bfqq->allocated--;
  3859. bfq_put_queue(bfqq);
  3860. }
  3861. static void bfq_finish_request(struct request *rq)
  3862. {
  3863. struct bfq_queue *bfqq;
  3864. struct bfq_data *bfqd;
  3865. if (!rq->elv.icq)
  3866. return;
  3867. bfqq = RQ_BFQQ(rq);
  3868. bfqd = bfqq->bfqd;
  3869. if (rq->rq_flags & RQF_STARTED)
  3870. bfqg_stats_update_completion(bfqq_group(bfqq),
  3871. rq_start_time_ns(rq),
  3872. rq_io_start_time_ns(rq),
  3873. rq->cmd_flags);
  3874. if (likely(rq->rq_flags & RQF_STARTED)) {
  3875. unsigned long flags;
  3876. spin_lock_irqsave(&bfqd->lock, flags);
  3877. bfq_completed_request(bfqq, bfqd);
  3878. bfq_put_rq_priv_body(bfqq);
  3879. spin_unlock_irqrestore(&bfqd->lock, flags);
  3880. } else {
  3881. /*
  3882. * Request rq may be still/already in the scheduler,
  3883. * in which case we need to remove it. And we cannot
  3884. * defer such a check and removal, to avoid
  3885. * inconsistencies in the time interval from the end
  3886. * of this function to the start of the deferred work.
  3887. * This situation seems to occur only in process
  3888. * context, as a consequence of a merge. In the
  3889. * current version of the code, this implies that the
  3890. * lock is held.
  3891. */
  3892. if (!RB_EMPTY_NODE(&rq->rb_node))
  3893. bfq_remove_request(rq->q, rq);
  3894. bfq_put_rq_priv_body(bfqq);
  3895. }
  3896. rq->elv.priv[0] = NULL;
  3897. rq->elv.priv[1] = NULL;
  3898. }
  3899. /*
  3900. * Returns NULL if a new bfqq should be allocated, or the old bfqq if this
  3901. * was the last process referring to that bfqq.
  3902. */
  3903. static struct bfq_queue *
  3904. bfq_split_bfqq(struct bfq_io_cq *bic, struct bfq_queue *bfqq)
  3905. {
  3906. bfq_log_bfqq(bfqq->bfqd, bfqq, "splitting queue");
  3907. if (bfqq_process_refs(bfqq) == 1) {
  3908. bfqq->pid = current->pid;
  3909. bfq_clear_bfqq_coop(bfqq);
  3910. bfq_clear_bfqq_split_coop(bfqq);
  3911. return bfqq;
  3912. }
  3913. bic_set_bfqq(bic, NULL, 1);
  3914. bfq_put_cooperator(bfqq);
  3915. bfq_put_queue(bfqq);
  3916. return NULL;
  3917. }
  3918. static struct bfq_queue *bfq_get_bfqq_handle_split(struct bfq_data *bfqd,
  3919. struct bfq_io_cq *bic,
  3920. struct bio *bio,
  3921. bool split, bool is_sync,
  3922. bool *new_queue)
  3923. {
  3924. struct bfq_queue *bfqq = bic_to_bfqq(bic, is_sync);
  3925. if (likely(bfqq && bfqq != &bfqd->oom_bfqq))
  3926. return bfqq;
  3927. if (new_queue)
  3928. *new_queue = true;
  3929. if (bfqq)
  3930. bfq_put_queue(bfqq);
  3931. bfqq = bfq_get_queue(bfqd, bio, is_sync, bic);
  3932. bic_set_bfqq(bic, bfqq, is_sync);
  3933. if (split && is_sync) {
  3934. if ((bic->was_in_burst_list && bfqd->large_burst) ||
  3935. bic->saved_in_large_burst)
  3936. bfq_mark_bfqq_in_large_burst(bfqq);
  3937. else {
  3938. bfq_clear_bfqq_in_large_burst(bfqq);
  3939. if (bic->was_in_burst_list)
  3940. hlist_add_head(&bfqq->burst_list_node,
  3941. &bfqd->burst_list);
  3942. }
  3943. bfqq->split_time = jiffies;
  3944. }
  3945. return bfqq;
  3946. }
  3947. /*
  3948. * Allocate bfq data structures associated with this request.
  3949. */
  3950. static void bfq_prepare_request(struct request *rq, struct bio *bio)
  3951. {
  3952. struct request_queue *q = rq->q;
  3953. struct bfq_data *bfqd = q->elevator->elevator_data;
  3954. struct bfq_io_cq *bic;
  3955. const int is_sync = rq_is_sync(rq);
  3956. struct bfq_queue *bfqq;
  3957. bool new_queue = false;
  3958. bool bfqq_already_existing = false, split = false;
  3959. if (!rq->elv.icq)
  3960. return;
  3961. bic = icq_to_bic(rq->elv.icq);
  3962. spin_lock_irq(&bfqd->lock);
  3963. bfq_check_ioprio_change(bic, bio);
  3964. bfq_bic_update_cgroup(bic, bio);
  3965. bfqq = bfq_get_bfqq_handle_split(bfqd, bic, bio, false, is_sync,
  3966. &new_queue);
  3967. if (likely(!new_queue)) {
  3968. /* If the queue was seeky for too long, break it apart. */
  3969. if (bfq_bfqq_coop(bfqq) && bfq_bfqq_split_coop(bfqq)) {
  3970. bfq_log_bfqq(bfqd, bfqq, "breaking apart bfqq");
  3971. /* Update bic before losing reference to bfqq */
  3972. if (bfq_bfqq_in_large_burst(bfqq))
  3973. bic->saved_in_large_burst = true;
  3974. bfqq = bfq_split_bfqq(bic, bfqq);
  3975. split = true;
  3976. if (!bfqq)
  3977. bfqq = bfq_get_bfqq_handle_split(bfqd, bic, bio,
  3978. true, is_sync,
  3979. NULL);
  3980. else
  3981. bfqq_already_existing = true;
  3982. }
  3983. }
  3984. bfqq->allocated++;
  3985. bfqq->ref++;
  3986. bfq_log_bfqq(bfqd, bfqq, "get_request %p: bfqq %p, %d",
  3987. rq, bfqq, bfqq->ref);
  3988. rq->elv.priv[0] = bic;
  3989. rq->elv.priv[1] = bfqq;
  3990. /*
  3991. * If a bfq_queue has only one process reference, it is owned
  3992. * by only this bic: we can then set bfqq->bic = bic. in
  3993. * addition, if the queue has also just been split, we have to
  3994. * resume its state.
  3995. */
  3996. if (likely(bfqq != &bfqd->oom_bfqq) && bfqq_process_refs(bfqq) == 1) {
  3997. bfqq->bic = bic;
  3998. if (split) {
  3999. /*
  4000. * The queue has just been split from a shared
  4001. * queue: restore the idle window and the
  4002. * possible weight raising period.
  4003. */
  4004. bfq_bfqq_resume_state(bfqq, bfqd, bic,
  4005. bfqq_already_existing);
  4006. }
  4007. }
  4008. if (unlikely(bfq_bfqq_just_created(bfqq)))
  4009. bfq_handle_burst(bfqd, bfqq);
  4010. spin_unlock_irq(&bfqd->lock);
  4011. }
  4012. static void bfq_idle_slice_timer_body(struct bfq_queue *bfqq)
  4013. {
  4014. struct bfq_data *bfqd = bfqq->bfqd;
  4015. enum bfqq_expiration reason;
  4016. unsigned long flags;
  4017. spin_lock_irqsave(&bfqd->lock, flags);
  4018. bfq_clear_bfqq_wait_request(bfqq);
  4019. if (bfqq != bfqd->in_service_queue) {
  4020. spin_unlock_irqrestore(&bfqd->lock, flags);
  4021. return;
  4022. }
  4023. if (bfq_bfqq_budget_timeout(bfqq))
  4024. /*
  4025. * Also here the queue can be safely expired
  4026. * for budget timeout without wasting
  4027. * guarantees
  4028. */
  4029. reason = BFQQE_BUDGET_TIMEOUT;
  4030. else if (bfqq->queued[0] == 0 && bfqq->queued[1] == 0)
  4031. /*
  4032. * The queue may not be empty upon timer expiration,
  4033. * because we may not disable the timer when the
  4034. * first request of the in-service queue arrives
  4035. * during disk idling.
  4036. */
  4037. reason = BFQQE_TOO_IDLE;
  4038. else
  4039. goto schedule_dispatch;
  4040. bfq_bfqq_expire(bfqd, bfqq, true, reason);
  4041. schedule_dispatch:
  4042. spin_unlock_irqrestore(&bfqd->lock, flags);
  4043. bfq_schedule_dispatch(bfqd);
  4044. }
  4045. /*
  4046. * Handler of the expiration of the timer running if the in-service queue
  4047. * is idling inside its time slice.
  4048. */
  4049. static enum hrtimer_restart bfq_idle_slice_timer(struct hrtimer *timer)
  4050. {
  4051. struct bfq_data *bfqd = container_of(timer, struct bfq_data,
  4052. idle_slice_timer);
  4053. struct bfq_queue *bfqq = bfqd->in_service_queue;
  4054. /*
  4055. * Theoretical race here: the in-service queue can be NULL or
  4056. * different from the queue that was idling if a new request
  4057. * arrives for the current queue and there is a full dispatch
  4058. * cycle that changes the in-service queue. This can hardly
  4059. * happen, but in the worst case we just expire a queue too
  4060. * early.
  4061. */
  4062. if (bfqq)
  4063. bfq_idle_slice_timer_body(bfqq);
  4064. return HRTIMER_NORESTART;
  4065. }
  4066. static void __bfq_put_async_bfqq(struct bfq_data *bfqd,
  4067. struct bfq_queue **bfqq_ptr)
  4068. {
  4069. struct bfq_queue *bfqq = *bfqq_ptr;
  4070. bfq_log(bfqd, "put_async_bfqq: %p", bfqq);
  4071. if (bfqq) {
  4072. bfq_bfqq_move(bfqd, bfqq, bfqd->root_group);
  4073. bfq_log_bfqq(bfqd, bfqq, "put_async_bfqq: putting %p, %d",
  4074. bfqq, bfqq->ref);
  4075. bfq_put_queue(bfqq);
  4076. *bfqq_ptr = NULL;
  4077. }
  4078. }
  4079. /*
  4080. * Release all the bfqg references to its async queues. If we are
  4081. * deallocating the group these queues may still contain requests, so
  4082. * we reparent them to the root cgroup (i.e., the only one that will
  4083. * exist for sure until all the requests on a device are gone).
  4084. */
  4085. void bfq_put_async_queues(struct bfq_data *bfqd, struct bfq_group *bfqg)
  4086. {
  4087. int i, j;
  4088. for (i = 0; i < 2; i++)
  4089. for (j = 0; j < IOPRIO_BE_NR; j++)
  4090. __bfq_put_async_bfqq(bfqd, &bfqg->async_bfqq[i][j]);
  4091. __bfq_put_async_bfqq(bfqd, &bfqg->async_idle_bfqq);
  4092. }
  4093. static void bfq_exit_queue(struct elevator_queue *e)
  4094. {
  4095. struct bfq_data *bfqd = e->elevator_data;
  4096. struct bfq_queue *bfqq, *n;
  4097. hrtimer_cancel(&bfqd->idle_slice_timer);
  4098. spin_lock_irq(&bfqd->lock);
  4099. list_for_each_entry_safe(bfqq, n, &bfqd->idle_list, bfqq_list)
  4100. bfq_deactivate_bfqq(bfqd, bfqq, false, false);
  4101. spin_unlock_irq(&bfqd->lock);
  4102. hrtimer_cancel(&bfqd->idle_slice_timer);
  4103. #ifdef CONFIG_BFQ_GROUP_IOSCHED
  4104. blkcg_deactivate_policy(bfqd->queue, &blkcg_policy_bfq);
  4105. #else
  4106. spin_lock_irq(&bfqd->lock);
  4107. bfq_put_async_queues(bfqd, bfqd->root_group);
  4108. kfree(bfqd->root_group);
  4109. spin_unlock_irq(&bfqd->lock);
  4110. #endif
  4111. kfree(bfqd);
  4112. }
  4113. static void bfq_init_root_group(struct bfq_group *root_group,
  4114. struct bfq_data *bfqd)
  4115. {
  4116. int i;
  4117. #ifdef CONFIG_BFQ_GROUP_IOSCHED
  4118. root_group->entity.parent = NULL;
  4119. root_group->my_entity = NULL;
  4120. root_group->bfqd = bfqd;
  4121. #endif
  4122. root_group->rq_pos_tree = RB_ROOT;
  4123. for (i = 0; i < BFQ_IOPRIO_CLASSES; i++)
  4124. root_group->sched_data.service_tree[i] = BFQ_SERVICE_TREE_INIT;
  4125. root_group->sched_data.bfq_class_idle_last_service = jiffies;
  4126. }
  4127. static int bfq_init_queue(struct request_queue *q, struct elevator_type *e)
  4128. {
  4129. struct bfq_data *bfqd;
  4130. struct elevator_queue *eq;
  4131. eq = elevator_alloc(q, e);
  4132. if (!eq)
  4133. return -ENOMEM;
  4134. bfqd = kzalloc_node(sizeof(*bfqd), GFP_KERNEL, q->node);
  4135. if (!bfqd) {
  4136. kobject_put(&eq->kobj);
  4137. return -ENOMEM;
  4138. }
  4139. eq->elevator_data = bfqd;
  4140. spin_lock_irq(q->queue_lock);
  4141. q->elevator = eq;
  4142. spin_unlock_irq(q->queue_lock);
  4143. /*
  4144. * Our fallback bfqq if bfq_find_alloc_queue() runs into OOM issues.
  4145. * Grab a permanent reference to it, so that the normal code flow
  4146. * will not attempt to free it.
  4147. */
  4148. bfq_init_bfqq(bfqd, &bfqd->oom_bfqq, NULL, 1, 0);
  4149. bfqd->oom_bfqq.ref++;
  4150. bfqd->oom_bfqq.new_ioprio = BFQ_DEFAULT_QUEUE_IOPRIO;
  4151. bfqd->oom_bfqq.new_ioprio_class = IOPRIO_CLASS_BE;
  4152. bfqd->oom_bfqq.entity.new_weight =
  4153. bfq_ioprio_to_weight(bfqd->oom_bfqq.new_ioprio);
  4154. /* oom_bfqq does not participate to bursts */
  4155. bfq_clear_bfqq_just_created(&bfqd->oom_bfqq);
  4156. /*
  4157. * Trigger weight initialization, according to ioprio, at the
  4158. * oom_bfqq's first activation. The oom_bfqq's ioprio and ioprio
  4159. * class won't be changed any more.
  4160. */
  4161. bfqd->oom_bfqq.entity.prio_changed = 1;
  4162. bfqd->queue = q;
  4163. INIT_LIST_HEAD(&bfqd->dispatch);
  4164. hrtimer_init(&bfqd->idle_slice_timer, CLOCK_MONOTONIC,
  4165. HRTIMER_MODE_REL);
  4166. bfqd->idle_slice_timer.function = bfq_idle_slice_timer;
  4167. bfqd->queue_weights_tree = RB_ROOT;
  4168. bfqd->group_weights_tree = RB_ROOT;
  4169. INIT_LIST_HEAD(&bfqd->active_list);
  4170. INIT_LIST_HEAD(&bfqd->idle_list);
  4171. INIT_HLIST_HEAD(&bfqd->burst_list);
  4172. bfqd->hw_tag = -1;
  4173. bfqd->bfq_max_budget = bfq_default_max_budget;
  4174. bfqd->bfq_fifo_expire[0] = bfq_fifo_expire[0];
  4175. bfqd->bfq_fifo_expire[1] = bfq_fifo_expire[1];
  4176. bfqd->bfq_back_max = bfq_back_max;
  4177. bfqd->bfq_back_penalty = bfq_back_penalty;
  4178. bfqd->bfq_slice_idle = bfq_slice_idle;
  4179. bfqd->bfq_timeout = bfq_timeout;
  4180. bfqd->bfq_requests_within_timer = 120;
  4181. bfqd->bfq_large_burst_thresh = 8;
  4182. bfqd->bfq_burst_interval = msecs_to_jiffies(180);
  4183. bfqd->low_latency = true;
  4184. /*
  4185. * Trade-off between responsiveness and fairness.
  4186. */
  4187. bfqd->bfq_wr_coeff = 30;
  4188. bfqd->bfq_wr_rt_max_time = msecs_to_jiffies(300);
  4189. bfqd->bfq_wr_max_time = 0;
  4190. bfqd->bfq_wr_min_idle_time = msecs_to_jiffies(2000);
  4191. bfqd->bfq_wr_min_inter_arr_async = msecs_to_jiffies(500);
  4192. bfqd->bfq_wr_max_softrt_rate = 7000; /*
  4193. * Approximate rate required
  4194. * to playback or record a
  4195. * high-definition compressed
  4196. * video.
  4197. */
  4198. bfqd->wr_busy_queues = 0;
  4199. /*
  4200. * Begin by assuming, optimistically, that the device is a
  4201. * high-speed one, and that its peak rate is equal to 2/3 of
  4202. * the highest reference rate.
  4203. */
  4204. bfqd->RT_prod = R_fast[blk_queue_nonrot(bfqd->queue)] *
  4205. T_fast[blk_queue_nonrot(bfqd->queue)];
  4206. bfqd->peak_rate = R_fast[blk_queue_nonrot(bfqd->queue)] * 2 / 3;
  4207. bfqd->device_speed = BFQ_BFQD_FAST;
  4208. spin_lock_init(&bfqd->lock);
  4209. /*
  4210. * The invocation of the next bfq_create_group_hierarchy
  4211. * function is the head of a chain of function calls
  4212. * (bfq_create_group_hierarchy->blkcg_activate_policy->
  4213. * blk_mq_freeze_queue) that may lead to the invocation of the
  4214. * has_work hook function. For this reason,
  4215. * bfq_create_group_hierarchy is invoked only after all
  4216. * scheduler data has been initialized, apart from the fields
  4217. * that can be initialized only after invoking
  4218. * bfq_create_group_hierarchy. This, in particular, enables
  4219. * has_work to correctly return false. Of course, to avoid
  4220. * other inconsistencies, the blk-mq stack must then refrain
  4221. * from invoking further scheduler hooks before this init
  4222. * function is finished.
  4223. */
  4224. bfqd->root_group = bfq_create_group_hierarchy(bfqd, q->node);
  4225. if (!bfqd->root_group)
  4226. goto out_free;
  4227. bfq_init_root_group(bfqd->root_group, bfqd);
  4228. bfq_init_entity(&bfqd->oom_bfqq.entity, bfqd->root_group);
  4229. return 0;
  4230. out_free:
  4231. kfree(bfqd);
  4232. kobject_put(&eq->kobj);
  4233. return -ENOMEM;
  4234. }
  4235. static void bfq_slab_kill(void)
  4236. {
  4237. kmem_cache_destroy(bfq_pool);
  4238. }
  4239. static int __init bfq_slab_setup(void)
  4240. {
  4241. bfq_pool = KMEM_CACHE(bfq_queue, 0);
  4242. if (!bfq_pool)
  4243. return -ENOMEM;
  4244. return 0;
  4245. }
  4246. static ssize_t bfq_var_show(unsigned int var, char *page)
  4247. {
  4248. return sprintf(page, "%u\n", var);
  4249. }
  4250. static int bfq_var_store(unsigned long *var, const char *page)
  4251. {
  4252. unsigned long new_val;
  4253. int ret = kstrtoul(page, 10, &new_val);
  4254. if (ret)
  4255. return ret;
  4256. *var = new_val;
  4257. return 0;
  4258. }
  4259. #define SHOW_FUNCTION(__FUNC, __VAR, __CONV) \
  4260. static ssize_t __FUNC(struct elevator_queue *e, char *page) \
  4261. { \
  4262. struct bfq_data *bfqd = e->elevator_data; \
  4263. u64 __data = __VAR; \
  4264. if (__CONV == 1) \
  4265. __data = jiffies_to_msecs(__data); \
  4266. else if (__CONV == 2) \
  4267. __data = div_u64(__data, NSEC_PER_MSEC); \
  4268. return bfq_var_show(__data, (page)); \
  4269. }
  4270. SHOW_FUNCTION(bfq_fifo_expire_sync_show, bfqd->bfq_fifo_expire[1], 2);
  4271. SHOW_FUNCTION(bfq_fifo_expire_async_show, bfqd->bfq_fifo_expire[0], 2);
  4272. SHOW_FUNCTION(bfq_back_seek_max_show, bfqd->bfq_back_max, 0);
  4273. SHOW_FUNCTION(bfq_back_seek_penalty_show, bfqd->bfq_back_penalty, 0);
  4274. SHOW_FUNCTION(bfq_slice_idle_show, bfqd->bfq_slice_idle, 2);
  4275. SHOW_FUNCTION(bfq_max_budget_show, bfqd->bfq_user_max_budget, 0);
  4276. SHOW_FUNCTION(bfq_timeout_sync_show, bfqd->bfq_timeout, 1);
  4277. SHOW_FUNCTION(bfq_strict_guarantees_show, bfqd->strict_guarantees, 0);
  4278. SHOW_FUNCTION(bfq_low_latency_show, bfqd->low_latency, 0);
  4279. #undef SHOW_FUNCTION
  4280. #define USEC_SHOW_FUNCTION(__FUNC, __VAR) \
  4281. static ssize_t __FUNC(struct elevator_queue *e, char *page) \
  4282. { \
  4283. struct bfq_data *bfqd = e->elevator_data; \
  4284. u64 __data = __VAR; \
  4285. __data = div_u64(__data, NSEC_PER_USEC); \
  4286. return bfq_var_show(__data, (page)); \
  4287. }
  4288. USEC_SHOW_FUNCTION(bfq_slice_idle_us_show, bfqd->bfq_slice_idle);
  4289. #undef USEC_SHOW_FUNCTION
  4290. #define STORE_FUNCTION(__FUNC, __PTR, MIN, MAX, __CONV) \
  4291. static ssize_t \
  4292. __FUNC(struct elevator_queue *e, const char *page, size_t count) \
  4293. { \
  4294. struct bfq_data *bfqd = e->elevator_data; \
  4295. unsigned long __data, __min = (MIN), __max = (MAX); \
  4296. int ret; \
  4297. \
  4298. ret = bfq_var_store(&__data, (page)); \
  4299. if (ret) \
  4300. return ret; \
  4301. if (__data < __min) \
  4302. __data = __min; \
  4303. else if (__data > __max) \
  4304. __data = __max; \
  4305. if (__CONV == 1) \
  4306. *(__PTR) = msecs_to_jiffies(__data); \
  4307. else if (__CONV == 2) \
  4308. *(__PTR) = (u64)__data * NSEC_PER_MSEC; \
  4309. else \
  4310. *(__PTR) = __data; \
  4311. return count; \
  4312. }
  4313. STORE_FUNCTION(bfq_fifo_expire_sync_store, &bfqd->bfq_fifo_expire[1], 1,
  4314. INT_MAX, 2);
  4315. STORE_FUNCTION(bfq_fifo_expire_async_store, &bfqd->bfq_fifo_expire[0], 1,
  4316. INT_MAX, 2);
  4317. STORE_FUNCTION(bfq_back_seek_max_store, &bfqd->bfq_back_max, 0, INT_MAX, 0);
  4318. STORE_FUNCTION(bfq_back_seek_penalty_store, &bfqd->bfq_back_penalty, 1,
  4319. INT_MAX, 0);
  4320. STORE_FUNCTION(bfq_slice_idle_store, &bfqd->bfq_slice_idle, 0, INT_MAX, 2);
  4321. #undef STORE_FUNCTION
  4322. #define USEC_STORE_FUNCTION(__FUNC, __PTR, MIN, MAX) \
  4323. static ssize_t __FUNC(struct elevator_queue *e, const char *page, size_t count)\
  4324. { \
  4325. struct bfq_data *bfqd = e->elevator_data; \
  4326. unsigned long __data, __min = (MIN), __max = (MAX); \
  4327. int ret; \
  4328. \
  4329. ret = bfq_var_store(&__data, (page)); \
  4330. if (ret) \
  4331. return ret; \
  4332. if (__data < __min) \
  4333. __data = __min; \
  4334. else if (__data > __max) \
  4335. __data = __max; \
  4336. *(__PTR) = (u64)__data * NSEC_PER_USEC; \
  4337. return count; \
  4338. }
  4339. USEC_STORE_FUNCTION(bfq_slice_idle_us_store, &bfqd->bfq_slice_idle, 0,
  4340. UINT_MAX);
  4341. #undef USEC_STORE_FUNCTION
  4342. static ssize_t bfq_max_budget_store(struct elevator_queue *e,
  4343. const char *page, size_t count)
  4344. {
  4345. struct bfq_data *bfqd = e->elevator_data;
  4346. unsigned long __data;
  4347. int ret;
  4348. ret = bfq_var_store(&__data, (page));
  4349. if (ret)
  4350. return ret;
  4351. if (__data == 0)
  4352. bfqd->bfq_max_budget = bfq_calc_max_budget(bfqd);
  4353. else {
  4354. if (__data > INT_MAX)
  4355. __data = INT_MAX;
  4356. bfqd->bfq_max_budget = __data;
  4357. }
  4358. bfqd->bfq_user_max_budget = __data;
  4359. return count;
  4360. }
  4361. /*
  4362. * Leaving this name to preserve name compatibility with cfq
  4363. * parameters, but this timeout is used for both sync and async.
  4364. */
  4365. static ssize_t bfq_timeout_sync_store(struct elevator_queue *e,
  4366. const char *page, size_t count)
  4367. {
  4368. struct bfq_data *bfqd = e->elevator_data;
  4369. unsigned long __data;
  4370. int ret;
  4371. ret = bfq_var_store(&__data, (page));
  4372. if (ret)
  4373. return ret;
  4374. if (__data < 1)
  4375. __data = 1;
  4376. else if (__data > INT_MAX)
  4377. __data = INT_MAX;
  4378. bfqd->bfq_timeout = msecs_to_jiffies(__data);
  4379. if (bfqd->bfq_user_max_budget == 0)
  4380. bfqd->bfq_max_budget = bfq_calc_max_budget(bfqd);
  4381. return count;
  4382. }
  4383. static ssize_t bfq_strict_guarantees_store(struct elevator_queue *e,
  4384. const char *page, size_t count)
  4385. {
  4386. struct bfq_data *bfqd = e->elevator_data;
  4387. unsigned long __data;
  4388. int ret;
  4389. ret = bfq_var_store(&__data, (page));
  4390. if (ret)
  4391. return ret;
  4392. if (__data > 1)
  4393. __data = 1;
  4394. if (!bfqd->strict_guarantees && __data == 1
  4395. && bfqd->bfq_slice_idle < 8 * NSEC_PER_MSEC)
  4396. bfqd->bfq_slice_idle = 8 * NSEC_PER_MSEC;
  4397. bfqd->strict_guarantees = __data;
  4398. return count;
  4399. }
  4400. static ssize_t bfq_low_latency_store(struct elevator_queue *e,
  4401. const char *page, size_t count)
  4402. {
  4403. struct bfq_data *bfqd = e->elevator_data;
  4404. unsigned long __data;
  4405. int ret;
  4406. ret = bfq_var_store(&__data, (page));
  4407. if (ret)
  4408. return ret;
  4409. if (__data > 1)
  4410. __data = 1;
  4411. if (__data == 0 && bfqd->low_latency != 0)
  4412. bfq_end_wr(bfqd);
  4413. bfqd->low_latency = __data;
  4414. return count;
  4415. }
  4416. #define BFQ_ATTR(name) \
  4417. __ATTR(name, 0644, bfq_##name##_show, bfq_##name##_store)
  4418. static struct elv_fs_entry bfq_attrs[] = {
  4419. BFQ_ATTR(fifo_expire_sync),
  4420. BFQ_ATTR(fifo_expire_async),
  4421. BFQ_ATTR(back_seek_max),
  4422. BFQ_ATTR(back_seek_penalty),
  4423. BFQ_ATTR(slice_idle),
  4424. BFQ_ATTR(slice_idle_us),
  4425. BFQ_ATTR(max_budget),
  4426. BFQ_ATTR(timeout_sync),
  4427. BFQ_ATTR(strict_guarantees),
  4428. BFQ_ATTR(low_latency),
  4429. __ATTR_NULL
  4430. };
  4431. static struct elevator_type iosched_bfq_mq = {
  4432. .ops.mq = {
  4433. .prepare_request = bfq_prepare_request,
  4434. .finish_request = bfq_finish_request,
  4435. .exit_icq = bfq_exit_icq,
  4436. .insert_requests = bfq_insert_requests,
  4437. .dispatch_request = bfq_dispatch_request,
  4438. .next_request = elv_rb_latter_request,
  4439. .former_request = elv_rb_former_request,
  4440. .allow_merge = bfq_allow_bio_merge,
  4441. .bio_merge = bfq_bio_merge,
  4442. .request_merge = bfq_request_merge,
  4443. .requests_merged = bfq_requests_merged,
  4444. .request_merged = bfq_request_merged,
  4445. .has_work = bfq_has_work,
  4446. .init_sched = bfq_init_queue,
  4447. .exit_sched = bfq_exit_queue,
  4448. },
  4449. .uses_mq = true,
  4450. .icq_size = sizeof(struct bfq_io_cq),
  4451. .icq_align = __alignof__(struct bfq_io_cq),
  4452. .elevator_attrs = bfq_attrs,
  4453. .elevator_name = "bfq",
  4454. .elevator_owner = THIS_MODULE,
  4455. };
  4456. MODULE_ALIAS("bfq-iosched");
  4457. static int __init bfq_init(void)
  4458. {
  4459. int ret;
  4460. #ifdef CONFIG_BFQ_GROUP_IOSCHED
  4461. ret = blkcg_policy_register(&blkcg_policy_bfq);
  4462. if (ret)
  4463. return ret;
  4464. #endif
  4465. ret = -ENOMEM;
  4466. if (bfq_slab_setup())
  4467. goto err_pol_unreg;
  4468. /*
  4469. * Times to load large popular applications for the typical
  4470. * systems installed on the reference devices (see the
  4471. * comments before the definitions of the next two
  4472. * arrays). Actually, we use slightly slower values, as the
  4473. * estimated peak rate tends to be smaller than the actual
  4474. * peak rate. The reason for this last fact is that estimates
  4475. * are computed over much shorter time intervals than the long
  4476. * intervals typically used for benchmarking. Why? First, to
  4477. * adapt more quickly to variations. Second, because an I/O
  4478. * scheduler cannot rely on a peak-rate-evaluation workload to
  4479. * be run for a long time.
  4480. */
  4481. T_slow[0] = msecs_to_jiffies(3500); /* actually 4 sec */
  4482. T_slow[1] = msecs_to_jiffies(6000); /* actually 6.5 sec */
  4483. T_fast[0] = msecs_to_jiffies(7000); /* actually 8 sec */
  4484. T_fast[1] = msecs_to_jiffies(2500); /* actually 3 sec */
  4485. /*
  4486. * Thresholds that determine the switch between speed classes
  4487. * (see the comments before the definition of the array
  4488. * device_speed_thresh). These thresholds are biased towards
  4489. * transitions to the fast class. This is safer than the
  4490. * opposite bias. In fact, a wrong transition to the slow
  4491. * class results in short weight-raising periods, because the
  4492. * speed of the device then tends to be higher that the
  4493. * reference peak rate. On the opposite end, a wrong
  4494. * transition to the fast class tends to increase
  4495. * weight-raising periods, because of the opposite reason.
  4496. */
  4497. device_speed_thresh[0] = (4 * R_slow[0]) / 3;
  4498. device_speed_thresh[1] = (4 * R_slow[1]) / 3;
  4499. ret = elv_register(&iosched_bfq_mq);
  4500. if (ret)
  4501. goto slab_kill;
  4502. return 0;
  4503. slab_kill:
  4504. bfq_slab_kill();
  4505. err_pol_unreg:
  4506. #ifdef CONFIG_BFQ_GROUP_IOSCHED
  4507. blkcg_policy_unregister(&blkcg_policy_bfq);
  4508. #endif
  4509. return ret;
  4510. }
  4511. static void __exit bfq_exit(void)
  4512. {
  4513. elv_unregister(&iosched_bfq_mq);
  4514. #ifdef CONFIG_BFQ_GROUP_IOSCHED
  4515. blkcg_policy_unregister(&blkcg_policy_bfq);
  4516. #endif
  4517. bfq_slab_kill();
  4518. }
  4519. module_init(bfq_init);
  4520. module_exit(bfq_exit);
  4521. MODULE_AUTHOR("Paolo Valente");
  4522. MODULE_LICENSE("GPL");
  4523. MODULE_DESCRIPTION("MQ Budget Fair Queueing I/O Scheduler");