Search code examples
linuxusbqemukvm

How to create **removable** USB stick in virtual qemu machine?


I am writing a program that needs to check if there are removable drives. It uses /sys/class/block to identify these devices by checking if the special file removable is present and contains a number that is not zero. For example, on my system, /sys/class/block/sdc/removable contains a zero since it is a SATA hard drive, while the USB stick in /sys/class/block/sdd/removable contains 1.

I am testing my program on a virtual machine using qemu. I got so far as to have entries in /sys/class/block by disabling CONFIG_SYSFS_DEPRECATED in the kernel configuration (kernel 6.1.14) and adding a USB drive like so:

kvm -bios /usr/share/qemu/OVMF.fd \
    -net none \
    -drive file=root.img,format=raw \
    -m 1G -cpu host -smp 2 \
    -drive if=none,id=stick,format=raw,file=usb.img \
    -device nec-usb-xhci,id=xhci \
    -device usb-storage,bus=xhci.0,drive=stick

taken from the QEmu documentation here. The USB stick works and can be mounted/unmounted, but there is no removable entry in the sys filesystem. What am I missing?


Solution

  • The usb-storage device defaults to behaving like a USB hard disk, which typically will not set the RMB (removable media bit) in the information it reports to the guest. However you can configure it to set RMB, making it behave like a typical USB thumb drive instead.

    You can do this by adding removable=on to your usb-storage device suboptions, so in your case:

    -device usb-storage,bus=xhci.0,drive=stick,removable=on