block.c 247 KB

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