block.c 248 KB

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