Linux – Gracefully shutting down USB disk drives before disconnect

hard-disklinuxusb-drive

With Fedora 27, when disconnecting an external USB disk drive the journal records lines like these:

May 07 22:29:11 usb 2-3.1: USB disconnect, device number 23
May 07 22:29:11 sd 3:0:0:0: [sdb] Synchronizing SCSI cache
May 07 22:29:11 sd 3:0:0:0: [sdb] Synchronize Cache(10) failed:
                            Result: hostbyte=DID_NO_CONNECT driverbyte=DRIVER_OK

What is one supposed to do about this?

why does the system/kernel tries to synchronize the cache after the drive is already disconnected?

Is it possible to gracefully shutdown the USB disk before the disconnect? For example with a command that issues the Synchronize-Cache command and then spins down the drive.

This would perhaps also reduce mechanical stress on the drive as the sudden power-loss with spinning disk isn't necessarily optimal.

Edit: An eject /dev/sdb is ineffective, i.e. the above kernel messages still show up on device unplug and the disk keeps spinning. Instead the eject command yields these kernel log messages:

May 18 17:26:06  ldm_validate_partition_table(): Disk read failed.
May 18 17:26:06  Dev sdb: unable to read RDB block 0
May 18 17:26:06   sdb: unable to read partition table
May 18 17:26:06  ldm_validate_partition_table(): Disk read failed.
May 18 17:26:06  Dev sdb: unable to read RDB block 0
May 18 17:26:06   sdb: unable to read partition table

Edit: Powering the disk down with udisksctl power-off --block-device /dev/sdb does work:

May 19 08:08:21  udisksd[9447]: Successfully sent SCSI command SYNCHRONIZE CACHE 
                                to /dev/sdb
May 19 08:08:21  udisksd[9447]: Successfully sent SCSI command START STOP UNIT
                                to /dev/sdb
May 19 08:08:21  kernel: sd 3:0:0:0: [sdb] Synchronizing SCSI cache
May 19 08:08:21  udisksd[9447]: Powered off /dev/sdb - successfully wrote
         to sysfs path /sys/devices/pci0000:00/0000:00:14.0/usb2/2-3/2-3.1/remove
May 19 08:08:21  kernel: usb 2-3.1: USB disconnect, device number 60

And indeed, the disk then powers down.

Best Answer

Use udisksctl to power off the drive:

   power-off
       Arranges for the drive to be safely removed and powered off. On the OS side this includes ensuring that
       no process is using the drive, then requesting that in-flight buffers and caches are committed to stable
       storage. The exact steps for powering off the drive depends on the drive itself and the interconnect
       used. For drives connected through USB, the effect is that the USB device will be deconfigured followed
       by disabling the upstream hub port it is connected to.

so e.g.

udisksctl power-off --block-device /dev/sdb

You can run the command as a regular user, no need for root access.
If you prefer a gui, gnome disks has a button to "power off this disk".

Related Question