Disable write-caching for removable storage devices

This is a constant annoyance I have with my Manjaro systems, and with Linux in general. It seems that whenever my desktop environment (Plasma) mounts removable devices, such as flash drives or SSDs, for some reason it thinks it’s a good idea to cache writes to it. Is there a way to disable this?

What I’m trying to prevent from happening are two things:

  • data loss if the drive was removed without ejecting/unmounting
  • Misleading “write speed” displays and progress bars.

I don’t usually mount my removable devices via command line, so I’m not sure if this also happens if I mount it that way. Also, I still want write-caching for internal drives.

There is an AUR package exactly for that: udev-usb-sync. Or you can do it manually, because the only thing it makes is to put /etc/udev/rules.d/99-usb-sync.rules

# rule to disable write cache for usb storage
# requires hdparm to be installed
ACTION=="add|change", KERNEL=="sd[a-z]", ENV{ID_USB_TYPE}=="disk", RUN+="/usr/bin/hdparm -W 0 /dev/%k"

The reason for this behavior is a very large RAM nowadays when it comes to caching (here “dirty cache”). So on systems with 16GB+ RAM there needs to be adjustments for async writes.

Here is a helper script which does it actually:

That actually disables the internal cache of the disk, not the dirty cache.

4 Likes
1 Like

I looked at the script. To be honest, I’m not sure what I’m supposed to be changing and to what. is it the dirty bytes?

The script suggested that I set it to 419430400, where previously it was 20. Doesn’t this make the problem worse?

Just use the recommend values, which are partially calculated according to your RAM. It simply writes these 2 files:

/etc/sysctl.d/99-maxperfwiz.conf
/etc/udev/rules.d/66-maxperfwiz.rules

which applies on the next boot. If something goes wrong, what I hardly believe, you can simply remove the files and reboot.

I’ve tried hdparm method and it didn’t work for me.

I was copying large files from HDD to USB sticks that had 10-20 Mb/s write speeds.
Without any udev rules applied plasma showed absolutely insane speeds like 600-800 Mb/s. With hdparm udev rule applied shown speeds were about 200 Mb/s, which equals to reading speed of my HDD. Sync udev rule produced basically the same result (~ 200 Mb/s).

Method that worked for me was usb-dirty-pages-udev. It shows accurate write speeds for USB sticks and as soon as copiyng progress bar reaches 100% flash drives can be safely removed immediately. Although that method requires kernel >= 6.2.

And all udev rules require USB disks to be automounted to work.