Skip to main content

Trimming SD Card with Raspberry Pi

Author
Kuan-Yi Li

Trim improves the lifetime and performance of flash-based media. However, most, if not all, USB card readers do not support this operation.

Raspberry Pi is fairly easy to get nowadays. Through its native MMC/SD/SDIO controller, we can perform trim/discard on SD cards.

What Hardware Do You Need
#

Besides a working PC, you’ll need

  1. Raspberry Pi
    • preferably a Pi 4B or Pi 5
  2. SD card to be trimmed
  3. SD card reader (internal or external)
    • does NOT require TRIM support
    • just used to flash an image to SD card
  4. USB-C cable
    • to connect Pi to your PC

Steps
#

Download the boot image, which includes util-linux binaries, of mass-storage-gadget64. Flash it to your SD card with whatever flasher (balenaEtcher, Raspberry Pi Imager, dd, etc.) of your choice.

Plug that SD card to Raspberry Pi and power it up by connecting it to your PC.

Pi will boot mass-storage-gadget64 to RAM and present itself as a USB gadget. Leave mass storage device alone. What we’re interested in is the debug console.

Connect to the debug console.

tio /dev/ttyACM0

There are a variety of terminal programs to do this. See Adafruit serial console tutorial for Linux, macOS and Windows.

Possible catches:

  • Permission denied opening /dev/ttyACM0
    • Possible solution 1: add user to allowed group (e.g. dialout on Debian-based systems)
    • Possible solution 2: use sudo
    • Possible solution 3: modify udev rules
  • Your system may consider ACM device as a modem and try to send AT command to it
    • Symptom 1: device or resource busy
    • Solution 1: wait some seconds and try again
    • Symptom 2: CLI misbehaves (caused by AT command residue)
    • Solution 2: press Ctrl-C a few times, until you see a shell prompt

Perform full SD card trim/discard by running the following command in debug console.

blkdiscard --force /dev/mmcblk0

Gracefully poweroff Pi when done.

poweroff

Other Technical Details
#

For advanced users, flashing can be skipped, further removing SD card reader from the equation, providing that the board is able to enter RPIBOOT mode.

This is incredibly convenient for boards like Pi 5, which can enter RPIBOOT mode simply by holding down the power button at power-on. In contrast, Pi 4B requires an irreversible change in place to enter RPIBOOT mode, thus making this much less viable.