block.c 244 KB

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