block.c 218 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226
  1. /*
  2. * QEMU System Emulator block driver
  3. *
  4. * Copyright (c) 2003 Fabrice Bellard
  5. *
  6. * Permission is hereby granted, free of charge, to any person obtaining a copy
  7. * of this software and associated documentation files (the "Software"), to deal
  8. * in the Software without restriction, including without limitation the rights
  9. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. * copies of the Software, and to permit persons to whom the Software is
  11. * furnished to do so, subject to the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be included in
  14. * all copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  19. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. * THE SOFTWARE.
  23. */
  24. #include "qemu/osdep.h"
  25. #include "block/trace.h"
  26. #include "block/block_int.h"
  27. #include "block/blockjob.h"
  28. #include "block/nbd.h"
  29. #include "block/qdict.h"
  30. #include "qemu/error-report.h"
  31. #include "block/module_block.h"
  32. #include "qemu/main-loop.h"
  33. #include "qemu/module.h"
  34. #include "qapi/error.h"
  35. #include "qapi/qmp/qdict.h"
  36. #include "qapi/qmp/qjson.h"
  37. #include "qapi/qmp/qnull.h"
  38. #include "qapi/qmp/qstring.h"
  39. #include "qapi/qobject-output-visitor.h"
  40. #include "qapi/qapi-visit-block-core.h"
  41. #include "sysemu/block-backend.h"
  42. #include "sysemu/sysemu.h"
  43. #include "qemu/notify.h"
  44. #include "qemu/option.h"
  45. #include "qemu/coroutine.h"
  46. #include "block/qapi.h"
  47. #include "qemu/timer.h"
  48. #include "qemu/cutils.h"
  49. #include "qemu/id.h"
  50. #include "block/coroutines.h"
  51. #ifdef CONFIG_BSD
  52. #include <sys/ioctl.h>
  53. #include <sys/queue.h>
  54. #if !defined(__DragonFly__) && !defined(CONFIG_IOS)
  55. #include <sys/disk.h>
  56. #endif
  57. #endif
  58. #ifdef _WIN32
  59. #include <windows.h>
  60. #endif
  61. #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
  62. static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
  63. QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
  64. static QTAILQ_HEAD(, BlockDriverState) all_bdrv_states =
  65. QTAILQ_HEAD_INITIALIZER(all_bdrv_states);
  66. static QLIST_HEAD(, BlockDriver) bdrv_drivers =
  67. QLIST_HEAD_INITIALIZER(bdrv_drivers);
  68. static BlockDriverState *bdrv_open_inherit(const char *filename,
  69. const char *reference,
  70. QDict *options, int flags,
  71. BlockDriverState *parent,
  72. const BdrvChildClass *child_class,
  73. BdrvChildRole child_role,
  74. Error **errp);
  75. /* If non-zero, use only whitelisted block drivers */
  76. static int use_bdrv_whitelist;
  77. #ifdef _WIN32
  78. static int is_windows_drive_prefix(const char *filename)
  79. {
  80. return (((filename[0] >= 'a' && filename[0] <= 'z') ||
  81. (filename[0] >= 'A' && filename[0] <= 'Z')) &&
  82. filename[1] == ':');
  83. }
  84. int is_windows_drive(const char *filename)
  85. {
  86. if (is_windows_drive_prefix(filename) &&
  87. filename[2] == '\0')
  88. return 1;
  89. if (strstart(filename, "\\\\.\\", NULL) ||
  90. strstart(filename, "//./", NULL))
  91. return 1;
  92. return 0;
  93. }
  94. #endif
  95. size_t bdrv_opt_mem_align(BlockDriverState *bs)
  96. {
  97. if (!bs || !bs->drv) {
  98. /* page size or 4k (hdd sector size) should be on the safe side */
  99. return MAX(4096, qemu_real_host_page_size);
  100. }
  101. return bs->bl.opt_mem_alignment;
  102. }
  103. size_t bdrv_min_mem_align(BlockDriverState *bs)
  104. {
  105. if (!bs || !bs->drv) {
  106. /* page size or 4k (hdd sector size) should be on the safe side */
  107. return MAX(4096, qemu_real_host_page_size);
  108. }
  109. return bs->bl.min_mem_alignment;
  110. }
  111. /* check if the path starts with "<protocol>:" */
  112. int path_has_protocol(const char *path)
  113. {
  114. const char *p;
  115. #ifdef _WIN32
  116. if (is_windows_drive(path) ||
  117. is_windows_drive_prefix(path)) {
  118. return 0;
  119. }
  120. p = path + strcspn(path, ":/\\");
  121. #else
  122. p = path + strcspn(path, ":/");
  123. #endif
  124. return *p == ':';
  125. }
  126. int path_is_absolute(const char *path)
  127. {
  128. #ifdef _WIN32
  129. /* specific case for names like: "\\.\d:" */
  130. if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
  131. return 1;
  132. }
  133. return (*path == '/' || *path == '\\');
  134. #else
  135. return (*path == '/');
  136. #endif
  137. }
  138. /* if filename is absolute, just return its duplicate. Otherwise, build a
  139. path to it by considering it is relative to base_path. URL are
  140. supported. */
  141. char *path_combine(const char *base_path, const char *filename)
  142. {
  143. const char *protocol_stripped = NULL;
  144. const char *p, *p1;
  145. char *result;
  146. int len;
  147. if (path_is_absolute(filename)) {
  148. return g_strdup(filename);
  149. }
  150. if (path_has_protocol(base_path)) {
  151. protocol_stripped = strchr(base_path, ':');
  152. if (protocol_stripped) {
  153. protocol_stripped++;
  154. }
  155. }
  156. p = protocol_stripped ?: base_path;
  157. p1 = strrchr(base_path, '/');
  158. #ifdef _WIN32
  159. {
  160. const char *p2;
  161. p2 = strrchr(base_path, '\\');
  162. if (!p1 || p2 > p1) {
  163. p1 = p2;
  164. }
  165. }
  166. #endif
  167. if (p1) {
  168. p1++;
  169. } else {
  170. p1 = base_path;
  171. }
  172. if (p1 > p) {
  173. p = p1;
  174. }
  175. len = p - base_path;
  176. result = g_malloc(len + strlen(filename) + 1);
  177. memcpy(result, base_path, len);
  178. strcpy(result + len, filename);
  179. return result;
  180. }
  181. /*
  182. * Helper function for bdrv_parse_filename() implementations to remove optional
  183. * protocol prefixes (especially "file:") from a filename and for putting the
  184. * stripped filename into the options QDict if there is such a prefix.
  185. */
  186. void bdrv_parse_filename_strip_prefix(const char *filename, const char *prefix,
  187. QDict *options)
  188. {
  189. if (strstart(filename, prefix, &filename)) {
  190. /* Stripping the explicit protocol prefix may result in a protocol
  191. * prefix being (wrongly) detected (if the filename contains a colon) */
  192. if (path_has_protocol(filename)) {
  193. QString *fat_filename;
  194. /* This means there is some colon before the first slash; therefore,
  195. * this cannot be an absolute path */
  196. assert(!path_is_absolute(filename));
  197. /* And we can thus fix the protocol detection issue by prefixing it
  198. * by "./" */
  199. fat_filename = qstring_from_str("./");
  200. qstring_append(fat_filename, filename);
  201. assert(!path_has_protocol(qstring_get_str(fat_filename)));
  202. qdict_put(options, "filename", fat_filename);
  203. } else {
  204. /* If no protocol prefix was detected, we can use the shortened
  205. * filename as-is */
  206. qdict_put_str(options, "filename", filename);
  207. }
  208. }
  209. }
  210. /* Returns whether the image file is opened as read-only. Note that this can
  211. * return false and writing to the image file is still not possible because the
  212. * image is inactivated. */
  213. bool bdrv_is_read_only(BlockDriverState *bs)
  214. {
  215. return bs->read_only;
  216. }
  217. int bdrv_can_set_read_only(BlockDriverState *bs, bool read_only,
  218. bool ignore_allow_rdw, Error **errp)
  219. {
  220. /* Do not set read_only if copy_on_read is enabled */
  221. if (bs->copy_on_read && read_only) {
  222. error_setg(errp, "Can't set node '%s' to r/o with copy-on-read enabled",
  223. bdrv_get_device_or_node_name(bs));
  224. return -EINVAL;
  225. }
  226. /* Do not clear read_only if it is prohibited */
  227. if (!read_only && !(bs->open_flags & BDRV_O_ALLOW_RDWR) &&
  228. !ignore_allow_rdw)
  229. {
  230. error_setg(errp, "Node '%s' is read only",
  231. bdrv_get_device_or_node_name(bs));
  232. return -EPERM;
  233. }
  234. return 0;
  235. }
  236. /*
  237. * Called by a driver that can only provide a read-only image.
  238. *
  239. * Returns 0 if the node is already read-only or it could switch the node to
  240. * read-only because BDRV_O_AUTO_RDONLY is set.
  241. *
  242. * Returns -EACCES if the node is read-write and BDRV_O_AUTO_RDONLY is not set
  243. * or bdrv_can_set_read_only() forbids making the node read-only. If @errmsg
  244. * is not NULL, it is used as the error message for the Error object.
  245. */
  246. int bdrv_apply_auto_read_only(BlockDriverState *bs, const char *errmsg,
  247. Error **errp)
  248. {
  249. int ret = 0;
  250. if (!(bs->open_flags & BDRV_O_RDWR)) {
  251. return 0;
  252. }
  253. if (!(bs->open_flags & BDRV_O_AUTO_RDONLY)) {
  254. goto fail;
  255. }
  256. ret = bdrv_can_set_read_only(bs, true, false, NULL);
  257. if (ret < 0) {
  258. goto fail;
  259. }
  260. bs->read_only = true;
  261. bs->open_flags &= ~BDRV_O_RDWR;
  262. return 0;
  263. fail:
  264. error_setg(errp, "%s", errmsg ?: "Image is read-only");
  265. return -EACCES;
  266. }
  267. /*
  268. * If @backing is empty, this function returns NULL without setting
  269. * @errp. In all other cases, NULL will only be returned with @errp
  270. * set.
  271. *
  272. * Therefore, a return value of NULL without @errp set means that
  273. * there is no backing file; if @errp is set, there is one but its
  274. * absolute filename cannot be generated.
  275. */
  276. char *bdrv_get_full_backing_filename_from_filename(const char *backed,
  277. const char *backing,
  278. Error **errp)
  279. {
  280. if (backing[0] == '\0') {
  281. return NULL;
  282. } else if (path_has_protocol(backing) || path_is_absolute(backing)) {
  283. return g_strdup(backing);
  284. } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
  285. error_setg(errp, "Cannot use relative backing file names for '%s'",
  286. backed);
  287. return NULL;
  288. } else {
  289. return path_combine(backed, backing);
  290. }
  291. }
  292. /*
  293. * If @filename is empty or NULL, this function returns NULL without
  294. * setting @errp. In all other cases, NULL will only be returned with
  295. * @errp set.
  296. */
  297. static char *bdrv_make_absolute_filename(BlockDriverState *relative_to,
  298. const char *filename, Error **errp)
  299. {
  300. char *dir, *full_name;
  301. if (!filename || filename[0] == '\0') {
  302. return NULL;
  303. } else if (path_has_protocol(filename) || path_is_absolute(filename)) {
  304. return g_strdup(filename);
  305. }
  306. dir = bdrv_dirname(relative_to, errp);
  307. if (!dir) {
  308. return NULL;
  309. }
  310. full_name = g_strconcat(dir, filename, NULL);
  311. g_free(dir);
  312. return full_name;
  313. }
  314. char *bdrv_get_full_backing_filename(BlockDriverState *bs, Error **errp)
  315. {
  316. return bdrv_make_absolute_filename(bs, bs->backing_file, errp);
  317. }
  318. void bdrv_register(BlockDriver *bdrv)
  319. {
  320. assert(bdrv->format_name);
  321. QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
  322. }
  323. BlockDriverState *bdrv_new(void)
  324. {
  325. BlockDriverState *bs;
  326. int i;
  327. bs = g_new0(BlockDriverState, 1);
  328. QLIST_INIT(&bs->dirty_bitmaps);
  329. for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
  330. QLIST_INIT(&bs->op_blockers[i]);
  331. }
  332. notifier_with_return_list_init(&bs->before_write_notifiers);
  333. qemu_co_mutex_init(&bs->reqs_lock);
  334. qemu_mutex_init(&bs->dirty_bitmap_mutex);
  335. bs->refcnt = 1;
  336. bs->aio_context = qemu_get_aio_context();
  337. qemu_co_queue_init(&bs->flush_queue);
  338. for (i = 0; i < bdrv_drain_all_count; i++) {
  339. bdrv_drained_begin(bs);
  340. }
  341. QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list);
  342. return bs;
  343. }
  344. static BlockDriver *bdrv_do_find_format(const char *format_name)
  345. {
  346. BlockDriver *drv1;
  347. QLIST_FOREACH(drv1, &bdrv_drivers, list) {
  348. if (!strcmp(drv1->format_name, format_name)) {
  349. return drv1;
  350. }
  351. }
  352. return NULL;
  353. }
  354. BlockDriver *bdrv_find_format(const char *format_name)
  355. {
  356. BlockDriver *drv1;
  357. int i;
  358. drv1 = bdrv_do_find_format(format_name);
  359. if (drv1) {
  360. return drv1;
  361. }
  362. /* The driver isn't registered, maybe we need to load a module */
  363. for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
  364. if (!strcmp(block_driver_modules[i].format_name, format_name)) {
  365. block_module_load_one(block_driver_modules[i].library_name);
  366. break;
  367. }
  368. }
  369. return bdrv_do_find_format(format_name);
  370. }
  371. static int bdrv_format_is_whitelisted(const char *format_name, bool read_only)
  372. {
  373. static const char *whitelist_rw[] = {
  374. CONFIG_BDRV_RW_WHITELIST
  375. NULL
  376. };
  377. static const char *whitelist_ro[] = {
  378. CONFIG_BDRV_RO_WHITELIST
  379. NULL
  380. };
  381. const char **p;
  382. if (!whitelist_rw[0] && !whitelist_ro[0]) {
  383. return 1; /* no whitelist, anything goes */
  384. }
  385. for (p = whitelist_rw; *p; p++) {
  386. if (!strcmp(format_name, *p)) {
  387. return 1;
  388. }
  389. }
  390. if (read_only) {
  391. for (p = whitelist_ro; *p; p++) {
  392. if (!strcmp(format_name, *p)) {
  393. return 1;
  394. }
  395. }
  396. }
  397. return 0;
  398. }
  399. int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
  400. {
  401. return bdrv_format_is_whitelisted(drv->format_name, read_only);
  402. }
  403. bool bdrv_uses_whitelist(void)
  404. {
  405. return use_bdrv_whitelist;
  406. }
  407. typedef struct CreateCo {
  408. BlockDriver *drv;
  409. char *filename;
  410. QemuOpts *opts;
  411. int ret;
  412. Error *err;
  413. } CreateCo;
  414. static void coroutine_fn bdrv_create_co_entry(void *opaque)
  415. {
  416. Error *local_err = NULL;
  417. int ret;
  418. CreateCo *cco = opaque;
  419. assert(cco->drv);
  420. ret = cco->drv->bdrv_co_create_opts(cco->drv,
  421. cco->filename, cco->opts, &local_err);
  422. error_propagate(&cco->err, local_err);
  423. cco->ret = ret;
  424. }
  425. int bdrv_create(BlockDriver *drv, const char* filename,
  426. QemuOpts *opts, Error **errp)
  427. {
  428. int ret;
  429. Coroutine *co;
  430. CreateCo cco = {
  431. .drv = drv,
  432. .filename = g_strdup(filename),
  433. .opts = opts,
  434. .ret = NOT_DONE,
  435. .err = NULL,
  436. };
  437. if (!drv->bdrv_co_create_opts) {
  438. error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
  439. ret = -ENOTSUP;
  440. goto out;
  441. }
  442. if (qemu_in_coroutine()) {
  443. /* Fast-path if already in coroutine context */
  444. bdrv_create_co_entry(&cco);
  445. } else {
  446. co = qemu_coroutine_create(bdrv_create_co_entry, &cco);
  447. qemu_coroutine_enter(co);
  448. while (cco.ret == NOT_DONE) {
  449. aio_poll(qemu_get_aio_context(), true);
  450. }
  451. }
  452. ret = cco.ret;
  453. if (ret < 0) {
  454. if (cco.err) {
  455. error_propagate(errp, cco.err);
  456. } else {
  457. error_setg_errno(errp, -ret, "Could not create image");
  458. }
  459. }
  460. out:
  461. g_free(cco.filename);
  462. return ret;
  463. }
  464. /**
  465. * Helper function for bdrv_create_file_fallback(): Resize @blk to at
  466. * least the given @minimum_size.
  467. *
  468. * On success, return @blk's actual length.
  469. * Otherwise, return -errno.
  470. */
  471. static int64_t create_file_fallback_truncate(BlockBackend *blk,
  472. int64_t minimum_size, Error **errp)
  473. {
  474. Error *local_err = NULL;
  475. int64_t size;
  476. int ret;
  477. ret = blk_truncate(blk, minimum_size, false, PREALLOC_MODE_OFF, 0,
  478. &local_err);
  479. if (ret < 0 && ret != -ENOTSUP) {
  480. error_propagate(errp, local_err);
  481. return ret;
  482. }
  483. size = blk_getlength(blk);
  484. if (size < 0) {
  485. error_free(local_err);
  486. error_setg_errno(errp, -size,
  487. "Failed to inquire the new image file's length");
  488. return size;
  489. }
  490. if (size < minimum_size) {
  491. /* Need to grow the image, but we failed to do that */
  492. error_propagate(errp, local_err);
  493. return -ENOTSUP;
  494. }
  495. error_free(local_err);
  496. local_err = NULL;
  497. return size;
  498. }
  499. /**
  500. * Helper function for bdrv_create_file_fallback(): Zero the first
  501. * sector to remove any potentially pre-existing image header.
  502. */
  503. static int create_file_fallback_zero_first_sector(BlockBackend *blk,
  504. int64_t current_size,
  505. Error **errp)
  506. {
  507. int64_t bytes_to_clear;
  508. int ret;
  509. bytes_to_clear = MIN(current_size, BDRV_SECTOR_SIZE);
  510. if (bytes_to_clear) {
  511. ret = blk_pwrite_zeroes(blk, 0, bytes_to_clear, BDRV_REQ_MAY_UNMAP);
  512. if (ret < 0) {
  513. error_setg_errno(errp, -ret,
  514. "Failed to clear the new image's first sector");
  515. return ret;
  516. }
  517. }
  518. return 0;
  519. }
  520. /**
  521. * Simple implementation of bdrv_co_create_opts for protocol drivers
  522. * which only support creation via opening a file
  523. * (usually existing raw storage device)
  524. */
  525. int coroutine_fn bdrv_co_create_opts_simple(BlockDriver *drv,
  526. const char *filename,
  527. QemuOpts *opts,
  528. Error **errp)
  529. {
  530. BlockBackend *blk;
  531. QDict *options;
  532. int64_t size = 0;
  533. char *buf = NULL;
  534. PreallocMode prealloc;
  535. Error *local_err = NULL;
  536. int ret;
  537. size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
  538. buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
  539. prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
  540. PREALLOC_MODE_OFF, &local_err);
  541. g_free(buf);
  542. if (local_err) {
  543. error_propagate(errp, local_err);
  544. return -EINVAL;
  545. }
  546. if (prealloc != PREALLOC_MODE_OFF) {
  547. error_setg(errp, "Unsupported preallocation mode '%s'",
  548. PreallocMode_str(prealloc));
  549. return -ENOTSUP;
  550. }
  551. options = qdict_new();
  552. qdict_put_str(options, "driver", drv->format_name);
  553. blk = blk_new_open(filename, NULL, options,
  554. BDRV_O_RDWR | BDRV_O_RESIZE, errp);
  555. if (!blk) {
  556. error_prepend(errp, "Protocol driver '%s' does not support image "
  557. "creation, and opening the image failed: ",
  558. drv->format_name);
  559. return -EINVAL;
  560. }
  561. size = create_file_fallback_truncate(blk, size, errp);
  562. if (size < 0) {
  563. ret = size;
  564. goto out;
  565. }
  566. ret = create_file_fallback_zero_first_sector(blk, size, errp);
  567. if (ret < 0) {
  568. goto out;
  569. }
  570. ret = 0;
  571. out:
  572. blk_unref(blk);
  573. return ret;
  574. }
  575. int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
  576. {
  577. BlockDriver *drv;
  578. drv = bdrv_find_protocol(filename, true, errp);
  579. if (drv == NULL) {
  580. return -ENOENT;
  581. }
  582. return bdrv_create(drv, filename, opts, errp);
  583. }
  584. int coroutine_fn bdrv_co_delete_file(BlockDriverState *bs, Error **errp)
  585. {
  586. Error *local_err = NULL;
  587. int ret;
  588. assert(bs != NULL);
  589. if (!bs->drv) {
  590. error_setg(errp, "Block node '%s' is not opened", bs->filename);
  591. return -ENOMEDIUM;
  592. }
  593. if (!bs->drv->bdrv_co_delete_file) {
  594. error_setg(errp, "Driver '%s' does not support image deletion",
  595. bs->drv->format_name);
  596. return -ENOTSUP;
  597. }
  598. ret = bs->drv->bdrv_co_delete_file(bs, &local_err);
  599. if (ret < 0) {
  600. error_propagate(errp, local_err);
  601. }
  602. return ret;
  603. }
  604. /**
  605. * Try to get @bs's logical and physical block size.
  606. * On success, store them in @bsz struct and return 0.
  607. * On failure return -errno.
  608. * @bs must not be empty.
  609. */
  610. int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
  611. {
  612. BlockDriver *drv = bs->drv;
  613. BlockDriverState *filtered = bdrv_filter_bs(bs);
  614. if (drv && drv->bdrv_probe_blocksizes) {
  615. return drv->bdrv_probe_blocksizes(bs, bsz);
  616. } else if (filtered) {
  617. return bdrv_probe_blocksizes(filtered, bsz);
  618. }
  619. return -ENOTSUP;
  620. }
  621. /**
  622. * Try to get @bs's geometry (cyls, heads, sectors).
  623. * On success, store them in @geo struct and return 0.
  624. * On failure return -errno.
  625. * @bs must not be empty.
  626. */
  627. int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
  628. {
  629. BlockDriver *drv = bs->drv;
  630. BlockDriverState *filtered = bdrv_filter_bs(bs);
  631. if (drv && drv->bdrv_probe_geometry) {
  632. return drv->bdrv_probe_geometry(bs, geo);
  633. } else if (filtered) {
  634. return bdrv_probe_geometry(filtered, geo);
  635. }
  636. return -ENOTSUP;
  637. }
  638. /*
  639. * Create a uniquely-named empty temporary file.
  640. * Return 0 upon success, otherwise a negative errno value.
  641. */
  642. int get_tmp_filename(char *filename, int size)
  643. {
  644. #ifdef _WIN32
  645. char temp_dir[MAX_PATH];
  646. /* GetTempFileName requires that its output buffer (4th param)
  647. have length MAX_PATH or greater. */
  648. assert(size >= MAX_PATH);
  649. return (GetTempPath(MAX_PATH, temp_dir)
  650. && GetTempFileName(temp_dir, "qem", 0, filename)
  651. ? 0 : -GetLastError());
  652. #else
  653. int fd;
  654. const char *tmpdir;
  655. tmpdir = getenv("TMPDIR");
  656. if (!tmpdir) {
  657. tmpdir = "/var/tmp";
  658. }
  659. if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
  660. return -EOVERFLOW;
  661. }
  662. fd = mkstemp(filename);
  663. if (fd < 0) {
  664. return -errno;
  665. }
  666. if (close(fd) != 0) {
  667. unlink(filename);
  668. return -errno;
  669. }
  670. return 0;
  671. #endif
  672. }
  673. /*
  674. * Detect host devices. By convention, /dev/cdrom[N] is always
  675. * recognized as a host CDROM.
  676. */
  677. static BlockDriver *find_hdev_driver(const char *filename)
  678. {
  679. int score_max = 0, score;
  680. BlockDriver *drv = NULL, *d;
  681. QLIST_FOREACH(d, &bdrv_drivers, list) {
  682. if (d->bdrv_probe_device) {
  683. score = d->bdrv_probe_device(filename);
  684. if (score > score_max) {
  685. score_max = score;
  686. drv = d;
  687. }
  688. }
  689. }
  690. return drv;
  691. }
  692. static BlockDriver *bdrv_do_find_protocol(const char *protocol)
  693. {
  694. BlockDriver *drv1;
  695. QLIST_FOREACH(drv1, &bdrv_drivers, list) {
  696. if (drv1->protocol_name && !strcmp(drv1->protocol_name, protocol)) {
  697. return drv1;
  698. }
  699. }
  700. return NULL;
  701. }
  702. BlockDriver *bdrv_find_protocol(const char *filename,
  703. bool allow_protocol_prefix,
  704. Error **errp)
  705. {
  706. BlockDriver *drv1;
  707. char protocol[128];
  708. int len;
  709. const char *p;
  710. int i;
  711. /* TODO Drivers without bdrv_file_open must be specified explicitly */
  712. /*
  713. * XXX(hch): we really should not let host device detection
  714. * override an explicit protocol specification, but moving this
  715. * later breaks access to device names with colons in them.
  716. * Thanks to the brain-dead persistent naming schemes on udev-
  717. * based Linux systems those actually are quite common.
  718. */
  719. drv1 = find_hdev_driver(filename);
  720. if (drv1) {
  721. return drv1;
  722. }
  723. if (!path_has_protocol(filename) || !allow_protocol_prefix) {
  724. return &bdrv_file;
  725. }
  726. p = strchr(filename, ':');
  727. assert(p != NULL);
  728. len = p - filename;
  729. if (len > sizeof(protocol) - 1)
  730. len = sizeof(protocol) - 1;
  731. memcpy(protocol, filename, len);
  732. protocol[len] = '\0';
  733. drv1 = bdrv_do_find_protocol(protocol);
  734. if (drv1) {
  735. return drv1;
  736. }
  737. for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
  738. if (block_driver_modules[i].protocol_name &&
  739. !strcmp(block_driver_modules[i].protocol_name, protocol)) {
  740. block_module_load_one(block_driver_modules[i].library_name);
  741. break;
  742. }
  743. }
  744. drv1 = bdrv_do_find_protocol(protocol);
  745. if (!drv1) {
  746. error_setg(errp, "Unknown protocol '%s'", protocol);
  747. }
  748. return drv1;
  749. }
  750. /*
  751. * Guess image format by probing its contents.
  752. * This is not a good idea when your image is raw (CVE-2008-2004), but
  753. * we do it anyway for backward compatibility.
  754. *
  755. * @buf contains the image's first @buf_size bytes.
  756. * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
  757. * but can be smaller if the image file is smaller)
  758. * @filename is its filename.
  759. *
  760. * For all block drivers, call the bdrv_probe() method to get its
  761. * probing score.
  762. * Return the first block driver with the highest probing score.
  763. */
  764. BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
  765. const char *filename)
  766. {
  767. int score_max = 0, score;
  768. BlockDriver *drv = NULL, *d;
  769. QLIST_FOREACH(d, &bdrv_drivers, list) {
  770. if (d->bdrv_probe) {
  771. score = d->bdrv_probe(buf, buf_size, filename);
  772. if (score > score_max) {
  773. score_max = score;
  774. drv = d;
  775. }
  776. }
  777. }
  778. return drv;
  779. }
  780. static int find_image_format(BlockBackend *file, const char *filename,
  781. BlockDriver **pdrv, Error **errp)
  782. {
  783. BlockDriver *drv;
  784. uint8_t buf[BLOCK_PROBE_BUF_SIZE];
  785. int ret = 0;
  786. /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
  787. if (blk_is_sg(file) || !blk_is_inserted(file) || blk_getlength(file) == 0) {
  788. *pdrv = &bdrv_raw;
  789. return ret;
  790. }
  791. ret = blk_pread(file, 0, buf, sizeof(buf));
  792. if (ret < 0) {
  793. error_setg_errno(errp, -ret, "Could not read image for determining its "
  794. "format");
  795. *pdrv = NULL;
  796. return ret;
  797. }
  798. drv = bdrv_probe_all(buf, ret, filename);
  799. if (!drv) {
  800. error_setg(errp, "Could not determine image format: No compatible "
  801. "driver found");
  802. ret = -ENOENT;
  803. }
  804. *pdrv = drv;
  805. return ret;
  806. }
  807. /**
  808. * Set the current 'total_sectors' value
  809. * Return 0 on success, -errno on error.
  810. */
  811. int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
  812. {
  813. BlockDriver *drv = bs->drv;
  814. if (!drv) {
  815. return -ENOMEDIUM;
  816. }
  817. /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
  818. if (bdrv_is_sg(bs))
  819. return 0;
  820. /* query actual device if possible, otherwise just trust the hint */
  821. if (drv->bdrv_getlength) {
  822. int64_t length = drv->bdrv_getlength(bs);
  823. if (length < 0) {
  824. return length;
  825. }
  826. hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
  827. }
  828. bs->total_sectors = hint;
  829. return 0;
  830. }
  831. /**
  832. * Combines a QDict of new block driver @options with any missing options taken
  833. * from @old_options, so that leaving out an option defaults to its old value.
  834. */
  835. static void bdrv_join_options(BlockDriverState *bs, QDict *options,
  836. QDict *old_options)
  837. {
  838. if (bs->drv && bs->drv->bdrv_join_options) {
  839. bs->drv->bdrv_join_options(options, old_options);
  840. } else {
  841. qdict_join(options, old_options, false);
  842. }
  843. }
  844. static BlockdevDetectZeroesOptions bdrv_parse_detect_zeroes(QemuOpts *opts,
  845. int open_flags,
  846. Error **errp)
  847. {
  848. Error *local_err = NULL;
  849. char *value = qemu_opt_get_del(opts, "detect-zeroes");
  850. BlockdevDetectZeroesOptions detect_zeroes =
  851. qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup, value,
  852. BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF, &local_err);
  853. g_free(value);
  854. if (local_err) {
  855. error_propagate(errp, local_err);
  856. return detect_zeroes;
  857. }
  858. if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
  859. !(open_flags & BDRV_O_UNMAP))
  860. {
  861. error_setg(errp, "setting detect-zeroes to unmap is not allowed "
  862. "without setting discard operation to unmap");
  863. }
  864. return detect_zeroes;
  865. }
  866. /**
  867. * Set open flags for aio engine
  868. *
  869. * Return 0 on success, -1 if the engine specified is invalid
  870. */
  871. int bdrv_parse_aio(const char *mode, int *flags)
  872. {
  873. if (!strcmp(mode, "threads")) {
  874. /* do nothing, default */
  875. } else if (!strcmp(mode, "native")) {
  876. *flags |= BDRV_O_NATIVE_AIO;
  877. #ifdef CONFIG_LINUX_IO_URING
  878. } else if (!strcmp(mode, "io_uring")) {
  879. *flags |= BDRV_O_IO_URING;
  880. #endif
  881. } else {
  882. return -1;
  883. }
  884. return 0;
  885. }
  886. /**
  887. * Set open flags for a given discard mode
  888. *
  889. * Return 0 on success, -1 if the discard mode was invalid.
  890. */
  891. int bdrv_parse_discard_flags(const char *mode, int *flags)
  892. {
  893. *flags &= ~BDRV_O_UNMAP;
  894. if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
  895. /* do nothing */
  896. } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
  897. *flags |= BDRV_O_UNMAP;
  898. } else {
  899. return -1;
  900. }
  901. return 0;
  902. }
  903. /**
  904. * Set open flags for a given cache mode
  905. *
  906. * Return 0 on success, -1 if the cache mode was invalid.
  907. */
  908. int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough)
  909. {
  910. *flags &= ~BDRV_O_CACHE_MASK;
  911. if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
  912. *writethrough = false;
  913. *flags |= BDRV_O_NOCACHE;
  914. } else if (!strcmp(mode, "directsync")) {
  915. *writethrough = true;
  916. *flags |= BDRV_O_NOCACHE;
  917. } else if (!strcmp(mode, "writeback")) {
  918. *writethrough = false;
  919. } else if (!strcmp(mode, "unsafe")) {
  920. *writethrough = false;
  921. *flags |= BDRV_O_NO_FLUSH;
  922. } else if (!strcmp(mode, "writethrough")) {
  923. *writethrough = true;
  924. } else {
  925. return -1;
  926. }
  927. return 0;
  928. }
  929. static char *bdrv_child_get_parent_desc(BdrvChild *c)
  930. {
  931. BlockDriverState *parent = c->opaque;
  932. return g_strdup(bdrv_get_device_or_node_name(parent));
  933. }
  934. static void bdrv_child_cb_drained_begin(BdrvChild *child)
  935. {
  936. BlockDriverState *bs = child->opaque;
  937. bdrv_do_drained_begin_quiesce(bs, NULL, false);
  938. }
  939. static bool bdrv_child_cb_drained_poll(BdrvChild *child)
  940. {
  941. BlockDriverState *bs = child->opaque;
  942. return bdrv_drain_poll(bs, false, NULL, false);
  943. }
  944. static void bdrv_child_cb_drained_end(BdrvChild *child,
  945. int *drained_end_counter)
  946. {
  947. BlockDriverState *bs = child->opaque;
  948. bdrv_drained_end_no_poll(bs, drained_end_counter);
  949. }
  950. static int bdrv_child_cb_inactivate(BdrvChild *child)
  951. {
  952. BlockDriverState *bs = child->opaque;
  953. assert(bs->open_flags & BDRV_O_INACTIVE);
  954. return 0;
  955. }
  956. static bool bdrv_child_cb_can_set_aio_ctx(BdrvChild *child, AioContext *ctx,
  957. GSList **ignore, Error **errp)
  958. {
  959. BlockDriverState *bs = child->opaque;
  960. return bdrv_can_set_aio_context(bs, ctx, ignore, errp);
  961. }
  962. static void bdrv_child_cb_set_aio_ctx(BdrvChild *child, AioContext *ctx,
  963. GSList **ignore)
  964. {
  965. BlockDriverState *bs = child->opaque;
  966. return bdrv_set_aio_context_ignore(bs, ctx, ignore);
  967. }
  968. /*
  969. * Returns the options and flags that a temporary snapshot should get, based on
  970. * the originally requested flags (the originally requested image will have
  971. * flags like a backing file)
  972. */
  973. static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options,
  974. int parent_flags, QDict *parent_options)
  975. {
  976. *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
  977. /* For temporary files, unconditional cache=unsafe is fine */
  978. qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off");
  979. qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
  980. /* Copy the read-only and discard options from the parent */
  981. qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
  982. qdict_copy_default(child_options, parent_options, BDRV_OPT_DISCARD);
  983. /* aio=native doesn't work for cache.direct=off, so disable it for the
  984. * temporary snapshot */
  985. *child_flags &= ~BDRV_O_NATIVE_AIO;
  986. }
  987. static void bdrv_backing_attach(BdrvChild *c)
  988. {
  989. BlockDriverState *parent = c->opaque;
  990. BlockDriverState *backing_hd = c->bs;
  991. assert(!parent->backing_blocker);
  992. error_setg(&parent->backing_blocker,
  993. "node is used as backing hd of '%s'",
  994. bdrv_get_device_or_node_name(parent));
  995. bdrv_refresh_filename(backing_hd);
  996. parent->open_flags &= ~BDRV_O_NO_BACKING;
  997. bdrv_op_block_all(backing_hd, parent->backing_blocker);
  998. /* Otherwise we won't be able to commit or stream */
  999. bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
  1000. parent->backing_blocker);
  1001. bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_STREAM,
  1002. parent->backing_blocker);
  1003. /*
  1004. * We do backup in 3 ways:
  1005. * 1. drive backup
  1006. * The target bs is new opened, and the source is top BDS
  1007. * 2. blockdev backup
  1008. * Both the source and the target are top BDSes.
  1009. * 3. internal backup(used for block replication)
  1010. * Both the source and the target are backing file
  1011. *
  1012. * In case 1 and 2, neither the source nor the target is the backing file.
  1013. * In case 3, we will block the top BDS, so there is only one block job
  1014. * for the top BDS and its backing chain.
  1015. */
  1016. bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_SOURCE,
  1017. parent->backing_blocker);
  1018. bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_TARGET,
  1019. parent->backing_blocker);
  1020. }
  1021. static void bdrv_backing_detach(BdrvChild *c)
  1022. {
  1023. BlockDriverState *parent = c->opaque;
  1024. assert(parent->backing_blocker);
  1025. bdrv_op_unblock_all(c->bs, parent->backing_blocker);
  1026. error_free(parent->backing_blocker);
  1027. parent->backing_blocker = NULL;
  1028. }
  1029. static int bdrv_backing_update_filename(BdrvChild *c, BlockDriverState *base,
  1030. const char *filename, Error **errp)
  1031. {
  1032. BlockDriverState *parent = c->opaque;
  1033. bool read_only = bdrv_is_read_only(parent);
  1034. int ret;
  1035. if (read_only) {
  1036. ret = bdrv_reopen_set_read_only(parent, false, errp);
  1037. if (ret < 0) {
  1038. return ret;
  1039. }
  1040. }
  1041. ret = bdrv_change_backing_file(parent, filename,
  1042. base->drv ? base->drv->format_name : "",
  1043. false);
  1044. if (ret < 0) {
  1045. error_setg_errno(errp, -ret, "Could not update backing file link");
  1046. }
  1047. if (read_only) {
  1048. bdrv_reopen_set_read_only(parent, true, NULL);
  1049. }
  1050. return ret;
  1051. }
  1052. /*
  1053. * Returns the options and flags that a generic child of a BDS should
  1054. * get, based on the given options and flags for the parent BDS.
  1055. */
  1056. static void bdrv_inherited_options(BdrvChildRole role, bool parent_is_format,
  1057. int *child_flags, QDict *child_options,
  1058. int parent_flags, QDict *parent_options)
  1059. {
  1060. int flags = parent_flags;
  1061. /*
  1062. * First, decide whether to set, clear, or leave BDRV_O_PROTOCOL.
  1063. * Generally, the question to answer is: Should this child be
  1064. * format-probed by default?
  1065. */
  1066. /*
  1067. * Pure and non-filtered data children of non-format nodes should
  1068. * be probed by default (even when the node itself has BDRV_O_PROTOCOL
  1069. * set). This only affects a very limited set of drivers (namely
  1070. * quorum and blkverify when this comment was written).
  1071. * Force-clear BDRV_O_PROTOCOL then.
  1072. */
  1073. if (!parent_is_format &&
  1074. (role & BDRV_CHILD_DATA) &&
  1075. !(role & (BDRV_CHILD_METADATA | BDRV_CHILD_FILTERED)))
  1076. {
  1077. flags &= ~BDRV_O_PROTOCOL;
  1078. }
  1079. /*
  1080. * All children of format nodes (except for COW children) and all
  1081. * metadata children in general should never be format-probed.
  1082. * Force-set BDRV_O_PROTOCOL then.
  1083. */
  1084. if ((parent_is_format && !(role & BDRV_CHILD_COW)) ||
  1085. (role & BDRV_CHILD_METADATA))
  1086. {
  1087. flags |= BDRV_O_PROTOCOL;
  1088. }
  1089. /*
  1090. * If the cache mode isn't explicitly set, inherit direct and no-flush from
  1091. * the parent.
  1092. */
  1093. qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
  1094. qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
  1095. qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE);
  1096. if (role & BDRV_CHILD_COW) {
  1097. /* backing files are opened read-only by default */
  1098. qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "on");
  1099. qdict_set_default_str(child_options, BDRV_OPT_AUTO_READ_ONLY, "off");
  1100. } else {
  1101. /* Inherit the read-only option from the parent if it's not set */
  1102. qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
  1103. qdict_copy_default(child_options, parent_options,
  1104. BDRV_OPT_AUTO_READ_ONLY);
  1105. }
  1106. /*
  1107. * bdrv_co_pdiscard() respects unmap policy for the parent, so we
  1108. * can default to enable it on lower layers regardless of the
  1109. * parent option.
  1110. */
  1111. qdict_set_default_str(child_options, BDRV_OPT_DISCARD, "unmap");
  1112. /* Clear flags that only apply to the top layer */
  1113. flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
  1114. if (role & BDRV_CHILD_METADATA) {
  1115. flags &= ~BDRV_O_NO_IO;
  1116. }
  1117. if (role & BDRV_CHILD_COW) {
  1118. flags &= ~BDRV_O_TEMPORARY;
  1119. }
  1120. *child_flags = flags;
  1121. }
  1122. static void bdrv_child_cb_attach(BdrvChild *child)
  1123. {
  1124. BlockDriverState *bs = child->opaque;
  1125. if (child->role & BDRV_CHILD_COW) {
  1126. bdrv_backing_attach(child);
  1127. }
  1128. bdrv_apply_subtree_drain(child, bs);
  1129. }
  1130. static void bdrv_child_cb_detach(BdrvChild *child)
  1131. {
  1132. BlockDriverState *bs = child->opaque;
  1133. if (child->role & BDRV_CHILD_COW) {
  1134. bdrv_backing_detach(child);
  1135. }
  1136. bdrv_unapply_subtree_drain(child, bs);
  1137. }
  1138. static int bdrv_child_cb_update_filename(BdrvChild *c, BlockDriverState *base,
  1139. const char *filename, Error **errp)
  1140. {
  1141. if (c->role & BDRV_CHILD_COW) {
  1142. return bdrv_backing_update_filename(c, base, filename, errp);
  1143. }
  1144. return 0;
  1145. }
  1146. const BdrvChildClass child_of_bds = {
  1147. .parent_is_bds = true,
  1148. .get_parent_desc = bdrv_child_get_parent_desc,
  1149. .inherit_options = bdrv_inherited_options,
  1150. .drained_begin = bdrv_child_cb_drained_begin,
  1151. .drained_poll = bdrv_child_cb_drained_poll,
  1152. .drained_end = bdrv_child_cb_drained_end,
  1153. .attach = bdrv_child_cb_attach,
  1154. .detach = bdrv_child_cb_detach,
  1155. .inactivate = bdrv_child_cb_inactivate,
  1156. .can_set_aio_ctx = bdrv_child_cb_can_set_aio_ctx,
  1157. .set_aio_ctx = bdrv_child_cb_set_aio_ctx,
  1158. .update_filename = bdrv_child_cb_update_filename,
  1159. };
  1160. static int bdrv_open_flags(BlockDriverState *bs, int flags)
  1161. {
  1162. int open_flags = flags;
  1163. /*
  1164. * Clear flags that are internal to the block layer before opening the
  1165. * image.
  1166. */
  1167. open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
  1168. return open_flags;
  1169. }
  1170. static void update_flags_from_options(int *flags, QemuOpts *opts)
  1171. {
  1172. *flags &= ~(BDRV_O_CACHE_MASK | BDRV_O_RDWR | BDRV_O_AUTO_RDONLY);
  1173. if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
  1174. *flags |= BDRV_O_NO_FLUSH;
  1175. }
  1176. if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_DIRECT, false)) {
  1177. *flags |= BDRV_O_NOCACHE;
  1178. }
  1179. if (!qemu_opt_get_bool_del(opts, BDRV_OPT_READ_ONLY, false)) {
  1180. *flags |= BDRV_O_RDWR;
  1181. }
  1182. if (qemu_opt_get_bool_del(opts, BDRV_OPT_AUTO_READ_ONLY, false)) {
  1183. *flags |= BDRV_O_AUTO_RDONLY;
  1184. }
  1185. }
  1186. static void update_options_from_flags(QDict *options, int flags)
  1187. {
  1188. if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
  1189. qdict_put_bool(options, BDRV_OPT_CACHE_DIRECT, flags & BDRV_O_NOCACHE);
  1190. }
  1191. if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
  1192. qdict_put_bool(options, BDRV_OPT_CACHE_NO_FLUSH,
  1193. flags & BDRV_O_NO_FLUSH);
  1194. }
  1195. if (!qdict_haskey(options, BDRV_OPT_READ_ONLY)) {
  1196. qdict_put_bool(options, BDRV_OPT_READ_ONLY, !(flags & BDRV_O_RDWR));
  1197. }
  1198. if (!qdict_haskey(options, BDRV_OPT_AUTO_READ_ONLY)) {
  1199. qdict_put_bool(options, BDRV_OPT_AUTO_READ_ONLY,
  1200. flags & BDRV_O_AUTO_RDONLY);
  1201. }
  1202. }
  1203. static void bdrv_assign_node_name(BlockDriverState *bs,
  1204. const char *node_name,
  1205. Error **errp)
  1206. {
  1207. char *gen_node_name = NULL;
  1208. if (!node_name) {
  1209. node_name = gen_node_name = id_generate(ID_BLOCK);
  1210. } else if (!id_wellformed(node_name)) {
  1211. /*
  1212. * Check for empty string or invalid characters, but not if it is
  1213. * generated (generated names use characters not available to the user)
  1214. */
  1215. error_setg(errp, "Invalid node name");
  1216. return;
  1217. }
  1218. /* takes care of avoiding namespaces collisions */
  1219. if (blk_by_name(node_name)) {
  1220. error_setg(errp, "node-name=%s is conflicting with a device id",
  1221. node_name);
  1222. goto out;
  1223. }
  1224. /* takes care of avoiding duplicates node names */
  1225. if (bdrv_find_node(node_name)) {
  1226. error_setg(errp, "Duplicate node name");
  1227. goto out;
  1228. }
  1229. /* Make sure that the node name isn't truncated */
  1230. if (strlen(node_name) >= sizeof(bs->node_name)) {
  1231. error_setg(errp, "Node name too long");
  1232. goto out;
  1233. }
  1234. /* copy node name into the bs and insert it into the graph list */
  1235. pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
  1236. QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
  1237. out:
  1238. g_free(gen_node_name);
  1239. }
  1240. static int bdrv_open_driver(BlockDriverState *bs, BlockDriver *drv,
  1241. const char *node_name, QDict *options,
  1242. int open_flags, Error **errp)
  1243. {
  1244. Error *local_err = NULL;
  1245. int i, ret;
  1246. bdrv_assign_node_name(bs, node_name, &local_err);
  1247. if (local_err) {
  1248. error_propagate(errp, local_err);
  1249. return -EINVAL;
  1250. }
  1251. bs->drv = drv;
  1252. bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
  1253. bs->opaque = g_malloc0(drv->instance_size);
  1254. if (drv->bdrv_file_open) {
  1255. assert(!drv->bdrv_needs_filename || bs->filename[0]);
  1256. ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
  1257. } else if (drv->bdrv_open) {
  1258. ret = drv->bdrv_open(bs, options, open_flags, &local_err);
  1259. } else {
  1260. ret = 0;
  1261. }
  1262. if (ret < 0) {
  1263. if (local_err) {
  1264. error_propagate(errp, local_err);
  1265. } else if (bs->filename[0]) {
  1266. error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
  1267. } else {
  1268. error_setg_errno(errp, -ret, "Could not open image");
  1269. }
  1270. goto open_failed;
  1271. }
  1272. ret = refresh_total_sectors(bs, bs->total_sectors);
  1273. if (ret < 0) {
  1274. error_setg_errno(errp, -ret, "Could not refresh total sector count");
  1275. return ret;
  1276. }
  1277. bdrv_refresh_limits(bs, &local_err);
  1278. if (local_err) {
  1279. error_propagate(errp, local_err);
  1280. return -EINVAL;
  1281. }
  1282. assert(bdrv_opt_mem_align(bs) != 0);
  1283. assert(bdrv_min_mem_align(bs) != 0);
  1284. assert(is_power_of_2(bs->bl.request_alignment));
  1285. for (i = 0; i < bs->quiesce_counter; i++) {
  1286. if (drv->bdrv_co_drain_begin) {
  1287. drv->bdrv_co_drain_begin(bs);
  1288. }
  1289. }
  1290. return 0;
  1291. open_failed:
  1292. bs->drv = NULL;
  1293. if (bs->file != NULL) {
  1294. bdrv_unref_child(bs, bs->file);
  1295. bs->file = NULL;
  1296. }
  1297. g_free(bs->opaque);
  1298. bs->opaque = NULL;
  1299. return ret;
  1300. }
  1301. BlockDriverState *bdrv_new_open_driver(BlockDriver *drv, const char *node_name,
  1302. int flags, Error **errp)
  1303. {
  1304. BlockDriverState *bs;
  1305. int ret;
  1306. bs = bdrv_new();
  1307. bs->open_flags = flags;
  1308. bs->explicit_options = qdict_new();
  1309. bs->options = qdict_new();
  1310. bs->opaque = NULL;
  1311. update_options_from_flags(bs->options, flags);
  1312. ret = bdrv_open_driver(bs, drv, node_name, bs->options, flags, errp);
  1313. if (ret < 0) {
  1314. qobject_unref(bs->explicit_options);
  1315. bs->explicit_options = NULL;
  1316. qobject_unref(bs->options);
  1317. bs->options = NULL;
  1318. bdrv_unref(bs);
  1319. return NULL;
  1320. }
  1321. return bs;
  1322. }
  1323. QemuOptsList bdrv_runtime_opts = {
  1324. .name = "bdrv_common",
  1325. .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
  1326. .desc = {
  1327. {
  1328. .name = "node-name",
  1329. .type = QEMU_OPT_STRING,
  1330. .help = "Node name of the block device node",
  1331. },
  1332. {
  1333. .name = "driver",
  1334. .type = QEMU_OPT_STRING,
  1335. .help = "Block driver to use for the node",
  1336. },
  1337. {
  1338. .name = BDRV_OPT_CACHE_DIRECT,
  1339. .type = QEMU_OPT_BOOL,
  1340. .help = "Bypass software writeback cache on the host",
  1341. },
  1342. {
  1343. .name = BDRV_OPT_CACHE_NO_FLUSH,
  1344. .type = QEMU_OPT_BOOL,
  1345. .help = "Ignore flush requests",
  1346. },
  1347. {
  1348. .name = BDRV_OPT_READ_ONLY,
  1349. .type = QEMU_OPT_BOOL,
  1350. .help = "Node is opened in read-only mode",
  1351. },
  1352. {
  1353. .name = BDRV_OPT_AUTO_READ_ONLY,
  1354. .type = QEMU_OPT_BOOL,
  1355. .help = "Node can become read-only if opening read-write fails",
  1356. },
  1357. {
  1358. .name = "detect-zeroes",
  1359. .type = QEMU_OPT_STRING,
  1360. .help = "try to optimize zero writes (off, on, unmap)",
  1361. },
  1362. {
  1363. .name = BDRV_OPT_DISCARD,
  1364. .type = QEMU_OPT_STRING,
  1365. .help = "discard operation (ignore/off, unmap/on)",
  1366. },
  1367. {
  1368. .name = BDRV_OPT_FORCE_SHARE,
  1369. .type = QEMU_OPT_BOOL,
  1370. .help = "always accept other writers (default: off)",
  1371. },
  1372. { /* end of list */ }
  1373. },
  1374. };
  1375. QemuOptsList bdrv_create_opts_simple = {
  1376. .name = "simple-create-opts",
  1377. .head = QTAILQ_HEAD_INITIALIZER(bdrv_create_opts_simple.head),
  1378. .desc = {
  1379. {
  1380. .name = BLOCK_OPT_SIZE,
  1381. .type = QEMU_OPT_SIZE,
  1382. .help = "Virtual disk size"
  1383. },
  1384. {
  1385. .name = BLOCK_OPT_PREALLOC,
  1386. .type = QEMU_OPT_STRING,
  1387. .help = "Preallocation mode (allowed values: off)"
  1388. },
  1389. { /* end of list */ }
  1390. }
  1391. };
  1392. /*
  1393. * Common part for opening disk images and files
  1394. *
  1395. * Removes all processed options from *options.
  1396. */
  1397. static int bdrv_open_common(BlockDriverState *bs, BlockBackend *file,
  1398. QDict *options, Error **errp)
  1399. {
  1400. int ret, open_flags;
  1401. const char *filename;
  1402. const char *driver_name = NULL;
  1403. const char *node_name = NULL;
  1404. const char *discard;
  1405. QemuOpts *opts;
  1406. BlockDriver *drv;
  1407. Error *local_err = NULL;
  1408. assert(bs->file == NULL);
  1409. assert(options != NULL && bs->options != options);
  1410. opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
  1411. if (!qemu_opts_absorb_qdict(opts, options, errp)) {
  1412. ret = -EINVAL;
  1413. goto fail_opts;
  1414. }
  1415. update_flags_from_options(&bs->open_flags, opts);
  1416. driver_name = qemu_opt_get(opts, "driver");
  1417. drv = bdrv_find_format(driver_name);
  1418. assert(drv != NULL);
  1419. bs->force_share = qemu_opt_get_bool(opts, BDRV_OPT_FORCE_SHARE, false);
  1420. if (bs->force_share && (bs->open_flags & BDRV_O_RDWR)) {
  1421. error_setg(errp,
  1422. BDRV_OPT_FORCE_SHARE
  1423. "=on can only be used with read-only images");
  1424. ret = -EINVAL;
  1425. goto fail_opts;
  1426. }
  1427. if (file != NULL) {
  1428. bdrv_refresh_filename(blk_bs(file));
  1429. filename = blk_bs(file)->filename;
  1430. } else {
  1431. /*
  1432. * Caution: while qdict_get_try_str() is fine, getting
  1433. * non-string types would require more care. When @options
  1434. * come from -blockdev or blockdev_add, its members are typed
  1435. * according to the QAPI schema, but when they come from
  1436. * -drive, they're all QString.
  1437. */
  1438. filename = qdict_get_try_str(options, "filename");
  1439. }
  1440. if (drv->bdrv_needs_filename && (!filename || !filename[0])) {
  1441. error_setg(errp, "The '%s' block driver requires a file name",
  1442. drv->format_name);
  1443. ret = -EINVAL;
  1444. goto fail_opts;
  1445. }
  1446. trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
  1447. drv->format_name);
  1448. bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
  1449. if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
  1450. if (!bs->read_only && bdrv_is_whitelisted(drv, true)) {
  1451. ret = bdrv_apply_auto_read_only(bs, NULL, NULL);
  1452. } else {
  1453. ret = -ENOTSUP;
  1454. }
  1455. if (ret < 0) {
  1456. error_setg(errp,
  1457. !bs->read_only && bdrv_is_whitelisted(drv, true)
  1458. ? "Driver '%s' can only be used for read-only devices"
  1459. : "Driver '%s' is not whitelisted",
  1460. drv->format_name);
  1461. goto fail_opts;
  1462. }
  1463. }
  1464. /* bdrv_new() and bdrv_close() make it so */
  1465. assert(qatomic_read(&bs->copy_on_read) == 0);
  1466. if (bs->open_flags & BDRV_O_COPY_ON_READ) {
  1467. if (!bs->read_only) {
  1468. bdrv_enable_copy_on_read(bs);
  1469. } else {
  1470. error_setg(errp, "Can't use copy-on-read on read-only device");
  1471. ret = -EINVAL;
  1472. goto fail_opts;
  1473. }
  1474. }
  1475. discard = qemu_opt_get(opts, BDRV_OPT_DISCARD);
  1476. if (discard != NULL) {
  1477. if (bdrv_parse_discard_flags(discard, &bs->open_flags) != 0) {
  1478. error_setg(errp, "Invalid discard option");
  1479. ret = -EINVAL;
  1480. goto fail_opts;
  1481. }
  1482. }
  1483. bs->detect_zeroes =
  1484. bdrv_parse_detect_zeroes(opts, bs->open_flags, &local_err);
  1485. if (local_err) {
  1486. error_propagate(errp, local_err);
  1487. ret = -EINVAL;
  1488. goto fail_opts;
  1489. }
  1490. if (filename != NULL) {
  1491. pstrcpy(bs->filename, sizeof(bs->filename), filename);
  1492. } else {
  1493. bs->filename[0] = '\0';
  1494. }
  1495. pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
  1496. /* Open the image, either directly or using a protocol */
  1497. open_flags = bdrv_open_flags(bs, bs->open_flags);
  1498. node_name = qemu_opt_get(opts, "node-name");
  1499. assert(!drv->bdrv_file_open || file == NULL);
  1500. ret = bdrv_open_driver(bs, drv, node_name, options, open_flags, errp);
  1501. if (ret < 0) {
  1502. goto fail_opts;
  1503. }
  1504. qemu_opts_del(opts);
  1505. return 0;
  1506. fail_opts:
  1507. qemu_opts_del(opts);
  1508. return ret;
  1509. }
  1510. static QDict *parse_json_filename(const char *filename, Error **errp)
  1511. {
  1512. QObject *options_obj;
  1513. QDict *options;
  1514. int ret;
  1515. ret = strstart(filename, "json:", &filename);
  1516. assert(ret);
  1517. options_obj = qobject_from_json(filename, errp);
  1518. if (!options_obj) {
  1519. error_prepend(errp, "Could not parse the JSON options: ");
  1520. return NULL;
  1521. }
  1522. options = qobject_to(QDict, options_obj);
  1523. if (!options) {
  1524. qobject_unref(options_obj);
  1525. error_setg(errp, "Invalid JSON object given");
  1526. return NULL;
  1527. }
  1528. qdict_flatten(options);
  1529. return options;
  1530. }
  1531. static void parse_json_protocol(QDict *options, const char **pfilename,
  1532. Error **errp)
  1533. {
  1534. QDict *json_options;
  1535. Error *local_err = NULL;
  1536. /* Parse json: pseudo-protocol */
  1537. if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
  1538. return;
  1539. }
  1540. json_options = parse_json_filename(*pfilename, &local_err);
  1541. if (local_err) {
  1542. error_propagate(errp, local_err);
  1543. return;
  1544. }
  1545. /* Options given in the filename have lower priority than options
  1546. * specified directly */
  1547. qdict_join(options, json_options, false);
  1548. qobject_unref(json_options);
  1549. *pfilename = NULL;
  1550. }
  1551. /*
  1552. * Fills in default options for opening images and converts the legacy
  1553. * filename/flags pair to option QDict entries.
  1554. * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
  1555. * block driver has been specified explicitly.
  1556. */
  1557. static int bdrv_fill_options(QDict **options, const char *filename,
  1558. int *flags, Error **errp)
  1559. {
  1560. const char *drvname;
  1561. bool protocol = *flags & BDRV_O_PROTOCOL;
  1562. bool parse_filename = false;
  1563. BlockDriver *drv = NULL;
  1564. Error *local_err = NULL;
  1565. /*
  1566. * Caution: while qdict_get_try_str() is fine, getting non-string
  1567. * types would require more care. When @options come from
  1568. * -blockdev or blockdev_add, its members are typed according to
  1569. * the QAPI schema, but when they come from -drive, they're all
  1570. * QString.
  1571. */
  1572. drvname = qdict_get_try_str(*options, "driver");
  1573. if (drvname) {
  1574. drv = bdrv_find_format(drvname);
  1575. if (!drv) {
  1576. error_setg(errp, "Unknown driver '%s'", drvname);
  1577. return -ENOENT;
  1578. }
  1579. /* If the user has explicitly specified the driver, this choice should
  1580. * override the BDRV_O_PROTOCOL flag */
  1581. protocol = drv->bdrv_file_open;
  1582. }
  1583. if (protocol) {
  1584. *flags |= BDRV_O_PROTOCOL;
  1585. } else {
  1586. *flags &= ~BDRV_O_PROTOCOL;
  1587. }
  1588. /* Translate cache options from flags into options */
  1589. update_options_from_flags(*options, *flags);
  1590. /* Fetch the file name from the options QDict if necessary */
  1591. if (protocol && filename) {
  1592. if (!qdict_haskey(*options, "filename")) {
  1593. qdict_put_str(*options, "filename", filename);
  1594. parse_filename = true;
  1595. } else {
  1596. error_setg(errp, "Can't specify 'file' and 'filename' options at "
  1597. "the same time");
  1598. return -EINVAL;
  1599. }
  1600. }
  1601. /* Find the right block driver */
  1602. /* See cautionary note on accessing @options above */
  1603. filename = qdict_get_try_str(*options, "filename");
  1604. if (!drvname && protocol) {
  1605. if (filename) {
  1606. drv = bdrv_find_protocol(filename, parse_filename, errp);
  1607. if (!drv) {
  1608. return -EINVAL;
  1609. }
  1610. drvname = drv->format_name;
  1611. qdict_put_str(*options, "driver", drvname);
  1612. } else {
  1613. error_setg(errp, "Must specify either driver or file");
  1614. return -EINVAL;
  1615. }
  1616. }
  1617. assert(drv || !protocol);
  1618. /* Driver-specific filename parsing */
  1619. if (drv && drv->bdrv_parse_filename && parse_filename) {
  1620. drv->bdrv_parse_filename(filename, *options, &local_err);
  1621. if (local_err) {
  1622. error_propagate(errp, local_err);
  1623. return -EINVAL;
  1624. }
  1625. if (!drv->bdrv_needs_filename) {
  1626. qdict_del(*options, "filename");
  1627. }
  1628. }
  1629. return 0;
  1630. }
  1631. static int bdrv_child_check_perm(BdrvChild *c, BlockReopenQueue *q,
  1632. uint64_t perm, uint64_t shared,
  1633. GSList *ignore_children,
  1634. bool *tighten_restrictions, Error **errp);
  1635. static void bdrv_child_abort_perm_update(BdrvChild *c);
  1636. static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared);
  1637. typedef struct BlockReopenQueueEntry {
  1638. bool prepared;
  1639. bool perms_checked;
  1640. BDRVReopenState state;
  1641. QTAILQ_ENTRY(BlockReopenQueueEntry) entry;
  1642. } BlockReopenQueueEntry;
  1643. /*
  1644. * Return the flags that @bs will have after the reopens in @q have
  1645. * successfully completed. If @q is NULL (or @bs is not contained in @q),
  1646. * return the current flags.
  1647. */
  1648. static int bdrv_reopen_get_flags(BlockReopenQueue *q, BlockDriverState *bs)
  1649. {
  1650. BlockReopenQueueEntry *entry;
  1651. if (q != NULL) {
  1652. QTAILQ_FOREACH(entry, q, entry) {
  1653. if (entry->state.bs == bs) {
  1654. return entry->state.flags;
  1655. }
  1656. }
  1657. }
  1658. return bs->open_flags;
  1659. }
  1660. /* Returns whether the image file can be written to after the reopen queue @q
  1661. * has been successfully applied, or right now if @q is NULL. */
  1662. static bool bdrv_is_writable_after_reopen(BlockDriverState *bs,
  1663. BlockReopenQueue *q)
  1664. {
  1665. int flags = bdrv_reopen_get_flags(q, bs);
  1666. return (flags & (BDRV_O_RDWR | BDRV_O_INACTIVE)) == BDRV_O_RDWR;
  1667. }
  1668. /*
  1669. * Return whether the BDS can be written to. This is not necessarily
  1670. * the same as !bdrv_is_read_only(bs), as inactivated images may not
  1671. * be written to but do not count as read-only images.
  1672. */
  1673. bool bdrv_is_writable(BlockDriverState *bs)
  1674. {
  1675. return bdrv_is_writable_after_reopen(bs, NULL);
  1676. }
  1677. static void bdrv_child_perm(BlockDriverState *bs, BlockDriverState *child_bs,
  1678. BdrvChild *c, BdrvChildRole role,
  1679. BlockReopenQueue *reopen_queue,
  1680. uint64_t parent_perm, uint64_t parent_shared,
  1681. uint64_t *nperm, uint64_t *nshared)
  1682. {
  1683. assert(bs->drv && bs->drv->bdrv_child_perm);
  1684. bs->drv->bdrv_child_perm(bs, c, role, reopen_queue,
  1685. parent_perm, parent_shared,
  1686. nperm, nshared);
  1687. /* TODO Take force_share from reopen_queue */
  1688. if (child_bs && child_bs->force_share) {
  1689. *nshared = BLK_PERM_ALL;
  1690. }
  1691. }
  1692. /*
  1693. * Check whether permissions on this node can be changed in a way that
  1694. * @cumulative_perms and @cumulative_shared_perms are the new cumulative
  1695. * permissions of all its parents. This involves checking whether all necessary
  1696. * permission changes to child nodes can be performed.
  1697. *
  1698. * Will set *tighten_restrictions to true if and only if new permissions have to
  1699. * be taken or currently shared permissions are to be unshared. Otherwise,
  1700. * errors are not fatal as long as the caller accepts that the restrictions
  1701. * remain tighter than they need to be. The caller still has to abort the
  1702. * transaction.
  1703. * @tighten_restrictions cannot be used together with @q: When reopening, we may
  1704. * encounter fatal errors even though no restrictions are to be tightened. For
  1705. * example, changing a node from RW to RO will fail if the WRITE permission is
  1706. * to be kept.
  1707. *
  1708. * A call to this function must always be followed by a call to bdrv_set_perm()
  1709. * or bdrv_abort_perm_update().
  1710. */
  1711. static int bdrv_check_perm(BlockDriverState *bs, BlockReopenQueue *q,
  1712. uint64_t cumulative_perms,
  1713. uint64_t cumulative_shared_perms,
  1714. GSList *ignore_children,
  1715. bool *tighten_restrictions, Error **errp)
  1716. {
  1717. BlockDriver *drv = bs->drv;
  1718. BdrvChild *c;
  1719. int ret;
  1720. assert(!q || !tighten_restrictions);
  1721. if (tighten_restrictions) {
  1722. uint64_t current_perms, current_shared;
  1723. uint64_t added_perms, removed_shared_perms;
  1724. bdrv_get_cumulative_perm(bs, &current_perms, &current_shared);
  1725. added_perms = cumulative_perms & ~current_perms;
  1726. removed_shared_perms = current_shared & ~cumulative_shared_perms;
  1727. *tighten_restrictions = added_perms || removed_shared_perms;
  1728. }
  1729. /* Write permissions never work with read-only images */
  1730. if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
  1731. !bdrv_is_writable_after_reopen(bs, q))
  1732. {
  1733. if (!bdrv_is_writable_after_reopen(bs, NULL)) {
  1734. error_setg(errp, "Block node is read-only");
  1735. } else {
  1736. uint64_t current_perms, current_shared;
  1737. bdrv_get_cumulative_perm(bs, &current_perms, &current_shared);
  1738. if (current_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) {
  1739. error_setg(errp, "Cannot make block node read-only, there is "
  1740. "a writer on it");
  1741. } else {
  1742. error_setg(errp, "Cannot make block node read-only and create "
  1743. "a writer on it");
  1744. }
  1745. }
  1746. return -EPERM;
  1747. }
  1748. /*
  1749. * Unaligned requests will automatically be aligned to bl.request_alignment
  1750. * and without RESIZE we can't extend requests to write to space beyond the
  1751. * end of the image, so it's required that the image size is aligned.
  1752. */
  1753. if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
  1754. !(cumulative_perms & BLK_PERM_RESIZE))
  1755. {
  1756. if ((bs->total_sectors * BDRV_SECTOR_SIZE) % bs->bl.request_alignment) {
  1757. error_setg(errp, "Cannot get 'write' permission without 'resize': "
  1758. "Image size is not a multiple of request "
  1759. "alignment");
  1760. return -EPERM;
  1761. }
  1762. }
  1763. /* Check this node */
  1764. if (!drv) {
  1765. return 0;
  1766. }
  1767. if (drv->bdrv_check_perm) {
  1768. return drv->bdrv_check_perm(bs, cumulative_perms,
  1769. cumulative_shared_perms, errp);
  1770. }
  1771. /* Drivers that never have children can omit .bdrv_child_perm() */
  1772. if (!drv->bdrv_child_perm) {
  1773. assert(QLIST_EMPTY(&bs->children));
  1774. return 0;
  1775. }
  1776. /* Check all children */
  1777. QLIST_FOREACH(c, &bs->children, next) {
  1778. uint64_t cur_perm, cur_shared;
  1779. bool child_tighten_restr;
  1780. bdrv_child_perm(bs, c->bs, c, c->role, q,
  1781. cumulative_perms, cumulative_shared_perms,
  1782. &cur_perm, &cur_shared);
  1783. ret = bdrv_child_check_perm(c, q, cur_perm, cur_shared, ignore_children,
  1784. tighten_restrictions ? &child_tighten_restr
  1785. : NULL,
  1786. errp);
  1787. if (tighten_restrictions) {
  1788. *tighten_restrictions |= child_tighten_restr;
  1789. }
  1790. if (ret < 0) {
  1791. return ret;
  1792. }
  1793. }
  1794. return 0;
  1795. }
  1796. /*
  1797. * Notifies drivers that after a previous bdrv_check_perm() call, the
  1798. * permission update is not performed and any preparations made for it (e.g.
  1799. * taken file locks) need to be undone.
  1800. *
  1801. * This function recursively notifies all child nodes.
  1802. */
  1803. static void bdrv_abort_perm_update(BlockDriverState *bs)
  1804. {
  1805. BlockDriver *drv = bs->drv;
  1806. BdrvChild *c;
  1807. if (!drv) {
  1808. return;
  1809. }
  1810. if (drv->bdrv_abort_perm_update) {
  1811. drv->bdrv_abort_perm_update(bs);
  1812. }
  1813. QLIST_FOREACH(c, &bs->children, next) {
  1814. bdrv_child_abort_perm_update(c);
  1815. }
  1816. }
  1817. static void bdrv_set_perm(BlockDriverState *bs, uint64_t cumulative_perms,
  1818. uint64_t cumulative_shared_perms)
  1819. {
  1820. BlockDriver *drv = bs->drv;
  1821. BdrvChild *c;
  1822. if (!drv) {
  1823. return;
  1824. }
  1825. /* Update this node */
  1826. if (drv->bdrv_set_perm) {
  1827. drv->bdrv_set_perm(bs, cumulative_perms, cumulative_shared_perms);
  1828. }
  1829. /* Drivers that never have children can omit .bdrv_child_perm() */
  1830. if (!drv->bdrv_child_perm) {
  1831. assert(QLIST_EMPTY(&bs->children));
  1832. return;
  1833. }
  1834. /* Update all children */
  1835. QLIST_FOREACH(c, &bs->children, next) {
  1836. uint64_t cur_perm, cur_shared;
  1837. bdrv_child_perm(bs, c->bs, c, c->role, NULL,
  1838. cumulative_perms, cumulative_shared_perms,
  1839. &cur_perm, &cur_shared);
  1840. bdrv_child_set_perm(c, cur_perm, cur_shared);
  1841. }
  1842. }
  1843. void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm,
  1844. uint64_t *shared_perm)
  1845. {
  1846. BdrvChild *c;
  1847. uint64_t cumulative_perms = 0;
  1848. uint64_t cumulative_shared_perms = BLK_PERM_ALL;
  1849. QLIST_FOREACH(c, &bs->parents, next_parent) {
  1850. cumulative_perms |= c->perm;
  1851. cumulative_shared_perms &= c->shared_perm;
  1852. }
  1853. *perm = cumulative_perms;
  1854. *shared_perm = cumulative_shared_perms;
  1855. }
  1856. static char *bdrv_child_user_desc(BdrvChild *c)
  1857. {
  1858. if (c->klass->get_parent_desc) {
  1859. return c->klass->get_parent_desc(c);
  1860. }
  1861. return g_strdup("another user");
  1862. }
  1863. char *bdrv_perm_names(uint64_t perm)
  1864. {
  1865. struct perm_name {
  1866. uint64_t perm;
  1867. const char *name;
  1868. } permissions[] = {
  1869. { BLK_PERM_CONSISTENT_READ, "consistent read" },
  1870. { BLK_PERM_WRITE, "write" },
  1871. { BLK_PERM_WRITE_UNCHANGED, "write unchanged" },
  1872. { BLK_PERM_RESIZE, "resize" },
  1873. { BLK_PERM_GRAPH_MOD, "change children" },
  1874. { 0, NULL }
  1875. };
  1876. GString *result = g_string_sized_new(30);
  1877. struct perm_name *p;
  1878. for (p = permissions; p->name; p++) {
  1879. if (perm & p->perm) {
  1880. if (result->len > 0) {
  1881. g_string_append(result, ", ");
  1882. }
  1883. g_string_append(result, p->name);
  1884. }
  1885. }
  1886. return g_string_free(result, FALSE);
  1887. }
  1888. /*
  1889. * Checks whether a new reference to @bs can be added if the new user requires
  1890. * @new_used_perm/@new_shared_perm as its permissions. If @ignore_children is
  1891. * set, the BdrvChild objects in this list are ignored in the calculations;
  1892. * this allows checking permission updates for an existing reference.
  1893. *
  1894. * See bdrv_check_perm() for the semantics of @tighten_restrictions.
  1895. *
  1896. * Needs to be followed by a call to either bdrv_set_perm() or
  1897. * bdrv_abort_perm_update(). */
  1898. static int bdrv_check_update_perm(BlockDriverState *bs, BlockReopenQueue *q,
  1899. uint64_t new_used_perm,
  1900. uint64_t new_shared_perm,
  1901. GSList *ignore_children,
  1902. bool *tighten_restrictions,
  1903. Error **errp)
  1904. {
  1905. BdrvChild *c;
  1906. uint64_t cumulative_perms = new_used_perm;
  1907. uint64_t cumulative_shared_perms = new_shared_perm;
  1908. assert(!q || !tighten_restrictions);
  1909. /* There is no reason why anyone couldn't tolerate write_unchanged */
  1910. assert(new_shared_perm & BLK_PERM_WRITE_UNCHANGED);
  1911. QLIST_FOREACH(c, &bs->parents, next_parent) {
  1912. if (g_slist_find(ignore_children, c)) {
  1913. continue;
  1914. }
  1915. if ((new_used_perm & c->shared_perm) != new_used_perm) {
  1916. char *user = bdrv_child_user_desc(c);
  1917. char *perm_names = bdrv_perm_names(new_used_perm & ~c->shared_perm);
  1918. if (tighten_restrictions) {
  1919. *tighten_restrictions = true;
  1920. }
  1921. error_setg(errp, "Conflicts with use by %s as '%s', which does not "
  1922. "allow '%s' on %s",
  1923. user, c->name, perm_names, bdrv_get_node_name(c->bs));
  1924. g_free(user);
  1925. g_free(perm_names);
  1926. return -EPERM;
  1927. }
  1928. if ((c->perm & new_shared_perm) != c->perm) {
  1929. char *user = bdrv_child_user_desc(c);
  1930. char *perm_names = bdrv_perm_names(c->perm & ~new_shared_perm);
  1931. if (tighten_restrictions) {
  1932. *tighten_restrictions = true;
  1933. }
  1934. error_setg(errp, "Conflicts with use by %s as '%s', which uses "
  1935. "'%s' on %s",
  1936. user, c->name, perm_names, bdrv_get_node_name(c->bs));
  1937. g_free(user);
  1938. g_free(perm_names);
  1939. return -EPERM;
  1940. }
  1941. cumulative_perms |= c->perm;
  1942. cumulative_shared_perms &= c->shared_perm;
  1943. }
  1944. return bdrv_check_perm(bs, q, cumulative_perms, cumulative_shared_perms,
  1945. ignore_children, tighten_restrictions, errp);
  1946. }
  1947. /* Needs to be followed by a call to either bdrv_child_set_perm() or
  1948. * bdrv_child_abort_perm_update(). */
  1949. static int bdrv_child_check_perm(BdrvChild *c, BlockReopenQueue *q,
  1950. uint64_t perm, uint64_t shared,
  1951. GSList *ignore_children,
  1952. bool *tighten_restrictions, Error **errp)
  1953. {
  1954. int ret;
  1955. ignore_children = g_slist_prepend(g_slist_copy(ignore_children), c);
  1956. ret = bdrv_check_update_perm(c->bs, q, perm, shared, ignore_children,
  1957. tighten_restrictions, errp);
  1958. g_slist_free(ignore_children);
  1959. if (ret < 0) {
  1960. return ret;
  1961. }
  1962. if (!c->has_backup_perm) {
  1963. c->has_backup_perm = true;
  1964. c->backup_perm = c->perm;
  1965. c->backup_shared_perm = c->shared_perm;
  1966. }
  1967. /*
  1968. * Note: it's OK if c->has_backup_perm was already set, as we can find the
  1969. * same child twice during check_perm procedure
  1970. */
  1971. c->perm = perm;
  1972. c->shared_perm = shared;
  1973. return 0;
  1974. }
  1975. static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared)
  1976. {
  1977. uint64_t cumulative_perms, cumulative_shared_perms;
  1978. c->has_backup_perm = false;
  1979. c->perm = perm;
  1980. c->shared_perm = shared;
  1981. bdrv_get_cumulative_perm(c->bs, &cumulative_perms,
  1982. &cumulative_shared_perms);
  1983. bdrv_set_perm(c->bs, cumulative_perms, cumulative_shared_perms);
  1984. }
  1985. static void bdrv_child_abort_perm_update(BdrvChild *c)
  1986. {
  1987. if (c->has_backup_perm) {
  1988. c->perm = c->backup_perm;
  1989. c->shared_perm = c->backup_shared_perm;
  1990. c->has_backup_perm = false;
  1991. }
  1992. bdrv_abort_perm_update(c->bs);
  1993. }
  1994. int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
  1995. Error **errp)
  1996. {
  1997. Error *local_err = NULL;
  1998. int ret;
  1999. bool tighten_restrictions;
  2000. ret = bdrv_child_check_perm(c, NULL, perm, shared, NULL,
  2001. &tighten_restrictions, &local_err);
  2002. if (ret < 0) {
  2003. bdrv_child_abort_perm_update(c);
  2004. if (tighten_restrictions) {
  2005. error_propagate(errp, local_err);
  2006. } else {
  2007. /*
  2008. * Our caller may intend to only loosen restrictions and
  2009. * does not expect this function to fail. Errors are not
  2010. * fatal in such a case, so we can just hide them from our
  2011. * caller.
  2012. */
  2013. error_free(local_err);
  2014. ret = 0;
  2015. }
  2016. return ret;
  2017. }
  2018. bdrv_child_set_perm(c, perm, shared);
  2019. return 0;
  2020. }
  2021. int bdrv_child_refresh_perms(BlockDriverState *bs, BdrvChild *c, Error **errp)
  2022. {
  2023. uint64_t parent_perms, parent_shared;
  2024. uint64_t perms, shared;
  2025. bdrv_get_cumulative_perm(bs, &parent_perms, &parent_shared);
  2026. bdrv_child_perm(bs, c->bs, c, c->role, NULL,
  2027. parent_perms, parent_shared, &perms, &shared);
  2028. return bdrv_child_try_set_perm(c, perms, shared, errp);
  2029. }
  2030. /*
  2031. * Default implementation for .bdrv_child_perm() for block filters:
  2032. * Forward CONSISTENT_READ, WRITE, WRITE_UNCHANGED, and RESIZE to the
  2033. * filtered child.
  2034. */
  2035. static void bdrv_filter_default_perms(BlockDriverState *bs, BdrvChild *c,
  2036. BdrvChildRole role,
  2037. BlockReopenQueue *reopen_queue,
  2038. uint64_t perm, uint64_t shared,
  2039. uint64_t *nperm, uint64_t *nshared)
  2040. {
  2041. *nperm = perm & DEFAULT_PERM_PASSTHROUGH;
  2042. *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) | DEFAULT_PERM_UNCHANGED;
  2043. }
  2044. static void bdrv_default_perms_for_cow(BlockDriverState *bs, BdrvChild *c,
  2045. BdrvChildRole role,
  2046. BlockReopenQueue *reopen_queue,
  2047. uint64_t perm, uint64_t shared,
  2048. uint64_t *nperm, uint64_t *nshared)
  2049. {
  2050. assert(role & BDRV_CHILD_COW);
  2051. /*
  2052. * We want consistent read from backing files if the parent needs it.
  2053. * No other operations are performed on backing files.
  2054. */
  2055. perm &= BLK_PERM_CONSISTENT_READ;
  2056. /*
  2057. * If the parent can deal with changing data, we're okay with a
  2058. * writable and resizable backing file.
  2059. * TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too?
  2060. */
  2061. if (shared & BLK_PERM_WRITE) {
  2062. shared = BLK_PERM_WRITE | BLK_PERM_RESIZE;
  2063. } else {
  2064. shared = 0;
  2065. }
  2066. shared |= BLK_PERM_CONSISTENT_READ | BLK_PERM_GRAPH_MOD |
  2067. BLK_PERM_WRITE_UNCHANGED;
  2068. if (bs->open_flags & BDRV_O_INACTIVE) {
  2069. shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
  2070. }
  2071. *nperm = perm;
  2072. *nshared = shared;
  2073. }
  2074. static void bdrv_default_perms_for_storage(BlockDriverState *bs, BdrvChild *c,
  2075. BdrvChildRole role,
  2076. BlockReopenQueue *reopen_queue,
  2077. uint64_t perm, uint64_t shared,
  2078. uint64_t *nperm, uint64_t *nshared)
  2079. {
  2080. int flags;
  2081. assert(role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA));
  2082. flags = bdrv_reopen_get_flags(reopen_queue, bs);
  2083. /*
  2084. * Apart from the modifications below, the same permissions are
  2085. * forwarded and left alone as for filters
  2086. */
  2087. bdrv_filter_default_perms(bs, c, role, reopen_queue,
  2088. perm, shared, &perm, &shared);
  2089. if (role & BDRV_CHILD_METADATA) {
  2090. /* Format drivers may touch metadata even if the guest doesn't write */
  2091. if (bdrv_is_writable_after_reopen(bs, reopen_queue)) {
  2092. perm |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
  2093. }
  2094. /*
  2095. * bs->file always needs to be consistent because of the
  2096. * metadata. We can never allow other users to resize or write
  2097. * to it.
  2098. */
  2099. if (!(flags & BDRV_O_NO_IO)) {
  2100. perm |= BLK_PERM_CONSISTENT_READ;
  2101. }
  2102. shared &= ~(BLK_PERM_WRITE | BLK_PERM_RESIZE);
  2103. }
  2104. if (role & BDRV_CHILD_DATA) {
  2105. /*
  2106. * Technically, everything in this block is a subset of the
  2107. * BDRV_CHILD_METADATA path taken above, and so this could
  2108. * be an "else if" branch. However, that is not obvious, and
  2109. * this function is not performance critical, therefore we let
  2110. * this be an independent "if".
  2111. */
  2112. /*
  2113. * We cannot allow other users to resize the file because the
  2114. * format driver might have some assumptions about the size
  2115. * (e.g. because it is stored in metadata, or because the file
  2116. * is split into fixed-size data files).
  2117. */
  2118. shared &= ~BLK_PERM_RESIZE;
  2119. /*
  2120. * WRITE_UNCHANGED often cannot be performed as such on the
  2121. * data file. For example, the qcow2 driver may still need to
  2122. * write copied clusters on copy-on-read.
  2123. */
  2124. if (perm & BLK_PERM_WRITE_UNCHANGED) {
  2125. perm |= BLK_PERM_WRITE;
  2126. }
  2127. /*
  2128. * If the data file is written to, the format driver may
  2129. * expect to be able to resize it by writing beyond the EOF.
  2130. */
  2131. if (perm & BLK_PERM_WRITE) {
  2132. perm |= BLK_PERM_RESIZE;
  2133. }
  2134. }
  2135. if (bs->open_flags & BDRV_O_INACTIVE) {
  2136. shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
  2137. }
  2138. *nperm = perm;
  2139. *nshared = shared;
  2140. }
  2141. void bdrv_default_perms(BlockDriverState *bs, BdrvChild *c,
  2142. BdrvChildRole role, BlockReopenQueue *reopen_queue,
  2143. uint64_t perm, uint64_t shared,
  2144. uint64_t *nperm, uint64_t *nshared)
  2145. {
  2146. if (role & BDRV_CHILD_FILTERED) {
  2147. assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
  2148. BDRV_CHILD_COW)));
  2149. bdrv_filter_default_perms(bs, c, role, reopen_queue,
  2150. perm, shared, nperm, nshared);
  2151. } else if (role & BDRV_CHILD_COW) {
  2152. assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA)));
  2153. bdrv_default_perms_for_cow(bs, c, role, reopen_queue,
  2154. perm, shared, nperm, nshared);
  2155. } else if (role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA)) {
  2156. bdrv_default_perms_for_storage(bs, c, role, reopen_queue,
  2157. perm, shared, nperm, nshared);
  2158. } else {
  2159. g_assert_not_reached();
  2160. }
  2161. }
  2162. uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm)
  2163. {
  2164. static const uint64_t permissions[] = {
  2165. [BLOCK_PERMISSION_CONSISTENT_READ] = BLK_PERM_CONSISTENT_READ,
  2166. [BLOCK_PERMISSION_WRITE] = BLK_PERM_WRITE,
  2167. [BLOCK_PERMISSION_WRITE_UNCHANGED] = BLK_PERM_WRITE_UNCHANGED,
  2168. [BLOCK_PERMISSION_RESIZE] = BLK_PERM_RESIZE,
  2169. [BLOCK_PERMISSION_GRAPH_MOD] = BLK_PERM_GRAPH_MOD,
  2170. };
  2171. QEMU_BUILD_BUG_ON(ARRAY_SIZE(permissions) != BLOCK_PERMISSION__MAX);
  2172. QEMU_BUILD_BUG_ON(1UL << ARRAY_SIZE(permissions) != BLK_PERM_ALL + 1);
  2173. assert(qapi_perm < BLOCK_PERMISSION__MAX);
  2174. return permissions[qapi_perm];
  2175. }
  2176. static void bdrv_replace_child_noperm(BdrvChild *child,
  2177. BlockDriverState *new_bs)
  2178. {
  2179. BlockDriverState *old_bs = child->bs;
  2180. int new_bs_quiesce_counter;
  2181. int drain_saldo;
  2182. assert(!child->frozen);
  2183. if (old_bs && new_bs) {
  2184. assert(bdrv_get_aio_context(old_bs) == bdrv_get_aio_context(new_bs));
  2185. }
  2186. new_bs_quiesce_counter = (new_bs ? new_bs->quiesce_counter : 0);
  2187. drain_saldo = new_bs_quiesce_counter - child->parent_quiesce_counter;
  2188. /*
  2189. * If the new child node is drained but the old one was not, flush
  2190. * all outstanding requests to the old child node.
  2191. */
  2192. while (drain_saldo > 0 && child->klass->drained_begin) {
  2193. bdrv_parent_drained_begin_single(child, true);
  2194. drain_saldo--;
  2195. }
  2196. if (old_bs) {
  2197. /* Detach first so that the recursive drain sections coming from @child
  2198. * are already gone and we only end the drain sections that came from
  2199. * elsewhere. */
  2200. if (child->klass->detach) {
  2201. child->klass->detach(child);
  2202. }
  2203. QLIST_REMOVE(child, next_parent);
  2204. }
  2205. child->bs = new_bs;
  2206. if (new_bs) {
  2207. QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
  2208. /*
  2209. * Detaching the old node may have led to the new node's
  2210. * quiesce_counter having been decreased. Not a problem, we
  2211. * just need to recognize this here and then invoke
  2212. * drained_end appropriately more often.
  2213. */
  2214. assert(new_bs->quiesce_counter <= new_bs_quiesce_counter);
  2215. drain_saldo += new_bs->quiesce_counter - new_bs_quiesce_counter;
  2216. /* Attach only after starting new drained sections, so that recursive
  2217. * drain sections coming from @child don't get an extra .drained_begin
  2218. * callback. */
  2219. if (child->klass->attach) {
  2220. child->klass->attach(child);
  2221. }
  2222. }
  2223. /*
  2224. * If the old child node was drained but the new one is not, allow
  2225. * requests to come in only after the new node has been attached.
  2226. */
  2227. while (drain_saldo < 0 && child->klass->drained_end) {
  2228. bdrv_parent_drained_end_single(child);
  2229. drain_saldo++;
  2230. }
  2231. }
  2232. /*
  2233. * Updates @child to change its reference to point to @new_bs, including
  2234. * checking and applying the necessary permission updates both to the old node
  2235. * and to @new_bs.
  2236. *
  2237. * NULL is passed as @new_bs for removing the reference before freeing @child.
  2238. *
  2239. * If @new_bs is not NULL, bdrv_check_perm() must be called beforehand, as this
  2240. * function uses bdrv_set_perm() to update the permissions according to the new
  2241. * reference that @new_bs gets.
  2242. *
  2243. * Callers must ensure that child->frozen is false.
  2244. */
  2245. static void bdrv_replace_child(BdrvChild *child, BlockDriverState *new_bs)
  2246. {
  2247. BlockDriverState *old_bs = child->bs;
  2248. uint64_t perm, shared_perm;
  2249. /* Asserts that child->frozen == false */
  2250. bdrv_replace_child_noperm(child, new_bs);
  2251. /*
  2252. * Start with the new node's permissions. If @new_bs is a (direct
  2253. * or indirect) child of @old_bs, we must complete the permission
  2254. * update on @new_bs before we loosen the restrictions on @old_bs.
  2255. * Otherwise, bdrv_check_perm() on @old_bs would re-initiate
  2256. * updating the permissions of @new_bs, and thus not purely loosen
  2257. * restrictions.
  2258. */
  2259. if (new_bs) {
  2260. bdrv_get_cumulative_perm(new_bs, &perm, &shared_perm);
  2261. bdrv_set_perm(new_bs, perm, shared_perm);
  2262. }
  2263. if (old_bs) {
  2264. /* Update permissions for old node. This is guaranteed to succeed
  2265. * because we're just taking a parent away, so we're loosening
  2266. * restrictions. */
  2267. bool tighten_restrictions;
  2268. int ret;
  2269. bdrv_get_cumulative_perm(old_bs, &perm, &shared_perm);
  2270. ret = bdrv_check_perm(old_bs, NULL, perm, shared_perm, NULL,
  2271. &tighten_restrictions, NULL);
  2272. assert(tighten_restrictions == false);
  2273. if (ret < 0) {
  2274. /* We only tried to loosen restrictions, so errors are not fatal */
  2275. bdrv_abort_perm_update(old_bs);
  2276. } else {
  2277. bdrv_set_perm(old_bs, perm, shared_perm);
  2278. }
  2279. /* When the parent requiring a non-default AioContext is removed, the
  2280. * node moves back to the main AioContext */
  2281. bdrv_try_set_aio_context(old_bs, qemu_get_aio_context(), NULL);
  2282. }
  2283. }
  2284. /*
  2285. * This function steals the reference to child_bs from the caller.
  2286. * That reference is later dropped by bdrv_root_unref_child().
  2287. *
  2288. * On failure NULL is returned, errp is set and the reference to
  2289. * child_bs is also dropped.
  2290. *
  2291. * The caller must hold the AioContext lock @child_bs, but not that of @ctx
  2292. * (unless @child_bs is already in @ctx).
  2293. */
  2294. BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
  2295. const char *child_name,
  2296. const BdrvChildClass *child_class,
  2297. BdrvChildRole child_role,
  2298. AioContext *ctx,
  2299. uint64_t perm, uint64_t shared_perm,
  2300. void *opaque, Error **errp)
  2301. {
  2302. BdrvChild *child;
  2303. Error *local_err = NULL;
  2304. int ret;
  2305. ret = bdrv_check_update_perm(child_bs, NULL, perm, shared_perm, NULL, NULL,
  2306. errp);
  2307. if (ret < 0) {
  2308. bdrv_abort_perm_update(child_bs);
  2309. bdrv_unref(child_bs);
  2310. return NULL;
  2311. }
  2312. child = g_new(BdrvChild, 1);
  2313. *child = (BdrvChild) {
  2314. .bs = NULL,
  2315. .name = g_strdup(child_name),
  2316. .klass = child_class,
  2317. .role = child_role,
  2318. .perm = perm,
  2319. .shared_perm = shared_perm,
  2320. .opaque = opaque,
  2321. };
  2322. /* If the AioContexts don't match, first try to move the subtree of
  2323. * child_bs into the AioContext of the new parent. If this doesn't work,
  2324. * try moving the parent into the AioContext of child_bs instead. */
  2325. if (bdrv_get_aio_context(child_bs) != ctx) {
  2326. ret = bdrv_try_set_aio_context(child_bs, ctx, &local_err);
  2327. if (ret < 0 && child_class->can_set_aio_ctx) {
  2328. GSList *ignore = g_slist_prepend(NULL, child);
  2329. ctx = bdrv_get_aio_context(child_bs);
  2330. if (child_class->can_set_aio_ctx(child, ctx, &ignore, NULL)) {
  2331. error_free(local_err);
  2332. ret = 0;
  2333. g_slist_free(ignore);
  2334. ignore = g_slist_prepend(NULL, child);
  2335. child_class->set_aio_ctx(child, ctx, &ignore);
  2336. }
  2337. g_slist_free(ignore);
  2338. }
  2339. if (ret < 0) {
  2340. error_propagate(errp, local_err);
  2341. g_free(child);
  2342. bdrv_abort_perm_update(child_bs);
  2343. bdrv_unref(child_bs);
  2344. return NULL;
  2345. }
  2346. }
  2347. /* This performs the matching bdrv_set_perm() for the above check. */
  2348. bdrv_replace_child(child, child_bs);
  2349. return child;
  2350. }
  2351. /*
  2352. * This function transfers the reference to child_bs from the caller
  2353. * to parent_bs. That reference is later dropped by parent_bs on
  2354. * bdrv_close() or if someone calls bdrv_unref_child().
  2355. *
  2356. * On failure NULL is returned, errp is set and the reference to
  2357. * child_bs is also dropped.
  2358. *
  2359. * If @parent_bs and @child_bs are in different AioContexts, the caller must
  2360. * hold the AioContext lock for @child_bs, but not for @parent_bs.
  2361. */
  2362. BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
  2363. BlockDriverState *child_bs,
  2364. const char *child_name,
  2365. const BdrvChildClass *child_class,
  2366. BdrvChildRole child_role,
  2367. Error **errp)
  2368. {
  2369. BdrvChild *child;
  2370. uint64_t perm, shared_perm;
  2371. bdrv_get_cumulative_perm(parent_bs, &perm, &shared_perm);
  2372. assert(parent_bs->drv);
  2373. bdrv_child_perm(parent_bs, child_bs, NULL, child_role, NULL,
  2374. perm, shared_perm, &perm, &shared_perm);
  2375. child = bdrv_root_attach_child(child_bs, child_name, child_class,
  2376. child_role, bdrv_get_aio_context(parent_bs),
  2377. perm, shared_perm, parent_bs, errp);
  2378. if (child == NULL) {
  2379. return NULL;
  2380. }
  2381. QLIST_INSERT_HEAD(&parent_bs->children, child, next);
  2382. return child;
  2383. }
  2384. static void bdrv_detach_child(BdrvChild *child)
  2385. {
  2386. QLIST_SAFE_REMOVE(child, next);
  2387. bdrv_replace_child(child, NULL);
  2388. g_free(child->name);
  2389. g_free(child);
  2390. }
  2391. /* Callers must ensure that child->frozen is false. */
  2392. void bdrv_root_unref_child(BdrvChild *child)
  2393. {
  2394. BlockDriverState *child_bs;
  2395. child_bs = child->bs;
  2396. bdrv_detach_child(child);
  2397. bdrv_unref(child_bs);
  2398. }
  2399. /**
  2400. * Clear all inherits_from pointers from children and grandchildren of
  2401. * @root that point to @root, where necessary.
  2402. */
  2403. static void bdrv_unset_inherits_from(BlockDriverState *root, BdrvChild *child)
  2404. {
  2405. BdrvChild *c;
  2406. if (child->bs->inherits_from == root) {
  2407. /*
  2408. * Remove inherits_from only when the last reference between root and
  2409. * child->bs goes away.
  2410. */
  2411. QLIST_FOREACH(c, &root->children, next) {
  2412. if (c != child && c->bs == child->bs) {
  2413. break;
  2414. }
  2415. }
  2416. if (c == NULL) {
  2417. child->bs->inherits_from = NULL;
  2418. }
  2419. }
  2420. QLIST_FOREACH(c, &child->bs->children, next) {
  2421. bdrv_unset_inherits_from(root, c);
  2422. }
  2423. }
  2424. /* Callers must ensure that child->frozen is false. */
  2425. void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
  2426. {
  2427. if (child == NULL) {
  2428. return;
  2429. }
  2430. bdrv_unset_inherits_from(parent, child);
  2431. bdrv_root_unref_child(child);
  2432. }
  2433. static void bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
  2434. {
  2435. BdrvChild *c;
  2436. QLIST_FOREACH(c, &bs->parents, next_parent) {
  2437. if (c->klass->change_media) {
  2438. c->klass->change_media(c, load);
  2439. }
  2440. }
  2441. }
  2442. /* Return true if you can reach parent going through child->inherits_from
  2443. * recursively. If parent or child are NULL, return false */
  2444. static bool bdrv_inherits_from_recursive(BlockDriverState *child,
  2445. BlockDriverState *parent)
  2446. {
  2447. while (child && child != parent) {
  2448. child = child->inherits_from;
  2449. }
  2450. return child != NULL;
  2451. }
  2452. /*
  2453. * Return the BdrvChildRole for @bs's backing child. bs->backing is
  2454. * mostly used for COW backing children (role = COW), but also for
  2455. * filtered children (role = FILTERED | PRIMARY).
  2456. */
  2457. static BdrvChildRole bdrv_backing_role(BlockDriverState *bs)
  2458. {
  2459. if (bs->drv && bs->drv->is_filter) {
  2460. return BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
  2461. } else {
  2462. return BDRV_CHILD_COW;
  2463. }
  2464. }
  2465. /*
  2466. * Sets the bs->backing link of a BDS. A new reference is created; callers
  2467. * which don't need their own reference any more must call bdrv_unref().
  2468. */
  2469. void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd,
  2470. Error **errp)
  2471. {
  2472. bool update_inherits_from = bdrv_chain_contains(bs, backing_hd) &&
  2473. bdrv_inherits_from_recursive(backing_hd, bs);
  2474. if (bdrv_is_backing_chain_frozen(bs, child_bs(bs->backing), errp)) {
  2475. return;
  2476. }
  2477. if (backing_hd) {
  2478. bdrv_ref(backing_hd);
  2479. }
  2480. if (bs->backing) {
  2481. /* Cannot be frozen, we checked that above */
  2482. bdrv_unref_child(bs, bs->backing);
  2483. bs->backing = NULL;
  2484. }
  2485. if (!backing_hd) {
  2486. goto out;
  2487. }
  2488. bs->backing = bdrv_attach_child(bs, backing_hd, "backing", &child_of_bds,
  2489. bdrv_backing_role(bs), errp);
  2490. /* If backing_hd was already part of bs's backing chain, and
  2491. * inherits_from pointed recursively to bs then let's update it to
  2492. * point directly to bs (else it will become NULL). */
  2493. if (bs->backing && update_inherits_from) {
  2494. backing_hd->inherits_from = bs;
  2495. }
  2496. out:
  2497. bdrv_refresh_limits(bs, NULL);
  2498. }
  2499. /*
  2500. * Opens the backing file for a BlockDriverState if not yet open
  2501. *
  2502. * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
  2503. * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
  2504. * itself, all options starting with "${bdref_key}." are considered part of the
  2505. * BlockdevRef.
  2506. *
  2507. * TODO Can this be unified with bdrv_open_image()?
  2508. */
  2509. int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
  2510. const char *bdref_key, Error **errp)
  2511. {
  2512. char *backing_filename = NULL;
  2513. char *bdref_key_dot;
  2514. const char *reference = NULL;
  2515. int ret = 0;
  2516. bool implicit_backing = false;
  2517. BlockDriverState *backing_hd;
  2518. QDict *options;
  2519. QDict *tmp_parent_options = NULL;
  2520. Error *local_err = NULL;
  2521. if (bs->backing != NULL) {
  2522. goto free_exit;
  2523. }
  2524. /* NULL means an empty set of options */
  2525. if (parent_options == NULL) {
  2526. tmp_parent_options = qdict_new();
  2527. parent_options = tmp_parent_options;
  2528. }
  2529. bs->open_flags &= ~BDRV_O_NO_BACKING;
  2530. bdref_key_dot = g_strdup_printf("%s.", bdref_key);
  2531. qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
  2532. g_free(bdref_key_dot);
  2533. /*
  2534. * Caution: while qdict_get_try_str() is fine, getting non-string
  2535. * types would require more care. When @parent_options come from
  2536. * -blockdev or blockdev_add, its members are typed according to
  2537. * the QAPI schema, but when they come from -drive, they're all
  2538. * QString.
  2539. */
  2540. reference = qdict_get_try_str(parent_options, bdref_key);
  2541. if (reference || qdict_haskey(options, "file.filename")) {
  2542. /* keep backing_filename NULL */
  2543. } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
  2544. qobject_unref(options);
  2545. goto free_exit;
  2546. } else {
  2547. if (qdict_size(options) == 0) {
  2548. /* If the user specifies options that do not modify the
  2549. * backing file's behavior, we might still consider it the
  2550. * implicit backing file. But it's easier this way, and
  2551. * just specifying some of the backing BDS's options is
  2552. * only possible with -drive anyway (otherwise the QAPI
  2553. * schema forces the user to specify everything). */
  2554. implicit_backing = !strcmp(bs->auto_backing_file, bs->backing_file);
  2555. }
  2556. backing_filename = bdrv_get_full_backing_filename(bs, &local_err);
  2557. if (local_err) {
  2558. ret = -EINVAL;
  2559. error_propagate(errp, local_err);
  2560. qobject_unref(options);
  2561. goto free_exit;
  2562. }
  2563. }
  2564. if (!bs->drv || !bs->drv->supports_backing) {
  2565. ret = -EINVAL;
  2566. error_setg(errp, "Driver doesn't support backing files");
  2567. qobject_unref(options);
  2568. goto free_exit;
  2569. }
  2570. if (!reference &&
  2571. bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
  2572. qdict_put_str(options, "driver", bs->backing_format);
  2573. }
  2574. backing_hd = bdrv_open_inherit(backing_filename, reference, options, 0, bs,
  2575. &child_of_bds, bdrv_backing_role(bs), errp);
  2576. if (!backing_hd) {
  2577. bs->open_flags |= BDRV_O_NO_BACKING;
  2578. error_prepend(errp, "Could not open backing file: ");
  2579. ret = -EINVAL;
  2580. goto free_exit;
  2581. }
  2582. if (implicit_backing) {
  2583. bdrv_refresh_filename(backing_hd);
  2584. pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
  2585. backing_hd->filename);
  2586. }
  2587. /* Hook up the backing file link; drop our reference, bs owns the
  2588. * backing_hd reference now */
  2589. bdrv_set_backing_hd(bs, backing_hd, &local_err);
  2590. bdrv_unref(backing_hd);
  2591. if (local_err) {
  2592. error_propagate(errp, local_err);
  2593. ret = -EINVAL;
  2594. goto free_exit;
  2595. }
  2596. qdict_del(parent_options, bdref_key);
  2597. free_exit:
  2598. g_free(backing_filename);
  2599. qobject_unref(tmp_parent_options);
  2600. return ret;
  2601. }
  2602. static BlockDriverState *
  2603. bdrv_open_child_bs(const char *filename, QDict *options, const char *bdref_key,
  2604. BlockDriverState *parent, const BdrvChildClass *child_class,
  2605. BdrvChildRole child_role, bool allow_none, Error **errp)
  2606. {
  2607. BlockDriverState *bs = NULL;
  2608. QDict *image_options;
  2609. char *bdref_key_dot;
  2610. const char *reference;
  2611. assert(child_class != NULL);
  2612. bdref_key_dot = g_strdup_printf("%s.", bdref_key);
  2613. qdict_extract_subqdict(options, &image_options, bdref_key_dot);
  2614. g_free(bdref_key_dot);
  2615. /*
  2616. * Caution: while qdict_get_try_str() is fine, getting non-string
  2617. * types would require more care. When @options come from
  2618. * -blockdev or blockdev_add, its members are typed according to
  2619. * the QAPI schema, but when they come from -drive, they're all
  2620. * QString.
  2621. */
  2622. reference = qdict_get_try_str(options, bdref_key);
  2623. if (!filename && !reference && !qdict_size(image_options)) {
  2624. if (!allow_none) {
  2625. error_setg(errp, "A block device must be specified for \"%s\"",
  2626. bdref_key);
  2627. }
  2628. qobject_unref(image_options);
  2629. goto done;
  2630. }
  2631. bs = bdrv_open_inherit(filename, reference, image_options, 0,
  2632. parent, child_class, child_role, errp);
  2633. if (!bs) {
  2634. goto done;
  2635. }
  2636. done:
  2637. qdict_del(options, bdref_key);
  2638. return bs;
  2639. }
  2640. /*
  2641. * Opens a disk image whose options are given as BlockdevRef in another block
  2642. * device's options.
  2643. *
  2644. * If allow_none is true, no image will be opened if filename is false and no
  2645. * BlockdevRef is given. NULL will be returned, but errp remains unset.
  2646. *
  2647. * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
  2648. * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
  2649. * itself, all options starting with "${bdref_key}." are considered part of the
  2650. * BlockdevRef.
  2651. *
  2652. * The BlockdevRef will be removed from the options QDict.
  2653. */
  2654. BdrvChild *bdrv_open_child(const char *filename,
  2655. QDict *options, const char *bdref_key,
  2656. BlockDriverState *parent,
  2657. const BdrvChildClass *child_class,
  2658. BdrvChildRole child_role,
  2659. bool allow_none, Error **errp)
  2660. {
  2661. BlockDriverState *bs;
  2662. bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_class,
  2663. child_role, allow_none, errp);
  2664. if (bs == NULL) {
  2665. return NULL;
  2666. }
  2667. return bdrv_attach_child(parent, bs, bdref_key, child_class, child_role,
  2668. errp);
  2669. }
  2670. /*
  2671. * TODO Future callers may need to specify parent/child_class in order for
  2672. * option inheritance to work. Existing callers use it for the root node.
  2673. */
  2674. BlockDriverState *bdrv_open_blockdev_ref(BlockdevRef *ref, Error **errp)
  2675. {
  2676. BlockDriverState *bs = NULL;
  2677. QObject *obj = NULL;
  2678. QDict *qdict = NULL;
  2679. const char *reference = NULL;
  2680. Visitor *v = NULL;
  2681. if (ref->type == QTYPE_QSTRING) {
  2682. reference = ref->u.reference;
  2683. } else {
  2684. BlockdevOptions *options = &ref->u.definition;
  2685. assert(ref->type == QTYPE_QDICT);
  2686. v = qobject_output_visitor_new(&obj);
  2687. visit_type_BlockdevOptions(v, NULL, &options, &error_abort);
  2688. visit_complete(v, &obj);
  2689. qdict = qobject_to(QDict, obj);
  2690. qdict_flatten(qdict);
  2691. /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
  2692. * compatibility with other callers) rather than what we want as the
  2693. * real defaults. Apply the defaults here instead. */
  2694. qdict_set_default_str(qdict, BDRV_OPT_CACHE_DIRECT, "off");
  2695. qdict_set_default_str(qdict, BDRV_OPT_CACHE_NO_FLUSH, "off");
  2696. qdict_set_default_str(qdict, BDRV_OPT_READ_ONLY, "off");
  2697. qdict_set_default_str(qdict, BDRV_OPT_AUTO_READ_ONLY, "off");
  2698. }
  2699. bs = bdrv_open_inherit(NULL, reference, qdict, 0, NULL, NULL, 0, errp);
  2700. obj = NULL;
  2701. qobject_unref(obj);
  2702. visit_free(v);
  2703. return bs;
  2704. }
  2705. static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
  2706. int flags,
  2707. QDict *snapshot_options,
  2708. Error **errp)
  2709. {
  2710. /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
  2711. char *tmp_filename = g_malloc0(PATH_MAX + 1);
  2712. int64_t total_size;
  2713. QemuOpts *opts = NULL;
  2714. BlockDriverState *bs_snapshot = NULL;
  2715. Error *local_err = NULL;
  2716. int ret;
  2717. /* if snapshot, we create a temporary backing file and open it
  2718. instead of opening 'filename' directly */
  2719. /* Get the required size from the image */
  2720. total_size = bdrv_getlength(bs);
  2721. if (total_size < 0) {
  2722. error_setg_errno(errp, -total_size, "Could not get image size");
  2723. goto out;
  2724. }
  2725. /* Create the temporary image */
  2726. ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
  2727. if (ret < 0) {
  2728. error_setg_errno(errp, -ret, "Could not get temporary filename");
  2729. goto out;
  2730. }
  2731. opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
  2732. &error_abort);
  2733. qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
  2734. ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
  2735. qemu_opts_del(opts);
  2736. if (ret < 0) {
  2737. error_prepend(errp, "Could not create temporary overlay '%s': ",
  2738. tmp_filename);
  2739. goto out;
  2740. }
  2741. /* Prepare options QDict for the temporary file */
  2742. qdict_put_str(snapshot_options, "file.driver", "file");
  2743. qdict_put_str(snapshot_options, "file.filename", tmp_filename);
  2744. qdict_put_str(snapshot_options, "driver", "qcow2");
  2745. bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
  2746. snapshot_options = NULL;
  2747. if (!bs_snapshot) {
  2748. goto out;
  2749. }
  2750. /* bdrv_append() consumes a strong reference to bs_snapshot
  2751. * (i.e. it will call bdrv_unref() on it) even on error, so in
  2752. * order to be able to return one, we have to increase
  2753. * bs_snapshot's refcount here */
  2754. bdrv_ref(bs_snapshot);
  2755. bdrv_append(bs_snapshot, bs, &local_err);
  2756. if (local_err) {
  2757. error_propagate(errp, local_err);
  2758. bs_snapshot = NULL;
  2759. goto out;
  2760. }
  2761. out:
  2762. qobject_unref(snapshot_options);
  2763. g_free(tmp_filename);
  2764. return bs_snapshot;
  2765. }
  2766. /*
  2767. * Opens a disk image (raw, qcow2, vmdk, ...)
  2768. *
  2769. * options is a QDict of options to pass to the block drivers, or NULL for an
  2770. * empty set of options. The reference to the QDict belongs to the block layer
  2771. * after the call (even on failure), so if the caller intends to reuse the
  2772. * dictionary, it needs to use qobject_ref() before calling bdrv_open.
  2773. *
  2774. * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
  2775. * If it is not NULL, the referenced BDS will be reused.
  2776. *
  2777. * The reference parameter may be used to specify an existing block device which
  2778. * should be opened. If specified, neither options nor a filename may be given,
  2779. * nor can an existing BDS be reused (that is, *pbs has to be NULL).
  2780. */
  2781. static BlockDriverState *bdrv_open_inherit(const char *filename,
  2782. const char *reference,
  2783. QDict *options, int flags,
  2784. BlockDriverState *parent,
  2785. const BdrvChildClass *child_class,
  2786. BdrvChildRole child_role,
  2787. Error **errp)
  2788. {
  2789. int ret;
  2790. BlockBackend *file = NULL;
  2791. BlockDriverState *bs;
  2792. BlockDriver *drv = NULL;
  2793. BdrvChild *child;
  2794. const char *drvname;
  2795. const char *backing;
  2796. Error *local_err = NULL;
  2797. QDict *snapshot_options = NULL;
  2798. int snapshot_flags = 0;
  2799. assert(!child_class || !flags);
  2800. assert(!child_class == !parent);
  2801. if (reference) {
  2802. bool options_non_empty = options ? qdict_size(options) : false;
  2803. qobject_unref(options);
  2804. if (filename || options_non_empty) {
  2805. error_setg(errp, "Cannot reference an existing block device with "
  2806. "additional options or a new filename");
  2807. return NULL;
  2808. }
  2809. bs = bdrv_lookup_bs(reference, reference, errp);
  2810. if (!bs) {
  2811. return NULL;
  2812. }
  2813. bdrv_ref(bs);
  2814. return bs;
  2815. }
  2816. bs = bdrv_new();
  2817. /* NULL means an empty set of options */
  2818. if (options == NULL) {
  2819. options = qdict_new();
  2820. }
  2821. /* json: syntax counts as explicit options, as if in the QDict */
  2822. parse_json_protocol(options, &filename, &local_err);
  2823. if (local_err) {
  2824. goto fail;
  2825. }
  2826. bs->explicit_options = qdict_clone_shallow(options);
  2827. if (child_class) {
  2828. bool parent_is_format;
  2829. if (parent->drv) {
  2830. parent_is_format = parent->drv->is_format;
  2831. } else {
  2832. /*
  2833. * parent->drv is not set yet because this node is opened for
  2834. * (potential) format probing. That means that @parent is going
  2835. * to be a format node.
  2836. */
  2837. parent_is_format = true;
  2838. }
  2839. bs->inherits_from = parent;
  2840. child_class->inherit_options(child_role, parent_is_format,
  2841. &flags, options,
  2842. parent->open_flags, parent->options);
  2843. }
  2844. ret = bdrv_fill_options(&options, filename, &flags, &local_err);
  2845. if (ret < 0) {
  2846. goto fail;
  2847. }
  2848. /*
  2849. * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
  2850. * Caution: getting a boolean member of @options requires care.
  2851. * When @options come from -blockdev or blockdev_add, members are
  2852. * typed according to the QAPI schema, but when they come from
  2853. * -drive, they're all QString.
  2854. */
  2855. if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&
  2856. !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {
  2857. flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);
  2858. } else {
  2859. flags &= ~BDRV_O_RDWR;
  2860. }
  2861. if (flags & BDRV_O_SNAPSHOT) {
  2862. snapshot_options = qdict_new();
  2863. bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
  2864. flags, options);
  2865. /* Let bdrv_backing_options() override "read-only" */
  2866. qdict_del(options, BDRV_OPT_READ_ONLY);
  2867. bdrv_inherited_options(BDRV_CHILD_COW, true,
  2868. &flags, options, flags, options);
  2869. }
  2870. bs->open_flags = flags;
  2871. bs->options = options;
  2872. options = qdict_clone_shallow(options);
  2873. /* Find the right image format driver */
  2874. /* See cautionary note on accessing @options above */
  2875. drvname = qdict_get_try_str(options, "driver");
  2876. if (drvname) {
  2877. drv = bdrv_find_format(drvname);
  2878. if (!drv) {
  2879. error_setg(errp, "Unknown driver: '%s'", drvname);
  2880. goto fail;
  2881. }
  2882. }
  2883. assert(drvname || !(flags & BDRV_O_PROTOCOL));
  2884. /* See cautionary note on accessing @options above */
  2885. backing = qdict_get_try_str(options, "backing");
  2886. if (qobject_to(QNull, qdict_get(options, "backing")) != NULL ||
  2887. (backing && *backing == '\0'))
  2888. {
  2889. if (backing) {
  2890. warn_report("Use of \"backing\": \"\" is deprecated; "
  2891. "use \"backing\": null instead");
  2892. }
  2893. flags |= BDRV_O_NO_BACKING;
  2894. qdict_del(bs->explicit_options, "backing");
  2895. qdict_del(bs->options, "backing");
  2896. qdict_del(options, "backing");
  2897. }
  2898. /* Open image file without format layer. This BlockBackend is only used for
  2899. * probing, the block drivers will do their own bdrv_open_child() for the
  2900. * same BDS, which is why we put the node name back into options. */
  2901. if ((flags & BDRV_O_PROTOCOL) == 0) {
  2902. BlockDriverState *file_bs;
  2903. file_bs = bdrv_open_child_bs(filename, options, "file", bs,
  2904. &child_of_bds, BDRV_CHILD_IMAGE,
  2905. true, &local_err);
  2906. if (local_err) {
  2907. goto fail;
  2908. }
  2909. if (file_bs != NULL) {
  2910. /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
  2911. * looking at the header to guess the image format. This works even
  2912. * in cases where a guest would not see a consistent state. */
  2913. file = blk_new(bdrv_get_aio_context(file_bs), 0, BLK_PERM_ALL);
  2914. blk_insert_bs(file, file_bs, &local_err);
  2915. bdrv_unref(file_bs);
  2916. if (local_err) {
  2917. goto fail;
  2918. }
  2919. qdict_put_str(options, "file", bdrv_get_node_name(file_bs));
  2920. }
  2921. }
  2922. /* Image format probing */
  2923. bs->probed = !drv;
  2924. if (!drv && file) {
  2925. ret = find_image_format(file, filename, &drv, &local_err);
  2926. if (ret < 0) {
  2927. goto fail;
  2928. }
  2929. /*
  2930. * This option update would logically belong in bdrv_fill_options(),
  2931. * but we first need to open bs->file for the probing to work, while
  2932. * opening bs->file already requires the (mostly) final set of options
  2933. * so that cache mode etc. can be inherited.
  2934. *
  2935. * Adding the driver later is somewhat ugly, but it's not an option
  2936. * that would ever be inherited, so it's correct. We just need to make
  2937. * sure to update both bs->options (which has the full effective
  2938. * options for bs) and options (which has file.* already removed).
  2939. */
  2940. qdict_put_str(bs->options, "driver", drv->format_name);
  2941. qdict_put_str(options, "driver", drv->format_name);
  2942. } else if (!drv) {
  2943. error_setg(errp, "Must specify either driver or file");
  2944. goto fail;
  2945. }
  2946. /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
  2947. assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
  2948. /* file must be NULL if a protocol BDS is about to be created
  2949. * (the inverse results in an error message from bdrv_open_common()) */
  2950. assert(!(flags & BDRV_O_PROTOCOL) || !file);
  2951. /* Open the image */
  2952. ret = bdrv_open_common(bs, file, options, &local_err);
  2953. if (ret < 0) {
  2954. goto fail;
  2955. }
  2956. if (file) {
  2957. blk_unref(file);
  2958. file = NULL;
  2959. }
  2960. /* If there is a backing file, use it */
  2961. if ((flags & BDRV_O_NO_BACKING) == 0) {
  2962. ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
  2963. if (ret < 0) {
  2964. goto close_and_fail;
  2965. }
  2966. }
  2967. /* Remove all children options and references
  2968. * from bs->options and bs->explicit_options */
  2969. QLIST_FOREACH(child, &bs->children, next) {
  2970. char *child_key_dot;
  2971. child_key_dot = g_strdup_printf("%s.", child->name);
  2972. qdict_extract_subqdict(bs->explicit_options, NULL, child_key_dot);
  2973. qdict_extract_subqdict(bs->options, NULL, child_key_dot);
  2974. qdict_del(bs->explicit_options, child->name);
  2975. qdict_del(bs->options, child->name);
  2976. g_free(child_key_dot);
  2977. }
  2978. /* Check if any unknown options were used */
  2979. if (qdict_size(options) != 0) {
  2980. const QDictEntry *entry = qdict_first(options);
  2981. if (flags & BDRV_O_PROTOCOL) {
  2982. error_setg(errp, "Block protocol '%s' doesn't support the option "
  2983. "'%s'", drv->format_name, entry->key);
  2984. } else {
  2985. error_setg(errp,
  2986. "Block format '%s' does not support the option '%s'",
  2987. drv->format_name, entry->key);
  2988. }
  2989. goto close_and_fail;
  2990. }
  2991. bdrv_parent_cb_change_media(bs, true);
  2992. qobject_unref(options);
  2993. options = NULL;
  2994. /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
  2995. * temporary snapshot afterwards. */
  2996. if (snapshot_flags) {
  2997. BlockDriverState *snapshot_bs;
  2998. snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
  2999. snapshot_options, &local_err);
  3000. snapshot_options = NULL;
  3001. if (local_err) {
  3002. goto close_and_fail;
  3003. }
  3004. /* We are not going to return bs but the overlay on top of it
  3005. * (snapshot_bs); thus, we have to drop the strong reference to bs
  3006. * (which we obtained by calling bdrv_new()). bs will not be deleted,
  3007. * though, because the overlay still has a reference to it. */
  3008. bdrv_unref(bs);
  3009. bs = snapshot_bs;
  3010. }
  3011. return bs;
  3012. fail:
  3013. blk_unref(file);
  3014. qobject_unref(snapshot_options);
  3015. qobject_unref(bs->explicit_options);
  3016. qobject_unref(bs->options);
  3017. qobject_unref(options);
  3018. bs->options = NULL;
  3019. bs->explicit_options = NULL;
  3020. bdrv_unref(bs);
  3021. error_propagate(errp, local_err);
  3022. return NULL;
  3023. close_and_fail:
  3024. bdrv_unref(bs);
  3025. qobject_unref(snapshot_options);
  3026. qobject_unref(options);
  3027. error_propagate(errp, local_err);
  3028. return NULL;
  3029. }
  3030. BlockDriverState *bdrv_open(const char *filename, const char *reference,
  3031. QDict *options, int flags, Error **errp)
  3032. {
  3033. return bdrv_open_inherit(filename, reference, options, flags, NULL,
  3034. NULL, 0, errp);
  3035. }
  3036. /* Return true if the NULL-terminated @list contains @str */
  3037. static bool is_str_in_list(const char *str, const char *const *list)
  3038. {
  3039. if (str && list) {
  3040. int i;
  3041. for (i = 0; list[i] != NULL; i++) {
  3042. if (!strcmp(str, list[i])) {
  3043. return true;
  3044. }
  3045. }
  3046. }
  3047. return false;
  3048. }
  3049. /*
  3050. * Check that every option set in @bs->options is also set in
  3051. * @new_opts.
  3052. *
  3053. * Options listed in the common_options list and in
  3054. * @bs->drv->mutable_opts are skipped.
  3055. *
  3056. * Return 0 on success, otherwise return -EINVAL and set @errp.
  3057. */
  3058. static int bdrv_reset_options_allowed(BlockDriverState *bs,
  3059. const QDict *new_opts, Error **errp)
  3060. {
  3061. const QDictEntry *e;
  3062. /* These options are common to all block drivers and are handled
  3063. * in bdrv_reopen_prepare() so they can be left out of @new_opts */
  3064. const char *const common_options[] = {
  3065. "node-name", "discard", "cache.direct", "cache.no-flush",
  3066. "read-only", "auto-read-only", "detect-zeroes", NULL
  3067. };
  3068. for (e = qdict_first(bs->options); e; e = qdict_next(bs->options, e)) {
  3069. if (!qdict_haskey(new_opts, e->key) &&
  3070. !is_str_in_list(e->key, common_options) &&
  3071. !is_str_in_list(e->key, bs->drv->mutable_opts)) {
  3072. error_setg(errp, "Option '%s' cannot be reset "
  3073. "to its default value", e->key);
  3074. return -EINVAL;
  3075. }
  3076. }
  3077. return 0;
  3078. }
  3079. /*
  3080. * Returns true if @child can be reached recursively from @bs
  3081. */
  3082. static bool bdrv_recurse_has_child(BlockDriverState *bs,
  3083. BlockDriverState *child)
  3084. {
  3085. BdrvChild *c;
  3086. if (bs == child) {
  3087. return true;
  3088. }
  3089. QLIST_FOREACH(c, &bs->children, next) {
  3090. if (bdrv_recurse_has_child(c->bs, child)) {
  3091. return true;
  3092. }
  3093. }
  3094. return false;
  3095. }
  3096. /*
  3097. * Adds a BlockDriverState to a simple queue for an atomic, transactional
  3098. * reopen of multiple devices.
  3099. *
  3100. * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
  3101. * already performed, or alternatively may be NULL a new BlockReopenQueue will
  3102. * be created and initialized. This newly created BlockReopenQueue should be
  3103. * passed back in for subsequent calls that are intended to be of the same
  3104. * atomic 'set'.
  3105. *
  3106. * bs is the BlockDriverState to add to the reopen queue.
  3107. *
  3108. * options contains the changed options for the associated bs
  3109. * (the BlockReopenQueue takes ownership)
  3110. *
  3111. * flags contains the open flags for the associated bs
  3112. *
  3113. * returns a pointer to bs_queue, which is either the newly allocated
  3114. * bs_queue, or the existing bs_queue being used.
  3115. *
  3116. * bs must be drained between bdrv_reopen_queue() and bdrv_reopen_multiple().
  3117. */
  3118. static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
  3119. BlockDriverState *bs,
  3120. QDict *options,
  3121. const BdrvChildClass *klass,
  3122. BdrvChildRole role,
  3123. bool parent_is_format,
  3124. QDict *parent_options,
  3125. int parent_flags,
  3126. bool keep_old_opts)
  3127. {
  3128. assert(bs != NULL);
  3129. BlockReopenQueueEntry *bs_entry;
  3130. BdrvChild *child;
  3131. QDict *old_options, *explicit_options, *options_copy;
  3132. int flags;
  3133. QemuOpts *opts;
  3134. /* Make sure that the caller remembered to use a drained section. This is
  3135. * important to avoid graph changes between the recursive queuing here and
  3136. * bdrv_reopen_multiple(). */
  3137. assert(bs->quiesce_counter > 0);
  3138. if (bs_queue == NULL) {
  3139. bs_queue = g_new0(BlockReopenQueue, 1);
  3140. QTAILQ_INIT(bs_queue);
  3141. }
  3142. if (!options) {
  3143. options = qdict_new();
  3144. }
  3145. /* Check if this BlockDriverState is already in the queue */
  3146. QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
  3147. if (bs == bs_entry->state.bs) {
  3148. break;
  3149. }
  3150. }
  3151. /*
  3152. * Precedence of options:
  3153. * 1. Explicitly passed in options (highest)
  3154. * 2. Retained from explicitly set options of bs
  3155. * 3. Inherited from parent node
  3156. * 4. Retained from effective options of bs
  3157. */
  3158. /* Old explicitly set values (don't overwrite by inherited value) */
  3159. if (bs_entry || keep_old_opts) {
  3160. old_options = qdict_clone_shallow(bs_entry ?
  3161. bs_entry->state.explicit_options :
  3162. bs->explicit_options);
  3163. bdrv_join_options(bs, options, old_options);
  3164. qobject_unref(old_options);
  3165. }
  3166. explicit_options = qdict_clone_shallow(options);
  3167. /* Inherit from parent node */
  3168. if (parent_options) {
  3169. flags = 0;
  3170. klass->inherit_options(role, parent_is_format, &flags, options,
  3171. parent_flags, parent_options);
  3172. } else {
  3173. flags = bdrv_get_flags(bs);
  3174. }
  3175. if (keep_old_opts) {
  3176. /* Old values are used for options that aren't set yet */
  3177. old_options = qdict_clone_shallow(bs->options);
  3178. bdrv_join_options(bs, options, old_options);
  3179. qobject_unref(old_options);
  3180. }
  3181. /* We have the final set of options so let's update the flags */
  3182. options_copy = qdict_clone_shallow(options);
  3183. opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
  3184. qemu_opts_absorb_qdict(opts, options_copy, NULL);
  3185. update_flags_from_options(&flags, opts);
  3186. qemu_opts_del(opts);
  3187. qobject_unref(options_copy);
  3188. /* bdrv_open_inherit() sets and clears some additional flags internally */
  3189. flags &= ~BDRV_O_PROTOCOL;
  3190. if (flags & BDRV_O_RDWR) {
  3191. flags |= BDRV_O_ALLOW_RDWR;
  3192. }
  3193. if (!bs_entry) {
  3194. bs_entry = g_new0(BlockReopenQueueEntry, 1);
  3195. QTAILQ_INSERT_TAIL(bs_queue, bs_entry, entry);
  3196. } else {
  3197. qobject_unref(bs_entry->state.options);
  3198. qobject_unref(bs_entry->state.explicit_options);
  3199. }
  3200. bs_entry->state.bs = bs;
  3201. bs_entry->state.options = options;
  3202. bs_entry->state.explicit_options = explicit_options;
  3203. bs_entry->state.flags = flags;
  3204. /* This needs to be overwritten in bdrv_reopen_prepare() */
  3205. bs_entry->state.perm = UINT64_MAX;
  3206. bs_entry->state.shared_perm = 0;
  3207. /*
  3208. * If keep_old_opts is false then it means that unspecified
  3209. * options must be reset to their original value. We don't allow
  3210. * resetting 'backing' but we need to know if the option is
  3211. * missing in order to decide if we have to return an error.
  3212. */
  3213. if (!keep_old_opts) {
  3214. bs_entry->state.backing_missing =
  3215. !qdict_haskey(options, "backing") &&
  3216. !qdict_haskey(options, "backing.driver");
  3217. }
  3218. QLIST_FOREACH(child, &bs->children, next) {
  3219. QDict *new_child_options = NULL;
  3220. bool child_keep_old = keep_old_opts;
  3221. /* reopen can only change the options of block devices that were
  3222. * implicitly created and inherited options. For other (referenced)
  3223. * block devices, a syntax like "backing.foo" results in an error. */
  3224. if (child->bs->inherits_from != bs) {
  3225. continue;
  3226. }
  3227. /* Check if the options contain a child reference */
  3228. if (qdict_haskey(options, child->name)) {
  3229. const char *childref = qdict_get_try_str(options, child->name);
  3230. /*
  3231. * The current child must not be reopened if the child
  3232. * reference is null or points to a different node.
  3233. */
  3234. if (g_strcmp0(childref, child->bs->node_name)) {
  3235. continue;
  3236. }
  3237. /*
  3238. * If the child reference points to the current child then
  3239. * reopen it with its existing set of options (note that
  3240. * it can still inherit new options from the parent).
  3241. */
  3242. child_keep_old = true;
  3243. } else {
  3244. /* Extract child options ("child-name.*") */
  3245. char *child_key_dot = g_strdup_printf("%s.", child->name);
  3246. qdict_extract_subqdict(explicit_options, NULL, child_key_dot);
  3247. qdict_extract_subqdict(options, &new_child_options, child_key_dot);
  3248. g_free(child_key_dot);
  3249. }
  3250. bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options,
  3251. child->klass, child->role, bs->drv->is_format,
  3252. options, flags, child_keep_old);
  3253. }
  3254. return bs_queue;
  3255. }
  3256. BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
  3257. BlockDriverState *bs,
  3258. QDict *options, bool keep_old_opts)
  3259. {
  3260. return bdrv_reopen_queue_child(bs_queue, bs, options, NULL, 0, false,
  3261. NULL, 0, keep_old_opts);
  3262. }
  3263. /*
  3264. * Reopen multiple BlockDriverStates atomically & transactionally.
  3265. *
  3266. * The queue passed in (bs_queue) must have been built up previous
  3267. * via bdrv_reopen_queue().
  3268. *
  3269. * Reopens all BDS specified in the queue, with the appropriate
  3270. * flags. All devices are prepared for reopen, and failure of any
  3271. * device will cause all device changes to be abandoned, and intermediate
  3272. * data cleaned up.
  3273. *
  3274. * If all devices prepare successfully, then the changes are committed
  3275. * to all devices.
  3276. *
  3277. * All affected nodes must be drained between bdrv_reopen_queue() and
  3278. * bdrv_reopen_multiple().
  3279. */
  3280. int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
  3281. {
  3282. int ret = -1;
  3283. BlockReopenQueueEntry *bs_entry, *next;
  3284. assert(bs_queue != NULL);
  3285. QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
  3286. assert(bs_entry->state.bs->quiesce_counter > 0);
  3287. if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, errp)) {
  3288. goto cleanup;
  3289. }
  3290. bs_entry->prepared = true;
  3291. }
  3292. QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
  3293. BDRVReopenState *state = &bs_entry->state;
  3294. ret = bdrv_check_perm(state->bs, bs_queue, state->perm,
  3295. state->shared_perm, NULL, NULL, errp);
  3296. if (ret < 0) {
  3297. goto cleanup_perm;
  3298. }
  3299. /* Check if new_backing_bs would accept the new permissions */
  3300. if (state->replace_backing_bs && state->new_backing_bs) {
  3301. uint64_t nperm, nshared;
  3302. bdrv_child_perm(state->bs, state->new_backing_bs,
  3303. NULL, bdrv_backing_role(state->bs),
  3304. bs_queue, state->perm, state->shared_perm,
  3305. &nperm, &nshared);
  3306. ret = bdrv_check_update_perm(state->new_backing_bs, NULL,
  3307. nperm, nshared, NULL, NULL, errp);
  3308. if (ret < 0) {
  3309. goto cleanup_perm;
  3310. }
  3311. }
  3312. bs_entry->perms_checked = true;
  3313. }
  3314. /*
  3315. * If we reach this point, we have success and just need to apply the
  3316. * changes.
  3317. *
  3318. * Reverse order is used to comfort qcow2 driver: on commit it need to write
  3319. * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
  3320. * children are usually goes after parents in reopen-queue, so go from last
  3321. * to first element.
  3322. */
  3323. QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
  3324. bdrv_reopen_commit(&bs_entry->state);
  3325. }
  3326. ret = 0;
  3327. cleanup_perm:
  3328. QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
  3329. BDRVReopenState *state = &bs_entry->state;
  3330. if (!bs_entry->perms_checked) {
  3331. continue;
  3332. }
  3333. if (ret == 0) {
  3334. bdrv_set_perm(state->bs, state->perm, state->shared_perm);
  3335. } else {
  3336. bdrv_abort_perm_update(state->bs);
  3337. if (state->replace_backing_bs && state->new_backing_bs) {
  3338. bdrv_abort_perm_update(state->new_backing_bs);
  3339. }
  3340. }
  3341. }
  3342. if (ret == 0) {
  3343. QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
  3344. BlockDriverState *bs = bs_entry->state.bs;
  3345. if (bs->drv->bdrv_reopen_commit_post)
  3346. bs->drv->bdrv_reopen_commit_post(&bs_entry->state);
  3347. }
  3348. }
  3349. cleanup:
  3350. QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
  3351. if (ret) {
  3352. if (bs_entry->prepared) {
  3353. bdrv_reopen_abort(&bs_entry->state);
  3354. }
  3355. qobject_unref(bs_entry->state.explicit_options);
  3356. qobject_unref(bs_entry->state.options);
  3357. }
  3358. if (bs_entry->state.new_backing_bs) {
  3359. bdrv_unref(bs_entry->state.new_backing_bs);
  3360. }
  3361. g_free(bs_entry);
  3362. }
  3363. g_free(bs_queue);
  3364. return ret;
  3365. }
  3366. int bdrv_reopen_set_read_only(BlockDriverState *bs, bool read_only,
  3367. Error **errp)
  3368. {
  3369. int ret;
  3370. BlockReopenQueue *queue;
  3371. QDict *opts = qdict_new();
  3372. qdict_put_bool(opts, BDRV_OPT_READ_ONLY, read_only);
  3373. bdrv_subtree_drained_begin(bs);
  3374. queue = bdrv_reopen_queue(NULL, bs, opts, true);
  3375. ret = bdrv_reopen_multiple(queue, errp);
  3376. bdrv_subtree_drained_end(bs);
  3377. return ret;
  3378. }
  3379. static BlockReopenQueueEntry *find_parent_in_reopen_queue(BlockReopenQueue *q,
  3380. BdrvChild *c)
  3381. {
  3382. BlockReopenQueueEntry *entry;
  3383. QTAILQ_FOREACH(entry, q, entry) {
  3384. BlockDriverState *bs = entry->state.bs;
  3385. BdrvChild *child;
  3386. QLIST_FOREACH(child, &bs->children, next) {
  3387. if (child == c) {
  3388. return entry;
  3389. }
  3390. }
  3391. }
  3392. return NULL;
  3393. }
  3394. static void bdrv_reopen_perm(BlockReopenQueue *q, BlockDriverState *bs,
  3395. uint64_t *perm, uint64_t *shared)
  3396. {
  3397. BdrvChild *c;
  3398. BlockReopenQueueEntry *parent;
  3399. uint64_t cumulative_perms = 0;
  3400. uint64_t cumulative_shared_perms = BLK_PERM_ALL;
  3401. QLIST_FOREACH(c, &bs->parents, next_parent) {
  3402. parent = find_parent_in_reopen_queue(q, c);
  3403. if (!parent) {
  3404. cumulative_perms |= c->perm;
  3405. cumulative_shared_perms &= c->shared_perm;
  3406. } else {
  3407. uint64_t nperm, nshared;
  3408. bdrv_child_perm(parent->state.bs, bs, c, c->role, q,
  3409. parent->state.perm, parent->state.shared_perm,
  3410. &nperm, &nshared);
  3411. cumulative_perms |= nperm;
  3412. cumulative_shared_perms &= nshared;
  3413. }
  3414. }
  3415. *perm = cumulative_perms;
  3416. *shared = cumulative_shared_perms;
  3417. }
  3418. static bool bdrv_reopen_can_attach(BlockDriverState *parent,
  3419. BdrvChild *child,
  3420. BlockDriverState *new_child,
  3421. Error **errp)
  3422. {
  3423. AioContext *parent_ctx = bdrv_get_aio_context(parent);
  3424. AioContext *child_ctx = bdrv_get_aio_context(new_child);
  3425. GSList *ignore;
  3426. bool ret;
  3427. ignore = g_slist_prepend(NULL, child);
  3428. ret = bdrv_can_set_aio_context(new_child, parent_ctx, &ignore, NULL);
  3429. g_slist_free(ignore);
  3430. if (ret) {
  3431. return ret;
  3432. }
  3433. ignore = g_slist_prepend(NULL, child);
  3434. ret = bdrv_can_set_aio_context(parent, child_ctx, &ignore, errp);
  3435. g_slist_free(ignore);
  3436. return ret;
  3437. }
  3438. /*
  3439. * Take a BDRVReopenState and check if the value of 'backing' in the
  3440. * reopen_state->options QDict is valid or not.
  3441. *
  3442. * If 'backing' is missing from the QDict then return 0.
  3443. *
  3444. * If 'backing' contains the node name of the backing file of
  3445. * reopen_state->bs then return 0.
  3446. *
  3447. * If 'backing' contains a different node name (or is null) then check
  3448. * whether the current backing file can be replaced with the new one.
  3449. * If that's the case then reopen_state->replace_backing_bs is set to
  3450. * true and reopen_state->new_backing_bs contains a pointer to the new
  3451. * backing BlockDriverState (or NULL).
  3452. *
  3453. * Return 0 on success, otherwise return < 0 and set @errp.
  3454. */
  3455. static int bdrv_reopen_parse_backing(BDRVReopenState *reopen_state,
  3456. Error **errp)
  3457. {
  3458. BlockDriverState *bs = reopen_state->bs;
  3459. BlockDriverState *overlay_bs, *below_bs, *new_backing_bs;
  3460. QObject *value;
  3461. const char *str;
  3462. value = qdict_get(reopen_state->options, "backing");
  3463. if (value == NULL) {
  3464. return 0;
  3465. }
  3466. switch (qobject_type(value)) {
  3467. case QTYPE_QNULL:
  3468. new_backing_bs = NULL;
  3469. break;
  3470. case QTYPE_QSTRING:
  3471. str = qobject_get_try_str(value);
  3472. new_backing_bs = bdrv_lookup_bs(NULL, str, errp);
  3473. if (new_backing_bs == NULL) {
  3474. return -EINVAL;
  3475. } else if (bdrv_recurse_has_child(new_backing_bs, bs)) {
  3476. error_setg(errp, "Making '%s' a backing file of '%s' "
  3477. "would create a cycle", str, bs->node_name);
  3478. return -EINVAL;
  3479. }
  3480. break;
  3481. default:
  3482. /* 'backing' does not allow any other data type */
  3483. g_assert_not_reached();
  3484. }
  3485. /*
  3486. * Check AioContext compatibility so that the bdrv_set_backing_hd() call in
  3487. * bdrv_reopen_commit() won't fail.
  3488. */
  3489. if (new_backing_bs) {
  3490. if (!bdrv_reopen_can_attach(bs, bs->backing, new_backing_bs, errp)) {
  3491. return -EINVAL;
  3492. }
  3493. }
  3494. /*
  3495. * Ensure that @bs can really handle backing files, because we are
  3496. * about to give it one (or swap the existing one)
  3497. */
  3498. if (bs->drv->is_filter) {
  3499. /* Filters always have a file or a backing child */
  3500. if (!bs->backing) {
  3501. error_setg(errp, "'%s' is a %s filter node that does not support a "
  3502. "backing child", bs->node_name, bs->drv->format_name);
  3503. return -EINVAL;
  3504. }
  3505. } else if (!bs->drv->supports_backing) {
  3506. error_setg(errp, "Driver '%s' of node '%s' does not support backing "
  3507. "files", bs->drv->format_name, bs->node_name);
  3508. return -EINVAL;
  3509. }
  3510. /*
  3511. * Find the "actual" backing file by skipping all links that point
  3512. * to an implicit node, if any (e.g. a commit filter node).
  3513. * We cannot use any of the bdrv_skip_*() functions here because
  3514. * those return the first explicit node, while we are looking for
  3515. * its overlay here.
  3516. */
  3517. overlay_bs = bs;
  3518. for (below_bs = bdrv_filter_or_cow_bs(overlay_bs);
  3519. below_bs && below_bs->implicit;
  3520. below_bs = bdrv_filter_or_cow_bs(overlay_bs))
  3521. {
  3522. overlay_bs = below_bs;
  3523. }
  3524. /* If we want to replace the backing file we need some extra checks */
  3525. if (new_backing_bs != bdrv_filter_or_cow_bs(overlay_bs)) {
  3526. /* Check for implicit nodes between bs and its backing file */
  3527. if (bs != overlay_bs) {
  3528. error_setg(errp, "Cannot change backing link if '%s' has "
  3529. "an implicit backing file", bs->node_name);
  3530. return -EPERM;
  3531. }
  3532. /*
  3533. * Check if the backing link that we want to replace is frozen.
  3534. * Note that
  3535. * bdrv_filter_or_cow_child(overlay_bs) == overlay_bs->backing,
  3536. * because we know that overlay_bs == bs, and that @bs
  3537. * either is a filter that uses ->backing or a COW format BDS
  3538. * with bs->drv->supports_backing == true.
  3539. */
  3540. if (bdrv_is_backing_chain_frozen(overlay_bs,
  3541. child_bs(overlay_bs->backing), errp))
  3542. {
  3543. return -EPERM;
  3544. }
  3545. reopen_state->replace_backing_bs = true;
  3546. if (new_backing_bs) {
  3547. bdrv_ref(new_backing_bs);
  3548. reopen_state->new_backing_bs = new_backing_bs;
  3549. }
  3550. }
  3551. return 0;
  3552. }
  3553. /*
  3554. * Prepares a BlockDriverState for reopen. All changes are staged in the
  3555. * 'opaque' field of the BDRVReopenState, which is used and allocated by
  3556. * the block driver layer .bdrv_reopen_prepare()
  3557. *
  3558. * bs is the BlockDriverState to reopen
  3559. * flags are the new open flags
  3560. * queue is the reopen queue
  3561. *
  3562. * Returns 0 on success, non-zero on error. On error errp will be set
  3563. * as well.
  3564. *
  3565. * On failure, bdrv_reopen_abort() will be called to clean up any data.
  3566. * It is the responsibility of the caller to then call the abort() or
  3567. * commit() for any other BDS that have been left in a prepare() state
  3568. *
  3569. */
  3570. int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
  3571. Error **errp)
  3572. {
  3573. int ret = -1;
  3574. int old_flags;
  3575. Error *local_err = NULL;
  3576. BlockDriver *drv;
  3577. QemuOpts *opts;
  3578. QDict *orig_reopen_opts;
  3579. char *discard = NULL;
  3580. bool read_only;
  3581. bool drv_prepared = false;
  3582. assert(reopen_state != NULL);
  3583. assert(reopen_state->bs->drv != NULL);
  3584. drv = reopen_state->bs->drv;
  3585. /* This function and each driver's bdrv_reopen_prepare() remove
  3586. * entries from reopen_state->options as they are processed, so
  3587. * we need to make a copy of the original QDict. */
  3588. orig_reopen_opts = qdict_clone_shallow(reopen_state->options);
  3589. /* Process generic block layer options */
  3590. opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
  3591. if (!qemu_opts_absorb_qdict(opts, reopen_state->options, errp)) {
  3592. ret = -EINVAL;
  3593. goto error;
  3594. }
  3595. /* This was already called in bdrv_reopen_queue_child() so the flags
  3596. * are up-to-date. This time we simply want to remove the options from
  3597. * QemuOpts in order to indicate that they have been processed. */
  3598. old_flags = reopen_state->flags;
  3599. update_flags_from_options(&reopen_state->flags, opts);
  3600. assert(old_flags == reopen_state->flags);
  3601. discard = qemu_opt_get_del(opts, BDRV_OPT_DISCARD);
  3602. if (discard != NULL) {
  3603. if (bdrv_parse_discard_flags(discard, &reopen_state->flags) != 0) {
  3604. error_setg(errp, "Invalid discard option");
  3605. ret = -EINVAL;
  3606. goto error;
  3607. }
  3608. }
  3609. reopen_state->detect_zeroes =
  3610. bdrv_parse_detect_zeroes(opts, reopen_state->flags, &local_err);
  3611. if (local_err) {
  3612. error_propagate(errp, local_err);
  3613. ret = -EINVAL;
  3614. goto error;
  3615. }
  3616. /* All other options (including node-name and driver) must be unchanged.
  3617. * Put them back into the QDict, so that they are checked at the end
  3618. * of this function. */
  3619. qemu_opts_to_qdict(opts, reopen_state->options);
  3620. /* If we are to stay read-only, do not allow permission change
  3621. * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
  3622. * not set, or if the BDS still has copy_on_read enabled */
  3623. read_only = !(reopen_state->flags & BDRV_O_RDWR);
  3624. ret = bdrv_can_set_read_only(reopen_state->bs, read_only, true, &local_err);
  3625. if (local_err) {
  3626. error_propagate(errp, local_err);
  3627. goto error;
  3628. }
  3629. /* Calculate required permissions after reopening */
  3630. bdrv_reopen_perm(queue, reopen_state->bs,
  3631. &reopen_state->perm, &reopen_state->shared_perm);
  3632. ret = bdrv_flush(reopen_state->bs);
  3633. if (ret) {
  3634. error_setg_errno(errp, -ret, "Error flushing drive");
  3635. goto error;
  3636. }
  3637. if (drv->bdrv_reopen_prepare) {
  3638. /*
  3639. * If a driver-specific option is missing, it means that we
  3640. * should reset it to its default value.
  3641. * But not all options allow that, so we need to check it first.
  3642. */
  3643. ret = bdrv_reset_options_allowed(reopen_state->bs,
  3644. reopen_state->options, errp);
  3645. if (ret) {
  3646. goto error;
  3647. }
  3648. ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
  3649. if (ret) {
  3650. if (local_err != NULL) {
  3651. error_propagate(errp, local_err);
  3652. } else {
  3653. bdrv_refresh_filename(reopen_state->bs);
  3654. error_setg(errp, "failed while preparing to reopen image '%s'",
  3655. reopen_state->bs->filename);
  3656. }
  3657. goto error;
  3658. }
  3659. } else {
  3660. /* It is currently mandatory to have a bdrv_reopen_prepare()
  3661. * handler for each supported drv. */
  3662. error_setg(errp, "Block format '%s' used by node '%s' "
  3663. "does not support reopening files", drv->format_name,
  3664. bdrv_get_device_or_node_name(reopen_state->bs));
  3665. ret = -1;
  3666. goto error;
  3667. }
  3668. drv_prepared = true;
  3669. /*
  3670. * We must provide the 'backing' option if the BDS has a backing
  3671. * file or if the image file has a backing file name as part of
  3672. * its metadata. Otherwise the 'backing' option can be omitted.
  3673. */
  3674. if (drv->supports_backing && reopen_state->backing_missing &&
  3675. (reopen_state->bs->backing || reopen_state->bs->backing_file[0])) {
  3676. error_setg(errp, "backing is missing for '%s'",
  3677. reopen_state->bs->node_name);
  3678. ret = -EINVAL;
  3679. goto error;
  3680. }
  3681. /*
  3682. * Allow changing the 'backing' option. The new value can be
  3683. * either a reference to an existing node (using its node name)
  3684. * or NULL to simply detach the current backing file.
  3685. */
  3686. ret = bdrv_reopen_parse_backing(reopen_state, errp);
  3687. if (ret < 0) {
  3688. goto error;
  3689. }
  3690. qdict_del(reopen_state->options, "backing");
  3691. /* Options that are not handled are only okay if they are unchanged
  3692. * compared to the old state. It is expected that some options are only
  3693. * used for the initial open, but not reopen (e.g. filename) */
  3694. if (qdict_size(reopen_state->options)) {
  3695. const QDictEntry *entry = qdict_first(reopen_state->options);
  3696. do {
  3697. QObject *new = entry->value;
  3698. QObject *old = qdict_get(reopen_state->bs->options, entry->key);
  3699. /* Allow child references (child_name=node_name) as long as they
  3700. * point to the current child (i.e. everything stays the same). */
  3701. if (qobject_type(new) == QTYPE_QSTRING) {
  3702. BdrvChild *child;
  3703. QLIST_FOREACH(child, &reopen_state->bs->children, next) {
  3704. if (!strcmp(child->name, entry->key)) {
  3705. break;
  3706. }
  3707. }
  3708. if (child) {
  3709. const char *str = qobject_get_try_str(new);
  3710. if (!strcmp(child->bs->node_name, str)) {
  3711. continue; /* Found child with this name, skip option */
  3712. }
  3713. }
  3714. }
  3715. /*
  3716. * TODO: When using -drive to specify blockdev options, all values
  3717. * will be strings; however, when using -blockdev, blockdev-add or
  3718. * filenames using the json:{} pseudo-protocol, they will be
  3719. * correctly typed.
  3720. * In contrast, reopening options are (currently) always strings
  3721. * (because you can only specify them through qemu-io; all other
  3722. * callers do not specify any options).
  3723. * Therefore, when using anything other than -drive to create a BDS,
  3724. * this cannot detect non-string options as unchanged, because
  3725. * qobject_is_equal() always returns false for objects of different
  3726. * type. In the future, this should be remedied by correctly typing
  3727. * all options. For now, this is not too big of an issue because
  3728. * the user can simply omit options which cannot be changed anyway,
  3729. * so they will stay unchanged.
  3730. */
  3731. if (!qobject_is_equal(new, old)) {
  3732. error_setg(errp, "Cannot change the option '%s'", entry->key);
  3733. ret = -EINVAL;
  3734. goto error;
  3735. }
  3736. } while ((entry = qdict_next(reopen_state->options, entry)));
  3737. }
  3738. ret = 0;
  3739. /* Restore the original reopen_state->options QDict */
  3740. qobject_unref(reopen_state->options);
  3741. reopen_state->options = qobject_ref(orig_reopen_opts);
  3742. error:
  3743. if (ret < 0 && drv_prepared) {
  3744. /* drv->bdrv_reopen_prepare() has succeeded, so we need to
  3745. * call drv->bdrv_reopen_abort() before signaling an error
  3746. * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
  3747. * when the respective bdrv_reopen_prepare() has failed) */
  3748. if (drv->bdrv_reopen_abort) {
  3749. drv->bdrv_reopen_abort(reopen_state);
  3750. }
  3751. }
  3752. qemu_opts_del(opts);
  3753. qobject_unref(orig_reopen_opts);
  3754. g_free(discard);
  3755. return ret;
  3756. }
  3757. /*
  3758. * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
  3759. * makes them final by swapping the staging BlockDriverState contents into
  3760. * the active BlockDriverState contents.
  3761. */
  3762. void bdrv_reopen_commit(BDRVReopenState *reopen_state)
  3763. {
  3764. BlockDriver *drv;
  3765. BlockDriverState *bs;
  3766. BdrvChild *child;
  3767. assert(reopen_state != NULL);
  3768. bs = reopen_state->bs;
  3769. drv = bs->drv;
  3770. assert(drv != NULL);
  3771. /* If there are any driver level actions to take */
  3772. if (drv->bdrv_reopen_commit) {
  3773. drv->bdrv_reopen_commit(reopen_state);
  3774. }
  3775. /* set BDS specific flags now */
  3776. qobject_unref(bs->explicit_options);
  3777. qobject_unref(bs->options);
  3778. bs->explicit_options = reopen_state->explicit_options;
  3779. bs->options = reopen_state->options;
  3780. bs->open_flags = reopen_state->flags;
  3781. bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
  3782. bs->detect_zeroes = reopen_state->detect_zeroes;
  3783. if (reopen_state->replace_backing_bs) {
  3784. qdict_del(bs->explicit_options, "backing");
  3785. qdict_del(bs->options, "backing");
  3786. }
  3787. /* Remove child references from bs->options and bs->explicit_options.
  3788. * Child options were already removed in bdrv_reopen_queue_child() */
  3789. QLIST_FOREACH(child, &bs->children, next) {
  3790. qdict_del(bs->explicit_options, child->name);
  3791. qdict_del(bs->options, child->name);
  3792. }
  3793. /*
  3794. * Change the backing file if a new one was specified. We do this
  3795. * after updating bs->options, so bdrv_refresh_filename() (called
  3796. * from bdrv_set_backing_hd()) has the new values.
  3797. */
  3798. if (reopen_state->replace_backing_bs) {
  3799. BlockDriverState *old_backing_bs = child_bs(bs->backing);
  3800. assert(!old_backing_bs || !old_backing_bs->implicit);
  3801. /* Abort the permission update on the backing bs we're detaching */
  3802. if (old_backing_bs) {
  3803. bdrv_abort_perm_update(old_backing_bs);
  3804. }
  3805. bdrv_set_backing_hd(bs, reopen_state->new_backing_bs, &error_abort);
  3806. }
  3807. bdrv_refresh_limits(bs, NULL);
  3808. }
  3809. /*
  3810. * Abort the reopen, and delete and free the staged changes in
  3811. * reopen_state
  3812. */
  3813. void bdrv_reopen_abort(BDRVReopenState *reopen_state)
  3814. {
  3815. BlockDriver *drv;
  3816. assert(reopen_state != NULL);
  3817. drv = reopen_state->bs->drv;
  3818. assert(drv != NULL);
  3819. if (drv->bdrv_reopen_abort) {
  3820. drv->bdrv_reopen_abort(reopen_state);
  3821. }
  3822. }
  3823. static void bdrv_close(BlockDriverState *bs)
  3824. {
  3825. BdrvAioNotifier *ban, *ban_next;
  3826. BdrvChild *child, *next;
  3827. assert(!bs->refcnt);
  3828. bdrv_drained_begin(bs); /* complete I/O */
  3829. bdrv_flush(bs);
  3830. bdrv_drain(bs); /* in case flush left pending I/O */
  3831. if (bs->drv) {
  3832. if (bs->drv->bdrv_close) {
  3833. /* Must unfreeze all children, so bdrv_unref_child() works */
  3834. bs->drv->bdrv_close(bs);
  3835. }
  3836. bs->drv = NULL;
  3837. }
  3838. QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
  3839. bdrv_unref_child(bs, child);
  3840. }
  3841. bs->backing = NULL;
  3842. bs->file = NULL;
  3843. g_free(bs->opaque);
  3844. bs->opaque = NULL;
  3845. qatomic_set(&bs->copy_on_read, 0);
  3846. bs->backing_file[0] = '\0';
  3847. bs->backing_format[0] = '\0';
  3848. bs->total_sectors = 0;
  3849. bs->encrypted = false;
  3850. bs->sg = false;
  3851. qobject_unref(bs->options);
  3852. qobject_unref(bs->explicit_options);
  3853. bs->options = NULL;
  3854. bs->explicit_options = NULL;
  3855. qobject_unref(bs->full_open_options);
  3856. bs->full_open_options = NULL;
  3857. bdrv_release_named_dirty_bitmaps(bs);
  3858. assert(QLIST_EMPTY(&bs->dirty_bitmaps));
  3859. QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
  3860. g_free(ban);
  3861. }
  3862. QLIST_INIT(&bs->aio_notifiers);
  3863. bdrv_drained_end(bs);
  3864. }
  3865. void bdrv_close_all(void)
  3866. {
  3867. assert(job_next(NULL) == NULL);
  3868. blk_exp_close_all();
  3869. /* Drop references from requests still in flight, such as canceled block
  3870. * jobs whose AIO context has not been polled yet */
  3871. bdrv_drain_all();
  3872. blk_remove_all_bs();
  3873. blockdev_close_all_bdrv_states();
  3874. assert(QTAILQ_EMPTY(&all_bdrv_states));
  3875. }
  3876. static bool should_update_child(BdrvChild *c, BlockDriverState *to)
  3877. {
  3878. GQueue *queue;
  3879. GHashTable *found;
  3880. bool ret;
  3881. if (c->klass->stay_at_node) {
  3882. return false;
  3883. }
  3884. /* If the child @c belongs to the BDS @to, replacing the current
  3885. * c->bs by @to would mean to create a loop.
  3886. *
  3887. * Such a case occurs when appending a BDS to a backing chain.
  3888. * For instance, imagine the following chain:
  3889. *
  3890. * guest device -> node A -> further backing chain...
  3891. *
  3892. * Now we create a new BDS B which we want to put on top of this
  3893. * chain, so we first attach A as its backing node:
  3894. *
  3895. * node B
  3896. * |
  3897. * v
  3898. * guest device -> node A -> further backing chain...
  3899. *
  3900. * Finally we want to replace A by B. When doing that, we want to
  3901. * replace all pointers to A by pointers to B -- except for the
  3902. * pointer from B because (1) that would create a loop, and (2)
  3903. * that pointer should simply stay intact:
  3904. *
  3905. * guest device -> node B
  3906. * |
  3907. * v
  3908. * node A -> further backing chain...
  3909. *
  3910. * In general, when replacing a node A (c->bs) by a node B (@to),
  3911. * if A is a child of B, that means we cannot replace A by B there
  3912. * because that would create a loop. Silently detaching A from B
  3913. * is also not really an option. So overall just leaving A in
  3914. * place there is the most sensible choice.
  3915. *
  3916. * We would also create a loop in any cases where @c is only
  3917. * indirectly referenced by @to. Prevent this by returning false
  3918. * if @c is found (by breadth-first search) anywhere in the whole
  3919. * subtree of @to.
  3920. */
  3921. ret = true;
  3922. found = g_hash_table_new(NULL, NULL);
  3923. g_hash_table_add(found, to);
  3924. queue = g_queue_new();
  3925. g_queue_push_tail(queue, to);
  3926. while (!g_queue_is_empty(queue)) {
  3927. BlockDriverState *v = g_queue_pop_head(queue);
  3928. BdrvChild *c2;
  3929. QLIST_FOREACH(c2, &v->children, next) {
  3930. if (c2 == c) {
  3931. ret = false;
  3932. break;
  3933. }
  3934. if (g_hash_table_contains(found, c2->bs)) {
  3935. continue;
  3936. }
  3937. g_queue_push_tail(queue, c2->bs);
  3938. g_hash_table_add(found, c2->bs);
  3939. }
  3940. }
  3941. g_queue_free(queue);
  3942. g_hash_table_destroy(found);
  3943. return ret;
  3944. }
  3945. void bdrv_replace_node(BlockDriverState *from, BlockDriverState *to,
  3946. Error **errp)
  3947. {
  3948. BdrvChild *c, *next;
  3949. GSList *list = NULL, *p;
  3950. uint64_t perm = 0, shared = BLK_PERM_ALL;
  3951. int ret;
  3952. /* Make sure that @from doesn't go away until we have successfully attached
  3953. * all of its parents to @to. */
  3954. bdrv_ref(from);
  3955. assert(qemu_get_current_aio_context() == qemu_get_aio_context());
  3956. assert(bdrv_get_aio_context(from) == bdrv_get_aio_context(to));
  3957. bdrv_drained_begin(from);
  3958. /* Put all parents into @list and calculate their cumulative permissions */
  3959. QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
  3960. assert(c->bs == from);
  3961. if (!should_update_child(c, to)) {
  3962. continue;
  3963. }
  3964. if (c->frozen) {
  3965. error_setg(errp, "Cannot change '%s' link to '%s'",
  3966. c->name, from->node_name);
  3967. goto out;
  3968. }
  3969. list = g_slist_prepend(list, c);
  3970. perm |= c->perm;
  3971. shared &= c->shared_perm;
  3972. }
  3973. /* Check whether the required permissions can be granted on @to, ignoring
  3974. * all BdrvChild in @list so that they can't block themselves. */
  3975. ret = bdrv_check_update_perm(to, NULL, perm, shared, list, NULL, errp);
  3976. if (ret < 0) {
  3977. bdrv_abort_perm_update(to);
  3978. goto out;
  3979. }
  3980. /* Now actually perform the change. We performed the permission check for
  3981. * all elements of @list at once, so set the permissions all at once at the
  3982. * very end. */
  3983. for (p = list; p != NULL; p = p->next) {
  3984. c = p->data;
  3985. bdrv_ref(to);
  3986. bdrv_replace_child_noperm(c, to);
  3987. bdrv_unref(from);
  3988. }
  3989. bdrv_get_cumulative_perm(to, &perm, &shared);
  3990. bdrv_set_perm(to, perm, shared);
  3991. out:
  3992. g_slist_free(list);
  3993. bdrv_drained_end(from);
  3994. bdrv_unref(from);
  3995. }
  3996. /*
  3997. * Add new bs contents at the top of an image chain while the chain is
  3998. * live, while keeping required fields on the top layer.
  3999. *
  4000. * This will modify the BlockDriverState fields, and swap contents
  4001. * between bs_new and bs_top. Both bs_new and bs_top are modified.
  4002. *
  4003. * bs_new must not be attached to a BlockBackend.
  4004. *
  4005. * This function does not create any image files.
  4006. *
  4007. * bdrv_append() takes ownership of a bs_new reference and unrefs it because
  4008. * that's what the callers commonly need. bs_new will be referenced by the old
  4009. * parents of bs_top after bdrv_append() returns. If the caller needs to keep a
  4010. * reference of its own, it must call bdrv_ref().
  4011. */
  4012. void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top,
  4013. Error **errp)
  4014. {
  4015. Error *local_err = NULL;
  4016. bdrv_set_backing_hd(bs_new, bs_top, &local_err);
  4017. if (local_err) {
  4018. error_propagate(errp, local_err);
  4019. goto out;
  4020. }
  4021. bdrv_replace_node(bs_top, bs_new, &local_err);
  4022. if (local_err) {
  4023. error_propagate(errp, local_err);
  4024. bdrv_set_backing_hd(bs_new, NULL, &error_abort);
  4025. goto out;
  4026. }
  4027. /* bs_new is now referenced by its new parents, we don't need the
  4028. * additional reference any more. */
  4029. out:
  4030. bdrv_unref(bs_new);
  4031. }
  4032. static void bdrv_delete(BlockDriverState *bs)
  4033. {
  4034. assert(bdrv_op_blocker_is_empty(bs));
  4035. assert(!bs->refcnt);
  4036. /* remove from list, if necessary */
  4037. if (bs->node_name[0] != '\0') {
  4038. QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
  4039. }
  4040. QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
  4041. bdrv_close(bs);
  4042. g_free(bs);
  4043. }
  4044. /*
  4045. * Run consistency checks on an image
  4046. *
  4047. * Returns 0 if the check could be completed (it doesn't mean that the image is
  4048. * free of errors) or -errno when an internal error occurred. The results of the
  4049. * check are stored in res.
  4050. */
  4051. int coroutine_fn bdrv_co_check(BlockDriverState *bs,
  4052. BdrvCheckResult *res, BdrvCheckMode fix)
  4053. {
  4054. if (bs->drv == NULL) {
  4055. return -ENOMEDIUM;
  4056. }
  4057. if (bs->drv->bdrv_co_check == NULL) {
  4058. return -ENOTSUP;
  4059. }
  4060. memset(res, 0, sizeof(*res));
  4061. return bs->drv->bdrv_co_check(bs, res, fix);
  4062. }
  4063. /*
  4064. * Return values:
  4065. * 0 - success
  4066. * -EINVAL - backing format specified, but no file
  4067. * -ENOSPC - can't update the backing file because no space is left in the
  4068. * image file header
  4069. * -ENOTSUP - format driver doesn't support changing the backing file
  4070. */
  4071. int bdrv_change_backing_file(BlockDriverState *bs, const char *backing_file,
  4072. const char *backing_fmt, bool warn)
  4073. {
  4074. BlockDriver *drv = bs->drv;
  4075. int ret;
  4076. if (!drv) {
  4077. return -ENOMEDIUM;
  4078. }
  4079. /* Backing file format doesn't make sense without a backing file */
  4080. if (backing_fmt && !backing_file) {
  4081. return -EINVAL;
  4082. }
  4083. if (warn && backing_file && !backing_fmt) {
  4084. warn_report("Deprecated use of backing file without explicit "
  4085. "backing format, use of this image requires "
  4086. "potentially unsafe format probing");
  4087. }
  4088. if (drv->bdrv_change_backing_file != NULL) {
  4089. ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
  4090. } else {
  4091. ret = -ENOTSUP;
  4092. }
  4093. if (ret == 0) {
  4094. pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
  4095. pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
  4096. pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
  4097. backing_file ?: "");
  4098. }
  4099. return ret;
  4100. }
  4101. /*
  4102. * Finds the first non-filter node above bs in the chain between
  4103. * active and bs. The returned node is either an immediate parent of
  4104. * bs, or there are only filter nodes between the two.
  4105. *
  4106. * Returns NULL if bs is not found in active's image chain,
  4107. * or if active == bs.
  4108. *
  4109. * Returns the bottommost base image if bs == NULL.
  4110. */
  4111. BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
  4112. BlockDriverState *bs)
  4113. {
  4114. bs = bdrv_skip_filters(bs);
  4115. active = bdrv_skip_filters(active);
  4116. while (active) {
  4117. BlockDriverState *next = bdrv_backing_chain_next(active);
  4118. if (bs == next) {
  4119. return active;
  4120. }
  4121. active = next;
  4122. }
  4123. return NULL;
  4124. }
  4125. /* Given a BDS, searches for the base layer. */
  4126. BlockDriverState *bdrv_find_base(BlockDriverState *bs)
  4127. {
  4128. return bdrv_find_overlay(bs, NULL);
  4129. }
  4130. /*
  4131. * Return true if at least one of the COW (backing) and filter links
  4132. * between @bs and @base is frozen. @errp is set if that's the case.
  4133. * @base must be reachable from @bs, or NULL.
  4134. */
  4135. bool bdrv_is_backing_chain_frozen(BlockDriverState *bs, BlockDriverState *base,
  4136. Error **errp)
  4137. {
  4138. BlockDriverState *i;
  4139. BdrvChild *child;
  4140. for (i = bs; i != base; i = child_bs(child)) {
  4141. child = bdrv_filter_or_cow_child(i);
  4142. if (child && child->frozen) {
  4143. error_setg(errp, "Cannot change '%s' link from '%s' to '%s'",
  4144. child->name, i->node_name, child->bs->node_name);
  4145. return true;
  4146. }
  4147. }
  4148. return false;
  4149. }
  4150. /*
  4151. * Freeze all COW (backing) and filter links between @bs and @base.
  4152. * If any of the links is already frozen the operation is aborted and
  4153. * none of the links are modified.
  4154. * @base must be reachable from @bs, or NULL.
  4155. * Returns 0 on success. On failure returns < 0 and sets @errp.
  4156. */
  4157. int bdrv_freeze_backing_chain(BlockDriverState *bs, BlockDriverState *base,
  4158. Error **errp)
  4159. {
  4160. BlockDriverState *i;
  4161. BdrvChild *child;
  4162. if (bdrv_is_backing_chain_frozen(bs, base, errp)) {
  4163. return -EPERM;
  4164. }
  4165. for (i = bs; i != base; i = child_bs(child)) {
  4166. child = bdrv_filter_or_cow_child(i);
  4167. if (child && child->bs->never_freeze) {
  4168. error_setg(errp, "Cannot freeze '%s' link to '%s'",
  4169. child->name, child->bs->node_name);
  4170. return -EPERM;
  4171. }
  4172. }
  4173. for (i = bs; i != base; i = child_bs(child)) {
  4174. child = bdrv_filter_or_cow_child(i);
  4175. if (child) {
  4176. child->frozen = true;
  4177. }
  4178. }
  4179. return 0;
  4180. }
  4181. /*
  4182. * Unfreeze all COW (backing) and filter links between @bs and @base.
  4183. * The caller must ensure that all links are frozen before using this
  4184. * function.
  4185. * @base must be reachable from @bs, or NULL.
  4186. */
  4187. void bdrv_unfreeze_backing_chain(BlockDriverState *bs, BlockDriverState *base)
  4188. {
  4189. BlockDriverState *i;
  4190. BdrvChild *child;
  4191. for (i = bs; i != base; i = child_bs(child)) {
  4192. child = bdrv_filter_or_cow_child(i);
  4193. if (child) {
  4194. assert(child->frozen);
  4195. child->frozen = false;
  4196. }
  4197. }
  4198. }
  4199. /*
  4200. * Drops images above 'base' up to and including 'top', and sets the image
  4201. * above 'top' to have base as its backing file.
  4202. *
  4203. * Requires that the overlay to 'top' is opened r/w, so that the backing file
  4204. * information in 'bs' can be properly updated.
  4205. *
  4206. * E.g., this will convert the following chain:
  4207. * bottom <- base <- intermediate <- top <- active
  4208. *
  4209. * to
  4210. *
  4211. * bottom <- base <- active
  4212. *
  4213. * It is allowed for bottom==base, in which case it converts:
  4214. *
  4215. * base <- intermediate <- top <- active
  4216. *
  4217. * to
  4218. *
  4219. * base <- active
  4220. *
  4221. * If backing_file_str is non-NULL, it will be used when modifying top's
  4222. * overlay image metadata.
  4223. *
  4224. * Error conditions:
  4225. * if active == top, that is considered an error
  4226. *
  4227. */
  4228. int bdrv_drop_intermediate(BlockDriverState *top, BlockDriverState *base,
  4229. const char *backing_file_str)
  4230. {
  4231. BlockDriverState *explicit_top = top;
  4232. bool update_inherits_from;
  4233. BdrvChild *c, *next;
  4234. Error *local_err = NULL;
  4235. int ret = -EIO;
  4236. bdrv_ref(top);
  4237. bdrv_subtree_drained_begin(top);
  4238. if (!top->drv || !base->drv) {
  4239. goto exit;
  4240. }
  4241. /* Make sure that base is in the backing chain of top */
  4242. if (!bdrv_chain_contains(top, base)) {
  4243. goto exit;
  4244. }
  4245. /* This function changes all links that point to top and makes
  4246. * them point to base. Check that none of them is frozen. */
  4247. QLIST_FOREACH(c, &top->parents, next_parent) {
  4248. if (c->frozen) {
  4249. goto exit;
  4250. }
  4251. }
  4252. /* If 'base' recursively inherits from 'top' then we should set
  4253. * base->inherits_from to top->inherits_from after 'top' and all
  4254. * other intermediate nodes have been dropped.
  4255. * If 'top' is an implicit node (e.g. "commit_top") we should skip
  4256. * it because no one inherits from it. We use explicit_top for that. */
  4257. explicit_top = bdrv_skip_implicit_filters(explicit_top);
  4258. update_inherits_from = bdrv_inherits_from_recursive(base, explicit_top);
  4259. /* success - we can delete the intermediate states, and link top->base */
  4260. /* TODO Check graph modification op blockers (BLK_PERM_GRAPH_MOD) once
  4261. * we've figured out how they should work. */
  4262. if (!backing_file_str) {
  4263. bdrv_refresh_filename(base);
  4264. backing_file_str = base->filename;
  4265. }
  4266. QLIST_FOREACH_SAFE(c, &top->parents, next_parent, next) {
  4267. /* Check whether we are allowed to switch c from top to base */
  4268. GSList *ignore_children = g_slist_prepend(NULL, c);
  4269. ret = bdrv_check_update_perm(base, NULL, c->perm, c->shared_perm,
  4270. ignore_children, NULL, &local_err);
  4271. g_slist_free(ignore_children);
  4272. if (ret < 0) {
  4273. error_report_err(local_err);
  4274. goto exit;
  4275. }
  4276. /* If so, update the backing file path in the image file */
  4277. if (c->klass->update_filename) {
  4278. ret = c->klass->update_filename(c, base, backing_file_str,
  4279. &local_err);
  4280. if (ret < 0) {
  4281. bdrv_abort_perm_update(base);
  4282. error_report_err(local_err);
  4283. goto exit;
  4284. }
  4285. }
  4286. /*
  4287. * Do the actual switch in the in-memory graph.
  4288. * Completes bdrv_check_update_perm() transaction internally.
  4289. * c->frozen is false, we have checked that above.
  4290. */
  4291. bdrv_ref(base);
  4292. bdrv_replace_child(c, base);
  4293. bdrv_unref(top);
  4294. }
  4295. if (update_inherits_from) {
  4296. base->inherits_from = explicit_top->inherits_from;
  4297. }
  4298. ret = 0;
  4299. exit:
  4300. bdrv_subtree_drained_end(top);
  4301. bdrv_unref(top);
  4302. return ret;
  4303. }
  4304. /**
  4305. * Implementation of BlockDriver.bdrv_get_allocated_file_size() that
  4306. * sums the size of all data-bearing children. (This excludes backing
  4307. * children.)
  4308. */
  4309. static int64_t bdrv_sum_allocated_file_size(BlockDriverState *bs)
  4310. {
  4311. BdrvChild *child;
  4312. int64_t child_size, sum = 0;
  4313. QLIST_FOREACH(child, &bs->children, next) {
  4314. if (child->role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
  4315. BDRV_CHILD_FILTERED))
  4316. {
  4317. child_size = bdrv_get_allocated_file_size(child->bs);
  4318. if (child_size < 0) {
  4319. return child_size;
  4320. }
  4321. sum += child_size;
  4322. }
  4323. }
  4324. return sum;
  4325. }
  4326. /**
  4327. * Length of a allocated file in bytes. Sparse files are counted by actual
  4328. * allocated space. Return < 0 if error or unknown.
  4329. */
  4330. int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
  4331. {
  4332. BlockDriver *drv = bs->drv;
  4333. if (!drv) {
  4334. return -ENOMEDIUM;
  4335. }
  4336. if (drv->bdrv_get_allocated_file_size) {
  4337. return drv->bdrv_get_allocated_file_size(bs);
  4338. }
  4339. if (drv->bdrv_file_open) {
  4340. /*
  4341. * Protocol drivers default to -ENOTSUP (most of their data is
  4342. * not stored in any of their children (if they even have any),
  4343. * so there is no generic way to figure it out).
  4344. */
  4345. return -ENOTSUP;
  4346. } else if (drv->is_filter) {
  4347. /* Filter drivers default to the size of their filtered child */
  4348. return bdrv_get_allocated_file_size(bdrv_filter_bs(bs));
  4349. } else {
  4350. /* Other drivers default to summing their children's sizes */
  4351. return bdrv_sum_allocated_file_size(bs);
  4352. }
  4353. }
  4354. /*
  4355. * bdrv_measure:
  4356. * @drv: Format driver
  4357. * @opts: Creation options for new image
  4358. * @in_bs: Existing image containing data for new image (may be NULL)
  4359. * @errp: Error object
  4360. * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
  4361. * or NULL on error
  4362. *
  4363. * Calculate file size required to create a new image.
  4364. *
  4365. * If @in_bs is given then space for allocated clusters and zero clusters
  4366. * from that image are included in the calculation. If @opts contains a
  4367. * backing file that is shared by @in_bs then backing clusters may be omitted
  4368. * from the calculation.
  4369. *
  4370. * If @in_bs is NULL then the calculation includes no allocated clusters
  4371. * unless a preallocation option is given in @opts.
  4372. *
  4373. * Note that @in_bs may use a different BlockDriver from @drv.
  4374. *
  4375. * If an error occurs the @errp pointer is set.
  4376. */
  4377. BlockMeasureInfo *bdrv_measure(BlockDriver *drv, QemuOpts *opts,
  4378. BlockDriverState *in_bs, Error **errp)
  4379. {
  4380. if (!drv->bdrv_measure) {
  4381. error_setg(errp, "Block driver '%s' does not support size measurement",
  4382. drv->format_name);
  4383. return NULL;
  4384. }
  4385. return drv->bdrv_measure(opts, in_bs, errp);
  4386. }
  4387. /**
  4388. * Return number of sectors on success, -errno on error.
  4389. */
  4390. int64_t bdrv_nb_sectors(BlockDriverState *bs)
  4391. {
  4392. BlockDriver *drv = bs->drv;
  4393. if (!drv)
  4394. return -ENOMEDIUM;
  4395. if (drv->has_variable_length) {
  4396. int ret = refresh_total_sectors(bs, bs->total_sectors);
  4397. if (ret < 0) {
  4398. return ret;
  4399. }
  4400. }
  4401. return bs->total_sectors;
  4402. }
  4403. /**
  4404. * Return length in bytes on success, -errno on error.
  4405. * The length is always a multiple of BDRV_SECTOR_SIZE.
  4406. */
  4407. int64_t bdrv_getlength(BlockDriverState *bs)
  4408. {
  4409. int64_t ret = bdrv_nb_sectors(bs);
  4410. ret = ret > INT64_MAX / BDRV_SECTOR_SIZE ? -EFBIG : ret;
  4411. return ret < 0 ? ret : ret * BDRV_SECTOR_SIZE;
  4412. }
  4413. /* return 0 as number of sectors if no device present or error */
  4414. void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
  4415. {
  4416. int64_t nb_sectors = bdrv_nb_sectors(bs);
  4417. *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
  4418. }
  4419. bool bdrv_is_sg(BlockDriverState *bs)
  4420. {
  4421. return bs->sg;
  4422. }
  4423. /**
  4424. * Return whether the given node supports compressed writes.
  4425. */
  4426. bool bdrv_supports_compressed_writes(BlockDriverState *bs)
  4427. {
  4428. BlockDriverState *filtered;
  4429. if (!bs->drv || !block_driver_can_compress(bs->drv)) {
  4430. return false;
  4431. }
  4432. filtered = bdrv_filter_bs(bs);
  4433. if (filtered) {
  4434. /*
  4435. * Filters can only forward compressed writes, so we have to
  4436. * check the child.
  4437. */
  4438. return bdrv_supports_compressed_writes(filtered);
  4439. }
  4440. return true;
  4441. }
  4442. const char *bdrv_get_format_name(BlockDriverState *bs)
  4443. {
  4444. return bs->drv ? bs->drv->format_name : NULL;
  4445. }
  4446. static int qsort_strcmp(const void *a, const void *b)
  4447. {
  4448. return strcmp(*(char *const *)a, *(char *const *)b);
  4449. }
  4450. void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
  4451. void *opaque, bool read_only)
  4452. {
  4453. BlockDriver *drv;
  4454. int count = 0;
  4455. int i;
  4456. const char **formats = NULL;
  4457. QLIST_FOREACH(drv, &bdrv_drivers, list) {
  4458. if (drv->format_name) {
  4459. bool found = false;
  4460. int i = count;
  4461. if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, read_only)) {
  4462. continue;
  4463. }
  4464. while (formats && i && !found) {
  4465. found = !strcmp(formats[--i], drv->format_name);
  4466. }
  4467. if (!found) {
  4468. formats = g_renew(const char *, formats, count + 1);
  4469. formats[count++] = drv->format_name;
  4470. }
  4471. }
  4472. }
  4473. for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); i++) {
  4474. const char *format_name = block_driver_modules[i].format_name;
  4475. if (format_name) {
  4476. bool found = false;
  4477. int j = count;
  4478. if (use_bdrv_whitelist &&
  4479. !bdrv_format_is_whitelisted(format_name, read_only)) {
  4480. continue;
  4481. }
  4482. while (formats && j && !found) {
  4483. found = !strcmp(formats[--j], format_name);
  4484. }
  4485. if (!found) {
  4486. formats = g_renew(const char *, formats, count + 1);
  4487. formats[count++] = format_name;
  4488. }
  4489. }
  4490. }
  4491. qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
  4492. for (i = 0; i < count; i++) {
  4493. it(opaque, formats[i]);
  4494. }
  4495. g_free(formats);
  4496. }
  4497. /* This function is to find a node in the bs graph */
  4498. BlockDriverState *bdrv_find_node(const char *node_name)
  4499. {
  4500. BlockDriverState *bs;
  4501. assert(node_name);
  4502. QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
  4503. if (!strcmp(node_name, bs->node_name)) {
  4504. return bs;
  4505. }
  4506. }
  4507. return NULL;
  4508. }
  4509. /* Put this QMP function here so it can access the static graph_bdrv_states. */
  4510. BlockDeviceInfoList *bdrv_named_nodes_list(bool flat,
  4511. Error **errp)
  4512. {
  4513. BlockDeviceInfoList *list, *entry;
  4514. BlockDriverState *bs;
  4515. list = NULL;
  4516. QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
  4517. BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, flat, errp);
  4518. if (!info) {
  4519. qapi_free_BlockDeviceInfoList(list);
  4520. return NULL;
  4521. }
  4522. entry = g_malloc0(sizeof(*entry));
  4523. entry->value = info;
  4524. entry->next = list;
  4525. list = entry;
  4526. }
  4527. return list;
  4528. }
  4529. #define QAPI_LIST_ADD(list, element) do { \
  4530. typeof(list) _tmp = g_new(typeof(*(list)), 1); \
  4531. _tmp->value = (element); \
  4532. _tmp->next = (list); \
  4533. (list) = _tmp; \
  4534. } while (0)
  4535. typedef struct XDbgBlockGraphConstructor {
  4536. XDbgBlockGraph *graph;
  4537. GHashTable *graph_nodes;
  4538. } XDbgBlockGraphConstructor;
  4539. static XDbgBlockGraphConstructor *xdbg_graph_new(void)
  4540. {
  4541. XDbgBlockGraphConstructor *gr = g_new(XDbgBlockGraphConstructor, 1);
  4542. gr->graph = g_new0(XDbgBlockGraph, 1);
  4543. gr->graph_nodes = g_hash_table_new(NULL, NULL);
  4544. return gr;
  4545. }
  4546. static XDbgBlockGraph *xdbg_graph_finalize(XDbgBlockGraphConstructor *gr)
  4547. {
  4548. XDbgBlockGraph *graph = gr->graph;
  4549. g_hash_table_destroy(gr->graph_nodes);
  4550. g_free(gr);
  4551. return graph;
  4552. }
  4553. static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor *gr, void *node)
  4554. {
  4555. uintptr_t ret = (uintptr_t)g_hash_table_lookup(gr->graph_nodes, node);
  4556. if (ret != 0) {
  4557. return ret;
  4558. }
  4559. /*
  4560. * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
  4561. * answer of g_hash_table_lookup.
  4562. */
  4563. ret = g_hash_table_size(gr->graph_nodes) + 1;
  4564. g_hash_table_insert(gr->graph_nodes, node, (void *)ret);
  4565. return ret;
  4566. }
  4567. static void xdbg_graph_add_node(XDbgBlockGraphConstructor *gr, void *node,
  4568. XDbgBlockGraphNodeType type, const char *name)
  4569. {
  4570. XDbgBlockGraphNode *n;
  4571. n = g_new0(XDbgBlockGraphNode, 1);
  4572. n->id = xdbg_graph_node_num(gr, node);
  4573. n->type = type;
  4574. n->name = g_strdup(name);
  4575. QAPI_LIST_ADD(gr->graph->nodes, n);
  4576. }
  4577. static void xdbg_graph_add_edge(XDbgBlockGraphConstructor *gr, void *parent,
  4578. const BdrvChild *child)
  4579. {
  4580. BlockPermission qapi_perm;
  4581. XDbgBlockGraphEdge *edge;
  4582. edge = g_new0(XDbgBlockGraphEdge, 1);
  4583. edge->parent = xdbg_graph_node_num(gr, parent);
  4584. edge->child = xdbg_graph_node_num(gr, child->bs);
  4585. edge->name = g_strdup(child->name);
  4586. for (qapi_perm = 0; qapi_perm < BLOCK_PERMISSION__MAX; qapi_perm++) {
  4587. uint64_t flag = bdrv_qapi_perm_to_blk_perm(qapi_perm);
  4588. if (flag & child->perm) {
  4589. QAPI_LIST_ADD(edge->perm, qapi_perm);
  4590. }
  4591. if (flag & child->shared_perm) {
  4592. QAPI_LIST_ADD(edge->shared_perm, qapi_perm);
  4593. }
  4594. }
  4595. QAPI_LIST_ADD(gr->graph->edges, edge);
  4596. }
  4597. XDbgBlockGraph *bdrv_get_xdbg_block_graph(Error **errp)
  4598. {
  4599. BlockBackend *blk;
  4600. BlockJob *job;
  4601. BlockDriverState *bs;
  4602. BdrvChild *child;
  4603. XDbgBlockGraphConstructor *gr = xdbg_graph_new();
  4604. for (blk = blk_all_next(NULL); blk; blk = blk_all_next(blk)) {
  4605. char *allocated_name = NULL;
  4606. const char *name = blk_name(blk);
  4607. if (!*name) {
  4608. name = allocated_name = blk_get_attached_dev_id(blk);
  4609. }
  4610. xdbg_graph_add_node(gr, blk, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND,
  4611. name);
  4612. g_free(allocated_name);
  4613. if (blk_root(blk)) {
  4614. xdbg_graph_add_edge(gr, blk, blk_root(blk));
  4615. }
  4616. }
  4617. for (job = block_job_next(NULL); job; job = block_job_next(job)) {
  4618. GSList *el;
  4619. xdbg_graph_add_node(gr, job, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB,
  4620. job->job.id);
  4621. for (el = job->nodes; el; el = el->next) {
  4622. xdbg_graph_add_edge(gr, job, (BdrvChild *)el->data);
  4623. }
  4624. }
  4625. QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
  4626. xdbg_graph_add_node(gr, bs, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER,
  4627. bs->node_name);
  4628. QLIST_FOREACH(child, &bs->children, next) {
  4629. xdbg_graph_add_edge(gr, bs, child);
  4630. }
  4631. }
  4632. return xdbg_graph_finalize(gr);
  4633. }
  4634. BlockDriverState *bdrv_lookup_bs(const char *device,
  4635. const char *node_name,
  4636. Error **errp)
  4637. {
  4638. BlockBackend *blk;
  4639. BlockDriverState *bs;
  4640. if (device) {
  4641. blk = blk_by_name(device);
  4642. if (blk) {
  4643. bs = blk_bs(blk);
  4644. if (!bs) {
  4645. error_setg(errp, "Device '%s' has no medium", device);
  4646. }
  4647. return bs;
  4648. }
  4649. }
  4650. if (node_name) {
  4651. bs = bdrv_find_node(node_name);
  4652. if (bs) {
  4653. return bs;
  4654. }
  4655. }
  4656. error_setg(errp, "Cannot find device=%s nor node_name=%s",
  4657. device ? device : "",
  4658. node_name ? node_name : "");
  4659. return NULL;
  4660. }
  4661. /* If 'base' is in the same chain as 'top', return true. Otherwise,
  4662. * return false. If either argument is NULL, return false. */
  4663. bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
  4664. {
  4665. while (top && top != base) {
  4666. top = bdrv_filter_or_cow_bs(top);
  4667. }
  4668. return top != NULL;
  4669. }
  4670. BlockDriverState *bdrv_next_node(BlockDriverState *bs)
  4671. {
  4672. if (!bs) {
  4673. return QTAILQ_FIRST(&graph_bdrv_states);
  4674. }
  4675. return QTAILQ_NEXT(bs, node_list);
  4676. }
  4677. BlockDriverState *bdrv_next_all_states(BlockDriverState *bs)
  4678. {
  4679. if (!bs) {
  4680. return QTAILQ_FIRST(&all_bdrv_states);
  4681. }
  4682. return QTAILQ_NEXT(bs, bs_list);
  4683. }
  4684. const char *bdrv_get_node_name(const BlockDriverState *bs)
  4685. {
  4686. return bs->node_name;
  4687. }
  4688. const char *bdrv_get_parent_name(const BlockDriverState *bs)
  4689. {
  4690. BdrvChild *c;
  4691. const char *name;
  4692. /* If multiple parents have a name, just pick the first one. */
  4693. QLIST_FOREACH(c, &bs->parents, next_parent) {
  4694. if (c->klass->get_name) {
  4695. name = c->klass->get_name(c);
  4696. if (name && *name) {
  4697. return name;
  4698. }
  4699. }
  4700. }
  4701. return NULL;
  4702. }
  4703. /* TODO check what callers really want: bs->node_name or blk_name() */
  4704. const char *bdrv_get_device_name(const BlockDriverState *bs)
  4705. {
  4706. return bdrv_get_parent_name(bs) ?: "";
  4707. }
  4708. /* This can be used to identify nodes that might not have a device
  4709. * name associated. Since node and device names live in the same
  4710. * namespace, the result is unambiguous. The exception is if both are
  4711. * absent, then this returns an empty (non-null) string. */
  4712. const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
  4713. {
  4714. return bdrv_get_parent_name(bs) ?: bs->node_name;
  4715. }
  4716. int bdrv_get_flags(BlockDriverState *bs)
  4717. {
  4718. return bs->open_flags;
  4719. }
  4720. int bdrv_has_zero_init_1(BlockDriverState *bs)
  4721. {
  4722. return 1;
  4723. }
  4724. int bdrv_has_zero_init(BlockDriverState *bs)
  4725. {
  4726. BlockDriverState *filtered;
  4727. if (!bs->drv) {
  4728. return 0;
  4729. }
  4730. /* If BS is a copy on write image, it is initialized to
  4731. the contents of the base image, which may not be zeroes. */
  4732. if (bdrv_cow_child(bs)) {
  4733. return 0;
  4734. }
  4735. if (bs->drv->bdrv_has_zero_init) {
  4736. return bs->drv->bdrv_has_zero_init(bs);
  4737. }
  4738. filtered = bdrv_filter_bs(bs);
  4739. if (filtered) {
  4740. return bdrv_has_zero_init(filtered);
  4741. }
  4742. /* safe default */
  4743. return 0;
  4744. }
  4745. bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
  4746. {
  4747. if (!(bs->open_flags & BDRV_O_UNMAP)) {
  4748. return false;
  4749. }
  4750. return bs->supported_zero_flags & BDRV_REQ_MAY_UNMAP;
  4751. }
  4752. void bdrv_get_backing_filename(BlockDriverState *bs,
  4753. char *filename, int filename_size)
  4754. {
  4755. pstrcpy(filename, filename_size, bs->backing_file);
  4756. }
  4757. int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
  4758. {
  4759. BlockDriver *drv = bs->drv;
  4760. /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
  4761. if (!drv) {
  4762. return -ENOMEDIUM;
  4763. }
  4764. if (!drv->bdrv_get_info) {
  4765. BlockDriverState *filtered = bdrv_filter_bs(bs);
  4766. if (filtered) {
  4767. return bdrv_get_info(filtered, bdi);
  4768. }
  4769. return -ENOTSUP;
  4770. }
  4771. memset(bdi, 0, sizeof(*bdi));
  4772. return drv->bdrv_get_info(bs, bdi);
  4773. }
  4774. ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs,
  4775. Error **errp)
  4776. {
  4777. BlockDriver *drv = bs->drv;
  4778. if (drv && drv->bdrv_get_specific_info) {
  4779. return drv->bdrv_get_specific_info(bs, errp);
  4780. }
  4781. return NULL;
  4782. }
  4783. BlockStatsSpecific *bdrv_get_specific_stats(BlockDriverState *bs)
  4784. {
  4785. BlockDriver *drv = bs->drv;
  4786. if (!drv || !drv->bdrv_get_specific_stats) {
  4787. return NULL;
  4788. }
  4789. return drv->bdrv_get_specific_stats(bs);
  4790. }
  4791. void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
  4792. {
  4793. if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
  4794. return;
  4795. }
  4796. bs->drv->bdrv_debug_event(bs, event);
  4797. }
  4798. static BlockDriverState *bdrv_find_debug_node(BlockDriverState *bs)
  4799. {
  4800. while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
  4801. bs = bdrv_primary_bs(bs);
  4802. }
  4803. if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
  4804. assert(bs->drv->bdrv_debug_remove_breakpoint);
  4805. return bs;
  4806. }
  4807. return NULL;
  4808. }
  4809. int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
  4810. const char *tag)
  4811. {
  4812. bs = bdrv_find_debug_node(bs);
  4813. if (bs) {
  4814. return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
  4815. }
  4816. return -ENOTSUP;
  4817. }
  4818. int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
  4819. {
  4820. bs = bdrv_find_debug_node(bs);
  4821. if (bs) {
  4822. return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
  4823. }
  4824. return -ENOTSUP;
  4825. }
  4826. int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
  4827. {
  4828. while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
  4829. bs = bdrv_primary_bs(bs);
  4830. }
  4831. if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
  4832. return bs->drv->bdrv_debug_resume(bs, tag);
  4833. }
  4834. return -ENOTSUP;
  4835. }
  4836. bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
  4837. {
  4838. while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
  4839. bs = bdrv_primary_bs(bs);
  4840. }
  4841. if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
  4842. return bs->drv->bdrv_debug_is_suspended(bs, tag);
  4843. }
  4844. return false;
  4845. }
  4846. /* backing_file can either be relative, or absolute, or a protocol. If it is
  4847. * relative, it must be relative to the chain. So, passing in bs->filename
  4848. * from a BDS as backing_file should not be done, as that may be relative to
  4849. * the CWD rather than the chain. */
  4850. BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
  4851. const char *backing_file)
  4852. {
  4853. char *filename_full = NULL;
  4854. char *backing_file_full = NULL;
  4855. char *filename_tmp = NULL;
  4856. int is_protocol = 0;
  4857. bool filenames_refreshed = false;
  4858. BlockDriverState *curr_bs = NULL;
  4859. BlockDriverState *retval = NULL;
  4860. BlockDriverState *bs_below;
  4861. if (!bs || !bs->drv || !backing_file) {
  4862. return NULL;
  4863. }
  4864. filename_full = g_malloc(PATH_MAX);
  4865. backing_file_full = g_malloc(PATH_MAX);
  4866. is_protocol = path_has_protocol(backing_file);
  4867. /*
  4868. * Being largely a legacy function, skip any filters here
  4869. * (because filters do not have normal filenames, so they cannot
  4870. * match anyway; and allowing json:{} filenames is a bit out of
  4871. * scope).
  4872. */
  4873. for (curr_bs = bdrv_skip_filters(bs);
  4874. bdrv_cow_child(curr_bs) != NULL;
  4875. curr_bs = bs_below)
  4876. {
  4877. bs_below = bdrv_backing_chain_next(curr_bs);
  4878. if (bdrv_backing_overridden(curr_bs)) {
  4879. /*
  4880. * If the backing file was overridden, we can only compare
  4881. * directly against the backing node's filename.
  4882. */
  4883. if (!filenames_refreshed) {
  4884. /*
  4885. * This will automatically refresh all of the
  4886. * filenames in the rest of the backing chain, so we
  4887. * only need to do this once.
  4888. */
  4889. bdrv_refresh_filename(bs_below);
  4890. filenames_refreshed = true;
  4891. }
  4892. if (strcmp(backing_file, bs_below->filename) == 0) {
  4893. retval = bs_below;
  4894. break;
  4895. }
  4896. } else if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
  4897. /*
  4898. * If either of the filename paths is actually a protocol, then
  4899. * compare unmodified paths; otherwise make paths relative.
  4900. */
  4901. char *backing_file_full_ret;
  4902. if (strcmp(backing_file, curr_bs->backing_file) == 0) {
  4903. retval = bs_below;
  4904. break;
  4905. }
  4906. /* Also check against the full backing filename for the image */
  4907. backing_file_full_ret = bdrv_get_full_backing_filename(curr_bs,
  4908. NULL);
  4909. if (backing_file_full_ret) {
  4910. bool equal = strcmp(backing_file, backing_file_full_ret) == 0;
  4911. g_free(backing_file_full_ret);
  4912. if (equal) {
  4913. retval = bs_below;
  4914. break;
  4915. }
  4916. }
  4917. } else {
  4918. /* If not an absolute filename path, make it relative to the current
  4919. * image's filename path */
  4920. filename_tmp = bdrv_make_absolute_filename(curr_bs, backing_file,
  4921. NULL);
  4922. /* We are going to compare canonicalized absolute pathnames */
  4923. if (!filename_tmp || !realpath(filename_tmp, filename_full)) {
  4924. g_free(filename_tmp);
  4925. continue;
  4926. }
  4927. g_free(filename_tmp);
  4928. /* We need to make sure the backing filename we are comparing against
  4929. * is relative to the current image filename (or absolute) */
  4930. filename_tmp = bdrv_get_full_backing_filename(curr_bs, NULL);
  4931. if (!filename_tmp || !realpath(filename_tmp, backing_file_full)) {
  4932. g_free(filename_tmp);
  4933. continue;
  4934. }
  4935. g_free(filename_tmp);
  4936. if (strcmp(backing_file_full, filename_full) == 0) {
  4937. retval = bs_below;
  4938. break;
  4939. }
  4940. }
  4941. }
  4942. g_free(filename_full);
  4943. g_free(backing_file_full);
  4944. return retval;
  4945. }
  4946. void bdrv_init(void)
  4947. {
  4948. module_call_init(MODULE_INIT_BLOCK);
  4949. }
  4950. void bdrv_init_with_whitelist(void)
  4951. {
  4952. use_bdrv_whitelist = 1;
  4953. bdrv_init();
  4954. }
  4955. int coroutine_fn bdrv_co_invalidate_cache(BlockDriverState *bs, Error **errp)
  4956. {
  4957. BdrvChild *child, *parent;
  4958. uint64_t perm, shared_perm;
  4959. Error *local_err = NULL;
  4960. int ret;
  4961. BdrvDirtyBitmap *bm;
  4962. if (!bs->drv) {
  4963. return -ENOMEDIUM;
  4964. }
  4965. QLIST_FOREACH(child, &bs->children, next) {
  4966. bdrv_co_invalidate_cache(child->bs, &local_err);
  4967. if (local_err) {
  4968. error_propagate(errp, local_err);
  4969. return -EINVAL;
  4970. }
  4971. }
  4972. /*
  4973. * Update permissions, they may differ for inactive nodes.
  4974. *
  4975. * Note that the required permissions of inactive images are always a
  4976. * subset of the permissions required after activating the image. This
  4977. * allows us to just get the permissions upfront without restricting
  4978. * drv->bdrv_invalidate_cache().
  4979. *
  4980. * It also means that in error cases, we don't have to try and revert to
  4981. * the old permissions (which is an operation that could fail, too). We can
  4982. * just keep the extended permissions for the next time that an activation
  4983. * of the image is tried.
  4984. */
  4985. if (bs->open_flags & BDRV_O_INACTIVE) {
  4986. bs->open_flags &= ~BDRV_O_INACTIVE;
  4987. bdrv_get_cumulative_perm(bs, &perm, &shared_perm);
  4988. ret = bdrv_check_perm(bs, NULL, perm, shared_perm, NULL, NULL, errp);
  4989. if (ret < 0) {
  4990. bs->open_flags |= BDRV_O_INACTIVE;
  4991. return ret;
  4992. }
  4993. bdrv_set_perm(bs, perm, shared_perm);
  4994. if (bs->drv->bdrv_co_invalidate_cache) {
  4995. bs->drv->bdrv_co_invalidate_cache(bs, &local_err);
  4996. if (local_err) {
  4997. bs->open_flags |= BDRV_O_INACTIVE;
  4998. error_propagate(errp, local_err);
  4999. return -EINVAL;
  5000. }
  5001. }
  5002. FOR_EACH_DIRTY_BITMAP(bs, bm) {
  5003. bdrv_dirty_bitmap_skip_store(bm, false);
  5004. }
  5005. ret = refresh_total_sectors(bs, bs->total_sectors);
  5006. if (ret < 0) {
  5007. bs->open_flags |= BDRV_O_INACTIVE;
  5008. error_setg_errno(errp, -ret, "Could not refresh total sector count");
  5009. return ret;
  5010. }
  5011. }
  5012. QLIST_FOREACH(parent, &bs->parents, next_parent) {
  5013. if (parent->klass->activate) {
  5014. parent->klass->activate(parent, &local_err);
  5015. if (local_err) {
  5016. bs->open_flags |= BDRV_O_INACTIVE;
  5017. error_propagate(errp, local_err);
  5018. return -EINVAL;
  5019. }
  5020. }
  5021. }
  5022. return 0;
  5023. }
  5024. void bdrv_invalidate_cache_all(Error **errp)
  5025. {
  5026. BlockDriverState *bs;
  5027. BdrvNextIterator it;
  5028. for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
  5029. AioContext *aio_context = bdrv_get_aio_context(bs);
  5030. int ret;
  5031. aio_context_acquire(aio_context);
  5032. ret = bdrv_invalidate_cache(bs, errp);
  5033. aio_context_release(aio_context);
  5034. if (ret < 0) {
  5035. bdrv_next_cleanup(&it);
  5036. return;
  5037. }
  5038. }
  5039. }
  5040. static bool bdrv_has_bds_parent(BlockDriverState *bs, bool only_active)
  5041. {
  5042. BdrvChild *parent;
  5043. QLIST_FOREACH(parent, &bs->parents, next_parent) {
  5044. if (parent->klass->parent_is_bds) {
  5045. BlockDriverState *parent_bs = parent->opaque;
  5046. if (!only_active || !(parent_bs->open_flags & BDRV_O_INACTIVE)) {
  5047. return true;
  5048. }
  5049. }
  5050. }
  5051. return false;
  5052. }
  5053. static int bdrv_inactivate_recurse(BlockDriverState *bs)
  5054. {
  5055. BdrvChild *child, *parent;
  5056. bool tighten_restrictions;
  5057. uint64_t perm, shared_perm;
  5058. int ret;
  5059. if (!bs->drv) {
  5060. return -ENOMEDIUM;
  5061. }
  5062. /* Make sure that we don't inactivate a child before its parent.
  5063. * It will be covered by recursion from the yet active parent. */
  5064. if (bdrv_has_bds_parent(bs, true)) {
  5065. return 0;
  5066. }
  5067. assert(!(bs->open_flags & BDRV_O_INACTIVE));
  5068. /* Inactivate this node */
  5069. if (bs->drv->bdrv_inactivate) {
  5070. ret = bs->drv->bdrv_inactivate(bs);
  5071. if (ret < 0) {
  5072. return ret;
  5073. }
  5074. }
  5075. QLIST_FOREACH(parent, &bs->parents, next_parent) {
  5076. if (parent->klass->inactivate) {
  5077. ret = parent->klass->inactivate(parent);
  5078. if (ret < 0) {
  5079. return ret;
  5080. }
  5081. }
  5082. }
  5083. bs->open_flags |= BDRV_O_INACTIVE;
  5084. /* Update permissions, they may differ for inactive nodes */
  5085. bdrv_get_cumulative_perm(bs, &perm, &shared_perm);
  5086. ret = bdrv_check_perm(bs, NULL, perm, shared_perm, NULL,
  5087. &tighten_restrictions, NULL);
  5088. assert(tighten_restrictions == false);
  5089. if (ret < 0) {
  5090. /* We only tried to loosen restrictions, so errors are not fatal */
  5091. bdrv_abort_perm_update(bs);
  5092. } else {
  5093. bdrv_set_perm(bs, perm, shared_perm);
  5094. }
  5095. /* Recursively inactivate children */
  5096. QLIST_FOREACH(child, &bs->children, next) {
  5097. ret = bdrv_inactivate_recurse(child->bs);
  5098. if (ret < 0) {
  5099. return ret;
  5100. }
  5101. }
  5102. return 0;
  5103. }
  5104. int bdrv_inactivate_all(void)
  5105. {
  5106. BlockDriverState *bs = NULL;
  5107. BdrvNextIterator it;
  5108. int ret = 0;
  5109. GSList *aio_ctxs = NULL, *ctx;
  5110. for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
  5111. AioContext *aio_context = bdrv_get_aio_context(bs);
  5112. if (!g_slist_find(aio_ctxs, aio_context)) {
  5113. aio_ctxs = g_slist_prepend(aio_ctxs, aio_context);
  5114. aio_context_acquire(aio_context);
  5115. }
  5116. }
  5117. for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
  5118. /* Nodes with BDS parents are covered by recursion from the last
  5119. * parent that gets inactivated. Don't inactivate them a second
  5120. * time if that has already happened. */
  5121. if (bdrv_has_bds_parent(bs, false)) {
  5122. continue;
  5123. }
  5124. ret = bdrv_inactivate_recurse(bs);
  5125. if (ret < 0) {
  5126. bdrv_next_cleanup(&it);
  5127. goto out;
  5128. }
  5129. }
  5130. out:
  5131. for (ctx = aio_ctxs; ctx != NULL; ctx = ctx->next) {
  5132. AioContext *aio_context = ctx->data;
  5133. aio_context_release(aio_context);
  5134. }
  5135. g_slist_free(aio_ctxs);
  5136. return ret;
  5137. }
  5138. /**************************************************************/
  5139. /* removable device support */
  5140. /**
  5141. * Return TRUE if the media is present
  5142. */
  5143. bool bdrv_is_inserted(BlockDriverState *bs)
  5144. {
  5145. BlockDriver *drv = bs->drv;
  5146. BdrvChild *child;
  5147. if (!drv) {
  5148. return false;
  5149. }
  5150. if (drv->bdrv_is_inserted) {
  5151. return drv->bdrv_is_inserted(bs);
  5152. }
  5153. QLIST_FOREACH(child, &bs->children, next) {
  5154. if (!bdrv_is_inserted(child->bs)) {
  5155. return false;
  5156. }
  5157. }
  5158. return true;
  5159. }
  5160. /**
  5161. * If eject_flag is TRUE, eject the media. Otherwise, close the tray
  5162. */
  5163. void bdrv_eject(BlockDriverState *bs, bool eject_flag)
  5164. {
  5165. BlockDriver *drv = bs->drv;
  5166. if (drv && drv->bdrv_eject) {
  5167. drv->bdrv_eject(bs, eject_flag);
  5168. }
  5169. }
  5170. /**
  5171. * Lock or unlock the media (if it is locked, the user won't be able
  5172. * to eject it manually).
  5173. */
  5174. void bdrv_lock_medium(BlockDriverState *bs, bool locked)
  5175. {
  5176. BlockDriver *drv = bs->drv;
  5177. trace_bdrv_lock_medium(bs, locked);
  5178. if (drv && drv->bdrv_lock_medium) {
  5179. drv->bdrv_lock_medium(bs, locked);
  5180. }
  5181. }
  5182. /* Get a reference to bs */
  5183. void bdrv_ref(BlockDriverState *bs)
  5184. {
  5185. bs->refcnt++;
  5186. }
  5187. /* Release a previously grabbed reference to bs.
  5188. * If after releasing, reference count is zero, the BlockDriverState is
  5189. * deleted. */
  5190. void bdrv_unref(BlockDriverState *bs)
  5191. {
  5192. if (!bs) {
  5193. return;
  5194. }
  5195. assert(bs->refcnt > 0);
  5196. if (--bs->refcnt == 0) {
  5197. bdrv_delete(bs);
  5198. }
  5199. }
  5200. struct BdrvOpBlocker {
  5201. Error *reason;
  5202. QLIST_ENTRY(BdrvOpBlocker) list;
  5203. };
  5204. bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
  5205. {
  5206. BdrvOpBlocker *blocker;
  5207. assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
  5208. if (!QLIST_EMPTY(&bs->op_blockers[op])) {
  5209. blocker = QLIST_FIRST(&bs->op_blockers[op]);
  5210. error_propagate_prepend(errp, error_copy(blocker->reason),
  5211. "Node '%s' is busy: ",
  5212. bdrv_get_device_or_node_name(bs));
  5213. return true;
  5214. }
  5215. return false;
  5216. }
  5217. void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
  5218. {
  5219. BdrvOpBlocker *blocker;
  5220. assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
  5221. blocker = g_new0(BdrvOpBlocker, 1);
  5222. blocker->reason = reason;
  5223. QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
  5224. }
  5225. void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
  5226. {
  5227. BdrvOpBlocker *blocker, *next;
  5228. assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
  5229. QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
  5230. if (blocker->reason == reason) {
  5231. QLIST_REMOVE(blocker, list);
  5232. g_free(blocker);
  5233. }
  5234. }
  5235. }
  5236. void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
  5237. {
  5238. int i;
  5239. for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
  5240. bdrv_op_block(bs, i, reason);
  5241. }
  5242. }
  5243. void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
  5244. {
  5245. int i;
  5246. for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
  5247. bdrv_op_unblock(bs, i, reason);
  5248. }
  5249. }
  5250. bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
  5251. {
  5252. int i;
  5253. for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
  5254. if (!QLIST_EMPTY(&bs->op_blockers[i])) {
  5255. return false;
  5256. }
  5257. }
  5258. return true;
  5259. }
  5260. void bdrv_img_create(const char *filename, const char *fmt,
  5261. const char *base_filename, const char *base_fmt,
  5262. char *options, uint64_t img_size, int flags, bool quiet,
  5263. Error **errp)
  5264. {
  5265. QemuOptsList *create_opts = NULL;
  5266. QemuOpts *opts = NULL;
  5267. const char *backing_fmt, *backing_file;
  5268. int64_t size;
  5269. BlockDriver *drv, *proto_drv;
  5270. Error *local_err = NULL;
  5271. int ret = 0;
  5272. /* Find driver and parse its options */
  5273. drv = bdrv_find_format(fmt);
  5274. if (!drv) {
  5275. error_setg(errp, "Unknown file format '%s'", fmt);
  5276. return;
  5277. }
  5278. proto_drv = bdrv_find_protocol(filename, true, errp);
  5279. if (!proto_drv) {
  5280. return;
  5281. }
  5282. if (!drv->create_opts) {
  5283. error_setg(errp, "Format driver '%s' does not support image creation",
  5284. drv->format_name);
  5285. return;
  5286. }
  5287. if (!proto_drv->create_opts) {
  5288. error_setg(errp, "Protocol driver '%s' does not support image creation",
  5289. proto_drv->format_name);
  5290. return;
  5291. }
  5292. /* Create parameter list */
  5293. create_opts = qemu_opts_append(create_opts, drv->create_opts);
  5294. create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
  5295. opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
  5296. /* Parse -o options */
  5297. if (options) {
  5298. if (!qemu_opts_do_parse(opts, options, NULL, errp)) {
  5299. goto out;
  5300. }
  5301. }
  5302. if (!qemu_opt_get(opts, BLOCK_OPT_SIZE)) {
  5303. qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
  5304. } else if (img_size != UINT64_C(-1)) {
  5305. error_setg(errp, "The image size must be specified only once");
  5306. goto out;
  5307. }
  5308. if (base_filename) {
  5309. if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename,
  5310. NULL)) {
  5311. error_setg(errp, "Backing file not supported for file format '%s'",
  5312. fmt);
  5313. goto out;
  5314. }
  5315. }
  5316. if (base_fmt) {
  5317. if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, NULL)) {
  5318. error_setg(errp, "Backing file format not supported for file "
  5319. "format '%s'", fmt);
  5320. goto out;
  5321. }
  5322. }
  5323. backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
  5324. if (backing_file) {
  5325. if (!strcmp(filename, backing_file)) {
  5326. error_setg(errp, "Error: Trying to create an image with the "
  5327. "same filename as the backing file");
  5328. goto out;
  5329. }
  5330. if (backing_file[0] == '\0') {
  5331. error_setg(errp, "Expected backing file name, got empty string");
  5332. goto out;
  5333. }
  5334. }
  5335. backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
  5336. /* The size for the image must always be specified, unless we have a backing
  5337. * file and we have not been forbidden from opening it. */
  5338. size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, img_size);
  5339. if (backing_file && !(flags & BDRV_O_NO_BACKING)) {
  5340. BlockDriverState *bs;
  5341. char *full_backing;
  5342. int back_flags;
  5343. QDict *backing_options = NULL;
  5344. full_backing =
  5345. bdrv_get_full_backing_filename_from_filename(filename, backing_file,
  5346. &local_err);
  5347. if (local_err) {
  5348. goto out;
  5349. }
  5350. assert(full_backing);
  5351. /* backing files always opened read-only */
  5352. back_flags = flags;
  5353. back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
  5354. backing_options = qdict_new();
  5355. if (backing_fmt) {
  5356. qdict_put_str(backing_options, "driver", backing_fmt);
  5357. }
  5358. qdict_put_bool(backing_options, BDRV_OPT_FORCE_SHARE, true);
  5359. bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
  5360. &local_err);
  5361. g_free(full_backing);
  5362. if (!bs) {
  5363. error_append_hint(&local_err, "Could not open backing image.\n");
  5364. goto out;
  5365. } else {
  5366. if (!backing_fmt) {
  5367. warn_report("Deprecated use of backing file without explicit "
  5368. "backing format (detected format of %s)",
  5369. bs->drv->format_name);
  5370. if (bs->drv != &bdrv_raw) {
  5371. /*
  5372. * A probe of raw deserves the most attention:
  5373. * leaving the backing format out of the image
  5374. * will ensure bs->probed is set (ensuring we
  5375. * don't accidentally commit into the backing
  5376. * file), and allow more spots to warn the users
  5377. * to fix their toolchain when opening this image
  5378. * later. For other images, we can safely record
  5379. * the format that we probed.
  5380. */
  5381. backing_fmt = bs->drv->format_name;
  5382. qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, backing_fmt,
  5383. NULL);
  5384. }
  5385. }
  5386. if (size == -1) {
  5387. /* Opened BS, have no size */
  5388. size = bdrv_getlength(bs);
  5389. if (size < 0) {
  5390. error_setg_errno(errp, -size, "Could not get size of '%s'",
  5391. backing_file);
  5392. bdrv_unref(bs);
  5393. goto out;
  5394. }
  5395. qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
  5396. }
  5397. bdrv_unref(bs);
  5398. }
  5399. /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
  5400. } else if (backing_file && !backing_fmt) {
  5401. warn_report("Deprecated use of unopened backing file without "
  5402. "explicit backing format, use of this image requires "
  5403. "potentially unsafe format probing");
  5404. }
  5405. if (size == -1) {
  5406. error_setg(errp, "Image creation needs a size parameter");
  5407. goto out;
  5408. }
  5409. if (!quiet) {
  5410. printf("Formatting '%s', fmt=%s ", filename, fmt);
  5411. qemu_opts_print(opts, " ");
  5412. puts("");
  5413. fflush(stdout);
  5414. }
  5415. ret = bdrv_create(drv, filename, opts, &local_err);
  5416. if (ret == -EFBIG) {
  5417. /* This is generally a better message than whatever the driver would
  5418. * deliver (especially because of the cluster_size_hint), since that
  5419. * is most probably not much different from "image too large". */
  5420. const char *cluster_size_hint = "";
  5421. if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
  5422. cluster_size_hint = " (try using a larger cluster size)";
  5423. }
  5424. error_setg(errp, "The image size is too large for file format '%s'"
  5425. "%s", fmt, cluster_size_hint);
  5426. error_free(local_err);
  5427. local_err = NULL;
  5428. }
  5429. out:
  5430. qemu_opts_del(opts);
  5431. qemu_opts_free(create_opts);
  5432. error_propagate(errp, local_err);
  5433. }
  5434. AioContext *bdrv_get_aio_context(BlockDriverState *bs)
  5435. {
  5436. return bs ? bs->aio_context : qemu_get_aio_context();
  5437. }
  5438. AioContext *coroutine_fn bdrv_co_enter(BlockDriverState *bs)
  5439. {
  5440. Coroutine *self = qemu_coroutine_self();
  5441. AioContext *old_ctx = qemu_coroutine_get_aio_context(self);
  5442. AioContext *new_ctx;
  5443. /*
  5444. * Increase bs->in_flight to ensure that this operation is completed before
  5445. * moving the node to a different AioContext. Read new_ctx only afterwards.
  5446. */
  5447. bdrv_inc_in_flight(bs);
  5448. new_ctx = bdrv_get_aio_context(bs);
  5449. aio_co_reschedule_self(new_ctx);
  5450. return old_ctx;
  5451. }
  5452. void coroutine_fn bdrv_co_leave(BlockDriverState *bs, AioContext *old_ctx)
  5453. {
  5454. aio_co_reschedule_self(old_ctx);
  5455. bdrv_dec_in_flight(bs);
  5456. }
  5457. void coroutine_fn bdrv_co_lock(BlockDriverState *bs)
  5458. {
  5459. AioContext *ctx = bdrv_get_aio_context(bs);
  5460. /* In the main thread, bs->aio_context won't change concurrently */
  5461. assert(qemu_get_current_aio_context() == qemu_get_aio_context());
  5462. /*
  5463. * We're in coroutine context, so we already hold the lock of the main
  5464. * loop AioContext. Don't lock it twice to avoid deadlocks.
  5465. */
  5466. assert(qemu_in_coroutine());
  5467. if (ctx != qemu_get_aio_context()) {
  5468. aio_context_acquire(ctx);
  5469. }
  5470. }
  5471. void coroutine_fn bdrv_co_unlock(BlockDriverState *bs)
  5472. {
  5473. AioContext *ctx = bdrv_get_aio_context(bs);
  5474. assert(qemu_in_coroutine());
  5475. if (ctx != qemu_get_aio_context()) {
  5476. aio_context_release(ctx);
  5477. }
  5478. }
  5479. void bdrv_coroutine_enter(BlockDriverState *bs, Coroutine *co)
  5480. {
  5481. aio_co_enter(bdrv_get_aio_context(bs), co);
  5482. }
  5483. static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier *ban)
  5484. {
  5485. QLIST_REMOVE(ban, list);
  5486. g_free(ban);
  5487. }
  5488. static void bdrv_detach_aio_context(BlockDriverState *bs)
  5489. {
  5490. BdrvAioNotifier *baf, *baf_tmp;
  5491. assert(!bs->walking_aio_notifiers);
  5492. bs->walking_aio_notifiers = true;
  5493. QLIST_FOREACH_SAFE(baf, &bs->aio_notifiers, list, baf_tmp) {
  5494. if (baf->deleted) {
  5495. bdrv_do_remove_aio_context_notifier(baf);
  5496. } else {
  5497. baf->detach_aio_context(baf->opaque);
  5498. }
  5499. }
  5500. /* Never mind iterating again to check for ->deleted. bdrv_close() will
  5501. * remove remaining aio notifiers if we aren't called again.
  5502. */
  5503. bs->walking_aio_notifiers = false;
  5504. if (bs->drv && bs->drv->bdrv_detach_aio_context) {
  5505. bs->drv->bdrv_detach_aio_context(bs);
  5506. }
  5507. if (bs->quiesce_counter) {
  5508. aio_enable_external(bs->aio_context);
  5509. }
  5510. bs->aio_context = NULL;
  5511. }
  5512. static void bdrv_attach_aio_context(BlockDriverState *bs,
  5513. AioContext *new_context)
  5514. {
  5515. BdrvAioNotifier *ban, *ban_tmp;
  5516. if (bs->quiesce_counter) {
  5517. aio_disable_external(new_context);
  5518. }
  5519. bs->aio_context = new_context;
  5520. if (bs->drv && bs->drv->bdrv_attach_aio_context) {
  5521. bs->drv->bdrv_attach_aio_context(bs, new_context);
  5522. }
  5523. assert(!bs->walking_aio_notifiers);
  5524. bs->walking_aio_notifiers = true;
  5525. QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_tmp) {
  5526. if (ban->deleted) {
  5527. bdrv_do_remove_aio_context_notifier(ban);
  5528. } else {
  5529. ban->attached_aio_context(new_context, ban->opaque);
  5530. }
  5531. }
  5532. bs->walking_aio_notifiers = false;
  5533. }
  5534. /*
  5535. * Changes the AioContext used for fd handlers, timers, and BHs by this
  5536. * BlockDriverState and all its children and parents.
  5537. *
  5538. * Must be called from the main AioContext.
  5539. *
  5540. * The caller must own the AioContext lock for the old AioContext of bs, but it
  5541. * must not own the AioContext lock for new_context (unless new_context is the
  5542. * same as the current context of bs).
  5543. *
  5544. * @ignore will accumulate all visited BdrvChild object. The caller is
  5545. * responsible for freeing the list afterwards.
  5546. */
  5547. void bdrv_set_aio_context_ignore(BlockDriverState *bs,
  5548. AioContext *new_context, GSList **ignore)
  5549. {
  5550. AioContext *old_context = bdrv_get_aio_context(bs);
  5551. BdrvChild *child;
  5552. g_assert(qemu_get_current_aio_context() == qemu_get_aio_context());
  5553. if (old_context == new_context) {
  5554. return;
  5555. }
  5556. bdrv_drained_begin(bs);
  5557. QLIST_FOREACH(child, &bs->children, next) {
  5558. if (g_slist_find(*ignore, child)) {
  5559. continue;
  5560. }
  5561. *ignore = g_slist_prepend(*ignore, child);
  5562. bdrv_set_aio_context_ignore(child->bs, new_context, ignore);
  5563. }
  5564. QLIST_FOREACH(child, &bs->parents, next_parent) {
  5565. if (g_slist_find(*ignore, child)) {
  5566. continue;
  5567. }
  5568. assert(child->klass->set_aio_ctx);
  5569. *ignore = g_slist_prepend(*ignore, child);
  5570. child->klass->set_aio_ctx(child, new_context, ignore);
  5571. }
  5572. bdrv_detach_aio_context(bs);
  5573. /* Acquire the new context, if necessary */
  5574. if (qemu_get_aio_context() != new_context) {
  5575. aio_context_acquire(new_context);
  5576. }
  5577. bdrv_attach_aio_context(bs, new_context);
  5578. /*
  5579. * If this function was recursively called from
  5580. * bdrv_set_aio_context_ignore(), there may be nodes in the
  5581. * subtree that have not yet been moved to the new AioContext.
  5582. * Release the old one so bdrv_drained_end() can poll them.
  5583. */
  5584. if (qemu_get_aio_context() != old_context) {
  5585. aio_context_release(old_context);
  5586. }
  5587. bdrv_drained_end(bs);
  5588. if (qemu_get_aio_context() != old_context) {
  5589. aio_context_acquire(old_context);
  5590. }
  5591. if (qemu_get_aio_context() != new_context) {
  5592. aio_context_release(new_context);
  5593. }
  5594. }
  5595. static bool bdrv_parent_can_set_aio_context(BdrvChild *c, AioContext *ctx,
  5596. GSList **ignore, Error **errp)
  5597. {
  5598. if (g_slist_find(*ignore, c)) {
  5599. return true;
  5600. }
  5601. *ignore = g_slist_prepend(*ignore, c);
  5602. /*
  5603. * A BdrvChildClass that doesn't handle AioContext changes cannot
  5604. * tolerate any AioContext changes
  5605. */
  5606. if (!c->klass->can_set_aio_ctx) {
  5607. char *user = bdrv_child_user_desc(c);
  5608. error_setg(errp, "Changing iothreads is not supported by %s", user);
  5609. g_free(user);
  5610. return false;
  5611. }
  5612. if (!c->klass->can_set_aio_ctx(c, ctx, ignore, errp)) {
  5613. assert(!errp || *errp);
  5614. return false;
  5615. }
  5616. return true;
  5617. }
  5618. bool bdrv_child_can_set_aio_context(BdrvChild *c, AioContext *ctx,
  5619. GSList **ignore, Error **errp)
  5620. {
  5621. if (g_slist_find(*ignore, c)) {
  5622. return true;
  5623. }
  5624. *ignore = g_slist_prepend(*ignore, c);
  5625. return bdrv_can_set_aio_context(c->bs, ctx, ignore, errp);
  5626. }
  5627. /* @ignore will accumulate all visited BdrvChild object. The caller is
  5628. * responsible for freeing the list afterwards. */
  5629. bool bdrv_can_set_aio_context(BlockDriverState *bs, AioContext *ctx,
  5630. GSList **ignore, Error **errp)
  5631. {
  5632. BdrvChild *c;
  5633. if (bdrv_get_aio_context(bs) == ctx) {
  5634. return true;
  5635. }
  5636. QLIST_FOREACH(c, &bs->parents, next_parent) {
  5637. if (!bdrv_parent_can_set_aio_context(c, ctx, ignore, errp)) {
  5638. return false;
  5639. }
  5640. }
  5641. QLIST_FOREACH(c, &bs->children, next) {
  5642. if (!bdrv_child_can_set_aio_context(c, ctx, ignore, errp)) {
  5643. return false;
  5644. }
  5645. }
  5646. return true;
  5647. }
  5648. int bdrv_child_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
  5649. BdrvChild *ignore_child, Error **errp)
  5650. {
  5651. GSList *ignore;
  5652. bool ret;
  5653. ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
  5654. ret = bdrv_can_set_aio_context(bs, ctx, &ignore, errp);
  5655. g_slist_free(ignore);
  5656. if (!ret) {
  5657. return -EPERM;
  5658. }
  5659. ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
  5660. bdrv_set_aio_context_ignore(bs, ctx, &ignore);
  5661. g_slist_free(ignore);
  5662. return 0;
  5663. }
  5664. int bdrv_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
  5665. Error **errp)
  5666. {
  5667. return bdrv_child_try_set_aio_context(bs, ctx, NULL, errp);
  5668. }
  5669. void bdrv_add_aio_context_notifier(BlockDriverState *bs,
  5670. void (*attached_aio_context)(AioContext *new_context, void *opaque),
  5671. void (*detach_aio_context)(void *opaque), void *opaque)
  5672. {
  5673. BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
  5674. *ban = (BdrvAioNotifier){
  5675. .attached_aio_context = attached_aio_context,
  5676. .detach_aio_context = detach_aio_context,
  5677. .opaque = opaque
  5678. };
  5679. QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
  5680. }
  5681. void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
  5682. void (*attached_aio_context)(AioContext *,
  5683. void *),
  5684. void (*detach_aio_context)(void *),
  5685. void *opaque)
  5686. {
  5687. BdrvAioNotifier *ban, *ban_next;
  5688. QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
  5689. if (ban->attached_aio_context == attached_aio_context &&
  5690. ban->detach_aio_context == detach_aio_context &&
  5691. ban->opaque == opaque &&
  5692. ban->deleted == false)
  5693. {
  5694. if (bs->walking_aio_notifiers) {
  5695. ban->deleted = true;
  5696. } else {
  5697. bdrv_do_remove_aio_context_notifier(ban);
  5698. }
  5699. return;
  5700. }
  5701. }
  5702. abort();
  5703. }
  5704. int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
  5705. BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
  5706. bool force,
  5707. Error **errp)
  5708. {
  5709. if (!bs->drv) {
  5710. error_setg(errp, "Node is ejected");
  5711. return -ENOMEDIUM;
  5712. }
  5713. if (!bs->drv->bdrv_amend_options) {
  5714. error_setg(errp, "Block driver '%s' does not support option amendment",
  5715. bs->drv->format_name);
  5716. return -ENOTSUP;
  5717. }
  5718. return bs->drv->bdrv_amend_options(bs, opts, status_cb,
  5719. cb_opaque, force, errp);
  5720. }
  5721. /*
  5722. * This function checks whether the given @to_replace is allowed to be
  5723. * replaced by a node that always shows the same data as @bs. This is
  5724. * used for example to verify whether the mirror job can replace
  5725. * @to_replace by the target mirrored from @bs.
  5726. * To be replaceable, @bs and @to_replace may either be guaranteed to
  5727. * always show the same data (because they are only connected through
  5728. * filters), or some driver may allow replacing one of its children
  5729. * because it can guarantee that this child's data is not visible at
  5730. * all (for example, for dissenting quorum children that have no other
  5731. * parents).
  5732. */
  5733. bool bdrv_recurse_can_replace(BlockDriverState *bs,
  5734. BlockDriverState *to_replace)
  5735. {
  5736. BlockDriverState *filtered;
  5737. if (!bs || !bs->drv) {
  5738. return false;
  5739. }
  5740. if (bs == to_replace) {
  5741. return true;
  5742. }
  5743. /* See what the driver can do */
  5744. if (bs->drv->bdrv_recurse_can_replace) {
  5745. return bs->drv->bdrv_recurse_can_replace(bs, to_replace);
  5746. }
  5747. /* For filters without an own implementation, we can recurse on our own */
  5748. filtered = bdrv_filter_bs(bs);
  5749. if (filtered) {
  5750. return bdrv_recurse_can_replace(filtered, to_replace);
  5751. }
  5752. /* Safe default */
  5753. return false;
  5754. }
  5755. /*
  5756. * Check whether the given @node_name can be replaced by a node that
  5757. * has the same data as @parent_bs. If so, return @node_name's BDS;
  5758. * NULL otherwise.
  5759. *
  5760. * @node_name must be a (recursive) *child of @parent_bs (or this
  5761. * function will return NULL).
  5762. *
  5763. * The result (whether the node can be replaced or not) is only valid
  5764. * for as long as no graph or permission changes occur.
  5765. */
  5766. BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
  5767. const char *node_name, Error **errp)
  5768. {
  5769. BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
  5770. AioContext *aio_context;
  5771. if (!to_replace_bs) {
  5772. error_setg(errp, "Node name '%s' not found", node_name);
  5773. return NULL;
  5774. }
  5775. aio_context = bdrv_get_aio_context(to_replace_bs);
  5776. aio_context_acquire(aio_context);
  5777. if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
  5778. to_replace_bs = NULL;
  5779. goto out;
  5780. }
  5781. /* We don't want arbitrary node of the BDS chain to be replaced only the top
  5782. * most non filter in order to prevent data corruption.
  5783. * Another benefit is that this tests exclude backing files which are
  5784. * blocked by the backing blockers.
  5785. */
  5786. if (!bdrv_recurse_can_replace(parent_bs, to_replace_bs)) {
  5787. error_setg(errp, "Cannot replace '%s' by a node mirrored from '%s', "
  5788. "because it cannot be guaranteed that doing so would not "
  5789. "lead to an abrupt change of visible data",
  5790. node_name, parent_bs->node_name);
  5791. to_replace_bs = NULL;
  5792. goto out;
  5793. }
  5794. out:
  5795. aio_context_release(aio_context);
  5796. return to_replace_bs;
  5797. }
  5798. /**
  5799. * Iterates through the list of runtime option keys that are said to
  5800. * be "strong" for a BDS. An option is called "strong" if it changes
  5801. * a BDS's data. For example, the null block driver's "size" and
  5802. * "read-zeroes" options are strong, but its "latency-ns" option is
  5803. * not.
  5804. *
  5805. * If a key returned by this function ends with a dot, all options
  5806. * starting with that prefix are strong.
  5807. */
  5808. static const char *const *strong_options(BlockDriverState *bs,
  5809. const char *const *curopt)
  5810. {
  5811. static const char *const global_options[] = {
  5812. "driver", "filename", NULL
  5813. };
  5814. if (!curopt) {
  5815. return &global_options[0];
  5816. }
  5817. curopt++;
  5818. if (curopt == &global_options[ARRAY_SIZE(global_options) - 1] && bs->drv) {
  5819. curopt = bs->drv->strong_runtime_opts;
  5820. }
  5821. return (curopt && *curopt) ? curopt : NULL;
  5822. }
  5823. /**
  5824. * Copies all strong runtime options from bs->options to the given
  5825. * QDict. The set of strong option keys is determined by invoking
  5826. * strong_options().
  5827. *
  5828. * Returns true iff any strong option was present in bs->options (and
  5829. * thus copied to the target QDict) with the exception of "filename"
  5830. * and "driver". The caller is expected to use this value to decide
  5831. * whether the existence of strong options prevents the generation of
  5832. * a plain filename.
  5833. */
  5834. static bool append_strong_runtime_options(QDict *d, BlockDriverState *bs)
  5835. {
  5836. bool found_any = false;
  5837. const char *const *option_name = NULL;
  5838. if (!bs->drv) {
  5839. return false;
  5840. }
  5841. while ((option_name = strong_options(bs, option_name))) {
  5842. bool option_given = false;
  5843. assert(strlen(*option_name) > 0);
  5844. if ((*option_name)[strlen(*option_name) - 1] != '.') {
  5845. QObject *entry = qdict_get(bs->options, *option_name);
  5846. if (!entry) {
  5847. continue;
  5848. }
  5849. qdict_put_obj(d, *option_name, qobject_ref(entry));
  5850. option_given = true;
  5851. } else {
  5852. const QDictEntry *entry;
  5853. for (entry = qdict_first(bs->options); entry;
  5854. entry = qdict_next(bs->options, entry))
  5855. {
  5856. if (strstart(qdict_entry_key(entry), *option_name, NULL)) {
  5857. qdict_put_obj(d, qdict_entry_key(entry),
  5858. qobject_ref(qdict_entry_value(entry)));
  5859. option_given = true;
  5860. }
  5861. }
  5862. }
  5863. /* While "driver" and "filename" need to be included in a JSON filename,
  5864. * their existence does not prohibit generation of a plain filename. */
  5865. if (!found_any && option_given &&
  5866. strcmp(*option_name, "driver") && strcmp(*option_name, "filename"))
  5867. {
  5868. found_any = true;
  5869. }
  5870. }
  5871. if (!qdict_haskey(d, "driver")) {
  5872. /* Drivers created with bdrv_new_open_driver() may not have a
  5873. * @driver option. Add it here. */
  5874. qdict_put_str(d, "driver", bs->drv->format_name);
  5875. }
  5876. return found_any;
  5877. }
  5878. /* Note: This function may return false positives; it may return true
  5879. * even if opening the backing file specified by bs's image header
  5880. * would result in exactly bs->backing. */
  5881. bool bdrv_backing_overridden(BlockDriverState *bs)
  5882. {
  5883. if (bs->backing) {
  5884. return strcmp(bs->auto_backing_file,
  5885. bs->backing->bs->filename);
  5886. } else {
  5887. /* No backing BDS, so if the image header reports any backing
  5888. * file, it must have been suppressed */
  5889. return bs->auto_backing_file[0] != '\0';
  5890. }
  5891. }
  5892. /* Updates the following BDS fields:
  5893. * - exact_filename: A filename which may be used for opening a block device
  5894. * which (mostly) equals the given BDS (even without any
  5895. * other options; so reading and writing must return the same
  5896. * results, but caching etc. may be different)
  5897. * - full_open_options: Options which, when given when opening a block device
  5898. * (without a filename), result in a BDS (mostly)
  5899. * equalling the given one
  5900. * - filename: If exact_filename is set, it is copied here. Otherwise,
  5901. * full_open_options is converted to a JSON object, prefixed with
  5902. * "json:" (for use through the JSON pseudo protocol) and put here.
  5903. */
  5904. void bdrv_refresh_filename(BlockDriverState *bs)
  5905. {
  5906. BlockDriver *drv = bs->drv;
  5907. BdrvChild *child;
  5908. BlockDriverState *primary_child_bs;
  5909. QDict *opts;
  5910. bool backing_overridden;
  5911. bool generate_json_filename; /* Whether our default implementation should
  5912. fill exact_filename (false) or not (true) */
  5913. if (!drv) {
  5914. return;
  5915. }
  5916. /* This BDS's file name may depend on any of its children's file names, so
  5917. * refresh those first */
  5918. QLIST_FOREACH(child, &bs->children, next) {
  5919. bdrv_refresh_filename(child->bs);
  5920. }
  5921. if (bs->implicit) {
  5922. /* For implicit nodes, just copy everything from the single child */
  5923. child = QLIST_FIRST(&bs->children);
  5924. assert(QLIST_NEXT(child, next) == NULL);
  5925. pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
  5926. child->bs->exact_filename);
  5927. pstrcpy(bs->filename, sizeof(bs->filename), child->bs->filename);
  5928. qobject_unref(bs->full_open_options);
  5929. bs->full_open_options = qobject_ref(child->bs->full_open_options);
  5930. return;
  5931. }
  5932. backing_overridden = bdrv_backing_overridden(bs);
  5933. if (bs->open_flags & BDRV_O_NO_IO) {
  5934. /* Without I/O, the backing file does not change anything.
  5935. * Therefore, in such a case (primarily qemu-img), we can
  5936. * pretend the backing file has not been overridden even if
  5937. * it technically has been. */
  5938. backing_overridden = false;
  5939. }
  5940. /* Gather the options QDict */
  5941. opts = qdict_new();
  5942. generate_json_filename = append_strong_runtime_options(opts, bs);
  5943. generate_json_filename |= backing_overridden;
  5944. if (drv->bdrv_gather_child_options) {
  5945. /* Some block drivers may not want to present all of their children's
  5946. * options, or name them differently from BdrvChild.name */
  5947. drv->bdrv_gather_child_options(bs, opts, backing_overridden);
  5948. } else {
  5949. QLIST_FOREACH(child, &bs->children, next) {
  5950. if (child == bs->backing && !backing_overridden) {
  5951. /* We can skip the backing BDS if it has not been overridden */
  5952. continue;
  5953. }
  5954. qdict_put(opts, child->name,
  5955. qobject_ref(child->bs->full_open_options));
  5956. }
  5957. if (backing_overridden && !bs->backing) {
  5958. /* Force no backing file */
  5959. qdict_put_null(opts, "backing");
  5960. }
  5961. }
  5962. qobject_unref(bs->full_open_options);
  5963. bs->full_open_options = opts;
  5964. primary_child_bs = bdrv_primary_bs(bs);
  5965. if (drv->bdrv_refresh_filename) {
  5966. /* Obsolete information is of no use here, so drop the old file name
  5967. * information before refreshing it */
  5968. bs->exact_filename[0] = '\0';
  5969. drv->bdrv_refresh_filename(bs);
  5970. } else if (primary_child_bs) {
  5971. /*
  5972. * Try to reconstruct valid information from the underlying
  5973. * file -- this only works for format nodes (filter nodes
  5974. * cannot be probed and as such must be selected by the user
  5975. * either through an options dict, or through a special
  5976. * filename which the filter driver must construct in its
  5977. * .bdrv_refresh_filename() implementation).
  5978. */
  5979. bs->exact_filename[0] = '\0';
  5980. /*
  5981. * We can use the underlying file's filename if:
  5982. * - it has a filename,
  5983. * - the current BDS is not a filter,
  5984. * - the file is a protocol BDS, and
  5985. * - opening that file (as this BDS's format) will automatically create
  5986. * the BDS tree we have right now, that is:
  5987. * - the user did not significantly change this BDS's behavior with
  5988. * some explicit (strong) options
  5989. * - no non-file child of this BDS has been overridden by the user
  5990. * Both of these conditions are represented by generate_json_filename.
  5991. */
  5992. if (primary_child_bs->exact_filename[0] &&
  5993. primary_child_bs->drv->bdrv_file_open &&
  5994. !drv->is_filter && !generate_json_filename)
  5995. {
  5996. strcpy(bs->exact_filename, primary_child_bs->exact_filename);
  5997. }
  5998. }
  5999. if (bs->exact_filename[0]) {
  6000. pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
  6001. } else {
  6002. QString *json = qobject_to_json(QOBJECT(bs->full_open_options));
  6003. if (snprintf(bs->filename, sizeof(bs->filename), "json:%s",
  6004. qstring_get_str(json)) >= sizeof(bs->filename)) {
  6005. /* Give user a hint if we truncated things. */
  6006. strcpy(bs->filename + sizeof(bs->filename) - 4, "...");
  6007. }
  6008. qobject_unref(json);
  6009. }
  6010. }
  6011. char *bdrv_dirname(BlockDriverState *bs, Error **errp)
  6012. {
  6013. BlockDriver *drv = bs->drv;
  6014. BlockDriverState *child_bs;
  6015. if (!drv) {
  6016. error_setg(errp, "Node '%s' is ejected", bs->node_name);
  6017. return NULL;
  6018. }
  6019. if (drv->bdrv_dirname) {
  6020. return drv->bdrv_dirname(bs, errp);
  6021. }
  6022. child_bs = bdrv_primary_bs(bs);
  6023. if (child_bs) {
  6024. return bdrv_dirname(child_bs, errp);
  6025. }
  6026. bdrv_refresh_filename(bs);
  6027. if (bs->exact_filename[0] != '\0') {
  6028. return path_combine(bs->exact_filename, "");
  6029. }
  6030. error_setg(errp, "Cannot generate a base directory for %s nodes",
  6031. drv->format_name);
  6032. return NULL;
  6033. }
  6034. /*
  6035. * Hot add/remove a BDS's child. So the user can take a child offline when
  6036. * it is broken and take a new child online
  6037. */
  6038. void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
  6039. Error **errp)
  6040. {
  6041. if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
  6042. error_setg(errp, "The node %s does not support adding a child",
  6043. bdrv_get_device_or_node_name(parent_bs));
  6044. return;
  6045. }
  6046. if (!QLIST_EMPTY(&child_bs->parents)) {
  6047. error_setg(errp, "The node %s already has a parent",
  6048. child_bs->node_name);
  6049. return;
  6050. }
  6051. parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
  6052. }
  6053. void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
  6054. {
  6055. BdrvChild *tmp;
  6056. if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
  6057. error_setg(errp, "The node %s does not support removing a child",
  6058. bdrv_get_device_or_node_name(parent_bs));
  6059. return;
  6060. }
  6061. QLIST_FOREACH(tmp, &parent_bs->children, next) {
  6062. if (tmp == child) {
  6063. break;
  6064. }
  6065. }
  6066. if (!tmp) {
  6067. error_setg(errp, "The node %s does not have a child named %s",
  6068. bdrv_get_device_or_node_name(parent_bs),
  6069. bdrv_get_device_or_node_name(child->bs));
  6070. return;
  6071. }
  6072. parent_bs->drv->bdrv_del_child(parent_bs, child, errp);
  6073. }
  6074. int bdrv_make_empty(BdrvChild *c, Error **errp)
  6075. {
  6076. BlockDriver *drv = c->bs->drv;
  6077. int ret;
  6078. assert(c->perm & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED));
  6079. if (!drv->bdrv_make_empty) {
  6080. error_setg(errp, "%s does not support emptying nodes",
  6081. drv->format_name);
  6082. return -ENOTSUP;
  6083. }
  6084. ret = drv->bdrv_make_empty(c->bs);
  6085. if (ret < 0) {
  6086. error_setg_errno(errp, -ret, "Failed to empty %s",
  6087. c->bs->filename);
  6088. return ret;
  6089. }
  6090. return 0;
  6091. }
  6092. /*
  6093. * Return the child that @bs acts as an overlay for, and from which data may be
  6094. * copied in COW or COR operations. Usually this is the backing file.
  6095. */
  6096. BdrvChild *bdrv_cow_child(BlockDriverState *bs)
  6097. {
  6098. if (!bs || !bs->drv) {
  6099. return NULL;
  6100. }
  6101. if (bs->drv->is_filter) {
  6102. return NULL;
  6103. }
  6104. if (!bs->backing) {
  6105. return NULL;
  6106. }
  6107. assert(bs->backing->role & BDRV_CHILD_COW);
  6108. return bs->backing;
  6109. }
  6110. /*
  6111. * If @bs acts as a filter for exactly one of its children, return
  6112. * that child.
  6113. */
  6114. BdrvChild *bdrv_filter_child(BlockDriverState *bs)
  6115. {
  6116. BdrvChild *c;
  6117. if (!bs || !bs->drv) {
  6118. return NULL;
  6119. }
  6120. if (!bs->drv->is_filter) {
  6121. return NULL;
  6122. }
  6123. /* Only one of @backing or @file may be used */
  6124. assert(!(bs->backing && bs->file));
  6125. c = bs->backing ?: bs->file;
  6126. if (!c) {
  6127. return NULL;
  6128. }
  6129. assert(c->role & BDRV_CHILD_FILTERED);
  6130. return c;
  6131. }
  6132. /*
  6133. * Return either the result of bdrv_cow_child() or bdrv_filter_child(),
  6134. * whichever is non-NULL.
  6135. *
  6136. * Return NULL if both are NULL.
  6137. */
  6138. BdrvChild *bdrv_filter_or_cow_child(BlockDriverState *bs)
  6139. {
  6140. BdrvChild *cow_child = bdrv_cow_child(bs);
  6141. BdrvChild *filter_child = bdrv_filter_child(bs);
  6142. /* Filter nodes cannot have COW backing files */
  6143. assert(!(cow_child && filter_child));
  6144. return cow_child ?: filter_child;
  6145. }
  6146. /*
  6147. * Return the primary child of this node: For filters, that is the
  6148. * filtered child. For other nodes, that is usually the child storing
  6149. * metadata.
  6150. * (A generally more helpful description is that this is (usually) the
  6151. * child that has the same filename as @bs.)
  6152. *
  6153. * Drivers do not necessarily have a primary child; for example quorum
  6154. * does not.
  6155. */
  6156. BdrvChild *bdrv_primary_child(BlockDriverState *bs)
  6157. {
  6158. BdrvChild *c, *found = NULL;
  6159. QLIST_FOREACH(c, &bs->children, next) {
  6160. if (c->role & BDRV_CHILD_PRIMARY) {
  6161. assert(!found);
  6162. found = c;
  6163. }
  6164. }
  6165. return found;
  6166. }
  6167. static BlockDriverState *bdrv_do_skip_filters(BlockDriverState *bs,
  6168. bool stop_on_explicit_filter)
  6169. {
  6170. BdrvChild *c;
  6171. if (!bs) {
  6172. return NULL;
  6173. }
  6174. while (!(stop_on_explicit_filter && !bs->implicit)) {
  6175. c = bdrv_filter_child(bs);
  6176. if (!c) {
  6177. /*
  6178. * A filter that is embedded in a working block graph must
  6179. * have a child. Assert this here so this function does
  6180. * not return a filter node that is not expected by the
  6181. * caller.
  6182. */
  6183. assert(!bs->drv || !bs->drv->is_filter);
  6184. break;
  6185. }
  6186. bs = c->bs;
  6187. }
  6188. /*
  6189. * Note that this treats nodes with bs->drv == NULL as not being
  6190. * filters (bs->drv == NULL should be replaced by something else
  6191. * anyway).
  6192. * The advantage of this behavior is that this function will thus
  6193. * always return a non-NULL value (given a non-NULL @bs).
  6194. */
  6195. return bs;
  6196. }
  6197. /*
  6198. * Return the first BDS that has not been added implicitly or that
  6199. * does not have a filtered child down the chain starting from @bs
  6200. * (including @bs itself).
  6201. */
  6202. BlockDriverState *bdrv_skip_implicit_filters(BlockDriverState *bs)
  6203. {
  6204. return bdrv_do_skip_filters(bs, true);
  6205. }
  6206. /*
  6207. * Return the first BDS that does not have a filtered child down the
  6208. * chain starting from @bs (including @bs itself).
  6209. */
  6210. BlockDriverState *bdrv_skip_filters(BlockDriverState *bs)
  6211. {
  6212. return bdrv_do_skip_filters(bs, false);
  6213. }
  6214. /*
  6215. * For a backing chain, return the first non-filter backing image of
  6216. * the first non-filter image.
  6217. */
  6218. BlockDriverState *bdrv_backing_chain_next(BlockDriverState *bs)
  6219. {
  6220. return bdrv_skip_filters(bdrv_cow_bs(bdrv_skip_filters(bs)));
  6221. }