I'm doing some tests involving data corruption from unsafely removing a usb drive, but I need a way to consistently remove the drive at a specific time. Is there a command that's equivalent to physically yanking the drive out without flushing any buffers or caches?
Some (but few) USB hubs have hardware support for port power control. If you're lucky enough to have one that implements that feature, then you could power off an individual port to mimic removing the device that is plugged into that port.
See the follow repo for the source code for a program that would enable you to control that feature (if present): https://github.com/codazoda/hub-ctrl.c
A block device simulator might work better than a real USB device for this type of research.
It should be possible to set up a virtual block device, create a file system on it, copy some files to it or do other write activity, and take snapshots of the device at random times.
The trick is that you need to reach into the device and freeze it and then take a snapshot, rather than reading the device while the writes are occurring.
It may also help if you can limit write speed to the device.
It is possible some of the filesystem authors have already created a testbed for this sort of corruption. (Thanks @Austin Hemmelgam) The dm_log_writes device mapper component goes a step beyond a virtual block device and gives you a stream of writes. You could easily snip this stream at any (all?) point and replay it to get your yank corrupted filesystem.
A (DIY) hardware solution would be to put a switch the 5V line of a USB extension cable programmatically. I'd use either:
- a normally-closed reed relay with a 5V coil voltage, and drive it with my usual trick when I need 1-2 bits of hardware IO: the status lines of a USB-232 adaptor. That's easy to write to from pretty much any programming language.
- an optoisolator, though the ones I use in this project to fire a camera (the circuit would easily adapt) may not handle the current drawn by a USB stick.