block.c 240 KB

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