When a CD-ROM device is created without a drive (an empty CD-ROM),
the realize function allocates an anonymous BlockBackend with
blk_new() and attaches it to the device with blk_attach_dev().
blk_new() returns the backend with refcnt == 1 (the creation
reference owned by the caller) and blk_attach_dev() takes an
additional reference for the device. Since the creation reference
is never released, blk_detach_dev() on unplug only drops the
device's reference and the BlockBackend is leaked.
This is not just a memory leak: if a medium was inserted into the
empty drive before the unplug, the leaked BlockBackend keeps the
medium's blockdev node in use forever, so a subsequent blockdev-del
of that node fails with "Node ... is in use".
Two hot-unpluggable devices are affected, scsi-cd and the Xen
CD-ROM. Both are fixed by releasing the creation reference right
after blk_attach_dev(), matching the idiom already used in
set_drive_helper() in hw/core/qdev-properties-system.c.
While touching xen_cdrom_realize(), patch 2 also fixes an inverted
error check on the return value of blk_attach_dev() (success was
reported as an error and failure silently ignored); since the only
failure path cannot be taken here, it is replaced with an assertion,
matching the other empty-drive realize paths.
Patch 4 adds a qtest regression test for the scsi-cd case: create an
empty scsi-cd, insert a medium, unplug the device, and verify that
the medium's node can then be deleted. The xen-block case is not
covered because Xen devices cannot be exercised under qtest.
Note that floppy_drive_realize(), swim_drive_realize() and
ide_dev_initfn() leak the creation reference in the same way, but
these devices do not support hot unplug, so the leaked reference has
no practical consequence. They are left as they are by this series.
Mitsuru Kariya (4):
scsi-disk: Fix BlockBackend leak on unplug of empty CD-ROM
xen-block: Fix inverted error check in xen_cdrom_realize()
xen-block: Fix BlockBackend leak on unplug of empty CD-ROM
tests/qtest: drive_del: Add regression test for empty CD-ROM
BlockBackend leak
hw/block/xen-block.c | 6 ++--
hw/scsi/scsi-disk.c | 1 +
tests/qtest/drive_del-test.c | 58 ++++++++++++++++++++++++++++++++++++
3 files changed, 61 insertions(+), 4 deletions(-)
base-commit: eca2c16212ef9dcb0871de39bb9d1c2efebe76be
--
2.43.0