I have a number of USB hard disks. Like, I suppose, mostly everyone who reads this blog. Unlike many people who do, however, for whatever reason I decided to create LVM volumes on most of my USB hard disks. The unfortunate result is that these now contain a lot of data with a somewhat less than efficient partitioning system.

I don't really care much, but it's somewhat annoying, not in the least because disconnecting an LVM device isn't as easy as it used to be; originally you could just run the lvm2 init script with the stop argument, but that isn't the case anymore today. That is, you can run that, but it won't help you because all that does, effectively, is exit 0.

So what do you do instead? This:

  • First, make sure your devices aren't mounted anymore. Note: do not use lazy umount for a device that you're going to remove from your system! I've seen a few forum posts here and there of people who think it's safe to use umount -l for a device they're about to remove from their system which is still in use. It's not. It's a good way to cause data loss.

    Instead, make sure your partitions are really unmounted. Use fuser -m if you need to figure out which process is still using the partition.

  • Next, use vgchange -a n. This will cause LVM to deactivate any logical volumes and volume groups that aren't open any more. Note that this can't work if you haven't done the above. Also note that this doesn't cause the devices to be gone when you do things like vgs or so. They're still there, they're just not in use anymore. Skipping this step isn't recommended, though; it will make LVM unhappy, mostly because some caches are still in use.
  • Remove your device from the computer. That is, disconnect the USB cable, or call nbd-client -d, or do whatever you need to make sure the PV isn't connected to your system anymore.
  • Finally, run vgchange --refresh. This will cause the system to rescan all partitions, notice that the volume groups which you've just disconnected aren't there anymore, and remove them from configuration.

Voila, your LVM volume group is no longer available, and you've not suffered data loss. Kewl.

Note: I don't know what the lvm2 init script used to do. I suspect there's another way which doesn't require the --refresh step. I don't think it matters all that much, though. This works, and is safe. That being said, comments are welcome...