Skip to contentSkip to conversation

Split BlockBackend off BDS with an axe

PATCH Superseded Markus Armbruster 5 participants 76 messages Sep 10, 2014 – Sep 12, 2014 Page 1 of 2

Subsystems (3)

v1 of 6 Superseded Latest is v6 →

lore
Share & tools
lore
#0 lore raw

cover Split BlockBackend off BDS with an axe

My last attempt got bogged down because I tried to do a reasonably complete job, and the complexity proved more than I could handle with the limited amount of uninterrupted time available. This time, I'm cutting BlockBackend off with an axe, leaving most of the work for later.

Done in this series already:

* Introduce a BlockBackend type, and lift up BlockDriverState's device_name, device_list, dev, dev_ops, dev_opaque. Much more remains to be lifted.

* Make BlockBackend own the DriveInfo.

* Wean hw/ off BlockDriverState, with two small exceptions.

* Fix blockdev-add not to create a bogus IDE drive (0,0).

* Take a few baby steps towards use of BlockBackend in monitor command code where appropriate.

Coming soon, hopefully:

* QMP command blockdev-del

* blockdev-add accepts node-name without id at top level

* Lift up more stuff

* More monitor command code BlockBackend use

Depends on my [PATCH 0/4] Block-related miscellaneous cleanups.

I know the diffstat looks intimidating. I tried very hard to split the patches so that the bigger ones do just one simple thing, and mostly mechanically.

Markus Armbruster (23):
block: Split bdrv_new_named() off bdrv_new()
block: New BlockBackend
block: Connect BlockBackend to BlockDriverState
block: Connect BlockBackend and DriveInfo
block: Make BlockBackend own its BlockDriverState
block: Eliminate bdrv_states, use block_next() instead
block: Eliminate bdrv_iterate(), use bdrv_next()
block: Eliminate BlockDriverState member device_name[]
block: Merge BlockBackend and BlockDriverState name spaces
block: Eliminate DriveInfo member bdrv, use blk_by_legacy_dinfo()
block: Rename BlockDriverAIOCB* to BlockAIOCB*
virtio-blk: Drop redundant VirtIOBlock member conf
virtio-blk: Rename VirtIOBlkConf variables to conf
hw: Convert from BlockDriverState to BlockBackend, mostly
ide: Complete conversion from BlockDriverState to BlockBackend
pc87312: Drop unused members of PC87312State
blockdev: Drop superfluous DriveInfo member id
blockdev: Fix blockdev-add not to create IDE drive (0,0)
blockdev: Drop DriveInfo member enable_auto_del block/qapi: Convert qmp_query_block() to BlockBackend
blockdev: Convert qmp_eject(), qmp_change_blockdev() to BlockBackend
block: Lift device model API into BlockBackend
block: Make device model's references to BlockBackend strong

 block-migration.c                        |  44 +--
 block.c                                  | 389 +++++++-------------
 block/Makefile.objs                      |   2 +-
 block/archipelago.c                      |  30 +-
 block/backup.c                           |   2 +-
 block/blkdebug.c                         |  22 +-
 block/blkverify.c                        |  20 +-
 block/block-backend.c                    | 588 +++++++++++++++++++++++++++++++
 block/commit.c                           |   2 +-
 block/cow.c                              |   2 +-
 block/curl.c                             |   8 +-
 block/iscsi.c                            |  10 +-
 block/linux-aio.c                        |   8 +-
 block/mirror.c                           |   9 +-
 block/qapi.c                             |  27 +-
 block/qcow.c                             |   4 +-
 block/qcow2.c                            |   4 +-
 block/qed-gencb.c                        |   4 +-
 block/qed-table.c                        |  10 +-
 block/qed.c                              |  48 +--
 block/qed.h                              |  12 +-
 block/quorum.c                           |  42 +--
 block/raw-aio.h                          |   8 +-
 block/raw-posix.c                        |  32 +-
 block/raw-win32.c                        |  16 +-
 block/raw_bsd.c                          |   8 +-
 block/rbd.c                              |  58 +--
 block/sheepdog.c                         |   4 +-
 block/stream.c                           |   2 +-
 block/vdi.c                              |   2 +-
 block/vhdx.c                             |   2 +-
 block/vmdk.c                             |   4 +-
 block/vpc.c                              |   2 +-
 block/vvfat.c                            |   4 +-
 block/win32-aio.c                        |   8 +-
 blockdev.c                               | 204 +++++------
 blockjob.c                               |   7 +-
 dma-helpers.c                            |  69 ++--
 hw/arm/collie.c                          |  10 +-
 hw/arm/gumstix.c                         |   6 +-
 hw/arm/highbank.c                        |   2 +-
 hw/arm/mainstone.c                       |   8 +-
 hw/arm/musicpal.c                        |  13 +-
 hw/arm/nseries.c                         |   7 +-
 hw/arm/omap1.c                           |   4 +-
 hw/arm/omap2.c                           |   4 +-
 hw/arm/omap_sx1.c                        |  10 +-
 hw/arm/pxa2xx.c                          |   7 +-
 hw/arm/realview.c                        |   2 +-
 hw/arm/spitz.c                           |   6 +-
 hw/arm/tosa.c                            |   3 +-
 hw/arm/versatilepb.c                     |   5 +-
 hw/arm/vexpress.c                        |   5 +-
 hw/arm/xilinx_zynq.c                     |   5 +-
 hw/arm/z2.c                              |   8 +-
 hw/block/block.c                         |  23 +-
 hw/block/dataplane/virtio-blk.c          |  35 +-
 hw/block/dataplane/virtio-blk.h          |   2 +-
 hw/block/fdc.c                           |  74 ++--
 hw/block/hd-geometry.c                   |  24 +-
 hw/block/m25p80.c                        |  31 +-
 hw/block/nand.c                          |  50 +--
 hw/block/nvme.c                          |  17 +-
 hw/block/nvme.h                          |   2 +-
 hw/block/onenand.c                       |  67 ++--
 hw/block/pflash_cfi01.c                  |  24 +-
 hw/block/pflash_cfi02.c                  |  24 +-
 hw/block/virtio-blk.c                    | 149 ++++----
 hw/block/xen_disk.c                      |  86 +++--
 hw/core/qdev-properties-system.c         |  26 +-
 hw/core/qdev-properties.c                |   2 +-
 hw/cris/axis_dev88.c                     |   4 +-
 hw/display/tc6393xb.c                    |   4 +-
 hw/i386/pc.c                             |   2 +-
 hw/i386/pc_piix.c                        |   2 +-
 hw/i386/pc_sysfw.c                       |  10 +-
 hw/i386/xen/xen_platform.c               |   5 +-
 hw/ide/ahci.c                            |  33 +-
 hw/ide/ahci.h                            |   2 +-
 hw/ide/atapi.c                           |  33 +-
 hw/ide/cmd646.c                          |   2 +-
 hw/ide/core.c                            | 206 ++++++-----
 hw/ide/ich.c                             |   2 +-
 hw/ide/internal.h                        |  16 +-
 hw/ide/isa.c                             |   2 +-
 hw/ide/macio.c                           |  54 +--
 hw/ide/microdrive.c                      |   4 +-
 hw/ide/mmio.c                            |   2 +-
 hw/ide/pci.c                             |   6 +-
 hw/ide/pci.h                             |   2 +-
 hw/ide/piix.c                            |   9 +-
 hw/ide/qdev.c                            |  13 +-
 hw/ide/via.c                             |   2 +-
 hw/isa/pc87312.c                         |   7 +-
 hw/lm32/lm32_boards.c                    |  14 +-
 hw/lm32/milkymist.c                      |   8 +-
 hw/microblaze/petalogix_ml605_mmu.c      |   6 +-
 hw/microblaze/petalogix_s3adsp1800_mmu.c |   6 +-
 hw/mips/mips_fulong2e.c                  |   2 +-
 hw/mips/mips_jazz.c                      |   2 +-
 hw/mips/mips_malta.c                     |   8 +-
 hw/mips/mips_r4k.c                       |   6 +-
 hw/nvram/spapr_nvram.c                   |  17 +-
 hw/pci/pci-hotplug-old.c                 |  10 +-
 hw/ppc/mac.h                             |   2 +-
 hw/ppc/mac_newworld.c                    |   2 +-
 hw/ppc/mac_oldworld.c                    |   2 +-
 hw/ppc/ppc405_boards.c                   |  27 +-
 hw/ppc/prep.c                            |   2 +-
 hw/ppc/spapr.c                           |   4 +-
 hw/ppc/virtex_ml507.c                    |   6 +-
 hw/s390x/s390-virtio-bus.c               |   2 +-
 hw/s390x/s390-virtio.c                   |   2 +-
 hw/s390x/virtio-ccw.c                    |   2 +-
 hw/scsi/megasas.c                        |  15 +-
 hw/scsi/scsi-bus.c                       |  11 +-
 hw/scsi/scsi-disk.c                      | 194 +++++-----
 hw/scsi/scsi-generic.c                   |  41 ++-
 hw/sd/milkymist-memcard.c                |   7 +-
 hw/sd/omap_mmc.c                         |   8 +-
 hw/sd/pl181.c                            |   3 +-
 hw/sd/pxa2xx_mmci.c                      |   4 +-
 hw/sd/sd.c                               |  60 ++--
 hw/sd/sdhci.c                            |   3 +-
 hw/sd/ssi-sd.c                           |   3 +-
 hw/sh4/r2d.c                             |   6 +-
 hw/sparc/sun4m.c                         |   2 +-
 hw/sparc64/sun4u.c                       |   2 +-
 hw/tpm/tpm_tis.c                         |   2 +-
 hw/tricore/tricore_testboard.c           |   2 +-
 hw/usb/dev-storage.c                     |  19 +-
 hw/virtio/virtio-pci.c                   |   2 +-
 hw/xen/xen_devconfig.c                   |   1 +
 hw/xenpv/xen_machine_pv.c                |   2 +-
 hw/xtensa/xtfpga.c                       |   5 +-
 include/block/aio.h                      |  12 +-
 include/block/block.h                    |  87 ++---
 include/block/block_int.h                |  46 +--
 include/block/blockjob.h                 |   4 +-
 include/block/qapi.h                     |   3 -
 include/block/thread-pool.h              |   4 +-
 include/hw/arm/omap.h                    |   4 +-
 include/hw/arm/pxa.h                     |   2 +-
 include/hw/block/block.h                 |   6 +-
 include/hw/block/flash.h                 |   6 +-
 include/hw/isa/pc87312.h                 |   3 -
 include/hw/qdev-properties.h             |   8 +-
 include/hw/scsi/scsi.h                   |   6 +-
 include/hw/sd.h                          |   2 +-
 include/hw/virtio/virtio-blk.h           |   9 +-
 include/monitor/monitor.h                |   4 +-
 include/qemu/typedefs.h                  |   2 +
 include/sysemu/block-backend.h           | 144 ++++++++
 include/sysemu/blockdev.h                |  12 +-
 include/sysemu/dma.h                     |  26 +-
 monitor.c                                |  39 +-
 qemu-img.c                               | 150 ++++----
 qemu-io.c                                |  15 +-
 qemu-nbd.c                               |   4 +-
 tests/test-thread-pool.c                 |   2 +-
 thread-pool.c                            |   8 +-
 trace-events                             |   8 +-
 162 files changed, 2317 insertions(+), 1701 deletions(-)
 create mode 100644 block/block-backend.c
 create mode 100644 include/sysemu/block-backend.h
Signature · 1 line
1.9.3
#1 lore raw

PATCH 1/23 block: Split bdrv_new_named() off bdrv_new()

Creating an anonymous BDS can't fail. Make that obvious.

---
 block.c               | 26 +++++++++++++++++++-------
 block/iscsi.c         |  2 +-
 block/vvfat.c         |  2 +-
 blockdev.c            |  2 +-
 hw/block/xen_disk.c   |  2 +-
 include/block/block.h |  3 ++-
 qemu-img.c            |  6 +++---
 qemu-io.c             |  2 +-
 qemu-nbd.c            |  2 +-
 9 files changed, 30 insertions(+), 17 deletions(-)
block.c +19 -7
index d06dd51..4b3bcd4 100644
@@ -335,10 +335,11 @@ void bdrv_register(BlockDriver *bdrv)
 }
 
 /* create a new block device (by default it is empty) */
-BlockDriverState *bdrv_new(const char *device_name, Error **errp)
+BlockDriverState *bdrv_new_named(const char *device_name, Error **errp)
 {
     BlockDriverState *bs;
-    int i;
+
+    assert(*device_name);
 
     if (bdrv_find(device_name)) {
         error_setg(errp, "Device with id '%s' already exists",
@@ -351,12 +352,23 @@ BlockDriverState *bdrv_new(const char *device_name, Error **errp)
         return NULL;
     }
 
-    bs = g_new0(BlockDriverState, 1);
-    QLIST_INIT(&bs->dirty_bitmaps);
+    bs = bdrv_new();
+
     pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
     if (device_name[0] != '\0') {
         QTAILQ_INSERT_TAIL(&bdrv_states, bs, device_list);
     }
+
+    return bs;
+}
+
+BlockDriverState *bdrv_new(void)
+{
+    BlockDriverState *bs;
+    int i;
+
+    bs = g_new0(BlockDriverState, 1);
+    QLIST_INIT(&bs->dirty_bitmaps);
     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
         QLIST_INIT(&bs->op_blockers[i]);
     }
@@ -1217,7 +1229,7 @@ int bdrv_open_backing_file(BlockDriverState *bs, QDict *options, Error **errp)
         goto free_exit;
     }
 
-    backing_hd = bdrv_new("", errp);
+    backing_hd = bdrv_new();
 
     if (bs->backing_format[0] != '\0') {
         back_drv = bdrv_find_format(bs->backing_format);
@@ -1346,7 +1358,7 @@ int bdrv_append_temp_snapshot(BlockDriverState *bs, int flags, Error **errp)
     qdict_put(snapshot_options, "file.filename",
               qstring_from_str(tmp_filename));
 
-    bs_snapshot = bdrv_new("", &error_abort);
+    bs_snapshot = bdrv_new();
 
     ret = bdrv_open(&bs_snapshot, NULL, NULL, snapshot_options,
                     flags, bdrv_qcow2, &local_err);
@@ -1417,7 +1429,7 @@ int bdrv_open(BlockDriverState **pbs, const char *filename,
     if (*pbs) {
         bs = *pbs;
     } else {
-        bs = bdrv_new("", &error_abort);
+        bs = bdrv_new();
     }
 
     /* NULL means an empty set of options */
block/iscsi.c +1 -1
index 3e19202..af3d0f6 100644
@@ -1528,7 +1528,7 @@ static int iscsi_create(const char *filename, QemuOpts *opts, Error **errp)
     IscsiLun *iscsilun = NULL;
     QDict *bs_options;
 
-    bs = bdrv_new("", &error_abort);
+    bs = bdrv_new();
 
     /* Read out options */
     total_size =
block/vvfat.c +1 -1
index 731e591..6c9fde0 100644
@@ -2939,7 +2939,7 @@ static int enable_write_target(BDRVVVFATState *s, Error **errp)
     unlink(s->qcow_filename);
 #endif
 
-    bdrv_set_backing_hd(s->bs, bdrv_new("", &error_abort));
+    bdrv_set_backing_hd(s->bs, bdrv_new());
     s->bs->backing_hd->drv = &vvfat_write_target;
     s->bs->backing_hd->opaque = g_new(void *, 1);
     *(void**)s->bs->backing_hd->opaque = s;
blockdev.c +1 -1
index e919566..9fbd888 100644
@@ -458,7 +458,7 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
     /* init */
     dinfo = g_malloc0(sizeof(*dinfo));
     dinfo->id = g_strdup(qemu_opts_id(opts));
-    dinfo->bdrv = bdrv_new(dinfo->id, &error);
+    dinfo->bdrv = bdrv_new_named(dinfo->id, &error);
     if (error) {
         error_propagate(errp, error);
         goto bdrv_new_err;
hw/block/xen_disk.c +1 -1
index 2dcef07..8bac7ff 100644
@@ -856,7 +856,7 @@ static int blk_connect(struct XenDevice *xendev)
 
         /* setup via xenbus -> create new block driver instance */
         xen_be_printf(&blkdev->xendev, 2, "create new bdrv (xenbus setup)\n");
-        blkdev->bs = bdrv_new(blkdev->dev, NULL);
+        blkdev->bs = bdrv_new_named(blkdev->dev, NULL);
         if (!blkdev->bs) {
             return -1;
         }
include/block/block.h +2 -1
index 8f4ad16..95139c0 100644
@@ -203,7 +203,8 @@ BlockDriver *bdrv_find_whitelisted_format(const char *format_name,
 int bdrv_create(BlockDriver *drv, const char* filename,
                 QemuOpts *opts, Error **errp);
 int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp);
-BlockDriverState *bdrv_new(const char *device_name, Error **errp);
+BlockDriverState *bdrv_new_named(const char *device_name, Error **errp);
+BlockDriverState *bdrv_new(void);
 void bdrv_make_anon(BlockDriverState *bs);
 void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old);
 void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top);
qemu-img.c +3 -3
index 91d1ac3..4490a22 100644
@@ -296,7 +296,7 @@ static BlockDriverState *bdrv_new_open(const char *id,
     Error *local_err = NULL;
     int ret;
 
-    bs = bdrv_new(id, &error_abort);
+    bs = bdrv_new_named(id, &error_abort);
 
     if (fmt) {
         drv = bdrv_find_format(fmt);
@@ -2425,7 +2425,7 @@ static int img_rebase(int argc, char **argv)
     if (!unsafe) {
         char backing_name[1024];
 
-        bs_old_backing = bdrv_new("old_backing", &error_abort);
+        bs_old_backing = bdrv_new_named("old_backing", &error_abort);
         bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
         ret = bdrv_open(&bs_old_backing, backing_name, NULL, NULL, src_flags,
                         old_backing_drv, &local_err);
@@ -2436,7 +2436,7 @@ static int img_rebase(int argc, char **argv)
             goto out;
         }
         if (out_baseimg[0]) {
-            bs_new_backing = bdrv_new("new_backing", &error_abort);
+            bs_new_backing = bdrv_new_named("new_backing", &error_abort);
             ret = bdrv_open(&bs_new_backing, out_baseimg, NULL, NULL, src_flags,
                             new_backing_drv, &local_err);
             if (ret) {
qemu-io.c +1 -1
index d2ab694..44c2e1c 100644
@@ -58,7 +58,7 @@ static int openfile(char *name, int flags, int growable, QDict *opts)
         return 1;
     }
 
-    qemuio_bs = bdrv_new("hda", &error_abort);
+    qemuio_bs = bdrv_new_named("hda", &error_abort);
 
     if (growable) {
         flags |= BDRV_O_PROTOCOL;
qemu-nbd.c +1 -1
index 9bc152e..a56ebfc 100644
@@ -687,7 +687,7 @@ int main(int argc, char **argv)
         drv = NULL;
     }
 
-    bs = bdrv_new("hda", &error_abort);
+    bs = bdrv_new_named("hda", &error_abort);
 
     srcpath = argv[optind];
     ret = bdrv_open(&bs, srcpath, NULL, NULL, flags, drv, &local_err);
Signature · 1 line
1.9.3
#2 lore raw

Re: [Qemu-devel] [PATCH 01/23] block: Split bdrv_new_named() off bdrv_new()

Quoted 20 lines · Markus Armbruster

Creating an anonymous BDS can't fail. Make that obvious.

---
 block.c               | 26 +++++++++++++++++++-------
 block/iscsi.c         |  2 +-
 block/vvfat.c         |  2 +-
 blockdev.c            |  2 +-
 hw/block/xen_disk.c   |  2 +-
 include/block/block.h |  3 ++-
 qemu-img.c            |  6 +++---
 qemu-io.c             |  2 +-
 qemu-nbd.c            |  2 +-
 9 files changed, 30 insertions(+), 17 deletions(-)
block.c +0 -0
index d06dd51..4b3bcd4 100644

block.c void bdrv_register(BlockDriver *bdrv) · line 342

Quoted 10 lines
block.c +3 -2
@@ -335,10 +335,11 @@ void bdrv_register(BlockDriver *bdrv)
 }
 
 /* create a new block device (by default it is empty) */
-BlockDriverState *bdrv_new(const char *device_name, Error **errp)
+BlockDriverState *bdrv_new_named(const char *device_name, Error **errp)
 {
     BlockDriverState *bs;
-    int i;
+
+    assert(*device_name);

This assert that device_name is not a null pointer.
But here we are pretty sure that the BDS should be named given the name of the function. Should we bake an assert on device_name[0] != '\0' to avoid bdrv_new_named being called with "" as device_name ?

Quoted 4 lines
block.c +0 -0
     if (bdrv_find(device_name)) {
         error_setg(errp, "Device with id '%s' already exists",

block.c BlockDriverState *bdrv_new(const char *device_name, Error **errp) · line 359

Quoted 10 lines
block.c +2 -2
@@ -351,12 +352,23 @@ BlockDriverState *bdrv_new(const char *device_name, Error **errp)
         return NULL;
     }
 
-    bs = g_new0(BlockDriverState, 1);
-    QLIST_INIT(&bs->dirty_bitmaps);
+    bs = bdrv_new();
+
     pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
 
     if (device_name[0] != '\0') {

Then we could remove this test.

block.c BlockDriverState *bdrv_new(const char *device_name, Error **errp) · line 359

Quoted 1 line
block.c +0 -0
         QTAILQ_INSERT_TAIL(&bdrv_states, bs, device_list);

Because here would be too late anyway: an unammed BDS would have been created if device_name == "".

Quoted 169 lines
block.c +11 -0
     }
+
+    return bs;
+}
+
+BlockDriverState *bdrv_new(void)
+{
+    BlockDriverState *bs;
+    int i;
+
+    bs = g_new0(BlockDriverState, 1);
+    QLIST_INIT(&bs->dirty_bitmaps);
     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
         QLIST_INIT(&bs->op_blockers[i]);
     }
block.c +3 -3
@@ -1217,7 +1229,7 @@ int bdrv_open_backing_file(BlockDriverState *bs, QDict *options, Error **errp)
         goto free_exit;
     }
 
-    backing_hd = bdrv_new("", errp);
+    backing_hd = bdrv_new();
 
     if (bs->backing_format[0] != '\0') {
         back_drv = bdrv_find_format(bs->backing_format);
@@ -1346,7 +1358,7 @@ int bdrv_append_temp_snapshot(BlockDriverState *bs, int flags, Error **errp)
     qdict_put(snapshot_options, "file.filename",
               qstring_from_str(tmp_filename));
 
-    bs_snapshot = bdrv_new("", &error_abort);
+    bs_snapshot = bdrv_new();
 
     ret = bdrv_open(&bs_snapshot, NULL, NULL, snapshot_options,
                     flags, bdrv_qcow2, &local_err);
@@ -1417,7 +1429,7 @@ int bdrv_open(BlockDriverState **pbs, const char *filename,
     if (*pbs) {
         bs = *pbs;
     } else {
-        bs = bdrv_new("", &error_abort);
+        bs = bdrv_new();
     }
 
     /* NULL means an empty set of options */
block/iscsi.c +1 -1
index 3e19202..af3d0f6 100644
@@ -1528,7 +1528,7 @@ static int iscsi_create(const char *filename, QemuOpts *opts, Error **errp)
     IscsiLun *iscsilun = NULL;
     QDict *bs_options;
 
-    bs = bdrv_new("", &error_abort);
+    bs = bdrv_new();
 
     /* Read out options */
     total_size =
block/vvfat.c +1 -1
index 731e591..6c9fde0 100644
@@ -2939,7 +2939,7 @@ static int enable_write_target(BDRVVVFATState *s, Error **errp)
     unlink(s->qcow_filename);
 #endif
 
-    bdrv_set_backing_hd(s->bs, bdrv_new("", &error_abort));
+    bdrv_set_backing_hd(s->bs, bdrv_new());
     s->bs->backing_hd->drv = &vvfat_write_target;
     s->bs->backing_hd->opaque = g_new(void *, 1);
     *(void**)s->bs->backing_hd->opaque = s;
blockdev.c +1 -1
index e919566..9fbd888 100644
@@ -458,7 +458,7 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
     /* init */
     dinfo = g_malloc0(sizeof(*dinfo));
     dinfo->id = g_strdup(qemu_opts_id(opts));
-    dinfo->bdrv = bdrv_new(dinfo->id, &error);
+    dinfo->bdrv = bdrv_new_named(dinfo->id, &error);
     if (error) {
         error_propagate(errp, error);
         goto bdrv_new_err;
hw/block/xen_disk.c +1 -1
index 2dcef07..8bac7ff 100644
@@ -856,7 +856,7 @@ static int blk_connect(struct XenDevice *xendev)
 
         /* setup via xenbus -> create new block driver instance */
         xen_be_printf(&blkdev->xendev, 2, "create new bdrv (xenbus setup)\n");
-        blkdev->bs = bdrv_new(blkdev->dev, NULL);
+        blkdev->bs = bdrv_new_named(blkdev->dev, NULL);
         if (!blkdev->bs) {
             return -1;
         }
include/block/block.h +2 -1
index 8f4ad16..95139c0 100644
@@ -203,7 +203,8 @@ BlockDriver *bdrv_find_whitelisted_format(const char *format_name,
 int bdrv_create(BlockDriver *drv, const char* filename,
                 QemuOpts *opts, Error **errp);
 int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp);
-BlockDriverState *bdrv_new(const char *device_name, Error **errp);
+BlockDriverState *bdrv_new_named(const char *device_name, Error **errp);
+BlockDriverState *bdrv_new(void);
 void bdrv_make_anon(BlockDriverState *bs);
 void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old);
 void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top);
qemu-img.c +3 -3
index 91d1ac3..4490a22 100644
@@ -296,7 +296,7 @@ static BlockDriverState *bdrv_new_open(const char *id,
     Error *local_err = NULL;
     int ret;
 
-    bs = bdrv_new(id, &error_abort);
+    bs = bdrv_new_named(id, &error_abort);
 
     if (fmt) {
         drv = bdrv_find_format(fmt);
@@ -2425,7 +2425,7 @@ static int img_rebase(int argc, char **argv)
     if (!unsafe) {
         char backing_name[1024];
 
-        bs_old_backing = bdrv_new("old_backing", &error_abort);
+        bs_old_backing = bdrv_new_named("old_backing", &error_abort);
         bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
         ret = bdrv_open(&bs_old_backing, backing_name, NULL, NULL, src_flags,
                         old_backing_drv, &local_err);
@@ -2436,7 +2436,7 @@ static int img_rebase(int argc, char **argv)
             goto out;
         }
         if (out_baseimg[0]) {
-            bs_new_backing = bdrv_new("new_backing", &error_abort);
+            bs_new_backing = bdrv_new_named("new_backing", &error_abort);
             ret = bdrv_open(&bs_new_backing, out_baseimg, NULL, NULL, src_flags,
                             new_backing_drv, &local_err);
             if (ret) {
qemu-io.c +1 -1
index d2ab694..44c2e1c 100644
@@ -58,7 +58,7 @@ static int openfile(char *name, int flags, int growable, QDict *opts)
         return 1;
     }
 
-    qemuio_bs = bdrv_new("hda", &error_abort);
+    qemuio_bs = bdrv_new_named("hda", &error_abort);
 
     if (growable) {
         flags |= BDRV_O_PROTOCOL;
qemu-nbd.c +1 -1
index 9bc152e..a56ebfc 100644
@@ -687,7 +687,7 @@ int main(int argc, char **argv)
         drv = NULL;
     }
 
-    bs = bdrv_new("hda", &error_abort);
+    bs = bdrv_new_named("hda", &error_abort);
 
     srcpath = argv[optind];
     ret = bdrv_open(&bs, srcpath, NULL, NULL, flags, drv, &local_err);
Signature · 1 line
1.9.3
#3 lore raw

Re: [Qemu-devel] [PATCH 01/23] block: Split bdrv_new_named() off bdrv_new()

Quoted 6 lines · Benoît Canet
Quoted 4 lines · Markus Armbruster

Creating an anonymous BDS can't fail. Make that obvious.

---

Quoted 10 lines

block.c void bdrv_register(BlockDriver *bdrv) · line 342

Quoted 8 lines

/* create a new block device (by default it is empty) */

block.c +3 -2
-BlockDriverState *bdrv_new(const char *device_name, Error **errp)
+BlockDriverState *bdrv_new_named(const char *device_name, Error **errp)
 {
     BlockDriverState *bs;
-    int i;
+
+    assert(*device_name);

This assert that device_name is not a null pointer.

No, it assumes that device_name is non-NULL and blindly dereferences it; it is asserting that the first byte of the dereferenced pointer is not NUL.

Quoted 3 lines

But here we are pretty sure that the BDS should be named given the name of the function. Should we bake an assert on device_name[0] != '\0' to avoid bdrv_new_named being called with "" as device_name ?

That's already what the code does. About the only thing it could do differently is:

assert(device_name && *device_name);

Signature · 2 lines
Eric Blake   eblake redhat com    +1-919-301-3266
Libvirt virtualization library http://libvirt.org
#4 lore raw

Re: [Qemu-devel] [PATCH 01/23] block: Split bdrv_new_named() off bdrv_new()

Quoted 27 lines · Eric Blake
Quoted 6 lines · Benoît Canet
Quoted 4 lines · Markus Armbruster

Creating an anonymous BDS can't fail. Make that obvious.

---

Quoted 10 lines

block.c void bdrv_register(BlockDriver *bdrv) · line 342

Quoted 8 lines

/* create a new block device (by default it is empty) */

block.c +3 -2
-BlockDriverState *bdrv_new(const char *device_name, Error **errp)
+BlockDriverState *bdrv_new_named(const char *device_name, Error **errp)
 {
     BlockDriverState *bs;
-    int i;
+
+    assert(*device_name);

This assert that device_name is not a null pointer.

No, it assumes that device_name is non-NULL and blindly dereferences it; it is asserting that the first byte of the dereferenced pointer is not NUL.

Quoted 5 lines

But here we are pretty sure that the BDS should be named given the name of the function.
Should we bake an assert on device_name[0] != '\0' to avoid bdrv_new_named being called
with "" as device_name ?

Quoted 4 lines

That's already what the code does. About the only thing it could do differently is:

assert(device_name && *device_name);

Converts a crash into an assertion failure. No difference to me, but if you guys think it's a worthwhile improvement...

#5 lore raw

Re: [Qemu-devel] [PATCH 01/23] block: Split bdrv_new_named() off bdrv_new()

In reply to Benoît Canet
Quoted 52 lines · Benoît Canet
Quoted 20 lines · Markus Armbruster

Creating an anonymous BDS can't fail. Make that obvious.

---
 block.c               | 26 +++++++++++++++++++-------
 block/iscsi.c         |  2 +-
 block/vvfat.c         |  2 +-
 blockdev.c            |  2 +-
 hw/block/xen_disk.c   |  2 +-
 include/block/block.h |  3 ++-
 qemu-img.c            |  6 +++---
 qemu-io.c             |  2 +-
 qemu-nbd.c            |  2 +-
 9 files changed, 30 insertions(+), 17 deletions(-)
block.c +0 -0
index d06dd51..4b3bcd4 100644

block.c void bdrv_register(BlockDriver *bdrv) · line 342

Quoted 10 lines
block.c +3 -2
@@ -335,10 +335,11 @@ void bdrv_register(BlockDriver *bdrv)
 }
 
 /* create a new block device (by default it is empty) */
-BlockDriverState *bdrv_new(const char *device_name, Error **errp)
+BlockDriverState *bdrv_new_named(const char *device_name, Error **errp)
 {
     BlockDriverState *bs;
-    int i;
+
+    assert(*device_name);

This assert that device_name is not a null pointer.
But here we are pretty sure that the BDS should be named given the name of the function.
Should we bake an assert on device_name[0] != '\0' to avoid bdrv_new_named being called
with "" as device_name ?

Quoted 12 lines
block.c +2 -2
     if (bdrv_find(device_name)) {
         error_setg(errp, "Device with id '%s' already exists",
@@ -351,12 +352,23 @@ BlockDriverState *bdrv_new(const char *device_name, Error **errp)
         return NULL;
     }
 
-    bs = g_new0(BlockDriverState, 1);
-    QLIST_INIT(&bs->dirty_bitmaps);
+    bs = bdrv_new();
+
     pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
Quoted 6 lines

block.c BlockDriverState *bdrv_new(const char *device_name, Error **errp) · line 358

Quoted 1 line
block.c +0 -0
     if (device_name[0] != '\0') {

Then we could remove this test.

block.c BlockDriverState *bdrv_new(const char *device_name, Error **errp) · line 359

Quoted 1 line
block.c +0 -0
         QTAILQ_INSERT_TAIL(&bdrv_states, bs, device_list);

Because here would be too late anyway: an unammed BDS would have been created if device_name == "".

Short answer: not worth it, the function goes away in PATCH 08, and its replacement works like you suggest.

Slightly longer answer: PATCH 02 adds BlockBackend, which also checks device names. blk_new() does it the way you suggest. PATCH 08 removes the now redundant BlockDriverState device name, including this function.

[...]

Reviewed-by on v1 1/23
#6 lore raw

Re: [Qemu-devel] [PATCH 01/23] block: Split bdrv_new_named() off bdrv_new()

In reply to Markus Armbruster
Quoted 14 lines · Markus Armbruster

Creating an anonymous BDS can't fail. Make that obvious.

---
 block.c               | 26 +++++++++++++++++++-------
 block/iscsi.c         |  2 +-
 block/vvfat.c         |  2 +-
 blockdev.c            |  2 +-
 hw/block/xen_disk.c   |  2 +-
 include/block/block.h |  3 ++-
 qemu-img.c            |  6 +++---
 qemu-io.c             |  2 +-
 qemu-nbd.c            |  2 +-
 9 files changed, 30 insertions(+), 17 deletions(-)
Signature · 2 lines
Eric Blake   eblake redhat com    +1-919-301-3266
Libvirt virtualization library http://libvirt.org
Reviewed-by on v1 1/23
#7 lore raw

Re: [Qemu-devel] [PATCH 01/23] block: Split bdrv_new_named() off bdrv_new()

In reply to Markus Armbruster
Quoted 212 lines · Markus Armbruster

Creating an anonymous BDS can't fail. Make that obvious.

---
 block.c               | 26 +++++++++++++++++++-------
 block/iscsi.c         |  2 +-
 block/vvfat.c         |  2 +-
 blockdev.c            |  2 +-
 hw/block/xen_disk.c   |  2 +-
 include/block/block.h |  3 ++-
 qemu-img.c            |  6 +++---
 qemu-io.c             |  2 +-
 qemu-nbd.c            |  2 +-
 9 files changed, 30 insertions(+), 17 deletions(-)
block.c +19 -7
index d06dd51..4b3bcd4 100644
@@ -335,10 +335,11 @@ void bdrv_register(BlockDriver *bdrv)
 }
 
 /* create a new block device (by default it is empty) */
-BlockDriverState *bdrv_new(const char *device_name, Error **errp)
+BlockDriverState *bdrv_new_named(const char *device_name, Error **errp)
 {
     BlockDriverState *bs;
-    int i;
+
+    assert(*device_name);
 
     if (bdrv_find(device_name)) {
         error_setg(errp, "Device with id '%s' already exists",
@@ -351,12 +352,23 @@ BlockDriverState *bdrv_new(const char *device_name, Error **errp)
         return NULL;
     }
 
-    bs = g_new0(BlockDriverState, 1);
-    QLIST_INIT(&bs->dirty_bitmaps);
+    bs = bdrv_new();
+
     pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
     if (device_name[0] != '\0') {
         QTAILQ_INSERT_TAIL(&bdrv_states, bs, device_list);
     }
+
+    return bs;
+}
+
+BlockDriverState *bdrv_new(void)
+{
+    BlockDriverState *bs;
+    int i;
+
+    bs = g_new0(BlockDriverState, 1);
+    QLIST_INIT(&bs->dirty_bitmaps);
     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
         QLIST_INIT(&bs->op_blockers[i]);
     }
@@ -1217,7 +1229,7 @@ int bdrv_open_backing_file(BlockDriverState *bs, QDict *options, Error **errp)
         goto free_exit;
     }
 
-    backing_hd = bdrv_new("", errp);
+    backing_hd = bdrv_new();
 
     if (bs->backing_format[0] != '\0') {
         back_drv = bdrv_find_format(bs->backing_format);
@@ -1346,7 +1358,7 @@ int bdrv_append_temp_snapshot(BlockDriverState *bs, int flags, Error **errp)
     qdict_put(snapshot_options, "file.filename",
               qstring_from_str(tmp_filename));
 
-    bs_snapshot = bdrv_new("", &error_abort);
+    bs_snapshot = bdrv_new();
 
     ret = bdrv_open(&bs_snapshot, NULL, NULL, snapshot_options,
                     flags, bdrv_qcow2, &local_err);
@@ -1417,7 +1429,7 @@ int bdrv_open(BlockDriverState **pbs, const char *filename,
     if (*pbs) {
         bs = *pbs;
     } else {
-        bs = bdrv_new("", &error_abort);
+        bs = bdrv_new();
     }
 
     /* NULL means an empty set of options */
block/iscsi.c +1 -1
index 3e19202..af3d0f6 100644
@@ -1528,7 +1528,7 @@ static int iscsi_create(const char *filename, QemuOpts *opts, Error **errp)
     IscsiLun *iscsilun = NULL;
     QDict *bs_options;
 
-    bs = bdrv_new("", &error_abort);
+    bs = bdrv_new();
 
     /* Read out options */
     total_size =
block/vvfat.c +1 -1
index 731e591..6c9fde0 100644
@@ -2939,7 +2939,7 @@ static int enable_write_target(BDRVVVFATState *s, Error **errp)
     unlink(s->qcow_filename);
 #endif
 
-    bdrv_set_backing_hd(s->bs, bdrv_new("", &error_abort));
+    bdrv_set_backing_hd(s->bs, bdrv_new());
     s->bs->backing_hd->drv = &vvfat_write_target;
     s->bs->backing_hd->opaque = g_new(void *, 1);
     *(void**)s->bs->backing_hd->opaque = s;
blockdev.c +1 -1
index e919566..9fbd888 100644
@@ -458,7 +458,7 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
     /* init */
     dinfo = g_malloc0(sizeof(*dinfo));
     dinfo->id = g_strdup(qemu_opts_id(opts));
-    dinfo->bdrv = bdrv_new(dinfo->id, &error);
+    dinfo->bdrv = bdrv_new_named(dinfo->id, &error);
     if (error) {
         error_propagate(errp, error);
         goto bdrv_new_err;
hw/block/xen_disk.c +1 -1
index 2dcef07..8bac7ff 100644
@@ -856,7 +856,7 @@ static int blk_connect(struct XenDevice *xendev)
 
         /* setup via xenbus -> create new block driver instance */
         xen_be_printf(&blkdev->xendev, 2, "create new bdrv (xenbus setup)\n");
-        blkdev->bs = bdrv_new(blkdev->dev, NULL);
+        blkdev->bs = bdrv_new_named(blkdev->dev, NULL);
         if (!blkdev->bs) {
             return -1;
         }
include/block/block.h +2 -1
index 8f4ad16..95139c0 100644
@@ -203,7 +203,8 @@ BlockDriver *bdrv_find_whitelisted_format(const char *format_name,
 int bdrv_create(BlockDriver *drv, const char* filename,
                 QemuOpts *opts, Error **errp);
 int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp);
-BlockDriverState *bdrv_new(const char *device_name, Error **errp);
+BlockDriverState *bdrv_new_named(const char *device_name, Error **errp);
+BlockDriverState *bdrv_new(void);
 void bdrv_make_anon(BlockDriverState *bs);
 void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old);
 void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top);
qemu-img.c +3 -3
index 91d1ac3..4490a22 100644
@@ -296,7 +296,7 @@ static BlockDriverState *bdrv_new_open(const char *id,
     Error *local_err = NULL;
     int ret;
 
-    bs = bdrv_new(id, &error_abort);
+    bs = bdrv_new_named(id, &error_abort);
 
     if (fmt) {
         drv = bdrv_find_format(fmt);
@@ -2425,7 +2425,7 @@ static int img_rebase(int argc, char **argv)
     if (!unsafe) {
         char backing_name[1024];
 
-        bs_old_backing = bdrv_new("old_backing", &error_abort);
+        bs_old_backing = bdrv_new_named("old_backing", &error_abort);
         bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
         ret = bdrv_open(&bs_old_backing, backing_name, NULL, NULL, src_flags,
                         old_backing_drv, &local_err);
@@ -2436,7 +2436,7 @@ static int img_rebase(int argc, char **argv)
             goto out;
         }
         if (out_baseimg[0]) {
-            bs_new_backing = bdrv_new("new_backing", &error_abort);
+            bs_new_backing = bdrv_new_named("new_backing", &error_abort);
             ret = bdrv_open(&bs_new_backing, out_baseimg, NULL, NULL, src_flags,
                             new_backing_drv, &local_err);
             if (ret) {
qemu-io.c +1 -1
index d2ab694..44c2e1c 100644
@@ -58,7 +58,7 @@ static int openfile(char *name, int flags, int growable, QDict *opts)
         return 1;
     }
 
-    qemuio_bs = bdrv_new("hda", &error_abort);
+    qemuio_bs = bdrv_new_named("hda", &error_abort);
 
     if (growable) {
         flags |= BDRV_O_PROTOCOL;
qemu-nbd.c +1 -1
index 9bc152e..a56ebfc 100644
@@ -687,7 +687,7 @@ int main(int argc, char **argv)
         drv = NULL;
     }
 
-    bs = bdrv_new("hda", &error_abort);
+    bs = bdrv_new_named("hda", &error_abort);
 
     srcpath = argv[optind];
     ret = bdrv_open(&bs, srcpath, NULL, NULL, flags, drv, &local_err);
Signature · 1 line
1.9.3
#8 lore raw

Re: [Qemu-devel] [PATCH 01/23] block: Split bdrv_new_named() off bdrv_new()

In reply to Markus Armbruster
Quoted 34 lines · Markus Armbruster

Creating an anonymous BDS can't fail. Make that obvious.

---
 block.c               | 26 +++++++++++++++++++-------
 block/iscsi.c         |  2 +-
 block/vvfat.c         |  2 +-
 blockdev.c            |  2 +-
 hw/block/xen_disk.c   |  2 +-
 include/block/block.h |  3 ++-
 qemu-img.c            |  6 +++---
 qemu-io.c             |  2 +-
 qemu-nbd.c            |  2 +-
 9 files changed, 30 insertions(+), 17 deletions(-)
block.c +3 -2
index d06dd51..4b3bcd4 100644
@@ -335,10 +335,11 @@ void bdrv_register(BlockDriver *bdrv)
 }
 
 /* create a new block device (by default it is empty) */
-BlockDriverState *bdrv_new(const char *device_name, Error **errp)
+BlockDriverState *bdrv_new_named(const char *device_name, Error **errp)
 {
     BlockDriverState *bs;
-    int i;
+
+    assert(*device_name);
 
     if (bdrv_find(device_name)) {
         error_setg(errp, "Device with id '%s' already exists",

block.c BlockDriverState *bdrv_new(const char *device_name, Error **errp) · line 358

Quoted 9 lines
block.c +2 -2
@@ -351,12 +352,23 @@ BlockDriverState *bdrv_new(const char *device_name, Error **errp)
         return NULL;
     }
 
-    bs = g_new0(BlockDriverState, 1);
-    QLIST_INIT(&bs->dirty_bitmaps);
+    bs = bdrv_new();
+
     pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
     if (device_name[0] != '\0') {

If finally understood why I said crap about the above assert. If *device_name is true then device_name[0] != '\0' is true. I diagnosed it in reverse.

I think we can remove the if up here the code will be simpler.

Quoted 169 lines
block.c +14 -3
         QTAILQ_INSERT_TAIL(&bdrv_states, bs, device_list);
     }
+
+    return bs;
+}
+
+BlockDriverState *bdrv_new(void)
+{
+    BlockDriverState *bs;
+    int i;
+
+    bs = g_new0(BlockDriverState, 1);
+    QLIST_INIT(&bs->dirty_bitmaps);
     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
         QLIST_INIT(&bs->op_blockers[i]);
     }
@@ -1217,7 +1229,7 @@ int bdrv_open_backing_file(BlockDriverState *bs, QDict *options, Error **errp)
         goto free_exit;
     }
 
-    backing_hd = bdrv_new("", errp);
+    backing_hd = bdrv_new();
 
     if (bs->backing_format[0] != '\0') {
         back_drv = bdrv_find_format(bs->backing_format);
@@ -1346,7 +1358,7 @@ int bdrv_append_temp_snapshot(BlockDriverState *bs, int flags, Error **errp)
     qdict_put(snapshot_options, "file.filename",
               qstring_from_str(tmp_filename));
 
-    bs_snapshot = bdrv_new("", &error_abort);
+    bs_snapshot = bdrv_new();
 
     ret = bdrv_open(&bs_snapshot, NULL, NULL, snapshot_options,
                     flags, bdrv_qcow2, &local_err);
@@ -1417,7 +1429,7 @@ int bdrv_open(BlockDriverState **pbs, const char *filename,
     if (*pbs) {
         bs = *pbs;
     } else {
-        bs = bdrv_new("", &error_abort);
+        bs = bdrv_new();
     }
 
     /* NULL means an empty set of options */
block/iscsi.c +1 -1
index 3e19202..af3d0f6 100644
@@ -1528,7 +1528,7 @@ static int iscsi_create(const char *filename, QemuOpts *opts, Error **errp)
     IscsiLun *iscsilun = NULL;
     QDict *bs_options;
 
-    bs = bdrv_new("", &error_abort);
+    bs = bdrv_new();
 
     /* Read out options */
     total_size =
block/vvfat.c +1 -1
index 731e591..6c9fde0 100644
@@ -2939,7 +2939,7 @@ static int enable_write_target(BDRVVVFATState *s, Error **errp)
     unlink(s->qcow_filename);
 #endif
 
-    bdrv_set_backing_hd(s->bs, bdrv_new("", &error_abort));
+    bdrv_set_backing_hd(s->bs, bdrv_new());
     s->bs->backing_hd->drv = &vvfat_write_target;
     s->bs->backing_hd->opaque = g_new(void *, 1);
     *(void**)s->bs->backing_hd->opaque = s;
blockdev.c +1 -1
index e919566..9fbd888 100644
@@ -458,7 +458,7 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
     /* init */
     dinfo = g_malloc0(sizeof(*dinfo));
     dinfo->id = g_strdup(qemu_opts_id(opts));
-    dinfo->bdrv = bdrv_new(dinfo->id, &error);
+    dinfo->bdrv = bdrv_new_named(dinfo->id, &error);
     if (error) {
         error_propagate(errp, error);
         goto bdrv_new_err;
hw/block/xen_disk.c +1 -1
index 2dcef07..8bac7ff 100644
@@ -856,7 +856,7 @@ static int blk_connect(struct XenDevice *xendev)
 
         /* setup via xenbus -> create new block driver instance */
         xen_be_printf(&blkdev->xendev, 2, "create new bdrv (xenbus setup)\n");
-        blkdev->bs = bdrv_new(blkdev->dev, NULL);
+        blkdev->bs = bdrv_new_named(blkdev->dev, NULL);
         if (!blkdev->bs) {
             return -1;
         }
include/block/block.h +2 -1
index 8f4ad16..95139c0 100644
@@ -203,7 +203,8 @@ BlockDriver *bdrv_find_whitelisted_format(const char *format_name,
 int bdrv_create(BlockDriver *drv, const char* filename,
                 QemuOpts *opts, Error **errp);
 int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp);
-BlockDriverState *bdrv_new(const char *device_name, Error **errp);
+BlockDriverState *bdrv_new_named(const char *device_name, Error **errp);
+BlockDriverState *bdrv_new(void);
 void bdrv_make_anon(BlockDriverState *bs);
 void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old);
 void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top);
qemu-img.c +3 -3
index 91d1ac3..4490a22 100644
@@ -296,7 +296,7 @@ static BlockDriverState *bdrv_new_open(const char *id,
     Error *local_err = NULL;
     int ret;
 
-    bs = bdrv_new(id, &error_abort);
+    bs = bdrv_new_named(id, &error_abort);
 
     if (fmt) {
         drv = bdrv_find_format(fmt);
@@ -2425,7 +2425,7 @@ static int img_rebase(int argc, char **argv)
     if (!unsafe) {
         char backing_name[1024];
 
-        bs_old_backing = bdrv_new("old_backing", &error_abort);
+        bs_old_backing = bdrv_new_named("old_backing", &error_abort);
         bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
         ret = bdrv_open(&bs_old_backing, backing_name, NULL, NULL, src_flags,
                         old_backing_drv, &local_err);
@@ -2436,7 +2436,7 @@ static int img_rebase(int argc, char **argv)
             goto out;
         }
         if (out_baseimg[0]) {
-            bs_new_backing = bdrv_new("new_backing", &error_abort);
+            bs_new_backing = bdrv_new_named("new_backing", &error_abort);
             ret = bdrv_open(&bs_new_backing, out_baseimg, NULL, NULL, src_flags,
                             new_backing_drv, &local_err);
             if (ret) {
qemu-io.c +1 -1
index d2ab694..44c2e1c 100644
@@ -58,7 +58,7 @@ static int openfile(char *name, int flags, int growable, QDict *opts)
         return 1;
     }
 
-    qemuio_bs = bdrv_new("hda", &error_abort);
+    qemuio_bs = bdrv_new_named("hda", &error_abort);
 
     if (growable) {
         flags |= BDRV_O_PROTOCOL;
qemu-nbd.c +1 -1
index 9bc152e..a56ebfc 100644
@@ -687,7 +687,7 @@ int main(int argc, char **argv)
         drv = NULL;
     }
 
-    bs = bdrv_new("hda", &error_abort);
+    bs = bdrv_new_named("hda", &error_abort);
 
     srcpath = argv[optind];
     ret = bdrv_open(&bs, srcpath, NULL, NULL, flags, drv, &local_err);
Signature · 1 line
1.9.3
Reviewed-by on v1 1/23
#9 lore raw

Re: [Qemu-devel] [PATCH 01/23] block: Split bdrv_new_named() off bdrv_new()

In reply to Markus Armbruster
Quoted 14 lines · Markus Armbruster

Creating an anonymous BDS can't fail. Make that obvious.

---
 block.c               | 26 +++++++++++++++++++-------
 block/iscsi.c         |  2 +-
 block/vvfat.c         |  2 +-
 blockdev.c            |  2 +-
 hw/block/xen_disk.c   |  2 +-
 include/block/block.h |  3 ++-
 qemu-img.c            |  6 +++---
 qemu-io.c             |  2 +-
 qemu-nbd.c            |  2 +-
 9 files changed, 30 insertions(+), 17 deletions(-)
Quoted 198 lines
block.c +19 -7
index d06dd51..4b3bcd4 100644
@@ -335,10 +335,11 @@ void bdrv_register(BlockDriver *bdrv)
 }
 
 /* create a new block device (by default it is empty) */
-BlockDriverState *bdrv_new(const char *device_name, Error **errp)
+BlockDriverState *bdrv_new_named(const char *device_name, Error **errp)
 {
     BlockDriverState *bs;
-    int i;
+
+    assert(*device_name);
 
     if (bdrv_find(device_name)) {
         error_setg(errp, "Device with id '%s' already exists",
@@ -351,12 +352,23 @@ BlockDriverState *bdrv_new(const char *device_name, Error **errp)
         return NULL;
     }
 
-    bs = g_new0(BlockDriverState, 1);
-    QLIST_INIT(&bs->dirty_bitmaps);
+    bs = bdrv_new();
+
     pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
     if (device_name[0] != '\0') {
         QTAILQ_INSERT_TAIL(&bdrv_states, bs, device_list);
     }
+
+    return bs;
+}
+
+BlockDriverState *bdrv_new(void)
+{
+    BlockDriverState *bs;
+    int i;
+
+    bs = g_new0(BlockDriverState, 1);
+    QLIST_INIT(&bs->dirty_bitmaps);
     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
         QLIST_INIT(&bs->op_blockers[i]);
     }
@@ -1217,7 +1229,7 @@ int bdrv_open_backing_file(BlockDriverState *bs, QDict *options, Error **errp)
         goto free_exit;
     }
 
-    backing_hd = bdrv_new("", errp);
+    backing_hd = bdrv_new();
 
     if (bs->backing_format[0] != '\0') {
         back_drv = bdrv_find_format(bs->backing_format);
@@ -1346,7 +1358,7 @@ int bdrv_append_temp_snapshot(BlockDriverState *bs, int flags, Error **errp)
     qdict_put(snapshot_options, "file.filename",
               qstring_from_str(tmp_filename));
 
-    bs_snapshot = bdrv_new("", &error_abort);
+    bs_snapshot = bdrv_new();
 
     ret = bdrv_open(&bs_snapshot, NULL, NULL, snapshot_options,
                     flags, bdrv_qcow2, &local_err);
@@ -1417,7 +1429,7 @@ int bdrv_open(BlockDriverState **pbs, const char *filename,
     if (*pbs) {
         bs = *pbs;
     } else {
-        bs = bdrv_new("", &error_abort);
+        bs = bdrv_new();
     }
 
     /* NULL means an empty set of options */
block/iscsi.c +1 -1
index 3e19202..af3d0f6 100644
@@ -1528,7 +1528,7 @@ static int iscsi_create(const char *filename, QemuOpts *opts, Error **errp)
     IscsiLun *iscsilun = NULL;
     QDict *bs_options;
 
-    bs = bdrv_new("", &error_abort);
+    bs = bdrv_new();
 
     /* Read out options */
     total_size =
block/vvfat.c +1 -1
index 731e591..6c9fde0 100644
@@ -2939,7 +2939,7 @@ static int enable_write_target(BDRVVVFATState *s, Error **errp)
     unlink(s->qcow_filename);
 #endif
 
-    bdrv_set_backing_hd(s->bs, bdrv_new("", &error_abort));
+    bdrv_set_backing_hd(s->bs, bdrv_new());
     s->bs->backing_hd->drv = &vvfat_write_target;
     s->bs->backing_hd->opaque = g_new(void *, 1);
     *(void**)s->bs->backing_hd->opaque = s;
blockdev.c +1 -1
index e919566..9fbd888 100644
@@ -458,7 +458,7 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
     /* init */
     dinfo = g_malloc0(sizeof(*dinfo));
     dinfo->id = g_strdup(qemu_opts_id(opts));
-    dinfo->bdrv = bdrv_new(dinfo->id, &error);
+    dinfo->bdrv = bdrv_new_named(dinfo->id, &error);
     if (error) {
         error_propagate(errp, error);
         goto bdrv_new_err;
hw/block/xen_disk.c +1 -1
index 2dcef07..8bac7ff 100644
@@ -856,7 +856,7 @@ static int blk_connect(struct XenDevice *xendev)
 
         /* setup via xenbus -> create new block driver instance */
         xen_be_printf(&blkdev->xendev, 2, "create new bdrv (xenbus setup)\n");
-        blkdev->bs = bdrv_new(blkdev->dev, NULL);
+        blkdev->bs = bdrv_new_named(blkdev->dev, NULL);
         if (!blkdev->bs) {
             return -1;
         }
include/block/block.h +2 -1
index 8f4ad16..95139c0 100644
@@ -203,7 +203,8 @@ BlockDriver *bdrv_find_whitelisted_format(const char *format_name,
 int bdrv_create(BlockDriver *drv, const char* filename,
                 QemuOpts *opts, Error **errp);
 int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp);
-BlockDriverState *bdrv_new(const char *device_name, Error **errp);
+BlockDriverState *bdrv_new_named(const char *device_name, Error **errp);
+BlockDriverState *bdrv_new(void);
 void bdrv_make_anon(BlockDriverState *bs);
 void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old);
 void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top);
qemu-img.c +3 -3
index 91d1ac3..4490a22 100644
@@ -296,7 +296,7 @@ static BlockDriverState *bdrv_new_open(const char *id,
     Error *local_err = NULL;
     int ret;
 
-    bs = bdrv_new(id, &error_abort);
+    bs = bdrv_new_named(id, &error_abort);
 
     if (fmt) {
         drv = bdrv_find_format(fmt);
@@ -2425,7 +2425,7 @@ static int img_rebase(int argc, char **argv)
     if (!unsafe) {
         char backing_name[1024];
 
-        bs_old_backing = bdrv_new("old_backing", &error_abort);
+        bs_old_backing = bdrv_new_named("old_backing", &error_abort);
         bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
         ret = bdrv_open(&bs_old_backing, backing_name, NULL, NULL, src_flags,
                         old_backing_drv, &local_err);
@@ -2436,7 +2436,7 @@ static int img_rebase(int argc, char **argv)
             goto out;
         }
         if (out_baseimg[0]) {
-            bs_new_backing = bdrv_new("new_backing", &error_abort);
+            bs_new_backing = bdrv_new_named("new_backing", &error_abort);
             ret = bdrv_open(&bs_new_backing, out_baseimg, NULL, NULL, src_flags,
                             new_backing_drv, &local_err);
             if (ret) {
qemu-io.c +1 -1
index d2ab694..44c2e1c 100644
@@ -58,7 +58,7 @@ static int openfile(char *name, int flags, int growable, QDict *opts)
         return 1;
     }
 
-    qemuio_bs = bdrv_new("hda", &error_abort);
+    qemuio_bs = bdrv_new_named("hda", &error_abort);
 
     if (growable) {
         flags |= BDRV_O_PROTOCOL;
qemu-nbd.c +1 -1
index 9bc152e..a56ebfc 100644
@@ -687,7 +687,7 @@ int main(int argc, char **argv)
         drv = NULL;
     }
 
-    bs = bdrv_new("hda", &error_abort);
+    bs = bdrv_new_named("hda", &error_abort);
 
     srcpath = argv[optind];
     ret = bdrv_open(&bs, srcpath, NULL, NULL, flags, drv, &local_err);
Signature · 1 line
1.9.3
#10 lore raw

PATCH 2/23 block: New BlockBackend

In reply to Markus Armbruster

A block device consists of a frontend device model and a backend.

A block backend has a tree of block drivers doing the actual work. The tree is managed by the block layer.

We currently use a single abstraction BlockDriverState both for tree nodes and the backend as a whole. Drawbacks:

* Its API includes both stuff that makes sense only at the block backend level (root of the tree) and stuff that's only for use within the block layer. This makes the API bigger and more complex than necessary. Moreover, it's not obvious which interfaces are meant for device models, and which really aren't.

* Since device models keep a reference to their backend, the backend object can't just be destroyed. But for media change, we need to replace the tree. Our solution is to make the BlockDriverState generic, with actual driver state in a separate object, pointed to by member opaque. That lets us replace the tree by deinitializing and reinitializing its root. This special need of the root makes the data structure awkward everywhere in the tree.

The general plan is to separate the APIs into "block backend", for use by device models, monitor and whatever other code dealing with block backends, and "block driver", for use by the block layer and whatever other code (if any) dealing with trees and tree nodes.

Code dealing with block backends, device models in particular, should become completely oblivious of BlockDriverState. This should let us clean up both APIs, and the tree data structures.

This commit is a first step. It creates a minimal "block backend"
API: type BlockBackend and functions to create, destroy and find them. BlockBackend objects are created and destroyed, but not yet used for anything; that'll come shortly.

BlockBackend is reference-counted. Its reference count never exceeds one so far, but that's going to change.

---
 block/Makefile.objs            |   2 +-
 block/block-backend.c          | 110 +++++++++++++++++++++++++++++++++++++++++
 blockdev.c                     |  10 +++-
 hw/block/xen_disk.c            |  11 +++++
 include/qemu/typedefs.h        |   1 +
 include/sysemu/block-backend.h |  26 ++++++++++
 qemu-img.c                     |  46 +++++++++++++++++
 qemu-io.c                      |   8 +++
 qemu-nbd.c                     |   3 +-
 9 files changed, 214 insertions(+), 3 deletions(-)
 create mode 100644 block/block-backend.c
 create mode 100644 include/sysemu/block-backend.h
block/Makefile.objs +1 -1
index f45f939..a70140b 100644
@@ -5,7 +5,7 @@ block-obj-y += qed-check.o
 block-obj-$(CONFIG_VHDX) += vhdx.o vhdx-endian.o vhdx-log.o
 block-obj-$(CONFIG_QUORUM) += quorum.o
 block-obj-y += parallels.o blkdebug.o blkverify.o
-block-obj-y += snapshot.o qapi.o
+block-obj-y += block-backend.o snapshot.o qapi.o
 block-obj-$(CONFIG_WIN32) += raw-win32.o win32-aio.o
 block-obj-$(CONFIG_POSIX) += raw-posix.o
 block-obj-$(CONFIG_LINUX_AIO) += linux-aio.o
block/block-backend.c new file +110 -0

110 lines not on this page · raw message

blockdev.c +9 -1
index 9fbd888..86596bc 100644
@@ -30,6 +30,7 @@
  * THE SOFTWARE.
  */
 
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "hw/block/block.h"
 #include "block/blockjob.h"
@@ -221,6 +222,7 @@ void drive_del(DriveInfo *dinfo)
     }
 
     bdrv_unref(dinfo->bdrv);
+    blk_unref(blk_by_name(dinfo->id));
     g_free(dinfo->id);
     QTAILQ_REMOVE(&drives, dinfo, next);
     g_free(dinfo->serial);
@@ -301,6 +303,7 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
     int ro = 0;
     int bdrv_flags = 0;
     int on_read_error, on_write_error;
+    BlockBackend *blk;
     DriveInfo *dinfo;
     ThrottleConfig cfg;
     int snapshot = 0;
@@ -456,6 +459,10 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
     }
 
     /* init */
+    blk = blk_new(qemu_opts_id(opts), errp);
+    if (!blk) {
+        goto early_err;
+    }
     dinfo = g_malloc0(sizeof(*dinfo));
     dinfo->id = g_strdup(qemu_opts_id(opts));
     dinfo->bdrv = bdrv_new_named(dinfo->id, &error);
@@ -525,6 +532,7 @@ err:
 bdrv_new_err:
     g_free(dinfo->id);
     g_free(dinfo);
+    blk_unref(blk);
 early_err:
     qemu_opts_del(opts);
 err_no_opts:
@@ -1770,7 +1778,7 @@ int do_drive_del(Monitor *mon, const QDict *qdict, QObject **ret_data)
      */
     if (bdrv_get_attached_dev(bs)) {
         bdrv_make_anon(bs);
-
+        blk_unref(blk_by_name(id));
         /* Further I/O must not pause the guest */
         bdrv_set_on_error(bs, BLOCKDEV_ON_ERROR_REPORT,
                           BLOCKDEV_ON_ERROR_REPORT);
hw/block/xen_disk.c +11 -0
index 8bac7ff..730a021 100644
@@ -39,6 +39,7 @@
 #include "hw/xen/xen_backend.h"
 #include "xen_blkif.h"
 #include "sysemu/blockdev.h"
+#include "sysemu/block-backend.h"
 
 /* ------------------------------------------------------------- */
 
@@ -852,12 +853,18 @@ static int blk_connect(struct XenDevice *xendev)
     blkdev->dinfo = drive_get(IF_XEN, 0, index);
     if (!blkdev->dinfo) {
         Error *local_err = NULL;
+        BlockBackend *blk;
         BlockDriver *drv;
 
         /* setup via xenbus -> create new block driver instance */
         xen_be_printf(&blkdev->xendev, 2, "create new bdrv (xenbus setup)\n");
+        blk = blk_new(blkdev->dev, NULL);
+        if (!blk) {
+            return -1;
+        }
         blkdev->bs = bdrv_new_named(blkdev->dev, NULL);
         if (!blkdev->bs) {
+            blk_unref(blk);
             return -1;
         }
 
@@ -868,6 +875,7 @@ static int blk_connect(struct XenDevice *xendev)
                           error_get_pretty(local_err));
             error_free(local_err);
             bdrv_unref(blkdev->bs);
+            blk_unref(blk);
             blkdev->bs = NULL;
             return -1;
         }
@@ -983,6 +991,9 @@ static void blk_disconnect(struct XenDevice *xendev)
     if (blkdev->bs) {
         bdrv_detach_dev(blkdev->bs, blkdev);
         bdrv_unref(blkdev->bs);
+        if (!blkdev->dinfo) {
+            blk_unref(blk_by_name(blkdev->dev));
+        }
         blkdev->bs = NULL;
     }
     xen_be_unbind_evtchn(&blkdev->xendev);
include/qemu/typedefs.h +1 -0
index 5f20b0e..198da2e 100644
@@ -35,6 +35,7 @@ typedef struct MachineClass MachineClass;
 typedef struct NICInfo NICInfo;
 typedef struct HCIInfo HCIInfo;
 typedef struct AudioState AudioState;
+typedef struct BlockBackend BlockBackend;
 typedef struct BlockDriverState BlockDriverState;
 typedef struct DriveInfo DriveInfo;
 typedef struct DisplayState DisplayState;
include/sysemu/block-backend.h new file +26 -0
new file mode 100644
index 0000000..3f8371c
@@ -0,0 +1,26 @@
+/*
+ * QEMU Block backends
+ *
+ * Copyright (C) 2014 Red Hat, Inc.
+ *
+ * Authors:
+ *  Markus Armbruster <[email protected]>,
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or
+ * later.  See the COPYING file in the top-level directory.
+ */
+
+#ifndef BLOCK_BACKEND_H
+#define BLOCK_BACKEND_H
+
+#include "qemu/typedefs.h"
+#include "qapi/error.h"
+
+BlockBackend *blk_new(const char *name, Error **errp);
+void blk_ref(BlockBackend *blk);
+void blk_unref(BlockBackend *blk);
+const char *blk_name(BlockBackend *blk);
+BlockBackend *blk_by_name(const char *name);
+BlockBackend *blk_next(BlockBackend *blk);
+
+#endif
qemu-img.c +46 -0

284 lines not on this page · raw message

qemu-io.c +8 -0
index 44c2e1c..45e5494 100644
@@ -19,6 +19,7 @@
 #include "qemu/option.h"
 #include "qemu/config-file.h"
 #include "qemu/readline.h"
+#include "sysemu/block-backend.h"
 #include "block/block_int.h"
 #include "trace/control.h"
 
@@ -26,6 +27,7 @@
 
 static char *progname;
 
+static BlockBackend *qemuio_blk;
 static BlockDriverState *qemuio_bs;
 
 /* qemu-io commands passed using -c */
@@ -37,7 +39,9 @@ static ReadLineState *readline_state;
 static int close_f(BlockDriverState *bs, int argc, char **argv)
 {
     bdrv_unref(bs);
+    blk_unref(qemuio_blk);
     qemuio_bs = NULL;
+    qemuio_blk = NULL;
     return 0;
 }
 
@@ -58,6 +62,7 @@ static int openfile(char *name, int flags, int growable, QDict *opts)
         return 1;
     }
 
+    qemuio_blk = blk_new("hda", &error_abort);
     qemuio_bs = bdrv_new_named("hda", &error_abort);
 
     if (growable) {
@@ -70,7 +75,9 @@ static int openfile(char *name, int flags, int growable, QDict *opts)
                 error_get_pretty(local_err));
         error_free(local_err);
         bdrv_unref(qemuio_bs);
+        blk_unref(qemuio_blk);
         qemuio_bs = NULL;
+        qemuio_blk = NULL;
         return 1;
     }
 
@@ -479,6 +486,7 @@ int main(int argc, char **argv)
     if (qemuio_bs) {
         bdrv_unref(qemuio_bs);
     }
+    blk_unref(qemuio_blk);
     g_free(readline_state);
     return 0;
 }
qemu-nbd.c +2 -1
index a56ebfc..94b9b49 100644
@@ -17,7 +17,7 @@
  */
 
 #include "qemu-common.h"
-#include "block/block.h"
+#include "sysemu/block-backend.h"
 #include "block/block_int.h"
 #include "block/nbd.h"
 #include "qemu/main-loop.h"
@@ -687,6 +687,7 @@ int main(int argc, char **argv)
         drv = NULL;
     }
 
+    blk_new("hda", &error_abort);
     bs = bdrv_new_named("hda", &error_abort);
 
     srcpath = argv[optind];
Signature · 1 line
1.9.3
#11 lore raw

Re: [Qemu-devel] [PATCH 02/23] block: New BlockBackend

Am 10.09.2014 um 10:13 hat Markus Armbruster geschrieben:

Quoted 74 lines

A block device consists of a frontend device model and a backend.

A block backend has a tree of block drivers doing the actual work. The tree is managed by the block layer.

We currently use a single abstraction BlockDriverState both for tree nodes and the backend as a whole. Drawbacks:

* Its API includes both stuff that makes sense only at the block backend level (root of the tree) and stuff that's only for use within the block layer. This makes the API bigger and more complex than necessary. Moreover, it's not obvious which interfaces are meant for device models, and which really aren't.

* Since device models keep a reference to their backend, the backend object can't just be destroyed. But for media change, we need to replace the tree. Our solution is to make the BlockDriverState generic, with actual driver state in a separate object, pointed to by member opaque. That lets us replace the tree by deinitializing and reinitializing its root. This special need of the root makes the data structure awkward everywhere in the tree.

The general plan is to separate the APIs into "block backend", for use by device models, monitor and whatever other code dealing with block backends, and "block driver", for use by the block layer and whatever other code (if any) dealing with trees and tree nodes.

Code dealing with block backends, device models in particular, should become completely oblivious of BlockDriverState. This should let us clean up both APIs, and the tree data structures.

This commit is a first step. It creates a minimal "block backend"
API: type BlockBackend and functions to create, destroy and find them. BlockBackend objects are created and destroyed, but not yet used for anything; that'll come shortly.

BlockBackend is reference-counted. Its reference count never exceeds one so far, but that's going to change.

---
 block/Makefile.objs            |   2 +-
 block/block-backend.c          | 110 +++++++++++++++++++++++++++++++++++++++++
 blockdev.c                     |  10 +++-
 hw/block/xen_disk.c            |  11 +++++
 include/qemu/typedefs.h        |   1 +
 include/sysemu/block-backend.h |  26 ++++++++++
 qemu-img.c                     |  46 +++++++++++++++++
 qemu-io.c                      |   8 +++
 qemu-nbd.c                     |   3 +-
 9 files changed, 214 insertions(+), 3 deletions(-)
 create mode 100644 block/block-backend.c
 create mode 100644 include/sysemu/block-backend.h
block/Makefile.objs +1 -1
index f45f939..a70140b 100644
@@ -5,7 +5,7 @@ block-obj-y += qed-check.o
 block-obj-$(CONFIG_VHDX) += vhdx.o vhdx-endian.o vhdx-log.o
 block-obj-$(CONFIG_QUORUM) += quorum.o
 block-obj-y += parallels.o blkdebug.o blkverify.o
-block-obj-y += snapshot.o qapi.o
+block-obj-y += block-backend.o snapshot.o qapi.o
 block-obj-$(CONFIG_WIN32) += raw-win32.o win32-aio.o
 block-obj-$(CONFIG_POSIX) += raw-posix.o
 block-obj-$(CONFIG_LINUX_AIO) += linux-aio.o
block/block-backend.c new file +1 -0
new file mode 100644
index 0000000..833f7d9
@@ -0,0 +1,110 @@
+/*

block/block-backend.c line 11

Quoted 10 lines
block/block-backend.c new file +10 -0
+ * QEMU Block backends
+ *
+ * Copyright (C) 2014 Red Hat, Inc.
+ *
+ * Authors:
+ *  Markus Armbruster <[email protected]>,
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or
+ * later.  See the COPYING file in the top-level directory.
+ */

I think we still have the long-term plan of exposing a block layer library that can be consumed by libvirt. As the usage in qemu-io/img/nbd shows, this will probably have to use BlockBackends, so this code is part of the block layer core.

Considering this, using the LGPL would be more practical. Can you please make this change for v2? (Personally, I would have used the MIT license that the rest of the block layer uses, which also make copying code around cleaner license-wise, but I know you dislike it.)

Quoted 20 lines
block/block-backend.c new file +20 -0
+#include "sysemu/block-backend.h"
+#include "block/block_int.h"
+
+struct BlockBackend {
+    char *name;
+    int refcnt;
+    QTAILQ_ENTRY(BlockBackend) link; /* for blk_backends */
+};
+
+static QTAILQ_HEAD(, BlockBackend) blk_backends =
+    QTAILQ_HEAD_INITIALIZER(blk_backends);
+
+/**
+ * blk_new:
+ * @name: name, must not be %NULL or empty
+ * @errp: return location for an error to be set on failure, or %NULL
+ *
+ * Create a new BlockBackend, with a reference count of one.  Fail if
+ * @name already exists.
+ *

block/block-backend.c line 42

Quoted 10 lines
block/block-backend.c new file +10 -0
+ * Returns: the BlockBackend on success, %NULL on failure
+ */
+BlockBackend *blk_new(const char *name, Error **errp)
+{
+    BlockBackend *blk = g_new0(BlockBackend, 1);
+
+    assert(name && name[0]);
+    if (blk_by_name(name)) {
+        error_setg(errp, "Device with id '%s' already exists", name);
+        return NULL;

blk is leaked here.

Quoted 25 lines
block/block-backend.c new file +25 -0
+    }
+    blk->name = g_strdup(name);
+    blk->refcnt = 1;
+    QTAILQ_INSERT_TAIL(&blk_backends, blk, link);
+    return blk;
+}
+
+static void blk_delete(BlockBackend *blk)
+{
+    assert(!blk->refcnt);
+    QTAILQ_REMOVE(&blk_backends, blk, link);
+    g_free(blk->name);
+    g_free(blk);
+}
+
+/**
+ * blk_ref:
+ *
+ * Increment @blk's reference count.
+ */
+void blk_ref(BlockBackend *blk)
+{
+    blk->refcnt++;
+}
+

block/block-backend.c line 77

Quoted 10 lines
block/block-backend.c new file +10 -0
+/**
+ * blk_unref:
+ *
+ * Decrement @blk's reference count.  If this drops it to zero,
+ * destroy @blk.
+ */
+void blk_unref(BlockBackend *blk)
+{
+    if (blk) {
+        g_assert(blk->refcnt > 0);

You're mixing assert() and g_assert() in this patch. Any reason for this? If not, I think plain assert() is clearly in the majority in the overall codebase.

Quoted 12 lines
block/block-backend.c new file +12 -0
+        if (!--blk->refcnt) {
+            blk_delete(blk);
+        }
+    }
+}
+
+const char *blk_name(BlockBackend *blk)
+{
+    return blk->name;
+}
+
+BlockBackend *blk_by_name(const char *name)

block/block-backend.c line 99

Quoted 10 lines
block/block-backend.c new file +10 -0
+{
+    BlockBackend *blk;
+
+    QTAILQ_FOREACH(blk, &blk_backends, link) {
+        if (!strcmp(name, blk->name)) {
+            return blk;
+        }
+    }
+    return NULL;
+}

No comment for these two non-static functions?

blockdev.c

Quoted 14 lines
block/block-backend.c new file +10 -0
+/**
+ * blk_next:
+ *
+ * Returns: the first BlockBackend if @blk is null, else @blk's next
+ * sibling, which is %NULL for the last BlockBackend
+ */
+BlockBackend *blk_next(BlockBackend *blk)
+{
+    return blk ? QTAILQ_NEXT(blk, link) : QTAILQ_FIRST(&blk_backends);
+}
blockdev.c +0 -0
index 9fbd888..86596bc 100644

Okay, so here the hard part starts: As long as the BB is completely unused, it's very hard to review at which places one must be created and deleted.

What was your approach to systematically find all of them?

Quoted 44 lines
blockdev.c +8 -0
@@ -30,6 +30,7 @@
  * THE SOFTWARE.
  */
 
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "hw/block/block.h"
 #include "block/blockjob.h"
@@ -221,6 +222,7 @@ void drive_del(DriveInfo *dinfo)
     }
 
     bdrv_unref(dinfo->bdrv);
+    blk_unref(blk_by_name(dinfo->id));
     g_free(dinfo->id);
     QTAILQ_REMOVE(&drives, dinfo, next);
     g_free(dinfo->serial);
@@ -301,6 +303,7 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
     int ro = 0;
     int bdrv_flags = 0;
     int on_read_error, on_write_error;
+    BlockBackend *blk;
     DriveInfo *dinfo;
     ThrottleConfig cfg;
     int snapshot = 0;
@@ -456,6 +459,10 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
     }
 
     /* init */
+    blk = blk_new(qemu_opts_id(opts), errp);
+    if (!blk) {
+        goto early_err;
+    }
     dinfo = g_malloc0(sizeof(*dinfo));
     dinfo->id = g_strdup(qemu_opts_id(opts));
     dinfo->bdrv = bdrv_new_named(dinfo->id, &error);
@@ -525,6 +532,7 @@ err:
 bdrv_new_err:
     g_free(dinfo->id);
     g_free(dinfo);
+    blk_unref(blk);
 early_err:
     qemu_opts_del(opts);
 err_no_opts:

blockdev.c int do_drive_del(Monitor *mon, const QDict *qdict, QObject **ret_data) · line 1784

Quoted 8 lines
blockdev.c +1 -1
@@ -1770,7 +1778,7 @@ int do_drive_del(Monitor *mon, const QDict *qdict, QObject **ret_data)
      */
     if (bdrv_get_attached_dev(bs)) {
         bdrv_make_anon(bs);
-
+        blk_unref(blk_by_name(id));
         /* Further I/O must not pause the guest */
         bdrv_set_on_error(bs, BLOCKDEV_ON_ERROR_REPORT,
                           BLOCKDEV_ON_ERROR_REPORT);

Won't we unref the BB a second time now when unplugging the device? (drive_del() called in blockdev_auto_del())

qemu-img.c

Quoted 97 lines
hw/block/xen_disk.c +11 -0
index 8bac7ff..730a021 100644
@@ -39,6 +39,7 @@
 #include "hw/xen/xen_backend.h"
 #include "xen_blkif.h"
 #include "sysemu/blockdev.h"
+#include "sysemu/block-backend.h"
 
 /* ------------------------------------------------------------- */
 
@@ -852,12 +853,18 @@ static int blk_connect(struct XenDevice *xendev)
     blkdev->dinfo = drive_get(IF_XEN, 0, index);
     if (!blkdev->dinfo) {
         Error *local_err = NULL;
+        BlockBackend *blk;
         BlockDriver *drv;
 
         /* setup via xenbus -> create new block driver instance */
         xen_be_printf(&blkdev->xendev, 2, "create new bdrv (xenbus setup)\n");
+        blk = blk_new(blkdev->dev, NULL);
+        if (!blk) {
+            return -1;
+        }
         blkdev->bs = bdrv_new_named(blkdev->dev, NULL);
         if (!blkdev->bs) {
+            blk_unref(blk);
             return -1;
         }
 
@@ -868,6 +875,7 @@ static int blk_connect(struct XenDevice *xendev)
                           error_get_pretty(local_err));
             error_free(local_err);
             bdrv_unref(blkdev->bs);
+            blk_unref(blk);
             blkdev->bs = NULL;
             return -1;
         }
@@ -983,6 +991,9 @@ static void blk_disconnect(struct XenDevice *xendev)
     if (blkdev->bs) {
         bdrv_detach_dev(blkdev->bs, blkdev);
         bdrv_unref(blkdev->bs);
+        if (!blkdev->dinfo) {
+            blk_unref(blk_by_name(blkdev->dev));
+        }
         blkdev->bs = NULL;
     }
     xen_be_unbind_evtchn(&blkdev->xendev);
include/qemu/typedefs.h +1 -0
index 5f20b0e..198da2e 100644
@@ -35,6 +35,7 @@ typedef struct MachineClass MachineClass;
 typedef struct NICInfo NICInfo;
 typedef struct HCIInfo HCIInfo;
 typedef struct AudioState AudioState;
+typedef struct BlockBackend BlockBackend;
 typedef struct BlockDriverState BlockDriverState;
 typedef struct DriveInfo DriveInfo;
 typedef struct DisplayState DisplayState;
include/sysemu/block-backend.h new file +26 -0
new file mode 100644
index 0000000..3f8371c
@@ -0,0 +1,26 @@
+/*
+ * QEMU Block backends
+ *
+ * Copyright (C) 2014 Red Hat, Inc.
+ *
+ * Authors:
+ *  Markus Armbruster <[email protected]>,
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or
+ * later.  See the COPYING file in the top-level directory.
+ */
+
+#ifndef BLOCK_BACKEND_H
+#define BLOCK_BACKEND_H
+
+#include "qemu/typedefs.h"
+#include "qapi/error.h"
+
+BlockBackend *blk_new(const char *name, Error **errp);
+void blk_ref(BlockBackend *blk);
+void blk_unref(BlockBackend *blk);
+const char *blk_name(BlockBackend *blk);
+BlockBackend *blk_by_name(const char *name);
+BlockBackend *blk_next(BlockBackend *blk);
+
+#endif
qemu-img.c +0 -0
index 4490a22..bad3f64 100644

Won't comment on each hunk in qemu-img, but in many cases, on bdrv_new_open() failure, blk is leaked.

Quoted 14 lines
qemu-nbd.c +1 -1
index a56ebfc..94b9b49 100644
@@ -17,7 +17,7 @@
  */
 
 #include "qemu-common.h"
-#include "block/block.h"
+#include "sysemu/block-backend.h"
 #include "block/block_int.h"
 #include "block/nbd.h"
 #include "qemu/main-loop.h"

qemu-nbd.c int main(int argc, char **argv) · line 693

Quoted 7 lines
qemu-nbd.c +1 -0
@@ -687,6 +687,7 @@ int main(int argc, char **argv)
         drv = NULL;
     }
 
+    blk_new("hda", &error_abort);
     bs = bdrv_new_named("hda", &error_abort);
 
     srcpath = argv[optind];

Where is the matching blk_unref?

Kevin

#12 lore raw

Re: [Qemu-devel] [PATCH 02/23] block: New BlockBackend

Quoted 91 lines · Kevin Wolf

Am 10.09.2014 um 10:13 hat Markus Armbruster geschrieben:

Quoted 74 lines

A block device consists of a frontend device model and a backend.

A block backend has a tree of block drivers doing the actual work. The tree is managed by the block layer.

We currently use a single abstraction BlockDriverState both for tree nodes and the backend as a whole. Drawbacks:

* Its API includes both stuff that makes sense only at the block backend level (root of the tree) and stuff that's only for use within the block layer. This makes the API bigger and more complex than necessary. Moreover, it's not obvious which interfaces are meant for device models, and which really aren't.

* Since device models keep a reference to their backend, the backend object can't just be destroyed. But for media change, we need to replace the tree. Our solution is to make the BlockDriverState generic, with actual driver state in a separate object, pointed to by member opaque. That lets us replace the tree by deinitializing and reinitializing its root. This special need of the root makes the data structure awkward everywhere in the tree.

The general plan is to separate the APIs into "block backend", for use by device models, monitor and whatever other code dealing with block backends, and "block driver", for use by the block layer and whatever other code (if any) dealing with trees and tree nodes.

Code dealing with block backends, device models in particular, should become completely oblivious of BlockDriverState. This should let us clean up both APIs, and the tree data structures.

This commit is a first step. It creates a minimal "block backend"
API: type BlockBackend and functions to create, destroy and find them. BlockBackend objects are created and destroyed, but not yet used for anything; that'll come shortly.

BlockBackend is reference-counted. Its reference count never exceeds one so far, but that's going to change.

---
 block/Makefile.objs            |   2 +-
 block/block-backend.c          | 110 +++++++++++++++++++++++++++++++++++++++++
 blockdev.c                     |  10 +++-
 hw/block/xen_disk.c            |  11 +++++
 include/qemu/typedefs.h        |   1 +
 include/sysemu/block-backend.h |  26 ++++++++++
 qemu-img.c                     |  46 +++++++++++++++++
 qemu-io.c                      |   8 +++
 qemu-nbd.c                     |   3 +-
 9 files changed, 214 insertions(+), 3 deletions(-)
 create mode 100644 block/block-backend.c
 create mode 100644 include/sysemu/block-backend.h
block/Makefile.objs +1 -1
index f45f939..a70140b 100644
@@ -5,7 +5,7 @@ block-obj-y += qed-check.o
 block-obj-$(CONFIG_VHDX) += vhdx.o vhdx-endian.o vhdx-log.o
 block-obj-$(CONFIG_QUORUM) += quorum.o
 block-obj-y += parallels.o blkdebug.o blkverify.o
-block-obj-y += snapshot.o qapi.o
+block-obj-y += block-backend.o snapshot.o qapi.o
 block-obj-$(CONFIG_WIN32) += raw-win32.o win32-aio.o
 block-obj-$(CONFIG_POSIX) += raw-posix.o
 block-obj-$(CONFIG_LINUX_AIO) += linux-aio.o
block/block-backend.c new file +1 -0
new file mode 100644
index 0000000..833f7d9
@@ -0,0 +1,110 @@
+/*

block/block-backend.c line 11

Quoted 10 lines
block/block-backend.c new file +10 -0
+ * QEMU Block backends
+ *
+ * Copyright (C) 2014 Red Hat, Inc.
+ *
+ * Authors:
+ *  Markus Armbruster <[email protected]>,
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or
+ * later.  See the COPYING file in the top-level directory.
+ */

I think we still have the long-term plan of exposing a block layer library that can be consumed by libvirt. As the usage in qemu-io/img/nbd shows, this will probably have to use BlockBackends, so this code is part of the block layer core.

Quoted 4 lines

Considering this, using the LGPL would be more practical. Can you please make this change for v2? (Personally, I would have used the MIT license that the rest of the block layer uses, which also make copying code around cleaner license-wise, but I know you dislike it.)

I do.

Having to accept the Lesser GPL's leaching loophole annoys me, but the libvirt licensing boat has long sailed.

Quoted 24 lines
Quoted 24 lines
block/block-backend.c new file +24 -0
+#include "sysemu/block-backend.h"
+#include "block/block_int.h"
+
+struct BlockBackend {
+    char *name;
+    int refcnt;
+    QTAILQ_ENTRY(BlockBackend) link; /* for blk_backends */
+};
+
+static QTAILQ_HEAD(, BlockBackend) blk_backends =
+    QTAILQ_HEAD_INITIALIZER(blk_backends);
+
+/**
+ * blk_new:
+ * @name: name, must not be %NULL or empty
+ * @errp: return location for an error to be set on failure, or %NULL
+ *
+ * Create a new BlockBackend, with a reference count of one.  Fail if
+ * @name already exists.
+ *
+ * Returns: the BlockBackend on success, %NULL on failure
+ */
+BlockBackend *blk_new(const char *name, Error **errp)
+{
Quoted 8 lines

block/block-backend.c line 42

Quoted 6 lines
block/block-backend.c new file +6 -0
+    BlockBackend *blk = g_new0(BlockBackend, 1);
+
+    assert(name && name[0]);
+    if (blk_by_name(name)) {
+        error_setg(errp, "Device with id '%s' already exists", name);
+        return NULL;

blk is leaked here.

Fixed.

Quoted 30 lines
Quoted 30 lines
block/block-backend.c new file +30 -0
+    }
+    blk->name = g_strdup(name);
+    blk->refcnt = 1;
+    QTAILQ_INSERT_TAIL(&blk_backends, blk, link);
+    return blk;
+}
+
+static void blk_delete(BlockBackend *blk)
+{
+    assert(!blk->refcnt);
+    QTAILQ_REMOVE(&blk_backends, blk, link);
+    g_free(blk->name);
+    g_free(blk);
+}
+
+/**
+ * blk_ref:
+ *
+ * Increment @blk's reference count.
+ */
+void blk_ref(BlockBackend *blk)
+{
+    blk->refcnt++;
+}
+
+/**
+ * blk_unref:
+ *
+ * Decrement @blk's reference count.  If this drops it to zero,
+ * destroy @blk.
Quoted 8 lines

block/block-backend.c line 77

Quoted 5 lines
block/block-backend.c new file +5 -0
+ */
+void blk_unref(BlockBackend *blk)
+{
+    if (blk) {
+        g_assert(blk->refcnt > 0);

You're mixing assert() and g_assert() in this patch. Any reason for this?

Stupidity?

Quoted 2 lines

If not, I think plain assert() is clearly in the majority in the
overall codebase.

Fixed.

Quoted 16 lines
Quoted 16 lines
block/block-backend.c new file +16 -0
+        if (!--blk->refcnt) {
+            blk_delete(blk);
+        }
+    }
+}
+
+const char *blk_name(BlockBackend *blk)
+{
+    return blk->name;
+}
+
+BlockBackend *blk_by_name(const char *name)
+{
+    BlockBackend *blk;
+
+    QTAILQ_FOREACH(blk, &blk_backends, link) {
Quoted 8 lines

block/block-backend.c line 99

Quoted 6 lines
block/block-backend.c new file +6 -0
+        if (!strcmp(name, blk->name)) {
+            return blk;
+        }
+    }
+    return NULL;
+}

No comment for these two non-static functions?

I considered the abysmal signal-to-noise ratio of their GTK-Doc-style function comments, and balked.

Considering we're not using this style in the block layer much, what do you think about me abandoning this GTK-doc business, and adding *concise* function comments to all my new public functions instead?

Quoted 19 lines

blockdev.c

Quoted 14 lines
block/block-backend.c new file +10 -0
+/**
+ * blk_next:
+ *
+ * Returns: the first BlockBackend if @blk is null, else @blk's next
+ * sibling, which is %NULL for the last BlockBackend
+ */
+BlockBackend *blk_next(BlockBackend *blk)
+{
+    return blk ? QTAILQ_NEXT(blk, link) : QTAILQ_FIRST(&blk_backends);
+}
blockdev.c +0 -0
index 9fbd888..86596bc 100644

Okay, so here the hard part starts: As long as the BB is completely unused, it's very hard to review at which places one must be created and deleted.

Quoted 1 line

What was your approach to systematically find all of them?

Good question! Fortunately, I have an answer ready :)

We want to create a BB exactly when we're creating a named BDS. "Named" in the sense of "in bdrv_states".

We want to destroy a BB exactly when we're destroying the BDS that motivated its creation.

This is a baby step towards having named BDSes owned by a BB. That'll be done by PATCH 05.

The places creating a named BDS are all clearly visible in PATCH 01, because I rename the function doing that to bdrv_new_named().

This patch adds a blk_new() right next to every bdrv_new_named(), except for qemu-img.c. qemu-img.c calls bdrv_new_named() in bdrv_new_open(). I can't easily call blk_new() there, because the callers need the new BB to be able to destroy it, but I can't easily return the new BB in addition to the new BDS. So I call blk_new() right before every bdrv_new_open() instead.

BB destruction isn't quite as obvious, because destruction of named and nameless BDSes looks the same in the code. Either you examine all bdrv_unref() and figure out whether it's named, and if yes, where you can get the BB you need to unref here. Or you figure out for every allocation of a named BDS where it can be destroyed, and add the BB destruction there. That's what I did.

Quoted 47 lines
Quoted 47 lines
blockdev.c +8 -0
@@ -30,6 +30,7 @@
  * THE SOFTWARE.
  */
 
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "hw/block/block.h"
 #include "block/blockjob.h"
@@ -221,6 +222,7 @@ void drive_del(DriveInfo *dinfo)
     }
 
     bdrv_unref(dinfo->bdrv);
+    blk_unref(blk_by_name(dinfo->id));
     g_free(dinfo->id);
     QTAILQ_REMOVE(&drives, dinfo, next);
     g_free(dinfo->serial);
@@ -301,6 +303,7 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
     int ro = 0;
     int bdrv_flags = 0;
     int on_read_error, on_write_error;
+    BlockBackend *blk;
     DriveInfo *dinfo;
     ThrottleConfig cfg;
     int snapshot = 0;
@@ -456,6 +459,10 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
     }
 
     /* init */
+    blk = blk_new(qemu_opts_id(opts), errp);
+    if (!blk) {
+        goto early_err;
+    }
     dinfo = g_malloc0(sizeof(*dinfo));
     dinfo->id = g_strdup(qemu_opts_id(opts));
     dinfo->bdrv = bdrv_new_named(dinfo->id, &error);
@@ -525,6 +532,7 @@ err:
 bdrv_new_err:
     g_free(dinfo->id);
     g_free(dinfo);
+    blk_unref(blk);
 early_err:
     qemu_opts_del(opts);
 err_no_opts:
@@ -1770,7 +1778,7 @@ int do_drive_del(Monitor *mon, const QDict *qdict, QObject **ret_data)
      */
     if (bdrv_get_attached_dev(bs)) {
         bdrv_make_anon(bs);
Quoted 8 lines

blockdev.c int do_drive_del(Monitor *mon, const QDict *qdict, QObject **ret_data) · line 1784

Quoted 5 lines
blockdev.c +1 -1
-
+        blk_unref(blk_by_name(id));
         /* Further I/O must not pause the guest */
         bdrv_set_on_error(bs, BLOCKDEV_ON_ERROR_REPORT,
                           BLOCKDEV_ON_ERROR_REPORT);

Won't we unref the BB a second time now when unplugging the device? (drive_del() called in blockdev_auto_del())

Short answer: you're right, there's a bug, and I'll fix it.

Long answer: this part is hairy, because the drive_del command is badly designed.

For historical reasons, unplugging a device model destroys the block backends it's attached to, and this is the only way to destroy block backends.

Aside: we're not carrying that misfeature forward to blockdev-add.

For some device models, the guest can prevent unplug. Some users need a way to forcibly revoke device model access to the block backend then, so the underlying images can be safely used for something else.

drive_del lets you do that. Unfortunately, it conflates revoking access with destroying the backend.

Commit 9063f81 makes drive_del immediately destroy the root BDS. Nice:
the device name becomes available for reuse immediately. Not so nice:
the device model's pointer to the root BDS dangles, and we're prone to crash when the memory gets reused.

Commit d22b2f4 fixed that by hiding the root BDS instead of destroying it. Destruction only happens on unplug. "Hiding" means removing it from bdrv_states and graph_bdrv_states; see bdrv_make_anon().

We should've limited the command to revoking access, avoiding this silly hiding business.

The obvious thing to do here is match the mess: hide the BB along with the BDS here, delete it in blockdev_auto_del().

Trouble is that hiding it makes it hard to find in blockdev_auto_del().

I tried to avoid the need to find it there by destroying it here. On unplug, drive_del()'s blk_unref(blk_by_name(dinfo->id)) won't do anything, because blk_by_name() returns NULL. *Except* when the user has since added *another* BB with the same name! Oops...

Simplest possible solution: I hide the BB here, and *leak* it (with a fat FIXME comment) until it becomes easy enough to find. I guess I can find it right in the next patch.

Quoted 92 lines
Quoted 92 lines
hw/block/xen_disk.c +11 -0
index 8bac7ff..730a021 100644
@@ -39,6 +39,7 @@
 #include "hw/xen/xen_backend.h"
 #include "xen_blkif.h"
 #include "sysemu/blockdev.h"
+#include "sysemu/block-backend.h"
 
 /* ------------------------------------------------------------- */
 
@@ -852,12 +853,18 @@ static int blk_connect(struct XenDevice *xendev)
     blkdev->dinfo = drive_get(IF_XEN, 0, index);
     if (!blkdev->dinfo) {
         Error *local_err = NULL;
+        BlockBackend *blk;
         BlockDriver *drv;
 
         /* setup via xenbus -> create new block driver instance */
         xen_be_printf(&blkdev->xendev, 2, "create new bdrv (xenbus setup)\n");
+        blk = blk_new(blkdev->dev, NULL);
+        if (!blk) {
+            return -1;
+        }
         blkdev->bs = bdrv_new_named(blkdev->dev, NULL);
         if (!blkdev->bs) {
+            blk_unref(blk);
             return -1;
         }
 
@@ -868,6 +875,7 @@ static int blk_connect(struct XenDevice *xendev)
                           error_get_pretty(local_err));
             error_free(local_err);
             bdrv_unref(blkdev->bs);
+            blk_unref(blk);
             blkdev->bs = NULL;
             return -1;
         }
@@ -983,6 +991,9 @@ static void blk_disconnect(struct XenDevice *xendev)
     if (blkdev->bs) {
         bdrv_detach_dev(blkdev->bs, blkdev);
         bdrv_unref(blkdev->bs);
+        if (!blkdev->dinfo) {
+            blk_unref(blk_by_name(blkdev->dev));
+        }
         blkdev->bs = NULL;
     }
     xen_be_unbind_evtchn(&blkdev->xendev);
include/qemu/typedefs.h +1 -0
index 5f20b0e..198da2e 100644
@@ -35,6 +35,7 @@ typedef struct MachineClass MachineClass;
 typedef struct NICInfo NICInfo;
 typedef struct HCIInfo HCIInfo;
 typedef struct AudioState AudioState;
+typedef struct BlockBackend BlockBackend;
 typedef struct BlockDriverState BlockDriverState;
 typedef struct DriveInfo DriveInfo;
 typedef struct DisplayState DisplayState;
include/sysemu/block-backend.h new file +25 -0
new file mode 100644
index 0000000..3f8371c
@@ -0,0 +1,26 @@
+/*
+ * QEMU Block backends
+ *
+ * Copyright (C) 2014 Red Hat, Inc.
+ *
+ * Authors:
+ *  Markus Armbruster <[email protected]>,
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or
+ * later.  See the COPYING file in the top-level directory.
+ */
+
+#ifndef BLOCK_BACKEND_H
+#define BLOCK_BACKEND_H
+
+#include "qemu/typedefs.h"
+#include "qapi/error.h"
+
+BlockBackend *blk_new(const char *name, Error **errp);
+void blk_ref(BlockBackend *blk);
+void blk_unref(BlockBackend *blk);
+const char *blk_name(BlockBackend *blk);
+BlockBackend *blk_by_name(const char *name);
+BlockBackend *blk_next(BlockBackend *blk);
+
Quoted 8 lines

qemu-img.c

Quoted 5 lines
include/sysemu/block-backend.h new file +1 -0
+#endif
qemu-img.c +0 -0
index 4490a22..bad3f64 100644

Won't comment on each hunk in qemu-img, but in many cases, on bdrv_new_open() failure, blk is leaked.

I'll check them systematically.

Quoted 17 lines
Quoted 17 lines
qemu-nbd.c +1 -1
index a56ebfc..94b9b49 100644
@@ -17,7 +17,7 @@
  */
 
 #include "qemu-common.h"
-#include "block/block.h"
+#include "sysemu/block-backend.h"
 #include "block/block_int.h"
 #include "block/nbd.h"
 #include "qemu/main-loop.h"
@@ -687,6 +687,7 @@ int main(int argc, char **argv)
         drv = NULL;
     }
 
Quoted 6 lines

qemu-nbd.c int main(int argc, char **argv) · line 693

Quoted 4 lines
qemu-nbd.c +1 -0
+    blk_new("hda", &error_abort);
     bs = bdrv_new_named("hda", &error_abort);
 
     srcpath = argv[optind];

Where is the matching blk_unref?

Right next to the bdrv_unref(): nowhere :)

If you like, I can throw in a preliminary patch adding the bdrv_unref(). Then add the matching blk_unref() in patch.

#13 lore raw

Re: [Qemu-devel] [PATCH 02/23] block: New BlockBackend

Quoted 1 line · Markus Armbruster

Kevin Wolf <[email protected]> writes:

[...]

Quoted 9 lines
Quoted 7 lines

qemu-img.c

Quoted 4 lines
qemu-img.c +0 -0
index 4490a22..bad3f64 100644

Won't comment on each hunk in qemu-img, but in many cases, on bdrv_new_open() failure, blk is leaked.

I'll check them systematically.

The leaks all go away in PATCH 03. Fixing PATCH 02 anyway, of course.

#14 lore raw

Re: [Qemu-devel] [PATCH 02/23] block: New BlockBackend

In reply to Markus Armbruster
Quoted 1 line · Markus Armbruster

Kevin Wolf <[email protected]> writes:

[...]

Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
blockdev.c +0 -0
index 9fbd888..86596bc 100644

[...]

Quoted 17 lines
Quoted 4 lines
Quoted 4 lines
blockdev.c +0 -0
@@ -1770,7 +1778,7 @@ int do_drive_del(Monitor *mon, const QDict *qdict, QObject **ret_data)
      */
     if (bdrv_get_attached_dev(bs)) {
         bdrv_make_anon(bs);
Quoted 8 lines

blockdev.c int do_drive_del(Monitor *mon, const QDict *qdict, QObject **ret_data) · line 1784

Quoted 5 lines
blockdev.c +1 -1
-
+        blk_unref(blk_by_name(id));
         /* Further I/O must not pause the guest */
         bdrv_set_on_error(bs, BLOCKDEV_ON_ERROR_REPORT,
                           BLOCKDEV_ON_ERROR_REPORT);

Won't we unref the BB a second time now when unplugging the device? (drive_del() called in blockdev_auto_del())

Short answer: you're right, there's a bug, and I'll fix it.

Long answer: this part is hairy, because the drive_del command is badly designed.

[...]

Quoted 3 lines

Simplest possible solution: I hide the BB here, and *leak* it (with a fat FIXME comment) until it becomes easy enough to find. I guess I can find it right in the next patch.

Nevermind, I found a tolerable way to avoid the temporary leak.

#15 lore raw

Re: [Qemu-devel] [PATCH 02/23] block: New BlockBackend

In reply to Markus Armbruster
Quoted 98 lines · Markus Armbruster

A block device consists of a frontend device model and a backend.

A block backend has a tree of block drivers doing the actual work. The tree is managed by the block layer.

We currently use a single abstraction BlockDriverState both for tree nodes and the backend as a whole. Drawbacks:

* Its API includes both stuff that makes sense only at the block backend level (root of the tree) and stuff that's only for use within the block layer. This makes the API bigger and more complex than necessary. Moreover, it's not obvious which interfaces are meant for device models, and which really aren't.

* Since device models keep a reference to their backend, the backend object can't just be destroyed. But for media change, we need to replace the tree. Our solution is to make the BlockDriverState generic, with actual driver state in a separate object, pointed to by member opaque. That lets us replace the tree by deinitializing and reinitializing its root. This special need of the root makes the data structure awkward everywhere in the tree.

The general plan is to separate the APIs into "block backend", for use by device models, monitor and whatever other code dealing with block backends, and "block driver", for use by the block layer and whatever other code (if any) dealing with trees and tree nodes.

Code dealing with block backends, device models in particular, should become completely oblivious of BlockDriverState. This should let us clean up both APIs, and the tree data structures.

This commit is a first step. It creates a minimal "block backend"
API: type BlockBackend and functions to create, destroy and find them. BlockBackend objects are created and destroyed, but not yet used for anything; that'll come shortly.

BlockBackend is reference-counted. Its reference count never exceeds one so far, but that's going to change.

---
 block/Makefile.objs            |   2 +-
 block/block-backend.c          | 110 +++++++++++++++++++++++++++++++++++++++++
 blockdev.c                     |  10 +++-
 hw/block/xen_disk.c            |  11 +++++
 include/qemu/typedefs.h        |   1 +
 include/sysemu/block-backend.h |  26 ++++++++++
 qemu-img.c                     |  46 +++++++++++++++++
 qemu-io.c                      |   8 +++
 qemu-nbd.c                     |   3 +-
 9 files changed, 214 insertions(+), 3 deletions(-)
 create mode 100644 block/block-backend.c
 create mode 100644 include/sysemu/block-backend.h
block/Makefile.objs +1 -1
index f45f939..a70140b 100644
@@ -5,7 +5,7 @@ block-obj-y += qed-check.o
 block-obj-$(CONFIG_VHDX) += vhdx.o vhdx-endian.o vhdx-log.o
 block-obj-$(CONFIG_QUORUM) += quorum.o
 block-obj-y += parallels.o blkdebug.o blkverify.o
-block-obj-y += snapshot.o qapi.o
+block-obj-y += block-backend.o snapshot.o qapi.o
 block-obj-$(CONFIG_WIN32) += raw-win32.o win32-aio.o
 block-obj-$(CONFIG_POSIX) += raw-posix.o
 block-obj-$(CONFIG_LINUX_AIO) += linux-aio.o
block/block-backend.c new file +25 -0
new file mode 100644
index 0000000..833f7d9
@@ -0,0 +1,110 @@
+/*
+ * QEMU Block backends
+ *
+ * Copyright (C) 2014 Red Hat, Inc.
+ *
+ * Authors:
+ *  Markus Armbruster <[email protected]>,
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or
+ * later.  See the COPYING file in the top-level directory.
+ */
+
+#include "sysemu/block-backend.h"
+#include "block/block_int.h"
+
+struct BlockBackend {
+    char *name;
+    int refcnt;
+    QTAILQ_ENTRY(BlockBackend) link; /* for blk_backends */
+};
+
+static QTAILQ_HEAD(, BlockBackend) blk_backends =
+    QTAILQ_HEAD_INITIALIZER(blk_backends);
+
+/**

block/block-backend.c line 35

Quoted 10 lines
block/block-backend.c new file +10 -0
+ * blk_new:
+ * @name: name, must not be %NULL or empty
+ * @errp: return location for an error to be set on failure, or %NULL
+ *
+ * Create a new BlockBackend, with a reference count of one.  Fail if
+ * @name already exists.
+ *
+ * Returns: the BlockBackend on success, %NULL on failure
+ */
+BlockBackend *blk_new(const char *name, Error **errp)

I am responding for the easy part first.

So here the blockbackend is identified by a name

block/block-backend.c line 41

Quoted 7 lines
block/block-backend.c new file +6 -0
+{
+    BlockBackend *blk = g_new0(BlockBackend, 1);
+
+    assert(name && name[0]);
+    if (blk_by_name(name)) {
 
+        error_setg(errp, "Device with id '%s' already exists", name);

But here is it an id or a name ?
Do we need to make a choice everywhere in the code between id and name ?

Quoted 13 lines
block/block-backend.c new file +13 -0
+        return NULL;
+    }
+    blk->name = g_strdup(name);
+    blk->refcnt = 1;
+    QTAILQ_INSERT_TAIL(&blk_backends, blk, link);
+    return blk;
+}
+
+static void blk_delete(BlockBackend *blk)
+{
+    assert(!blk->refcnt);
+    QTAILQ_REMOVE(&blk_backends, blk, link);
+    g_free(blk->name);

block/block-backend.c line 64

Quoted 10 lines
block/block-backend.c new file +10 -0
+    g_free(blk);
+}
+
+/**
+ * blk_ref:
+ *
+ * Increment @blk's reference count.
+ */
+void blk_ref(BlockBackend *blk)
+{

if blk_unref you take care of doing
+ if (blk) {
to make sur the user does not pass a NULL pointer. Transforming blk into a NULL pointer is not a side effect of blk_unref so this test is designed to prevent a user brain damage.

If the user can be brain damaged to pass a NULL to blk_unref he could be equally stupid passing a NULL to blk_ref. Why not adding the same test here ?

Quoted 59 lines
block/block-backend.c new file +46 -0
+    blk->refcnt++;
+}
+
+/**
+ * blk_unref:
+ *
+ * Decrement @blk's reference count.  If this drops it to zero,
+ * destroy @blk.
+ */
+void blk_unref(BlockBackend *blk)
+{
+    if (blk) {
+        g_assert(blk->refcnt > 0);
+        if (!--blk->refcnt) {
+            blk_delete(blk);
+        }
+    }
+}
+
+const char *blk_name(BlockBackend *blk)
+{
+    return blk->name;
+}
+
+BlockBackend *blk_by_name(const char *name)
+{
+    BlockBackend *blk;
+
+    QTAILQ_FOREACH(blk, &blk_backends, link) {
+        if (!strcmp(name, blk->name)) {
+            return blk;
+        }
+    }
+    return NULL;
+}
+
+/**
+ * blk_next:
+ *
+ * Returns: the first BlockBackend if @blk is null, else @blk's next
+ * sibling, which is %NULL for the last BlockBackend
+ */
+BlockBackend *blk_next(BlockBackend *blk)
+{
+    return blk ? QTAILQ_NEXT(blk, link) : QTAILQ_FIRST(&blk_backends);
+}
blockdev.c +1 -0
index 9fbd888..86596bc 100644
@@ -30,6 +30,7 @@
  * THE SOFTWARE.
  */
 
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "hw/block/block.h"
 #include "block/blockjob.h"

blockdev.c void drive_del(DriveInfo *dinfo) · line 225

Quoted 4 lines
blockdev.c +1 -0
@@ -221,6 +222,7 @@ void drive_del(DriveInfo *dinfo)
     }
 
     bdrv_unref(dinfo->bdrv);
+    blk_unref(blk_by_name(dinfo->id));

Really the mix of name and id is odd.

Quoted 539 lines
blockdev.c +7 -1
     g_free(dinfo->id);
     QTAILQ_REMOVE(&drives, dinfo, next);
     g_free(dinfo->serial);
@@ -301,6 +303,7 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
     int ro = 0;
     int bdrv_flags = 0;
     int on_read_error, on_write_error;
+    BlockBackend *blk;
     DriveInfo *dinfo;
     ThrottleConfig cfg;
     int snapshot = 0;
@@ -456,6 +459,10 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
     }
 
     /* init */
+    blk = blk_new(qemu_opts_id(opts), errp);
+    if (!blk) {
+        goto early_err;
+    }
     dinfo = g_malloc0(sizeof(*dinfo));
     dinfo->id = g_strdup(qemu_opts_id(opts));
     dinfo->bdrv = bdrv_new_named(dinfo->id, &error);
@@ -525,6 +532,7 @@ err:
 bdrv_new_err:
     g_free(dinfo->id);
     g_free(dinfo);
+    blk_unref(blk);
 early_err:
     qemu_opts_del(opts);
 err_no_opts:
@@ -1770,7 +1778,7 @@ int do_drive_del(Monitor *mon, const QDict *qdict, QObject **ret_data)
      */
     if (bdrv_get_attached_dev(bs)) {
         bdrv_make_anon(bs);
-
+        blk_unref(blk_by_name(id));
         /* Further I/O must not pause the guest */
         bdrv_set_on_error(bs, BLOCKDEV_ON_ERROR_REPORT,
                           BLOCKDEV_ON_ERROR_REPORT);
hw/block/xen_disk.c +11 -0
index 8bac7ff..730a021 100644
@@ -39,6 +39,7 @@
 #include "hw/xen/xen_backend.h"
 #include "xen_blkif.h"
 #include "sysemu/blockdev.h"
+#include "sysemu/block-backend.h"
 
 /* ------------------------------------------------------------- */
 
@@ -852,12 +853,18 @@ static int blk_connect(struct XenDevice *xendev)
     blkdev->dinfo = drive_get(IF_XEN, 0, index);
     if (!blkdev->dinfo) {
         Error *local_err = NULL;
+        BlockBackend *blk;
         BlockDriver *drv;
 
         /* setup via xenbus -> create new block driver instance */
         xen_be_printf(&blkdev->xendev, 2, "create new bdrv (xenbus setup)\n");
+        blk = blk_new(blkdev->dev, NULL);
+        if (!blk) {
+            return -1;
+        }
         blkdev->bs = bdrv_new_named(blkdev->dev, NULL);
         if (!blkdev->bs) {
+            blk_unref(blk);
             return -1;
         }
 
@@ -868,6 +875,7 @@ static int blk_connect(struct XenDevice *xendev)
                           error_get_pretty(local_err));
             error_free(local_err);
             bdrv_unref(blkdev->bs);
+            blk_unref(blk);
             blkdev->bs = NULL;
             return -1;
         }
@@ -983,6 +991,9 @@ static void blk_disconnect(struct XenDevice *xendev)
     if (blkdev->bs) {
         bdrv_detach_dev(blkdev->bs, blkdev);
         bdrv_unref(blkdev->bs);
+        if (!blkdev->dinfo) {
+            blk_unref(blk_by_name(blkdev->dev));
+        }
         blkdev->bs = NULL;
     }
     xen_be_unbind_evtchn(&blkdev->xendev);
include/qemu/typedefs.h +1 -0
index 5f20b0e..198da2e 100644
@@ -35,6 +35,7 @@ typedef struct MachineClass MachineClass;
 typedef struct NICInfo NICInfo;
 typedef struct HCIInfo HCIInfo;
 typedef struct AudioState AudioState;
+typedef struct BlockBackend BlockBackend;
 typedef struct BlockDriverState BlockDriverState;
 typedef struct DriveInfo DriveInfo;
 typedef struct DisplayState DisplayState;
include/sysemu/block-backend.h new file +26 -0
new file mode 100644
index 0000000..3f8371c
@@ -0,0 +1,26 @@
+/*
+ * QEMU Block backends
+ *
+ * Copyright (C) 2014 Red Hat, Inc.
+ *
+ * Authors:
+ *  Markus Armbruster <[email protected]>,
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or
+ * later.  See the COPYING file in the top-level directory.
+ */
+
+#ifndef BLOCK_BACKEND_H
+#define BLOCK_BACKEND_H
+
+#include "qemu/typedefs.h"
+#include "qapi/error.h"
+
+BlockBackend *blk_new(const char *name, Error **errp);
+void blk_ref(BlockBackend *blk);
+void blk_unref(BlockBackend *blk);
+const char *blk_name(BlockBackend *blk);
+BlockBackend *blk_by_name(const char *name);
+BlockBackend *blk_next(BlockBackend *blk);
+
+#endif
qemu-img.c +46 -0
index 4490a22..bad3f64 100644
@@ -29,6 +29,7 @@
 #include "qemu/error-report.h"
 #include "qemu/osdep.h"
 #include "sysemu/sysemu.h"
+#include "sysemu/block-backend.h"
 #include "block/block_int.h"
 #include "block/qapi.h"
 #include <getopt.h>
@@ -575,6 +576,7 @@ static int img_check(int argc, char **argv)
     int c, ret;
     OutputFormat output_format = OFORMAT_HUMAN;
     const char *filename, *fmt, *output, *cache;
+    BlockBackend *blk;
     BlockDriverState *bs;
     int fix = 0;
     int flags = BDRV_O_FLAGS | BDRV_O_CHECK;
@@ -649,6 +651,7 @@ static int img_check(int argc, char **argv)
         return 1;
     }
 
+    blk = blk_new("image", &error_abort);
     bs = bdrv_new_open("image", filename, fmt, flags, true, quiet);
     if (!bs) {
         return 1;
@@ -710,6 +713,7 @@ static int img_check(int argc, char **argv)
 fail:
     qapi_free_ImageCheck(check);
     bdrv_unref(bs);
+    blk_unref(blk);
 
     return ret;
 }
@@ -718,6 +722,7 @@ static int img_commit(int argc, char **argv)
 {
     int c, ret, flags;
     const char *filename, *fmt, *cache;
+    BlockBackend *blk;
     BlockDriverState *bs;
     bool quiet = false;
 
@@ -756,6 +761,7 @@ static int img_commit(int argc, char **argv)
         return 1;
     }
 
+    blk = blk_new("image", &error_abort);
     bs = bdrv_new_open("image", filename, fmt, flags, true, quiet);
     if (!bs) {
         return 1;
@@ -780,6 +786,7 @@ static int img_commit(int argc, char **argv)
     }
 
     bdrv_unref(bs);
+    blk_unref(blk);
     if (ret) {
         return 1;
     }
@@ -942,6 +949,7 @@ static int check_empty_sectors(BlockDriverState *bs, int64_t sect_num,
 static int img_compare(int argc, char **argv)
 {
     const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
+    BlockBackend *blk1, *blk2;
     BlockDriverState *bs1, *bs2;
     int64_t total_sectors1, total_sectors2;
     uint8_t *buf1 = NULL, *buf2 = NULL;
@@ -1011,6 +1019,7 @@ static int img_compare(int argc, char **argv)
         goto out3;
     }
 
+    blk1 = blk_new("image 1", &error_abort);
     bs1 = bdrv_new_open("image 1", filename1, fmt1, flags, true, quiet);
     if (!bs1) {
         error_report("Can't open file %s", filename1);
@@ -1018,6 +1027,7 @@ static int img_compare(int argc, char **argv)
         goto out3;
     }
 
+    blk2 = blk_new("image 2", &error_abort);
     bs2 = bdrv_new_open("image 2", filename2, fmt2, flags, true, quiet);
     if (!bs2) {
         error_report("Can't open file %s", filename2);
@@ -1184,10 +1194,12 @@ static int img_compare(int argc, char **argv)
 
 out:
     bdrv_unref(bs2);
+    blk_unref(blk2);
     qemu_vfree(buf1);
     qemu_vfree(buf2);
 out2:
     bdrv_unref(bs1);
+    blk_unref(blk1);
 out3:
     qemu_progress_end();
     return ret;
@@ -1200,6 +1212,7 @@ static int img_convert(int argc, char **argv)
     int progress = 0, flags, src_flags;
     const char *fmt, *out_fmt, *cache, *src_cache, *out_baseimg, *out_filename;
     BlockDriver *drv, *proto_drv;
+    BlockBackend **blk = NULL, *out_blk = NULL;
     BlockDriverState **bs = NULL, *out_bs = NULL;
     int64_t total_sectors, nb_sectors, sector_num, bs_offset;
     int64_t *bs_sectors = NULL;
@@ -1354,6 +1367,7 @@ static int img_convert(int argc, char **argv)
 
     qemu_progress_print(0, 100);
 
+    blk = g_new0(BlockBackend *, bs_n);
     bs = g_new0(BlockDriverState *, bs_n);
     bs_sectors = g_new(int64_t, bs_n);
 
@@ -1361,6 +1375,7 @@ static int img_convert(int argc, char **argv)
     for (bs_i = 0; bs_i < bs_n; bs_i++) {
         char *id = bs_n > 1 ? g_strdup_printf("source %d", bs_i)
                             : g_strdup("source");
+        blk[bs_i] = blk_new(id, &error_abort);
         bs[bs_i] = bdrv_new_open(id, argv[optind + bs_i], fmt, src_flags,
                                  true, quiet);
         g_free(id);
@@ -1486,6 +1501,7 @@ static int img_convert(int argc, char **argv)
         goto out;
     }
 
+    out_blk = blk_new("target", &error_abort);
     out_bs = bdrv_new_open("target", out_filename, out_fmt, flags, true, quiet);
     if (!out_bs) {
         ret = -1;
@@ -1742,6 +1758,7 @@ out:
     if (out_bs) {
         bdrv_unref(out_bs);
     }
+    blk_unref(out_blk);
     if (bs) {
         for (bs_i = 0; bs_i < bs_n; bs_i++) {
             if (bs[bs_i]) {
@@ -1750,6 +1767,12 @@ out:
         }
         g_free(bs);
     }
+    if (blk) {
+        for (bs_i = 0; bs_i < bs_n; bs_i++) {
+            blk_unref(blk[bs_i]);
+        }
+        g_free(blk);
+    }
     g_free(bs_sectors);
 fail_getopt:
     g_free(options);
@@ -1858,6 +1881,7 @@ static ImageInfoList *collect_image_info_list(const char *filename,
     filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
 
     while (filename) {
+        BlockBackend *blk;
         BlockDriverState *bs;
         ImageInfo *info;
         ImageInfoList *elem;
@@ -1869,6 +1893,7 @@ static ImageInfoList *collect_image_info_list(const char *filename,
         }
         g_hash_table_insert(filenames, (gpointer)filename, NULL);
 
+        blk = blk_new("image", &error_abort);
         bs = bdrv_new_open("image", filename, fmt,
                            BDRV_O_FLAGS | BDRV_O_NO_BACKING, false, false);
         if (!bs) {
@@ -1880,6 +1905,7 @@ static ImageInfoList *collect_image_info_list(const char *filename,
             error_report("%s", error_get_pretty(err));
             error_free(err);
             bdrv_unref(bs);
+            blk_unref(blk);
             goto err;
         }
 
@@ -1889,6 +1915,7 @@ static ImageInfoList *collect_image_info_list(const char *filename,
         last = &elem->next;
 
         bdrv_unref(bs);
+        blk_unref(blk);
 
         filename = fmt = NULL;
         if (chain) {
@@ -2082,6 +2109,7 @@ static int img_map(int argc, char **argv)
 {
     int c;
     OutputFormat output_format = OFORMAT_HUMAN;
+    BlockBackend *blk;
     BlockDriverState *bs;
     const char *filename, *fmt, *output;
     int64_t length;
@@ -2130,6 +2158,7 @@ static int img_map(int argc, char **argv)
         return 1;
     }
 
+    blk = blk_new("image", &error_abort);
     bs = bdrv_new_open("image", filename, fmt, BDRV_O_FLAGS, true, false);
     if (!bs) {
         return 1;
@@ -2175,6 +2204,7 @@ static int img_map(int argc, char **argv)
 
 out:
     bdrv_unref(bs);
+    blk_unref(blk);
     return ret < 0;
 }
 
@@ -2185,6 +2215,7 @@ out:
 
 static int img_snapshot(int argc, char **argv)
 {
+    BlockBackend *blk;
     BlockDriverState *bs;
     QEMUSnapshotInfo sn;
     char *filename, *snapshot_name = NULL;
@@ -2250,6 +2281,7 @@ static int img_snapshot(int argc, char **argv)
     filename = argv[optind++];
 
     /* Open the image */
+    blk = blk_new("image", &error_abort);
     bs = bdrv_new_open("image", filename, NULL, bdrv_oflags, true, quiet);
     if (!bs) {
         return 1;
@@ -2297,6 +2329,7 @@ static int img_snapshot(int argc, char **argv)
 
     /* Cleanup */
     bdrv_unref(bs);
+    blk_unref(blk);
     if (ret) {
         return 1;
     }
@@ -2305,6 +2338,7 @@ static int img_snapshot(int argc, char **argv)
 
 static int img_rebase(int argc, char **argv)
 {
+    BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
     BlockDriverState *bs = NULL, *bs_old_backing = NULL, *bs_new_backing = NULL;
     BlockDriver *old_backing_drv, *new_backing_drv;
     char *filename;
@@ -2393,6 +2427,7 @@ static int img_rebase(int argc, char **argv)
      * Ignore the old backing file for unsafe rebase in case we want to correct
      * the reference to a renamed or moved backing file.
      */
+    blk = blk_new("image", &error_abort);
     bs = bdrv_new_open("image", filename, fmt, flags, true, quiet);
     if (!bs) {
         ret = -1;
@@ -2425,6 +2460,7 @@ static int img_rebase(int argc, char **argv)
     if (!unsafe) {
         char backing_name[1024];
 
+        blk_old_backing = blk_new("old_backing", &error_abort);
         bs_old_backing = bdrv_new_named("old_backing", &error_abort);
         bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
         ret = bdrv_open(&bs_old_backing, backing_name, NULL, NULL, src_flags,
@@ -2436,6 +2472,7 @@ static int img_rebase(int argc, char **argv)
             goto out;
         }
         if (out_baseimg[0]) {
+            blk_new_backing = blk_new("new_backing", &error_abort);
             bs_new_backing = bdrv_new_named("new_backing", &error_abort);
             ret = bdrv_open(&bs_new_backing, out_baseimg, NULL, NULL, src_flags,
                             new_backing_drv, &local_err);
@@ -2614,12 +2651,15 @@ out:
         if (bs_old_backing != NULL) {
             bdrv_unref(bs_old_backing);
         }
+        blk_unref(blk_old_backing);
         if (bs_new_backing != NULL) {
             bdrv_unref(bs_new_backing);
         }
+        blk_unref(blk_new_backing);
     }
 
     bdrv_unref(bs);
+    blk_unref(blk);
     if (ret) {
         return 1;
     }
@@ -2632,6 +2672,7 @@ static int img_resize(int argc, char **argv)
     const char *filename, *fmt, *size;
     int64_t n, total_size;
     bool quiet = false;
+    BlockBackend *blk = NULL;
     BlockDriverState *bs = NULL;
     QemuOpts *param;
     static QemuOptsList resize_options = {
@@ -2708,6 +2749,7 @@ static int img_resize(int argc, char **argv)
     n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
     qemu_opts_del(param);
 
+    blk = blk_new("image", &error_abort);
     bs = bdrv_new_open("image", filename, fmt, BDRV_O_FLAGS | BDRV_O_RDWR,
                        true, quiet);
     if (!bs) {
@@ -2745,6 +2787,7 @@ out:
     if (bs) {
         bdrv_unref(bs);
     }
+    blk_unref(blk);
     if (ret) {
         return 1;
     }
@@ -2760,6 +2803,7 @@ static int img_amend(int argc, char **argv)
     const char *fmt = NULL, *filename, *cache;
     int flags;
     bool quiet = false;
+    BlockBackend *blk = NULL;
     BlockDriverState *bs = NULL;
 
     cache = BDRV_DEFAULT_CACHE;
@@ -2823,6 +2867,7 @@ static int img_amend(int argc, char **argv)
         goto out;
     }
 
+    blk = blk_new("image", &error_abort);
     bs = bdrv_new_open("image", filename, fmt, flags, true, quiet);
     if (!bs) {
         error_report("Could not open image '%s'", filename);
@@ -2856,6 +2901,7 @@ out:
     if (bs) {
         bdrv_unref(bs);
     }
+    blk_unref(blk);
     qemu_opts_del(opts);
     qemu_opts_free(create_opts);
     g_free(options);
qemu-io.c +8 -0
index 44c2e1c..45e5494 100644
@@ -19,6 +19,7 @@
 #include "qemu/option.h"
 #include "qemu/config-file.h"
 #include "qemu/readline.h"
+#include "sysemu/block-backend.h"
 #include "block/block_int.h"
 #include "trace/control.h"
 
@@ -26,6 +27,7 @@
 
 static char *progname;
 
+static BlockBackend *qemuio_blk;
 static BlockDriverState *qemuio_bs;
 
 /* qemu-io commands passed using -c */
@@ -37,7 +39,9 @@ static ReadLineState *readline_state;
 static int close_f(BlockDriverState *bs, int argc, char **argv)
 {
     bdrv_unref(bs);
+    blk_unref(qemuio_blk);
     qemuio_bs = NULL;
+    qemuio_blk = NULL;
     return 0;
 }
 
@@ -58,6 +62,7 @@ static int openfile(char *name, int flags, int growable, QDict *opts)
         return 1;
     }
 
+    qemuio_blk = blk_new("hda", &error_abort);
     qemuio_bs = bdrv_new_named("hda", &error_abort);
 
     if (growable) {
@@ -70,7 +75,9 @@ static int openfile(char *name, int flags, int growable, QDict *opts)
                 error_get_pretty(local_err));
         error_free(local_err);
         bdrv_unref(qemuio_bs);
+        blk_unref(qemuio_blk);
         qemuio_bs = NULL;
+        qemuio_blk = NULL;
         return 1;
     }
 
@@ -479,6 +486,7 @@ int main(int argc, char **argv)
     if (qemuio_bs) {
         bdrv_unref(qemuio_bs);
     }
+    blk_unref(qemuio_blk);
     g_free(readline_state);
     return 0;
 }
qemu-nbd.c +2 -1
index a56ebfc..94b9b49 100644
@@ -17,7 +17,7 @@
  */
 
 #include "qemu-common.h"
-#include "block/block.h"
+#include "sysemu/block-backend.h"
 #include "block/block_int.h"
 #include "block/nbd.h"
 #include "qemu/main-loop.h"
@@ -687,6 +687,7 @@ int main(int argc, char **argv)
         drv = NULL;
     }
 
+    blk_new("hda", &error_abort);
     bs = bdrv_new_named("hda", &error_abort);
 
     srcpath = argv[optind];
Signature · 1 line
1.9.3
#16 lore raw

Re: [Qemu-devel] [PATCH 02/23] block: New BlockBackend

Am 10.09.2014 um 13:34 hat Benoît Canet geschrieben:

Quoted 42 lines
Quoted 40 lines · Markus Armbruster

A block device consists of a frontend device model and a backend.

A block backend has a tree of block drivers doing the actual work. The tree is managed by the block layer.

We currently use a single abstraction BlockDriverState both for tree nodes and the backend as a whole. Drawbacks:

* Its API includes both stuff that makes sense only at the block backend level (root of the tree) and stuff that's only for use within the block layer. This makes the API bigger and more complex than necessary. Moreover, it's not obvious which interfaces are meant for device models, and which really aren't.

* Since device models keep a reference to their backend, the backend object can't just be destroyed. But for media change, we need to replace the tree. Our solution is to make the BlockDriverState generic, with actual driver state in a separate object, pointed to by member opaque. That lets us replace the tree by deinitializing and reinitializing its root. This special need of the root makes the data structure awkward everywhere in the tree.

The general plan is to separate the APIs into "block backend", for use by device models, monitor and whatever other code dealing with block backends, and "block driver", for use by the block layer and whatever other code (if any) dealing with trees and tree nodes.

Code dealing with block backends, device models in particular, should become completely oblivious of BlockDriverState. This should let us clean up both APIs, and the tree data structures.

This commit is a first step. It creates a minimal "block backend"
API: type BlockBackend and functions to create, destroy and find them. BlockBackend objects are created and destroyed, but not yet used for anything; that'll come shortly.

BlockBackend is reference-counted. Its reference count never exceeds one so far, but that's going to change.

Quoted 14 lines

block/block-backend.c line 64

Quoted 7 lines
block/block-backend.c new file +7 -0
+/**
+ * blk_ref:
+ *
+ * Increment @blk's reference count.
+ */
+void blk_ref(BlockBackend *blk)
+{

if blk_unref you take care of doing
+ if (blk) {
to make sur the user does not pass a NULL pointer. Transforming blk into a NULL pointer is not a side effect of blk_unref so this test is designed to prevent a user brain damage.

Not really, I'd rather consider it a convenience feature, just like you're allowed to call free(NULL) or bdrv_unref(NULL) without having a check for != NULL everywhere. This will be handy especially in error paths.

Quoted 3 lines

If the user can be brain damaged to pass a NULL to blk_unref he could be equally stupid passing a NULL to blk_ref. Why not adding the same test here ?

Whereas in blk_ref() it really wouldn't make any sense.

Kevin

#17 lore raw

Re: [Qemu-devel] [PATCH 02/23] block: New BlockBackend

Quoted 58 lines · Kevin Wolf

Am 10.09.2014 um 13:34 hat Benoît Canet geschrieben:

Quoted 42 lines
Quoted 40 lines · Markus Armbruster

A block device consists of a frontend device model and a backend.

A block backend has a tree of block drivers doing the actual work. The tree is managed by the block layer.

We currently use a single abstraction BlockDriverState both for tree nodes and the backend as a whole. Drawbacks:

* Its API includes both stuff that makes sense only at the block backend level (root of the tree) and stuff that's only for use within the block layer. This makes the API bigger and more complex than necessary. Moreover, it's not obvious which interfaces are meant for device models, and which really aren't.

* Since device models keep a reference to their backend, the backend object can't just be destroyed. But for media change, we need to replace the tree. Our solution is to make the BlockDriverState generic, with actual driver state in a separate object, pointed to by member opaque. That lets us replace the tree by deinitializing and reinitializing its root. This special need of the root makes the data structure awkward everywhere in the tree.

The general plan is to separate the APIs into "block backend", for use by device models, monitor and whatever other code dealing with block backends, and "block driver", for use by the block layer and whatever other code (if any) dealing with trees and tree nodes.

Code dealing with block backends, device models in particular, should become completely oblivious of BlockDriverState. This should let us clean up both APIs, and the tree data structures.

This commit is a first step. It creates a minimal "block backend"
API: type BlockBackend and functions to create, destroy and find them. BlockBackend objects are created and destroyed, but not yet used for anything; that'll come shortly.

BlockBackend is reference-counted. Its reference count never exceeds one so far, but that's going to change.

Quoted 14 lines

block/block-backend.c line 64

Quoted 7 lines
block/block-backend.c new file +7 -0
+/**
+ * blk_ref:
+ *
+ * Increment @blk's reference count.
+ */
+void blk_ref(BlockBackend *blk)
+{

if blk_unref you take care of doing
+ if (blk) {
to make sur the user does not pass a NULL pointer. Transforming blk into a NULL pointer is not a side effect of blk_unref so this test is designed to prevent a user brain damage.

Quoted 4 lines

Not really, I'd rather consider it a convenience feature, just like you're allowed to call free(NULL) or bdrv_unref(NULL) without having a check for != NULL everywhere. This will be handy especially in error paths.

ok I see the spirit of it.

Benoit

Quoted 9 lines
Quoted 4 lines

If the user can be brain damaged to pass a NULL to blk_unref he could be equally stupid passing a NULL to blk_ref. Why not adding the same test here ?

Whereas in blk_ref() it really wouldn't make any sense.

Kevin

#18 lore raw

Re: [Qemu-devel] [PATCH 02/23] block: New BlockBackend

In reply to Benoît Canet
Quoted 120 lines · Benoît Canet
Quoted 98 lines · Markus Armbruster

A block device consists of a frontend device model and a backend.

A block backend has a tree of block drivers doing the actual work. The tree is managed by the block layer.

We currently use a single abstraction BlockDriverState both for tree nodes and the backend as a whole. Drawbacks:

* Its API includes both stuff that makes sense only at the block backend level (root of the tree) and stuff that's only for use within the block layer. This makes the API bigger and more complex than necessary. Moreover, it's not obvious which interfaces are meant for device models, and which really aren't.

* Since device models keep a reference to their backend, the backend object can't just be destroyed. But for media change, we need to replace the tree. Our solution is to make the BlockDriverState generic, with actual driver state in a separate object, pointed to by member opaque. That lets us replace the tree by deinitializing and reinitializing its root. This special need of the root makes the data structure awkward everywhere in the tree.

The general plan is to separate the APIs into "block backend", for use by device models, monitor and whatever other code dealing with block backends, and "block driver", for use by the block layer and whatever other code (if any) dealing with trees and tree nodes.

Code dealing with block backends, device models in particular, should become completely oblivious of BlockDriverState. This should let us clean up both APIs, and the tree data structures.

This commit is a first step. It creates a minimal "block backend"
API: type BlockBackend and functions to create, destroy and find them. BlockBackend objects are created and destroyed, but not yet used for anything; that'll come shortly.

BlockBackend is reference-counted. Its reference count never exceeds one so far, but that's going to change.

---
 block/Makefile.objs            |   2 +-
 block/block-backend.c          | 110 +++++++++++++++++++++++++++++++++++++++++
 blockdev.c                     |  10 +++-
 hw/block/xen_disk.c            |  11 +++++
 include/qemu/typedefs.h        |   1 +
 include/sysemu/block-backend.h |  26 ++++++++++
 qemu-img.c                     |  46 +++++++++++++++++
 qemu-io.c                      |   8 +++
 qemu-nbd.c                     |   3 +-
 9 files changed, 214 insertions(+), 3 deletions(-)
 create mode 100644 block/block-backend.c
 create mode 100644 include/sysemu/block-backend.h
block/Makefile.objs +1 -1
index f45f939..a70140b 100644
@@ -5,7 +5,7 @@ block-obj-y += qed-check.o
 block-obj-$(CONFIG_VHDX) += vhdx.o vhdx-endian.o vhdx-log.o
 block-obj-$(CONFIG_QUORUM) += quorum.o
 block-obj-y += parallels.o blkdebug.o blkverify.o
-block-obj-y += snapshot.o qapi.o
+block-obj-y += block-backend.o snapshot.o qapi.o
 block-obj-$(CONFIG_WIN32) += raw-win32.o win32-aio.o
 block-obj-$(CONFIG_POSIX) += raw-posix.o
 block-obj-$(CONFIG_LINUX_AIO) += linux-aio.o
block/block-backend.c new file +25 -0
new file mode 100644
index 0000000..833f7d9
@@ -0,0 +1,110 @@
+/*
+ * QEMU Block backends
+ *
+ * Copyright (C) 2014 Red Hat, Inc.
+ *
+ * Authors:
+ *  Markus Armbruster <[email protected]>,
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or
+ * later.  See the COPYING file in the top-level directory.
+ */
+
+#include "sysemu/block-backend.h"
+#include "block/block_int.h"
+
+struct BlockBackend {
+    char *name;
+    int refcnt;
+    QTAILQ_ENTRY(BlockBackend) link; /* for blk_backends */
+};
+
+static QTAILQ_HEAD(, BlockBackend) blk_backends =
+    QTAILQ_HEAD_INITIALIZER(blk_backends);
+
+/**

block/block-backend.c line 35

Quoted 10 lines
block/block-backend.c new file +10 -0
+ * blk_new:
+ * @name: name, must not be %NULL or empty
+ * @errp: return location for an error to be set on failure, or %NULL
+ *
+ * Create a new BlockBackend, with a reference count of one.  Fail if
+ * @name already exists.
+ *
+ * Returns: the BlockBackend on success, %NULL on failure
+ */
+BlockBackend *blk_new(const char *name, Error **errp)

I am responding for the easy part first.

So here the blockbackend is identified by a name

Quoted 5 lines
block/block-backend.c new file +5 -0
+{
+    BlockBackend *blk = g_new0(BlockBackend, 1);
+
+    assert(name && name[0]);
+    if (blk_by_name(name)) {
Quoted 4 lines

block/block-backend.c line 41

Quoted 1 line
block/block-backend.c new file +1 -0
+        error_setg(errp, "Device with id '%s' already exists", name);

But here is it an id or a name ?
Do we need to make a choice everywhere in the code between id and name ?

If we can agree on a convention to use within the block layer, I'll be happy to follow it.

Right now, we mix "id", "device", "device name" freely. My patch mimicks existing usage: "id" in QemuOpts and some error messages, "device name" and its abbreviated variations in the code, the schema, and some other error messages.

Quoted 31 lines
Quoted 13 lines
block/block-backend.c new file +13 -0
+        return NULL;
+    }
+    blk->name = g_strdup(name);
+    blk->refcnt = 1;
+    QTAILQ_INSERT_TAIL(&blk_backends, blk, link);
+    return blk;
+}
+
+static void blk_delete(BlockBackend *blk)
+{
+    assert(!blk->refcnt);
+    QTAILQ_REMOVE(&blk_backends, blk, link);
+    g_free(blk->name);

block/block-backend.c line 64

Quoted 10 lines
block/block-backend.c new file +10 -0
+    g_free(blk);
+}
+
+/**
+ * blk_ref:
+ *
+ * Increment @blk's reference count.
+ */
+void blk_ref(BlockBackend *blk)
+{

if blk_unref you take care of doing
+ if (blk) {
to make sur the user does not pass a NULL pointer. Transforming blk into a NULL pointer is not a side effect of blk_unref so this test is designed to prevent a user brain damage.

Quoted 3 lines

If the user can be brain damaged to pass a NULL to blk_unref he could be equally stupid passing a NULL to blk_ref. Why not adding the same test here ?

Kevin already explained this one.

[...]

#19 lore raw

Re: [Qemu-devel] [PATCH 02/23] block: New BlockBackend

In reply to Markus Armbruster
Quoted 212 lines · Markus Armbruster

A block device consists of a frontend device model and a backend.

A block backend has a tree of block drivers doing the actual work. The tree is managed by the block layer.

We currently use a single abstraction BlockDriverState both for tree nodes and the backend as a whole. Drawbacks:

* Its API includes both stuff that makes sense only at the block backend level (root of the tree) and stuff that's only for use within the block layer. This makes the API bigger and more complex than necessary. Moreover, it's not obvious which interfaces are meant for device models, and which really aren't.

* Since device models keep a reference to their backend, the backend object can't just be destroyed. But for media change, we need to replace the tree. Our solution is to make the BlockDriverState generic, with actual driver state in a separate object, pointed to by member opaque. That lets us replace the tree by deinitializing and reinitializing its root. This special need of the root makes the data structure awkward everywhere in the tree.

The general plan is to separate the APIs into "block backend", for use by device models, monitor and whatever other code dealing with block backends, and "block driver", for use by the block layer and whatever other code (if any) dealing with trees and tree nodes.

Code dealing with block backends, device models in particular, should become completely oblivious of BlockDriverState. This should let us clean up both APIs, and the tree data structures.

This commit is a first step. It creates a minimal "block backend"
API: type BlockBackend and functions to create, destroy and find them. BlockBackend objects are created and destroyed, but not yet used for anything; that'll come shortly.

BlockBackend is reference-counted. Its reference count never exceeds one so far, but that's going to change.

---
 block/Makefile.objs            |   2 +-
 block/block-backend.c          | 110 +++++++++++++++++++++++++++++++++++++++++
 blockdev.c                     |  10 +++-
 hw/block/xen_disk.c            |  11 +++++
 include/qemu/typedefs.h        |   1 +
 include/sysemu/block-backend.h |  26 ++++++++++
 qemu-img.c                     |  46 +++++++++++++++++
 qemu-io.c                      |   8 +++
 qemu-nbd.c                     |   3 +-
 9 files changed, 214 insertions(+), 3 deletions(-)
 create mode 100644 block/block-backend.c
 create mode 100644 include/sysemu/block-backend.h
block/Makefile.objs +1 -1
index f45f939..a70140b 100644
@@ -5,7 +5,7 @@ block-obj-y += qed-check.o
 block-obj-$(CONFIG_VHDX) += vhdx.o vhdx-endian.o vhdx-log.o
 block-obj-$(CONFIG_QUORUM) += quorum.o
 block-obj-y += parallels.o blkdebug.o blkverify.o
-block-obj-y += snapshot.o qapi.o
+block-obj-y += block-backend.o snapshot.o qapi.o
 block-obj-$(CONFIG_WIN32) += raw-win32.o win32-aio.o
 block-obj-$(CONFIG_POSIX) += raw-posix.o
 block-obj-$(CONFIG_LINUX_AIO) += linux-aio.o
block/block-backend.c new file +110 -0
new file mode 100644
index 0000000..833f7d9
@@ -0,0 +1,110 @@
+/*
+ * QEMU Block backends
+ *
+ * Copyright (C) 2014 Red Hat, Inc.
+ *
+ * Authors:
+ *  Markus Armbruster <[email protected]>,
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or
+ * later.  See the COPYING file in the top-level directory.
+ */
+
+#include "sysemu/block-backend.h"
+#include "block/block_int.h"
+
+struct BlockBackend {
+    char *name;
+    int refcnt;
+    QTAILQ_ENTRY(BlockBackend) link; /* for blk_backends */
+};
+
+static QTAILQ_HEAD(, BlockBackend) blk_backends =
+    QTAILQ_HEAD_INITIALIZER(blk_backends);
+
+/**
+ * blk_new:
+ * @name: name, must not be %NULL or empty
+ * @errp: return location for an error to be set on failure, or %NULL
+ *
+ * Create a new BlockBackend, with a reference count of one.  Fail if
+ * @name already exists.
+ *
+ * Returns: the BlockBackend on success, %NULL on failure
+ */
+BlockBackend *blk_new(const char *name, Error **errp)
+{
+    BlockBackend *blk = g_new0(BlockBackend, 1);
+
+    assert(name && name[0]);
+    if (blk_by_name(name)) {
+        error_setg(errp, "Device with id '%s' already exists", name);
+        return NULL;
+    }
+    blk->name = g_strdup(name);
+    blk->refcnt = 1;
+    QTAILQ_INSERT_TAIL(&blk_backends, blk, link);
+    return blk;
+}
+
+static void blk_delete(BlockBackend *blk)
+{
+    assert(!blk->refcnt);
+    QTAILQ_REMOVE(&blk_backends, blk, link);
+    g_free(blk->name);
+    g_free(blk);
+}
+
+/**
+ * blk_ref:
+ *
+ * Increment @blk's reference count.
+ */
+void blk_ref(BlockBackend *blk)
+{
+    blk->refcnt++;
+}
+
+/**
+ * blk_unref:
+ *
+ * Decrement @blk's reference count.  If this drops it to zero,
+ * destroy @blk.
+ */
+void blk_unref(BlockBackend *blk)
+{
+    if (blk) {
+        g_assert(blk->refcnt > 0);
+        if (!--blk->refcnt) {
+            blk_delete(blk);
+        }
+    }
+}
+
+const char *blk_name(BlockBackend *blk)
+{
+    return blk->name;
+}
+
+BlockBackend *blk_by_name(const char *name)
+{
+    BlockBackend *blk;
+
+    QTAILQ_FOREACH(blk, &blk_backends, link) {
+        if (!strcmp(name, blk->name)) {
+            return blk;
+        }
+    }
+    return NULL;
+}
+
+/**
+ * blk_next:
+ *
+ * Returns: the first BlockBackend if @blk is null, else @blk's next
+ * sibling, which is %NULL for the last BlockBackend
+ */
+BlockBackend *blk_next(BlockBackend *blk)
+{
+    return blk ? QTAILQ_NEXT(blk, link) : QTAILQ_FIRST(&blk_backends);
+}
blockdev.c +3 -0
index 9fbd888..86596bc 100644
@@ -30,6 +30,7 @@
  * THE SOFTWARE.
  */
 
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "hw/block/block.h"
 #include "block/blockjob.h"
@@ -221,6 +222,7 @@ void drive_del(DriveInfo *dinfo)
     }
 
     bdrv_unref(dinfo->bdrv);
+    blk_unref(blk_by_name(dinfo->id));
     g_free(dinfo->id);
     QTAILQ_REMOVE(&drives, dinfo, next);
     g_free(dinfo->serial);
@@ -301,6 +303,7 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
     int ro = 0;
     int bdrv_flags = 0;
     int on_read_error, on_write_error;
+    BlockBackend *blk;
     DriveInfo *dinfo;
     ThrottleConfig cfg;
     int snapshot = 0;

blockdev.c static DriveInfo *blockdev_init(const char *file, QDict *bs_opts, · line 465

Quoted 7 lines
blockdev.c +4 -0
@@ -456,6 +459,10 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
     }
 
     /* init */
+    blk = blk_new(qemu_opts_id(opts), errp);
+    if (!blk) {
+        goto early_err;
+    }

Here you create a new block backend.
And you don't attach it to anything in any way yet.

So down in the code the following test will leak it:

    if (!file || !*file) {                                                      
        if (has_driver_specific_opts) {                                         
            file = NULL;                                                        
        } else {                                                                
            QDECREF(bs_opts);                                                   
            qemu_opts_del(opts);                                                
            return dinfo;                                                       
        }                                                                       
    } 

I am sure one of your next patchs fixes this but for this precise commit this do look like a leak.

Quoted 134 lines
blockdev.c +2 -1
     dinfo = g_malloc0(sizeof(*dinfo));
     dinfo->id = g_strdup(qemu_opts_id(opts));
     dinfo->bdrv = bdrv_new_named(dinfo->id, &error);
@@ -525,6 +532,7 @@ err:
 bdrv_new_err:
     g_free(dinfo->id);
     g_free(dinfo);
+    blk_unref(blk);
 early_err:
     qemu_opts_del(opts);
 err_no_opts:
@@ -1770,7 +1778,7 @@ int do_drive_del(Monitor *mon, const QDict *qdict, QObject **ret_data)
      */
     if (bdrv_get_attached_dev(bs)) {
         bdrv_make_anon(bs);
-
+        blk_unref(blk_by_name(id));
         /* Further I/O must not pause the guest */
         bdrv_set_on_error(bs, BLOCKDEV_ON_ERROR_REPORT,
                           BLOCKDEV_ON_ERROR_REPORT);
hw/block/xen_disk.c +11 -0
index 8bac7ff..730a021 100644
@@ -39,6 +39,7 @@
 #include "hw/xen/xen_backend.h"
 #include "xen_blkif.h"
 #include "sysemu/blockdev.h"
+#include "sysemu/block-backend.h"
 
 /* ------------------------------------------------------------- */
 
@@ -852,12 +853,18 @@ static int blk_connect(struct XenDevice *xendev)
     blkdev->dinfo = drive_get(IF_XEN, 0, index);
     if (!blkdev->dinfo) {
         Error *local_err = NULL;
+        BlockBackend *blk;
         BlockDriver *drv;
 
         /* setup via xenbus -> create new block driver instance */
         xen_be_printf(&blkdev->xendev, 2, "create new bdrv (xenbus setup)\n");
+        blk = blk_new(blkdev->dev, NULL);
+        if (!blk) {
+            return -1;
+        }
         blkdev->bs = bdrv_new_named(blkdev->dev, NULL);
         if (!blkdev->bs) {
+            blk_unref(blk);
             return -1;
         }
 
@@ -868,6 +875,7 @@ static int blk_connect(struct XenDevice *xendev)
                           error_get_pretty(local_err));
             error_free(local_err);
             bdrv_unref(blkdev->bs);
+            blk_unref(blk);
             blkdev->bs = NULL;
             return -1;
         }
@@ -983,6 +991,9 @@ static void blk_disconnect(struct XenDevice *xendev)
     if (blkdev->bs) {
         bdrv_detach_dev(blkdev->bs, blkdev);
         bdrv_unref(blkdev->bs);
+        if (!blkdev->dinfo) {
+            blk_unref(blk_by_name(blkdev->dev));
+        }
         blkdev->bs = NULL;
     }
     xen_be_unbind_evtchn(&blkdev->xendev);
include/qemu/typedefs.h +1 -0
index 5f20b0e..198da2e 100644
@@ -35,6 +35,7 @@ typedef struct MachineClass MachineClass;
 typedef struct NICInfo NICInfo;
 typedef struct HCIInfo HCIInfo;
 typedef struct AudioState AudioState;
+typedef struct BlockBackend BlockBackend;
 typedef struct BlockDriverState BlockDriverState;
 typedef struct DriveInfo DriveInfo;
 typedef struct DisplayState DisplayState;
include/sysemu/block-backend.h new file +26 -0
new file mode 100644
index 0000000..3f8371c
@@ -0,0 +1,26 @@
+/*
+ * QEMU Block backends
+ *
+ * Copyright (C) 2014 Red Hat, Inc.
+ *
+ * Authors:
+ *  Markus Armbruster <[email protected]>,
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or
+ * later.  See the COPYING file in the top-level directory.
+ */
+
+#ifndef BLOCK_BACKEND_H
+#define BLOCK_BACKEND_H
+
+#include "qemu/typedefs.h"
+#include "qapi/error.h"
+
+BlockBackend *blk_new(const char *name, Error **errp);
+void blk_ref(BlockBackend *blk);
+void blk_unref(BlockBackend *blk);
+const char *blk_name(BlockBackend *blk);
+BlockBackend *blk_by_name(const char *name);
+BlockBackend *blk_next(BlockBackend *blk);
+
+#endif
qemu-img.c +2 -0
index 4490a22..bad3f64 100644
@@ -29,6 +29,7 @@
 #include "qemu/error-report.h"
 #include "qemu/osdep.h"
 #include "sysemu/sysemu.h"
+#include "sysemu/block-backend.h"
 #include "block/block_int.h"
 #include "block/qapi.h"
 #include <getopt.h>
@@ -575,6 +576,7 @@ static int img_check(int argc, char **argv)
     int c, ret;
     OutputFormat output_format = OFORMAT_HUMAN;
     const char *filename, *fmt, *output, *cache;
+    BlockBackend *blk;
     BlockDriverState *bs;
     int fix = 0;
     int flags = BDRV_O_FLAGS | BDRV_O_CHECK;

qemu-img.c static int img_check(int argc, char **argv) · line 655

Quoted 5 lines
qemu-img.c +1 -0
@@ -649,6 +651,7 @@ static int img_check(int argc, char **argv)
         return 1;
     }
 
 
+    blk = blk_new("image", &error_abort);

Hmm we are so sure this will work that we don't do if (!block) ?

Quoted 134 lines
qemu-img.c +0 -0
     bs = bdrv_new_open("image", filename, fmt, flags, true, quiet);
     if (!bs) {
         return 1;
qemu-img.c +21 -0
@@ -710,6 +713,7 @@ static int img_check(int argc, char **argv)
 fail:
     qapi_free_ImageCheck(check);
     bdrv_unref(bs);
+    blk_unref(blk);
 
     return ret;
 }
@@ -718,6 +722,7 @@ static int img_commit(int argc, char **argv)
 {
     int c, ret, flags;
     const char *filename, *fmt, *cache;
+    BlockBackend *blk;
     BlockDriverState *bs;
     bool quiet = false;
 
@@ -756,6 +761,7 @@ static int img_commit(int argc, char **argv)
         return 1;
     }
 
+    blk = blk_new("image", &error_abort);
     bs = bdrv_new_open("image", filename, fmt, flags, true, quiet);
     if (!bs) {
         return 1;
@@ -780,6 +786,7 @@ static int img_commit(int argc, char **argv)
     }
 
     bdrv_unref(bs);
+    blk_unref(blk);
     if (ret) {
         return 1;
     }
@@ -942,6 +949,7 @@ static int check_empty_sectors(BlockDriverState *bs, int64_t sect_num,
 static int img_compare(int argc, char **argv)
 {
     const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
+    BlockBackend *blk1, *blk2;
     BlockDriverState *bs1, *bs2;
     int64_t total_sectors1, total_sectors2;
     uint8_t *buf1 = NULL, *buf2 = NULL;
@@ -1011,6 +1019,7 @@ static int img_compare(int argc, char **argv)
         goto out3;
     }
 
+    blk1 = blk_new("image 1", &error_abort);
     bs1 = bdrv_new_open("image 1", filename1, fmt1, flags, true, quiet);
     if (!bs1) {
         error_report("Can't open file %s", filename1);
@@ -1018,6 +1027,7 @@ static int img_compare(int argc, char **argv)
         goto out3;
     }
 
+    blk2 = blk_new("image 2", &error_abort);
     bs2 = bdrv_new_open("image 2", filename2, fmt2, flags, true, quiet);
     if (!bs2) {
         error_report("Can't open file %s", filename2);
@@ -1184,10 +1194,12 @@ static int img_compare(int argc, char **argv)
 
 out:
     bdrv_unref(bs2);
+    blk_unref(blk2);
     qemu_vfree(buf1);
     qemu_vfree(buf2);
 out2:
     bdrv_unref(bs1);
+    blk_unref(blk1);
 out3:
     qemu_progress_end();
     return ret;
@@ -1200,6 +1212,7 @@ static int img_convert(int argc, char **argv)
     int progress = 0, flags, src_flags;
     const char *fmt, *out_fmt, *cache, *src_cache, *out_baseimg, *out_filename;
     BlockDriver *drv, *proto_drv;
+    BlockBackend **blk = NULL, *out_blk = NULL;
     BlockDriverState **bs = NULL, *out_bs = NULL;
     int64_t total_sectors, nb_sectors, sector_num, bs_offset;
     int64_t *bs_sectors = NULL;
@@ -1354,6 +1367,7 @@ static int img_convert(int argc, char **argv)
 
     qemu_progress_print(0, 100);
 
+    blk = g_new0(BlockBackend *, bs_n);
     bs = g_new0(BlockDriverState *, bs_n);
     bs_sectors = g_new(int64_t, bs_n);
 
@@ -1361,6 +1375,7 @@ static int img_convert(int argc, char **argv)
     for (bs_i = 0; bs_i < bs_n; bs_i++) {
         char *id = bs_n > 1 ? g_strdup_printf("source %d", bs_i)
                             : g_strdup("source");
+        blk[bs_i] = blk_new(id, &error_abort);
         bs[bs_i] = bdrv_new_open(id, argv[optind + bs_i], fmt, src_flags,
                                  true, quiet);
         g_free(id);
@@ -1486,6 +1501,7 @@ static int img_convert(int argc, char **argv)
         goto out;
     }
 
+    out_blk = blk_new("target", &error_abort);
     out_bs = bdrv_new_open("target", out_filename, out_fmt, flags, true, quiet);
     if (!out_bs) {
         ret = -1;
@@ -1742,6 +1758,7 @@ out:
     if (out_bs) {
         bdrv_unref(out_bs);
     }
+    blk_unref(out_blk);
     if (bs) {
         for (bs_i = 0; bs_i < bs_n; bs_i++) {
             if (bs[bs_i]) {
@@ -1750,6 +1767,12 @@ out:
         }
         g_free(bs);
     }
+    if (blk) {
+        for (bs_i = 0; bs_i < bs_n; bs_i++) {
+            blk_unref(blk[bs_i]);
+        }
+        g_free(blk);
+    }
     g_free(bs_sectors);
 fail_getopt:
     g_free(options);
@@ -1858,6 +1881,7 @@ static ImageInfoList *collect_image_info_list(const char *filename,
     filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
 
     while (filename) {
+        BlockBackend *blk;
         BlockDriverState *bs;
         ImageInfo *info;
         ImageInfoList *elem;

qemu-img.c static ImageInfoList *collect_image_info_list(const char *filename, · line 1899

Quoted 7 lines
qemu-img.c +1 -0
@@ -1869,6 +1893,7 @@ static ImageInfoList *collect_image_info_list(const char *filename,
         }
         g_hash_table_insert(filenames, (gpointer)filename, NULL);
 
+        blk = blk_new("image", &error_abort);
         bs = bdrv_new_open("image", filename, fmt,
                            BDRV_O_FLAGS | BDRV_O_NO_BACKING, false, false);
         if (!bs) {

I think it misses an

Quoted 1 line

+ blk_unref(blk);

in if(!bs) branch.

Quoted 191 lines
qemu-img.c +21 -0
@@ -1880,6 +1905,7 @@ static ImageInfoList *collect_image_info_list(const char *filename,
             error_report("%s", error_get_pretty(err));
             error_free(err);
             bdrv_unref(bs);
+            blk_unref(blk);
             goto err;
         }
 
@@ -1889,6 +1915,7 @@ static ImageInfoList *collect_image_info_list(const char *filename,
         last = &elem->next;
 
         bdrv_unref(bs);
+        blk_unref(blk);
 
         filename = fmt = NULL;
         if (chain) {
@@ -2082,6 +2109,7 @@ static int img_map(int argc, char **argv)
 {
     int c;
     OutputFormat output_format = OFORMAT_HUMAN;
+    BlockBackend *blk;
     BlockDriverState *bs;
     const char *filename, *fmt, *output;
     int64_t length;
@@ -2130,6 +2158,7 @@ static int img_map(int argc, char **argv)
         return 1;
     }
 
+    blk = blk_new("image", &error_abort);
     bs = bdrv_new_open("image", filename, fmt, BDRV_O_FLAGS, true, false);
     if (!bs) {
         return 1;
@@ -2175,6 +2204,7 @@ static int img_map(int argc, char **argv)
 
 out:
     bdrv_unref(bs);
+    blk_unref(blk);
     return ret < 0;
 }
 
@@ -2185,6 +2215,7 @@ out:
 
 static int img_snapshot(int argc, char **argv)
 {
+    BlockBackend *blk;
     BlockDriverState *bs;
     QEMUSnapshotInfo sn;
     char *filename, *snapshot_name = NULL;
@@ -2250,6 +2281,7 @@ static int img_snapshot(int argc, char **argv)
     filename = argv[optind++];
 
     /* Open the image */
+    blk = blk_new("image", &error_abort);
     bs = bdrv_new_open("image", filename, NULL, bdrv_oflags, true, quiet);
     if (!bs) {
         return 1;
@@ -2297,6 +2329,7 @@ static int img_snapshot(int argc, char **argv)
 
     /* Cleanup */
     bdrv_unref(bs);
+    blk_unref(blk);
     if (ret) {
         return 1;
     }
@@ -2305,6 +2338,7 @@ static int img_snapshot(int argc, char **argv)
 
 static int img_rebase(int argc, char **argv)
 {
+    BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
     BlockDriverState *bs = NULL, *bs_old_backing = NULL, *bs_new_backing = NULL;
     BlockDriver *old_backing_drv, *new_backing_drv;
     char *filename;
@@ -2393,6 +2427,7 @@ static int img_rebase(int argc, char **argv)
      * Ignore the old backing file for unsafe rebase in case we want to correct
      * the reference to a renamed or moved backing file.
      */
+    blk = blk_new("image", &error_abort);
     bs = bdrv_new_open("image", filename, fmt, flags, true, quiet);
     if (!bs) {
         ret = -1;
@@ -2425,6 +2460,7 @@ static int img_rebase(int argc, char **argv)
     if (!unsafe) {
         char backing_name[1024];
 
+        blk_old_backing = blk_new("old_backing", &error_abort);
         bs_old_backing = bdrv_new_named("old_backing", &error_abort);
         bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
         ret = bdrv_open(&bs_old_backing, backing_name, NULL, NULL, src_flags,
@@ -2436,6 +2472,7 @@ static int img_rebase(int argc, char **argv)
             goto out;
         }
         if (out_baseimg[0]) {
+            blk_new_backing = blk_new("new_backing", &error_abort);
             bs_new_backing = bdrv_new_named("new_backing", &error_abort);
             ret = bdrv_open(&bs_new_backing, out_baseimg, NULL, NULL, src_flags,
                             new_backing_drv, &local_err);
@@ -2614,12 +2651,15 @@ out:
         if (bs_old_backing != NULL) {
             bdrv_unref(bs_old_backing);
         }
+        blk_unref(blk_old_backing);
         if (bs_new_backing != NULL) {
             bdrv_unref(bs_new_backing);
         }
+        blk_unref(blk_new_backing);
     }
 
     bdrv_unref(bs);
+    blk_unref(blk);
     if (ret) {
         return 1;
     }
@@ -2632,6 +2672,7 @@ static int img_resize(int argc, char **argv)
     const char *filename, *fmt, *size;
     int64_t n, total_size;
     bool quiet = false;
+    BlockBackend *blk = NULL;
     BlockDriverState *bs = NULL;
     QemuOpts *param;
     static QemuOptsList resize_options = {
@@ -2708,6 +2749,7 @@ static int img_resize(int argc, char **argv)
     n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
     qemu_opts_del(param);
 
+    blk = blk_new("image", &error_abort);
     bs = bdrv_new_open("image", filename, fmt, BDRV_O_FLAGS | BDRV_O_RDWR,
                        true, quiet);
     if (!bs) {
@@ -2745,6 +2787,7 @@ out:
     if (bs) {
         bdrv_unref(bs);
     }
+    blk_unref(blk);
     if (ret) {
         return 1;
     }
@@ -2760,6 +2803,7 @@ static int img_amend(int argc, char **argv)
     const char *fmt = NULL, *filename, *cache;
     int flags;
     bool quiet = false;
+    BlockBackend *blk = NULL;
     BlockDriverState *bs = NULL;
 
     cache = BDRV_DEFAULT_CACHE;
@@ -2823,6 +2867,7 @@ static int img_amend(int argc, char **argv)
         goto out;
     }
 
+    blk = blk_new("image", &error_abort);
     bs = bdrv_new_open("image", filename, fmt, flags, true, quiet);
     if (!bs) {
         error_report("Could not open image '%s'", filename);
@@ -2856,6 +2901,7 @@ out:
     if (bs) {
         bdrv_unref(bs);
     }
+    blk_unref(blk);
     qemu_opts_del(opts);
     qemu_opts_free(create_opts);
     g_free(options);
qemu-io.c +4 -0
index 44c2e1c..45e5494 100644
@@ -19,6 +19,7 @@
 #include "qemu/option.h"
 #include "qemu/config-file.h"
 #include "qemu/readline.h"
+#include "sysemu/block-backend.h"
 #include "block/block_int.h"
 #include "trace/control.h"
 
@@ -26,6 +27,7 @@
 
 static char *progname;
 
+static BlockBackend *qemuio_blk;
 static BlockDriverState *qemuio_bs;
 
 /* qemu-io commands passed using -c */
@@ -37,7 +39,9 @@ static ReadLineState *readline_state;
 static int close_f(BlockDriverState *bs, int argc, char **argv)
 {
     bdrv_unref(bs);
+    blk_unref(qemuio_blk);
     qemuio_bs = NULL;
+    qemuio_blk = NULL;
     return 0;
 }
 

qemu-io.c static int openfile(char *name, int flags, int growable, QDict *opts) · line 67

Quoted 6 lines
qemu-io.c +1 -0
@@ -58,6 +62,7 @@ static int openfile(char *name, int flags, int growable, QDict *opts)
         return 1;
     }
 
+    qemuio_blk = blk_new("hda", &error_abort);
 
     qemuio_bs = bdrv_new_named("hda", &error_abort);

I see accepting that an allocation _will_ work is the qemu tools style.

Quoted 45 lines
qemu-io.c +3 -0
     if (growable) {
@@ -70,7 +75,9 @@ static int openfile(char *name, int flags, int growable, QDict *opts)
                 error_get_pretty(local_err));
         error_free(local_err);
         bdrv_unref(qemuio_bs);
+        blk_unref(qemuio_blk);
         qemuio_bs = NULL;
+        qemuio_blk = NULL;
         return 1;
     }
 
@@ -479,6 +486,7 @@ int main(int argc, char **argv)
     if (qemuio_bs) {
         bdrv_unref(qemuio_bs);
     }
+    blk_unref(qemuio_blk);
     g_free(readline_state);
     return 0;
 }
qemu-nbd.c +2 -1
index a56ebfc..94b9b49 100644
@@ -17,7 +17,7 @@
  */
 
 #include "qemu-common.h"
-#include "block/block.h"
+#include "sysemu/block-backend.h"
 #include "block/block_int.h"
 #include "block/nbd.h"
 #include "qemu/main-loop.h"
@@ -687,6 +687,7 @@ int main(int argc, char **argv)
         drv = NULL;
     }
 
+    blk_new("hda", &error_abort);
     bs = bdrv_new_named("hda", &error_abort);
 
     srcpath = argv[optind];
Signature · 1 line
1.9.3
#20 lore raw

Re: [Qemu-devel] [PATCH 02/23] block: New BlockBackend

Quoted 376 lines · Benoît Canet
Quoted 212 lines · Markus Armbruster

A block device consists of a frontend device model and a backend.

A block backend has a tree of block drivers doing the actual work. The tree is managed by the block layer.

We currently use a single abstraction BlockDriverState both for tree nodes and the backend as a whole. Drawbacks:

* Its API includes both stuff that makes sense only at the block backend level (root of the tree) and stuff that's only for use within the block layer. This makes the API bigger and more complex than necessary. Moreover, it's not obvious which interfaces are meant for device models, and which really aren't.

* Since device models keep a reference to their backend, the backend object can't just be destroyed. But for media change, we need to replace the tree. Our solution is to make the BlockDriverState generic, with actual driver state in a separate object, pointed to by member opaque. That lets us replace the tree by deinitializing and reinitializing its root. This special need of the root makes the data structure awkward everywhere in the tree.

The general plan is to separate the APIs into "block backend", for use by device models, monitor and whatever other code dealing with block backends, and "block driver", for use by the block layer and whatever other code (if any) dealing with trees and tree nodes.

Code dealing with block backends, device models in particular, should become completely oblivious of BlockDriverState. This should let us clean up both APIs, and the tree data structures.

This commit is a first step. It creates a minimal "block backend"
API: type BlockBackend and functions to create, destroy and find them. BlockBackend objects are created and destroyed, but not yet used for anything; that'll come shortly.

BlockBackend is reference-counted. Its reference count never exceeds one so far, but that's going to change.

---
 block/Makefile.objs            |   2 +-
 block/block-backend.c          | 110 +++++++++++++++++++++++++++++++++++++++++
 blockdev.c                     |  10 +++-
 hw/block/xen_disk.c            |  11 +++++
 include/qemu/typedefs.h        |   1 +
 include/sysemu/block-backend.h |  26 ++++++++++
 qemu-img.c                     |  46 +++++++++++++++++
 qemu-io.c                      |   8 +++
 qemu-nbd.c                     |   3 +-
 9 files changed, 214 insertions(+), 3 deletions(-)
 create mode 100644 block/block-backend.c
 create mode 100644 include/sysemu/block-backend.h
block/Makefile.objs +1 -1
index f45f939..a70140b 100644
@@ -5,7 +5,7 @@ block-obj-y += qed-check.o
 block-obj-$(CONFIG_VHDX) += vhdx.o vhdx-endian.o vhdx-log.o
 block-obj-$(CONFIG_QUORUM) += quorum.o
 block-obj-y += parallels.o blkdebug.o blkverify.o
-block-obj-y += snapshot.o qapi.o
+block-obj-y += block-backend.o snapshot.o qapi.o
 block-obj-$(CONFIG_WIN32) += raw-win32.o win32-aio.o
 block-obj-$(CONFIG_POSIX) += raw-posix.o
 block-obj-$(CONFIG_LINUX_AIO) += linux-aio.o
block/block-backend.c new file +110 -0
new file mode 100644
index 0000000..833f7d9
@@ -0,0 +1,110 @@
+/*
+ * QEMU Block backends
+ *
+ * Copyright (C) 2014 Red Hat, Inc.
+ *
+ * Authors:
+ *  Markus Armbruster <[email protected]>,
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or
+ * later.  See the COPYING file in the top-level directory.
+ */
+
+#include "sysemu/block-backend.h"
+#include "block/block_int.h"
+
+struct BlockBackend {
+    char *name;
+    int refcnt;
+    QTAILQ_ENTRY(BlockBackend) link; /* for blk_backends */
+};
+
+static QTAILQ_HEAD(, BlockBackend) blk_backends =
+    QTAILQ_HEAD_INITIALIZER(blk_backends);
+
+/**
+ * blk_new:
+ * @name: name, must not be %NULL or empty
+ * @errp: return location for an error to be set on failure, or %NULL
+ *
+ * Create a new BlockBackend, with a reference count of one.  Fail if
+ * @name already exists.
+ *
+ * Returns: the BlockBackend on success, %NULL on failure
+ */
+BlockBackend *blk_new(const char *name, Error **errp)
+{
+    BlockBackend *blk = g_new0(BlockBackend, 1);
+
+    assert(name && name[0]);
+    if (blk_by_name(name)) {
+        error_setg(errp, "Device with id '%s' already exists", name);
+        return NULL;
+    }
+    blk->name = g_strdup(name);
+    blk->refcnt = 1;
+    QTAILQ_INSERT_TAIL(&blk_backends, blk, link);
+    return blk;
+}
+
+static void blk_delete(BlockBackend *blk)
+{
+    assert(!blk->refcnt);
+    QTAILQ_REMOVE(&blk_backends, blk, link);
+    g_free(blk->name);
+    g_free(blk);
+}
+
+/**
+ * blk_ref:
+ *
+ * Increment @blk's reference count.
+ */
+void blk_ref(BlockBackend *blk)
+{
+    blk->refcnt++;
+}
+
+/**
+ * blk_unref:
+ *
+ * Decrement @blk's reference count.  If this drops it to zero,
+ * destroy @blk.
+ */
+void blk_unref(BlockBackend *blk)
+{
+    if (blk) {
+        g_assert(blk->refcnt > 0);
+        if (!--blk->refcnt) {
+            blk_delete(blk);
+        }
+    }
+}
+
+const char *blk_name(BlockBackend *blk)
+{
+    return blk->name;
+}
+
+BlockBackend *blk_by_name(const char *name)
+{
+    BlockBackend *blk;
+
+    QTAILQ_FOREACH(blk, &blk_backends, link) {
+        if (!strcmp(name, blk->name)) {
+            return blk;
+        }
+    }
+    return NULL;
+}
+
+/**
+ * blk_next:
+ *
+ * Returns: the first BlockBackend if @blk is null, else @blk's next
+ * sibling, which is %NULL for the last BlockBackend
+ */
+BlockBackend *blk_next(BlockBackend *blk)
+{
+    return blk ? QTAILQ_NEXT(blk, link) : QTAILQ_FIRST(&blk_backends);
+}
blockdev.c +3 -0
index 9fbd888..86596bc 100644
@@ -30,6 +30,7 @@
  * THE SOFTWARE.
  */
 
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "hw/block/block.h"
 #include "block/blockjob.h"
@@ -221,6 +222,7 @@ void drive_del(DriveInfo *dinfo)
     }
 
     bdrv_unref(dinfo->bdrv);
+    blk_unref(blk_by_name(dinfo->id));
     g_free(dinfo->id);
     QTAILQ_REMOVE(&drives, dinfo, next);
     g_free(dinfo->serial);
@@ -301,6 +303,7 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
     int ro = 0;
     int bdrv_flags = 0;
     int on_read_error, on_write_error;
+    BlockBackend *blk;
     DriveInfo *dinfo;
     ThrottleConfig cfg;
     int snapshot = 0;

blockdev.c static DriveInfo *blockdev_init(const char *file, QDict *bs_opts, · line 465

Quoted 7 lines
blockdev.c +4 -0
@@ -456,6 +459,10 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
     }
 
     /* init */
+    blk = blk_new(qemu_opts_id(opts), errp);
+    if (!blk) {
+        goto early_err;
+    }

Here you create a new block backend.
And you don't attach it to anything in any way yet.

So down in the code the following test will leak it:

    if (!file || !*file) {                                                      
        if (has_driver_specific_opts) {                                         
            file = NULL;                                                        
        } else {                                                                
            QDECREF(bs_opts);                                                   
            qemu_opts_del(opts);                                                
            return dinfo;                                                       
        }                                                                       
    } 

I am sure one of your next patchs fixes this but for this precise commit this do look like a leak.

Quoted 137 lines
blockdev.c +2 -1
     dinfo = g_malloc0(sizeof(*dinfo));
     dinfo->id = g_strdup(qemu_opts_id(opts));
     dinfo->bdrv = bdrv_new_named(dinfo->id, &error);
@@ -525,6 +532,7 @@ err:
 bdrv_new_err:
     g_free(dinfo->id);
     g_free(dinfo);
+    blk_unref(blk);
 early_err:
     qemu_opts_del(opts);
 err_no_opts:
@@ -1770,7 +1778,7 @@ int do_drive_del(Monitor *mon, const QDict *qdict, QObject **ret_data)
      */
     if (bdrv_get_attached_dev(bs)) {
         bdrv_make_anon(bs);
-
+        blk_unref(blk_by_name(id));
         /* Further I/O must not pause the guest */
         bdrv_set_on_error(bs, BLOCKDEV_ON_ERROR_REPORT,
                           BLOCKDEV_ON_ERROR_REPORT);
hw/block/xen_disk.c +11 -0
index 8bac7ff..730a021 100644
@@ -39,6 +39,7 @@
 #include "hw/xen/xen_backend.h"
 #include "xen_blkif.h"
 #include "sysemu/blockdev.h"
+#include "sysemu/block-backend.h"
 
 /* ------------------------------------------------------------- */
 
@@ -852,12 +853,18 @@ static int blk_connect(struct XenDevice *xendev)
     blkdev->dinfo = drive_get(IF_XEN, 0, index);
     if (!blkdev->dinfo) {
         Error *local_err = NULL;
+        BlockBackend *blk;
         BlockDriver *drv;
 
         /* setup via xenbus -> create new block driver instance */
         xen_be_printf(&blkdev->xendev, 2, "create new bdrv (xenbus setup)\n");
+        blk = blk_new(blkdev->dev, NULL);
+        if (!blk) {
+            return -1;
+        }
         blkdev->bs = bdrv_new_named(blkdev->dev, NULL);
         if (!blkdev->bs) {
+            blk_unref(blk);
             return -1;
         }
 
@@ -868,6 +875,7 @@ static int blk_connect(struct XenDevice *xendev)
                           error_get_pretty(local_err));
             error_free(local_err);
             bdrv_unref(blkdev->bs);
+            blk_unref(blk);
             blkdev->bs = NULL;
             return -1;
         }
@@ -983,6 +991,9 @@ static void blk_disconnect(struct XenDevice *xendev)
     if (blkdev->bs) {
         bdrv_detach_dev(blkdev->bs, blkdev);
         bdrv_unref(blkdev->bs);
+        if (!blkdev->dinfo) {
+            blk_unref(blk_by_name(blkdev->dev));
+        }
         blkdev->bs = NULL;
     }
     xen_be_unbind_evtchn(&blkdev->xendev);
include/qemu/typedefs.h +1 -0
index 5f20b0e..198da2e 100644
@@ -35,6 +35,7 @@ typedef struct MachineClass MachineClass;
 typedef struct NICInfo NICInfo;
 typedef struct HCIInfo HCIInfo;
 typedef struct AudioState AudioState;
+typedef struct BlockBackend BlockBackend;
 typedef struct BlockDriverState BlockDriverState;
 typedef struct DriveInfo DriveInfo;
 typedef struct DisplayState DisplayState;
include/sysemu/block-backend.h new file +26 -0
new file mode 100644
index 0000000..3f8371c
@@ -0,0 +1,26 @@
+/*
+ * QEMU Block backends
+ *
+ * Copyright (C) 2014 Red Hat, Inc.
+ *
+ * Authors:
+ *  Markus Armbruster <[email protected]>,
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or
+ * later.  See the COPYING file in the top-level directory.
+ */
+
+#ifndef BLOCK_BACKEND_H
+#define BLOCK_BACKEND_H
+
+#include "qemu/typedefs.h"
+#include "qapi/error.h"
+
+BlockBackend *blk_new(const char *name, Error **errp);
+void blk_ref(BlockBackend *blk);
+void blk_unref(BlockBackend *blk);
+const char *blk_name(BlockBackend *blk);
+BlockBackend *blk_by_name(const char *name);
+BlockBackend *blk_next(BlockBackend *blk);
+
+#endif
qemu-img.c +2 -0
index 4490a22..bad3f64 100644
@@ -29,6 +29,7 @@
 #include "qemu/error-report.h"
 #include "qemu/osdep.h"
 #include "sysemu/sysemu.h"
+#include "sysemu/block-backend.h"
 #include "block/block_int.h"
 #include "block/qapi.h"
 #include <getopt.h>
@@ -575,6 +576,7 @@ static int img_check(int argc, char **argv)
     int c, ret;
     OutputFormat output_format = OFORMAT_HUMAN;
     const char *filename, *fmt, *output, *cache;
+    BlockBackend *blk;
     BlockDriverState *bs;
     int fix = 0;
     int flags = BDRV_O_FLAGS | BDRV_O_CHECK;
@@ -649,6 +651,7 @@ static int img_check(int argc, char **argv)
         return 1;
     }
 
Quoted 2 lines

qemu-img.c static int img_check(int argc, char **argv) · line 654

Quoted 1 line
qemu-img.c +1 -0
+    blk = blk_new("image", &error_abort);

Hmm we are so sure this will work that we don't do if (!block) ?

Ok I understood we are sure because we control the id and won't use twice the same.

Quoted 391 lines
Quoted 135 lines
qemu-img.c +21 -0
     bs = bdrv_new_open("image", filename, fmt, flags, true, quiet);
     if (!bs) {
         return 1;
@@ -710,6 +713,7 @@ static int img_check(int argc, char **argv)
 fail:
     qapi_free_ImageCheck(check);
     bdrv_unref(bs);
+    blk_unref(blk);
 
     return ret;
 }
@@ -718,6 +722,7 @@ static int img_commit(int argc, char **argv)
 {
     int c, ret, flags;
     const char *filename, *fmt, *cache;
+    BlockBackend *blk;
     BlockDriverState *bs;
     bool quiet = false;
 
@@ -756,6 +761,7 @@ static int img_commit(int argc, char **argv)
         return 1;
     }
 
+    blk = blk_new("image", &error_abort);
     bs = bdrv_new_open("image", filename, fmt, flags, true, quiet);
     if (!bs) {
         return 1;
@@ -780,6 +786,7 @@ static int img_commit(int argc, char **argv)
     }
 
     bdrv_unref(bs);
+    blk_unref(blk);
     if (ret) {
         return 1;
     }
@@ -942,6 +949,7 @@ static int check_empty_sectors(BlockDriverState *bs, int64_t sect_num,
 static int img_compare(int argc, char **argv)
 {
     const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
+    BlockBackend *blk1, *blk2;
     BlockDriverState *bs1, *bs2;
     int64_t total_sectors1, total_sectors2;
     uint8_t *buf1 = NULL, *buf2 = NULL;
@@ -1011,6 +1019,7 @@ static int img_compare(int argc, char **argv)
         goto out3;
     }
 
+    blk1 = blk_new("image 1", &error_abort);
     bs1 = bdrv_new_open("image 1", filename1, fmt1, flags, true, quiet);
     if (!bs1) {
         error_report("Can't open file %s", filename1);
@@ -1018,6 +1027,7 @@ static int img_compare(int argc, char **argv)
         goto out3;
     }
 
+    blk2 = blk_new("image 2", &error_abort);
     bs2 = bdrv_new_open("image 2", filename2, fmt2, flags, true, quiet);
     if (!bs2) {
         error_report("Can't open file %s", filename2);
@@ -1184,10 +1194,12 @@ static int img_compare(int argc, char **argv)
 
 out:
     bdrv_unref(bs2);
+    blk_unref(blk2);
     qemu_vfree(buf1);
     qemu_vfree(buf2);
 out2:
     bdrv_unref(bs1);
+    blk_unref(blk1);
 out3:
     qemu_progress_end();
     return ret;
@@ -1200,6 +1212,7 @@ static int img_convert(int argc, char **argv)
     int progress = 0, flags, src_flags;
     const char *fmt, *out_fmt, *cache, *src_cache, *out_baseimg, *out_filename;
     BlockDriver *drv, *proto_drv;
+    BlockBackend **blk = NULL, *out_blk = NULL;
     BlockDriverState **bs = NULL, *out_bs = NULL;
     int64_t total_sectors, nb_sectors, sector_num, bs_offset;
     int64_t *bs_sectors = NULL;
@@ -1354,6 +1367,7 @@ static int img_convert(int argc, char **argv)
 
     qemu_progress_print(0, 100);
 
+    blk = g_new0(BlockBackend *, bs_n);
     bs = g_new0(BlockDriverState *, bs_n);
     bs_sectors = g_new(int64_t, bs_n);
 
@@ -1361,6 +1375,7 @@ static int img_convert(int argc, char **argv)
     for (bs_i = 0; bs_i < bs_n; bs_i++) {
         char *id = bs_n > 1 ? g_strdup_printf("source %d", bs_i)
                             : g_strdup("source");
+        blk[bs_i] = blk_new(id, &error_abort);
         bs[bs_i] = bdrv_new_open(id, argv[optind + bs_i], fmt, src_flags,
                                  true, quiet);
         g_free(id);
@@ -1486,6 +1501,7 @@ static int img_convert(int argc, char **argv)
         goto out;
     }
 
+    out_blk = blk_new("target", &error_abort);
     out_bs = bdrv_new_open("target", out_filename, out_fmt, flags, true, quiet);
     if (!out_bs) {
         ret = -1;
@@ -1742,6 +1758,7 @@ out:
     if (out_bs) {
         bdrv_unref(out_bs);
     }
+    blk_unref(out_blk);
     if (bs) {
         for (bs_i = 0; bs_i < bs_n; bs_i++) {
             if (bs[bs_i]) {
@@ -1750,6 +1767,12 @@ out:
         }
         g_free(bs);
     }
+    if (blk) {
+        for (bs_i = 0; bs_i < bs_n; bs_i++) {
+            blk_unref(blk[bs_i]);
+        }
+        g_free(blk);
+    }
     g_free(bs_sectors);
 fail_getopt:
     g_free(options);
@@ -1858,6 +1881,7 @@ static ImageInfoList *collect_image_info_list(const char *filename,
     filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
 
     while (filename) {
+        BlockBackend *blk;
         BlockDriverState *bs;
         ImageInfo *info;
         ImageInfoList *elem;

qemu-img.c static ImageInfoList *collect_image_info_list(const char *filename, · line 1899

Quoted 7 lines
qemu-img.c +1 -0
@@ -1869,6 +1893,7 @@ static ImageInfoList *collect_image_info_list(const char *filename,
         }
         g_hash_table_insert(filenames, (gpointer)filename, NULL);
 
+        blk = blk_new("image", &error_abort);
         bs = bdrv_new_open("image", filename, fmt,
                            BDRV_O_FLAGS | BDRV_O_NO_BACKING, false, false);
         if (!bs) {

I think it misses an

Quoted 1 line

+ blk_unref(blk);

in if(!bs) branch.

Quoted 191 lines
qemu-img.c +21 -0
@@ -1880,6 +1905,7 @@ static ImageInfoList *collect_image_info_list(const char *filename,
             error_report("%s", error_get_pretty(err));
             error_free(err);
             bdrv_unref(bs);
+            blk_unref(blk);
             goto err;
         }
 
@@ -1889,6 +1915,7 @@ static ImageInfoList *collect_image_info_list(const char *filename,
         last = &elem->next;
 
         bdrv_unref(bs);
+        blk_unref(blk);
 
         filename = fmt = NULL;
         if (chain) {
@@ -2082,6 +2109,7 @@ static int img_map(int argc, char **argv)
 {
     int c;
     OutputFormat output_format = OFORMAT_HUMAN;
+    BlockBackend *blk;
     BlockDriverState *bs;
     const char *filename, *fmt, *output;
     int64_t length;
@@ -2130,6 +2158,7 @@ static int img_map(int argc, char **argv)
         return 1;
     }
 
+    blk = blk_new("image", &error_abort);
     bs = bdrv_new_open("image", filename, fmt, BDRV_O_FLAGS, true, false);
     if (!bs) {
         return 1;
@@ -2175,6 +2204,7 @@ static int img_map(int argc, char **argv)
 
 out:
     bdrv_unref(bs);
+    blk_unref(blk);
     return ret < 0;
 }
 
@@ -2185,6 +2215,7 @@ out:
 
 static int img_snapshot(int argc, char **argv)
 {
+    BlockBackend *blk;
     BlockDriverState *bs;
     QEMUSnapshotInfo sn;
     char *filename, *snapshot_name = NULL;
@@ -2250,6 +2281,7 @@ static int img_snapshot(int argc, char **argv)
     filename = argv[optind++];
 
     /* Open the image */
+    blk = blk_new("image", &error_abort);
     bs = bdrv_new_open("image", filename, NULL, bdrv_oflags, true, quiet);
     if (!bs) {
         return 1;
@@ -2297,6 +2329,7 @@ static int img_snapshot(int argc, char **argv)
 
     /* Cleanup */
     bdrv_unref(bs);
+    blk_unref(blk);
     if (ret) {
         return 1;
     }
@@ -2305,6 +2338,7 @@ static int img_snapshot(int argc, char **argv)
 
 static int img_rebase(int argc, char **argv)
 {
+    BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
     BlockDriverState *bs = NULL, *bs_old_backing = NULL, *bs_new_backing = NULL;
     BlockDriver *old_backing_drv, *new_backing_drv;
     char *filename;
@@ -2393,6 +2427,7 @@ static int img_rebase(int argc, char **argv)
      * Ignore the old backing file for unsafe rebase in case we want to correct
      * the reference to a renamed or moved backing file.
      */
+    blk = blk_new("image", &error_abort);
     bs = bdrv_new_open("image", filename, fmt, flags, true, quiet);
     if (!bs) {
         ret = -1;
@@ -2425,6 +2460,7 @@ static int img_rebase(int argc, char **argv)
     if (!unsafe) {
         char backing_name[1024];
 
+        blk_old_backing = blk_new("old_backing", &error_abort);
         bs_old_backing = bdrv_new_named("old_backing", &error_abort);
         bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
         ret = bdrv_open(&bs_old_backing, backing_name, NULL, NULL, src_flags,
@@ -2436,6 +2472,7 @@ static int img_rebase(int argc, char **argv)
             goto out;
         }
         if (out_baseimg[0]) {
+            blk_new_backing = blk_new("new_backing", &error_abort);
             bs_new_backing = bdrv_new_named("new_backing", &error_abort);
             ret = bdrv_open(&bs_new_backing, out_baseimg, NULL, NULL, src_flags,
                             new_backing_drv, &local_err);
@@ -2614,12 +2651,15 @@ out:
         if (bs_old_backing != NULL) {
             bdrv_unref(bs_old_backing);
         }
+        blk_unref(blk_old_backing);
         if (bs_new_backing != NULL) {
             bdrv_unref(bs_new_backing);
         }
+        blk_unref(blk_new_backing);
     }
 
     bdrv_unref(bs);
+    blk_unref(blk);
     if (ret) {
         return 1;
     }
@@ -2632,6 +2672,7 @@ static int img_resize(int argc, char **argv)
     const char *filename, *fmt, *size;
     int64_t n, total_size;
     bool quiet = false;
+    BlockBackend *blk = NULL;
     BlockDriverState *bs = NULL;
     QemuOpts *param;
     static QemuOptsList resize_options = {
@@ -2708,6 +2749,7 @@ static int img_resize(int argc, char **argv)
     n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
     qemu_opts_del(param);
 
+    blk = blk_new("image", &error_abort);
     bs = bdrv_new_open("image", filename, fmt, BDRV_O_FLAGS | BDRV_O_RDWR,
                        true, quiet);
     if (!bs) {
@@ -2745,6 +2787,7 @@ out:
     if (bs) {
         bdrv_unref(bs);
     }
+    blk_unref(blk);
     if (ret) {
         return 1;
     }
@@ -2760,6 +2803,7 @@ static int img_amend(int argc, char **argv)
     const char *fmt = NULL, *filename, *cache;
     int flags;
     bool quiet = false;
+    BlockBackend *blk = NULL;
     BlockDriverState *bs = NULL;
 
     cache = BDRV_DEFAULT_CACHE;
@@ -2823,6 +2867,7 @@ static int img_amend(int argc, char **argv)
         goto out;
     }
 
+    blk = blk_new("image", &error_abort);
     bs = bdrv_new_open("image", filename, fmt, flags, true, quiet);
     if (!bs) {
         error_report("Could not open image '%s'", filename);
@@ -2856,6 +2901,7 @@ out:
     if (bs) {
         bdrv_unref(bs);
     }
+    blk_unref(blk);
     qemu_opts_del(opts);
     qemu_opts_free(create_opts);
     g_free(options);
qemu-io.c +4 -0
index 44c2e1c..45e5494 100644
@@ -19,6 +19,7 @@
 #include "qemu/option.h"
 #include "qemu/config-file.h"
 #include "qemu/readline.h"
+#include "sysemu/block-backend.h"
 #include "block/block_int.h"
 #include "trace/control.h"
 
@@ -26,6 +27,7 @@
 
 static char *progname;
 
+static BlockBackend *qemuio_blk;
 static BlockDriverState *qemuio_bs;
 
 /* qemu-io commands passed using -c */
@@ -37,7 +39,9 @@ static ReadLineState *readline_state;
 static int close_f(BlockDriverState *bs, int argc, char **argv)
 {
     bdrv_unref(bs);
+    blk_unref(qemuio_blk);
     qemuio_bs = NULL;
+    qemuio_blk = NULL;
     return 0;
 }
 

qemu-io.c static int openfile(char *name, int flags, int growable, QDict *opts) · line 67

Quoted 6 lines
qemu-io.c +1 -0
@@ -58,6 +62,7 @@ static int openfile(char *name, int flags, int growable, QDict *opts)
         return 1;
     }
 
+    qemuio_blk = blk_new("hda", &error_abort);
 
     qemuio_bs = bdrv_new_named("hda", &error_abort);

I see accepting that an allocation _will_ work is the qemu tools style.

Quoted 45 lines
qemu-io.c +3 -0
     if (growable) {
@@ -70,7 +75,9 @@ static int openfile(char *name, int flags, int growable, QDict *opts)
                 error_get_pretty(local_err));
         error_free(local_err);
         bdrv_unref(qemuio_bs);
+        blk_unref(qemuio_blk);
         qemuio_bs = NULL;
+        qemuio_blk = NULL;
         return 1;
     }
 
@@ -479,6 +486,7 @@ int main(int argc, char **argv)
     if (qemuio_bs) {
         bdrv_unref(qemuio_bs);
     }
+    blk_unref(qemuio_blk);
     g_free(readline_state);
     return 0;
 }
qemu-nbd.c +2 -1
index a56ebfc..94b9b49 100644
@@ -17,7 +17,7 @@
  */
 
 #include "qemu-common.h"
-#include "block/block.h"
+#include "sysemu/block-backend.h"
 #include "block/block_int.h"
 #include "block/nbd.h"
 #include "qemu/main-loop.h"
@@ -687,6 +687,7 @@ int main(int argc, char **argv)
         drv = NULL;
     }
 
+    blk_new("hda", &error_abort);
     bs = bdrv_new_named("hda", &error_abort);
 
     srcpath = argv[optind];
Signature · 1 line
1.9.3
#21 lore raw

Re: [Qemu-devel] [PATCH 02/23] block: New BlockBackend

Quoted 2 lines · Benoît Canet
Quoted 1 line · Benoît Canet

The Wednesday 10 Sep 2014 à 10:13:31 (+0200), Markus Armbruster wrote :

[...]

Quoted 25 lines
Quoted 25 lines
Quoted 24 lines
qemu-img.c +2 -0
index 4490a22..bad3f64 100644
@@ -29,6 +29,7 @@
 #include "qemu/error-report.h"
 #include "qemu/osdep.h"
 #include "sysemu/sysemu.h"
+#include "sysemu/block-backend.h"
 #include "block/block_int.h"
 #include "block/qapi.h"
 #include <getopt.h>
@@ -575,6 +576,7 @@ static int img_check(int argc, char **argv)
     int c, ret;
     OutputFormat output_format = OFORMAT_HUMAN;
     const char *filename, *fmt, *output, *cache;
+    BlockBackend *blk;
     BlockDriverState *bs;
     int fix = 0;
     int flags = BDRV_O_FLAGS | BDRV_O_CHECK;
@@ -649,6 +651,7 @@ static int img_check(int argc, char **argv)
         return 1;
     }
 
Quoted 4 lines
Quoted 2 lines

qemu-img.c static int img_check(int argc, char **argv) · line 654

Quoted 1 line
qemu-img.c +1 -0
+    blk = blk_new("image", &error_abort);

Hmm we are so sure this will work that we don't do if (!block) ?

Ok I understood we are sure because we control the id and won't use twice the same.

Exactly!

[...]

#22 lore raw

Re: [Qemu-devel] [PATCH 02/23] block: New BlockBackend

In reply to Benoît Canet
Quoted 215 lines · Benoît Canet
Quoted 214 lines · Markus Armbruster

A block device consists of a frontend device model and a backend.

A block backend has a tree of block drivers doing the actual work. The tree is managed by the block layer.

We currently use a single abstraction BlockDriverState both for tree nodes and the backend as a whole. Drawbacks:

* Its API includes both stuff that makes sense only at the block backend level (root of the tree) and stuff that's only for use within the block layer. This makes the API bigger and more complex than necessary. Moreover, it's not obvious which interfaces are meant for device models, and which really aren't.

* Since device models keep a reference to their backend, the backend object can't just be destroyed. But for media change, we need to replace the tree. Our solution is to make the BlockDriverState generic, with actual driver state in a separate object, pointed to by member opaque. That lets us replace the tree by deinitializing and reinitializing its root. This special need of the root makes the data structure awkward everywhere in the tree.

The general plan is to separate the APIs into "block backend", for use by device models, monitor and whatever other code dealing with block backends, and "block driver", for use by the block layer and whatever other code (if any) dealing with trees and tree nodes.

Code dealing with block backends, device models in particular, should become completely oblivious of BlockDriverState. This should let us clean up both APIs, and the tree data structures.

This commit is a first step. It creates a minimal "block backend"
API: type BlockBackend and functions to create, destroy and find them. BlockBackend objects are created and destroyed, but not yet used for anything; that'll come shortly.

BlockBackend is reference-counted. Its reference count never exceeds one so far, but that's going to change.

---
 block/Makefile.objs            |   2 +-
 block/block-backend.c          | 110 +++++++++++++++++++++++++++++++++++++++++
 blockdev.c                     |  10 +++-
 hw/block/xen_disk.c            |  11 +++++
 include/qemu/typedefs.h        |   1 +
 include/sysemu/block-backend.h |  26 ++++++++++
 qemu-img.c                     |  46 +++++++++++++++++
 qemu-io.c                      |   8 +++
 qemu-nbd.c                     |   3 +-
 9 files changed, 214 insertions(+), 3 deletions(-)
 create mode 100644 block/block-backend.c
 create mode 100644 include/sysemu/block-backend.h
block/Makefile.objs +1 -1
index f45f939..a70140b 100644
@@ -5,7 +5,7 @@ block-obj-y += qed-check.o
 block-obj-$(CONFIG_VHDX) += vhdx.o vhdx-endian.o vhdx-log.o
 block-obj-$(CONFIG_QUORUM) += quorum.o
 block-obj-y += parallels.o blkdebug.o blkverify.o
-block-obj-y += snapshot.o qapi.o
+block-obj-y += block-backend.o snapshot.o qapi.o
 block-obj-$(CONFIG_WIN32) += raw-win32.o win32-aio.o
 block-obj-$(CONFIG_POSIX) += raw-posix.o
 block-obj-$(CONFIG_LINUX_AIO) += linux-aio.o
block/block-backend.c new file +110 -0
new file mode 100644
index 0000000..833f7d9
@@ -0,0 +1,110 @@
+/*
+ * QEMU Block backends
+ *
+ * Copyright (C) 2014 Red Hat, Inc.
+ *
+ * Authors:
+ *  Markus Armbruster <[email protected]>,
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or
+ * later.  See the COPYING file in the top-level directory.
+ */
+
+#include "sysemu/block-backend.h"
+#include "block/block_int.h"
+
+struct BlockBackend {
+    char *name;
+    int refcnt;
+    QTAILQ_ENTRY(BlockBackend) link; /* for blk_backends */
+};
+
+static QTAILQ_HEAD(, BlockBackend) blk_backends =
+    QTAILQ_HEAD_INITIALIZER(blk_backends);
+
+/**
+ * blk_new:
+ * @name: name, must not be %NULL or empty
+ * @errp: return location for an error to be set on failure, or %NULL
+ *
+ * Create a new BlockBackend, with a reference count of one.  Fail if
+ * @name already exists.
+ *
+ * Returns: the BlockBackend on success, %NULL on failure
+ */
+BlockBackend *blk_new(const char *name, Error **errp)
+{
+    BlockBackend *blk = g_new0(BlockBackend, 1);
+
+    assert(name && name[0]);
+    if (blk_by_name(name)) {
+        error_setg(errp, "Device with id '%s' already exists", name);
+        return NULL;
+    }
+    blk->name = g_strdup(name);
+    blk->refcnt = 1;
+    QTAILQ_INSERT_TAIL(&blk_backends, blk, link);
+    return blk;
+}
+
+static void blk_delete(BlockBackend *blk)
+{
+    assert(!blk->refcnt);
+    QTAILQ_REMOVE(&blk_backends, blk, link);
+    g_free(blk->name);
+    g_free(blk);
+}
+
+/**
+ * blk_ref:
+ *
+ * Increment @blk's reference count.
+ */
+void blk_ref(BlockBackend *blk)
+{
+    blk->refcnt++;
+}
+
+/**
+ * blk_unref:
+ *
+ * Decrement @blk's reference count.  If this drops it to zero,
+ * destroy @blk.
+ */
+void blk_unref(BlockBackend *blk)
+{
+    if (blk) {
+        g_assert(blk->refcnt > 0);
+        if (!--blk->refcnt) {
+            blk_delete(blk);
+        }
+    }
+}
+
+const char *blk_name(BlockBackend *blk)
+{
+    return blk->name;
+}
+
+BlockBackend *blk_by_name(const char *name)
+{
+    BlockBackend *blk;
+
+    QTAILQ_FOREACH(blk, &blk_backends, link) {
+        if (!strcmp(name, blk->name)) {
+            return blk;
+        }
+    }
+    return NULL;
+}
+
+/**
+ * blk_next:
+ *
+ * Returns: the first BlockBackend if @blk is null, else @blk's next
+ * sibling, which is %NULL for the last BlockBackend
+ */
+BlockBackend *blk_next(BlockBackend *blk)
+{
+    return blk ? QTAILQ_NEXT(blk, link) : QTAILQ_FIRST(&blk_backends);
+}
blockdev.c +3 -0
index 9fbd888..86596bc 100644
@@ -30,6 +30,7 @@
  * THE SOFTWARE.
  */
 
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "hw/block/block.h"
 #include "block/blockjob.h"
@@ -221,6 +222,7 @@ void drive_del(DriveInfo *dinfo)
     }
 
     bdrv_unref(dinfo->bdrv);
+    blk_unref(blk_by_name(dinfo->id));
     g_free(dinfo->id);
     QTAILQ_REMOVE(&drives, dinfo, next);
     g_free(dinfo->serial);
@@ -301,6 +303,7 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
     int ro = 0;
     int bdrv_flags = 0;
     int on_read_error, on_write_error;
+    BlockBackend *blk;
     DriveInfo *dinfo;
     ThrottleConfig cfg;
     int snapshot = 0;
@@ -456,6 +459,10 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
     }
 
Quoted 8 lines

blockdev.c static DriveInfo *blockdev_init(const char *file, QDict *bs_opts, · line 465

Quoted 5 lines
blockdev.c +4 -0
     /* init */
+    blk = blk_new(qemu_opts_id(opts), errp);
+    if (!blk) {
+        goto early_err;
+    }

Here you create a new block backend.
And you don't attach it to anything in any way yet.

Yes. Right before creating the root BDS.

Quoted 10 lines

So down in the code the following test will leak it:

    if (!file || !*file) {                                                      
        if (has_driver_specific_opts) {                                         
            file = NULL;                                                        
        } else {                                                                
            QDECREF(bs_opts);                                                   
            qemu_opts_del(opts);                                                
            return dinfo;                                                       
        }                                                                       
    } 

The root BDS isn't destroyed here, and therefore the BB isn't, either.

The BB will be destroyed right when the root BDS is.

Quoted 141 lines

I am sure one of your next patchs fixes this but for this precise commit this do look like a leak.

Quoted 137 lines
blockdev.c +2 -1
     dinfo = g_malloc0(sizeof(*dinfo));
     dinfo->id = g_strdup(qemu_opts_id(opts));
     dinfo->bdrv = bdrv_new_named(dinfo->id, &error);
@@ -525,6 +532,7 @@ err:
 bdrv_new_err:
     g_free(dinfo->id);
     g_free(dinfo);
+    blk_unref(blk);
 early_err:
     qemu_opts_del(opts);
 err_no_opts:
@@ -1770,7 +1778,7 @@ int do_drive_del(Monitor *mon, const QDict *qdict, QObject **ret_data)
      */
     if (bdrv_get_attached_dev(bs)) {
         bdrv_make_anon(bs);
-
+        blk_unref(blk_by_name(id));
         /* Further I/O must not pause the guest */
         bdrv_set_on_error(bs, BLOCKDEV_ON_ERROR_REPORT,
                           BLOCKDEV_ON_ERROR_REPORT);
hw/block/xen_disk.c +11 -0
index 8bac7ff..730a021 100644
@@ -39,6 +39,7 @@
 #include "hw/xen/xen_backend.h"
 #include "xen_blkif.h"
 #include "sysemu/blockdev.h"
+#include "sysemu/block-backend.h"
 
 /* ------------------------------------------------------------- */
 
@@ -852,12 +853,18 @@ static int blk_connect(struct XenDevice *xendev)
     blkdev->dinfo = drive_get(IF_XEN, 0, index);
     if (!blkdev->dinfo) {
         Error *local_err = NULL;
+        BlockBackend *blk;
         BlockDriver *drv;
 
         /* setup via xenbus -> create new block driver instance */
         xen_be_printf(&blkdev->xendev, 2, "create new bdrv (xenbus setup)\n");
+        blk = blk_new(blkdev->dev, NULL);
+        if (!blk) {
+            return -1;
+        }
         blkdev->bs = bdrv_new_named(blkdev->dev, NULL);
         if (!blkdev->bs) {
+            blk_unref(blk);
             return -1;
         }
 
@@ -868,6 +875,7 @@ static int blk_connect(struct XenDevice *xendev)
                           error_get_pretty(local_err));
             error_free(local_err);
             bdrv_unref(blkdev->bs);
+            blk_unref(blk);
             blkdev->bs = NULL;
             return -1;
         }
@@ -983,6 +991,9 @@ static void blk_disconnect(struct XenDevice *xendev)
     if (blkdev->bs) {
         bdrv_detach_dev(blkdev->bs, blkdev);
         bdrv_unref(blkdev->bs);
+        if (!blkdev->dinfo) {
+            blk_unref(blk_by_name(blkdev->dev));
+        }
         blkdev->bs = NULL;
     }
     xen_be_unbind_evtchn(&blkdev->xendev);
include/qemu/typedefs.h +1 -0
index 5f20b0e..198da2e 100644
@@ -35,6 +35,7 @@ typedef struct MachineClass MachineClass;
 typedef struct NICInfo NICInfo;
 typedef struct HCIInfo HCIInfo;
 typedef struct AudioState AudioState;
+typedef struct BlockBackend BlockBackend;
 typedef struct BlockDriverState BlockDriverState;
 typedef struct DriveInfo DriveInfo;
 typedef struct DisplayState DisplayState;
include/sysemu/block-backend.h new file +26 -0
new file mode 100644
index 0000000..3f8371c
@@ -0,0 +1,26 @@
+/*
+ * QEMU Block backends
+ *
+ * Copyright (C) 2014 Red Hat, Inc.
+ *
+ * Authors:
+ *  Markus Armbruster <[email protected]>,
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or
+ * later.  See the COPYING file in the top-level directory.
+ */
+
+#ifndef BLOCK_BACKEND_H
+#define BLOCK_BACKEND_H
+
+#include "qemu/typedefs.h"
+#include "qapi/error.h"
+
+BlockBackend *blk_new(const char *name, Error **errp);
+void blk_ref(BlockBackend *blk);
+void blk_unref(BlockBackend *blk);
+const char *blk_name(BlockBackend *blk);
+BlockBackend *blk_by_name(const char *name);
+BlockBackend *blk_next(BlockBackend *blk);
+
+#endif
qemu-img.c +2 -0
index 4490a22..bad3f64 100644
@@ -29,6 +29,7 @@
 #include "qemu/error-report.h"
 #include "qemu/osdep.h"
 #include "sysemu/sysemu.h"
+#include "sysemu/block-backend.h"
 #include "block/block_int.h"
 #include "block/qapi.h"
 #include <getopt.h>
@@ -575,6 +576,7 @@ static int img_check(int argc, char **argv)
     int c, ret;
     OutputFormat output_format = OFORMAT_HUMAN;
     const char *filename, *fmt, *output, *cache;
+    BlockBackend *blk;
     BlockDriverState *bs;
     int fix = 0;
     int flags = BDRV_O_FLAGS | BDRV_O_CHECK;
@@ -649,6 +651,7 @@ static int img_check(int argc, char **argv)
         return 1;
     }
 
Quoted 2 lines

qemu-img.c static int img_check(int argc, char **argv) · line 654

Quoted 1 line
qemu-img.c +1 -0
+    blk = blk_new("image", &error_abort);

Hmm we are so sure this will work that we don't do if (!block) ?

Matches what bdrv_new_open() does:

    bs = bdrv_new_named(id, &error_abort);

As you noted further down, the tools treat these failures as programming errors. That's appropriate.

Quoted 137 lines
Quoted 137 lines
qemu-img.c +21 -0
     bs = bdrv_new_open("image", filename, fmt, flags, true, quiet);
     if (!bs) {
         return 1;
@@ -710,6 +713,7 @@ static int img_check(int argc, char **argv)
 fail:
     qapi_free_ImageCheck(check);
     bdrv_unref(bs);
+    blk_unref(blk);
 
     return ret;
 }
@@ -718,6 +722,7 @@ static int img_commit(int argc, char **argv)
 {
     int c, ret, flags;
     const char *filename, *fmt, *cache;
+    BlockBackend *blk;
     BlockDriverState *bs;
     bool quiet = false;
 
@@ -756,6 +761,7 @@ static int img_commit(int argc, char **argv)
         return 1;
     }
 
+    blk = blk_new("image", &error_abort);
     bs = bdrv_new_open("image", filename, fmt, flags, true, quiet);
     if (!bs) {
         return 1;
@@ -780,6 +786,7 @@ static int img_commit(int argc, char **argv)
     }
 
     bdrv_unref(bs);
+    blk_unref(blk);
     if (ret) {
         return 1;
     }
@@ -942,6 +949,7 @@ static int check_empty_sectors(BlockDriverState *bs, int64_t sect_num,
 static int img_compare(int argc, char **argv)
 {
     const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
+    BlockBackend *blk1, *blk2;
     BlockDriverState *bs1, *bs2;
     int64_t total_sectors1, total_sectors2;
     uint8_t *buf1 = NULL, *buf2 = NULL;
@@ -1011,6 +1019,7 @@ static int img_compare(int argc, char **argv)
         goto out3;
     }
 
+    blk1 = blk_new("image 1", &error_abort);
     bs1 = bdrv_new_open("image 1", filename1, fmt1, flags, true, quiet);
     if (!bs1) {
         error_report("Can't open file %s", filename1);
@@ -1018,6 +1027,7 @@ static int img_compare(int argc, char **argv)
         goto out3;
     }
 
+    blk2 = blk_new("image 2", &error_abort);
     bs2 = bdrv_new_open("image 2", filename2, fmt2, flags, true, quiet);
     if (!bs2) {
         error_report("Can't open file %s", filename2);
@@ -1184,10 +1194,12 @@ static int img_compare(int argc, char **argv)
 
 out:
     bdrv_unref(bs2);
+    blk_unref(blk2);
     qemu_vfree(buf1);
     qemu_vfree(buf2);
 out2:
     bdrv_unref(bs1);
+    blk_unref(blk1);
 out3:
     qemu_progress_end();
     return ret;
@@ -1200,6 +1212,7 @@ static int img_convert(int argc, char **argv)
     int progress = 0, flags, src_flags;
     const char *fmt, *out_fmt, *cache, *src_cache, *out_baseimg, *out_filename;
     BlockDriver *drv, *proto_drv;
+    BlockBackend **blk = NULL, *out_blk = NULL;
     BlockDriverState **bs = NULL, *out_bs = NULL;
     int64_t total_sectors, nb_sectors, sector_num, bs_offset;
     int64_t *bs_sectors = NULL;
@@ -1354,6 +1367,7 @@ static int img_convert(int argc, char **argv)
 
     qemu_progress_print(0, 100);
 
+    blk = g_new0(BlockBackend *, bs_n);
     bs = g_new0(BlockDriverState *, bs_n);
     bs_sectors = g_new(int64_t, bs_n);
 
@@ -1361,6 +1375,7 @@ static int img_convert(int argc, char **argv)
     for (bs_i = 0; bs_i < bs_n; bs_i++) {
         char *id = bs_n > 1 ? g_strdup_printf("source %d", bs_i)
                             : g_strdup("source");
+        blk[bs_i] = blk_new(id, &error_abort);
         bs[bs_i] = bdrv_new_open(id, argv[optind + bs_i], fmt, src_flags,
                                  true, quiet);
         g_free(id);
@@ -1486,6 +1501,7 @@ static int img_convert(int argc, char **argv)
         goto out;
     }
 
+    out_blk = blk_new("target", &error_abort);
     out_bs = bdrv_new_open("target", out_filename, out_fmt, flags, true, quiet);
     if (!out_bs) {
         ret = -1;
@@ -1742,6 +1758,7 @@ out:
     if (out_bs) {
         bdrv_unref(out_bs);
     }
+    blk_unref(out_blk);
     if (bs) {
         for (bs_i = 0; bs_i < bs_n; bs_i++) {
             if (bs[bs_i]) {
@@ -1750,6 +1767,12 @@ out:
         }
         g_free(bs);
     }
+    if (blk) {
+        for (bs_i = 0; bs_i < bs_n; bs_i++) {
+            blk_unref(blk[bs_i]);
+        }
+        g_free(blk);
+    }
     g_free(bs_sectors);
 fail_getopt:
     g_free(options);
@@ -1858,6 +1881,7 @@ static ImageInfoList *collect_image_info_list(const char *filename,
     filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
 
     while (filename) {
+        BlockBackend *blk;
         BlockDriverState *bs;
         ImageInfo *info;
         ImageInfoList *elem;
@@ -1869,6 +1893,7 @@ static ImageInfoList *collect_image_info_list(const char *filename,
         }
         g_hash_table_insert(filenames, (gpointer)filename, NULL);
 
Quoted 8 lines

qemu-img.c static ImageInfoList *collect_image_info_list(const char *filename, · line 1899

Quoted 4 lines
qemu-img.c +1 -0
+        blk = blk_new("image", &error_abort);
         bs = bdrv_new_open("image", filename, fmt,
                            BDRV_O_FLAGS | BDRV_O_NO_BACKING, false, false);
         if (!bs) {

I think it misses an

Quoted 1 line

+ blk_unref(blk);

in if(!bs) branch.

Yes. Kevin noted that, too. I'll fix it.

[...]

#23 lore raw

PATCH 3/23 block: Connect BlockBackend to BlockDriverState

In reply to Markus Armbruster

The pointer from BlockBackend to BlockDriverState is a strong reference, managed with bdrv_ref() / bdrv_unref(), the back-pointer is a weak one.

Convenience function blk_new_with_bs() creates a BlockBackend with its BlockDriverState. Callers have to unref both. The commit after next will relieve them of the need to unref the BlockDriverState.

---
 block.c                        |  10 ++--
 block/block-backend.c          |  79 +++++++++++++++++++++++++++++++
 blockdev.c                     |  49 +++++++++++---------
 hw/block/xen_disk.c            |   8 +---
 include/block/block_int.h      |   2 +
 include/sysemu/block-backend.h |   5 ++
 qemu-img.c                     | 103 +++++++++++++++++++++--------------------
 qemu-io.c                      |   4 +-
 qemu-nbd.c                     |   3 +-
 9 files changed, 175 insertions(+), 88 deletions(-)
block.c +6 -4
index 4b3bcd4..a6c03da 100644
@@ -2032,7 +2032,7 @@ static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
  * This will modify the BlockDriverState fields, and swap contents
  * between bs_new and bs_old. Both bs_new and bs_old are modified.
  *
- * bs_new is required to be anonymous.
+ * bs_new must be nameless and not attached to a BlockBackend.
  *
  * This function does not create any image files.
  */
@@ -2051,8 +2051,9 @@ void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old)
         QTAILQ_REMOVE(&graph_bdrv_states, bs_old, node_list);
     }
 
-    /* bs_new must be anonymous and shouldn't have anything fancy enabled */
+    /* bs_new must be nameless and shouldn't have anything fancy enabled */
     assert(bs_new->device_name[0] == '\0');
+    assert(!bs_new->blk);
     assert(QLIST_EMPTY(&bs_new->dirty_bitmaps));
     assert(bs_new->job == NULL);
     assert(bs_new->dev == NULL);
@@ -2068,8 +2069,9 @@ void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old)
     bdrv_move_feature_fields(bs_old, bs_new);
     bdrv_move_feature_fields(bs_new, &tmp);
 
-    /* bs_new shouldn't be in bdrv_states even after the swap!  */
+    /* bs_new must remain nameless and unattached */
     assert(bs_new->device_name[0] == '\0');
+    assert(!bs_new->blk);
 
     /* Check a few fields that should remain attached to the device */
     assert(bs_new->dev == NULL);
@@ -2096,7 +2098,7 @@ void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old)
  * This will modify the BlockDriverState fields, and swap contents
  * between bs_new and bs_top. Both bs_new and bs_top are modified.
  *
- * bs_new is required to be anonymous.
+ * bs_new must be nameless and not attached to a BlockBackend.
  *
  * This function does not create any image files.
  */
block/block-backend.c +79 -0

103 lines not on this page · raw message

blockdev.c +26 -23

107 lines not on this page · raw message

hw/block/xen_disk.c +2 -6
index 730a021..51f4f3a 100644
@@ -858,15 +858,11 @@ static int blk_connect(struct XenDevice *xendev)
 
         /* setup via xenbus -> create new block driver instance */
         xen_be_printf(&blkdev->xendev, 2, "create new bdrv (xenbus setup)\n");
-        blk = blk_new(blkdev->dev, NULL);
+        blk = blk_new_with_bs(blkdev->dev, NULL);
         if (!blk) {
             return -1;
         }
-        blkdev->bs = bdrv_new_named(blkdev->dev, NULL);
-        if (!blkdev->bs) {
-            blk_unref(blk);
-            return -1;
-        }
+        blkdev->bs = blk_bs(blk);
 
         drv = bdrv_find_whitelisted_format(blkdev->fileproto, readonly);
         if (bdrv_open(&blkdev->bs, blkdev->filename, NULL, NULL, qflags,
include/block/block_int.h +2 -0
index 8a61215..a04c852 100644
@@ -323,6 +323,8 @@ struct BlockDriverState {
     BlockDriver *drv; /* NULL means no media */
     void *opaque;
 
+    BlockBackend *blk;          /* owning backend, if any */
+
     void *dev;                  /* attached device model, if any */
     /* TODO change to DeviceState when all users are qdevified */
     const BlockDevOps *dev_ops;
include/sysemu/block-backend.h +5 -0
index 3f8371c..539b96f 100644
@@ -17,10 +17,15 @@
 #include "qapi/error.h"
 
 BlockBackend *blk_new(const char *name, Error **errp);
+BlockBackend *blk_new_with_bs(const char *name, Error **errp);
 void blk_ref(BlockBackend *blk);
 void blk_unref(BlockBackend *blk);
 const char *blk_name(BlockBackend *blk);
 BlockBackend *blk_by_name(const char *name);
 BlockBackend *blk_next(BlockBackend *blk);
 
+void blk_attach_bs(BlockBackend *blk, BlockDriverState *bs);
+BlockDriverState *blk_detach_bs(BlockBackend *blk);
+BlockDriverState *blk_bs(BlockBackend *blk);
+
 #endif
qemu-img.c +52 -51

239 lines not on this page · raw message

qemu-io.c +2 -2
index 45e5494..ef1d3ea 100644
@@ -62,8 +62,8 @@ static int openfile(char *name, int flags, int growable, QDict *opts)
         return 1;
     }
 
-    qemuio_blk = blk_new("hda", &error_abort);
-    qemuio_bs = bdrv_new_named("hda", &error_abort);
+    qemuio_blk = blk_new_with_bs("hda", &error_abort);
+    qemuio_bs = blk_bs(qemuio_blk);
 
     if (growable) {
         flags |= BDRV_O_PROTOCOL;
qemu-nbd.c +1 -2
index 94b9b49..8eff588 100644
@@ -687,8 +687,7 @@ int main(int argc, char **argv)
         drv = NULL;
     }
 
-    blk_new("hda", &error_abort);
-    bs = bdrv_new_named("hda", &error_abort);
+    bs = blk_bs(blk_new_with_bs("hda", &error_abort));
 
     srcpath = argv[optind];
     ret = bdrv_open(&bs, srcpath, NULL, NULL, flags, drv, &local_err);
Signature · 1 line
1.9.3
#24 lore raw

Re: [Qemu-devel] [PATCH 03/23] block: Connect BlockBackend to BlockDriverState

Quoted 26 lines · Markus Armbruster

The pointer from BlockBackend to BlockDriverState is a strong reference, managed with bdrv_ref() / bdrv_unref(), the back-pointer is a weak one.

Convenience function blk_new_with_bs() creates a BlockBackend with its BlockDriverState. Callers have to unref both. The commit after next will relieve them of the need to unref the BlockDriverState.

---
 block.c                        |  10 ++--
 block/block-backend.c          |  79 +++++++++++++++++++++++++++++++
 blockdev.c                     |  49 +++++++++++---------
 hw/block/xen_disk.c            |   8 +---
 include/block/block_int.h      |   2 +
 include/sysemu/block-backend.h |   5 ++
 qemu-img.c                     | 103 +++++++++++++++++++++--------------------
 qemu-io.c                      |   4 +-
 qemu-nbd.c                     |   3 +-
 9 files changed, 175 insertions(+), 88 deletions(-)
block.c +0 -0
index 4b3bcd4..a6c03da 100644

block.c static void bdrv_move_feature_fields(BlockDriverState *bs_dest, · line 2035

Quoted 5 lines
block.c +1 -1
@@ -2032,7 +2032,7 @@ static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
  * This will modify the BlockDriverState fields, and swap contents
  * between bs_new and bs_old. Both bs_new and bs_old are modified.
  *
- * bs_new is required to be anonymous.
+ * bs_new must be nameless and not attached to a BlockBackend.

1)
Does "nameless" refer to device_name or node_name ?

Quoted 1 line

From the code I see it's device_name but the wording can be confusing.

maybe:
+ * bs_new must have an empty device_name and not be attached to a BlockBackend.

Quoted 15 lines

*
* This function does not create any image files. */

block.c +2 -1
@@ -2051,8 +2051,9 @@ void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old)
         QTAILQ_REMOVE(&graph_bdrv_states, bs_old, node_list);
     }
 
-    /* bs_new must be anonymous and shouldn't have anything fancy enabled */
+    /* bs_new must be nameless and shouldn't have anything fancy enabled */
     assert(bs_new->device_name[0] == '\0');
+    assert(!bs_new->blk);
     assert(QLIST_EMPTY(&bs_new->dirty_bitmaps));
     assert(bs_new->job == NULL);
     assert(bs_new->dev == NULL);

block.c void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old) · line 2072

Quoted 5 lines
block.c +1 -1
@@ -2068,8 +2069,9 @@ void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old)
     bdrv_move_feature_fields(bs_old, bs_new);
     bdrv_move_feature_fields(bs_new, &tmp);
 
-    /* bs_new shouldn't be in bdrv_states even after the swap!  */
+    /* bs_new must remain nameless and unattached */

Here the proximity get rid of the ambiguity so it's ok.

block.c void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old) · line 2101

Quoted 11 lines
block.c +2 -1
     assert(bs_new->device_name[0] == '\0');
+    assert(!bs_new->blk);
 
     /* Check a few fields that should remain attached to the device */
     assert(bs_new->dev == NULL);
@@ -2096,7 +2098,7 @@ void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old)
  * This will modify the BlockDriverState fields, and swap contents
  * between bs_new and bs_top. Both bs_new and bs_top are modified.
  *
- * bs_new is required to be anonymous.
+ * bs_new must be nameless and not attached to a BlockBackend.

See 1)

Quoted 577 lines
block.c +0 -0
  *
  * This function does not create any image files.
  */
block/block-backend.c +79 -0
index 833f7d9..deccb54 100644
@@ -16,6 +16,7 @@
 struct BlockBackend {
     char *name;
     int refcnt;
+    BlockDriverState *bs;
     QTAILQ_ENTRY(BlockBackend) link; /* for blk_backends */
 };
 
@@ -47,9 +48,43 @@ BlockBackend *blk_new(const char *name, Error **errp)
     return blk;
 }
 
+/**
+ * blk_new_with_bs:
+ * @name: name, must not be %NULL or empty
+ * @errp: return location for an error to be set on failure, or %NULL
+ *
+ * Create a new BlockBackend, with a reference count of one, and
+ * attach a new BlockDriverState to it, also with a reference count of
+ * one.  Caller owns *both* references.
+ * TODO Let caller own only the BlockBackend reference
+ * Fail if @name already exists.
+ *
+ * Returns: the BlockBackend on success, %NULL on error
+ */
+BlockBackend *blk_new_with_bs(const char *name, Error **errp)
+{
+    BlockBackend *blk;
+    BlockDriverState *bs;
+
+    blk = blk_new(name, errp);
+    if (!blk) {
+        return NULL;
+    }
+
+    bs = bdrv_new_named(name, errp);
+    if (!bs) {
+        blk_unref(blk);
+        return NULL;
+    }
+
+    blk_attach_bs(blk, bs);
+    return blk;
+}
+
 static void blk_delete(BlockBackend *blk)
 {
     assert(!blk->refcnt);
+    blk_detach_bs(blk);
     QTAILQ_REMOVE(&blk_backends, blk, link);
     g_free(blk->name);
     g_free(blk);
@@ -70,6 +105,9 @@ void blk_ref(BlockBackend *blk)
  *
  * Decrement @blk's reference count.  If this drops it to zero,
  * destroy @blk.
+ *
+ * Does *not* touch the attached BlockDriverState's reference count.
+ * TODO Decrement it!
  */
 void blk_unref(BlockBackend *blk)
 {
@@ -108,3 +146,44 @@ BlockBackend *blk_next(BlockBackend *blk)
 {
     return blk ? QTAILQ_NEXT(blk, link) : QTAILQ_FIRST(&blk_backends);
 }
+
+/**
+ * blk_attach_bs:
+ *
+ * Attach @bs to @blk, taking over the caller's reference to @bs.
+ */
+void blk_attach_bs(BlockBackend *blk, BlockDriverState *bs)
+{
+    assert(!blk->bs && !bs->blk);
+    blk->bs = bs;
+    bs->blk = blk;
+}
+
+/**
+ * blk_bs:
+ *
+ * Returns: the BlockDriverState attached to @blk, or %NULL
+ */
+BlockDriverState *blk_bs(BlockBackend *blk)
+{
+    return blk->bs;
+}
+
+/**
+ * blk_detach_bs:
+ *
+ * Detach @blk's BlockDriverState, giving up its reference to the
+ * caller.
+ *
+ * Returns: the detached BlockDriverState
+ */
+BlockDriverState *blk_detach_bs(BlockBackend *blk)
+{
+    BlockDriverState *bs = blk->bs;
+
+    if (bs) {
+        bs->blk = NULL;
+        blk->bs = NULL;
+    }
+    return bs;
+}
blockdev.c +26 -23
index 86596bc..0a0b95e 100644
@@ -304,6 +304,7 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
     int bdrv_flags = 0;
     int on_read_error, on_write_error;
     BlockBackend *blk;
+    BlockDriverState *bs;
     DriveInfo *dinfo;
     ThrottleConfig cfg;
     int snapshot = 0;
@@ -459,30 +460,28 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
     }
 
     /* init */
-    blk = blk_new(qemu_opts_id(opts), errp);
+    blk = blk_new_with_bs(qemu_opts_id(opts), errp);
     if (!blk) {
         goto early_err;
     }
+    bs = blk_bs(blk);
+    bs->open_flags = snapshot ? BDRV_O_SNAPSHOT : 0;
+    bs->read_only = ro;
+    bs->detect_zeroes = detect_zeroes;
+
+    bdrv_set_on_error(bs, on_read_error, on_write_error);
+
+    /* disk I/O throttling */
+    if (throttle_enabled(&cfg)) {
+        bdrv_io_limits_enable(bs);
+        bdrv_set_io_limits(bs, &cfg);
+    }
+
     dinfo = g_malloc0(sizeof(*dinfo));
     dinfo->id = g_strdup(qemu_opts_id(opts));
-    dinfo->bdrv = bdrv_new_named(dinfo->id, &error);
-    if (error) {
-        error_propagate(errp, error);
-        goto bdrv_new_err;
-    }
-    dinfo->bdrv->open_flags = snapshot ? BDRV_O_SNAPSHOT : 0;
-    dinfo->bdrv->read_only = ro;
-    dinfo->bdrv->detect_zeroes = detect_zeroes;
+    dinfo->bdrv = bs;
     QTAILQ_INSERT_TAIL(&drives, dinfo, next);
 
-    bdrv_set_on_error(dinfo->bdrv, on_read_error, on_write_error);
-
-    /* disk I/O throttling */
-    if (throttle_enabled(&cfg)) {
-        bdrv_io_limits_enable(dinfo->bdrv);
-        bdrv_set_io_limits(dinfo->bdrv, &cfg);
-    }
-
     if (!file || !*file) {
         if (has_driver_specific_opts) {
             file = NULL;
@@ -509,7 +508,8 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
     bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
 
     QINCREF(bs_opts);
-    ret = bdrv_open(&dinfo->bdrv, file, NULL, bs_opts, bdrv_flags, drv, &error);
+    ret = bdrv_open(&bs, file, NULL, bs_opts, bdrv_flags, drv, &error);
+    assert(bs == blk_bs(blk));
 
     if (ret < 0) {
         error_setg(errp, "could not open disk image %s: %s",
@@ -518,8 +518,9 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
         goto err;
     }
 
-    if (bdrv_key_required(dinfo->bdrv))
+    if (bdrv_key_required(bs)) {
         autostart = 0;
+    }
 
     QDECREF(bs_opts);
     qemu_opts_del(opts);
@@ -529,7 +530,6 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
 err:
     bdrv_unref(dinfo->bdrv);
     QTAILQ_REMOVE(&drives, dinfo, next);
-bdrv_new_err:
     g_free(dinfo->id);
     g_free(dinfo);
     blk_unref(blk);
@@ -1746,15 +1746,17 @@ void qmp_block_set_io_throttle(const char *device, int64_t bps, int64_t bps_rd,
 int do_drive_del(Monitor *mon, const QDict *qdict, QObject **ret_data)
 {
     const char *id = qdict_get_str(qdict, "id");
+    BlockBackend *blk;
     BlockDriverState *bs;
     AioContext *aio_context;
     Error *local_err = NULL;
 
-    bs = bdrv_find(id);
-    if (!bs) {
+    blk = blk_by_name(id);
+    if (!blk) {
         error_report("Device '%s' not found", id);
         return -1;
     }
+    bs = blk_bs(blk);
 
     aio_context = bdrv_get_aio_context(bs);
     aio_context_acquire(aio_context);
@@ -1777,8 +1779,9 @@ int do_drive_del(Monitor *mon, const QDict *qdict, QObject **ret_data)
      * then we can just get rid of the block driver state right here.
      */
     if (bdrv_get_attached_dev(bs)) {
+        blk_detach_bs(blk);
+        blk_unref(blk);
         bdrv_make_anon(bs);
-        blk_unref(blk_by_name(id));
         /* Further I/O must not pause the guest */
         bdrv_set_on_error(bs, BLOCKDEV_ON_ERROR_REPORT,
                           BLOCKDEV_ON_ERROR_REPORT);
hw/block/xen_disk.c +2 -6
index 730a021..51f4f3a 100644
@@ -858,15 +858,11 @@ static int blk_connect(struct XenDevice *xendev)
 
         /* setup via xenbus -> create new block driver instance */
         xen_be_printf(&blkdev->xendev, 2, "create new bdrv (xenbus setup)\n");
-        blk = blk_new(blkdev->dev, NULL);
+        blk = blk_new_with_bs(blkdev->dev, NULL);
         if (!blk) {
             return -1;
         }
-        blkdev->bs = bdrv_new_named(blkdev->dev, NULL);
-        if (!blkdev->bs) {
-            blk_unref(blk);
-            return -1;
-        }
+        blkdev->bs = blk_bs(blk);
 
         drv = bdrv_find_whitelisted_format(blkdev->fileproto, readonly);
         if (bdrv_open(&blkdev->bs, blkdev->filename, NULL, NULL, qflags,
include/block/block_int.h +2 -0
index 8a61215..a04c852 100644
@@ -323,6 +323,8 @@ struct BlockDriverState {
     BlockDriver *drv; /* NULL means no media */
     void *opaque;
 
+    BlockBackend *blk;          /* owning backend, if any */
+
     void *dev;                  /* attached device model, if any */
     /* TODO change to DeviceState when all users are qdevified */
     const BlockDevOps *dev_ops;
include/sysemu/block-backend.h +5 -0
index 3f8371c..539b96f 100644
@@ -17,10 +17,15 @@
 #include "qapi/error.h"
 
 BlockBackend *blk_new(const char *name, Error **errp);
+BlockBackend *blk_new_with_bs(const char *name, Error **errp);
 void blk_ref(BlockBackend *blk);
 void blk_unref(BlockBackend *blk);
 const char *blk_name(BlockBackend *blk);
 BlockBackend *blk_by_name(const char *name);
 BlockBackend *blk_next(BlockBackend *blk);
 
+void blk_attach_bs(BlockBackend *blk, BlockDriverState *bs);
+BlockDriverState *blk_detach_bs(BlockBackend *blk);
+BlockDriverState *blk_bs(BlockBackend *blk);
+
 #endif
qemu-img.c +52 -51
index bad3f64..9fba5a1 100644
@@ -284,20 +284,19 @@ static int print_block_option_help(const char *filename, const char *fmt)
     return 0;
 }
 
-static BlockDriverState *bdrv_new_open(const char *id,
-                                       const char *filename,
-                                       const char *fmt,
-                                       int flags,
-                                       bool require_io,
-                                       bool quiet)
+static BlockBackend *img_open(const char *id, const char *filename,
+                              const char *fmt, int flags,
+                              bool require_io, bool quiet)
 {
+    BlockBackend *blk;
     BlockDriverState *bs;
     BlockDriver *drv;
     char password[256];
     Error *local_err = NULL;
     int ret;
 
-    bs = bdrv_new_named(id, &error_abort);
+    blk = blk_new_with_bs(id, &error_abort);
+    bs = blk_bs(blk);
 
     if (fmt) {
         drv = bdrv_find_format(fmt);
@@ -328,9 +327,10 @@ static BlockDriverState *bdrv_new_open(const char *id,
             goto fail;
         }
     }
-    return bs;
+    return blk;
 fail:
     bdrv_unref(bs);
+    blk_unref(blk);
     return NULL;
 }
 
@@ -651,11 +651,11 @@ static int img_check(int argc, char **argv)
         return 1;
     }
 
-    blk = blk_new("image", &error_abort);
-    bs = bdrv_new_open("image", filename, fmt, flags, true, quiet);
-    if (!bs) {
+    blk = img_open("image", filename, fmt, flags, true, quiet);
+    if (!blk) {
         return 1;
     }
+    bs = blk_bs(blk);
 
     check = g_new0(ImageCheck, 1);
     ret = collect_image_check(bs, check, filename, fmt, fix);
@@ -761,11 +761,12 @@ static int img_commit(int argc, char **argv)
         return 1;
     }
 
-    blk = blk_new("image", &error_abort);
-    bs = bdrv_new_open("image", filename, fmt, flags, true, quiet);
-    if (!bs) {
+    blk = img_open("image", filename, fmt, flags, true, quiet);
+    if (!blk) {
         return 1;
     }
+    bs = blk_bs(blk);
+
     ret = bdrv_commit(bs);
     switch(ret) {
     case 0:
@@ -1019,21 +1020,21 @@ static int img_compare(int argc, char **argv)
         goto out3;
     }
 
-    blk1 = blk_new("image 1", &error_abort);
-    bs1 = bdrv_new_open("image 1", filename1, fmt1, flags, true, quiet);
-    if (!bs1) {
+    blk1 = img_open("image 1", filename1, fmt1, flags, true, quiet);
+    if (!blk1) {
         error_report("Can't open file %s", filename1);
         ret = 2;
         goto out3;
     }
+    bs1 = blk_bs(blk1);
 
-    blk2 = blk_new("image 2", &error_abort);
-    bs2 = bdrv_new_open("image 2", filename2, fmt2, flags, true, quiet);
-    if (!bs2) {
+    blk2 = img_open("image 2", filename2, fmt2, flags, true, quiet);
+    if (!blk2) {
         error_report("Can't open file %s", filename2);
         ret = 2;
         goto out2;
     }
+    bs2 = blk_bs(blk2);
 
     buf1 = qemu_blockalign(bs1, IO_BUF_SIZE);
     buf2 = qemu_blockalign(bs2, IO_BUF_SIZE);
@@ -1375,15 +1376,15 @@ static int img_convert(int argc, char **argv)
     for (bs_i = 0; bs_i < bs_n; bs_i++) {
         char *id = bs_n > 1 ? g_strdup_printf("source %d", bs_i)
                             : g_strdup("source");
-        blk[bs_i] = blk_new(id, &error_abort);
-        bs[bs_i] = bdrv_new_open(id, argv[optind + bs_i], fmt, src_flags,
-                                 true, quiet);
+        blk[bs_i] = img_open(id, argv[optind + bs_i], fmt, src_flags,
+                             true, quiet);
         g_free(id);
-        if (!bs[bs_i]) {
+        if (!blk[bs_i]) {
             error_report("Could not open '%s'", argv[optind + bs_i]);
             ret = -1;
             goto out;
         }
+        bs[bs_i] = blk_bs(blk[bs_i]);
         bs_sectors[bs_i] = bdrv_nb_sectors(bs[bs_i]);
         if (bs_sectors[bs_i] < 0) {
             error_report("Could not get size of %s: %s",
@@ -1501,12 +1502,12 @@ static int img_convert(int argc, char **argv)
         goto out;
     }
 
-    out_blk = blk_new("target", &error_abort);
-    out_bs = bdrv_new_open("target", out_filename, out_fmt, flags, true, quiet);
-    if (!out_bs) {
+    out_blk = img_open("target", out_filename, out_fmt, flags, true, quiet);
+    if (!out_blk) {
         ret = -1;
         goto out;
     }
+    out_bs = blk_bs(out_blk);
 
     bs_i = 0;
     bs_offset = 0;
@@ -1893,12 +1894,12 @@ static ImageInfoList *collect_image_info_list(const char *filename,
         }
         g_hash_table_insert(filenames, (gpointer)filename, NULL);
 
-        blk = blk_new("image", &error_abort);
-        bs = bdrv_new_open("image", filename, fmt,
-                           BDRV_O_FLAGS | BDRV_O_NO_BACKING, false, false);
-        if (!bs) {
+        blk = img_open("image", filename, fmt,
+                       BDRV_O_FLAGS | BDRV_O_NO_BACKING, false, false);
+        if (!blk) {
             goto err;
         }
+        bs = blk_bs(blk);
 
         bdrv_query_image_info(bs, &info, &err);
         if (err) {
@@ -2158,11 +2159,11 @@ static int img_map(int argc, char **argv)
         return 1;
     }
 
-    blk = blk_new("image", &error_abort);
-    bs = bdrv_new_open("image", filename, fmt, BDRV_O_FLAGS, true, false);
-    if (!bs) {
+    blk = img_open("image", filename, fmt, BDRV_O_FLAGS, true, false);
+    if (!blk) {
         return 1;
     }
+    bs = blk_bs(blk);
 
     if (output_format == OFORMAT_HUMAN) {
         printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
@@ -2281,11 +2282,11 @@ static int img_snapshot(int argc, char **argv)
     filename = argv[optind++];
 
     /* Open the image */
-    blk = blk_new("image", &error_abort);
-    bs = bdrv_new_open("image", filename, NULL, bdrv_oflags, true, quiet);
-    if (!bs) {
+    blk = img_open("image", filename, NULL, bdrv_oflags, true, quiet);
+    if (!blk) {
         return 1;
     }
+    bs = blk_bs(blk);
 
     /* Perform the requested action */
     switch(action) {
@@ -2427,12 +2428,12 @@ static int img_rebase(int argc, char **argv)
      * Ignore the old backing file for unsafe rebase in case we want to correct
      * the reference to a renamed or moved backing file.
      */
-    blk = blk_new("image", &error_abort);
-    bs = bdrv_new_open("image", filename, fmt, flags, true, quiet);
-    if (!bs) {
+    blk = img_open("image", filename, fmt, flags, true, quiet);
+    if (!blk) {
         ret = -1;
         goto out;
     }
+    bs = blk_bs(blk);
 
     /* Find the right drivers for the backing files */
     old_backing_drv = NULL;
@@ -2460,8 +2461,8 @@ static int img_rebase(int argc, char **argv)
     if (!unsafe) {
         char backing_name[1024];
 
-        blk_old_backing = blk_new("old_backing", &error_abort);
-        bs_old_backing = bdrv_new_named("old_backing", &error_abort);
+        blk_old_backing = blk_new_with_bs("old_backing", &error_abort);
+        bs_old_backing = blk_bs(blk_old_backing);
         bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
         ret = bdrv_open(&bs_old_backing, backing_name, NULL, NULL, src_flags,
                         old_backing_drv, &local_err);
@@ -2472,8 +2473,8 @@ static int img_rebase(int argc, char **argv)
             goto out;
         }
         if (out_baseimg[0]) {
-            blk_new_backing = blk_new("new_backing", &error_abort);
-            bs_new_backing = bdrv_new_named("new_backing", &error_abort);
+            blk_new_backing = blk_new_with_bs("new_backing", &error_abort);
+            bs_new_backing = blk_bs(blk_new_backing);
             ret = bdrv_open(&bs_new_backing, out_baseimg, NULL, NULL, src_flags,
                             new_backing_drv, &local_err);
             if (ret) {
@@ -2749,13 +2750,13 @@ static int img_resize(int argc, char **argv)
     n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
     qemu_opts_del(param);
 
-    blk = blk_new("image", &error_abort);
-    bs = bdrv_new_open("image", filename, fmt, BDRV_O_FLAGS | BDRV_O_RDWR,
-                       true, quiet);
-    if (!bs) {
+    blk = img_open("image", filename, fmt, BDRV_O_FLAGS | BDRV_O_RDWR,
+                   true, quiet);
+    if (!blk) {
         ret = -1;
         goto out;
     }
+    bs = blk_bs(blk);
 
     if (relative) {
         total_size = bdrv_getlength(bs) + n * relative;
@@ -2867,13 +2868,13 @@ static int img_amend(int argc, char **argv)
         goto out;
     }
 
-    blk = blk_new("image", &error_abort);
-    bs = bdrv_new_open("image", filename, fmt, flags, true, quiet);
-    if (!bs) {
+    blk = img_open("image", filename, fmt, flags, true, quiet);
+    if (!blk) {
         error_report("Could not open image '%s'", filename);
         ret = -1;
         goto out;
     }
+    bs = blk_bs(blk);
 
     fmt = bs->drv->format_name;
 
qemu-io.c +2 -2
index 45e5494..ef1d3ea 100644
@@ -62,8 +62,8 @@ static int openfile(char *name, int flags, int growable, QDict *opts)
         return 1;
     }
 
-    qemuio_blk = blk_new("hda", &error_abort);
-    qemuio_bs = bdrv_new_named("hda", &error_abort);
+    qemuio_blk = blk_new_with_bs("hda", &error_abort);
+    qemuio_bs = blk_bs(qemuio_blk);
 
     if (growable) {
         flags |= BDRV_O_PROTOCOL;
qemu-nbd.c +1 -2
index 94b9b49..8eff588 100644
@@ -687,8 +687,7 @@ int main(int argc, char **argv)
         drv = NULL;
     }
 
-    blk_new("hda", &error_abort);
-    bs = bdrv_new_named("hda", &error_abort);
+    bs = blk_bs(blk_new_with_bs("hda", &error_abort));
 
     srcpath = argv[optind];
     ret = bdrv_open(&bs, srcpath, NULL, NULL, flags, drv, &local_err);
Signature · 1 line
1.9.3
#25 lore raw

Re: [Qemu-devel] [PATCH 03/23] block: Connect BlockBackend to BlockDriverState

Quoted 22 lines · Benoît Canet
Quoted 21 lines · Markus Armbruster

The pointer from BlockBackend to BlockDriverState is a strong reference, managed with bdrv_ref() / bdrv_unref(), the back-pointer is a weak one.

Convenience function blk_new_with_bs() creates a BlockBackend with its BlockDriverState. Callers have to unref both. The commit after next will relieve them of the need to unref the BlockDriverState.

---
 block.c                        |  10 ++--
 block/block-backend.c          |  79 +++++++++++++++++++++++++++++++
 blockdev.c                     |  49 +++++++++++---------
 hw/block/xen_disk.c            |   8 +---
 include/block/block_int.h      |   2 +
 include/sysemu/block-backend.h |   5 ++
 qemu-img.c                     | 103 +++++++++++++++++++++--------------------
 qemu-io.c                      |   4 +-
 qemu-nbd.c                     |   3 +-
 9 files changed, 175 insertions(+), 88 deletions(-)
Quoted 14 lines

block.c static void bdrv_move_feature_fields(BlockDriverState *bs_dest, · line 2035

Quoted 10 lines
block.c +1 -1
index 4b3bcd4..a6c03da 100644
@@ -2032,7 +2032,7 @@ static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
  * This will modify the BlockDriverState fields, and swap contents
  * between bs_new and bs_old. Both bs_new and bs_old are modified.
  *
- * bs_new is required to be anonymous.
+ * bs_new must be nameless and not attached to a BlockBackend.

1)
Does "nameless" refer to device_name or node_name ?
From the code I see it's device_name but the wording can be confusing.

Yes. It's slightly better than "anonymous", because that really means both device_name and node_name (since commit dc364f4).

The "nameless" part will go away in PATCH 08, so I'm inclined not to worry about it now.

Quoted 2 lines

maybe:
+ * bs_new must have an empty device_name and not be attached to a BlockBackend.

Can do if you think it's necessary.

#26 lore raw

Re: [Qemu-devel] [PATCH 03/23] block: Connect BlockBackend to BlockDriverState

In reply to Markus Armbruster

Am 10.09.2014 um 10:13 hat Markus Armbruster geschrieben:

Quoted 9 lines

The pointer from BlockBackend to BlockDriverState is a strong reference, managed with bdrv_ref() / bdrv_unref(), the back-pointer is a weak one.

Convenience function blk_new_with_bs() creates a BlockBackend with its BlockDriverState. Callers have to unref both. The commit after next will relieve them of the need to unref the BlockDriverState.

I'm wondering whether this is the right direction to take. In creating a block device, we have the following operations:

1. Create a BlockBackend
2. Create a BlockDriverState
3. Open the BlockDriverState

bdrv_open() can do 2 and 3, which is probably what we want to have in the end - new/create and delete/close should be a single operation for BDSes.

Combining 1 and 2 into a single function might make it harder to actually use bdrv_open() in this way.

Quoted 48 lines
blockdev.c +16 -10
index 86596bc..0a0b95e 100644
@@ -304,6 +304,7 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
     int bdrv_flags = 0;
     int on_read_error, on_write_error;
     BlockBackend *blk;
+    BlockDriverState *bs;
     DriveInfo *dinfo;
     ThrottleConfig cfg;
     int snapshot = 0;
@@ -459,30 +460,28 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
     }
 
     /* init */
-    blk = blk_new(qemu_opts_id(opts), errp);
+    blk = blk_new_with_bs(qemu_opts_id(opts), errp);
     if (!blk) {
         goto early_err;
     }
+    bs = blk_bs(blk);
+    bs->open_flags = snapshot ? BDRV_O_SNAPSHOT : 0;
+    bs->read_only = ro;
+    bs->detect_zeroes = detect_zeroes;
+
+    bdrv_set_on_error(bs, on_read_error, on_write_error);
+
+    /* disk I/O throttling */
+    if (throttle_enabled(&cfg)) {
+        bdrv_io_limits_enable(bs);
+        bdrv_set_io_limits(bs, &cfg);
+    }
+
     dinfo = g_malloc0(sizeof(*dinfo));
     dinfo->id = g_strdup(qemu_opts_id(opts));
-    dinfo->bdrv = bdrv_new_named(dinfo->id, &error);
-    if (error) {
-        error_propagate(errp, error);
-        goto bdrv_new_err;
-    }
-    dinfo->bdrv->open_flags = snapshot ? BDRV_O_SNAPSHOT : 0;
-    dinfo->bdrv->read_only = ro;
-    dinfo->bdrv->detect_zeroes = detect_zeroes;
+    dinfo->bdrv = bs;
     QTAILQ_INSERT_TAIL(&drives, dinfo, next);
 
-    bdrv_set_on_error(dinfo->bdrv, on_read_error, on_write_error);

blockdev.c static DriveInfo *blockdev_init(const char *file, QDict *bs_opts, · line 487

Quoted 10 lines
blockdev.c +0 -7
-
-    /* disk I/O throttling */
-    if (throttle_enabled(&cfg)) {
-        bdrv_io_limits_enable(dinfo->bdrv);
-        bdrv_set_io_limits(dinfo->bdrv, &cfg);
-    }
-
     if (!file || !*file) {
         if (has_driver_specific_opts) {
             file = NULL;

This looks correct, but it's really doing two things at once (on the one hand changing code to use bs instead of dinfo->bdrv and reordering, on the other hand introducing blk_new_with_bs()).

Might be worth doing in separate patches.

Quoted 50 lines
blockdev.c +8 -5
@@ -509,7 +508,8 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
     bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
 
     QINCREF(bs_opts);
-    ret = bdrv_open(&dinfo->bdrv, file, NULL, bs_opts, bdrv_flags, drv, &error);
+    ret = bdrv_open(&bs, file, NULL, bs_opts, bdrv_flags, drv, &error);
+    assert(bs == blk_bs(blk));
 
     if (ret < 0) {
         error_setg(errp, "could not open disk image %s: %s",
@@ -518,8 +518,9 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
         goto err;
     }
 
-    if (bdrv_key_required(dinfo->bdrv))
+    if (bdrv_key_required(bs)) {
         autostart = 0;
+    }
 
     QDECREF(bs_opts);
     qemu_opts_del(opts);
@@ -529,7 +530,6 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
 err:
     bdrv_unref(dinfo->bdrv);
     QTAILQ_REMOVE(&drives, dinfo, next);
-bdrv_new_err:
     g_free(dinfo->id);
     g_free(dinfo);
     blk_unref(blk);
@@ -1746,15 +1746,17 @@ void qmp_block_set_io_throttle(const char *device, int64_t bps, int64_t bps_rd,
 int do_drive_del(Monitor *mon, const QDict *qdict, QObject **ret_data)
 {
     const char *id = qdict_get_str(qdict, "id");
+    BlockBackend *blk;
     BlockDriverState *bs;
     AioContext *aio_context;
     Error *local_err = NULL;
 
-    bs = bdrv_find(id);
-    if (!bs) {
+    blk = blk_by_name(id);
+    if (!blk) {
         error_report("Device '%s' not found", id);
         return -1;
     }
+    bs = blk_bs(blk);
 
     aio_context = bdrv_get_aio_context(bs);
     aio_context_acquire(aio_context);

blockdev.c int do_drive_del(Monitor *mon, const QDict *qdict, QObject **ret_data) · line 1783

Quoted 5 lines
blockdev.c +2 -0
@@ -1777,8 +1779,9 @@ int do_drive_del(Monitor *mon, const QDict *qdict, QObject **ret_data)
      * then we can just get rid of the block driver state right here.
      */
     if (bdrv_get_attached_dev(bs)) {
+        blk_detach_bs(blk);
+        blk_unref(blk);

We're not doing real refcounting yet, but if we did, and if the refcount didn't drop to zero here, why would detaching the bs still be correct?

blk_delete() already takes care of detaching after this patch, so I suppose removing the call here would be right.

blockdev.c int do_drive_del(Monitor *mon, const QDict *qdict, QObject **ret_data) · line 1787

Quoted 5 lines
blockdev.c +0 -1
         bdrv_make_anon(bs);
-        blk_unref(blk_by_name(id));
         /* Further I/O must not pause the guest */
         bdrv_set_on_error(bs, BLOCKDEV_ON_ERROR_REPORT,
                           BLOCKDEV_ON_ERROR_REPORT);

Kevin

#27 lore raw

Re: [Qemu-devel] [PATCH 03/23] block: Connect BlockBackend to BlockDriverState

Quoted 14 lines · Kevin Wolf

Am 10.09.2014 um 10:13 hat Markus Armbruster geschrieben:

Quoted 9 lines

The pointer from BlockBackend to BlockDriverState is a strong reference, managed with bdrv_ref() / bdrv_unref(), the back-pointer is a weak one.

Convenience function blk_new_with_bs() creates a BlockBackend with its BlockDriverState. Callers have to unref both. The commit after next will relieve them of the need to unref the BlockDriverState.

I'm wondering whether this is the right direction to take. In creating a block device, we have the following operations:

Quoted 7 lines

1. Create a BlockBackend
2. Create a BlockDriverState
3. Open the BlockDriverState

bdrv_open() can do 2 and 3, which is probably what we want to have in the end - new/create and delete/close should be a single operation for BDSes.

Agreed.

Quoted 2 lines

Combining 1 and 2 into a single function might make it harder to actually use bdrv_open() in this way.

Not really.

Before my series, callers all look like:

    bs = bdrv_new(name, errp);
    if (!bs) {
        [bail out]
    }
    [stuff...]
    ret = bdrv_open(&bs, [...]);
    if (ret < 0) {
        [bail out, unreffing blk and bdrv (only blk after PATCH 05]
    }

Fusing bdrv_new() and bdrv_open() into bdrv_open_new() would make it look like:

    [stuff'...]
    bs = bdrv_open_new([...]);
    if (!bs) {
        [bail out]
    }
    [stuff''...]

Transforming [stuff...] may take some thought.

Now let's consider how my patch affects such a future fusion. After my patch, we have:

    blk = blk_new_with_bs(name, errp);
    if (!blk) {
        [bail out]
    }
    bs = blk_bs(blk);
    [stuff...]
    ret = bdrv_open(&bs, [...]);
    if (ret < 0) {
        [bail out, unreffing blk and bdrv (only blk after PATCH 05]
    }

Avoiding the convenience function would make it look like:

    blk = blk_new(name, errp);
    if (!blk) {
        [bail out]
    }
    bs = bdrv_new_named(name, errp);
    if (!bs) {
        [bail out, unreffing blk]
    }
    blk_attach_bs(blk, bs);
    [stuff...]
    ret = bdrv_open(&bs, [...]);
    if (ret < 0) {
        [bail out, unreffing blk and bdrv (only blk after PATCH 05]
    }

More verbose, and more complicated error handling. Okay if it really buys us something. Let's fuse and see:

    [stuff'...]
    blk = blk_new(name, errp);
    if (!blk) {
        [bail out]
    }
    [stuff''...]
    ret = bdrv_open(&bs, [...]);
    if (ret < 0) {
        [bail out, unreffing blk]
    }
    [stuff'''...]

As above, transforming [stuff...] may take some thought. Having to inline the convenience function, however, is utterly trivial, and doesn't make the fusing any harder.

Quoted 63 lines
Quoted 48 lines
blockdev.c +16 -10
index 86596bc..0a0b95e 100644
@@ -304,6 +304,7 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
     int bdrv_flags = 0;
     int on_read_error, on_write_error;
     BlockBackend *blk;
+    BlockDriverState *bs;
     DriveInfo *dinfo;
     ThrottleConfig cfg;
     int snapshot = 0;
@@ -459,30 +460,28 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
     }
 
     /* init */
-    blk = blk_new(qemu_opts_id(opts), errp);
+    blk = blk_new_with_bs(qemu_opts_id(opts), errp);
     if (!blk) {
         goto early_err;
     }
+    bs = blk_bs(blk);
+    bs->open_flags = snapshot ? BDRV_O_SNAPSHOT : 0;
+    bs->read_only = ro;
+    bs->detect_zeroes = detect_zeroes;
+
+    bdrv_set_on_error(bs, on_read_error, on_write_error);
+
+    /* disk I/O throttling */
+    if (throttle_enabled(&cfg)) {
+        bdrv_io_limits_enable(bs);
+        bdrv_set_io_limits(bs, &cfg);
+    }
+
     dinfo = g_malloc0(sizeof(*dinfo));
     dinfo->id = g_strdup(qemu_opts_id(opts));
-    dinfo->bdrv = bdrv_new_named(dinfo->id, &error);
-    if (error) {
-        error_propagate(errp, error);
-        goto bdrv_new_err;
-    }
-    dinfo->bdrv->open_flags = snapshot ? BDRV_O_SNAPSHOT : 0;
-    dinfo->bdrv->read_only = ro;
-    dinfo->bdrv->detect_zeroes = detect_zeroes;
+    dinfo->bdrv = bs;
     QTAILQ_INSERT_TAIL(&drives, dinfo, next);
 
-    bdrv_set_on_error(dinfo->bdrv, on_read_error, on_write_error);

blockdev.c static DriveInfo *blockdev_init(const char *file, QDict *bs_opts, · line 487

Quoted 10 lines
blockdev.c +0 -7
-
-    /* disk I/O throttling */
-    if (throttle_enabled(&cfg)) {
-        bdrv_io_limits_enable(dinfo->bdrv);
-        bdrv_set_io_limits(dinfo->bdrv, &cfg);
-    }
-
     if (!file || !*file) {
         if (has_driver_specific_opts) {
             file = NULL;

This looks correct, but it's really doing two things at once (on the one hand changing code to use bs instead of dinfo->bdrv and reordering, on the other hand introducing blk_new_with_bs()).

Quoted 1 line

Might be worth doing in separate patches.

I'll give it a try.

Quoted 59 lines
Quoted 50 lines
blockdev.c +8 -5
@@ -509,7 +508,8 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
     bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
 
     QINCREF(bs_opts);
-    ret = bdrv_open(&dinfo->bdrv, file, NULL, bs_opts, bdrv_flags, drv, &error);
+    ret = bdrv_open(&bs, file, NULL, bs_opts, bdrv_flags, drv, &error);
+    assert(bs == blk_bs(blk));
 
     if (ret < 0) {
         error_setg(errp, "could not open disk image %s: %s",
@@ -518,8 +518,9 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
         goto err;
     }
 
-    if (bdrv_key_required(dinfo->bdrv))
+    if (bdrv_key_required(bs)) {
         autostart = 0;
+    }
 
     QDECREF(bs_opts);
     qemu_opts_del(opts);
@@ -529,7 +530,6 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
 err:
     bdrv_unref(dinfo->bdrv);
     QTAILQ_REMOVE(&drives, dinfo, next);
-bdrv_new_err:
     g_free(dinfo->id);
     g_free(dinfo);
     blk_unref(blk);
@@ -1746,15 +1746,17 @@ void qmp_block_set_io_throttle(const char *device, int64_t bps, int64_t bps_rd,
 int do_drive_del(Monitor *mon, const QDict *qdict, QObject **ret_data)
 {
     const char *id = qdict_get_str(qdict, "id");
+    BlockBackend *blk;
     BlockDriverState *bs;
     AioContext *aio_context;
     Error *local_err = NULL;
 
-    bs = bdrv_find(id);
-    if (!bs) {
+    blk = blk_by_name(id);
+    if (!blk) {
         error_report("Device '%s' not found", id);
         return -1;
     }
+    bs = blk_bs(blk);
 
     aio_context = bdrv_get_aio_context(bs);
     aio_context_acquire(aio_context);

blockdev.c int do_drive_del(Monitor *mon, const QDict *qdict, QObject **ret_data) · line 1783

Quoted 5 lines
blockdev.c +2 -0
@@ -1777,8 +1779,9 @@ int do_drive_del(Monitor *mon, const QDict *qdict, QObject **ret_data)
      * then we can just get rid of the block driver state right here.
      */
     if (bdrv_get_attached_dev(bs)) {
+        blk_detach_bs(blk);
+        blk_unref(blk);

We're not doing real refcounting yet, but if we did, and if the refcount didn't drop to zero here, why would detaching the bs still be correct?

Quoted 2 lines

blk_delete() already takes care of detaching after this patch, so I suppose removing the call here would be right.

I've since reworked this part to address the temporary leak you pointed out in your review of PATCH 02. My current tree has this hunk here:

@@ -1791,8 +1787,7 @@ int do_drive_del(Monitor *mon, const QDict *qdict, QObject **ret_data)

      * then we can just get rid of the block driver state right here.
      */
     if (bdrv_get_attached_dev(bs)) {
-        bdrv_make_anon(bs);
-        blk_unref(blk_by_name(id));
+        blk_make_anon(blk);
         /* Further I/O must not pause the guest */
         bdrv_set_on_error(bs, BLOCKDEV_ON_ERROR_REPORT,
                           BLOCKDEV_ON_ERROR_REPORT);

Suggest you take another careful look when you review v2.

Quoted 7 lines

blockdev.c int do_drive_del(Monitor *mon, const QDict *qdict, QObject **ret_data) · line 1787

Quoted 5 lines
blockdev.c +0 -1
         bdrv_make_anon(bs);
-        blk_unref(blk_by_name(id));
         /* Further I/O must not pause the guest */
         bdrv_set_on_error(bs, BLOCKDEV_ON_ERROR_REPORT,
                           BLOCKDEV_ON_ERROR_REPORT);

Kevin

#28 lore raw

PATCH 4/23 block: Connect BlockBackend and DriveInfo

In reply to Markus Armbruster

Make the BlockBackend own the DriveInfo. Change blockdev_init() to return the BlockBackend instead of the DriveInfo.

---
 block/block-backend.c     | 38 +++++++++++++++++++++++
 blockdev.c                | 79 +++++++++++++++++++++--------------------------
 include/sysemu/blockdev.h |  4 +++
 3 files changed, 78 insertions(+), 43 deletions(-)
block/block-backend.c +38 -0
index deccb54..2a22660 100644
@@ -12,14 +12,18 @@
 
 #include "sysemu/block-backend.h"
 #include "block/block_int.h"
+#include "sysemu/blockdev.h"
 
 struct BlockBackend {
     char *name;
     int refcnt;
     BlockDriverState *bs;
+    DriveInfo *legacy_dinfo;
     QTAILQ_ENTRY(BlockBackend) link; /* for blk_backends */
 };
 
+static void drive_info_del(DriveInfo *dinfo);
+
 static QTAILQ_HEAD(, BlockBackend) blk_backends =
     QTAILQ_HEAD_INITIALIZER(blk_backends);
 
@@ -87,6 +91,7 @@ static void blk_delete(BlockBackend *blk)
     blk_detach_bs(blk);
     QTAILQ_REMOVE(&blk_backends, blk, link);
     g_free(blk->name);
+    drive_info_del(blk->legacy_dinfo);
     g_free(blk);
 }
 
@@ -119,6 +124,16 @@ void blk_unref(BlockBackend *blk)
     }
 }
 
+static void drive_info_del(DriveInfo *dinfo)
+{
+    if (dinfo) {
+        qemu_opts_del(dinfo->opts);
+        g_free(dinfo->id);
+        g_free(dinfo->serial);
+        g_free(dinfo);
+    }
+}
+
 const char *blk_name(BlockBackend *blk)
 {
     return blk->name;
@@ -187,3 +202,26 @@ BlockDriverState *blk_detach_bs(BlockBackend *blk)
     }
     return bs;
 }
+
+DriveInfo *blk_legacy_dinfo(BlockBackend *blk)
+{
+    return blk->legacy_dinfo;
+}
+
+DriveInfo *blk_set_legacy_dinfo(BlockBackend *blk, DriveInfo *dinfo)
+{
+    assert(!blk->legacy_dinfo);
+    return blk->legacy_dinfo = dinfo;
+}
+
+BlockBackend *blk_by_legacy_dinfo(DriveInfo *dinfo)
+{
+    BlockBackend *blk;
+
+    QTAILQ_FOREACH(blk, &blk_backends, link) {
+        if (blk->legacy_dinfo == dinfo) {
+            return blk;
+        }
+    }
+    assert(0);
+}
blockdev.c +36 -43

194 lines not on this page · raw message

include/sysemu/blockdev.h +4 -0
index 23a5d10..2ed297b 100644
@@ -45,6 +45,10 @@ struct DriveInfo {
     QTAILQ_ENTRY(DriveInfo) next;
 };
 
+DriveInfo *blk_legacy_dinfo(BlockBackend *blk);
+DriveInfo *blk_set_legacy_dinfo(BlockBackend *blk, DriveInfo *dinfo);
+BlockBackend *blk_by_legacy_dinfo(DriveInfo *dinfo);
+
 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit);
 DriveInfo *drive_get_by_index(BlockInterfaceType type, int index);
 int drive_get_max_bus(BlockInterfaceType type);
Signature · 1 line
1.9.3
#29 lore raw

Re: [Qemu-devel] [PATCH 04/23] block: Connect BlockBackend and DriveInfo

Quoted 20 lines · Markus Armbruster

Make the BlockBackend own the DriveInfo. Change blockdev_init() to return the BlockBackend instead of the DriveInfo.

---
 block/block-backend.c     | 38 +++++++++++++++++++++++
 blockdev.c                | 79 +++++++++++++++++++++--------------------------
 include/sysemu/blockdev.h |  4 +++
 3 files changed, 78 insertions(+), 43 deletions(-)
block/block-backend.c +1 -0
index deccb54..2a22660 100644
@@ -12,14 +12,18 @@
 
 #include "sysemu/block-backend.h"
 #include "block/block_int.h"
+#include "sysemu/blockdev.h"
 

block/block-backend.c line 26

Quoted 10 lines
block/block-backend.c +2 -0
 struct BlockBackend {
     char *name;
     int refcnt;
     BlockDriverState *bs;
+    DriveInfo *legacy_dinfo;
     QTAILQ_ENTRY(BlockBackend) link; /* for blk_backends */
 };
 
 
+static void drive_info_del(DriveInfo *dinfo);

Is there any technical reason not to just put the drive_info_del above the blk_delete function ?
I don't see any possible circular references between the two.

Some people like Eric frown upon static function prototypes in final code that's why I am asking.

Quoted 93 lines
block/block-backend.c +35 -0
+
 static QTAILQ_HEAD(, BlockBackend) blk_backends =
     QTAILQ_HEAD_INITIALIZER(blk_backends);
@@ -87,6 +91,7 @@ static void blk_delete(BlockBackend *blk)
     blk_detach_bs(blk);
     QTAILQ_REMOVE(&blk_backends, blk, link);
     g_free(blk->name);
+    drive_info_del(blk->legacy_dinfo);
     g_free(blk);
 }
 
@@ -119,6 +124,16 @@ void blk_unref(BlockBackend *blk)
     }
 }
 
+static void drive_info_del(DriveInfo *dinfo)
+{
+    if (dinfo) {
+        qemu_opts_del(dinfo->opts);
+        g_free(dinfo->id);
+        g_free(dinfo->serial);
+        g_free(dinfo);
+    }
+}
+
 const char *blk_name(BlockBackend *blk)
 {
     return blk->name;
@@ -187,3 +202,26 @@ BlockDriverState *blk_detach_bs(BlockBackend *blk)
     }
     return bs;
 }
+
+DriveInfo *blk_legacy_dinfo(BlockBackend *blk)
+{
+    return blk->legacy_dinfo;
+}
+
+DriveInfo *blk_set_legacy_dinfo(BlockBackend *blk, DriveInfo *dinfo)
+{
+    assert(!blk->legacy_dinfo);
+    return blk->legacy_dinfo = dinfo;
+}
+
+BlockBackend *blk_by_legacy_dinfo(DriveInfo *dinfo)
+{
+    BlockBackend *blk;
+
+    QTAILQ_FOREACH(blk, &blk_backends, link) {
+        if (blk->legacy_dinfo == dinfo) {
+            return blk;
+        }
+    }
+    assert(0);
+}
blockdev.c +4 -4
index 0a0b95e..73e2da9 100644
@@ -47,8 +47,6 @@
 #include "trace.h"
 #include "sysemu/arch_init.h"
 
-static QTAILQ_HEAD(drivelist, DriveInfo) drives = QTAILQ_HEAD_INITIALIZER(drives);
-
 static const char *const if_name[IF_COUNT] = {
     [IF_NONE] = "none",
     [IF_IDE] = "ide",
@@ -89,7 +87,8 @@ static const int if_max_devs[IF_COUNT] = {
  */
 void blockdev_mark_auto_del(BlockDriverState *bs)
 {
-    DriveInfo *dinfo = drive_get_by_blockdev(bs);
+    BlockBackend *blk = bs->blk;
+    DriveInfo *dinfo = blk_legacy_dinfo(blk);
 
     if (dinfo && !dinfo->enable_auto_del) {
         return;
@@ -105,7 +104,8 @@ void blockdev_mark_auto_del(BlockDriverState *bs)
 
 void blockdev_auto_del(BlockDriverState *bs)
 {
-    DriveInfo *dinfo = drive_get_by_blockdev(bs);
+    BlockBackend *blk = bs->blk;
+    DriveInfo *dinfo = blk_legacy_dinfo(blk);
 
     if (dinfo && dinfo->auto_del) {
         drive_del(dinfo);
@@ -153,15 +153,15 @@ QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
 
 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
 {

blockdev.c QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file, · line 159

Quoted 10 lines
blockdev.c +2 -6
+    BlockBackend *blk;
     DriveInfo *dinfo;
 
-    /* seek interface, bus and unit */
-
-    QTAILQ_FOREACH(dinfo, &drives, next) {
-        if (dinfo->type == type &&
-	    dinfo->bus == bus &&
-	    dinfo->unit == unit)
+    for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {

Here I understand why you didn't made blk_next pure round robin circling in a loop. Maybe the comments of the blk_next function should say it's just an iterator.

Quoted 83 lines
blockdev.c +18 -18
+        dinfo = blk_legacy_dinfo(blk);
+        if (dinfo && dinfo->type == type
+            && dinfo->bus == bus && dinfo->unit == unit) {
             return dinfo;
+        }
     }
 
     return NULL;
@@ -177,13 +177,15 @@ DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
 int drive_get_max_bus(BlockInterfaceType type)
 {
     int max_bus;
+    BlockBackend *blk;
     DriveInfo *dinfo;
 
     max_bus = -1;
-    QTAILQ_FOREACH(dinfo, &drives, next) {
-        if(dinfo->type == type &&
-           dinfo->bus > max_bus)
+    for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
+        dinfo = blk_legacy_dinfo(blk);
+        if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
             max_bus = dinfo->bus;
+        }
     }
     return max_bus;
 }
@@ -200,11 +202,11 @@ DriveInfo *drive_get_next(BlockInterfaceType type)
 
 DriveInfo *drive_get_by_blockdev(BlockDriverState *bs)
 {
-    DriveInfo *dinfo;
+    BlockBackend *blk;
 
-    QTAILQ_FOREACH(dinfo, &drives, next) {
-        if (dinfo->bdrv == bs) {
-            return dinfo;
+    for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
+        if (blk_bs(blk) == bs) {
+            return blk_legacy_dinfo(blk);
         }
     }
     return NULL;
@@ -217,16 +219,10 @@ static void bdrv_format_print(void *opaque, const char *name)
 
 void drive_del(DriveInfo *dinfo)
 {
-    if (dinfo->opts) {
-        qemu_opts_del(dinfo->opts);
-    }
+    BlockBackend *blk = dinfo->bdrv->blk;
 
     bdrv_unref(dinfo->bdrv);
-    blk_unref(blk_by_name(dinfo->id));
-    g_free(dinfo->id);
-    QTAILQ_REMOVE(&drives, dinfo, next);
-    g_free(dinfo->serial);
-    g_free(dinfo);
+    blk_unref(blk);
 }
 
 typedef struct {
@@ -296,8 +292,8 @@ static bool check_throttle_config(ThrottleConfig *cfg, Error **errp)
 typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
 
 /* Takes the ownership of bs_opts */
-static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
-                                Error **errp)
+static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
+                                   Error **errp)
 {
     const char *buf;
     int ro = 0;
@@ -480,7 +476,7 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
     dinfo = g_malloc0(sizeof(*dinfo));
     dinfo->id = g_strdup(qemu_opts_id(opts));
     dinfo->bdrv = bs;
-    QTAILQ_INSERT_TAIL(&drives, dinfo, next);
+    blk_set_legacy_dinfo(blk, dinfo);
 
     if (!file || !*file) {
         if (has_driver_specific_opts) {

blockdev.c static DriveInfo *blockdev_init(const char *file, QDict *bs_opts, · line 488

Quoted 6 lines
blockdev.c +1 -1
@@ -488,7 +484,7 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
         } else {
             QDECREF(bs_opts);
             qemu_opts_del(opts);
-            return dinfo;
 
+            return blk;

Here you fix the leak I found on a previous patch.

Quoted 30 lines
blockdev.c +0 -0
         }
     }
     if (snapshot) {
blockdev.c +2 -4
@@ -525,13 +521,10 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
     QDECREF(bs_opts);
     qemu_opts_del(opts);
 
-    return dinfo;
+    return blk;
 
 err:
     bdrv_unref(dinfo->bdrv);
-    QTAILQ_REMOVE(&drives, dinfo, next);
-    g_free(dinfo->id);
-    g_free(dinfo);
     blk_unref(blk);
 early_err:
     qemu_opts_del(opts);
@@ -635,6 +628,7 @@ QemuOptsList qemu_legacy_drive_opts = {
 DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
 {
     const char *value;
+    BlockBackend *blk;
     DriveInfo *dinfo = NULL;
     QDict *bs_opts;
     QemuOpts *legacy_opts;
@@ -917,19 +911,17 @@ DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
     }
 
     /* Actual block device init: Functionality shared with blockdev-add */

blockdev.c DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type) · line 917

Quoted 10 lines
blockdev.c +2 -6
-    dinfo = blockdev_init(filename, bs_opts, &local_err);
+    blk = blockdev_init(filename, bs_opts, &local_err);
     bs_opts = NULL;
-    if (dinfo == NULL) {
-        if (local_err) {
-            error_report("%s", error_get_pretty(local_err));
-            error_free(local_err);
-        }
 
+    if (!blk) {

Just down the code an existing test does if (local_err) { after blk = blockdev_init(NULL, qdict, &local_err);.

Is the prefered convention checking blk or local_err ?

Quoted 57 lines
blockdev.c +7 -4
+        error_report("%s", error_get_pretty(local_err));
         goto fail;
     } else {
         assert(!local_err);
     }
 
     /* Set legacy DriveInfo fields */
+    dinfo = blk_legacy_dinfo(blk);
     dinfo->enable_auto_del = true;
     dinfo->opts = all_opts;
@@ -2478,7 +2470,7 @@ void qmp_change_backing_file(const char *device,
 void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
 {
     QmpOutputVisitor *ov = qmp_output_visitor_new();
-    DriveInfo *dinfo;
+    BlockBackend *blk;
     QObject *obj;
     QDict *qdict;
     Error *local_err = NULL;
@@ -2516,14 +2508,15 @@ void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
 
     qdict_flatten(qdict);
 
-    dinfo = blockdev_init(NULL, qdict, &local_err);
+    blk = blockdev_init(NULL, qdict, &local_err);
     if (local_err) {
         error_propagate(errp, local_err);
         goto fail;
     }
 
-    if (bdrv_key_required(dinfo->bdrv)) {
-        drive_del(dinfo);
+    if (bdrv_key_required(blk_bs(blk))) {
+        bdrv_unref(blk_bs(blk));
+        blk_unref(blk);
         error_setg(errp, "blockdev-add doesn't support encrypted devices");
         goto fail;
     }
include/sysemu/blockdev.h +4 -0
index 23a5d10..2ed297b 100644
@@ -45,6 +45,10 @@ struct DriveInfo {
     QTAILQ_ENTRY(DriveInfo) next;
 };
 
+DriveInfo *blk_legacy_dinfo(BlockBackend *blk);
+DriveInfo *blk_set_legacy_dinfo(BlockBackend *blk, DriveInfo *dinfo);
+BlockBackend *blk_by_legacy_dinfo(DriveInfo *dinfo);
+
 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit);
 DriveInfo *drive_get_by_index(BlockInterfaceType type, int index);
 int drive_get_max_bus(BlockInterfaceType type);
Signature · 1 line
1.9.3
#30 lore raw

Re: [Qemu-devel] [PATCH 04/23] block: Connect BlockBackend and DriveInfo

Quoted 30 lines · Benoît Canet
Quoted 28 lines · Markus Armbruster

Make the BlockBackend own the DriveInfo. Change blockdev_init() to return the BlockBackend instead of the DriveInfo.

---
 block/block-backend.c     | 38 +++++++++++++++++++++++
 blockdev.c                | 79 +++++++++++++++++++++--------------------------
 include/sysemu/blockdev.h |  4 +++
 3 files changed, 78 insertions(+), 43 deletions(-)
block/block-backend.c +2 -0
index deccb54..2a22660 100644
@@ -12,14 +12,18 @@
 
 #include "sysemu/block-backend.h"
 #include "block/block_int.h"
+#include "sysemu/blockdev.h"
 
 struct BlockBackend {
     char *name;
     int refcnt;
     BlockDriverState *bs;
+    DriveInfo *legacy_dinfo;
     QTAILQ_ENTRY(BlockBackend) link; /* for blk_backends */
 };
 
Quoted 8 lines

block/block-backend.c line 25

Quoted 1 line
block/block-backend.c +1 -0
+static void drive_info_del(DriveInfo *dinfo);

Is there any technical reason not to just put the drive_info_del above the blk_delete function ?
I don't see any possible circular references between the two.

Some people like Eric frown upon static function prototypes in final code that's why I am asking.

Placing functions before their callers makes the program easier to read when you need to see the functions definition before you can understand their use.

Placing the functions after callers makes the program easier to read when the gist of what they do is obvious from the call. You're omitting unnecessary detail there, to be flesh it own further down. Saving a function declaration is immaterial compared to that.

Before I put the function where I don't want it, I'd inline it :)

Quoted 96 lines
Quoted 96 lines
block/block-backend.c +35 -0
+
 static QTAILQ_HEAD(, BlockBackend) blk_backends =
     QTAILQ_HEAD_INITIALIZER(blk_backends);
 
@@ -87,6 +91,7 @@ static void blk_delete(BlockBackend *blk)
     blk_detach_bs(blk);
     QTAILQ_REMOVE(&blk_backends, blk, link);
     g_free(blk->name);
+    drive_info_del(blk->legacy_dinfo);
     g_free(blk);
 }
 
@@ -119,6 +124,16 @@ void blk_unref(BlockBackend *blk)
     }
 }
 
+static void drive_info_del(DriveInfo *dinfo)
+{
+    if (dinfo) {
+        qemu_opts_del(dinfo->opts);
+        g_free(dinfo->id);
+        g_free(dinfo->serial);
+        g_free(dinfo);
+    }
+}
+
 const char *blk_name(BlockBackend *blk)
 {
     return blk->name;
@@ -187,3 +202,26 @@ BlockDriverState *blk_detach_bs(BlockBackend *blk)
     }
     return bs;
 }
+
+DriveInfo *blk_legacy_dinfo(BlockBackend *blk)
+{
+    return blk->legacy_dinfo;
+}
+
+DriveInfo *blk_set_legacy_dinfo(BlockBackend *blk, DriveInfo *dinfo)
+{
+    assert(!blk->legacy_dinfo);
+    return blk->legacy_dinfo = dinfo;
+}
+
+BlockBackend *blk_by_legacy_dinfo(DriveInfo *dinfo)
+{
+    BlockBackend *blk;
+
+    QTAILQ_FOREACH(blk, &blk_backends, link) {
+        if (blk->legacy_dinfo == dinfo) {
+            return blk;
+        }
+    }
+    assert(0);
+}
blockdev.c +5 -4
index 0a0b95e..73e2da9 100644
@@ -47,8 +47,6 @@
 #include "trace.h"
 #include "sysemu/arch_init.h"
 
-static QTAILQ_HEAD(drivelist, DriveInfo) drives = QTAILQ_HEAD_INITIALIZER(drives);
-
 static const char *const if_name[IF_COUNT] = {
     [IF_NONE] = "none",
     [IF_IDE] = "ide",
@@ -89,7 +87,8 @@ static const int if_max_devs[IF_COUNT] = {
  */
 void blockdev_mark_auto_del(BlockDriverState *bs)
 {
-    DriveInfo *dinfo = drive_get_by_blockdev(bs);
+    BlockBackend *blk = bs->blk;
+    DriveInfo *dinfo = blk_legacy_dinfo(blk);
 
     if (dinfo && !dinfo->enable_auto_del) {
         return;
@@ -105,7 +104,8 @@ void blockdev_mark_auto_del(BlockDriverState *bs)
 
 void blockdev_auto_del(BlockDriverState *bs)
 {
-    DriveInfo *dinfo = drive_get_by_blockdev(bs);
+    BlockBackend *blk = bs->blk;
+    DriveInfo *dinfo = blk_legacy_dinfo(blk);
 
     if (dinfo && dinfo->auto_del) {
         drive_del(dinfo);
@@ -153,15 +153,15 @@ QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
 
 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
 {
+    BlockBackend *blk;
     DriveInfo *dinfo;
 
Quoted 10 lines

blockdev.c QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file, · line 159

Quoted 7 lines
blockdev.c +1 -6
-    /* seek interface, bus and unit */
-
-    QTAILQ_FOREACH(dinfo, &drives, next) {
-        if (dinfo->type == type &&
-	    dinfo->bus == bus &&
-	    dinfo->unit == unit)
+    for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {

Here I understand why you didn't made blk_next pure round robin circling in a loop.

It works exactly like bdrv_next().

Quoted 1 line

Maybe the comments of the blk_next function should say it's just an iterator.

I could add example usage to the comment there.

Quoted 88 lines
Quoted 87 lines
blockdev.c +18 -19
+        dinfo = blk_legacy_dinfo(blk);
+        if (dinfo && dinfo->type == type
+            && dinfo->bus == bus && dinfo->unit == unit) {
             return dinfo;
+        }
     }
 
     return NULL;
@@ -177,13 +177,15 @@ DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
 int drive_get_max_bus(BlockInterfaceType type)
 {
     int max_bus;
+    BlockBackend *blk;
     DriveInfo *dinfo;
 
     max_bus = -1;
-    QTAILQ_FOREACH(dinfo, &drives, next) {
-        if(dinfo->type == type &&
-           dinfo->bus > max_bus)
+    for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
+        dinfo = blk_legacy_dinfo(blk);
+        if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
             max_bus = dinfo->bus;
+        }
     }
     return max_bus;
 }
@@ -200,11 +202,11 @@ DriveInfo *drive_get_next(BlockInterfaceType type)
 
 DriveInfo *drive_get_by_blockdev(BlockDriverState *bs)
 {
-    DriveInfo *dinfo;
+    BlockBackend *blk;
 
-    QTAILQ_FOREACH(dinfo, &drives, next) {
-        if (dinfo->bdrv == bs) {
-            return dinfo;
+    for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
+        if (blk_bs(blk) == bs) {
+            return blk_legacy_dinfo(blk);
         }
     }
     return NULL;
@@ -217,16 +219,10 @@ static void bdrv_format_print(void *opaque, const char *name)
 
 void drive_del(DriveInfo *dinfo)
 {
-    if (dinfo->opts) {
-        qemu_opts_del(dinfo->opts);
-    }
+    BlockBackend *blk = dinfo->bdrv->blk;
 
     bdrv_unref(dinfo->bdrv);
-    blk_unref(blk_by_name(dinfo->id));
-    g_free(dinfo->id);
-    QTAILQ_REMOVE(&drives, dinfo, next);
-    g_free(dinfo->serial);
-    g_free(dinfo);
+    blk_unref(blk);
 }
 
 typedef struct {
@@ -296,8 +292,8 @@ static bool check_throttle_config(ThrottleConfig *cfg, Error **errp)
 typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
 
 /* Takes the ownership of bs_opts */
-static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
-                                Error **errp)
+static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
+                                   Error **errp)
 {
     const char *buf;
     int ro = 0;
@@ -480,7 +476,7 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
     dinfo = g_malloc0(sizeof(*dinfo));
     dinfo->id = g_strdup(qemu_opts_id(opts));
     dinfo->bdrv = bs;
-    QTAILQ_INSERT_TAIL(&drives, dinfo, next);
+    blk_set_legacy_dinfo(blk, dinfo);
 
     if (!file || !*file) {
         if (has_driver_specific_opts) {
@@ -488,7 +484,7 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
         } else {
             QDECREF(bs_opts);
             qemu_opts_del(opts);
-            return dinfo;
Quoted 2 lines

blockdev.c static DriveInfo *blockdev_init(const char *file, QDict *bs_opts, · line 487

Quoted 1 line
blockdev.c +1 -0
+            return blk;

Here you fix the leak I found on a previous patch.

I don't think it leaked.

Quoted 39 lines
Quoted 38 lines
blockdev.c +3 -10
         }
     }
     if (snapshot) {
@@ -525,13 +521,10 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
     QDECREF(bs_opts);
     qemu_opts_del(opts);
 
-    return dinfo;
+    return blk;
 
 err:
     bdrv_unref(dinfo->bdrv);
-    QTAILQ_REMOVE(&drives, dinfo, next);
-    g_free(dinfo->id);
-    g_free(dinfo);
     blk_unref(blk);
 early_err:
     qemu_opts_del(opts);
@@ -635,6 +628,7 @@ QemuOptsList qemu_legacy_drive_opts = {
 DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
 {
     const char *value;
+    BlockBackend *blk;
     DriveInfo *dinfo = NULL;
     QDict *bs_opts;
     QemuOpts *legacy_opts;
@@ -917,19 +911,17 @@ DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
     }
 
     /* Actual block device init: Functionality shared with blockdev-add */
-    dinfo = blockdev_init(filename, bs_opts, &local_err);
+    blk = blockdev_init(filename, bs_opts, &local_err);
     bs_opts = NULL;
-    if (dinfo == NULL) {
-        if (local_err) {
-            error_report("%s", error_get_pretty(local_err));
-            error_free(local_err);
-        }
Quoted 6 lines

blockdev.c DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type) · line 916

Quoted 1 line
blockdev.c +1 -0
+    if (!blk) {

Just down the code an existing test does if (local_err) { after blk = blockdev_init(NULL, qdict, &local_err);.

Is the prefered convention checking blk or local_err ?

Both

    foop = foo_new(bar, &local_err);
    if (local_err) {
        assert(!foop);
        error_propagate(errp, local_err)
        goto fail;
    }
    assert(!local_err);

and

    foop = foo_new(bar, &errp);
    if (!foop) {
        assert(!errp || *errp);
        goto fail;
    }
    assert(!errp || *errp);

work. Of course, nobody bothers with the assertions; the error handling is enough verbiage as it is.

However, I dislike the first variant intensely. Not least because it's prone to get Coverity worry about foop being null in code following it.

Quoted 11 lines
Quoted 11 lines
blockdev.c +2 -0
+        error_report("%s", error_get_pretty(local_err));
         goto fail;
     } else {
         assert(!local_err);
     }
 
     /* Set legacy DriveInfo fields */
+    dinfo = blk_legacy_dinfo(blk);
     dinfo->enable_auto_del = true;
     dinfo->opts = all_opts;
 

[...]

#31 lore raw

Re: [Qemu-devel] [PATCH 04/23] block: Connect BlockBackend and DriveInfo

Quoted 10 lines · Markus Armbruster
Quoted 6 lines · Benoît Canet
Quoted 5 lines · Markus Armbruster

Make the BlockBackend own the DriveInfo. Change blockdev_init() to return the BlockBackend instead of the DriveInfo.

---

Quoted 8 lines
Quoted 8 lines
Quoted 1 line

+static void drive_info_del(DriveInfo *dinfo);

Is there any technical reason not to just put the drive_info_del above the blk_delete function ?
I don't see any possible circular references between the two.

Some people like Eric frown upon static function prototypes in final code that's why I am asking.

I dislike it in code I write, and so I point it out in reviews, but I also concede that it is a style, not technical issue, so I will never reject a patch that uses forward declarations if the author thinks that makes the presentation of the overall file easier to follow.

Quoted 11 lines

Placing functions before their callers makes the program easier to read when you need to see the functions definition before you can understand their use.

Placing the functions after callers makes the program easier to read when the gist of what they do is obvious from the call. You're omitting unnecessary detail there, to be flesh it own further down. Saving a function declaration is immaterial compared to that.

Before I put the function where I don't want it, I'd inline it :)

Then I won't try to convince you to paint the bikeshed any other color.

Signature · 2 lines
Eric Blake   eblake redhat com    +1-919-301-3266
Libvirt virtualization library http://libvirt.org
#32 lore raw

Re: [Qemu-devel] [PATCH 04/23] block: Connect BlockBackend and DriveInfo

In reply to Markus Armbruster

Am 10.09.2014 um 10:13 hat Markus Armbruster geschrieben:

Quoted 109 lines

Make the BlockBackend own the DriveInfo. Change blockdev_init() to return the BlockBackend instead of the DriveInfo.

---
 block/block-backend.c     | 38 +++++++++++++++++++++++
 blockdev.c                | 79 +++++++++++++++++++++--------------------------
 include/sysemu/blockdev.h |  4 +++
 3 files changed, 78 insertions(+), 43 deletions(-)
block/block-backend.c +38 -0
index deccb54..2a22660 100644
@@ -12,14 +12,18 @@
 
 #include "sysemu/block-backend.h"
 #include "block/block_int.h"
+#include "sysemu/blockdev.h"
 
 struct BlockBackend {
     char *name;
     int refcnt;
     BlockDriverState *bs;
+    DriveInfo *legacy_dinfo;
     QTAILQ_ENTRY(BlockBackend) link; /* for blk_backends */
 };
 
+static void drive_info_del(DriveInfo *dinfo);
+
 static QTAILQ_HEAD(, BlockBackend) blk_backends =
     QTAILQ_HEAD_INITIALIZER(blk_backends);
 
@@ -87,6 +91,7 @@ static void blk_delete(BlockBackend *blk)
     blk_detach_bs(blk);
     QTAILQ_REMOVE(&blk_backends, blk, link);
     g_free(blk->name);
+    drive_info_del(blk->legacy_dinfo);
     g_free(blk);
 }
 
@@ -119,6 +124,16 @@ void blk_unref(BlockBackend *blk)
     }
 }
 
+static void drive_info_del(DriveInfo *dinfo)
+{
+    if (dinfo) {
+        qemu_opts_del(dinfo->opts);
+        g_free(dinfo->id);
+        g_free(dinfo->serial);
+        g_free(dinfo);
+    }
+}
+
 const char *blk_name(BlockBackend *blk)
 {
     return blk->name;
@@ -187,3 +202,26 @@ BlockDriverState *blk_detach_bs(BlockBackend *blk)
     }
     return bs;
 }
+
+DriveInfo *blk_legacy_dinfo(BlockBackend *blk)
+{
+    return blk->legacy_dinfo;
+}
+
+DriveInfo *blk_set_legacy_dinfo(BlockBackend *blk, DriveInfo *dinfo)
+{
+    assert(!blk->legacy_dinfo);
+    return blk->legacy_dinfo = dinfo;
+}
+
+BlockBackend *blk_by_legacy_dinfo(DriveInfo *dinfo)
+{
+    BlockBackend *blk;
+
+    QTAILQ_FOREACH(blk, &blk_backends, link) {
+        if (blk->legacy_dinfo == dinfo) {
+            return blk;
+        }
+    }
+    assert(0);
+}
blockdev.c +2 -3
index 0a0b95e..73e2da9 100644
@@ -47,8 +47,6 @@
 #include "trace.h"
 #include "sysemu/arch_init.h"
 
-static QTAILQ_HEAD(drivelist, DriveInfo) drives = QTAILQ_HEAD_INITIALIZER(drives);
-
 static const char *const if_name[IF_COUNT] = {
     [IF_NONE] = "none",
     [IF_IDE] = "ide",
@@ -89,7 +87,8 @@ static const int if_max_devs[IF_COUNT] = {
  */
 void blockdev_mark_auto_del(BlockDriverState *bs)
 {
-    DriveInfo *dinfo = drive_get_by_blockdev(bs);
+    BlockBackend *blk = bs->blk;
+    DriveInfo *dinfo = blk_legacy_dinfo(blk);
 
     if (dinfo && !dinfo->enable_auto_del) {
         return;

blockdev.c void blockdev_mark_auto_del(BlockDriverState *bs) · line 111

Quoted 9 lines
blockdev.c +2 -1
@@ -105,7 +104,8 @@ void blockdev_mark_auto_del(BlockDriverState *bs)
 
 void blockdev_auto_del(BlockDriverState *bs)
 {
-    DriveInfo *dinfo = drive_get_by_blockdev(bs);
+    BlockBackend *blk = bs->blk;
+    DriveInfo *dinfo = blk_legacy_dinfo(blk);
 
     if (dinfo && dinfo->auto_del) {
         drive_del(dinfo);

The if condition looks as if there were cases where dinfo was NULL. To be precise, this was introduced in commit 0fc0f1fa, so that hot unplug after a forced drive_del wouldn't segfault.

Does such a device that doesn't have a dinfo at least have a BlockBackend? If it doesn't, we'll segfault in blk_legacy_dinfo(). I won't say that I understand that part of the code, but I can't see why BlockBackend would still be there when DriveInfo isn't any more.

Quoted 64 lines
blockdev.c +15 -16
@@ -153,15 +153,15 @@ QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
 
 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
 {
+    BlockBackend *blk;
     DriveInfo *dinfo;
 
-    /* seek interface, bus and unit */
-
-    QTAILQ_FOREACH(dinfo, &drives, next) {
-        if (dinfo->type == type &&
-	    dinfo->bus == bus &&
-	    dinfo->unit == unit)
+    for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
+        dinfo = blk_legacy_dinfo(blk);
+        if (dinfo && dinfo->type == type
+            && dinfo->bus == bus && dinfo->unit == unit) {
             return dinfo;
+        }
     }
 
     return NULL;
@@ -177,13 +177,15 @@ DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
 int drive_get_max_bus(BlockInterfaceType type)
 {
     int max_bus;
+    BlockBackend *blk;
     DriveInfo *dinfo;
 
     max_bus = -1;
-    QTAILQ_FOREACH(dinfo, &drives, next) {
-        if(dinfo->type == type &&
-           dinfo->bus > max_bus)
+    for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
+        dinfo = blk_legacy_dinfo(blk);
+        if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
             max_bus = dinfo->bus;
+        }
     }
     return max_bus;
 }
@@ -200,11 +202,11 @@ DriveInfo *drive_get_next(BlockInterfaceType type)
 
 DriveInfo *drive_get_by_blockdev(BlockDriverState *bs)
 {
-    DriveInfo *dinfo;
+    BlockBackend *blk;
 
-    QTAILQ_FOREACH(dinfo, &drives, next) {
-        if (dinfo->bdrv == bs) {
-            return dinfo;
+    for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
+        if (blk_bs(blk) == bs) {
+            return blk_legacy_dinfo(blk);
         }
     }
     return NULL;
@@ -217,16 +219,10 @@ static void bdrv_format_print(void *opaque, const char *name)
 
 void drive_del(DriveInfo *dinfo)
 {
-    if (dinfo->opts) {
-        qemu_opts_del(dinfo->opts);
-    }

blockdev.c static void bdrv_format_print(void *opaque, const char *name) · line 226

Quoted 10 lines
blockdev.c +2 -5
+    BlockBackend *blk = dinfo->bdrv->blk;
 
     bdrv_unref(dinfo->bdrv);
-    blk_unref(blk_by_name(dinfo->id));
-    g_free(dinfo->id);
-    QTAILQ_REMOVE(&drives, dinfo, next);
-    g_free(dinfo->serial);
-    g_free(dinfo);
+    blk_unref(blk);
 }

Now the dinfo stays alive until the last reference for blk is gone. We probably don't care much about the memory that isn't used any more, but not freed yet. What about dinfo->opts? Does it block IDs that should be available again?

Do we need a dinfo_attach/detach like for BDSes?

Quoted 57 lines
blockdev.c +6 -8
 typedef struct {
@@ -296,8 +292,8 @@ static bool check_throttle_config(ThrottleConfig *cfg, Error **errp)
 typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
 
 /* Takes the ownership of bs_opts */
-static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
-                                Error **errp)
+static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
+                                   Error **errp)
 {
     const char *buf;
     int ro = 0;
@@ -480,7 +476,7 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
     dinfo = g_malloc0(sizeof(*dinfo));
     dinfo->id = g_strdup(qemu_opts_id(opts));
     dinfo->bdrv = bs;
-    QTAILQ_INSERT_TAIL(&drives, dinfo, next);
+    blk_set_legacy_dinfo(blk, dinfo);
 
     if (!file || !*file) {
         if (has_driver_specific_opts) {
@@ -488,7 +484,7 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
         } else {
             QDECREF(bs_opts);
             qemu_opts_del(opts);
-            return dinfo;
+            return blk;
         }
     }
     if (snapshot) {
@@ -525,13 +521,10 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
     QDECREF(bs_opts);
     qemu_opts_del(opts);
 
-    return dinfo;
+    return blk;
 
 err:
     bdrv_unref(dinfo->bdrv);
-    QTAILQ_REMOVE(&drives, dinfo, next);
-    g_free(dinfo->id);
-    g_free(dinfo);
     blk_unref(blk);
 early_err:
     qemu_opts_del(opts);
@@ -635,6 +628,7 @@ QemuOptsList qemu_legacy_drive_opts = {
 DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
 {
     const char *value;
+    BlockBackend *blk;
     DriveInfo *dinfo = NULL;
     QDict *bs_opts;
     QemuOpts *legacy_opts;
@@ -917,19 +911,17 @@ DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
     }
 
     /* Actual block device init: Functionality shared with blockdev-add */

blockdev.c DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type) · line 917

Quoted 10 lines
blockdev.c +3 -6
-    dinfo = blockdev_init(filename, bs_opts, &local_err);
+    blk = blockdev_init(filename, bs_opts, &local_err);
     bs_opts = NULL;
-    if (dinfo == NULL) {
-        if (local_err) {
-            error_report("%s", error_get_pretty(local_err));
-            error_free(local_err);
-        }
+    if (!blk) {
+        error_report("%s", error_get_pretty(local_err));

Now local_err is leaked.

blockdev.c DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type) · line 921

Quoted 4 lines
blockdev.c +0 -0
         goto fail;
     } else {
         assert(!local_err);
     }

Kevin

#33 lore raw

Re: [Qemu-devel] [PATCH 04/23] block: Connect BlockBackend and DriveInfo

Quoted 124 lines · Kevin Wolf

Am 10.09.2014 um 10:13 hat Markus Armbruster geschrieben:

Quoted 109 lines

Make the BlockBackend own the DriveInfo. Change blockdev_init() to return the BlockBackend instead of the DriveInfo.

---
 block/block-backend.c     | 38 +++++++++++++++++++++++
 blockdev.c                | 79 +++++++++++++++++++++--------------------------
 include/sysemu/blockdev.h |  4 +++
 3 files changed, 78 insertions(+), 43 deletions(-)
block/block-backend.c +38 -0
index deccb54..2a22660 100644
@@ -12,14 +12,18 @@
 
 #include "sysemu/block-backend.h"
 #include "block/block_int.h"
+#include "sysemu/blockdev.h"
 
 struct BlockBackend {
     char *name;
     int refcnt;
     BlockDriverState *bs;
+    DriveInfo *legacy_dinfo;
     QTAILQ_ENTRY(BlockBackend) link; /* for blk_backends */
 };
 
+static void drive_info_del(DriveInfo *dinfo);
+
 static QTAILQ_HEAD(, BlockBackend) blk_backends =
     QTAILQ_HEAD_INITIALIZER(blk_backends);
 
@@ -87,6 +91,7 @@ static void blk_delete(BlockBackend *blk)
     blk_detach_bs(blk);
     QTAILQ_REMOVE(&blk_backends, blk, link);
     g_free(blk->name);
+    drive_info_del(blk->legacy_dinfo);
     g_free(blk);
 }
 
@@ -119,6 +124,16 @@ void blk_unref(BlockBackend *blk)
     }
 }
 
+static void drive_info_del(DriveInfo *dinfo)
+{
+    if (dinfo) {
+        qemu_opts_del(dinfo->opts);
+        g_free(dinfo->id);
+        g_free(dinfo->serial);
+        g_free(dinfo);
+    }
+}
+
 const char *blk_name(BlockBackend *blk)
 {
     return blk->name;
@@ -187,3 +202,26 @@ BlockDriverState *blk_detach_bs(BlockBackend *blk)
     }
     return bs;
 }
+
+DriveInfo *blk_legacy_dinfo(BlockBackend *blk)
+{
+    return blk->legacy_dinfo;
+}
+
+DriveInfo *blk_set_legacy_dinfo(BlockBackend *blk, DriveInfo *dinfo)
+{
+    assert(!blk->legacy_dinfo);
+    return blk->legacy_dinfo = dinfo;
+}
+
+BlockBackend *blk_by_legacy_dinfo(DriveInfo *dinfo)
+{
+    BlockBackend *blk;
+
+    QTAILQ_FOREACH(blk, &blk_backends, link) {
+        if (blk->legacy_dinfo == dinfo) {
+            return blk;
+        }
+    }
+    assert(0);
+}
blockdev.c +2 -3
index 0a0b95e..73e2da9 100644
@@ -47,8 +47,6 @@
 #include "trace.h"
 #include "sysemu/arch_init.h"
 
-static QTAILQ_HEAD(drivelist, DriveInfo) drives = QTAILQ_HEAD_INITIALIZER(drives);
-
 static const char *const if_name[IF_COUNT] = {
     [IF_NONE] = "none",
     [IF_IDE] = "ide",
@@ -89,7 +87,8 @@ static const int if_max_devs[IF_COUNT] = {
  */
 void blockdev_mark_auto_del(BlockDriverState *bs)
 {
-    DriveInfo *dinfo = drive_get_by_blockdev(bs);
+    BlockBackend *blk = bs->blk;
+    DriveInfo *dinfo = blk_legacy_dinfo(blk);
 
     if (dinfo && !dinfo->enable_auto_del) {
         return;

blockdev.c void blockdev_mark_auto_del(BlockDriverState *bs) · line 111

Quoted 9 lines
blockdev.c +2 -1
@@ -105,7 +104,8 @@ void blockdev_mark_auto_del(BlockDriverState *bs)
 
 void blockdev_auto_del(BlockDriverState *bs)
 {
-    DriveInfo *dinfo = drive_get_by_blockdev(bs);
+    BlockBackend *blk = bs->blk;
+    DriveInfo *dinfo = blk_legacy_dinfo(blk);
 
     if (dinfo && dinfo->auto_del) {
         drive_del(dinfo);

The if condition looks as if there were cases where dinfo was NULL. To be precise, this was introduced in commit 0fc0f1fa, so that hot unplug after a forced drive_del wouldn't segfault.

Quoted 4 lines

Does such a device that doesn't have a dinfo at least have a BlockBackend? If it doesn't, we'll segfault in blk_legacy_dinfo(). I won't say that I understand that part of the code, but I can't see why BlockBackend would still be there when DriveInfo isn't any more.

Ah, our friend drive_del again.

As I explained in my reply to your review of PATCH 02, the initial implementation of drive_del destroyed the root BDS and the DriveInfo right away, leaving the device model with a dangling pointer to the root BDS. Naturally, this was prone to crash eventually, when the memory gets reused. But here, it crashes right away, because the DriveInfo no longer exists. Commit 0fc0f1f "fixed" that part. The real fix is commit d22b2f4.

However, my PATCH 18 will change blockdev-add not to create a DriveInfo, and then this test will become necessary again.

Quoted 66 lines
Quoted 66 lines
blockdev.c +16 -16
@@ -153,15 +153,15 @@ QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
 
 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
 {
+    BlockBackend *blk;
     DriveInfo *dinfo;
 
-    /* seek interface, bus and unit */
-
-    QTAILQ_FOREACH(dinfo, &drives, next) {
-        if (dinfo->type == type &&
-	    dinfo->bus == bus &&
-	    dinfo->unit == unit)
+    for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
+        dinfo = blk_legacy_dinfo(blk);
+        if (dinfo && dinfo->type == type
+            && dinfo->bus == bus && dinfo->unit == unit) {
             return dinfo;
+        }
     }
 
     return NULL;
@@ -177,13 +177,15 @@ DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
 int drive_get_max_bus(BlockInterfaceType type)
 {
     int max_bus;
+    BlockBackend *blk;
     DriveInfo *dinfo;
 
     max_bus = -1;
-    QTAILQ_FOREACH(dinfo, &drives, next) {
-        if(dinfo->type == type &&
-           dinfo->bus > max_bus)
+    for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
+        dinfo = blk_legacy_dinfo(blk);
+        if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
             max_bus = dinfo->bus;
+        }
     }
     return max_bus;
 }
@@ -200,11 +202,11 @@ DriveInfo *drive_get_next(BlockInterfaceType type)
 
 DriveInfo *drive_get_by_blockdev(BlockDriverState *bs)
 {
-    DriveInfo *dinfo;
+    BlockBackend *blk;
 
-    QTAILQ_FOREACH(dinfo, &drives, next) {
-        if (dinfo->bdrv == bs) {
-            return dinfo;
+    for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
+        if (blk_bs(blk) == bs) {
+            return blk_legacy_dinfo(blk);
         }
     }
     return NULL;
@@ -217,16 +219,10 @@ static void bdrv_format_print(void *opaque, const char *name)
 
 void drive_del(DriveInfo *dinfo)
 {
-    if (dinfo->opts) {
-        qemu_opts_del(dinfo->opts);
-    }
+    BlockBackend *blk = dinfo->bdrv->blk;
 
Quoted 13 lines

blockdev.c static void bdrv_format_print(void *opaque, const char *name) · line 226

Quoted 8 lines
blockdev.c +1 -5
     bdrv_unref(dinfo->bdrv);
-    blk_unref(blk_by_name(dinfo->id));
-    g_free(dinfo->id);
-    QTAILQ_REMOVE(&drives, dinfo, next);
-    g_free(dinfo->serial);
-    g_free(dinfo);
+    blk_unref(blk);
 }

Now the dinfo stays alive until the last reference for blk is gone. We probably don't care much about the memory that isn't used any more, but not freed yet. What about dinfo->opts? Does it block IDs that should be available again?

Hmm.

I don't think deleting options and DriveInfo makes the ID available for reuse. While you can create new options with the same ID then, you still can't create a new BDS or BB with the same ID while the old ones live.

But let's dig deeper.

This hunk changes behavior of drive_del when blk->refcnt > 1: DriveInfo and the options in qemu_drive_opts stay around. blk->recfcnt > 1 can't happen so far, but that's no excuse.

In current master, we have:

    void drive_del(DriveInfo *dinfo)
    {
        if (dinfo->opts) {
            qemu_opts_del(dinfo->opts);
        }

        bdrv_unref(dinfo->bdrv);
        g_free(dinfo->id);
        QTAILQ_REMOVE(&drives, dinfo, next);
        g_free(dinfo->serial);
        g_free(dinfo);
    }

We destroy the DriveInfo and the options unconditionally, but the BDS only when dinfo->bdrv->refcnt == 1.

Callers:

* drive_hot_add()

Cleanup on error, thus refcnt == 1; destroys both BDS and DriveInfo. Good.

* qmp_blockdev_add() if image is encryped

Likewise.

* blockdev_auto_del()

Runs during device model destruction, when we detach it from its BDS.

If the BDS's refcnt > 0, we destroy the DriveInfo, but not the BDS. Code assuming such a BDS always has a DriveInfo could crash. PATCH 18 eliminates that assumption, thus shows the code in question: all device model initialization.

If we somehow manage to use the BDS to plug in such a device model before the BDS's refcnt drops to zero, we crash. I figure this is possible, because device_add resolves property "drive" via bdrv_find() just fine, even when there's no DriveInfo.

* pci_piix3_xen_ide_unplug()

No idea what this one's supposed to do. Anyway, it also detaches device model from its BDS before drive_del(), so my crash scenario should apply.

* do_drive_del() if no device model is attached

Crash scenario applies.

So my patch is actually a bug fix. I'll look into separating the bug fix part into its own patch.

Quoted 1 line

Do we need a dinfo_attach/detach like for BDSes?

I doubt it.

Quoted 56 lines
Quoted 56 lines
blockdev.c +6 -8
 typedef struct {
@@ -296,8 +292,8 @@ static bool check_throttle_config(ThrottleConfig *cfg, Error **errp)
 typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
 
 /* Takes the ownership of bs_opts */
-static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
-                                Error **errp)
+static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
+                                   Error **errp)
 {
     const char *buf;
     int ro = 0;
@@ -480,7 +476,7 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
     dinfo = g_malloc0(sizeof(*dinfo));
     dinfo->id = g_strdup(qemu_opts_id(opts));
     dinfo->bdrv = bs;
-    QTAILQ_INSERT_TAIL(&drives, dinfo, next);
+    blk_set_legacy_dinfo(blk, dinfo);
 
     if (!file || !*file) {
         if (has_driver_specific_opts) {
@@ -488,7 +484,7 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
         } else {
             QDECREF(bs_opts);
             qemu_opts_del(opts);
-            return dinfo;
+            return blk;
         }
     }
     if (snapshot) {
@@ -525,13 +521,10 @@ static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
     QDECREF(bs_opts);
     qemu_opts_del(opts);
 
-    return dinfo;
+    return blk;
 
 err:
     bdrv_unref(dinfo->bdrv);
-    QTAILQ_REMOVE(&drives, dinfo, next);
-    g_free(dinfo->id);
-    g_free(dinfo);
     blk_unref(blk);
 early_err:
     qemu_opts_del(opts);
@@ -635,6 +628,7 @@ QemuOptsList qemu_legacy_drive_opts = {
 DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
 {
     const char *value;
+    BlockBackend *blk;
     DriveInfo *dinfo = NULL;
     QDict *bs_opts;
     QemuOpts *legacy_opts;
@@ -917,19 +911,17 @@ DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
     }
 
Quoted 13 lines

blockdev.c DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type) · line 917

Quoted 11 lines
blockdev.c +3 -6
     /* Actual block device init: Functionality shared with blockdev-add */
-    dinfo = blockdev_init(filename, bs_opts, &local_err);
+    blk = blockdev_init(filename, bs_opts, &local_err);
     bs_opts = NULL;
-    if (dinfo == NULL) {
-        if (local_err) {
-            error_report("%s", error_get_pretty(local_err));
-            error_free(local_err);
-        }
+    if (!blk) {
+        error_report("%s", error_get_pretty(local_err));

Now local_err is leaked.

Fixing...

Quoted 6 lines

blockdev.c DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type) · line 921

Quoted 4 lines
blockdev.c +0 -0
         goto fail;
     } else {
         assert(!local_err);
     }

Kevin

#34 lore raw

PATCH 5/23 block: Make BlockBackend own its BlockDriverState

In reply to Markus Armbruster

On BlockBackend destruction, unref its BlockDriverState. Replaces the callers' unrefs.

---
 block/block-backend.c |  9 ++-------
 blockdev.c            | 11 +++--------
 hw/block/xen_disk.c   |  6 +++---
 qemu-img.c            | 35 +----------------------------------
 qemu-io.c             |  5 -----
 5 files changed, 9 insertions(+), 57 deletions(-)
block/block-backend.c +2 -7
index 2a22660..ae51f7f 100644
@@ -58,10 +58,7 @@ BlockBackend *blk_new(const char *name, Error **errp)
  * @errp: return location for an error to be set on failure, or %NULL
  *
  * Create a new BlockBackend, with a reference count of one, and
- * attach a new BlockDriverState to it, also with a reference count of
- * one.  Caller owns *both* references.
- * TODO Let caller own only the BlockBackend reference
- * Fail if @name already exists.
+ * a new BlockDriverState attached.  Fail if @name already exists.
  *
  * Returns: the BlockBackend on success, %NULL on error
  */
@@ -88,6 +85,7 @@ BlockBackend *blk_new_with_bs(const char *name, Error **errp)
 static void blk_delete(BlockBackend *blk)
 {
     assert(!blk->refcnt);
+    bdrv_unref(blk->bs);
     blk_detach_bs(blk);
     QTAILQ_REMOVE(&blk_backends, blk, link);
     g_free(blk->name);
@@ -110,9 +108,6 @@ void blk_ref(BlockBackend *blk)
  *
  * Decrement @blk's reference count.  If this drops it to zero,
  * destroy @blk.
- *
- * Does *not* touch the attached BlockDriverState's reference count.
- * TODO Decrement it!
  */
 void blk_unref(BlockBackend *blk)
 {
blockdev.c +3 -8
index 73e2da9..791f6d9 100644
@@ -108,7 +108,7 @@ void blockdev_auto_del(BlockDriverState *bs)
     DriveInfo *dinfo = blk_legacy_dinfo(blk);
 
     if (dinfo && dinfo->auto_del) {
-        drive_del(dinfo);
+        blk_unref(blk);
     }
 }
 
@@ -219,10 +219,7 @@ static void bdrv_format_print(void *opaque, const char *name)
 
 void drive_del(DriveInfo *dinfo)
 {
-    BlockBackend *blk = dinfo->bdrv->blk;
-
-    bdrv_unref(dinfo->bdrv);
-    blk_unref(blk);
+    blk_unref(dinfo->bdrv->blk);
 }
 
 typedef struct {
@@ -524,7 +521,6 @@ static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
     return blk;
 
 err:
-    bdrv_unref(dinfo->bdrv);
     blk_unref(blk);
 early_err:
     qemu_opts_del(opts);
@@ -1778,7 +1774,7 @@ int do_drive_del(Monitor *mon, const QDict *qdict, QObject **ret_data)
         bdrv_set_on_error(bs, BLOCKDEV_ON_ERROR_REPORT,
                           BLOCKDEV_ON_ERROR_REPORT);
     } else {
-        drive_del(drive_get_by_blockdev(bs));
+        blk_unref(blk);
     }
 
     aio_context_release(aio_context);
@@ -2515,7 +2511,6 @@ void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
     }
 
     if (bdrv_key_required(blk_bs(blk))) {
-        bdrv_unref(blk_bs(blk));
         blk_unref(blk);
         error_setg(errp, "blockdev-add doesn't support encrypted devices");
         goto fail;
hw/block/xen_disk.c +3 -3
index 51f4f3a..6d474b9 100644
@@ -870,7 +870,6 @@ static int blk_connect(struct XenDevice *xendev)
             xen_be_printf(&blkdev->xendev, 0, "error: %s\n",
                           error_get_pretty(local_err));
             error_free(local_err);
-            bdrv_unref(blkdev->bs);
             blk_unref(blk);
             blkdev->bs = NULL;
             return -1;
@@ -886,7 +885,9 @@ static int blk_connect(struct XenDevice *xendev)
         }
         /* blkdev->bs is not create by us, we get a reference
          * so we can bdrv_unref() unconditionally */
-        bdrv_ref(blkdev->bs);
+        /* Except we don't bdrv_unref() anymore, we blk_unref().
+         * Conditionally, because we can't easily blk_ref() here.
+         * TODO Clean this up! */
     }
     bdrv_attach_dev_nofail(blkdev->bs, blkdev);
     blkdev->file_size = bdrv_getlength(blkdev->bs);
@@ -986,7 +987,6 @@ static void blk_disconnect(struct XenDevice *xendev)
 
     if (blkdev->bs) {
         bdrv_detach_dev(blkdev->bs, blkdev);
-        bdrv_unref(blkdev->bs);
         if (!blkdev->dinfo) {
             blk_unref(blk_by_name(blkdev->dev));
         }
qemu-img.c +1 -34
index 9fba5a1..083a8eb 100644
@@ -329,7 +329,6 @@ static BlockBackend *img_open(const char *id, const char *filename,
     }
     return blk;
 fail:
-    bdrv_unref(bs);
     blk_unref(blk);
     return NULL;
 }
@@ -712,9 +711,7 @@ static int img_check(int argc, char **argv)
 
 fail:
     qapi_free_ImageCheck(check);
-    bdrv_unref(bs);
     blk_unref(blk);
-
     return ret;
 }
 
@@ -786,7 +783,6 @@ static int img_commit(int argc, char **argv)
         break;
     }
 
-    bdrv_unref(bs);
     blk_unref(blk);
     if (ret) {
         return 1;
@@ -1194,12 +1190,10 @@ static int img_compare(int argc, char **argv)
     ret = 0;
 
 out:
-    bdrv_unref(bs2);
     blk_unref(blk2);
     qemu_vfree(buf1);
     qemu_vfree(buf2);
 out2:
-    bdrv_unref(bs1);
     blk_unref(blk1);
 out3:
     qemu_progress_end();
@@ -1756,18 +1750,8 @@ out:
     if (sn_opts) {
         qemu_opts_del(sn_opts);
     }
-    if (out_bs) {
-        bdrv_unref(out_bs);
-    }
     blk_unref(out_blk);
-    if (bs) {
-        for (bs_i = 0; bs_i < bs_n; bs_i++) {
-            if (bs[bs_i]) {
-                bdrv_unref(bs[bs_i]);
-            }
-        }
-        g_free(bs);
-    }
+    g_free(bs);
     if (blk) {
         for (bs_i = 0; bs_i < bs_n; bs_i++) {
             blk_unref(blk[bs_i]);
@@ -1905,7 +1889,6 @@ static ImageInfoList *collect_image_info_list(const char *filename,
         if (err) {
             error_report("%s", error_get_pretty(err));
             error_free(err);
-            bdrv_unref(bs);
             blk_unref(blk);
             goto err;
         }
@@ -1915,7 +1898,6 @@ static ImageInfoList *collect_image_info_list(const char *filename,
         *last = elem;
         last = &elem->next;
 
-        bdrv_unref(bs);
         blk_unref(blk);
 
         filename = fmt = NULL;
@@ -2204,7 +2186,6 @@ static int img_map(int argc, char **argv)
     dump_map_entry(output_format, &curr, NULL);
 
 out:
-    bdrv_unref(bs);
     blk_unref(blk);
     return ret < 0;
 }
@@ -2329,7 +2310,6 @@ static int img_snapshot(int argc, char **argv)
     }
 
     /* Cleanup */
-    bdrv_unref(bs);
     blk_unref(blk);
     if (ret) {
         return 1;
@@ -2649,17 +2629,10 @@ out:
     qemu_progress_end();
     /* Cleanup */
     if (!unsafe) {
-        if (bs_old_backing != NULL) {
-            bdrv_unref(bs_old_backing);
-        }
         blk_unref(blk_old_backing);
-        if (bs_new_backing != NULL) {
-            bdrv_unref(bs_new_backing);
-        }
         blk_unref(blk_new_backing);
     }
 
-    bdrv_unref(bs);
     blk_unref(blk);
     if (ret) {
         return 1;
@@ -2785,9 +2758,6 @@ static int img_resize(int argc, char **argv)
         break;
     }
 out:
-    if (bs) {
-        bdrv_unref(bs);
-    }
     blk_unref(blk);
     if (ret) {
         return 1;
@@ -2899,9 +2869,6 @@ static int img_amend(int argc, char **argv)
     }
 
 out:
-    if (bs) {
-        bdrv_unref(bs);
-    }
     blk_unref(blk);
     qemu_opts_del(opts);
     qemu_opts_free(create_opts);
qemu-io.c +0 -5
index ef1d3ea..45e8167 100644
@@ -38,7 +38,6 @@ static ReadLineState *readline_state;
 
 static int close_f(BlockDriverState *bs, int argc, char **argv)
 {
-    bdrv_unref(bs);
     blk_unref(qemuio_blk);
     qemuio_bs = NULL;
     qemuio_blk = NULL;
@@ -74,7 +73,6 @@ static int openfile(char *name, int flags, int growable, QDict *opts)
                 name ? " device " : "", name ?: "",
                 error_get_pretty(local_err));
         error_free(local_err);
-        bdrv_unref(qemuio_bs);
         blk_unref(qemuio_blk);
         qemuio_bs = NULL;
         qemuio_blk = NULL;
@@ -483,9 +481,6 @@ int main(int argc, char **argv)
      */
     bdrv_drain_all();
 
-    if (qemuio_bs) {
-        bdrv_unref(qemuio_bs);
-    }
     blk_unref(qemuio_blk);
     g_free(readline_state);
     return 0;
Signature · 1 line
1.9.3
#35 lore raw

Re: [Qemu-devel] [PATCH 05/23] block: Make BlockBackend own its BlockDriverState

Am 10.09.2014 um 10:13 hat Markus Armbruster geschrieben:

Quoted 29 lines

On BlockBackend destruction, unref its BlockDriverState. Replaces the callers' unrefs.

---
 block/block-backend.c |  9 ++-------
 blockdev.c            | 11 +++--------
 hw/block/xen_disk.c   |  6 +++---
 qemu-img.c            | 35 +----------------------------------
 qemu-io.c             |  5 -----
 5 files changed, 9 insertions(+), 57 deletions(-)
block/block-backend.c +1 -4
index 2a22660..ae51f7f 100644
@@ -58,10 +58,7 @@ BlockBackend *blk_new(const char *name, Error **errp)
  * @errp: return location for an error to be set on failure, or %NULL
  *
  * Create a new BlockBackend, with a reference count of one, and
- * attach a new BlockDriverState to it, also with a reference count of
- * one.  Caller owns *both* references.
- * TODO Let caller own only the BlockBackend reference
- * Fail if @name already exists.
+ * a new BlockDriverState attached.  Fail if @name already exists.
  *
  * Returns: the BlockBackend on success, %NULL on error
  */

block/block-backend.c BlockBackend *blk_new_with_bs(const char *name, Error **errp) · line 89

Quoted 5 lines
block/block-backend.c +1 -0
@@ -88,6 +85,7 @@ BlockBackend *blk_new_with_bs(const char *name, Error **errp)
 static void blk_delete(BlockBackend *blk)
 {
     assert(!blk->refcnt);
+    bdrv_unref(blk->bs);
     blk_detach_bs(blk);

I think the bdrv_unref() should really be part of blk_detach_bs().

The same way it would be more logical to have bdrv_ref() as part of blk_attach_bs(). For blk_new_with_bs() this might mean bdrv_new, blk_attach_bs, bdrv_unref, which looks a bit odd, but if blk_attach_bs() is ever called from somewhere else, it probably makes more sense (if it isn't, it should be static).

Kevin

#36 lore raw

Re: [Qemu-devel] [PATCH 05/23] block: Make BlockBackend own its BlockDriverState

Quoted 38 lines · Kevin Wolf

Am 10.09.2014 um 10:13 hat Markus Armbruster geschrieben:

Quoted 29 lines

On BlockBackend destruction, unref its BlockDriverState. Replaces the callers' unrefs.

---
 block/block-backend.c |  9 ++-------
 blockdev.c            | 11 +++--------
 hw/block/xen_disk.c   |  6 +++---
 qemu-img.c            | 35 +----------------------------------
 qemu-io.c             |  5 -----
 5 files changed, 9 insertions(+), 57 deletions(-)
block/block-backend.c +1 -4
index 2a22660..ae51f7f 100644
@@ -58,10 +58,7 @@ BlockBackend *blk_new(const char *name, Error **errp)
  * @errp: return location for an error to be set on failure, or %NULL
  *
  * Create a new BlockBackend, with a reference count of one, and
- * attach a new BlockDriverState to it, also with a reference count of
- * one.  Caller owns *both* references.
- * TODO Let caller own only the BlockBackend reference
- * Fail if @name already exists.
+ * a new BlockDriverState attached.  Fail if @name already exists.
  *
  * Returns: the BlockBackend on success, %NULL on error
  */

block/block-backend.c BlockBackend *blk_new_with_bs(const char *name, Error **errp) · line 89

Quoted 5 lines
block/block-backend.c +1 -0
@@ -88,6 +85,7 @@ BlockBackend *blk_new_with_bs(const char *name, Error **errp)
 static void blk_delete(BlockBackend *blk)
 {
     assert(!blk->refcnt);
+    bdrv_unref(blk->bs);
     blk_detach_bs(blk);

I think the bdrv_unref() should really be part of blk_detach_bs().

Quoted 5 lines

The same way it would be more logical to have bdrv_ref() as part of blk_attach_bs(). For blk_new_with_bs() this might mean bdrv_new, blk_attach_bs, bdrv_unref, which looks a bit odd, but if blk_attach_bs() is ever called from somewhere else, it probably makes more sense (if it isn't, it should be static).

My thinking was that you usually want to acquire a reference when you detach, and you're usually ready to give yours up when you attach.

However, I now think I got a use-after-free hidden around there. I'll look into it tomorrow with a fresh mind. Might lead to me accepting your suggestion without further ado :)

#37 lore raw

PATCH 6/23 block: Eliminate bdrv_states, use block_next() instead

In reply to Markus Armbruster
---
 block.c                   | 43 +++++++++++++++++++------------------------
 block/block-backend.c     |  4 ++++
 include/block/block_int.h |  2 --
 3 files changed, 23 insertions(+), 26 deletions(-)
block.c +19 -24
index a6c03da..89f9cf0 100644
@@ -24,6 +24,7 @@
 #include "config-host.h"
 #include "qemu-common.h"
 #include "trace.h"
+#include "sysemu/block-backend.h"
 #include "block/block_int.h"
 #include "block/blockjob.h"
 #include "qemu/module.h"
@@ -90,9 +91,6 @@ static void coroutine_fn bdrv_co_do_rw(void *opaque);
 static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
     int64_t sector_num, int nb_sectors, BdrvRequestFlags flags);
 
-static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
-    QTAILQ_HEAD_INITIALIZER(bdrv_states);
-
 static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
     QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
 
@@ -355,9 +353,6 @@ BlockDriverState *bdrv_new_named(const char *device_name, Error **errp)
     bs = bdrv_new();
 
     pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
-    if (device_name[0] != '\0') {
-        QTAILQ_INSERT_TAIL(&bdrv_states, bs, device_list);
-    }
 
     return bs;
 }
@@ -1888,7 +1883,7 @@ void bdrv_close_all(void)
 {
     BlockDriverState *bs;
 
-    QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
+    for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
         AioContext *aio_context = bdrv_get_aio_context(bs);
 
         aio_context_acquire(aio_context);
@@ -1939,7 +1934,7 @@ void bdrv_drain_all(void)
     while (busy) {
         busy = false;
 
-        QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
+        for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
             AioContext *aio_context = bdrv_get_aio_context(bs);
             bool bs_busy;
 
@@ -1960,9 +1955,6 @@ void bdrv_drain_all(void)
    Also, NULL terminate the device_name to prevent double remove */
 void bdrv_make_anon(BlockDriverState *bs)
 {
-    if (bs->device_name[0] != '\0') {
-        QTAILQ_REMOVE(&bdrv_states, bs, device_list);
-    }
     bs->device_name[0] = '\0';
     if (bs->node_name[0] != '\0') {
         QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
@@ -2016,10 +2008,9 @@ static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
     /* job */
     bs_dest->job                = bs_src->job;
 
-    /* keep the same entry in bdrv_states */
     pstrcpy(bs_dest->device_name, sizeof(bs_dest->device_name),
             bs_src->device_name);
-    bs_dest->device_list = bs_src->device_list;
+
     memcpy(bs_dest->op_blockers, bs_src->op_blockers,
            sizeof(bs_dest->op_blockers));
 }
@@ -2363,7 +2354,7 @@ int bdrv_commit_all(void)
 {
     BlockDriverState *bs;
 
-    QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
+    for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
         AioContext *aio_context = bdrv_get_aio_context(bs);
 
         aio_context_acquire(aio_context);
@@ -3807,7 +3798,7 @@ BlockDriverState *bdrv_find(const char *name)
 {
     BlockDriverState *bs;
 
-    QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
+    for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
         if (!strcmp(name, bs->device_name)) {
             return bs;
         }
@@ -3888,17 +3879,21 @@ bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
 
 BlockDriverState *bdrv_next(BlockDriverState *bs)
 {
-    if (!bs) {
-        return QTAILQ_FIRST(&bdrv_states);
-    }
-    return QTAILQ_NEXT(bs, device_list);
+    BlockBackend *blk;
+
+    for (blk = blk_next(bs ? bs->blk : NULL);
+         blk && !blk_bs(blk);
+         blk = blk_next(blk))
+        ;
+
+    return blk ? blk_bs(blk) : NULL;
 }
 
 void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
 {
     BlockDriverState *bs;
 
-    QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
+    for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
         it(opaque, bs);
     }
 }
@@ -3918,7 +3913,7 @@ int bdrv_flush_all(void)
     BlockDriverState *bs;
     int result = 0;
 
-    QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
+    for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
         AioContext *aio_context = bdrv_get_aio_context(bs);
         int ret;
 
@@ -5065,7 +5060,7 @@ void bdrv_invalidate_cache_all(Error **errp)
     BlockDriverState *bs;
     Error *local_err = NULL;
 
-    QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
+    for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
         AioContext *aio_context = bdrv_get_aio_context(bs);
 
         aio_context_acquire(aio_context);
@@ -5082,7 +5077,7 @@ void bdrv_clear_incoming_migration_all(void)
 {
     BlockDriverState *bs;
 
-    QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
+    for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
         AioContext *aio_context = bdrv_get_aio_context(bs);
 
         aio_context_acquire(aio_context);
@@ -5918,7 +5913,7 @@ bool bdrv_is_first_non_filter(BlockDriverState *candidate)
     BlockDriverState *bs;
 
     /* walk down the bs forest recursively */
-    QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
+    for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
         bool perm;
 
         /* try to recurse in this top level bs */
block/block-backend.c +4 -0
index ae51f7f..c0876fa 100644
@@ -191,6 +191,10 @@ BlockDriverState *blk_detach_bs(BlockBackend *blk)
 {
     BlockDriverState *bs = blk->bs;
 
+    /*
+     * Must bdrv_unref() before zapping bs->blk, or else
+     * bdrv_drain_all() will miss bs.
+     */
     if (bs) {
         bs->blk = NULL;
         blk->bs = NULL;
include/block/block_int.h +0 -2
index a04c852..d5de08b 100644
@@ -396,8 +396,6 @@ struct BlockDriverState {
     QTAILQ_ENTRY(BlockDriverState) node_list;
     /* Device name is the name associated with the "drive" the guest sees */
     char device_name[32];
-    /* element of the list of "drives" the guest sees */
-    QTAILQ_ENTRY(BlockDriverState) device_list;
     QLIST_HEAD(, BdrvDirtyBitmap) dirty_bitmaps;
     int refcnt;
 
Signature · 1 line
1.9.3
#38 lore raw

Re: [Qemu-devel] [PATCH 06/23] block: Eliminate bdrv_states, use block_next() instead

Quoted 104 lines · Markus Armbruster
---
 block.c                   | 43 +++++++++++++++++++------------------------
 block/block-backend.c     |  4 ++++
 include/block/block_int.h |  2 --
 3 files changed, 23 insertions(+), 26 deletions(-)
block.c +6 -18
index a6c03da..89f9cf0 100644
@@ -24,6 +24,7 @@
 #include "config-host.h"
 #include "qemu-common.h"
 #include "trace.h"
+#include "sysemu/block-backend.h"
 #include "block/block_int.h"
 #include "block/blockjob.h"
 #include "qemu/module.h"
@@ -90,9 +91,6 @@ static void coroutine_fn bdrv_co_do_rw(void *opaque);
 static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
     int64_t sector_num, int nb_sectors, BdrvRequestFlags flags);
 
-static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
-    QTAILQ_HEAD_INITIALIZER(bdrv_states);
-
 static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
     QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
 
@@ -355,9 +353,6 @@ BlockDriverState *bdrv_new_named(const char *device_name, Error **errp)
     bs = bdrv_new();
 
     pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
-    if (device_name[0] != '\0') {
-        QTAILQ_INSERT_TAIL(&bdrv_states, bs, device_list);
-    }
 
     return bs;
 }
@@ -1888,7 +1883,7 @@ void bdrv_close_all(void)
 {
     BlockDriverState *bs;
 
-    QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
+    for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
         AioContext *aio_context = bdrv_get_aio_context(bs);
 
         aio_context_acquire(aio_context);
@@ -1939,7 +1934,7 @@ void bdrv_drain_all(void)
     while (busy) {
         busy = false;
 
-        QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
+        for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
             AioContext *aio_context = bdrv_get_aio_context(bs);
             bool bs_busy;
 
@@ -1960,9 +1955,6 @@ void bdrv_drain_all(void)
    Also, NULL terminate the device_name to prevent double remove */
 void bdrv_make_anon(BlockDriverState *bs)
 {
-    if (bs->device_name[0] != '\0') {
-        QTAILQ_REMOVE(&bdrv_states, bs, device_list);
-    }
     bs->device_name[0] = '\0';
     if (bs->node_name[0] != '\0') {
         QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
@@ -2016,10 +2008,9 @@ static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
     /* job */
     bs_dest->job                = bs_src->job;
 
-    /* keep the same entry in bdrv_states */
     pstrcpy(bs_dest->device_name, sizeof(bs_dest->device_name),
             bs_src->device_name);
-    bs_dest->device_list = bs_src->device_list;
+
     memcpy(bs_dest->op_blockers, bs_src->op_blockers,
            sizeof(bs_dest->op_blockers));
 }
@@ -2363,7 +2354,7 @@ int bdrv_commit_all(void)
 {
     BlockDriverState *bs;
 
-    QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
+    for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
         AioContext *aio_context = bdrv_get_aio_context(bs);
 
         aio_context_acquire(aio_context);
@@ -3807,7 +3798,7 @@ BlockDriverState *bdrv_find(const char *name)
 {
     BlockDriverState *bs;
 
-    QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
+    for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
         if (!strcmp(name, bs->device_name)) {
             return bs;
         }
@@ -3888,17 +3879,21 @@ bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
 
 BlockDriverState *bdrv_next(BlockDriverState *bs)
 {
-    if (!bs) {
-        return QTAILQ_FIRST(&bdrv_states);
-    }

block.c bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base) · line 3890

Quoted 10 lines
block.c +8 -1
-    return QTAILQ_NEXT(bs, device_list);
 
+    BlockBackend *blk;
+
+    for (blk = blk_next(bs ? bs->blk : NULL);
+         blk && !blk_bs(blk);
+         blk = blk_next(blk))
+        ;
+
+    return blk ? blk_bs(blk) : NULL;

I find ?: hard to read and I know at least one maintainer prefers simples ifs to it.

BlockDriverState *bdrv_next(BlockDriverState *bs)

{
    BlockBackend *blk = NULL;

    /* if a BDS is provided use it's block backend as a starting point */
    if (bs) {
        blk = bl->blk;
    }

    /* looking for the next block backend having a BDS attached */
    for (blk = blk_next(blk);
         blk && !blk_bs(blk);
         blk = blk_next(blk))
         ;
   /* the search was successfull */
   if (blk) {
       return blk_bs(blk);
   }

return NULL;
}

I think getting rid of ?: spread the brain load sequentially by being less compact but anyway your code is correct so it's up to you.

Quoted 78 lines
block.c +1 -1
 }
 
 void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
 {
     BlockDriverState *bs;
 
-    QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
+    for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
         it(opaque, bs);
     }

}

block.c +4 -4
@@ -3918,7 +3913,7 @@ int bdrv_flush_all(void)
     BlockDriverState *bs;
     int result = 0;
 
-    QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
+    for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
         AioContext *aio_context = bdrv_get_aio_context(bs);
         int ret;
 
@@ -5065,7 +5060,7 @@ void bdrv_invalidate_cache_all(Error **errp)
     BlockDriverState *bs;
     Error *local_err = NULL;
 
-    QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
+    for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
         AioContext *aio_context = bdrv_get_aio_context(bs);
 
         aio_context_acquire(aio_context);
@@ -5082,7 +5077,7 @@ void bdrv_clear_incoming_migration_all(void)
 {
     BlockDriverState *bs;
 
-    QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
+    for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
         AioContext *aio_context = bdrv_get_aio_context(bs);
 
         aio_context_acquire(aio_context);
@@ -5918,7 +5913,7 @@ bool bdrv_is_first_non_filter(BlockDriverState *candidate)
     BlockDriverState *bs;
 
     /* walk down the bs forest recursively */
-    QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
+    for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
         bool perm;
 
         /* try to recurse in this top level bs */
block/block-backend.c +4 -0
index ae51f7f..c0876fa 100644
@@ -191,6 +191,10 @@ BlockDriverState *blk_detach_bs(BlockBackend *blk)
 {
     BlockDriverState *bs = blk->bs;
 
+    /*
+     * Must bdrv_unref() before zapping bs->blk, or else
+     * bdrv_drain_all() will miss bs.
+     */
     if (bs) {
         bs->blk = NULL;
         blk->bs = NULL;
include/block/block_int.h +0 -2
index a04c852..d5de08b 100644
@@ -396,8 +396,6 @@ struct BlockDriverState {
     QTAILQ_ENTRY(BlockDriverState) node_list;
     /* Device name is the name associated with the "drive" the guest sees */
     char device_name[32];
-    /* element of the list of "drives" the guest sees */
-    QTAILQ_ENTRY(BlockDriverState) device_list;
     QLIST_HEAD(, BdrvDirtyBitmap) dirty_bitmaps;
     int refcnt;
 
Signature · 1 line
1.9.3
#39 lore raw

PATCH 7/23 block: Eliminate bdrv_iterate(), use bdrv_next()

In reply to Markus Armbruster
---
 block-migration.c     | 30 +++++++++++++++---------------
 block.c               |  9 ---------
 blockdev.c            | 31 +++++++++++++------------------
 include/block/block.h |  2 --
 monitor.c             | 33 +++++++++------------------------
 5 files changed, 37 insertions(+), 68 deletions(-)
block-migration.c +15 -15
index 3ad31a2..cb3e16c 100644
@@ -343,12 +343,25 @@ static void unset_dirty_tracking(void)
     }
 }
 
-static void init_blk_migration_it(void *opaque, BlockDriverState *bs)
+static void init_blk_migration(QEMUFile *f)
 {
+    BlockDriverState *bs;
     BlkMigDevState *bmds;
     int64_t sectors;
 
-    if (!bdrv_is_read_only(bs)) {
+    block_mig_state.submitted = 0;
+    block_mig_state.read_done = 0;
+    block_mig_state.transferred = 0;
+    block_mig_state.total_sector_sum = 0;
+    block_mig_state.prev_progress = -1;
+    block_mig_state.bulk_completed = 0;
+    block_mig_state.zero_blocks = migrate_zero_blocks();
+
+    for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
+        if (bdrv_is_read_only(bs)) {
+            continue;
+        }
+
         sectors = bdrv_nb_sectors(bs);
         if (sectors <= 0) {
             return;
@@ -378,19 +391,6 @@ static void init_blk_migration_it(void *opaque, BlockDriverState *bs)
     }
 }
 
-static void init_blk_migration(QEMUFile *f)
-{
-    block_mig_state.submitted = 0;
-    block_mig_state.read_done = 0;
-    block_mig_state.transferred = 0;
-    block_mig_state.total_sector_sum = 0;
-    block_mig_state.prev_progress = -1;
-    block_mig_state.bulk_completed = 0;
-    block_mig_state.zero_blocks = migrate_zero_blocks();
-
-    bdrv_iterate(init_blk_migration_it, NULL);
-}
-
 /* Called with no lock taken.  */
 
 static int blk_mig_save_bulked_block(QEMUFile *f)
block.c +0 -9
index 89f9cf0..593d89b 100644
@@ -3889,15 +3889,6 @@ BlockDriverState *bdrv_next(BlockDriverState *bs)
     return blk ? blk_bs(blk) : NULL;
 }
 
-void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
-{
-    BlockDriverState *bs;
-
-    for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
-        it(opaque, bs);
-    }
-}
-
 const char *bdrv_get_device_name(BlockDriverState *bs)
 {
     return bs->device_name;
blockdev.c +13 -18
index 791f6d9..353563e 100644
@@ -2520,26 +2520,21 @@ fail:
     qmp_output_visitor_cleanup(ov);
 }
 
-static void do_qmp_query_block_jobs_one(void *opaque, BlockDriverState *bs)
-{
-    BlockJobInfoList **prev = opaque;
-    BlockJob *job = bs->job;
-
-    if (job) {
-        BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1);
-        elem->value = block_job_query(bs->job);
-        (*prev)->next = elem;
-        *prev = elem;
-    }
-}
-
 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
 {
-    /* Dummy is a fake list element for holding the head pointer */
-    BlockJobInfoList dummy = {};
-    BlockJobInfoList *prev = &dummy;
-    bdrv_iterate(do_qmp_query_block_jobs_one, &prev);
-    return dummy.next;
+    BlockJobInfoList *head = NULL, **p_next = &head;
+    BlockDriverState *bs;
+
+    for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
+        if (bs->job) {
+            BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1);
+            elem->value = block_job_query(bs->job);
+            *p_next = elem;
+            p_next = &elem->next;
+        }
+    }
+
+    return head;
 }
 
 QemuOptsList qemu_common_drive_opts = {
include/block/block.h +0 -2
index 95139c0..8cf9ea3 100644
@@ -409,8 +409,6 @@ BlockDriverState *bdrv_lookup_bs(const char *device,
                                  Error **errp);
 bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base);
 BlockDriverState *bdrv_next(BlockDriverState *bs);
-void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs),
-                  void *opaque);
 int bdrv_is_encrypted(BlockDriverState *bs);
 int bdrv_key_required(BlockDriverState *bs);
 int bdrv_set_key(BlockDriverState *bs, const char *key);
monitor.c +9 -24
index 34cee74..4ae66df 100644
@@ -4208,24 +4208,6 @@ static void file_completion(Monitor *mon, const char *input)
     closedir(ffs);
 }
 
-typedef struct MonitorBlockComplete {
-    Monitor *mon;
-    const char *input;
-} MonitorBlockComplete;
-
-static void block_completion_it(void *opaque, BlockDriverState *bs)
-{
-    const char *name = bdrv_get_device_name(bs);
-    MonitorBlockComplete *mbc = opaque;
-    Monitor *mon = mbc->mon;
-    const char *input = mbc->input;
-
-    if (input[0] == '\0' ||
-        !strncmp(name, (char *)input, strlen(input))) {
-        readline_add_completion(mon->rs, name);
-    }
-}
-
 static const char *next_arg_type(const char *typestr)
 {
     const char *p = strchr(typestr, ':');
@@ -4663,9 +4645,9 @@ static void monitor_find_completion_by_table(Monitor *mon,
 {
     const char *cmdname;
     int i;
-    const char *ptype, *str;
+    const char *ptype, *str, *name;
     const mon_cmd_t *cmd;
-    MonitorBlockComplete mbs;
+    BlockDriverState *bs;
 
     if (nb_args <= 1) {
         /* command completion */
@@ -4717,10 +4699,13 @@ static void monitor_find_completion_by_table(Monitor *mon,
             break;
         case 'B':
             /* block device name completion */
-            mbs.mon = mon;
-            mbs.input = str;
-            readline_set_completion_index(mon->rs, strlen(str));
-            bdrv_iterate(block_completion_it, &mbs);
+            for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
+                name = bdrv_get_device_name(bs);
+                if (str[0] == '\0' ||
+                    !strncmp(name, str, strlen(str))) {
+                    readline_add_completion(mon->rs, name);
+                }
+            }
             break;
         case 's':
         case 'S':
Signature · 1 line
1.9.3
#40 lore raw

Re: [Qemu-devel] [PATCH 07/23] block: Eliminate bdrv_iterate(), use bdrv_next()

Quoted 180 lines · Markus Armbruster
---
 block-migration.c     | 30 +++++++++++++++---------------
 block.c               |  9 ---------
 blockdev.c            | 31 +++++++++++++------------------
 include/block/block.h |  2 --
 monitor.c             | 33 +++++++++------------------------
 5 files changed, 37 insertions(+), 68 deletions(-)
block-migration.c +15 -15
index 3ad31a2..cb3e16c 100644
@@ -343,12 +343,25 @@ static void unset_dirty_tracking(void)
     }
 }
 
-static void init_blk_migration_it(void *opaque, BlockDriverState *bs)
+static void init_blk_migration(QEMUFile *f)
 {
+    BlockDriverState *bs;
     BlkMigDevState *bmds;
     int64_t sectors;
 
-    if (!bdrv_is_read_only(bs)) {
+    block_mig_state.submitted = 0;
+    block_mig_state.read_done = 0;
+    block_mig_state.transferred = 0;
+    block_mig_state.total_sector_sum = 0;
+    block_mig_state.prev_progress = -1;
+    block_mig_state.bulk_completed = 0;
+    block_mig_state.zero_blocks = migrate_zero_blocks();
+
+    for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
+        if (bdrv_is_read_only(bs)) {
+            continue;
+        }
+
         sectors = bdrv_nb_sectors(bs);
         if (sectors <= 0) {
             return;
@@ -378,19 +391,6 @@ static void init_blk_migration_it(void *opaque, BlockDriverState *bs)
     }
 }
 
-static void init_blk_migration(QEMUFile *f)
-{
-    block_mig_state.submitted = 0;
-    block_mig_state.read_done = 0;
-    block_mig_state.transferred = 0;
-    block_mig_state.total_sector_sum = 0;
-    block_mig_state.prev_progress = -1;
-    block_mig_state.bulk_completed = 0;
-    block_mig_state.zero_blocks = migrate_zero_blocks();
-
-    bdrv_iterate(init_blk_migration_it, NULL);
-}
-
 /* Called with no lock taken.  */
 
 static int blk_mig_save_bulked_block(QEMUFile *f)
block.c +0 -9
index 89f9cf0..593d89b 100644
@@ -3889,15 +3889,6 @@ BlockDriverState *bdrv_next(BlockDriverState *bs)
     return blk ? blk_bs(blk) : NULL;
 }
 
-void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
-{
-    BlockDriverState *bs;
-
-    for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
-        it(opaque, bs);
-    }
-}
-
 const char *bdrv_get_device_name(BlockDriverState *bs)
 {
     return bs->device_name;
blockdev.c +13 -18
index 791f6d9..353563e 100644
@@ -2520,26 +2520,21 @@ fail:
     qmp_output_visitor_cleanup(ov);
 }
 
-static void do_qmp_query_block_jobs_one(void *opaque, BlockDriverState *bs)
-{
-    BlockJobInfoList **prev = opaque;
-    BlockJob *job = bs->job;
-
-    if (job) {
-        BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1);
-        elem->value = block_job_query(bs->job);
-        (*prev)->next = elem;
-        *prev = elem;
-    }
-}
-
 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
 {
-    /* Dummy is a fake list element for holding the head pointer */
-    BlockJobInfoList dummy = {};
-    BlockJobInfoList *prev = &dummy;
-    bdrv_iterate(do_qmp_query_block_jobs_one, &prev);
-    return dummy.next;
+    BlockJobInfoList *head = NULL, **p_next = &head;
+    BlockDriverState *bs;
+
+    for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
+        if (bs->job) {
+            BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1);
+            elem->value = block_job_query(bs->job);
+            *p_next = elem;
+            p_next = &elem->next;
+        }
+    }
+
+    return head;
 }
 
 QemuOptsList qemu_common_drive_opts = {
include/block/block.h +0 -2
index 95139c0..8cf9ea3 100644
@@ -409,8 +409,6 @@ BlockDriverState *bdrv_lookup_bs(const char *device,
                                  Error **errp);
 bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base);
 BlockDriverState *bdrv_next(BlockDriverState *bs);
-void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs),
-                  void *opaque);
 int bdrv_is_encrypted(BlockDriverState *bs);
 int bdrv_key_required(BlockDriverState *bs);
 int bdrv_set_key(BlockDriverState *bs, const char *key);
monitor.c +2 -20
index 34cee74..4ae66df 100644
@@ -4208,24 +4208,6 @@ static void file_completion(Monitor *mon, const char *input)
     closedir(ffs);
 }
 
-typedef struct MonitorBlockComplete {
-    Monitor *mon;
-    const char *input;
-} MonitorBlockComplete;
-
-static void block_completion_it(void *opaque, BlockDriverState *bs)
-{
-    const char *name = bdrv_get_device_name(bs);
-    MonitorBlockComplete *mbc = opaque;
-    Monitor *mon = mbc->mon;
-    const char *input = mbc->input;
-
-    if (input[0] == '\0' ||
-        !strncmp(name, (char *)input, strlen(input))) {
-        readline_add_completion(mon->rs, name);
-    }
-}
-
 static const char *next_arg_type(const char *typestr)
 {
     const char *p = strchr(typestr, ':');
@@ -4663,9 +4645,9 @@ static void monitor_find_completion_by_table(Monitor *mon,
 {
     const char *cmdname;
     int i;
-    const char *ptype, *str;
+    const char *ptype, *str, *name;
     const mon_cmd_t *cmd;
-    MonitorBlockComplete mbs;
+    BlockDriverState *bs;
 
     if (nb_args <= 1) {
         /* command completion */

monitor.c static void monitor_find_completion_by_table(Monitor *mon, · line 4723

Quoted 7 lines
monitor.c +0 -3
@@ -4717,10 +4699,13 @@ static void monitor_find_completion_by_table(Monitor *mon,
             break;
         case 'B':
             /* block device name completion */
-            mbs.mon = mon;
-            mbs.input = str;
 
-            readline_set_completion_index(mon->rs, strlen(str));

Why is this line removed ?
In monitor readline_set_completion_index seems to work in pair with readline_add_completion. Either this line should be removed and readline_add_completion too or the oposite.

Quoted 15 lines
monitor.c +7 -1
-            bdrv_iterate(block_completion_it, &mbs);
+            for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
+                name = bdrv_get_device_name(bs);
+                if (str[0] == '\0' ||
+                    !strncmp(name, str, strlen(str))) {
+                    readline_add_completion(mon->rs, name);
+                }
+            }
             break;
         case 's':
         case 'S':
Signature · 1 line
1.9.3
#41 lore raw

Re: [Qemu-devel] [PATCH 07/23] block: Eliminate bdrv_iterate(), use bdrv_next()

Quoted 1 line · Benoît Canet

The Wednesday 10 Sep 2014 à 10:13:36 (+0200), Markus Armbruster wrote :

[...]

Quoted 46 lines
Quoted 45 lines
monitor.c +2 -22
@@ -4208,24 +4208,6 @@ static void file_completion(Monitor *mon, const char *input)
     closedir(ffs);
 }
 
-typedef struct MonitorBlockComplete {
-    Monitor *mon;
-    const char *input;
-} MonitorBlockComplete;
-
-static void block_completion_it(void *opaque, BlockDriverState *bs)
-{
-    const char *name = bdrv_get_device_name(bs);
-    MonitorBlockComplete *mbc = opaque;
-    Monitor *mon = mbc->mon;
-    const char *input = mbc->input;
-
-    if (input[0] == '\0' ||
-        !strncmp(name, (char *)input, strlen(input))) {
-        readline_add_completion(mon->rs, name);
-    }
-}
-
 static const char *next_arg_type(const char *typestr)
 {
     const char *p = strchr(typestr, ':');
@@ -4663,9 +4645,9 @@ static void monitor_find_completion_by_table(Monitor *mon,
 {
     const char *cmdname;
     int i;
-    const char *ptype, *str;
+    const char *ptype, *str, *name;
     const mon_cmd_t *cmd;
-    MonitorBlockComplete mbs;
+    BlockDriverState *bs;
 
     if (nb_args <= 1) {
         /* command completion */
@@ -4717,10 +4699,13 @@ static void monitor_find_completion_by_table(Monitor *mon,
             break;
         case 'B':
             /* block device name completion */
-            mbs.mon = mon;
-            mbs.input = str;
Quoted 3 lines

monitor.c static void monitor_find_completion_by_table(Monitor *mon, · line 4722

Quoted 1 line
monitor.c +0 -1
-            readline_set_completion_index(mon->rs, strlen(str));

Why is this line removed ?

Accident! Fixing...

Quoted 20 lines

In monitor readline_set_completion_index seems to work in pair with readline_add_completion.
Either this line should be removed and readline_add_completion too or the oposite.

Quoted 15 lines
monitor.c +7 -1
-            bdrv_iterate(block_completion_it, &mbs);
+            for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
+                name = bdrv_get_device_name(bs);
+                if (str[0] == '\0' ||
+                    !strncmp(name, str, strlen(str))) {
+                    readline_add_completion(mon->rs, name);
+                }
+            }
             break;
         case 's':
         case 'S':
Signature · 1 line
1.9.3
#42 lore raw

PATCH 8/23 block: Eliminate BlockDriverState member device_name[]

In reply to Markus Armbruster

device_name[] is can become non-empty only in bdrv_new_named() and bdrv_move_feature_fields(). The latter is used only to undo damage done by bdrv_swap(). The former is called only by blk_new_with_bs(). Therefore, when a BlockDriverState's device_name[] is non-empty, then it's owned by a BlockBackend.

The converse is also true, because blk_attach_bs() is called only by blk_new_with_bs() so far.

Furthermore, blk_new_with_bs() keeps the two names equal.

Therefore, device_name[] is redundant. Eliminate it.

---
 block-migration.c         | 12 +++++----
 block.c                   | 63 ++++++++++++++---------------------------------
 block/block-backend.c     | 12 ++++-----
 block/cow.c               |  2 +-
 block/mirror.c            |  3 ++-
 block/qapi.c              |  6 ++---
 block/qcow.c              |  4 +--
 block/qcow2.c             |  4 +--
 block/qed.c               |  2 +-
 block/quorum.c            |  4 +--
 block/vdi.c               |  2 +-
 block/vhdx.c              |  2 +-
 block/vmdk.c              |  4 +--
 block/vpc.c               |  2 +-
 block/vvfat.c             |  2 +-
 blockjob.c                |  3 ++-
 include/block/block.h     |  3 +--
 include/block/block_int.h |  2 --
 18 files changed, 53 insertions(+), 79 deletions(-)
block-migration.c +7 -5
index cb3e16c..da30e93 100644
@@ -14,7 +14,9 @@
  */
 
 #include "qemu-common.h"
-#include "block/block_int.h"
+#include "block/block.h"
+#include "qemu/error-report.h"
+#include "qemu/main-loop.h"
 #include "hw/hw.h"
 #include "qemu/queue.h"
 #include "qemu/timer.h"
@@ -130,9 +132,9 @@ static void blk_send(QEMUFile *f, BlkMigBlock * blk)
                      | flags);
 
     /* device name */
-    len = strlen(blk->bmds->bs->device_name);
+    len = strlen(bdrv_get_device_name(blk->bmds->bs));
     qemu_put_byte(f, len);
-    qemu_put_buffer(f, (uint8_t *)blk->bmds->bs->device_name, len);
+    qemu_put_buffer(f, (uint8_t *)bdrv_get_device_name(blk->bmds->bs), len);
 
     /* if a block is zero we need to flush here since the network
      * bandwidth is now a lot higher than the storage device bandwidth.
@@ -382,9 +384,9 @@ static void init_blk_migration(QEMUFile *f)
 
         if (bmds->shared_base) {
             DPRINTF("Start migration for %s with shared base image\n",
-                    bs->device_name);
+                    bdrv_get_device_name(bs));
         } else {
-            DPRINTF("Start full migration for %s\n", bs->device_name);
+            DPRINTF("Start full migration for %s\n", bdrv_get_device_name(bs));
         }
 
         QSIMPLEQ_INSERT_TAIL(&block_mig_state.bmds_list, bmds, entry);
block.c +18 -45

159 lines not on this page · raw message

block/block-backend.c +6 -6
index c0876fa..2f10d6a 100644
@@ -67,17 +67,17 @@ BlockBackend *blk_new_with_bs(const char *name, Error **errp)
     BlockBackend *blk;
     BlockDriverState *bs;
 
+    if (bdrv_find_node(name)) {
+        error_setg(errp, "Device with node-name '%s' already exists", name);
+        return NULL;
+    }
+
     blk = blk_new(name, errp);
     if (!blk) {
         return NULL;
     }
 
-    bs = bdrv_new_named(name, errp);
-    if (!bs) {
-        blk_unref(blk);
-        return NULL;
-    }
-
+    bs = bdrv_new();
     blk_attach_bs(blk, bs);
     return blk;
 }
block/cow.c +1 -1
index 6ee4833..dda1e17 100644
@@ -84,7 +84,7 @@ static int cow_open(BlockDriverState *bs, QDict *options, int flags,
         snprintf(version, sizeof(version),
                "COW version %" PRIu32, cow_header.version);
         error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
-            bs->device_name, "cow", version);
+            bdrv_get_device_name(bs), "cow", version);
         ret = -ENOTSUP;
         goto fail;
     }
block/mirror.c +2 -1
index 18b18e0..829be2f 100644
@@ -567,7 +567,8 @@ static void mirror_complete(BlockJob *job, Error **errp)
         return;
     }
     if (!s->synced) {
-        error_set(errp, QERR_BLOCK_JOB_NOT_READY, job->bs->device_name);
+        error_set(errp, QERR_BLOCK_JOB_NOT_READY,
+                  bdrv_get_device_name(job->bs));
         return;
     }
 
block/qapi.c +3 -3
index 79d1e6a..cc8f711 100644
@@ -272,7 +272,7 @@ void bdrv_query_info(BlockDriverState *bs,
     BlockDriverState *bs0;
     ImageInfo **p_image_info;
     Error *local_err = NULL;
-    info->device = g_strdup(bs->device_name);
+    info->device = g_strdup(bdrv_get_device_name(bs));
     info->type = g_strdup("unknown");
     info->locked = bdrv_dev_is_medium_locked(bs);
     info->removable = bdrv_dev_has_removable_media(bs);
@@ -327,9 +327,9 @@ static BlockStats *bdrv_query_stats(const BlockDriverState *bs)
 
     s = g_malloc0(sizeof(*s));
 
-    if (bs->device_name[0]) {
+    if (bdrv_get_device_name(bs)[0]) {
         s->has_device = true;
-        s->device = g_strdup(bs->device_name);
+        s->device = g_strdup(bdrv_get_device_name(bs));
     }
 
     s->stats = g_malloc0(sizeof(*s->stats));
block/qcow.c +2 -2
index 67c237f..2d803ac 100644
@@ -124,7 +124,7 @@ static int qcow_open(BlockDriverState *bs, QDict *options, int flags,
         snprintf(version, sizeof(version), "QCOW version %" PRIu32,
                  header.version);
         error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
-                  bs->device_name, "qcow", version);
+                  bdrv_get_device_name(bs), "qcow", version);
         ret = -ENOTSUP;
         goto fail;
     }
@@ -231,7 +231,7 @@ static int qcow_open(BlockDriverState *bs, QDict *options, int flags,
     /* Disable migration when qcow images are used */
     error_set(&s->migration_blocker,
               QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
-              "qcow", bs->device_name, "live migration");
+              "qcow", bdrv_get_device_name(bs), "live migration");
     migrate_add_blocker(s->migration_blocker);
 
     qemu_co_mutex_init(&s->lock);
block/qcow2.c +2 -2
index f9e045f..0ab455e 100644
@@ -203,8 +203,8 @@ static void GCC_FMT_ATTR(3, 4) report_unsupported(BlockDriverState *bs,
     vsnprintf(msg, sizeof(msg), fmt, ap);
     va_end(ap);
 
-    error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE, bs->device_name, "qcow2",
-              msg);
+    error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
+              bdrv_get_device_name(bs), "qcow2", msg);
 }
 
 static void report_unsupported_feature(BlockDriverState *bs,
block/qed.c +1 -1
index ba395af..f20ffb3 100644
@@ -422,7 +422,7 @@ static int bdrv_qed_open(BlockDriverState *bs, QDict *options, int flags,
         snprintf(buf, sizeof(buf), "%" PRIx64,
             s->header.features & ~QED_FEATURE_MASK);
         error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
-            bs->device_name, "QED", buf);
+            bdrv_get_device_name(bs), "QED", buf);
         return -ENOTSUP;
     }
     if (!qed_is_cluster_size_valid(s->header.cluster_size)) {
block/quorum.c +2 -2
index 093382e..f958269 100644
@@ -227,8 +227,8 @@ static void quorum_report_bad(QuorumAIOCB *acb, char *node_name, int ret)
 
 static void quorum_report_failure(QuorumAIOCB *acb)
 {
-    const char *reference = acb->common.bs->device_name[0] ?
-                            acb->common.bs->device_name :
+    const char *reference = bdrv_get_device_name(acb->common.bs)[0] ?
+                            bdrv_get_device_name(acb->common.bs) :
                             acb->common.bs->node_name;
 
     qapi_event_send_quorum_failure(reference, acb->sector_num,
block/vdi.c +1 -1
index 4b10aac..2e6f31c 100644
@@ -490,7 +490,7 @@ static int vdi_open(BlockDriverState *bs, QDict *options, int flags,
     /* Disable migration when vdi images are used */
     error_set(&s->migration_blocker,
               QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
-              "vdi", bs->device_name, "live migration");
+              "vdi", bdrv_get_device_name(bs), "live migration");
     migrate_add_blocker(s->migration_blocker);
 
     return 0;
block/vhdx.c +1 -1
index 87c99fc..8bf1af1 100644
@@ -1003,7 +1003,7 @@ static int vhdx_open(BlockDriverState *bs, QDict *options, int flags,
     /* Disable migration when VHDX images are used */
     error_set(&s->migration_blocker,
             QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
-            "vhdx", bs->device_name, "live migration");
+            "vhdx", bdrv_get_device_name(bs), "live migration");
     migrate_add_blocker(s->migration_blocker);
 
     return 0;
block/vmdk.c +2 -2
index a1cb911..7bc1474 100644
@@ -657,7 +657,7 @@ static int vmdk_open_vmdk4(BlockDriverState *bs,
         snprintf(buf, sizeof(buf), "VMDK version %" PRId32,
                  le32_to_cpu(header.version));
         error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
-                  bs->device_name, "vmdk", buf);
+                  bdrv_get_device_name(bs), "vmdk", buf);
         return -ENOTSUP;
     } else if (le32_to_cpu(header.version) == 3 && (flags & BDRV_O_RDWR)) {
         /* VMware KB 2064959 explains that version 3 added support for
@@ -939,7 +939,7 @@ static int vmdk_open(BlockDriverState *bs, QDict *options, int flags,
     /* Disable migration when VMDK images are used */
     error_set(&s->migration_blocker,
               QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
-              "vmdk", bs->device_name, "live migration");
+              "vmdk", bdrv_get_device_name(bs), "live migration");
     migrate_add_blocker(s->migration_blocker);
     g_free(buf);
     return 0;
block/vpc.c +1 -1
index 055efc4..7bb90d5 100644
@@ -320,7 +320,7 @@ static int vpc_open(BlockDriverState *bs, QDict *options, int flags,
     /* Disable migration when VHD images are used */
     error_set(&s->migration_blocker,
               QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
-              "vpc", bs->device_name, "live migration");
+              "vpc", bdrv_get_device_name(bs), "live migration");
     migrate_add_blocker(s->migration_blocker);
 
     return 0;
block/vvfat.c +1 -1
index 6c9fde0..cefe3a4 100644
@@ -1182,7 +1182,7 @@ static int vvfat_open(BlockDriverState *bs, QDict *options, int flags,
     if (s->qcow) {
         error_set(&s->migration_blocker,
                   QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
-                  "vvfat (rw)", bs->device_name, "live migration");
+                  "vvfat (rw)", bdrv_get_device_name(bs), "live migration");
         migrate_add_blocker(s->migration_blocker);
     }
 
blockjob.c +2 -1
index 0689fdd..3af0f6c 100644
@@ -107,7 +107,8 @@ void block_job_set_speed(BlockJob *job, int64_t speed, Error **errp)
 void block_job_complete(BlockJob *job, Error **errp)
 {
     if (job->paused || job->cancelled || !job->driver->complete) {
-        error_set(errp, QERR_BLOCK_JOB_NOT_READY, job->bs->device_name);
+        error_set(errp, QERR_BLOCK_JOB_NOT_READY,
+                  bdrv_get_device_name(job->bs));
         return;
     }
 
include/block/block.h +1 -2
index 8cf9ea3..fb4fff9 100644
@@ -203,7 +203,6 @@ BlockDriver *bdrv_find_whitelisted_format(const char *format_name,
 int bdrv_create(BlockDriver *drv, const char* filename,
                 QemuOpts *opts, Error **errp);
 int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp);
-BlockDriverState *bdrv_new_named(const char *device_name, Error **errp);
 BlockDriverState *bdrv_new(void);
 void bdrv_make_anon(BlockDriverState *bs);
 void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old);
@@ -415,7 +414,7 @@ int bdrv_set_key(BlockDriverState *bs, const char *key);
 int bdrv_query_missing_keys(void);
 void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
                          void *opaque);
-const char *bdrv_get_device_name(BlockDriverState *bs);
+const char *bdrv_get_device_name(const BlockDriverState *bs);
 int bdrv_get_flags(BlockDriverState *bs);
 int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
                           const uint8_t *buf, int nb_sectors);
include/block/block_int.h +0 -2
index d5de08b..08ccb27 100644
@@ -394,8 +394,6 @@ struct BlockDriverState {
     char node_name[32];
     /* element of the list of named nodes building the graph */
     QTAILQ_ENTRY(BlockDriverState) node_list;
-    /* Device name is the name associated with the "drive" the guest sees */
-    char device_name[32];
     QLIST_HEAD(, BdrvDirtyBitmap) dirty_bitmaps;
     int refcnt;
 
Signature · 1 line
1.9.3
#43 lore raw

Re: [Qemu-devel] [PATCH 08/23] block: Eliminate BlockDriverState member device_name[]

Quoted 1 line · Markus Armbruster

device_name[] is can become non-empty only in bdrv_new_named() and

s/is //

Quoted 14 lines

bdrv_move_feature_fields(). The latter is used only to undo damage done by bdrv_swap(). The former is called only by blk_new_with_bs(). Therefore, when a BlockDriverState's device_name[] is non-empty, then it's owned by a BlockBackend.

The converse is also true, because blk_attach_bs() is called only by blk_new_with_bs() so far.

Furthermore, blk_new_with_bs() keeps the two names equal.

Therefore, device_name[] is redundant. Eliminate it.

---

Signature · 2 lines
Eric Blake   eblake redhat com    +1-919-301-3266
Libvirt virtualization library http://libvirt.org
#44 lore raw

Re: [Qemu-devel] [PATCH 08/23] block: Eliminate BlockDriverState member device_name[]

Quoted 4 lines · Eric Blake
Quoted 1 line · Markus Armbruster

device_name[] is can become non-empty only in bdrv_new_named() and

s/is //

Fixing, thanks!

Quoted 14 lines
Quoted 14 lines

bdrv_move_feature_fields(). The latter is used only to undo damage done by bdrv_swap(). The former is called only by blk_new_with_bs(). Therefore, when a BlockDriverState's device_name[] is non-empty, then it's owned by a BlockBackend.

The converse is also true, because blk_attach_bs() is called only by blk_new_with_bs() so far.

Furthermore, blk_new_with_bs() keeps the two names equal.

Therefore, device_name[] is redundant. Eliminate it.

---

#45 lore raw

Re: [Qemu-devel] [PATCH 08/23] block: Eliminate BlockDriverState member device_name[]

In reply to Markus Armbruster
Quoted 212 lines · Markus Armbruster

device_name[] is can become non-empty only in bdrv_new_named() and bdrv_move_feature_fields(). The latter is used only to undo damage done by bdrv_swap(). The former is called only by blk_new_with_bs(). Therefore, when a BlockDriverState's device_name[] is non-empty, then it's owned by a BlockBackend.

The converse is also true, because blk_attach_bs() is called only by blk_new_with_bs() so far.

Furthermore, blk_new_with_bs() keeps the two names equal.

Therefore, device_name[] is redundant. Eliminate it.

---
 block-migration.c         | 12 +++++----
 block.c                   | 63 ++++++++++++++---------------------------------
 block/block-backend.c     | 12 ++++-----
 block/cow.c               |  2 +-
 block/mirror.c            |  3 ++-
 block/qapi.c              |  6 ++---
 block/qcow.c              |  4 +--
 block/qcow2.c             |  4 +--
 block/qed.c               |  2 +-
 block/quorum.c            |  4 +--
 block/vdi.c               |  2 +-
 block/vhdx.c              |  2 +-
 block/vmdk.c              |  4 +--
 block/vpc.c               |  2 +-
 block/vvfat.c             |  2 +-
 blockjob.c                |  3 ++-
 include/block/block.h     |  3 +--
 include/block/block_int.h |  2 --
 18 files changed, 53 insertions(+), 79 deletions(-)
block-migration.c +7 -5
index cb3e16c..da30e93 100644
@@ -14,7 +14,9 @@
  */
 
 #include "qemu-common.h"
-#include "block/block_int.h"
+#include "block/block.h"
+#include "qemu/error-report.h"
+#include "qemu/main-loop.h"
 #include "hw/hw.h"
 #include "qemu/queue.h"
 #include "qemu/timer.h"
@@ -130,9 +132,9 @@ static void blk_send(QEMUFile *f, BlkMigBlock * blk)
                      | flags);
 
     /* device name */
-    len = strlen(blk->bmds->bs->device_name);
+    len = strlen(bdrv_get_device_name(blk->bmds->bs));
     qemu_put_byte(f, len);
-    qemu_put_buffer(f, (uint8_t *)blk->bmds->bs->device_name, len);
+    qemu_put_buffer(f, (uint8_t *)bdrv_get_device_name(blk->bmds->bs), len);
 
     /* if a block is zero we need to flush here since the network
      * bandwidth is now a lot higher than the storage device bandwidth.
@@ -382,9 +384,9 @@ static void init_blk_migration(QEMUFile *f)
 
         if (bmds->shared_base) {
             DPRINTF("Start migration for %s with shared base image\n",
-                    bs->device_name);
+                    bdrv_get_device_name(bs));
         } else {
-            DPRINTF("Start full migration for %s\n", bs->device_name);
+            DPRINTF("Start full migration for %s\n", bdrv_get_device_name(bs));
         }
 
         QSIMPLEQ_INSERT_TAIL(&block_mig_state.bmds_list, bmds, entry);
block.c +9 -40
index 593d89b..61ea15d 100644
@@ -332,31 +332,6 @@ void bdrv_register(BlockDriver *bdrv)
     QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
 }
 
-/* create a new block device (by default it is empty) */
-BlockDriverState *bdrv_new_named(const char *device_name, Error **errp)
-{
-    BlockDriverState *bs;
-
-    assert(*device_name);
-
-    if (bdrv_find(device_name)) {
-        error_setg(errp, "Device with id '%s' already exists",
-                   device_name);
-        return NULL;
-    }
-    if (bdrv_find_node(device_name)) {
-        error_setg(errp, "Device with node-name '%s' already exists",
-                   device_name);
-        return NULL;
-    }
-
-    bs = bdrv_new();
-
-    pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
-
-    return bs;
-}
-
 BlockDriverState *bdrv_new(void)
 {
     BlockDriverState *bs;
@@ -1159,7 +1134,7 @@ void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd)
     } else if (backing_hd) {
         error_setg(&bs->backing_blocker,
                    "device is used as backing hd of '%s'",
-                   bs->device_name);
+                   bdrv_get_device_name(bs));
     }
 
     bs->backing_hd = backing_hd;
@@ -1533,7 +1508,7 @@ int bdrv_open(BlockDriverState **pbs, const char *filename,
         } else {
             error_setg(errp, "Block format '%s' used by device '%s' doesn't "
                        "support the option '%s'", drv->format_name,
-                       bs->device_name, entry->key);
+                       bdrv_get_device_name(bs), entry->key);
         }
 
         ret = -EINVAL;
@@ -1740,7 +1715,7 @@ int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
     if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
         reopen_state->flags & BDRV_O_RDWR) {
         error_set(errp, QERR_DEVICE_IS_READ_ONLY,
-                  reopen_state->bs->device_name);
+                  bdrv_get_device_name(reopen_state->bs));
         goto error;
     }
 
@@ -1767,7 +1742,7 @@ int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
         /* It is currently mandatory to have a bdrv_reopen_prepare()
          * handler for each supported drv. */
         error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
-                  drv->format_name, reopen_state->bs->device_name,
+                  drv->format_name, bdrv_get_device_name(reopen_state->bs),
                  "reopening of file");
         ret = -1;
         goto error;
@@ -1955,7 +1930,6 @@ void bdrv_drain_all(void)
    Also, NULL terminate the device_name to prevent double remove */
 void bdrv_make_anon(BlockDriverState *bs)
 {
-    bs->device_name[0] = '\0';
     if (bs->node_name[0] != '\0') {
         QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
     }
@@ -2008,9 +1982,6 @@ static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
     /* job */
     bs_dest->job                = bs_src->job;
 
-    pstrcpy(bs_dest->device_name, sizeof(bs_dest->device_name),
-            bs_src->device_name);
-
     memcpy(bs_dest->op_blockers, bs_src->op_blockers,
            sizeof(bs_dest->op_blockers));
 }
@@ -2023,7 +1994,7 @@ static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
  * This will modify the BlockDriverState fields, and swap contents
  * between bs_new and bs_old. Both bs_new and bs_old are modified.
  *
- * bs_new must be nameless and not attached to a BlockBackend.
+ * bs_new must not be attached to a BlockBackend.
  *
  * This function does not create any image files.
  */
@@ -2042,8 +2013,7 @@ void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old)
         QTAILQ_REMOVE(&graph_bdrv_states, bs_old, node_list);
     }
 
-    /* bs_new must be nameless and shouldn't have anything fancy enabled */
-    assert(bs_new->device_name[0] == '\0');
+    /* bs_new must be unattached and shouldn't have anything fancy enabled */
     assert(!bs_new->blk);
     assert(QLIST_EMPTY(&bs_new->dirty_bitmaps));
     assert(bs_new->job == NULL);
@@ -2060,8 +2030,7 @@ void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old)
     bdrv_move_feature_fields(bs_old, bs_new);
     bdrv_move_feature_fields(bs_new, &tmp);
 
-    /* bs_new must remain nameless and unattached */
-    assert(bs_new->device_name[0] == '\0');
+    /* bs_new must remain unattached */
     assert(!bs_new->blk);
 
     /* Check a few fields that should remain attached to the device */
@@ -2089,7 +2058,7 @@ void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old)
  * This will modify the BlockDriverState fields, and swap contents
  * between bs_new and bs_top. Both bs_new and bs_top are modified.
  *
- * bs_new must be nameless and not attached to a BlockBackend.
+ * bs_new must not be attached to a BlockBackend.
  *
  * This function does not create any image files.
  */
@@ -3799,7 +3768,7 @@ BlockDriverState *bdrv_find(const char *name)
     BlockDriverState *bs;
 
     for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
-        if (!strcmp(name, bs->device_name)) {
+        if (!strcmp(name, bdrv_get_device_name(bs))) {
             return bs;
         }
     }

block.c BlockDriverState *bdrv_next(BlockDriverState *bs) · line 3865

Quoted 10 lines
block.c +3 -2
@@ -3889,9 +3858,10 @@ BlockDriverState *bdrv_next(BlockDriverState *bs)
     return blk ? blk_bs(blk) : NULL;
 }
 
-const char *bdrv_get_device_name(BlockDriverState *bs)
+const char *bdrv_get_device_name(const BlockDriverState *bs)
 {
-    return bs->device_name;
+    const char *name = bs->blk ? blk_name(bs->blk) : NULL;
+    return name ?: "";
 }

Why not ?

    return bs->blk ? blk_name(bs->blk) : "";

or

    if (bs->blk) {
        return blk_name(bs->blk);
    }

    return "";

Would it fail to do the job ?

Also we could have made sure that bdrv_get_device_name return either a non empty string or NULL.

(We know blk_name will return a non empty string it's asserted)

This would need to change a few test all around the code but the final code logic would be less convoluted:
-convert NULL to "" then test for not ""
would turn into
-return NULL test for not NULL

Quoted 35 lines
block.c +5 -3
 int bdrv_get_flags(BlockDriverState *bs)
@@ -5253,13 +5223,15 @@ int bdrv_media_changed(BlockDriverState *bs)
 void bdrv_eject(BlockDriverState *bs, bool eject_flag)
 {
     BlockDriver *drv = bs->drv;
+    const char *device_name;
 
     if (drv && drv->bdrv_eject) {
         drv->bdrv_eject(bs, eject_flag);
     }
 
-    if (bs->device_name[0] != '\0') {
-        qapi_event_send_device_tray_moved(bdrv_get_device_name(bs),
 
+    device_name = bdrv_get_device_name(bs);
+        qapi_event_send_device_tray_moved(device_name,
                                           eject_flag, &error_abort);
     }
 }
@@ -5469,7 +5441,8 @@ bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
         blocker = QLIST_FIRST(&bs->op_blockers[op]);
         if (errp) {
             error_setg(errp, "Device '%s' is busy: %s",
-                       bs->device_name, error_get_pretty(blocker->reason));
+                       bdrv_get_device_name(bs),
+                       error_get_pretty(blocker->reason));
         }
         return true;
     }
block/block-backend.c +0 -0
index c0876fa..2f10d6a 100644

block/block-backend.c BlockBackend *blk_new_with_bs(const char *name, Error **errp) · line 71

Quoted 5 lines
block/block-backend.c +2 -0
@@ -67,17 +67,17 @@ BlockBackend *blk_new_with_bs(const char *name, Error **errp)
     BlockBackend *blk;
     BlockDriverState *bs;
 
+    if (bdrv_find_node(name)) {
+        error_setg(errp, "Device with node-name '%s' already exists", name);

Maybe the message written by the person who contributed the initial code (me) mislead you. I think the intent is good but the wording is wrong.
node-name is associated with a regular BDS. A device cannot have a node name.

Maybe something in the vein of:

        error_setg(errp, "Device name '%s' would conflict with the node-name of an existing block driver state", name);
Quoted 261 lines
block/block-backend.c +4 -6
+        return NULL;
+    }
+
     blk = blk_new(name, errp);
     if (!blk) {
         return NULL;
     }
 
-    bs = bdrv_new_named(name, errp);
-    if (!bs) {
-        blk_unref(blk);
-        return NULL;
-    }
-
+    bs = bdrv_new();
     blk_attach_bs(blk, bs);
     return blk;
 }
block/cow.c +1 -1
index 6ee4833..dda1e17 100644
@@ -84,7 +84,7 @@ static int cow_open(BlockDriverState *bs, QDict *options, int flags,
         snprintf(version, sizeof(version),
                "COW version %" PRIu32, cow_header.version);
         error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
-            bs->device_name, "cow", version);
+            bdrv_get_device_name(bs), "cow", version);
         ret = -ENOTSUP;
         goto fail;
     }
block/mirror.c +2 -1
index 18b18e0..829be2f 100644
@@ -567,7 +567,8 @@ static void mirror_complete(BlockJob *job, Error **errp)
         return;
     }
     if (!s->synced) {
-        error_set(errp, QERR_BLOCK_JOB_NOT_READY, job->bs->device_name);
+        error_set(errp, QERR_BLOCK_JOB_NOT_READY,
+                  bdrv_get_device_name(job->bs));
         return;
     }
 
block/qapi.c +3 -3
index 79d1e6a..cc8f711 100644
@@ -272,7 +272,7 @@ void bdrv_query_info(BlockDriverState *bs,
     BlockDriverState *bs0;
     ImageInfo **p_image_info;
     Error *local_err = NULL;
-    info->device = g_strdup(bs->device_name);
+    info->device = g_strdup(bdrv_get_device_name(bs));
     info->type = g_strdup("unknown");
     info->locked = bdrv_dev_is_medium_locked(bs);
     info->removable = bdrv_dev_has_removable_media(bs);
@@ -327,9 +327,9 @@ static BlockStats *bdrv_query_stats(const BlockDriverState *bs)
 
     s = g_malloc0(sizeof(*s));
 
-    if (bs->device_name[0]) {
+    if (bdrv_get_device_name(bs)[0]) {
         s->has_device = true;
-        s->device = g_strdup(bs->device_name);
+        s->device = g_strdup(bdrv_get_device_name(bs));
     }
 
     s->stats = g_malloc0(sizeof(*s->stats));
block/qcow.c +2 -2
index 67c237f..2d803ac 100644
@@ -124,7 +124,7 @@ static int qcow_open(BlockDriverState *bs, QDict *options, int flags,
         snprintf(version, sizeof(version), "QCOW version %" PRIu32,
                  header.version);
         error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
-                  bs->device_name, "qcow", version);
+                  bdrv_get_device_name(bs), "qcow", version);
         ret = -ENOTSUP;
         goto fail;
     }
@@ -231,7 +231,7 @@ static int qcow_open(BlockDriverState *bs, QDict *options, int flags,
     /* Disable migration when qcow images are used */
     error_set(&s->migration_blocker,
               QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
-              "qcow", bs->device_name, "live migration");
+              "qcow", bdrv_get_device_name(bs), "live migration");
     migrate_add_blocker(s->migration_blocker);
 
     qemu_co_mutex_init(&s->lock);
block/qcow2.c +2 -2
index f9e045f..0ab455e 100644
@@ -203,8 +203,8 @@ static void GCC_FMT_ATTR(3, 4) report_unsupported(BlockDriverState *bs,
     vsnprintf(msg, sizeof(msg), fmt, ap);
     va_end(ap);
 
-    error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE, bs->device_name, "qcow2",
-              msg);
+    error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
+              bdrv_get_device_name(bs), "qcow2", msg);
 }
 
 static void report_unsupported_feature(BlockDriverState *bs,
block/qed.c +1 -1
index ba395af..f20ffb3 100644
@@ -422,7 +422,7 @@ static int bdrv_qed_open(BlockDriverState *bs, QDict *options, int flags,
         snprintf(buf, sizeof(buf), "%" PRIx64,
             s->header.features & ~QED_FEATURE_MASK);
         error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
-            bs->device_name, "QED", buf);
+            bdrv_get_device_name(bs), "QED", buf);
         return -ENOTSUP;
     }
     if (!qed_is_cluster_size_valid(s->header.cluster_size)) {
block/quorum.c +2 -2
index 093382e..f958269 100644
@@ -227,8 +227,8 @@ static void quorum_report_bad(QuorumAIOCB *acb, char *node_name, int ret)
 
 static void quorum_report_failure(QuorumAIOCB *acb)
 {
-    const char *reference = acb->common.bs->device_name[0] ?
-                            acb->common.bs->device_name :
+    const char *reference = bdrv_get_device_name(acb->common.bs)[0] ?
+                            bdrv_get_device_name(acb->common.bs) :
                             acb->common.bs->node_name;
 
     qapi_event_send_quorum_failure(reference, acb->sector_num,
block/vdi.c +1 -1
index 4b10aac..2e6f31c 100644
@@ -490,7 +490,7 @@ static int vdi_open(BlockDriverState *bs, QDict *options, int flags,
     /* Disable migration when vdi images are used */
     error_set(&s->migration_blocker,
               QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
-              "vdi", bs->device_name, "live migration");
+              "vdi", bdrv_get_device_name(bs), "live migration");
     migrate_add_blocker(s->migration_blocker);
 
     return 0;
block/vhdx.c +1 -1
index 87c99fc..8bf1af1 100644
@@ -1003,7 +1003,7 @@ static int vhdx_open(BlockDriverState *bs, QDict *options, int flags,
     /* Disable migration when VHDX images are used */
     error_set(&s->migration_blocker,
             QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
-            "vhdx", bs->device_name, "live migration");
+            "vhdx", bdrv_get_device_name(bs), "live migration");
     migrate_add_blocker(s->migration_blocker);
 
     return 0;
block/vmdk.c +2 -2
index a1cb911..7bc1474 100644
@@ -657,7 +657,7 @@ static int vmdk_open_vmdk4(BlockDriverState *bs,
         snprintf(buf, sizeof(buf), "VMDK version %" PRId32,
                  le32_to_cpu(header.version));
         error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
-                  bs->device_name, "vmdk", buf);
+                  bdrv_get_device_name(bs), "vmdk", buf);
         return -ENOTSUP;
     } else if (le32_to_cpu(header.version) == 3 && (flags & BDRV_O_RDWR)) {
         /* VMware KB 2064959 explains that version 3 added support for
@@ -939,7 +939,7 @@ static int vmdk_open(BlockDriverState *bs, QDict *options, int flags,
     /* Disable migration when VMDK images are used */
     error_set(&s->migration_blocker,
               QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
-              "vmdk", bs->device_name, "live migration");
+              "vmdk", bdrv_get_device_name(bs), "live migration");
     migrate_add_blocker(s->migration_blocker);
     g_free(buf);
     return 0;
block/vpc.c +1 -1
index 055efc4..7bb90d5 100644
@@ -320,7 +320,7 @@ static int vpc_open(BlockDriverState *bs, QDict *options, int flags,
     /* Disable migration when VHD images are used */
     error_set(&s->migration_blocker,
               QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
-              "vpc", bs->device_name, "live migration");
+              "vpc", bdrv_get_device_name(bs), "live migration");
     migrate_add_blocker(s->migration_blocker);
 
     return 0;
block/vvfat.c +1 -1
index 6c9fde0..cefe3a4 100644
@@ -1182,7 +1182,7 @@ static int vvfat_open(BlockDriverState *bs, QDict *options, int flags,
     if (s->qcow) {
         error_set(&s->migration_blocker,
                   QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
-                  "vvfat (rw)", bs->device_name, "live migration");
+                  "vvfat (rw)", bdrv_get_device_name(bs), "live migration");
         migrate_add_blocker(s->migration_blocker);
     }
 
blockjob.c +2 -1
index 0689fdd..3af0f6c 100644
@@ -107,7 +107,8 @@ void block_job_set_speed(BlockJob *job, int64_t speed, Error **errp)
 void block_job_complete(BlockJob *job, Error **errp)
 {
     if (job->paused || job->cancelled || !job->driver->complete) {
-        error_set(errp, QERR_BLOCK_JOB_NOT_READY, job->bs->device_name);
+        error_set(errp, QERR_BLOCK_JOB_NOT_READY,
+                  bdrv_get_device_name(job->bs));
         return;
     }
 
include/block/block.h +1 -2
index 8cf9ea3..fb4fff9 100644
@@ -203,7 +203,6 @@ BlockDriver *bdrv_find_whitelisted_format(const char *format_name,
 int bdrv_create(BlockDriver *drv, const char* filename,
                 QemuOpts *opts, Error **errp);
 int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp);
-BlockDriverState *bdrv_new_named(const char *device_name, Error **errp);
 BlockDriverState *bdrv_new(void);
 void bdrv_make_anon(BlockDriverState *bs);
 void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old);
@@ -415,7 +414,7 @@ int bdrv_set_key(BlockDriverState *bs, const char *key);
 int bdrv_query_missing_keys(void);
 void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
                          void *opaque);
-const char *bdrv_get_device_name(BlockDriverState *bs);
+const char *bdrv_get_device_name(const BlockDriverState *bs);
 int bdrv_get_flags(BlockDriverState *bs);
 int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
                           const uint8_t *buf, int nb_sectors);
include/block/block_int.h +0 -2
index d5de08b..08ccb27 100644
@@ -394,8 +394,6 @@ struct BlockDriverState {
     char node_name[32];
     /* element of the list of named nodes building the graph */
     QTAILQ_ENTRY(BlockDriverState) node_list;
-    /* Device name is the name associated with the "drive" the guest sees */
-    char device_name[32];
     QLIST_HEAD(, BdrvDirtyBitmap) dirty_bitmaps;
     int refcnt;
 
Signature · 1 line
1.9.3
#46 lore raw

Re: [Qemu-devel] [PATCH 08/23] block: Eliminate BlockDriverState member device_name[]

Quoted 294 lines · Benoît Canet
Quoted 212 lines · Markus Armbruster

device_name[] is can become non-empty only in bdrv_new_named() and bdrv_move_feature_fields(). The latter is used only to undo damage done by bdrv_swap(). The former is called only by blk_new_with_bs(). Therefore, when a BlockDriverState's device_name[] is non-empty, then it's owned by a BlockBackend.

The converse is also true, because blk_attach_bs() is called only by blk_new_with_bs() so far.

Furthermore, blk_new_with_bs() keeps the two names equal.

Therefore, device_name[] is redundant. Eliminate it.

---
 block-migration.c         | 12 +++++----
 block.c                   | 63 ++++++++++++++---------------------------------
 block/block-backend.c     | 12 ++++-----
 block/cow.c               |  2 +-
 block/mirror.c            |  3 ++-
 block/qapi.c              |  6 ++---
 block/qcow.c              |  4 +--
 block/qcow2.c             |  4 +--
 block/qed.c               |  2 +-
 block/quorum.c            |  4 +--
 block/vdi.c               |  2 +-
 block/vhdx.c              |  2 +-
 block/vmdk.c              |  4 +--
 block/vpc.c               |  2 +-
 block/vvfat.c             |  2 +-
 blockjob.c                |  3 ++-
 include/block/block.h     |  3 +--
 include/block/block_int.h |  2 --
 18 files changed, 53 insertions(+), 79 deletions(-)
block-migration.c +7 -5
index cb3e16c..da30e93 100644
@@ -14,7 +14,9 @@
  */
 
 #include "qemu-common.h"
-#include "block/block_int.h"
+#include "block/block.h"
+#include "qemu/error-report.h"
+#include "qemu/main-loop.h"
 #include "hw/hw.h"
 #include "qemu/queue.h"
 #include "qemu/timer.h"
@@ -130,9 +132,9 @@ static void blk_send(QEMUFile *f, BlkMigBlock * blk)
                      | flags);
 
     /* device name */
-    len = strlen(blk->bmds->bs->device_name);
+    len = strlen(bdrv_get_device_name(blk->bmds->bs));
     qemu_put_byte(f, len);
-    qemu_put_buffer(f, (uint8_t *)blk->bmds->bs->device_name, len);
+    qemu_put_buffer(f, (uint8_t *)bdrv_get_device_name(blk->bmds->bs), len);
 
     /* if a block is zero we need to flush here since the network
      * bandwidth is now a lot higher than the storage device bandwidth.
@@ -382,9 +384,9 @@ static void init_blk_migration(QEMUFile *f)
 
         if (bmds->shared_base) {
             DPRINTF("Start migration for %s with shared base image\n",
-                    bs->device_name);
+                    bdrv_get_device_name(bs));
         } else {
-            DPRINTF("Start full migration for %s\n", bs->device_name);
+            DPRINTF("Start full migration for %s\n", bdrv_get_device_name(bs));
         }
 
         QSIMPLEQ_INSERT_TAIL(&block_mig_state.bmds_list, bmds, entry);
block.c +9 -40
index 593d89b..61ea15d 100644
@@ -332,31 +332,6 @@ void bdrv_register(BlockDriver *bdrv)
     QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
 }
 
-/* create a new block device (by default it is empty) */
-BlockDriverState *bdrv_new_named(const char *device_name, Error **errp)
-{
-    BlockDriverState *bs;
-
-    assert(*device_name);
-
-    if (bdrv_find(device_name)) {
-        error_setg(errp, "Device with id '%s' already exists",
-                   device_name);
-        return NULL;
-    }
-    if (bdrv_find_node(device_name)) {
-        error_setg(errp, "Device with node-name '%s' already exists",
-                   device_name);
-        return NULL;
-    }
-
-    bs = bdrv_new();
-
-    pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
-
-    return bs;
-}
-
 BlockDriverState *bdrv_new(void)
 {
     BlockDriverState *bs;
@@ -1159,7 +1134,7 @@ void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd)
     } else if (backing_hd) {
         error_setg(&bs->backing_blocker,
                    "device is used as backing hd of '%s'",
-                   bs->device_name);
+                   bdrv_get_device_name(bs));
     }
 
     bs->backing_hd = backing_hd;
@@ -1533,7 +1508,7 @@ int bdrv_open(BlockDriverState **pbs, const char *filename,
         } else {
             error_setg(errp, "Block format '%s' used by device '%s' doesn't "
                        "support the option '%s'", drv->format_name,
-                       bs->device_name, entry->key);
+                       bdrv_get_device_name(bs), entry->key);
         }
 
         ret = -EINVAL;
@@ -1740,7 +1715,7 @@ int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
     if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
         reopen_state->flags & BDRV_O_RDWR) {
         error_set(errp, QERR_DEVICE_IS_READ_ONLY,
-                  reopen_state->bs->device_name);
+                  bdrv_get_device_name(reopen_state->bs));
         goto error;
     }
 
@@ -1767,7 +1742,7 @@ int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
         /* It is currently mandatory to have a bdrv_reopen_prepare()
          * handler for each supported drv. */
         error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
-                  drv->format_name, reopen_state->bs->device_name,
+                  drv->format_name, bdrv_get_device_name(reopen_state->bs),
                  "reopening of file");
         ret = -1;
         goto error;
@@ -1955,7 +1930,6 @@ void bdrv_drain_all(void)
    Also, NULL terminate the device_name to prevent double remove */
 void bdrv_make_anon(BlockDriverState *bs)
 {
-    bs->device_name[0] = '\0';
     if (bs->node_name[0] != '\0') {
         QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
     }
@@ -2008,9 +1982,6 @@ static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
     /* job */
     bs_dest->job                = bs_src->job;
 
-    pstrcpy(bs_dest->device_name, sizeof(bs_dest->device_name),
-            bs_src->device_name);
-
     memcpy(bs_dest->op_blockers, bs_src->op_blockers,
            sizeof(bs_dest->op_blockers));
 }
@@ -2023,7 +1994,7 @@ static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
  * This will modify the BlockDriverState fields, and swap contents
  * between bs_new and bs_old. Both bs_new and bs_old are modified.
  *
- * bs_new must be nameless and not attached to a BlockBackend.
+ * bs_new must not be attached to a BlockBackend.
  *
  * This function does not create any image files.
  */
@@ -2042,8 +2013,7 @@ void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old)
         QTAILQ_REMOVE(&graph_bdrv_states, bs_old, node_list);
     }
 
-    /* bs_new must be nameless and shouldn't have anything fancy enabled */
-    assert(bs_new->device_name[0] == '\0');
+    /* bs_new must be unattached and shouldn't have anything fancy enabled */
     assert(!bs_new->blk);
     assert(QLIST_EMPTY(&bs_new->dirty_bitmaps));
     assert(bs_new->job == NULL);
@@ -2060,8 +2030,7 @@ void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old)
     bdrv_move_feature_fields(bs_old, bs_new);
     bdrv_move_feature_fields(bs_new, &tmp);
 
-    /* bs_new must remain nameless and unattached */
-    assert(bs_new->device_name[0] == '\0');
+    /* bs_new must remain unattached */
     assert(!bs_new->blk);
 
     /* Check a few fields that should remain attached to the device */
@@ -2089,7 +2058,7 @@ void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old)
  * This will modify the BlockDriverState fields, and swap contents
  * between bs_new and bs_top. Both bs_new and bs_top are modified.
  *
- * bs_new must be nameless and not attached to a BlockBackend.
+ * bs_new must not be attached to a BlockBackend.
  *
  * This function does not create any image files.
  */
@@ -3799,7 +3768,7 @@ BlockDriverState *bdrv_find(const char *name)
     BlockDriverState *bs;
 
     for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
-        if (!strcmp(name, bs->device_name)) {
+        if (!strcmp(name, bdrv_get_device_name(bs))) {
             return bs;
         }
     }

block.c BlockDriverState *bdrv_next(BlockDriverState *bs) · line 3865

Quoted 10 lines
block.c +3 -2
@@ -3889,9 +3858,10 @@ BlockDriverState *bdrv_next(BlockDriverState *bs)
     return blk ? blk_bs(blk) : NULL;
 }
 
-const char *bdrv_get_device_name(BlockDriverState *bs)
+const char *bdrv_get_device_name(const BlockDriverState *bs)
 {
-    return bs->device_name;
+    const char *name = bs->blk ? blk_name(bs->blk) : NULL;
+    return name ?: "";
 }

Why not ?

    return bs->blk ? blk_name(bs->blk) : "";

or

    if (bs->blk) {
        return blk_name(bs->blk);
    }

    return "";

Would it fail to do the job ?

Also we could have made sure that bdrv_get_device_name return either a non empty string or NULL.

(We know blk_name will return a non empty string it's asserted)

This would need to change a few test all around the code but the final code logic would be less convoluted:
-convert NULL to "" then test for not ""
would turn into
-return NULL test for not NULL

Quoted 35 lines
block.c +5 -3
 int bdrv_get_flags(BlockDriverState *bs)
@@ -5253,13 +5223,15 @@ int bdrv_media_changed(BlockDriverState *bs)
 void bdrv_eject(BlockDriverState *bs, bool eject_flag)
 {
     BlockDriver *drv = bs->drv;
+    const char *device_name;
 
     if (drv && drv->bdrv_eject) {
         drv->bdrv_eject(bs, eject_flag);
     }
 
-    if (bs->device_name[0] != '\0') {
-        qapi_event_send_device_tray_moved(bdrv_get_device_name(bs),
 
+    device_name = bdrv_get_device_name(bs);
+        qapi_event_send_device_tray_moved(device_name,
                                           eject_flag, &error_abort);
     }
 }
@@ -5469,7 +5441,8 @@ bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
         blocker = QLIST_FIRST(&bs->op_blockers[op]);
         if (errp) {
             error_setg(errp, "Device '%s' is busy: %s",
-                       bs->device_name, error_get_pretty(blocker->reason));
+                       bdrv_get_device_name(bs),
+                       error_get_pretty(blocker->reason));
         }
         return true;
     }
block/block-backend.c +0 -0
index c0876fa..2f10d6a 100644

block/block-backend.c BlockBackend *blk_new_with_bs(const char *name, Error **errp) · line 71

Quoted 5 lines
block/block-backend.c +2 -0
@@ -67,17 +67,17 @@ BlockBackend *blk_new_with_bs(const char *name, Error **errp)
     BlockBackend *blk;
     BlockDriverState *bs;
 
+    if (bdrv_find_node(name)) {
+        error_setg(errp, "Device with node-name '%s' already exists", name);

Maybe the message written by the person who contributed the initial code (me) mislead you. I think the intent is good but the wording is wrong.
node-name is associated with a regular BDS. A device cannot have a node name.

Quoted 6 lines

Maybe something in the vein of:

        error_setg(errp, "Device name '%s' would conflict with the node-name of an existing block driver state", name);
Quoted 3 lines
block/block-backend.c +3 -0
+        return NULL;
+    }
+

I re read the patch and saw you just moved it around. Maybe a followup patch fixing the message would be a good idea.

Quoted 259 lines
Quoted 258 lines
block/block-backend.c +1 -6
     blk = blk_new(name, errp);
     if (!blk) {
         return NULL;
     }
 
-    bs = bdrv_new_named(name, errp);
-    if (!bs) {
-        blk_unref(blk);
-        return NULL;
-    }
-
+    bs = bdrv_new();
     blk_attach_bs(blk, bs);
     return blk;
 }
block/cow.c +1 -1
index 6ee4833..dda1e17 100644
@@ -84,7 +84,7 @@ static int cow_open(BlockDriverState *bs, QDict *options, int flags,
         snprintf(version, sizeof(version),
                "COW version %" PRIu32, cow_header.version);
         error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
-            bs->device_name, "cow", version);
+            bdrv_get_device_name(bs), "cow", version);
         ret = -ENOTSUP;
         goto fail;
     }
block/mirror.c +2 -1
index 18b18e0..829be2f 100644
@@ -567,7 +567,8 @@ static void mirror_complete(BlockJob *job, Error **errp)
         return;
     }
     if (!s->synced) {
-        error_set(errp, QERR_BLOCK_JOB_NOT_READY, job->bs->device_name);
+        error_set(errp, QERR_BLOCK_JOB_NOT_READY,
+                  bdrv_get_device_name(job->bs));
         return;
     }
 
block/qapi.c +3 -3
index 79d1e6a..cc8f711 100644
@@ -272,7 +272,7 @@ void bdrv_query_info(BlockDriverState *bs,
     BlockDriverState *bs0;
     ImageInfo **p_image_info;
     Error *local_err = NULL;
-    info->device = g_strdup(bs->device_name);
+    info->device = g_strdup(bdrv_get_device_name(bs));
     info->type = g_strdup("unknown");
     info->locked = bdrv_dev_is_medium_locked(bs);
     info->removable = bdrv_dev_has_removable_media(bs);
@@ -327,9 +327,9 @@ static BlockStats *bdrv_query_stats(const BlockDriverState *bs)
 
     s = g_malloc0(sizeof(*s));
 
-    if (bs->device_name[0]) {
+    if (bdrv_get_device_name(bs)[0]) {
         s->has_device = true;
-        s->device = g_strdup(bs->device_name);
+        s->device = g_strdup(bdrv_get_device_name(bs));
     }
 
     s->stats = g_malloc0(sizeof(*s->stats));
block/qcow.c +2 -2
index 67c237f..2d803ac 100644
@@ -124,7 +124,7 @@ static int qcow_open(BlockDriverState *bs, QDict *options, int flags,
         snprintf(version, sizeof(version), "QCOW version %" PRIu32,
                  header.version);
         error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
-                  bs->device_name, "qcow", version);
+                  bdrv_get_device_name(bs), "qcow", version);
         ret = -ENOTSUP;
         goto fail;
     }
@@ -231,7 +231,7 @@ static int qcow_open(BlockDriverState *bs, QDict *options, int flags,
     /* Disable migration when qcow images are used */
     error_set(&s->migration_blocker,
               QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
-              "qcow", bs->device_name, "live migration");
+              "qcow", bdrv_get_device_name(bs), "live migration");
     migrate_add_blocker(s->migration_blocker);
 
     qemu_co_mutex_init(&s->lock);
block/qcow2.c +2 -2
index f9e045f..0ab455e 100644
@@ -203,8 +203,8 @@ static void GCC_FMT_ATTR(3, 4) report_unsupported(BlockDriverState *bs,
     vsnprintf(msg, sizeof(msg), fmt, ap);
     va_end(ap);
 
-    error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE, bs->device_name, "qcow2",
-              msg);
+    error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
+              bdrv_get_device_name(bs), "qcow2", msg);
 }
 
 static void report_unsupported_feature(BlockDriverState *bs,
block/qed.c +1 -1
index ba395af..f20ffb3 100644
@@ -422,7 +422,7 @@ static int bdrv_qed_open(BlockDriverState *bs, QDict *options, int flags,
         snprintf(buf, sizeof(buf), "%" PRIx64,
             s->header.features & ~QED_FEATURE_MASK);
         error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
-            bs->device_name, "QED", buf);
+            bdrv_get_device_name(bs), "QED", buf);
         return -ENOTSUP;
     }
     if (!qed_is_cluster_size_valid(s->header.cluster_size)) {
block/quorum.c +2 -2
index 093382e..f958269 100644
@@ -227,8 +227,8 @@ static void quorum_report_bad(QuorumAIOCB *acb, char *node_name, int ret)
 
 static void quorum_report_failure(QuorumAIOCB *acb)
 {
-    const char *reference = acb->common.bs->device_name[0] ?
-                            acb->common.bs->device_name :
+    const char *reference = bdrv_get_device_name(acb->common.bs)[0] ?
+                            bdrv_get_device_name(acb->common.bs) :
                             acb->common.bs->node_name;
 
     qapi_event_send_quorum_failure(reference, acb->sector_num,
block/vdi.c +1 -1
index 4b10aac..2e6f31c 100644
@@ -490,7 +490,7 @@ static int vdi_open(BlockDriverState *bs, QDict *options, int flags,
     /* Disable migration when vdi images are used */
     error_set(&s->migration_blocker,
               QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
-              "vdi", bs->device_name, "live migration");
+              "vdi", bdrv_get_device_name(bs), "live migration");
     migrate_add_blocker(s->migration_blocker);
 
     return 0;
block/vhdx.c +1 -1
index 87c99fc..8bf1af1 100644
@@ -1003,7 +1003,7 @@ static int vhdx_open(BlockDriverState *bs, QDict *options, int flags,
     /* Disable migration when VHDX images are used */
     error_set(&s->migration_blocker,
             QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
-            "vhdx", bs->device_name, "live migration");
+            "vhdx", bdrv_get_device_name(bs), "live migration");
     migrate_add_blocker(s->migration_blocker);
 
     return 0;
block/vmdk.c +2 -2
index a1cb911..7bc1474 100644
@@ -657,7 +657,7 @@ static int vmdk_open_vmdk4(BlockDriverState *bs,
         snprintf(buf, sizeof(buf), "VMDK version %" PRId32,
                  le32_to_cpu(header.version));
         error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
-                  bs->device_name, "vmdk", buf);
+                  bdrv_get_device_name(bs), "vmdk", buf);
         return -ENOTSUP;
     } else if (le32_to_cpu(header.version) == 3 && (flags & BDRV_O_RDWR)) {
         /* VMware KB 2064959 explains that version 3 added support for
@@ -939,7 +939,7 @@ static int vmdk_open(BlockDriverState *bs, QDict *options, int flags,
     /* Disable migration when VMDK images are used */
     error_set(&s->migration_blocker,
               QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
-              "vmdk", bs->device_name, "live migration");
+              "vmdk", bdrv_get_device_name(bs), "live migration");
     migrate_add_blocker(s->migration_blocker);
     g_free(buf);
     return 0;
block/vpc.c +1 -1
index 055efc4..7bb90d5 100644
@@ -320,7 +320,7 @@ static int vpc_open(BlockDriverState *bs, QDict *options, int flags,
     /* Disable migration when VHD images are used */
     error_set(&s->migration_blocker,
               QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
-              "vpc", bs->device_name, "live migration");
+              "vpc", bdrv_get_device_name(bs), "live migration");
     migrate_add_blocker(s->migration_blocker);
 
     return 0;
block/vvfat.c +1 -1
index 6c9fde0..cefe3a4 100644
@@ -1182,7 +1182,7 @@ static int vvfat_open(BlockDriverState *bs, QDict *options, int flags,
     if (s->qcow) {
         error_set(&s->migration_blocker,
                   QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
-                  "vvfat (rw)", bs->device_name, "live migration");
+                  "vvfat (rw)", bdrv_get_device_name(bs), "live migration");
         migrate_add_blocker(s->migration_blocker);
     }
 
blockjob.c +2 -1
index 0689fdd..3af0f6c 100644
@@ -107,7 +107,8 @@ void block_job_set_speed(BlockJob *job, int64_t speed, Error **errp)
 void block_job_complete(BlockJob *job, Error **errp)
 {
     if (job->paused || job->cancelled || !job->driver->complete) {
-        error_set(errp, QERR_BLOCK_JOB_NOT_READY, job->bs->device_name);
+        error_set(errp, QERR_BLOCK_JOB_NOT_READY,
+                  bdrv_get_device_name(job->bs));
         return;
     }
 
include/block/block.h +1 -2
index 8cf9ea3..fb4fff9 100644
@@ -203,7 +203,6 @@ BlockDriver *bdrv_find_whitelisted_format(const char *format_name,
 int bdrv_create(BlockDriver *drv, const char* filename,
                 QemuOpts *opts, Error **errp);
 int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp);
-BlockDriverState *bdrv_new_named(const char *device_name, Error **errp);
 BlockDriverState *bdrv_new(void);
 void bdrv_make_anon(BlockDriverState *bs);
 void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old);
@@ -415,7 +414,7 @@ int bdrv_set_key(BlockDriverState *bs, const char *key);
 int bdrv_query_missing_keys(void);
 void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
                          void *opaque);
-const char *bdrv_get_device_name(BlockDriverState *bs);
+const char *bdrv_get_device_name(const BlockDriverState *bs);
 int bdrv_get_flags(BlockDriverState *bs);
 int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
                           const uint8_t *buf, int nb_sectors);
include/block/block_int.h +0 -2
index d5de08b..08ccb27 100644
@@ -394,8 +394,6 @@ struct BlockDriverState {
     char node_name[32];
     /* element of the list of named nodes building the graph */
     QTAILQ_ENTRY(BlockDriverState) node_list;
-    /* Device name is the name associated with the "drive" the guest sees */
-    char device_name[32];
     QLIST_HEAD(, BdrvDirtyBitmap) dirty_bitmaps;
     int refcnt;
 
Signature · 1 line
1.9.3
#47 lore raw

Re: [Qemu-devel] [PATCH 08/23] block: Eliminate BlockDriverState member device_name[]

In reply to Benoît Canet
Quoted 6 lines · Benoît Canet
Quoted 5 lines · Markus Armbruster

device_name[] is can become non-empty only in bdrv_new_named() and bdrv_move_feature_fields(). The latter is used only to undo damage done by bdrv_swap(). The former is called only by blk_new_with_bs(). Therefore, when a BlockDriverState's device_name[] is non-empty, then it's owned by a BlockBackend.

[lots of lines trimmed - it's not only okay, but desirable to trim out portions of a patch that you are okay with, in order to call attention to the problem spots that you are commenting on without making the reader have to scroll through pages of quoted context]

Quoted 11 lines

block.c BlockDriverState *bdrv_next(BlockDriverState *bs) · line 3865

Quoted 8 lines
block.c +3 -2
-const char *bdrv_get_device_name(BlockDriverState *bs)
+const char *bdrv_get_device_name(const BlockDriverState *bs)
 {
-    return bs->device_name;
+    const char *name = bs->blk ? blk_name(bs->blk) : NULL;
+    return name ?: "";
 }

Why not ?

Quoted 1 line
    return bs->blk ? blk_name(bs->blk) : "";

If I understand right, it was because blk_name(bs->blk) may return NULL, but this function is guaranteed to return non-NULL.

Quoted 14 lines

or

    if (bs->blk) {
        return blk_name(bs->blk);
    }

    return "";

Would it fail to do the job ?

Also we could have made sure that bdrv_get_device_name return either a non empty string or NULL.

Quoted 7 lines

(We know blk_name will return a non empty string it's asserted)

This would need to change a few test all around the code but the final code logic would be less convoluted:
-convert NULL to "" then test for not ""
would turn into
-return NULL test for not NULL

Indeed, the logic of NULL vs. string is slightly easier than the logic of "" vs non-empty string; if we can guarantee that a non-NULL string will be non-empty. I'm not sure how much churn it would cause, though.

Signature · 2 lines
Eric Blake   eblake redhat com    +1-919-301-3266
Libvirt virtualization library http://libvirt.org
#48 lore raw

Re: [Qemu-devel] [PATCH 08/23] block: Eliminate BlockDriverState member device_name[]

Quoted 24 lines · Eric Blake
Quoted 6 lines · Benoît Canet
Quoted 5 lines · Markus Armbruster

device_name[] is can become non-empty only in bdrv_new_named() and bdrv_move_feature_fields(). The latter is used only to undo damage done by bdrv_swap(). The former is called only by blk_new_with_bs(). Therefore, when a BlockDriverState's device_name[] is non-empty, then it's owned by a BlockBackend.

[lots of lines trimmed - it's not only okay, but desirable to trim out portions of a patch that you are okay with, in order to call attention to the problem spots that you are commenting on without making the reader have to scroll through pages of quoted context]

Quoted 11 lines

block.c BlockDriverState *bdrv_next(BlockDriverState *bs) · line 3865

Quoted 8 lines
block.c +3 -2
-const char *bdrv_get_device_name(BlockDriverState *bs)
+const char *bdrv_get_device_name(const BlockDriverState *bs)
 {
-    return bs->device_name;
+    const char *name = bs->blk ? blk_name(bs->blk) : NULL;
+    return name ?: "";
 }

Why not ?

Quoted 3 lines
Quoted 1 line
    return bs->blk ? blk_name(bs->blk) : "";

If I understand right, it was because blk_name(bs->blk) may return NULL,

It think it can't: see patch 2 extract:

Quoted 7 lines
(quoted diff) +5 -0
+BlockBackend *blk_new(const char *name, Error **errp)
+{
+    BlockBackend *blk = g_new0(BlockBackend, 1);
+     
+    assert(name && name[0]);

but this function is guaranteed to return non-NULL.

#49 lore raw

Re: [Qemu-devel] [PATCH 08/23] block: Eliminate BlockDriverState member device_name[]

Quoted 25 lines · Benoît Canet
Quoted 24 lines · Eric Blake
Quoted 6 lines · Benoît Canet
Quoted 5 lines · Markus Armbruster

device_name[] is can become non-empty only in bdrv_new_named() and bdrv_move_feature_fields(). The latter is used only to undo damage done by bdrv_swap(). The former is called only by blk_new_with_bs(). Therefore, when a BlockDriverState's device_name[] is non-empty, then it's owned by a BlockBackend.

[lots of lines trimmed - it's not only okay, but desirable to trim out portions of a patch that you are okay with, in order to call attention to the problem spots that you are commenting on without making the reader have to scroll through pages of quoted context]

Quoted 11 lines

block.c BlockDriverState *bdrv_next(BlockDriverState *bs) · line 3865

Quoted 8 lines
block.c +3 -2
-const char *bdrv_get_device_name(BlockDriverState *bs)
+const char *bdrv_get_device_name(const BlockDriverState *bs)
 {
-    return bs->device_name;
+    const char *name = bs->blk ? blk_name(bs->blk) : NULL;
+    return name ?: "";
 }

Why not ?

Quoted 13 lines
Quoted 3 lines
Quoted 1 line
    return bs->blk ? blk_name(bs->blk) : "";

If I understand right, it was because blk_name(bs->blk) may return NULL,

It think it can't: see patch 2 extract:

Quoted 7 lines
(quoted diff) +5 -0
+BlockBackend *blk_new(const char *name, Error **errp)
+{
+    BlockBackend *blk = g_new0(BlockBackend, 1);
+     
+    assert(name && name[0]);

but this function is guaranteed to return non-NULL.

You're right, blk_new() always returns a non-null, non-empty string.

The condition to check here is "bs is not owned by a BB". Benoît's

    bs->blk ? blk_name(bs->blk) : ""

does that nicely.

Of course, Eric is right in that returning NULL on "not owned by a BB" would be cleaner than returning "". However, doing that in the middle of a series with a four-digit diffstat doesn't strike me as a good idea. Better do it on top.

#50 lore raw

Re: [Qemu-devel] [PATCH 08/23] block: Eliminate BlockDriverState member device_name[]

In reply to Benoît Canet
Quoted 226 lines · Benoît Canet
Quoted 212 lines · Markus Armbruster

device_name[] is can become non-empty only in bdrv_new_named() and bdrv_move_feature_fields(). The latter is used only to undo damage done by bdrv_swap(). The former is called only by blk_new_with_bs(). Therefore, when a BlockDriverState's device_name[] is non-empty, then it's owned by a BlockBackend.

The converse is also true, because blk_attach_bs() is called only by blk_new_with_bs() so far.

Furthermore, blk_new_with_bs() keeps the two names equal.

Therefore, device_name[] is redundant. Eliminate it.

---
 block-migration.c         | 12 +++++----
 block.c                   | 63 ++++++++++++++---------------------------------
 block/block-backend.c     | 12 ++++-----
 block/cow.c               |  2 +-
 block/mirror.c            |  3 ++-
 block/qapi.c              |  6 ++---
 block/qcow.c              |  4 +--
 block/qcow2.c             |  4 +--
 block/qed.c               |  2 +-
 block/quorum.c            |  4 +--
 block/vdi.c               |  2 +-
 block/vhdx.c              |  2 +-
 block/vmdk.c              |  4 +--
 block/vpc.c               |  2 +-
 block/vvfat.c             |  2 +-
 blockjob.c                |  3 ++-
 include/block/block.h     |  3 +--
 include/block/block_int.h |  2 --
 18 files changed, 53 insertions(+), 79 deletions(-)
block-migration.c +7 -5
index cb3e16c..da30e93 100644
@@ -14,7 +14,9 @@
  */
 
 #include "qemu-common.h"
-#include "block/block_int.h"
+#include "block/block.h"
+#include "qemu/error-report.h"
+#include "qemu/main-loop.h"
 #include "hw/hw.h"
 #include "qemu/queue.h"
 #include "qemu/timer.h"
@@ -130,9 +132,9 @@ static void blk_send(QEMUFile *f, BlkMigBlock * blk)
                      | flags);
 
     /* device name */
-    len = strlen(blk->bmds->bs->device_name);
+    len = strlen(bdrv_get_device_name(blk->bmds->bs));
     qemu_put_byte(f, len);
-    qemu_put_buffer(f, (uint8_t *)blk->bmds->bs->device_name, len);
+    qemu_put_buffer(f, (uint8_t *)bdrv_get_device_name(blk->bmds->bs), len);
 
     /* if a block is zero we need to flush here since the network
      * bandwidth is now a lot higher than the storage device bandwidth.
@@ -382,9 +384,9 @@ static void init_blk_migration(QEMUFile *f)
 
         if (bmds->shared_base) {
             DPRINTF("Start migration for %s with shared base image\n",
-                    bs->device_name);
+                    bdrv_get_device_name(bs));
         } else {
-            DPRINTF("Start full migration for %s\n", bs->device_name);
+            DPRINTF("Start full migration for %s\n", bdrv_get_device_name(bs));
         }
 
         QSIMPLEQ_INSERT_TAIL(&block_mig_state.bmds_list, bmds, entry);
block.c +9 -40
index 593d89b..61ea15d 100644
@@ -332,31 +332,6 @@ void bdrv_register(BlockDriver *bdrv)
     QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
 }
 
-/* create a new block device (by default it is empty) */
-BlockDriverState *bdrv_new_named(const char *device_name, Error **errp)
-{
-    BlockDriverState *bs;
-
-    assert(*device_name);
-
-    if (bdrv_find(device_name)) {
-        error_setg(errp, "Device with id '%s' already exists",
-                   device_name);
-        return NULL;
-    }
-    if (bdrv_find_node(device_name)) {
-        error_setg(errp, "Device with node-name '%s' already exists",
-                   device_name);
-        return NULL;
-    }
-
-    bs = bdrv_new();
-
-    pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
-
-    return bs;
-}
-
 BlockDriverState *bdrv_new(void)
 {
     BlockDriverState *bs;
@@ -1159,7 +1134,7 @@ void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd)
     } else if (backing_hd) {
         error_setg(&bs->backing_blocker,
                    "device is used as backing hd of '%s'",
-                   bs->device_name);
+                   bdrv_get_device_name(bs));
     }
 
     bs->backing_hd = backing_hd;
@@ -1533,7 +1508,7 @@ int bdrv_open(BlockDriverState **pbs, const char *filename,
         } else {
             error_setg(errp, "Block format '%s' used by device '%s' doesn't "
                        "support the option '%s'", drv->format_name,
-                       bs->device_name, entry->key);
+                       bdrv_get_device_name(bs), entry->key);
         }
 
         ret = -EINVAL;
@@ -1740,7 +1715,7 @@ int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
     if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
         reopen_state->flags & BDRV_O_RDWR) {
         error_set(errp, QERR_DEVICE_IS_READ_ONLY,
-                  reopen_state->bs->device_name);
+                  bdrv_get_device_name(reopen_state->bs));
         goto error;
     }
 
@@ -1767,7 +1742,7 @@ int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
         /* It is currently mandatory to have a bdrv_reopen_prepare()
          * handler for each supported drv. */
         error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
-                  drv->format_name, reopen_state->bs->device_name,
+                  drv->format_name, bdrv_get_device_name(reopen_state->bs),
                  "reopening of file");
         ret = -1;
         goto error;
@@ -1955,7 +1930,6 @@ void bdrv_drain_all(void)
    Also, NULL terminate the device_name to prevent double remove */
 void bdrv_make_anon(BlockDriverState *bs)
 {
-    bs->device_name[0] = '\0';
     if (bs->node_name[0] != '\0') {
         QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
     }
@@ -2008,9 +1982,6 @@ static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
     /* job */
     bs_dest->job                = bs_src->job;
 
-    pstrcpy(bs_dest->device_name, sizeof(bs_dest->device_name),
-            bs_src->device_name);
-
     memcpy(bs_dest->op_blockers, bs_src->op_blockers,
            sizeof(bs_dest->op_blockers));
 }
@@ -2023,7 +1994,7 @@ static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
  * This will modify the BlockDriverState fields, and swap contents
  * between bs_new and bs_old. Both bs_new and bs_old are modified.
  *
- * bs_new must be nameless and not attached to a BlockBackend.
+ * bs_new must not be attached to a BlockBackend.
  *
  * This function does not create any image files.
  */
@@ -2042,8 +2013,7 @@ void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old)
         QTAILQ_REMOVE(&graph_bdrv_states, bs_old, node_list);
     }
 
-    /* bs_new must be nameless and shouldn't have anything fancy enabled */
-    assert(bs_new->device_name[0] == '\0');
+    /* bs_new must be unattached and shouldn't have anything fancy enabled */
     assert(!bs_new->blk);
     assert(QLIST_EMPTY(&bs_new->dirty_bitmaps));
     assert(bs_new->job == NULL);
@@ -2060,8 +2030,7 @@ void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old)
     bdrv_move_feature_fields(bs_old, bs_new);
     bdrv_move_feature_fields(bs_new, &tmp);
 
-    /* bs_new must remain nameless and unattached */
-    assert(bs_new->device_name[0] == '\0');
+    /* bs_new must remain unattached */
     assert(!bs_new->blk);
 
     /* Check a few fields that should remain attached to the device */
@@ -2089,7 +2058,7 @@ void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old)
  * This will modify the BlockDriverState fields, and swap contents
  * between bs_new and bs_top. Both bs_new and bs_top are modified.
  *
- * bs_new must be nameless and not attached to a BlockBackend.
+ * bs_new must not be attached to a BlockBackend.
  *
  * This function does not create any image files.
  */
@@ -3799,7 +3768,7 @@ BlockDriverState *bdrv_find(const char *name)
     BlockDriverState *bs;
 
     for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
-        if (!strcmp(name, bs->device_name)) {
+        if (!strcmp(name, bdrv_get_device_name(bs))) {
             return bs;
         }
     }

block.c BlockDriverState *bdrv_next(BlockDriverState *bs) · line 3865

Quoted 10 lines
block.c +3 -2
@@ -3889,9 +3858,10 @@ BlockDriverState *bdrv_next(BlockDriverState *bs)
     return blk ? blk_bs(blk) : NULL;
 }
 
-const char *bdrv_get_device_name(BlockDriverState *bs)
+const char *bdrv_get_device_name(const BlockDriverState *bs)
 {
-    return bs->device_name;
+    const char *name = bs->blk ? blk_name(bs->blk) : NULL;
+    return name ?: "";
 }

Why not ?

Quoted 1 line
    return bs->blk ? blk_name(bs->blk) : "";

Sold!

Quoted 8 lines

or

    if (bs->blk) {
        return blk_name(bs->blk);
    }

    return "";
Quoted 6 lines

Would it fail to do the job ?

Also we could have made sure that bdrv_get_device_name return either a non empty string or NULL.

(We know blk_name will return a non empty string it's asserted)

In current master, bdrv_get_device_name(bs) returns an empty string if and only if bs is in bdrv_states.

PATCH 06 switches from bdrv_states to blk_backends without changing the value of bdrv_get_device_name().

Likewise, this patch switches from BDS member device_name to BB member name without changing the value of bdrv_get_device_name().

That's good, because changing the value would involve checking all the callers, and this series taxes certainly myself and probably my reviewers enough already, so I'd rather not do that right now.

Quoted 51 lines

This would need to change a few test all around the code but the final code logic would be less convoluted:
-convert NULL to "" then test for not ""
would turn into
-return NULL test for not NULL

Quoted 35 lines
block.c +5 -3
 int bdrv_get_flags(BlockDriverState *bs)
@@ -5253,13 +5223,15 @@ int bdrv_media_changed(BlockDriverState *bs)
 void bdrv_eject(BlockDriverState *bs, bool eject_flag)
 {
     BlockDriver *drv = bs->drv;
+    const char *device_name;
 
     if (drv && drv->bdrv_eject) {
         drv->bdrv_eject(bs, eject_flag);
     }
 
-    if (bs->device_name[0] != '\0') {
-        qapi_event_send_device_tray_moved(bdrv_get_device_name(bs),
 
+    device_name = bdrv_get_device_name(bs);
+        qapi_event_send_device_tray_moved(device_name,
                                           eject_flag, &error_abort);
     }
 }
@@ -5469,7 +5441,8 @@ bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
         blocker = QLIST_FIRST(&bs->op_blockers[op]);
         if (errp) {
             error_setg(errp, "Device '%s' is busy: %s",
-                       bs->device_name, error_get_pretty(blocker->reason));
+                       bdrv_get_device_name(bs),
+                       error_get_pretty(blocker->reason));
         }
         return true;
     }
block/block-backend.c +0 -0
index c0876fa..2f10d6a 100644

block/block-backend.c BlockBackend *blk_new_with_bs(const char *name, Error **errp) · line 71

Quoted 5 lines
block/block-backend.c +2 -0
@@ -67,17 +67,17 @@ BlockBackend *blk_new_with_bs(const char *name, Error **errp)
     BlockBackend *blk;
     BlockDriverState *bs;
 
+    if (bdrv_find_node(name)) {
+        error_setg(errp, "Device with node-name '%s' already exists", name);

Maybe the message written by the person who contributed the initial code (me) mislead you. I think the intent is good but the wording is wrong.
node-name is associated with a regular BDS. A device cannot have a node name.

Quoted 2 lines

Maybe something in the vein of:

        error_setg(errp, "Device name '%s' would conflict with the node-name of an existing block driver state", name);

I moved the message from block.c. Comes from Kevin's commit f2d953e. I like your wording better. Kevin, would you mind me changing it in the same patch, or do you want a separate one?

Quoted 18 lines
Quoted 18 lines
block/block-backend.c +4 -6
+        return NULL;
+    }
+
     blk = blk_new(name, errp);
     if (!blk) {
         return NULL;
     }
 
-    bs = bdrv_new_named(name, errp);
-    if (!bs) {
-        blk_unref(blk);
-        return NULL;
-    }
-
+    bs = bdrv_new();
     blk_attach_bs(blk, bs);
     return blk;
 }

[...]

#51 lore raw

PATCH 9/23 block: Merge BlockBackend and BlockDriverState name spaces

In reply to Markus Armbruster

BlockBackend's name space is separate only to keep the patches simple. Time to merge the two.

---
 block.c               | 11 +++--------
 block/block-backend.c | 10 +++++-----
 2 files changed, 8 insertions(+), 13 deletions(-)
block.c +3 -8
index 61ea15d..34c8f8c 100644
@@ -850,7 +850,7 @@ static void bdrv_assign_node_name(BlockDriverState *bs,
     }
 
     /* takes care of avoiding namespaces collisions */
-    if (bdrv_find(node_name)) {
+    if (blk_by_name(node_name)) {
         error_setg(errp, "node-name=%s is conflicting with a device id",
                    node_name);
         return;
@@ -3765,14 +3765,9 @@ void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
 /* This function is to find block backend bs */
 BlockDriverState *bdrv_find(const char *name)
 {
-    BlockDriverState *bs;
+    BlockBackend *blk = blk_by_name(name);
 
-    for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
-        if (!strcmp(name, bdrv_get_device_name(bs))) {
-            return bs;
-        }
-    }
-    return NULL;
+    return blk ? blk_bs(blk) : NULL;
 }
 
 /* This function is to find a node in the bs graph */
block/block-backend.c +5 -5
index 2f10d6a..b2db97b 100644
@@ -46,6 +46,11 @@ BlockBackend *blk_new(const char *name, Error **errp)
         error_setg(errp, "Device with id '%s' already exists", name);
         return NULL;
     }
+    if (bdrv_find_node(name)) {
+        error_setg(errp, "Device with node-name '%s' already exists", name);
+        return NULL;
+    }
+
     blk->name = g_strdup(name);
     blk->refcnt = 1;
     QTAILQ_INSERT_TAIL(&blk_backends, blk, link);
@@ -67,11 +72,6 @@ BlockBackend *blk_new_with_bs(const char *name, Error **errp)
     BlockBackend *blk;
     BlockDriverState *bs;
 
-    if (bdrv_find_node(name)) {
-        error_setg(errp, "Device with node-name '%s' already exists", name);
-        return NULL;
-    }
-
     blk = blk_new(name, errp);
     if (!blk) {
         return NULL;
Signature · 1 line
1.9.3
#52 lore raw

PATCH 10/23 block: Eliminate DriveInfo member bdrv, use blk_by_legacy_dinfo()

In reply to Markus Armbruster
---
 blockdev.c                               |  3 +--
 hw/arm/collie.c                          |  9 +++++----
 hw/arm/gumstix.c                         |  5 +++--
 hw/arm/mainstone.c                       |  8 ++++----
 hw/arm/musicpal.c                        | 11 ++++++-----
 hw/arm/nseries.c                         |  6 ++++--
 hw/arm/omap1.c                           |  4 +++-
 hw/arm/omap2.c                           |  4 +++-
 hw/arm/omap_sx1.c                        |  9 +++++----
 hw/arm/pxa2xx.c                          |  7 +++++--
 hw/arm/spitz.c                           |  4 +++-
 hw/arm/versatilepb.c                     |  4 +++-
 hw/arm/vexpress.c                        |  4 +++-
 hw/arm/xilinx_zynq.c                     |  4 +++-
 hw/arm/z2.c                              |  7 ++++---
 hw/block/fdc.c                           | 16 +++++++++++-----
 hw/block/m25p80.c                        |  5 +++--
 hw/block/xen_disk.c                      |  2 +-
 hw/cris/axis_dev88.c                     |  3 ++-
 hw/display/tc6393xb.c                    |  4 +++-
 hw/i386/pc_sysfw.c                       |  3 ++-
 hw/ide/piix.c                            |  6 ++++--
 hw/ide/qdev.c                            |  4 +++-
 hw/isa/pc87312.c                         |  7 +++++--
 hw/lm32/lm32_boards.c                    | 13 +++++++------
 hw/lm32/milkymist.c                      |  7 ++++---
 hw/microblaze/petalogix_ml605_mmu.c      |  5 +++--
 hw/microblaze/petalogix_s3adsp1800_mmu.c |  5 +++--
 hw/mips/mips_malta.c                     |  4 +++-
 hw/mips/mips_r4k.c                       |  5 +++--
 hw/pci/pci-hotplug-old.c                 |  9 ++++++---
 hw/ppc/ppc405_boards.c                   | 25 ++++++++++++++++---------
 hw/ppc/spapr.c                           |  4 +++-
 hw/ppc/virtex_ml507.c                    |  5 +++--
 hw/scsi/scsi-bus.c                       |  5 +++--
 hw/sd/milkymist-memcard.c                |  7 +++++--
 hw/sd/pl181.c                            |  3 ++-
 hw/sd/sdhci.c                            |  3 ++-
 hw/sd/ssi-sd.c                           |  3 ++-
 hw/sh4/r2d.c                             |  5 +++--
 hw/usb/dev-storage.c                     |  4 +++-
 hw/xtensa/xtfpga.c                       |  4 +++-
 include/sysemu/blockdev.h                |  1 -
 43 files changed, 163 insertions(+), 93 deletions(-)
blockdev.c +1 -2
index 353563e..5c75abd 100644
@@ -219,7 +219,7 @@ static void bdrv_format_print(void *opaque, const char *name)
 
 void drive_del(DriveInfo *dinfo)
 {
-    blk_unref(dinfo->bdrv->blk);
+    blk_unref(blk_by_legacy_dinfo(dinfo));
 }
 
 typedef struct {
@@ -472,7 +472,6 @@ static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
 
     dinfo = g_malloc0(sizeof(*dinfo));
     dinfo->id = g_strdup(qemu_opts_id(opts));
-    dinfo->bdrv = bs;
     blk_set_legacy_dinfo(blk, dinfo);
 
     if (!file || !*file) {
hw/arm/collie.c +5 -4
index ed7851f..0247290 100644
@@ -15,6 +15,7 @@
 #include "strongarm.h"
 #include "hw/arm/arm.h"
 #include "hw/block/flash.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "exec/address-spaces.h"
 
@@ -41,13 +42,13 @@ static void collie_init(MachineState *machine)
 
     dinfo = drive_get(IF_PFLASH, 0, 0);
     pflash_cfi01_register(SA_CS0, NULL, "collie.fl1", 0x02000000,
-                    dinfo ? dinfo->bdrv : NULL, (64 * 1024),
-                    512, 4, 0x00, 0x00, 0x00, 0x00, 0);
+                    dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL,
+                    (64 * 1024), 512, 4, 0x00, 0x00, 0x00, 0x00, 0);
 
     dinfo = drive_get(IF_PFLASH, 0, 1);
     pflash_cfi01_register(SA_CS1, NULL, "collie.fl2", 0x02000000,
-                    dinfo ? dinfo->bdrv : NULL, (64 * 1024),
-                    512, 4, 0x00, 0x00, 0x00, 0x00, 0);
+                    dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL,
+                    (64 * 1024), 512, 4, 0x00, 0x00, 0x00, 0x00, 0);
 
     sysbus_create_simple("scoop", 0x40800000, NULL);
 
hw/arm/gumstix.c +3 -2
index 3f8465e..49f9339 100644
@@ -40,6 +40,7 @@
 #include "hw/block/flash.h"
 #include "hw/devices.h"
 #include "hw/boards.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "exec/address-spaces.h"
 #include "sysemu/qtest.h"
@@ -71,7 +72,7 @@ static void connex_init(MachineState *machine)
     be = 0;
 #endif
     if (!pflash_cfi01_register(0x00000000, NULL, "connext.rom", connex_rom,
-                               dinfo ? dinfo->bdrv : NULL,
+                               dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL,
                                sector_len, connex_rom / sector_len,
                                2, 0, 0, 0, 0, be)) {
         fprintf(stderr, "qemu: Error registering flash memory.\n");
@@ -109,7 +110,7 @@ static void verdex_init(MachineState *machine)
     be = 0;
 #endif
     if (!pflash_cfi01_register(0x00000000, NULL, "verdex.rom", verdex_rom,
-                               dinfo ? dinfo->bdrv : NULL,
+                               dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL,
                                sector_len, verdex_rom / sector_len,
                                2, 0, 0, 0, 0, be)) {
         fprintf(stderr, "qemu: Error registering flash memory.\n");
hw/arm/mainstone.c +4 -4
index 44f1873..fb17d85 100644
@@ -18,7 +18,7 @@
 #include "hw/devices.h"
 #include "hw/boards.h"
 #include "hw/block/flash.h"
-#include "sysemu/blockdev.h"
+#include "sysemu/block-backend.h"
 #include "hw/sysbus.h"
 #include "exec/address-spaces.h"
 #include "sysemu/qtest.h"
@@ -148,9 +148,9 @@ static void mainstone_common_init(MemoryRegion *address_space_mem,
         if (!pflash_cfi01_register(mainstone_flash_base[i], NULL,
                                    i ? "mainstone.flash1" : "mainstone.flash0",
                                    MAINSTONE_FLASH,
-                                   dinfo->bdrv, sector_len,
-                                   MAINSTONE_FLASH / sector_len, 4, 0, 0, 0, 0,
-                                   be)) {
+                                   blk_bs(blk_by_legacy_dinfo(dinfo)),
+                                   sector_len, MAINSTONE_FLASH / sector_len,
+                                   4, 0, 0, 0, 0, be)) {
             fprintf(stderr, "qemu: Error registering flash memory.\n");
             exit(1);
         }
hw/arm/musicpal.c +6 -5
index 6a134f2..6a41d9c 100644
@@ -22,6 +22,7 @@
 #include "hw/block/flash.h"
 #include "ui/console.h"
 #include "hw/i2c/i2c.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "exec/address-spaces.h"
 #include "ui/pixel_ops.h"
@@ -1630,7 +1631,9 @@ static void musicpal_init(MachineState *machine)
     /* Register flash */
     dinfo = drive_get(IF_PFLASH, 0, 0);
     if (dinfo) {
-        flash_size = bdrv_getlength(dinfo->bdrv);
+        BlockDriverState *bs = blk_bs(blk_by_legacy_dinfo(dinfo));
+
+        flash_size = bdrv_getlength(bs);
         if (flash_size != 8*1024*1024 && flash_size != 16*1024*1024 &&
             flash_size != 32*1024*1024) {
             fprintf(stderr, "Invalid flash image size\n");
@@ -1645,16 +1648,14 @@ static void musicpal_init(MachineState *machine)
 #ifdef TARGET_WORDS_BIGENDIAN
         pflash_cfi02_register(0x100000000ULL-MP_FLASH_SIZE_MAX, NULL,
                               "musicpal.flash", flash_size,
-                              dinfo->bdrv, 0x10000,
-                              (flash_size + 0xffff) >> 16,
+                              bs, 0x10000, (flash_size + 0xffff) >> 16,
                               MP_FLASH_SIZE_MAX / flash_size,
                               2, 0x00BF, 0x236D, 0x0000, 0x0000,
                               0x5555, 0x2AAA, 1);
 #else
         pflash_cfi02_register(0x100000000ULL-MP_FLASH_SIZE_MAX, NULL,
                               "musicpal.flash", flash_size,
-                              dinfo->bdrv, 0x10000,
-                              (flash_size + 0xffff) >> 16,
+                              bs, 0x10000, (flash_size + 0xffff) >> 16,
                               MP_FLASH_SIZE_MAX / flash_size,
                               2, 0x00BF, 0x236D, 0x0000, 0x0000,
                               0x5555, 0x2AAA, 0);
hw/arm/nseries.c +4 -2
index 4f092d6..2536078 100644
@@ -31,6 +31,7 @@
 #include "hw/hw.h"
 #include "hw/bt.h"
 #include "hw/loader.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "hw/sysbus.h"
 #include "exec/address-spaces.h"
@@ -172,8 +173,9 @@ static void n8x0_nand_setup(struct n800_s *s)
     qdev_prop_set_uint16(s->nand, "version_id", 0);
     qdev_prop_set_int32(s->nand, "shift", 1);
     dinfo = drive_get(IF_MTD, 0, 0);
-    if (dinfo && dinfo->bdrv) {
-        qdev_prop_set_drive_nofail(s->nand, "drive", dinfo->bdrv);
+    if (dinfo) {
+        qdev_prop_set_drive_nofail(s->nand, "drive",
+                                   blk_bs(blk_by_legacy_dinfo(dinfo)));
     }
     qdev_init_nofail(s->nand);
     sysbus_connect_irq(SYS_BUS_DEVICE(s->nand), 0,
hw/arm/omap1.c +3 -1
index e7cc5d7..e38e07f 100644
@@ -21,6 +21,7 @@
 #include "hw/arm/omap.h"
 #include "sysemu/sysemu.h"
 #include "hw/arm/soc_dma.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "qemu/range.h"
 #include "hw/sysbus.h"
@@ -3976,7 +3977,8 @@ struct omap_mpu_state_s *omap310_mpu_init(MemoryRegion *system_memory,
         fprintf(stderr, "qemu: missing SecureDigital device\n");
         exit(1);
     }
-    s->mmc = omap_mmc_init(0xfffb7800, system_memory, dinfo->bdrv,
+    s->mmc = omap_mmc_init(0xfffb7800, system_memory,
+                           blk_bs(blk_by_legacy_dinfo(dinfo)),
                            qdev_get_gpio_in(s->ih[1], OMAP_INT_OQN),
                            &s->drq[OMAP_DMA_MMC_TX],
                     omap_findclk(s, "mmc_ck"));
hw/arm/omap2.c +3 -1
index dc53a7a..e47dd63 100644
@@ -18,6 +18,7 @@
  * with this program; if not, see <http://www.gnu.org/licenses/>.
  */
 
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "hw/hw.h"
 #include "hw/arm/arm.h"
@@ -2459,7 +2460,8 @@ struct omap_mpu_state_s *omap2420_mpu_init(MemoryRegion *sysmem,
         fprintf(stderr, "qemu: missing SecureDigital device\n");
         exit(1);
     }
-    s->mmc = omap2_mmc_init(omap_l4tao(s->l4, 9), dinfo->bdrv,
+    s->mmc = omap2_mmc_init(omap_l4tao(s->l4, 9),
+                    blk_bs(blk_by_legacy_dinfo(dinfo)),
                     qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_MMC_IRQ),
                     &s->drq[OMAP24XX_DMA_MMC1_TX],
                     omap_findclk(s, "mmc_fclk"), omap_findclk(s, "mmc_iclk"));
hw/arm/omap_sx1.c +5 -4
index b4f6da6..f475afc 100644
@@ -31,6 +31,7 @@
 #include "hw/boards.h"
 #include "hw/arm/arm.h"
 #include "hw/block/flash.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "sysemu/qtest.h"
 #include "exec/address-spaces.h"
@@ -153,8 +154,8 @@ static void sx1_init(MachineState *machine, const int version)
     if ((dinfo = drive_get(IF_PFLASH, 0, fl_idx)) != NULL) {
         if (!pflash_cfi01_register(OMAP_CS0_BASE, NULL,
                                    "omap_sx1.flash0-1", flash_size,
-                                   dinfo->bdrv, sector_size,
-                                   flash_size / sector_size,
+                                   blk_bs(blk_by_legacy_dinfo(dinfo)),
+                                   sector_size, flash_size / sector_size,
                                    4, 0, 0, 0, 0, be)) {
             fprintf(stderr, "qemu: Error registering flash memory %d.\n",
                            fl_idx);
@@ -176,8 +177,8 @@ static void sx1_init(MachineState *machine, const int version)
 
         if (!pflash_cfi01_register(OMAP_CS1_BASE, NULL,
                                    "omap_sx1.flash1-1", flash1_size,
-                                   dinfo->bdrv, sector_size,
-                                   flash1_size / sector_size,
+                                   blk_bs(blk_by_legacy_dinfo(dinfo)),
+                                   sector_size, flash1_size / sector_size,
                                    4, 0, 0, 0, 0, be)) {
             fprintf(stderr, "qemu: Error registering flash memory %d.\n",
                            fl_idx);
hw/arm/pxa2xx.c +5 -2
index 557e0f1..7ec0da8 100644
@@ -14,6 +14,7 @@
 #include "hw/i2c/i2c.h"
 #include "hw/ssi.h"
 #include "sysemu/char.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 
 static struct {
@@ -2083,7 +2084,8 @@ PXA2xxState *pxa270_init(MemoryRegion *address_space,
         fprintf(stderr, "qemu: missing SecureDigital device\n");
         exit(1);
     }
-    s->mmc = pxa2xx_mmci_init(address_space, 0x41100000, dinfo->bdrv,
+    s->mmc = pxa2xx_mmci_init(address_space, 0x41100000,
+                    blk_bs(blk_by_legacy_dinfo(dinfo)),
                     qdev_get_gpio_in(s->pic, PXA2XX_PIC_MMC),
                     qdev_get_gpio_in(s->dma, PXA2XX_RX_RQ_MMCI),
                     qdev_get_gpio_in(s->dma, PXA2XX_TX_RQ_MMCI));
@@ -2214,7 +2216,8 @@ PXA2xxState *pxa255_init(MemoryRegion *address_space, unsigned int sdram_size)
         fprintf(stderr, "qemu: missing SecureDigital device\n");
         exit(1);
     }
-    s->mmc = pxa2xx_mmci_init(address_space, 0x41100000, dinfo->bdrv,
+    s->mmc = pxa2xx_mmci_init(address_space, 0x41100000,
+                    blk_bs(blk_by_legacy_dinfo(dinfo)),
                     qdev_get_gpio_in(s->pic, PXA2XX_PIC_MMC),
                     qdev_get_gpio_in(s->dma, PXA2XX_RX_RQ_MMCI),
                     qdev_get_gpio_in(s->dma, PXA2XX_TX_RQ_MMCI));
hw/arm/spitz.c +3 -1
index 03cc6ce..5d684a2 100644
@@ -25,6 +25,7 @@
 #include "block/block.h"
 #include "audio/audio.h"
 #include "hw/boards.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "hw/sysbus.h"
 #include "exec/address-spaces.h"
@@ -170,7 +171,8 @@ static int sl_nand_init(SysBusDevice *dev)
 
     s->ctl = 0;
     nand = drive_get(IF_MTD, 0, 0);
-    s->nand = nand_init(nand ? nand->bdrv : NULL, s->manf_id, s->chip_id);
+    s->nand = nand_init(nand ? blk_bs(blk_by_legacy_dinfo(nand)) : NULL,
+                        s->manf_id, s->chip_id);
 
     memory_region_init_io(&s->iomem, OBJECT(s), &sl_ops, s, "sl", 0x40);
     sysbus_init_mmio(dev, &s->iomem);
hw/arm/versatilepb.c +3 -1
index dea5fc7..c88be6b 100644
@@ -15,6 +15,7 @@
 #include "hw/pci/pci.h"
 #include "hw/i2c/i2c.h"
 #include "hw/boards.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "exec/address-spaces.h"
 #include "hw/block/flash.h"
@@ -337,7 +338,8 @@ static void versatile_init(MachineState *machine, int board_id)
 
     dinfo = drive_get(IF_PFLASH, 0, 0);
     if (!pflash_cfi01_register(VERSATILE_FLASH_ADDR, NULL, "versatile.flash",
-                          VERSATILE_FLASH_SIZE, dinfo ? dinfo->bdrv : NULL,
+                          VERSATILE_FLASH_SIZE,
+                          dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL,
                           VERSATILE_FLASH_SECT_SIZE,
                           VERSATILE_FLASH_SIZE / VERSATILE_FLASH_SECT_SIZE,
                           4, 0x0089, 0x0018, 0x0000, 0x0, 0)) {
hw/arm/vexpress.c +3 -1
index a88732c..a492c22 100644
@@ -30,6 +30,7 @@
 #include "hw/boards.h"
 #include "hw/loader.h"
 #include "exec/address-spaces.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "hw/block/flash.h"
 #include "sysemu/device_tree.h"
@@ -488,7 +489,8 @@ static pflash_t *ve_pflash_cfi01_register(hwaddr base, const char *name,
 {
     DeviceState *dev = qdev_create(NULL, "cfi.pflash01");
 
-    if (di && qdev_prop_set_drive(dev, "drive", di->bdrv)) {
+    if (di && qdev_prop_set_drive(dev, "drive",
+                                  blk_bs(blk_by_legacy_dinfo(di)))) {
         abort();
     }
 
hw/arm/xilinx_zynq.c +3 -1
index ba5aa82..78e6934 100644
@@ -22,6 +22,7 @@
 #include "sysemu/sysemu.h"
 #include "hw/boards.h"
 #include "hw/block/flash.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "hw/loader.h"
 #include "hw/ssi.h"
@@ -162,7 +163,8 @@ static void zynq_init(MachineState *machine)
 
     /* AMD */
     pflash_cfi02_register(0xe2000000, NULL, "zynq.pflash", FLASH_SIZE,
-                          dinfo ? dinfo->bdrv : NULL, FLASH_SECTOR_SIZE,
+                          dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL,
+                          FLASH_SECTOR_SIZE,
                           FLASH_SIZE/FLASH_SECTOR_SIZE, 1,
                           1, 0x0066, 0x0022, 0x0000, 0x0000, 0x0555, 0x2aa,
                               0);
hw/arm/z2.c +4 -3
index 36b3b50..9b38a2b 100644
@@ -20,6 +20,7 @@
 #include "hw/boards.h"
 #include "sysemu/sysemu.h"
 #include "hw/block/flash.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "ui/console.h"
 #include "audio/audio.h"
@@ -336,9 +337,9 @@ static void z2_init(MachineState *machine)
 
     if (!pflash_cfi01_register(Z2_FLASH_BASE,
                                NULL, "z2.flash0", Z2_FLASH_SIZE,
-                               dinfo ? dinfo->bdrv : NULL, sector_len,
-                               Z2_FLASH_SIZE / sector_len, 4, 0, 0, 0, 0,
-                               be)) {
+                               dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL,
+                               sector_len, Z2_FLASH_SIZE / sector_len,
+                               4, 0, 0, 0, 0, be)) {
         fprintf(stderr, "qemu: Error registering flash memory.\n");
         exit(1);
     }
hw/block/fdc.c +11 -5
index 490d127..19f215f 100644
@@ -33,6 +33,7 @@
 #include "qemu/timer.h"
 #include "hw/isa/isa.h"
 #include "hw/sysbus.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "sysemu/sysemu.h"
 #include "qemu/log.h"
@@ -2033,10 +2034,12 @@ ISADevice *fdctrl_init_isa(ISABus *bus, DriveInfo **fds)
     dev = DEVICE(isadev);
 
     if (fds[0]) {
-        qdev_prop_set_drive_nofail(dev, "driveA", fds[0]->bdrv);
+        qdev_prop_set_drive_nofail(dev, "driveA",
+                                   blk_bs(blk_by_legacy_dinfo(fds[0])));
     }
     if (fds[1]) {
-        qdev_prop_set_drive_nofail(dev, "driveB", fds[1]->bdrv);
+        qdev_prop_set_drive_nofail(dev, "driveB",
+                                   blk_bs(blk_by_legacy_dinfo(fds[1])));
     }
     qdev_init_nofail(dev);
 
@@ -2056,10 +2059,12 @@ void fdctrl_init_sysbus(qemu_irq irq, int dma_chann,
     fdctrl = &sys->state;
     fdctrl->dma_chann = dma_chann; /* FIXME */
     if (fds[0]) {
-        qdev_prop_set_drive_nofail(dev, "driveA", fds[0]->bdrv);
+        qdev_prop_set_drive_nofail(dev, "driveA",
+                                   blk_bs(blk_by_legacy_dinfo(fds[0])));
     }
     if (fds[1]) {
-        qdev_prop_set_drive_nofail(dev, "driveB", fds[1]->bdrv);
+        qdev_prop_set_drive_nofail(dev, "driveB",
+                                   blk_bs(blk_by_legacy_dinfo(fds[1])));
     }
     qdev_init_nofail(dev);
     sbd = SYS_BUS_DEVICE(dev);
@@ -2075,7 +2080,8 @@ void sun4m_fdctrl_init(qemu_irq irq, hwaddr io_base,
 
     dev = qdev_create(NULL, "SUNW,fdtwo");
     if (fds[0]) {
-        qdev_prop_set_drive_nofail(dev, "drive", fds[0]->bdrv);
+        qdev_prop_set_drive_nofail(dev, "drive",
+                                   blk_bs(blk_by_legacy_dinfo(fds[0])));
     }
     qdev_init_nofail(dev);
     sys = SYSBUS_FDC(dev);
hw/block/m25p80.c +3 -2
index 5893773..78280a8 100644
@@ -22,6 +22,7 @@
  */
 
 #include "hw/hw.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "hw/ssi.h"
 
@@ -624,9 +625,9 @@ static int m25p80_init(SSISlave *ss)
 
     dinfo = drive_get_next(IF_MTD);
 
-    if (dinfo && dinfo->bdrv) {
+    if (dinfo) {
         DB_PRINT_L(0, "Binding to IF_MTD drive\n");
-        s->bdrv = dinfo->bdrv;
+        s->bdrv = blk_bs(blk_by_legacy_dinfo(dinfo));
 
         /* FIXME: Move to late init */
         if (bdrv_read(s->bdrv, 0, s->storage, DIV_ROUND_UP(s->size,
hw/block/xen_disk.c +1 -1
index 6d474b9..b571bbe 100644
@@ -877,7 +877,7 @@ static int blk_connect(struct XenDevice *xendev)
     } else {
         /* setup via qemu cmdline -> already setup for us */
         xen_be_printf(&blkdev->xendev, 2, "get configured bdrv (cmdline setup)\n");
-        blkdev->bs = blkdev->dinfo->bdrv;
+        blkdev->bs = blk_bs(blk_by_legacy_dinfo(blkdev->dinfo));
         if (bdrv_is_read_only(blkdev->bs) && !readonly) {
             xen_be_printf(&blkdev->xendev, 0, "Unexpected read-only drive");
             blkdev->bs = NULL;
hw/cris/axis_dev88.c +2 -1
index 1849338..280722d 100644
@@ -30,6 +30,7 @@
 #include "hw/loader.h"
 #include "elf.h"
 #include "boot.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "exec/address-spaces.h"
 #include "sysemu/qtest.h"
@@ -282,7 +283,7 @@ void axisdev88_init(MachineState *machine)
 
       /* Attach a NAND flash to CS1.  */
     nand = drive_get(IF_MTD, 0, 0);
-    nand_state.nand = nand_init(nand ? nand->bdrv : NULL,
+    nand_state.nand = nand_init(nand ? blk_bs(blk_by_legacy_dinfo(nand)) : NULL,
                                 NAND_MFR_STMICRO, 0x39);
     memory_region_init_io(&nand_state.iomem, NULL, &nand_ops, &nand_state,
                           "nand", 0x05000000);
hw/display/tc6393xb.c +3 -1
index f4011d2..62d6663 100644
@@ -15,6 +15,7 @@
 #include "hw/block/flash.h"
 #include "ui/console.h"
 #include "ui/pixel_ops.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 
 #define IRQ_TC6393_NAND		0
@@ -576,7 +577,8 @@ TC6393xbState *tc6393xb_init(MemoryRegion *sysmem, uint32_t base, qemu_irq irq)
     s->sub_irqs = qemu_allocate_irqs(tc6393xb_sub_irq, s, TC6393XB_NR_IRQS);
 
     nand = drive_get(IF_MTD, 0, 0);
-    s->flash = nand_init(nand ? nand->bdrv : NULL, NAND_MFR_TOSHIBA, 0x76);
+    s->flash = nand_init(nand ? blk_bs(blk_by_legacy_dinfo(nand)) : NULL,
+                         NAND_MFR_TOSHIBA, 0x76);
 
     memory_region_init_io(&s->iomem, NULL, &tc6393xb_ops, s, "tc6393xb", 0x10000);
     memory_region_add_subregion(sysmem, base, &s->iomem);
hw/i386/pc_sysfw.c +2 -1
index 75a7ebb..6cd264a 100644
@@ -23,6 +23,7 @@
  * THE SOFTWARE.
  */
 
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "qemu/error-report.h"
 #include "hw/sysbus.h"
@@ -118,7 +119,7 @@ static void pc_system_flash_init(MemoryRegion *rom_memory)
          (unit < FLASH_MAP_UNIT_MAX &&
           (pflash_drv = drive_get(IF_PFLASH, 0, unit)) != NULL);
          ++unit) {
-        bdrv = pflash_drv->bdrv;
+        bdrv = blk_bs(blk_by_legacy_dinfo(pflash_drv));
         size = bdrv_getlength(bdrv);
         if (size < 0) {
             fatal_errmsg = g_strdup_printf("failed to get backing file size");
hw/ide/piix.c +4 -2
index 49e78a7..c6c256f 100644
@@ -27,6 +27,7 @@
 #include <hw/i386/pc.h>
 #include <hw/pci/pci.h>
 #include <hw/isa/isa.h>
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "sysemu/sysemu.h"
 #include "sysemu/dma.h"
@@ -178,9 +179,10 @@ int pci_piix3_xen_ide_unplug(DeviceState *dev)
     for (; i < 3; i++) {
         di = drive_get_by_index(IF_IDE, i);
         if (di != NULL && !di->media_cd) {
-            DeviceState *ds = bdrv_get_attached_dev(di->bdrv);
+            BlockDriverState *bs = blk_bs(blk_by_legacy_dinfo(di));
+            DeviceState *ds = bdrv_get_attached_dev(bs);
             if (ds) {
-                bdrv_detach_dev(di->bdrv, ds);
+                bdrv_detach_dev(bs, ds);
             }
             pci_ide->bus[di->bus].ifs[di->unit].bs = NULL;
             drive_del(di);
hw/ide/qdev.c +3 -1
index efab95b..75e8eb3 100644
@@ -20,6 +20,7 @@
 #include "sysemu/dma.h"
 #include "qemu/error-report.h"
 #include <hw/ide/internal.h>
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "hw/block/block.h"
 #include "sysemu/sysemu.h"
@@ -116,7 +117,8 @@ IDEDevice *ide_create_drive(IDEBus *bus, int unit, DriveInfo *drive)
 
     dev = qdev_create(&bus->qbus, drive->media_cd ? "ide-cd" : "ide-hd");
     qdev_prop_set_uint32(dev, "unit", unit);
-    qdev_prop_set_drive_nofail(dev, "drive", drive->bdrv);
+    qdev_prop_set_drive_nofail(dev, "drive",
+                               blk_bs(blk_by_legacy_dinfo(drive)));
     qdev_init_nofail(dev);
     return DO_UPCAST(IDEDevice, qdev, dev);
 }
hw/isa/pc87312.c +5 -2
index 9327c53..b691a0c 100644
@@ -25,6 +25,7 @@
 
 #include "hw/isa/pc87312.h"
 #include "qemu/error-report.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "sysemu/sysemu.h"
 #include "sysemu/char.h"
@@ -320,11 +321,13 @@ static void pc87312_realize(DeviceState *dev, Error **errp)
         qdev_prop_set_uint32(d, "irq", 6);
         drive = drive_get(IF_FLOPPY, 0, 0);
         if (drive != NULL) {
-            qdev_prop_set_drive_nofail(d, "driveA", drive->bdrv);
+            qdev_prop_set_drive_nofail(d, "driveA",
+                                       blk_bs(blk_by_legacy_dinfo(drive)));
         }
         drive = drive_get(IF_FLOPPY, 0, 1);
         if (drive != NULL) {
-            qdev_prop_set_drive_nofail(d, "driveB", drive->bdrv);
+            qdev_prop_set_drive_nofail(d, "driveB",
+                                       blk_bs(blk_by_legacy_dinfo(drive)));
         }
         qdev_init_nofail(d);
         s->fdc.dev = isa;
hw/lm32/lm32_boards.c +7 -6
index 0e01340..17c5610 100644
@@ -23,6 +23,7 @@
 #include "hw/devices.h"
 #include "hw/boards.h"
 #include "hw/loader.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "elf.h"
 #include "lm32_hwsetup.h"
@@ -118,9 +119,9 @@ static void lm32_evr_init(MachineState *machine)
     dinfo = drive_get(IF_PFLASH, 0, 0);
     /* Spansion S29NS128P */
     pflash_cfi02_register(flash_base, NULL, "lm32_evr.flash", flash_size,
-                          dinfo ? dinfo->bdrv : NULL, flash_sector_size,
-                          flash_size / flash_sector_size, 1, 2,
-                          0x01, 0x7e, 0x43, 0x00, 0x555, 0x2aa, 1);
+                          dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL,
+                          flash_sector_size, flash_size / flash_sector_size,
+                          1, 2, 0x01, 0x7e, 0x43, 0x00, 0x555, 0x2aa, 1);
 
     /* create irq lines */
     cpu_irq = qemu_allocate_irqs(cpu_irq_handler, cpu, 1);
@@ -220,9 +221,9 @@ static void lm32_uclinux_init(MachineState *machine)
     dinfo = drive_get(IF_PFLASH, 0, 0);
     /* Spansion S29NS128P */
     pflash_cfi02_register(flash_base, NULL, "lm32_uclinux.flash", flash_size,
-                          dinfo ? dinfo->bdrv : NULL, flash_sector_size,
-                          flash_size / flash_sector_size, 1, 2,
-                          0x01, 0x7e, 0x43, 0x00, 0x555, 0x2aa, 1);
+                          dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL,
+                          flash_sector_size, flash_size / flash_sector_size,
+                          1, 2, 0x01, 0x7e, 0x43, 0x00, 0x555, 0x2aa, 1);
 
     /* create irq lines */
     cpu_irq = qemu_allocate_irqs(cpu_irq_handler, env, 1);
hw/lm32/milkymist.c +4 -3
index 81c3933..904b9c0 100644
@@ -26,6 +26,7 @@
 #include "hw/boards.h"
 #include "hw/loader.h"
 #include "elf.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "milkymist-hw.h"
 #include "lm32.h"
@@ -125,9 +126,9 @@ milkymist_init(MachineState *machine)
     dinfo = drive_get(IF_PFLASH, 0, 0);
     /* Numonyx JS28F256J3F105 */
     pflash_cfi01_register(flash_base, NULL, "milkymist.flash", flash_size,
-                          dinfo ? dinfo->bdrv : NULL, flash_sector_size,
-                          flash_size / flash_sector_size, 2,
-                          0x00, 0x89, 0x00, 0x1d, 1);
+                          dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL,
+                          flash_sector_size, flash_size / flash_sector_size,
+                          2, 0x00, 0x89, 0x00, 0x1d, 1);
 
     /* create irq lines */
     cpu_irq = qemu_allocate_irqs(cpu_irq_handler, cpu, 1);
hw/microblaze/petalogix_ml605_mmu.c +3 -2
index 6843abf..2974791 100644
@@ -32,6 +32,7 @@
 #include "sysemu/sysemu.h"
 #include "hw/devices.h"
 #include "hw/boards.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "hw/char/serial.h"
 #include "exec/address-spaces.h"
@@ -112,8 +113,8 @@ petalogix_ml605_init(MachineState *machine)
      * 10th paremeter 0 means little-endian */
     pflash_cfi01_register(FLASH_BASEADDR,
                           NULL, "petalogix_ml605.flash", FLASH_SIZE,
-                          dinfo ? dinfo->bdrv : NULL, (64 * 1024),
-                          FLASH_SIZE >> 16,
+                          dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL,
+                          (64 * 1024), FLASH_SIZE >> 16,
                           2, 0x89, 0x18, 0x0000, 0x0, 0);
 
 
hw/microblaze/petalogix_s3adsp1800_mmu.c +3 -2
index 49dc6d1..a69301f 100644
@@ -30,6 +30,7 @@
 #include "sysemu/sysemu.h"
 #include "hw/devices.h"
 #include "hw/boards.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "exec/address-spaces.h"
 
@@ -92,8 +93,8 @@ petalogix_s3adsp1800_init(MachineState *machine)
     dinfo = drive_get(IF_PFLASH, 0, 0);
     pflash_cfi01_register(FLASH_BASEADDR,
                           NULL, "petalogix_s3adsp1800.flash", FLASH_SIZE,
-                          dinfo ? dinfo->bdrv : NULL, (64 * 1024),
-                          FLASH_SIZE >> 16,
+                          dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL,
+                          (64 * 1024), FLASH_SIZE >> 16,
                           1, 0x89, 0x18, 0x0000, 0x0, 1);
 
     dev = qdev_create(NULL, "xlnx.xps-intc");
hw/mips/mips_malta.c +3 -1
index cfb60af..9f84ad6 100644
@@ -44,6 +44,7 @@
 #include "elf.h"
 #include "hw/timer/mc146818rtc.h"
 #include "hw/timer/i8254.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "exec/address-spaces.h"
 #include "hw/sysbus.h"             /* SysBusDevice */
@@ -1035,7 +1036,8 @@ void mips_malta_init(MachineState *machine)
     }
 #endif
     fl = pflash_cfi01_register(FLASH_ADDRESS, NULL, "mips_malta.bios",
-                               BIOS_SIZE, dinfo ? dinfo->bdrv : NULL,
+                               BIOS_SIZE,
+                               dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL,
                                65536, fl_sectors,
                                4, 0x0000, 0x0000, 0x0000, 0x0000, be);
     bios = pflash_cfi01_get_memory(fl);
hw/mips/mips_r4k.c +3 -2
index 7120293..6fd69b9 100644
@@ -24,6 +24,7 @@
 #include "elf.h"
 #include "hw/timer/mc146818rtc.h"
 #include "hw/timer/i8254.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "exec/address-spaces.h"
 #include "sysemu/qtest.h"
@@ -240,8 +241,8 @@ void mips_r4k_init(MachineState *machine)
     } else if ((dinfo = drive_get(IF_PFLASH, 0, 0)) != NULL) {
         uint32_t mips_rom = 0x00400000;
         if (!pflash_cfi01_register(0x1fc00000, NULL, "mips_r4k.bios", mips_rom,
-                                   dinfo->bdrv, sector_len,
-                                   mips_rom / sector_len,
+                                   blk_bs(blk_by_legacy_dinfo(dinfo)),
+                                   sector_len, mips_rom / sector_len,
                                    4, 0, 0, 0, 0, be)) {
             fprintf(stderr, "qemu: Error registering flash memory.\n");
 	}
hw/pci/pci-hotplug-old.c +6 -3
index cf2caeb..e4d51de 100644
@@ -33,6 +33,7 @@
 #include "hw/scsi/scsi.h"
 #include "hw/virtio/virtio-blk.h"
 #include "qemu/config-file.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "qapi/error.h"
 
@@ -126,8 +127,9 @@ static int scsi_hot_add(Monitor *mon, DeviceState *adapter,
      */
     dinfo->unit = qemu_opt_get_number(dinfo->opts, "unit", -1);
     dinfo->bus = scsibus->busnr;
-    scsidev = scsi_bus_legacy_add_drive(scsibus, dinfo->bdrv, dinfo->unit,
-                                        false, -1, NULL, NULL);
+    scsidev = scsi_bus_legacy_add_drive(scsibus,
+                                        blk_bs(blk_by_legacy_dinfo(dinfo)),
+                                        dinfo->unit, false, -1, NULL, NULL);
     if (!scsidev) {
         return -1;
     }
@@ -247,7 +249,8 @@ static PCIDevice *qemu_pci_hot_add_storage(Monitor *mon,
             return NULL;
         }
         dev = pci_create(bus, devfn, "virtio-blk-pci");
-        if (qdev_prop_set_drive(&dev->qdev, "drive", dinfo->bdrv) < 0) {
+        if (qdev_prop_set_drive(&dev->qdev, "drive",
+                                blk_bs(blk_by_legacy_dinfo(dinfo))) < 0) {
             object_unparent(OBJECT(dev));
             dev = NULL;
             break;
hw/ppc/ppc405_boards.c +16 -9
index 11d3379..7ff5ee5 100644
@@ -33,6 +33,7 @@
 #include "qemu/log.h"
 #include "qemu/error-report.h"
 #include "hw/loader.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "exec/address-spaces.h"
 
@@ -225,17 +226,19 @@ static void ref405ep_init(MachineState *machine)
 #ifdef USE_FLASH_BIOS
     dinfo = drive_get(IF_PFLASH, 0, fl_idx);
     if (dinfo) {
-        bios_size = bdrv_getlength(dinfo->bdrv);
+        BlockDriverState *bs = blk_bs(blk_by_legacy_dinfo(dinfo));
+
+        bios_size = bdrv_getlength(bs);
         fl_sectors = (bios_size + 65535) >> 16;
 #ifdef DEBUG_BOARD_INIT
         printf("Register parallel flash %d size %lx"
                " at addr %lx '%s' %d\n",
                fl_idx, bios_size, -bios_size,
-               bdrv_get_device_name(dinfo->bdrv), fl_sectors);
+               bdrv_get_device_name(bs), fl_sectors);
 #endif
         pflash_cfi02_register((uint32_t)(-bios_size),
                               NULL, "ef405ep.bios", bios_size,
-                              dinfo->bdrv, 65536, fl_sectors, 1,
+                              bs, 65536, fl_sectors, 1,
                               2, 0x0001, 0x22DA, 0x0000, 0x0000, 0x555, 0x2AA,
                               1);
         fl_idx++;
@@ -547,7 +550,9 @@ static void taihu_405ep_init(MachineState *machine)
 #if defined(USE_FLASH_BIOS)
     dinfo = drive_get(IF_PFLASH, 0, fl_idx);
     if (dinfo) {
-        bios_size = bdrv_getlength(dinfo->bdrv);
+        BlockDriverState *bs = blk_bs(blk_by_legacy_dinfo(dinfo));
+
+        bios_size = bdrv_getlength(bs);
         /* XXX: should check that size is 2MB */
         //        bios_size = 2 * 1024 * 1024;
         fl_sectors = (bios_size + 65535) >> 16;
@@ -555,11 +560,11 @@ static void taihu_405ep_init(MachineState *machine)
         printf("Register parallel flash %d size %lx"
                " at addr %lx '%s' %d\n",
                fl_idx, bios_size, -bios_size,
-               bdrv_get_device_name(dinfo->bdrv), fl_sectors);
+               bdrv_get_device_name(bs), fl_sectors);
 #endif
         pflash_cfi02_register((uint32_t)(-bios_size),
                               NULL, "taihu_405ep.bios", bios_size,
-                              dinfo->bdrv, 65536, fl_sectors, 1,
+                              bs, 65536, fl_sectors, 1,
                               4, 0x0001, 0x22DA, 0x0000, 0x0000, 0x555, 0x2AA,
                               1);
         fl_idx++;
@@ -593,7 +598,9 @@ static void taihu_405ep_init(MachineState *machine)
     /* Register Linux flash */
     dinfo = drive_get(IF_PFLASH, 0, fl_idx);
     if (dinfo) {
-        bios_size = bdrv_getlength(dinfo->bdrv);
+        BlockDriverState *bs = blk_bs(blk_by_legacy_dinfo(dinfo));
+
+        bios_size = bdrv_getlength(bs);
         /* XXX: should check that size is 32MB */
         bios_size = 32 * 1024 * 1024;
         fl_sectors = (bios_size + 65535) >> 16;
@@ -601,10 +608,10 @@ static void taihu_405ep_init(MachineState *machine)
         printf("Register parallel flash %d size %lx"
                " at addr " TARGET_FMT_lx " '%s'\n",
                fl_idx, bios_size, (target_ulong)0xfc000000,
-               bdrv_get_device_name(dinfo->bdrv));
+               bdrv_get_device_name(bs));
 #endif
         pflash_cfi02_register(0xfc000000, NULL, "taihu_405ep.flash", bios_size,
-                              dinfo->bdrv, 65536, fl_sectors, 1,
+                              bs, 65536, fl_sectors, 1,
                               4, 0x0001, 0x22DA, 0x0000, 0x0000, 0x555, 0x2AA,
                               1);
         fl_idx++;
hw/ppc/spapr.c +3 -1
index 2ab4460..a577812 100644
@@ -29,6 +29,7 @@
 #include "hw/fw-path-provider.h"
 #include "elf.h"
 #include "net/net.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "sysemu/cpus.h"
 #include "sysemu/kvm.h"
@@ -925,7 +926,8 @@ static void spapr_create_nvram(sPAPREnvironment *spapr)
     DriveInfo *dinfo = drive_get(IF_PFLASH, 0, 0);
 
     if (dinfo) {
-        qdev_prop_set_drive_nofail(dev, "drive", dinfo->bdrv);
+        qdev_prop_set_drive_nofail(dev, "drive",
+                                   blk_bs(blk_by_legacy_dinfo(dinfo)));
     }
 
     qdev_init_nofail(dev);
hw/ppc/virtex_ml507.c +3 -2
index 0de5148..a0ce447 100644
@@ -39,6 +39,7 @@
 #include "hw/ppc/ppc4xx.h"
 #include "ppc405.h"
 
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "qapi/qmp/qerror.h"
 
@@ -227,8 +228,8 @@ static void virtex_init(MachineState *machine)
 
     dinfo = drive_get(IF_PFLASH, 0, 0);
     pflash_cfi01_register(PFLASH_BASEADDR, NULL, "virtex.flash", FLASH_SIZE,
-                          dinfo ? dinfo->bdrv : NULL, (64 * 1024),
-                          FLASH_SIZE >> 16,
+                          dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL,
+                          (64 * 1024), FLASH_SIZE >> 16,
                           1, 0x89, 0x18, 0x0000, 0x0, 1);
 
     cpu_irq = (qemu_irq *) &env->irq_inputs[PPC40x_INPUT_INT];
hw/scsi/scsi-bus.c +3 -2
index 954c607..f5156ae 100644
@@ -3,6 +3,7 @@
 #include "hw/scsi/scsi.h"
 #include "block/scsi.h"
 #include "hw/qdev.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "trace.h"
 #include "sysemu/dma.h"
@@ -267,8 +268,8 @@ void scsi_bus_legacy_handle_cmdline(SCSIBus *bus, Error **errp)
             continue;
         }
         qemu_opts_loc_restore(dinfo->opts);
-        scsi_bus_legacy_add_drive(bus, dinfo->bdrv, unit, false, -1, NULL,
-                                  &err);
+        scsi_bus_legacy_add_drive(bus, blk_bs(blk_by_legacy_dinfo(dinfo)),
+                                  unit, false, -1, NULL, &err);
         if (err != NULL) {
             error_report("%s", error_get_pretty(err));
             error_propagate(errp, err);
hw/sd/milkymist-memcard.c +5 -2
index 2a40f92..501aa3a 100644
@@ -26,6 +26,7 @@
 #include "sysemu/sysemu.h"
 #include "trace.h"
 #include "qemu/error-report.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "hw/sd.h"
 
@@ -252,14 +253,16 @@ static int milkymist_memcard_init(SysBusDevice *dev)
 {
     MilkymistMemcardState *s = MILKYMIST_MEMCARD(dev);
     DriveInfo *dinfo;
+    BlockDriverState *bs;
 
     dinfo = drive_get_next(IF_SD);
-    s->card = sd_init(dinfo ? dinfo->bdrv : NULL, false);
+    bs = dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL;
+    s->card = sd_init(bs, false);
     if (s->card == NULL) {
         return -1;
     }
 
-    s->enabled = dinfo ? bdrv_is_inserted(dinfo->bdrv) : 0;
+    s->enabled = bs && bdrv_is_inserted(bs);
 
     memory_region_init_io(&s->regs_region, OBJECT(s), &memcard_mmio_ops, s,
             "milkymist-memcard", R_MAX * 4);
hw/sd/pl181.c +2 -1
index 462558b..0501d40 100644
@@ -7,6 +7,7 @@
  * This code is licensed under the GPL.
  */
 
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "hw/sysbus.h"
 #include "hw/sd.h"
@@ -490,7 +491,7 @@ static int pl181_init(SysBusDevice *sbd)
     sysbus_init_irq(sbd, &s->irq[1]);
     qdev_init_gpio_out(dev, s->cardstatus, 2);
     dinfo = drive_get_next(IF_SD);
-    s->card = sd_init(dinfo ? dinfo->bdrv : NULL, false);
+    s->card = sd_init(dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL, false);
     if (s->card == NULL) {
         return -1;
     }
hw/sd/sdhci.c +2 -1
index f9fe700..0b7d754 100644
@@ -23,6 +23,7 @@
  */
 
 #include "hw/hw.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "sysemu/dma.h"
 #include "qemu/timer.h"
@@ -1165,7 +1166,7 @@ static void sdhci_initfn(Object *obj)
     DriveInfo *di;
 
     di = drive_get_next(IF_SD);
-    s->card = sd_init(di ? di->bdrv : NULL, false);
+    s->card = sd_init(di ? blk_bs(blk_by_legacy_dinfo(di)) : NULL, false);
     if (s->card == NULL) {
         exit(1);
     }
hw/sd/ssi-sd.c +2 -1
index b012e57..6ae99e4 100644
@@ -10,6 +10,7 @@
  * GNU GPL, version 2 or (at your option) any later version.
  */
 
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "hw/ssi.h"
 #include "hw/sd.h"
@@ -255,7 +256,7 @@ static int ssi_sd_init(SSISlave *d)
 
     s->mode = SSI_SD_CMD;
     dinfo = drive_get_next(IF_SD);
-    s->sd = sd_init(dinfo ? dinfo->bdrv : NULL, true);
+    s->sd = sd_init(dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL, true);
     if (s->sd == NULL) {
         return -1;
     }
hw/sh4/r2d.c +3 -2
index 95c0246..d652619 100644
@@ -36,6 +36,7 @@
 #include "hw/loader.h"
 #include "hw/usb.h"
 #include "hw/block/flash.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "exec/address-spaces.h"
 
@@ -290,8 +291,8 @@ static void r2d_init(MachineState *machine)
     /* onboard flash memory */
     dinfo = drive_get(IF_PFLASH, 0, 0);
     pflash_cfi02_register(0x0, NULL, "r2d.flash", FLASH_SIZE,
-                          dinfo ? dinfo->bdrv : NULL, (16 * 1024),
-                          FLASH_SIZE >> 16,
+                          dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL,
+                          (16 * 1024), FLASH_SIZE >> 16,
                           1, 4, 0x0000, 0x0000, 0x0000, 0x0000,
                           0x555, 0x2aa, 0);
 
hw/usb/dev-storage.c +3 -1
index ae4efcb..525f657 100644
@@ -16,6 +16,7 @@
 #include "ui/console.h"
 #include "monitor/monitor.h"
 #include "sysemu/sysemu.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 
 //#define DEBUG_MSD
@@ -702,7 +703,8 @@ static USBDevice *usb_msd_init(USBBus *bus, const char *filename)
     if (!dev) {
         return NULL;
     }
-    if (qdev_prop_set_drive(&dev->qdev, "drive", dinfo->bdrv) < 0) {
+    if (qdev_prop_set_drive(&dev->qdev, "drive",
+                            blk_bs(blk_by_legacy_dinfo(dinfo))) < 0) {
         object_unparent(OBJECT(dev));
         return NULL;
     }
hw/xtensa/xtfpga.c +3 -1
index a2dff5a..7c4719e 100644
@@ -35,6 +35,7 @@
 #include "net/net.h"
 #include "hw/sysbus.h"
 #include "hw/block/flash.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "sysemu/char.h"
 #include "sysemu/device_tree.h"
@@ -229,7 +230,8 @@ static void lx_init(const LxBoardDesc *board, MachineState *machine)
     if (dinfo) {
         flash = pflash_cfi01_register(board->flash_base,
                 NULL, "lx60.io.flash", board->flash_size,
-                dinfo->bdrv, board->flash_sector_size,
+                blk_bs(blk_by_legacy_dinfo(dinfo)),
+                board->flash_sector_size,
                 board->flash_size / board->flash_sector_size,
                 4, 0x0000, 0x0000, 0x0000, 0x0000, be);
         if (flash == NULL) {
include/sysemu/blockdev.h +0 -1
index 2ed297b..75f6ac6 100644
@@ -30,7 +30,6 @@ typedef enum {
 } BlockInterfaceType;
 
 struct DriveInfo {
-    BlockDriverState *bdrv;
     char *id;
     const char *devaddr;
     BlockInterfaceType type;
Signature · 1 line
1.9.3
#53 lore raw

Re: [Qemu-devel] [PATCH 10/23] block: Eliminate DriveInfo member bdrv, use blk_by_legacy_dinfo()

Quoted 1,187 lines · Markus Armbruster
---
 blockdev.c                               |  3 +--
 hw/arm/collie.c                          |  9 +++++----
 hw/arm/gumstix.c                         |  5 +++--
 hw/arm/mainstone.c                       |  8 ++++----
 hw/arm/musicpal.c                        | 11 ++++++-----
 hw/arm/nseries.c                         |  6 ++++--
 hw/arm/omap1.c                           |  4 +++-
 hw/arm/omap2.c                           |  4 +++-
 hw/arm/omap_sx1.c                        |  9 +++++----
 hw/arm/pxa2xx.c                          |  7 +++++--
 hw/arm/spitz.c                           |  4 +++-
 hw/arm/versatilepb.c                     |  4 +++-
 hw/arm/vexpress.c                        |  4 +++-
 hw/arm/xilinx_zynq.c                     |  4 +++-
 hw/arm/z2.c                              |  7 ++++---
 hw/block/fdc.c                           | 16 +++++++++++-----
 hw/block/m25p80.c                        |  5 +++--
 hw/block/xen_disk.c                      |  2 +-
 hw/cris/axis_dev88.c                     |  3 ++-
 hw/display/tc6393xb.c                    |  4 +++-
 hw/i386/pc_sysfw.c                       |  3 ++-
 hw/ide/piix.c                            |  6 ++++--
 hw/ide/qdev.c                            |  4 +++-
 hw/isa/pc87312.c                         |  7 +++++--
 hw/lm32/lm32_boards.c                    | 13 +++++++------
 hw/lm32/milkymist.c                      |  7 ++++---
 hw/microblaze/petalogix_ml605_mmu.c      |  5 +++--
 hw/microblaze/petalogix_s3adsp1800_mmu.c |  5 +++--
 hw/mips/mips_malta.c                     |  4 +++-
 hw/mips/mips_r4k.c                       |  5 +++--
 hw/pci/pci-hotplug-old.c                 |  9 ++++++---
 hw/ppc/ppc405_boards.c                   | 25 ++++++++++++++++---------
 hw/ppc/spapr.c                           |  4 +++-
 hw/ppc/virtex_ml507.c                    |  5 +++--
 hw/scsi/scsi-bus.c                       |  5 +++--
 hw/sd/milkymist-memcard.c                |  7 +++++--
 hw/sd/pl181.c                            |  3 ++-
 hw/sd/sdhci.c                            |  3 ++-
 hw/sd/ssi-sd.c                           |  3 ++-
 hw/sh4/r2d.c                             |  5 +++--
 hw/usb/dev-storage.c                     |  4 +++-
 hw/xtensa/xtfpga.c                       |  4 +++-
 include/sysemu/blockdev.h                |  1 -
 43 files changed, 163 insertions(+), 93 deletions(-)
blockdev.c +1 -2
index 353563e..5c75abd 100644
@@ -219,7 +219,7 @@ static void bdrv_format_print(void *opaque, const char *name)
 
 void drive_del(DriveInfo *dinfo)
 {
-    blk_unref(dinfo->bdrv->blk);
+    blk_unref(blk_by_legacy_dinfo(dinfo));
 }
 
 typedef struct {
@@ -472,7 +472,6 @@ static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
 
     dinfo = g_malloc0(sizeof(*dinfo));
     dinfo->id = g_strdup(qemu_opts_id(opts));
-    dinfo->bdrv = bs;
     blk_set_legacy_dinfo(blk, dinfo);
 
     if (!file || !*file) {
hw/arm/collie.c +5 -4
index ed7851f..0247290 100644
@@ -15,6 +15,7 @@
 #include "strongarm.h"
 #include "hw/arm/arm.h"
 #include "hw/block/flash.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "exec/address-spaces.h"
 
@@ -41,13 +42,13 @@ static void collie_init(MachineState *machine)
 
     dinfo = drive_get(IF_PFLASH, 0, 0);
     pflash_cfi01_register(SA_CS0, NULL, "collie.fl1", 0x02000000,
-                    dinfo ? dinfo->bdrv : NULL, (64 * 1024),
-                    512, 4, 0x00, 0x00, 0x00, 0x00, 0);
+                    dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL,
+                    (64 * 1024), 512, 4, 0x00, 0x00, 0x00, 0x00, 0);
 
     dinfo = drive_get(IF_PFLASH, 0, 1);
     pflash_cfi01_register(SA_CS1, NULL, "collie.fl2", 0x02000000,
-                    dinfo ? dinfo->bdrv : NULL, (64 * 1024),
-                    512, 4, 0x00, 0x00, 0x00, 0x00, 0);
+                    dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL,
+                    (64 * 1024), 512, 4, 0x00, 0x00, 0x00, 0x00, 0);
 
     sysbus_create_simple("scoop", 0x40800000, NULL);
 
hw/arm/gumstix.c +3 -2
index 3f8465e..49f9339 100644
@@ -40,6 +40,7 @@
 #include "hw/block/flash.h"
 #include "hw/devices.h"
 #include "hw/boards.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "exec/address-spaces.h"
 #include "sysemu/qtest.h"
@@ -71,7 +72,7 @@ static void connex_init(MachineState *machine)
     be = 0;
 #endif
     if (!pflash_cfi01_register(0x00000000, NULL, "connext.rom", connex_rom,
-                               dinfo ? dinfo->bdrv : NULL,
+                               dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL,
                                sector_len, connex_rom / sector_len,
                                2, 0, 0, 0, 0, be)) {
         fprintf(stderr, "qemu: Error registering flash memory.\n");
@@ -109,7 +110,7 @@ static void verdex_init(MachineState *machine)
     be = 0;
 #endif
     if (!pflash_cfi01_register(0x00000000, NULL, "verdex.rom", verdex_rom,
-                               dinfo ? dinfo->bdrv : NULL,
+                               dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL,
                                sector_len, verdex_rom / sector_len,
                                2, 0, 0, 0, 0, be)) {
         fprintf(stderr, "qemu: Error registering flash memory.\n");
hw/arm/mainstone.c +4 -4
index 44f1873..fb17d85 100644
@@ -18,7 +18,7 @@
 #include "hw/devices.h"
 #include "hw/boards.h"
 #include "hw/block/flash.h"
-#include "sysemu/blockdev.h"
+#include "sysemu/block-backend.h"
 #include "hw/sysbus.h"
 #include "exec/address-spaces.h"
 #include "sysemu/qtest.h"
@@ -148,9 +148,9 @@ static void mainstone_common_init(MemoryRegion *address_space_mem,
         if (!pflash_cfi01_register(mainstone_flash_base[i], NULL,
                                    i ? "mainstone.flash1" : "mainstone.flash0",
                                    MAINSTONE_FLASH,
-                                   dinfo->bdrv, sector_len,
-                                   MAINSTONE_FLASH / sector_len, 4, 0, 0, 0, 0,
-                                   be)) {
+                                   blk_bs(blk_by_legacy_dinfo(dinfo)),
+                                   sector_len, MAINSTONE_FLASH / sector_len,
+                                   4, 0, 0, 0, 0, be)) {
             fprintf(stderr, "qemu: Error registering flash memory.\n");
             exit(1);
         }
hw/arm/musicpal.c +6 -5
index 6a134f2..6a41d9c 100644
@@ -22,6 +22,7 @@
 #include "hw/block/flash.h"
 #include "ui/console.h"
 #include "hw/i2c/i2c.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "exec/address-spaces.h"
 #include "ui/pixel_ops.h"
@@ -1630,7 +1631,9 @@ static void musicpal_init(MachineState *machine)
     /* Register flash */
     dinfo = drive_get(IF_PFLASH, 0, 0);
     if (dinfo) {
-        flash_size = bdrv_getlength(dinfo->bdrv);
+        BlockDriverState *bs = blk_bs(blk_by_legacy_dinfo(dinfo));
+
+        flash_size = bdrv_getlength(bs);
         if (flash_size != 8*1024*1024 && flash_size != 16*1024*1024 &&
             flash_size != 32*1024*1024) {
             fprintf(stderr, "Invalid flash image size\n");
@@ -1645,16 +1648,14 @@ static void musicpal_init(MachineState *machine)
 #ifdef TARGET_WORDS_BIGENDIAN
         pflash_cfi02_register(0x100000000ULL-MP_FLASH_SIZE_MAX, NULL,
                               "musicpal.flash", flash_size,
-                              dinfo->bdrv, 0x10000,
-                              (flash_size + 0xffff) >> 16,
+                              bs, 0x10000, (flash_size + 0xffff) >> 16,
                               MP_FLASH_SIZE_MAX / flash_size,
                               2, 0x00BF, 0x236D, 0x0000, 0x0000,
                               0x5555, 0x2AAA, 1);
 #else
         pflash_cfi02_register(0x100000000ULL-MP_FLASH_SIZE_MAX, NULL,
                               "musicpal.flash", flash_size,
-                              dinfo->bdrv, 0x10000,
-                              (flash_size + 0xffff) >> 16,
+                              bs, 0x10000, (flash_size + 0xffff) >> 16,
                               MP_FLASH_SIZE_MAX / flash_size,
                               2, 0x00BF, 0x236D, 0x0000, 0x0000,
                               0x5555, 0x2AAA, 0);
hw/arm/nseries.c +4 -2
index 4f092d6..2536078 100644
@@ -31,6 +31,7 @@
 #include "hw/hw.h"
 #include "hw/bt.h"
 #include "hw/loader.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "hw/sysbus.h"
 #include "exec/address-spaces.h"
@@ -172,8 +173,9 @@ static void n8x0_nand_setup(struct n800_s *s)
     qdev_prop_set_uint16(s->nand, "version_id", 0);
     qdev_prop_set_int32(s->nand, "shift", 1);
     dinfo = drive_get(IF_MTD, 0, 0);
-    if (dinfo && dinfo->bdrv) {
-        qdev_prop_set_drive_nofail(s->nand, "drive", dinfo->bdrv);
+    if (dinfo) {
+        qdev_prop_set_drive_nofail(s->nand, "drive",
+                                   blk_bs(blk_by_legacy_dinfo(dinfo)));
     }
     qdev_init_nofail(s->nand);
     sysbus_connect_irq(SYS_BUS_DEVICE(s->nand), 0,
hw/arm/omap1.c +3 -1
index e7cc5d7..e38e07f 100644
@@ -21,6 +21,7 @@
 #include "hw/arm/omap.h"
 #include "sysemu/sysemu.h"
 #include "hw/arm/soc_dma.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "qemu/range.h"
 #include "hw/sysbus.h"
@@ -3976,7 +3977,8 @@ struct omap_mpu_state_s *omap310_mpu_init(MemoryRegion *system_memory,
         fprintf(stderr, "qemu: missing SecureDigital device\n");
         exit(1);
     }
-    s->mmc = omap_mmc_init(0xfffb7800, system_memory, dinfo->bdrv,
+    s->mmc = omap_mmc_init(0xfffb7800, system_memory,
+                           blk_bs(blk_by_legacy_dinfo(dinfo)),
                            qdev_get_gpio_in(s->ih[1], OMAP_INT_OQN),
                            &s->drq[OMAP_DMA_MMC_TX],
                     omap_findclk(s, "mmc_ck"));
hw/arm/omap2.c +3 -1
index dc53a7a..e47dd63 100644
@@ -18,6 +18,7 @@
  * with this program; if not, see <http://www.gnu.org/licenses/>.
  */
 
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "hw/hw.h"
 #include "hw/arm/arm.h"
@@ -2459,7 +2460,8 @@ struct omap_mpu_state_s *omap2420_mpu_init(MemoryRegion *sysmem,
         fprintf(stderr, "qemu: missing SecureDigital device\n");
         exit(1);
     }
-    s->mmc = omap2_mmc_init(omap_l4tao(s->l4, 9), dinfo->bdrv,
+    s->mmc = omap2_mmc_init(omap_l4tao(s->l4, 9),
+                    blk_bs(blk_by_legacy_dinfo(dinfo)),
                     qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_MMC_IRQ),
                     &s->drq[OMAP24XX_DMA_MMC1_TX],
                     omap_findclk(s, "mmc_fclk"), omap_findclk(s, "mmc_iclk"));
hw/arm/omap_sx1.c +5 -4
index b4f6da6..f475afc 100644
@@ -31,6 +31,7 @@
 #include "hw/boards.h"
 #include "hw/arm/arm.h"
 #include "hw/block/flash.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "sysemu/qtest.h"
 #include "exec/address-spaces.h"
@@ -153,8 +154,8 @@ static void sx1_init(MachineState *machine, const int version)
     if ((dinfo = drive_get(IF_PFLASH, 0, fl_idx)) != NULL) {
         if (!pflash_cfi01_register(OMAP_CS0_BASE, NULL,
                                    "omap_sx1.flash0-1", flash_size,
-                                   dinfo->bdrv, sector_size,
-                                   flash_size / sector_size,
+                                   blk_bs(blk_by_legacy_dinfo(dinfo)),
+                                   sector_size, flash_size / sector_size,
                                    4, 0, 0, 0, 0, be)) {
             fprintf(stderr, "qemu: Error registering flash memory %d.\n",
                            fl_idx);
@@ -176,8 +177,8 @@ static void sx1_init(MachineState *machine, const int version)
 
         if (!pflash_cfi01_register(OMAP_CS1_BASE, NULL,
                                    "omap_sx1.flash1-1", flash1_size,
-                                   dinfo->bdrv, sector_size,
-                                   flash1_size / sector_size,
+                                   blk_bs(blk_by_legacy_dinfo(dinfo)),
+                                   sector_size, flash1_size / sector_size,
                                    4, 0, 0, 0, 0, be)) {
             fprintf(stderr, "qemu: Error registering flash memory %d.\n",
                            fl_idx);
hw/arm/pxa2xx.c +5 -2
index 557e0f1..7ec0da8 100644
@@ -14,6 +14,7 @@
 #include "hw/i2c/i2c.h"
 #include "hw/ssi.h"
 #include "sysemu/char.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 
 static struct {
@@ -2083,7 +2084,8 @@ PXA2xxState *pxa270_init(MemoryRegion *address_space,
         fprintf(stderr, "qemu: missing SecureDigital device\n");
         exit(1);
     }
-    s->mmc = pxa2xx_mmci_init(address_space, 0x41100000, dinfo->bdrv,
+    s->mmc = pxa2xx_mmci_init(address_space, 0x41100000,
+                    blk_bs(blk_by_legacy_dinfo(dinfo)),
                     qdev_get_gpio_in(s->pic, PXA2XX_PIC_MMC),
                     qdev_get_gpio_in(s->dma, PXA2XX_RX_RQ_MMCI),
                     qdev_get_gpio_in(s->dma, PXA2XX_TX_RQ_MMCI));
@@ -2214,7 +2216,8 @@ PXA2xxState *pxa255_init(MemoryRegion *address_space, unsigned int sdram_size)
         fprintf(stderr, "qemu: missing SecureDigital device\n");
         exit(1);
     }
-    s->mmc = pxa2xx_mmci_init(address_space, 0x41100000, dinfo->bdrv,
+    s->mmc = pxa2xx_mmci_init(address_space, 0x41100000,
+                    blk_bs(blk_by_legacy_dinfo(dinfo)),
                     qdev_get_gpio_in(s->pic, PXA2XX_PIC_MMC),
                     qdev_get_gpio_in(s->dma, PXA2XX_RX_RQ_MMCI),
                     qdev_get_gpio_in(s->dma, PXA2XX_TX_RQ_MMCI));
hw/arm/spitz.c +3 -1
index 03cc6ce..5d684a2 100644
@@ -25,6 +25,7 @@
 #include "block/block.h"
 #include "audio/audio.h"
 #include "hw/boards.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "hw/sysbus.h"
 #include "exec/address-spaces.h"
@@ -170,7 +171,8 @@ static int sl_nand_init(SysBusDevice *dev)
 
     s->ctl = 0;
     nand = drive_get(IF_MTD, 0, 0);
-    s->nand = nand_init(nand ? nand->bdrv : NULL, s->manf_id, s->chip_id);
+    s->nand = nand_init(nand ? blk_bs(blk_by_legacy_dinfo(nand)) : NULL,
+                        s->manf_id, s->chip_id);
 
     memory_region_init_io(&s->iomem, OBJECT(s), &sl_ops, s, "sl", 0x40);
     sysbus_init_mmio(dev, &s->iomem);
hw/arm/versatilepb.c +3 -1
index dea5fc7..c88be6b 100644
@@ -15,6 +15,7 @@
 #include "hw/pci/pci.h"
 #include "hw/i2c/i2c.h"
 #include "hw/boards.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "exec/address-spaces.h"
 #include "hw/block/flash.h"
@@ -337,7 +338,8 @@ static void versatile_init(MachineState *machine, int board_id)
 
     dinfo = drive_get(IF_PFLASH, 0, 0);
     if (!pflash_cfi01_register(VERSATILE_FLASH_ADDR, NULL, "versatile.flash",
-                          VERSATILE_FLASH_SIZE, dinfo ? dinfo->bdrv : NULL,
+                          VERSATILE_FLASH_SIZE,
+                          dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL,
                           VERSATILE_FLASH_SECT_SIZE,
                           VERSATILE_FLASH_SIZE / VERSATILE_FLASH_SECT_SIZE,
                           4, 0x0089, 0x0018, 0x0000, 0x0, 0)) {
hw/arm/vexpress.c +3 -1
index a88732c..a492c22 100644
@@ -30,6 +30,7 @@
 #include "hw/boards.h"
 #include "hw/loader.h"
 #include "exec/address-spaces.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "hw/block/flash.h"
 #include "sysemu/device_tree.h"
@@ -488,7 +489,8 @@ static pflash_t *ve_pflash_cfi01_register(hwaddr base, const char *name,
 {
     DeviceState *dev = qdev_create(NULL, "cfi.pflash01");
 
-    if (di && qdev_prop_set_drive(dev, "drive", di->bdrv)) {
+    if (di && qdev_prop_set_drive(dev, "drive",
+                                  blk_bs(blk_by_legacy_dinfo(di)))) {
         abort();
     }
 
hw/arm/xilinx_zynq.c +3 -1
index ba5aa82..78e6934 100644
@@ -22,6 +22,7 @@
 #include "sysemu/sysemu.h"
 #include "hw/boards.h"
 #include "hw/block/flash.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "hw/loader.h"
 #include "hw/ssi.h"
@@ -162,7 +163,8 @@ static void zynq_init(MachineState *machine)
 
     /* AMD */
     pflash_cfi02_register(0xe2000000, NULL, "zynq.pflash", FLASH_SIZE,
-                          dinfo ? dinfo->bdrv : NULL, FLASH_SECTOR_SIZE,
+                          dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL,
+                          FLASH_SECTOR_SIZE,
                           FLASH_SIZE/FLASH_SECTOR_SIZE, 1,
                           1, 0x0066, 0x0022, 0x0000, 0x0000, 0x0555, 0x2aa,
                               0);
hw/arm/z2.c +4 -3
index 36b3b50..9b38a2b 100644
@@ -20,6 +20,7 @@
 #include "hw/boards.h"
 #include "sysemu/sysemu.h"
 #include "hw/block/flash.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "ui/console.h"
 #include "audio/audio.h"
@@ -336,9 +337,9 @@ static void z2_init(MachineState *machine)
 
     if (!pflash_cfi01_register(Z2_FLASH_BASE,
                                NULL, "z2.flash0", Z2_FLASH_SIZE,
-                               dinfo ? dinfo->bdrv : NULL, sector_len,
-                               Z2_FLASH_SIZE / sector_len, 4, 0, 0, 0, 0,
-                               be)) {
+                               dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL,
+                               sector_len, Z2_FLASH_SIZE / sector_len,
+                               4, 0, 0, 0, 0, be)) {
         fprintf(stderr, "qemu: Error registering flash memory.\n");
         exit(1);
     }
hw/block/fdc.c +11 -5
index 490d127..19f215f 100644
@@ -33,6 +33,7 @@
 #include "qemu/timer.h"
 #include "hw/isa/isa.h"
 #include "hw/sysbus.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "sysemu/sysemu.h"
 #include "qemu/log.h"
@@ -2033,10 +2034,12 @@ ISADevice *fdctrl_init_isa(ISABus *bus, DriveInfo **fds)
     dev = DEVICE(isadev);
 
     if (fds[0]) {
-        qdev_prop_set_drive_nofail(dev, "driveA", fds[0]->bdrv);
+        qdev_prop_set_drive_nofail(dev, "driveA",
+                                   blk_bs(blk_by_legacy_dinfo(fds[0])));
     }
     if (fds[1]) {
-        qdev_prop_set_drive_nofail(dev, "driveB", fds[1]->bdrv);
+        qdev_prop_set_drive_nofail(dev, "driveB",
+                                   blk_bs(blk_by_legacy_dinfo(fds[1])));
     }
     qdev_init_nofail(dev);
 
@@ -2056,10 +2059,12 @@ void fdctrl_init_sysbus(qemu_irq irq, int dma_chann,
     fdctrl = &sys->state;
     fdctrl->dma_chann = dma_chann; /* FIXME */
     if (fds[0]) {
-        qdev_prop_set_drive_nofail(dev, "driveA", fds[0]->bdrv);
+        qdev_prop_set_drive_nofail(dev, "driveA",
+                                   blk_bs(blk_by_legacy_dinfo(fds[0])));
     }
     if (fds[1]) {
-        qdev_prop_set_drive_nofail(dev, "driveB", fds[1]->bdrv);
+        qdev_prop_set_drive_nofail(dev, "driveB",
+                                   blk_bs(blk_by_legacy_dinfo(fds[1])));
     }
     qdev_init_nofail(dev);
     sbd = SYS_BUS_DEVICE(dev);
@@ -2075,7 +2080,8 @@ void sun4m_fdctrl_init(qemu_irq irq, hwaddr io_base,
 
     dev = qdev_create(NULL, "SUNW,fdtwo");
     if (fds[0]) {
-        qdev_prop_set_drive_nofail(dev, "drive", fds[0]->bdrv);
+        qdev_prop_set_drive_nofail(dev, "drive",
+                                   blk_bs(blk_by_legacy_dinfo(fds[0])));
     }
     qdev_init_nofail(dev);
     sys = SYSBUS_FDC(dev);
hw/block/m25p80.c +3 -2
index 5893773..78280a8 100644
@@ -22,6 +22,7 @@
  */
 
 #include "hw/hw.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "hw/ssi.h"
 
@@ -624,9 +625,9 @@ static int m25p80_init(SSISlave *ss)
 
     dinfo = drive_get_next(IF_MTD);
 
-    if (dinfo && dinfo->bdrv) {
+    if (dinfo) {
         DB_PRINT_L(0, "Binding to IF_MTD drive\n");
-        s->bdrv = dinfo->bdrv;
+        s->bdrv = blk_bs(blk_by_legacy_dinfo(dinfo));
 
         /* FIXME: Move to late init */
         if (bdrv_read(s->bdrv, 0, s->storage, DIV_ROUND_UP(s->size,
hw/block/xen_disk.c +1 -1
index 6d474b9..b571bbe 100644
@@ -877,7 +877,7 @@ static int blk_connect(struct XenDevice *xendev)
     } else {
         /* setup via qemu cmdline -> already setup for us */
         xen_be_printf(&blkdev->xendev, 2, "get configured bdrv (cmdline setup)\n");
-        blkdev->bs = blkdev->dinfo->bdrv;
+        blkdev->bs = blk_bs(blk_by_legacy_dinfo(blkdev->dinfo));
         if (bdrv_is_read_only(blkdev->bs) && !readonly) {
             xen_be_printf(&blkdev->xendev, 0, "Unexpected read-only drive");
             blkdev->bs = NULL;
hw/cris/axis_dev88.c +2 -1
index 1849338..280722d 100644
@@ -30,6 +30,7 @@
 #include "hw/loader.h"
 #include "elf.h"
 #include "boot.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "exec/address-spaces.h"
 #include "sysemu/qtest.h"
@@ -282,7 +283,7 @@ void axisdev88_init(MachineState *machine)
 
       /* Attach a NAND flash to CS1.  */
     nand = drive_get(IF_MTD, 0, 0);
-    nand_state.nand = nand_init(nand ? nand->bdrv : NULL,
+    nand_state.nand = nand_init(nand ? blk_bs(blk_by_legacy_dinfo(nand)) : NULL,
                                 NAND_MFR_STMICRO, 0x39);
     memory_region_init_io(&nand_state.iomem, NULL, &nand_ops, &nand_state,
                           "nand", 0x05000000);
hw/display/tc6393xb.c +3 -1
index f4011d2..62d6663 100644
@@ -15,6 +15,7 @@
 #include "hw/block/flash.h"
 #include "ui/console.h"
 #include "ui/pixel_ops.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 
 #define IRQ_TC6393_NAND		0
@@ -576,7 +577,8 @@ TC6393xbState *tc6393xb_init(MemoryRegion *sysmem, uint32_t base, qemu_irq irq)
     s->sub_irqs = qemu_allocate_irqs(tc6393xb_sub_irq, s, TC6393XB_NR_IRQS);
 
     nand = drive_get(IF_MTD, 0, 0);
-    s->flash = nand_init(nand ? nand->bdrv : NULL, NAND_MFR_TOSHIBA, 0x76);
+    s->flash = nand_init(nand ? blk_bs(blk_by_legacy_dinfo(nand)) : NULL,
+                         NAND_MFR_TOSHIBA, 0x76);
 
     memory_region_init_io(&s->iomem, NULL, &tc6393xb_ops, s, "tc6393xb", 0x10000);
     memory_region_add_subregion(sysmem, base, &s->iomem);
hw/i386/pc_sysfw.c +2 -1
index 75a7ebb..6cd264a 100644
@@ -23,6 +23,7 @@
  * THE SOFTWARE.
  */
 
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "qemu/error-report.h"
 #include "hw/sysbus.h"
@@ -118,7 +119,7 @@ static void pc_system_flash_init(MemoryRegion *rom_memory)
          (unit < FLASH_MAP_UNIT_MAX &&
           (pflash_drv = drive_get(IF_PFLASH, 0, unit)) != NULL);
          ++unit) {
-        bdrv = pflash_drv->bdrv;
+        bdrv = blk_bs(blk_by_legacy_dinfo(pflash_drv));
         size = bdrv_getlength(bdrv);
         if (size < 0) {
             fatal_errmsg = g_strdup_printf("failed to get backing file size");
hw/ide/piix.c +4 -2
index 49e78a7..c6c256f 100644
@@ -27,6 +27,7 @@
 #include <hw/i386/pc.h>
 #include <hw/pci/pci.h>
 #include <hw/isa/isa.h>
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "sysemu/sysemu.h"
 #include "sysemu/dma.h"
@@ -178,9 +179,10 @@ int pci_piix3_xen_ide_unplug(DeviceState *dev)
     for (; i < 3; i++) {
         di = drive_get_by_index(IF_IDE, i);
         if (di != NULL && !di->media_cd) {
-            DeviceState *ds = bdrv_get_attached_dev(di->bdrv);
+            BlockDriverState *bs = blk_bs(blk_by_legacy_dinfo(di));
+            DeviceState *ds = bdrv_get_attached_dev(bs);
             if (ds) {
-                bdrv_detach_dev(di->bdrv, ds);
+                bdrv_detach_dev(bs, ds);
             }
             pci_ide->bus[di->bus].ifs[di->unit].bs = NULL;
             drive_del(di);
hw/ide/qdev.c +3 -1
index efab95b..75e8eb3 100644
@@ -20,6 +20,7 @@
 #include "sysemu/dma.h"
 #include "qemu/error-report.h"
 #include <hw/ide/internal.h>
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "hw/block/block.h"
 #include "sysemu/sysemu.h"
@@ -116,7 +117,8 @@ IDEDevice *ide_create_drive(IDEBus *bus, int unit, DriveInfo *drive)
 
     dev = qdev_create(&bus->qbus, drive->media_cd ? "ide-cd" : "ide-hd");
     qdev_prop_set_uint32(dev, "unit", unit);
-    qdev_prop_set_drive_nofail(dev, "drive", drive->bdrv);
+    qdev_prop_set_drive_nofail(dev, "drive",
+                               blk_bs(blk_by_legacy_dinfo(drive)));
     qdev_init_nofail(dev);
     return DO_UPCAST(IDEDevice, qdev, dev);
 }
hw/isa/pc87312.c +5 -2
index 9327c53..b691a0c 100644
@@ -25,6 +25,7 @@
 
 #include "hw/isa/pc87312.h"
 #include "qemu/error-report.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "sysemu/sysemu.h"
 #include "sysemu/char.h"
@@ -320,11 +321,13 @@ static void pc87312_realize(DeviceState *dev, Error **errp)
         qdev_prop_set_uint32(d, "irq", 6);
         drive = drive_get(IF_FLOPPY, 0, 0);
         if (drive != NULL) {
-            qdev_prop_set_drive_nofail(d, "driveA", drive->bdrv);
+            qdev_prop_set_drive_nofail(d, "driveA",
+                                       blk_bs(blk_by_legacy_dinfo(drive)));
         }
         drive = drive_get(IF_FLOPPY, 0, 1);
         if (drive != NULL) {
-            qdev_prop_set_drive_nofail(d, "driveB", drive->bdrv);
+            qdev_prop_set_drive_nofail(d, "driveB",
+                                       blk_bs(blk_by_legacy_dinfo(drive)));
         }
         qdev_init_nofail(d);
         s->fdc.dev = isa;
hw/lm32/lm32_boards.c +7 -6
index 0e01340..17c5610 100644
@@ -23,6 +23,7 @@
 #include "hw/devices.h"
 #include "hw/boards.h"
 #include "hw/loader.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "elf.h"
 #include "lm32_hwsetup.h"
@@ -118,9 +119,9 @@ static void lm32_evr_init(MachineState *machine)
     dinfo = drive_get(IF_PFLASH, 0, 0);
     /* Spansion S29NS128P */
     pflash_cfi02_register(flash_base, NULL, "lm32_evr.flash", flash_size,
-                          dinfo ? dinfo->bdrv : NULL, flash_sector_size,
-                          flash_size / flash_sector_size, 1, 2,
-                          0x01, 0x7e, 0x43, 0x00, 0x555, 0x2aa, 1);
+                          dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL,
+                          flash_sector_size, flash_size / flash_sector_size,
+                          1, 2, 0x01, 0x7e, 0x43, 0x00, 0x555, 0x2aa, 1);
 
     /* create irq lines */
     cpu_irq = qemu_allocate_irqs(cpu_irq_handler, cpu, 1);
@@ -220,9 +221,9 @@ static void lm32_uclinux_init(MachineState *machine)
     dinfo = drive_get(IF_PFLASH, 0, 0);
     /* Spansion S29NS128P */
     pflash_cfi02_register(flash_base, NULL, "lm32_uclinux.flash", flash_size,
-                          dinfo ? dinfo->bdrv : NULL, flash_sector_size,
-                          flash_size / flash_sector_size, 1, 2,
-                          0x01, 0x7e, 0x43, 0x00, 0x555, 0x2aa, 1);
+                          dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL,
+                          flash_sector_size, flash_size / flash_sector_size,
+                          1, 2, 0x01, 0x7e, 0x43, 0x00, 0x555, 0x2aa, 1);
 
     /* create irq lines */
     cpu_irq = qemu_allocate_irqs(cpu_irq_handler, env, 1);
hw/lm32/milkymist.c +4 -3
index 81c3933..904b9c0 100644
@@ -26,6 +26,7 @@
 #include "hw/boards.h"
 #include "hw/loader.h"
 #include "elf.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "milkymist-hw.h"
 #include "lm32.h"
@@ -125,9 +126,9 @@ milkymist_init(MachineState *machine)
     dinfo = drive_get(IF_PFLASH, 0, 0);
     /* Numonyx JS28F256J3F105 */
     pflash_cfi01_register(flash_base, NULL, "milkymist.flash", flash_size,
-                          dinfo ? dinfo->bdrv : NULL, flash_sector_size,
-                          flash_size / flash_sector_size, 2,
-                          0x00, 0x89, 0x00, 0x1d, 1);
+                          dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL,
+                          flash_sector_size, flash_size / flash_sector_size,
+                          2, 0x00, 0x89, 0x00, 0x1d, 1);
 
     /* create irq lines */
     cpu_irq = qemu_allocate_irqs(cpu_irq_handler, cpu, 1);
hw/microblaze/petalogix_ml605_mmu.c +3 -2
index 6843abf..2974791 100644
@@ -32,6 +32,7 @@
 #include "sysemu/sysemu.h"
 #include "hw/devices.h"
 #include "hw/boards.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "hw/char/serial.h"
 #include "exec/address-spaces.h"
@@ -112,8 +113,8 @@ petalogix_ml605_init(MachineState *machine)
      * 10th paremeter 0 means little-endian */
     pflash_cfi01_register(FLASH_BASEADDR,
                           NULL, "petalogix_ml605.flash", FLASH_SIZE,
-                          dinfo ? dinfo->bdrv : NULL, (64 * 1024),
-                          FLASH_SIZE >> 16,
+                          dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL,
+                          (64 * 1024), FLASH_SIZE >> 16,
                           2, 0x89, 0x18, 0x0000, 0x0, 0);
 
 
hw/microblaze/petalogix_s3adsp1800_mmu.c +3 -2
index 49dc6d1..a69301f 100644
@@ -30,6 +30,7 @@
 #include "sysemu/sysemu.h"
 #include "hw/devices.h"
 #include "hw/boards.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "exec/address-spaces.h"
 
@@ -92,8 +93,8 @@ petalogix_s3adsp1800_init(MachineState *machine)
     dinfo = drive_get(IF_PFLASH, 0, 0);
     pflash_cfi01_register(FLASH_BASEADDR,
                           NULL, "petalogix_s3adsp1800.flash", FLASH_SIZE,
-                          dinfo ? dinfo->bdrv : NULL, (64 * 1024),
-                          FLASH_SIZE >> 16,
+                          dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL,
+                          (64 * 1024), FLASH_SIZE >> 16,
                           1, 0x89, 0x18, 0x0000, 0x0, 1);
 
     dev = qdev_create(NULL, "xlnx.xps-intc");
hw/mips/mips_malta.c +3 -1
index cfb60af..9f84ad6 100644
@@ -44,6 +44,7 @@
 #include "elf.h"
 #include "hw/timer/mc146818rtc.h"
 #include "hw/timer/i8254.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "exec/address-spaces.h"
 #include "hw/sysbus.h"             /* SysBusDevice */
@@ -1035,7 +1036,8 @@ void mips_malta_init(MachineState *machine)
     }
 #endif
     fl = pflash_cfi01_register(FLASH_ADDRESS, NULL, "mips_malta.bios",
-                               BIOS_SIZE, dinfo ? dinfo->bdrv : NULL,
+                               BIOS_SIZE,
+                               dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL,
                                65536, fl_sectors,
                                4, 0x0000, 0x0000, 0x0000, 0x0000, be);
     bios = pflash_cfi01_get_memory(fl);
hw/mips/mips_r4k.c +3 -2
index 7120293..6fd69b9 100644
@@ -24,6 +24,7 @@
 #include "elf.h"
 #include "hw/timer/mc146818rtc.h"
 #include "hw/timer/i8254.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "exec/address-spaces.h"
 #include "sysemu/qtest.h"
@@ -240,8 +241,8 @@ void mips_r4k_init(MachineState *machine)
     } else if ((dinfo = drive_get(IF_PFLASH, 0, 0)) != NULL) {
         uint32_t mips_rom = 0x00400000;
         if (!pflash_cfi01_register(0x1fc00000, NULL, "mips_r4k.bios", mips_rom,
-                                   dinfo->bdrv, sector_len,
-                                   mips_rom / sector_len,
+                                   blk_bs(blk_by_legacy_dinfo(dinfo)),
+                                   sector_len, mips_rom / sector_len,
                                    4, 0, 0, 0, 0, be)) {
             fprintf(stderr, "qemu: Error registering flash memory.\n");
 	}
hw/pci/pci-hotplug-old.c +6 -3
index cf2caeb..e4d51de 100644
@@ -33,6 +33,7 @@
 #include "hw/scsi/scsi.h"
 #include "hw/virtio/virtio-blk.h"
 #include "qemu/config-file.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "qapi/error.h"
 
@@ -126,8 +127,9 @@ static int scsi_hot_add(Monitor *mon, DeviceState *adapter,
      */
     dinfo->unit = qemu_opt_get_number(dinfo->opts, "unit", -1);
     dinfo->bus = scsibus->busnr;
-    scsidev = scsi_bus_legacy_add_drive(scsibus, dinfo->bdrv, dinfo->unit,
-                                        false, -1, NULL, NULL);
+    scsidev = scsi_bus_legacy_add_drive(scsibus,
+                                        blk_bs(blk_by_legacy_dinfo(dinfo)),
+                                        dinfo->unit, false, -1, NULL, NULL);
     if (!scsidev) {
         return -1;
     }
@@ -247,7 +249,8 @@ static PCIDevice *qemu_pci_hot_add_storage(Monitor *mon,
             return NULL;
         }
         dev = pci_create(bus, devfn, "virtio-blk-pci");
-        if (qdev_prop_set_drive(&dev->qdev, "drive", dinfo->bdrv) < 0) {
+        if (qdev_prop_set_drive(&dev->qdev, "drive",
+                                blk_bs(blk_by_legacy_dinfo(dinfo))) < 0) {
             object_unparent(OBJECT(dev));
             dev = NULL;
             break;
hw/ppc/ppc405_boards.c +16 -9
index 11d3379..7ff5ee5 100644
@@ -33,6 +33,7 @@
 #include "qemu/log.h"
 #include "qemu/error-report.h"
 #include "hw/loader.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "exec/address-spaces.h"
 
@@ -225,17 +226,19 @@ static void ref405ep_init(MachineState *machine)
 #ifdef USE_FLASH_BIOS
     dinfo = drive_get(IF_PFLASH, 0, fl_idx);
     if (dinfo) {
-        bios_size = bdrv_getlength(dinfo->bdrv);
+        BlockDriverState *bs = blk_bs(blk_by_legacy_dinfo(dinfo));
+
+        bios_size = bdrv_getlength(bs);
         fl_sectors = (bios_size + 65535) >> 16;
 #ifdef DEBUG_BOARD_INIT
         printf("Register parallel flash %d size %lx"
                " at addr %lx '%s' %d\n",
                fl_idx, bios_size, -bios_size,
-               bdrv_get_device_name(dinfo->bdrv), fl_sectors);
+               bdrv_get_device_name(bs), fl_sectors);
 #endif
         pflash_cfi02_register((uint32_t)(-bios_size),
                               NULL, "ef405ep.bios", bios_size,
-                              dinfo->bdrv, 65536, fl_sectors, 1,
+                              bs, 65536, fl_sectors, 1,
                               2, 0x0001, 0x22DA, 0x0000, 0x0000, 0x555, 0x2AA,
                               1);
         fl_idx++;
@@ -547,7 +550,9 @@ static void taihu_405ep_init(MachineState *machine)
 #if defined(USE_FLASH_BIOS)
     dinfo = drive_get(IF_PFLASH, 0, fl_idx);
     if (dinfo) {
-        bios_size = bdrv_getlength(dinfo->bdrv);
+        BlockDriverState *bs = blk_bs(blk_by_legacy_dinfo(dinfo));
+
+        bios_size = bdrv_getlength(bs);
         /* XXX: should check that size is 2MB */
         //        bios_size = 2 * 1024 * 1024;
         fl_sectors = (bios_size + 65535) >> 16;
@@ -555,11 +560,11 @@ static void taihu_405ep_init(MachineState *machine)
         printf("Register parallel flash %d size %lx"
                " at addr %lx '%s' %d\n",
                fl_idx, bios_size, -bios_size,
-               bdrv_get_device_name(dinfo->bdrv), fl_sectors);
+               bdrv_get_device_name(bs), fl_sectors);
 #endif
         pflash_cfi02_register((uint32_t)(-bios_size),
                               NULL, "taihu_405ep.bios", bios_size,
-                              dinfo->bdrv, 65536, fl_sectors, 1,
+                              bs, 65536, fl_sectors, 1,
                               4, 0x0001, 0x22DA, 0x0000, 0x0000, 0x555, 0x2AA,
                               1);
         fl_idx++;
@@ -593,7 +598,9 @@ static void taihu_405ep_init(MachineState *machine)
     /* Register Linux flash */
     dinfo = drive_get(IF_PFLASH, 0, fl_idx);
     if (dinfo) {
-        bios_size = bdrv_getlength(dinfo->bdrv);
+        BlockDriverState *bs = blk_bs(blk_by_legacy_dinfo(dinfo));
+
+        bios_size = bdrv_getlength(bs);
         /* XXX: should check that size is 32MB */
         bios_size = 32 * 1024 * 1024;
         fl_sectors = (bios_size + 65535) >> 16;
@@ -601,10 +608,10 @@ static void taihu_405ep_init(MachineState *machine)
         printf("Register parallel flash %d size %lx"
                " at addr " TARGET_FMT_lx " '%s'\n",
                fl_idx, bios_size, (target_ulong)0xfc000000,
-               bdrv_get_device_name(dinfo->bdrv));
+               bdrv_get_device_name(bs));
 #endif
         pflash_cfi02_register(0xfc000000, NULL, "taihu_405ep.flash", bios_size,
-                              dinfo->bdrv, 65536, fl_sectors, 1,
+                              bs, 65536, fl_sectors, 1,
                               4, 0x0001, 0x22DA, 0x0000, 0x0000, 0x555, 0x2AA,
                               1);
         fl_idx++;
hw/ppc/spapr.c +3 -1
index 2ab4460..a577812 100644
@@ -29,6 +29,7 @@
 #include "hw/fw-path-provider.h"
 #include "elf.h"
 #include "net/net.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "sysemu/cpus.h"
 #include "sysemu/kvm.h"
@@ -925,7 +926,8 @@ static void spapr_create_nvram(sPAPREnvironment *spapr)
     DriveInfo *dinfo = drive_get(IF_PFLASH, 0, 0);
 
     if (dinfo) {
-        qdev_prop_set_drive_nofail(dev, "drive", dinfo->bdrv);
+        qdev_prop_set_drive_nofail(dev, "drive",
+                                   blk_bs(blk_by_legacy_dinfo(dinfo)));
     }
 
     qdev_init_nofail(dev);
hw/ppc/virtex_ml507.c +3 -2
index 0de5148..a0ce447 100644
@@ -39,6 +39,7 @@
 #include "hw/ppc/ppc4xx.h"
 #include "ppc405.h"
 
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "qapi/qmp/qerror.h"
 
@@ -227,8 +228,8 @@ static void virtex_init(MachineState *machine)
 
     dinfo = drive_get(IF_PFLASH, 0, 0);
     pflash_cfi01_register(PFLASH_BASEADDR, NULL, "virtex.flash", FLASH_SIZE,
-                          dinfo ? dinfo->bdrv : NULL, (64 * 1024),
-                          FLASH_SIZE >> 16,
+                          dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL,
+                          (64 * 1024), FLASH_SIZE >> 16,
                           1, 0x89, 0x18, 0x0000, 0x0, 1);
 
     cpu_irq = (qemu_irq *) &env->irq_inputs[PPC40x_INPUT_INT];
hw/scsi/scsi-bus.c +3 -2
index 954c607..f5156ae 100644
@@ -3,6 +3,7 @@
 #include "hw/scsi/scsi.h"
 #include "block/scsi.h"
 #include "hw/qdev.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "trace.h"
 #include "sysemu/dma.h"
@@ -267,8 +268,8 @@ void scsi_bus_legacy_handle_cmdline(SCSIBus *bus, Error **errp)
             continue;
         }
         qemu_opts_loc_restore(dinfo->opts);
-        scsi_bus_legacy_add_drive(bus, dinfo->bdrv, unit, false, -1, NULL,
-                                  &err);
+        scsi_bus_legacy_add_drive(bus, blk_bs(blk_by_legacy_dinfo(dinfo)),
+                                  unit, false, -1, NULL, &err);
         if (err != NULL) {
             error_report("%s", error_get_pretty(err));
             error_propagate(errp, err);
hw/sd/milkymist-memcard.c +5 -2
index 2a40f92..501aa3a 100644
@@ -26,6 +26,7 @@
 #include "sysemu/sysemu.h"
 #include "trace.h"
 #include "qemu/error-report.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "hw/sd.h"
 
@@ -252,14 +253,16 @@ static int milkymist_memcard_init(SysBusDevice *dev)
 {
     MilkymistMemcardState *s = MILKYMIST_MEMCARD(dev);
     DriveInfo *dinfo;
+    BlockDriverState *bs;
 
     dinfo = drive_get_next(IF_SD);
-    s->card = sd_init(dinfo ? dinfo->bdrv : NULL, false);
+    bs = dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL;
+    s->card = sd_init(bs, false);
     if (s->card == NULL) {
         return -1;
     }
 
-    s->enabled = dinfo ? bdrv_is_inserted(dinfo->bdrv) : 0;
+    s->enabled = bs && bdrv_is_inserted(bs);
 
     memory_region_init_io(&s->regs_region, OBJECT(s), &memcard_mmio_ops, s,
             "milkymist-memcard", R_MAX * 4);
hw/sd/pl181.c +2 -1
index 462558b..0501d40 100644
@@ -7,6 +7,7 @@
  * This code is licensed under the GPL.
  */
 
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "hw/sysbus.h"
 #include "hw/sd.h"
@@ -490,7 +491,7 @@ static int pl181_init(SysBusDevice *sbd)
     sysbus_init_irq(sbd, &s->irq[1]);
     qdev_init_gpio_out(dev, s->cardstatus, 2);
     dinfo = drive_get_next(IF_SD);
-    s->card = sd_init(dinfo ? dinfo->bdrv : NULL, false);
+    s->card = sd_init(dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL, false);
     if (s->card == NULL) {
         return -1;
     }
hw/sd/sdhci.c +2 -1
index f9fe700..0b7d754 100644
@@ -23,6 +23,7 @@
  */
 
 #include "hw/hw.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "sysemu/dma.h"
 #include "qemu/timer.h"
@@ -1165,7 +1166,7 @@ static void sdhci_initfn(Object *obj)
     DriveInfo *di;
 
     di = drive_get_next(IF_SD);
-    s->card = sd_init(di ? di->bdrv : NULL, false);
+    s->card = sd_init(di ? blk_bs(blk_by_legacy_dinfo(di)) : NULL, false);
     if (s->card == NULL) {
         exit(1);
     }
hw/sd/ssi-sd.c +2 -1
index b012e57..6ae99e4 100644
@@ -10,6 +10,7 @@
  * GNU GPL, version 2 or (at your option) any later version.
  */
 
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "hw/ssi.h"
 #include "hw/sd.h"
@@ -255,7 +256,7 @@ static int ssi_sd_init(SSISlave *d)
 
     s->mode = SSI_SD_CMD;
     dinfo = drive_get_next(IF_SD);
-    s->sd = sd_init(dinfo ? dinfo->bdrv : NULL, true);
+    s->sd = sd_init(dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL, true);
     if (s->sd == NULL) {
         return -1;
     }
hw/sh4/r2d.c +3 -2
index 95c0246..d652619 100644
@@ -36,6 +36,7 @@
 #include "hw/loader.h"
 #include "hw/usb.h"
 #include "hw/block/flash.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "exec/address-spaces.h"
 
@@ -290,8 +291,8 @@ static void r2d_init(MachineState *machine)
     /* onboard flash memory */
     dinfo = drive_get(IF_PFLASH, 0, 0);
     pflash_cfi02_register(0x0, NULL, "r2d.flash", FLASH_SIZE,
-                          dinfo ? dinfo->bdrv : NULL, (16 * 1024),
-                          FLASH_SIZE >> 16,
+                          dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL,
+                          (16 * 1024), FLASH_SIZE >> 16,
                           1, 4, 0x0000, 0x0000, 0x0000, 0x0000,
                           0x555, 0x2aa, 0);
 
hw/usb/dev-storage.c +3 -1
index ae4efcb..525f657 100644
@@ -16,6 +16,7 @@
 #include "ui/console.h"
 #include "monitor/monitor.h"
 #include "sysemu/sysemu.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 
 //#define DEBUG_MSD
@@ -702,7 +703,8 @@ static USBDevice *usb_msd_init(USBBus *bus, const char *filename)
     if (!dev) {
         return NULL;
     }
-    if (qdev_prop_set_drive(&dev->qdev, "drive", dinfo->bdrv) < 0) {
+    if (qdev_prop_set_drive(&dev->qdev, "drive",
+                            blk_bs(blk_by_legacy_dinfo(dinfo))) < 0) {
         object_unparent(OBJECT(dev));
         return NULL;
     }
hw/xtensa/xtfpga.c +3 -1
index a2dff5a..7c4719e 100644
@@ -35,6 +35,7 @@
 #include "net/net.h"
 #include "hw/sysbus.h"
 #include "hw/block/flash.h"
+#include "sysemu/block-backend.h"
 #include "sysemu/blockdev.h"
 #include "sysemu/char.h"
 #include "sysemu/device_tree.h"
@@ -229,7 +230,8 @@ static void lx_init(const LxBoardDesc *board, MachineState *machine)
     if (dinfo) {
         flash = pflash_cfi01_register(board->flash_base,
                 NULL, "lx60.io.flash", board->flash_size,
-                dinfo->bdrv, board->flash_sector_size,
+                blk_bs(blk_by_legacy_dinfo(dinfo)),
+                board->flash_sector_size,
                 board->flash_size / board->flash_sector_size,
                 4, 0x0000, 0x0000, 0x0000, 0x0000, be);
         if (flash == NULL) {
include/sysemu/blockdev.h +0 -1
index 2ed297b..75f6ac6 100644
@@ -30,7 +30,6 @@ typedef enum {
 } BlockInterfaceType;
 
 struct DriveInfo {
-    BlockDriverState *bdrv;
     char *id;
     const char *devaddr;
     BlockInterfaceType type;
Signature · 1 line
1.9.3

I have trouble to review this as I don't understand the qdevs parts. Maybe someone else could have a look at it.

#54 lore raw

Re: [Qemu-devel] [PATCH 10/23] block: Eliminate DriveInfo member bdrv, use blk_by_legacy_dinfo()

Quoted 2 lines · Benoît Canet

I have trouble to review this as I don't understand the qdevs parts. Maybe someone else could have a look at it.

The patch is big, but all it really does is replacing

    dinfo->bdrv

by

blk_bs(blk_legacy_dinfo(dinfo))

Line wrapping muddies the waters a bit. I also omit tests whether dinfo->bdrv is null, because it never is.

#55 lore raw

Re: [Qemu-devel] [PATCH 10/23] block: Eliminate DriveInfo member bdrv, use blk_by_legacy_dinfo()

In reply to Markus Armbruster
Quoted 2 lines

+ blk_bs(blk_by_legacy_dinfo(dinfo)));

This seems to be a fairly common pattern: "blk_bs(blk_by_legacy_dinfo())". How about a helper function ?

#56 lore raw

Re: [Qemu-devel] [PATCH 10/23] block: Eliminate DriveInfo member bdrv, use blk_by_legacy_dinfo()

Quoted 4 lines · Benoît Canet
Quoted 1 line

+ blk_bs(blk_by_legacy_dinfo(dinfo)));

This seems to be a fairly common pattern: "blk_bs(blk_by_legacy_dinfo())". How about a helper function ?

Yes, except the pattern is going to evaporate in patch 14 :)

#57 lore raw

Re: [Qemu-devel] [PATCH 10/23] block: Eliminate DriveInfo member bdrv, use blk_by_legacy_dinfo()

Quoted 8 lines · Markus Armbruster
Quoted 4 lines · Benoît Canet
Quoted 1 line

+ blk_bs(blk_by_legacy_dinfo(dinfo)));

This seems to be a fairly common pattern: "blk_bs(blk_by_legacy_dinfo())". How about a helper function ?

Yes, except the pattern is going to evaporate in patch 14 :)

haha

#58 lore raw

Re: [Qemu-devel] [PATCH 10/23] block: Eliminate DriveInfo member bdrv, use blk_by_legacy_dinfo()

Quoted 11 lines · Benoît Canet
Quoted 8 lines · Markus Armbruster
Quoted 4 lines · Benoît Canet
Quoted 1 line

+ blk_bs(blk_by_legacy_dinfo(dinfo)));

This seems to be a fairly common pattern: "blk_bs(blk_by_legacy_dinfo())". How about a helper function ?

Yes, except the pattern is going to evaporate in patch 14 :)

haha

Still, worth mentioning this fact in the commit message, rather than making reviewers guess at it (that is, add a sentence something like:
This commit mechanically introduces long lines via repetitive pattern replacement that will be shortened in a later patch

Signature · 2 lines
Eric Blake   eblake redhat com    +1-919-301-3266
Libvirt virtualization library http://libvirt.org
#59 lore raw

Re: [Qemu-devel] [PATCH 10/23] block: Eliminate DriveInfo member bdrv, use blk_by_legacy_dinfo()

Quoted 9 lines · Eric Blake
Quoted 8 lines · Benoît Canet
Quoted 7 lines · Markus Armbruster
Quoted 4 lines · Benoît Canet
Quoted 1 line

+ blk_bs(blk_by_legacy_dinfo(dinfo)));

This seems to be a fairly common pattern: "blk_bs(blk_by_legacy_dinfo())". How about a helper function ?

Quoted 8 lines
Quoted 3 lines
Quoted 1 line

Yes, except the pattern is going to evaporate in patch 14 :)

haha

Still, worth mentioning this fact in the commit message, rather than making reviewers guess at it (that is, add a sentence something like:
This commit mechanically introduces long lines via repetitive pattern replacement that will be shortened in a later patch

I can do that.