Skip to content

Raspberry Pi USB OTG Mass-Storage Gadget

A Raspberry Pi USB mass-storage gadget appears to a host computer as a flash drive backed by an image file or block device on the Pi. The critical rule is that the host and Raspberry Pi must not mount the same writable filesystem at the same time. Two independent writers can corrupt it.

Protect existing data and remote access

Formatting destroys the selected image's contents. This example creates a new private trial directory; never substitute an existing file or device. Keep a separate local console or verified Wi-Fi/Ethernet connection: a standalone mass-storage gadget and USB Ethernet cannot both own the same UDC. Do not disconnect a cable that powers a running Pi.

Verification scope

This is a documentation and safety review against the Linux mass-storage gadget documentation. USB mass-storage enumeration, host eject and writable recovery have not been tested on this site's Pi or host. The previous USB Ethernet test does not verify this workflow.

If your goal is SSH or file transfer over a network, use the supported Trixie USB Gadget Mode for SSH instead. Mass-storage emulation is for appliances, test fixtures, virtual media, and controlled file-exchange workflows.

Choose the safer design

Requirement Recommended design
SSH and normal file transfer USB Ethernet Gadget + SSH/SFTP
Host must see a removable drive File-backed mass-storage gadget
Host only needs fixed content Read-only mass-storage gadget
Both Pi and host need live writable access Do not use one shared filesystem; use networking or an application protocol
Production appliance Use configfs/systemd with explicit attach/detach state and recovery testing

Start with a disposable image file, not a physical partition containing important data.

Hardware and port requirements

Use a Raspberry Pi and port capable of USB device/peripheral mode. Pi Zero, Zero W, and Zero 2 W are common test targets; use the micro-USB port labelled USB, not PWR IN.

Newer boards can have dual-role USB-C ports, but power, controller, boot configuration, and peripheral trade-offs differ. Validate the exact model and port before deployment.

Requirements:

  • USB data cable, not charge-only cable
  • Stable power arrangement
  • Raspberry Pi OS with the dwc2 peripheral controller available
  • Root privileges to load the gadget driver
  • Disposable backing image for initial testing
  • Local recovery access

Architecture

1
2
3
4
5
6
7
8
9
Host computer
    │ USB Mass Storage protocol
    ▼
Linux USB gadget driver on Raspberry Pi
    │
    ▼
$image
    │
    └── FAT filesystem mounted by either host OR Pi, never both writable

The image file is not a synchronisation layer. The kernel exports its blocks to the host, which expects exclusive control of filesystem metadata and caches.

Step 1: enable peripheral mode

First inspect the controller, active gadgets and configuration. An empty controller directory needs model-specific setup; a built-in driver may not appear in lsmod:

1
2
3
4
5
ls -1 /sys/class/udc
cat /sys/class/udc/*/state 2>/dev/null
lsmod | grep -E 'dwc2|g_ether|g_mass_storage'
cat /proc/cmdline
grep -nE 'dwc2|otg_mode' /boot/firmware/config.txt

If the controller is absent, consult the diagnostic guide and the board-specific manual setup and backup procedure. Do not add duplicate or conflicting boot settings. Make changes and reboot only with a verified independent recovery route.

Stop if another gadget owns the controller or g_mass_storage is already loaded. The supported rpi-usb-gadget Ethernet workflow and this standalone mass-storage gadget compete for the UDC. Module and ConfigFS inspection can help identify the owner; a module-based gadget may not appear in ConfigFS. Never unload an unrelated gadget or disconnect your only route to the Pi. This guide does not switch off or restore a package-managed Ethernet gadget for you.

Step 2: create a disposable backing image

On the Pi, install dosfstools if mkfs.vfat is unavailable. The following creates a new private directory under your home directory and an image inside it. It does not reuse the old fixed /srv/usb-gadget/disk.img path. Run these commands in one shell and save the printed directory path; after reconnecting you must deliberately restore the variables to that exact path.

1
2
3
4
5
6
trial_dir=$(mktemp -d "$HOME/usb-storage-trial.XXXXXX") || exit 1
image="$trial_dir/disk.img"
mount_dir="$trial_dir/mount"
printf 'Trial directory: %s\nImage: %s\n' "$trial_dir" "$image"
mkdir "$mount_dir"
test ! -e "$image" && truncate -s 1G "$image"

If any command fails, stop. Before formatting, independently check the printed path is inside the newly created private directory, the image is a new disposable regular file and nothing has mounted or exported it. mkfs.vfat overwrites filesystem data; never run it on an existing image or block device:

mkfs.vfat -F 32 -n PI_GADGET "$image"

This places one FAT filesystem directly in the image without a partition table. Do not reuse this block to reset an existing image: rerunning the format destroys its content.

Confirm its type:

file "$image"

Step 3: add initial files on the Pi

The image is not yet exported, so mount it locally:

1
2
3
sudo mount -o loop "$image" "$mount_dir"
findmnt -M "$mount_dir"
sudo losetup -j "$image"

Continue only if the exact mountpoint is mounted from a loop device associated with this trial image. If either check fails, stop; do not write to an unintended directory. Then add the test file and unmount:

1
2
3
4
printf '%s\n' 'Raspberry Pi USB gadget test' | \
  sudo tee "$mount_dir/README.txt"
sync
sudo umount "$mount_dir"

Verify it is unmounted before exporting:

findmnt --target "$mount_dir"
sudo losetup -j "$image"

findmnt --target may show the enclosing filesystem even when the trial mount is gone; check whether the exact TARGET is $mount_dir. Inspect any loop devices reported by losetup -j and their mountpoints with findmnt; stop if the image is still mounted or ownership is unclear. Do not detach a loop device belonging to another workload.

Step 4: export read-only first

Before loading, recheck that $image is the recorded trial file, it is not locally mounted, no other process modifies it, the UDC is free, and g_mass_storage is not already loaded. A successful modprobe on an already-loaded module does not guarantee that new parameters were applied. Only then load the module for this trial:

1
2
3
4
5
sudo modprobe g_mass_storage \
  "file=$image" \
  removable=1 \
  ro=1 \
  stall=0

Connect the data cable to the correct device-mode port. The host should detect a drive named PI_GADGET.

Inspect the Pi log:

journalctl -b -k --no-pager | tail -100
lsmod | grep g_mass_storage

ro=1 requests host-side read-only access; confirm enumeration, media visibility and the actual backing file and read-only state before drawing conclusions. See the kernel documentation for LUN state and eject behavior. Do not modify the backing image while it is exported, even when the host is read-only.

Step 5: detach safely

Eject the drive in the host operating system first. Identify the active gadget and confirm it is the one loaded for this trial. Only then remove that module on the Pi; never unload an existing gadget owned by another service:

sudo modprobe -r g_mass_storage

Confirm the module is gone before mounting the image locally:

lsmod | grep g_mass_storage || true

Stop if the module is still present, its backing file remains in use, or ownership is unclear. The lsmod output alone does not prove a built-in or independently configured gadget is detached. Once detachment is confirmed, mount the trial image again and verify the exact mountpoint and loop device as in Step 3 before making any local changes:

1
2
3
sudo mount -o loop "$image" "$mount_dir"
findmnt -M "$mount_dir"
sudo losetup -j "$image"

After local changes, unmount and verify the image is no longer mounted before any new export:

sync
sudo umount "$mount_dir"

Then export again.

Writable host access

Only enable writable export after the read-only workflow is reliable, its gadget has been detached, and the image is unmounted and not owned by another process. The following is an alternative new load, not an update to an already loaded module:

1
2
3
4
5
sudo modprobe g_mass_storage \
  "file=$image" \
  removable=1 \
  ro=0 \
  stall=0

While this module is active, do not mount the image on the Pi. Even a read-only local mount can produce confusing cache behaviour; use a strict attach/detach state machine.

Before detaching:

  1. Stop applications writing to the host drive.
  2. Eject/unmount it on the host.
  3. Wait for the host operation to finish.
  4. Remove g_mass_storage on the Pi.
  5. Run a filesystem check before local reuse when the host disconnected unexpectedly.
sudo fsck.vfat -n "$image"

Use -n for a non-modifying first inspection. Back up the image before attempting repair.

Read-only appliance pattern

For installers, documentation, or fixed configuration payloads, keep the exported image read-only and rebuild it offline when content changes. This avoids ambiguous ownership and greatly reduces corruption risk.

Workflow:

Detach gadget → mount image on Pi → update → unmount → verify → export read-only

After detaching the gadget and unmounting the image, record a checksum:

sha256sum "$image" | tee "$trial_dir/disk.img.sha256"

Do not export the active root filesystem

Never point g_mass_storage at a mounted root partition or another filesystem the Pi is actively using. A host OS may write partition metadata, indexing files, recycle-bin data, or repair information without an obvious prompt.

Use an isolated image or dedicated block device with explicit ownership transitions.

Automatic startup considerations

Do not automate the gadget until manual attach, host eject, detach, filesystem check, and recovery all work. A production service should:

  • Refuse to attach if the image is locally mounted.
  • Refuse local mounting while the gadget is attached.
  • Log every state transition.
  • Default to read-only after an unclean shutdown.
  • Stop cleanly before power-off.
  • Expose health/status separately from the mass-storage filesystem.

Configfs supports composite and more controlled gadgets, but increases implementation responsibility. Use it when you need multiple functions or stable descriptors, not merely because an old tutorial uses it.

Finish the trial and restore your setup

Eject the host drive, verify the trial gadget is detached and the trial image is unmounted, and inspect any loop devices before cleanup. Keep the recorded trial directory until you have verified it contains only your disposable test files; remove those specific files and the empty trial directory only when no process uses them. This page does not automatically delete images or backups.

If you deliberately changed boot configuration or another service, use the independently verified console or network route to restore only your recorded changes. Verify the previous connection and its expected boot behavior separately; unloading g_mass_storage does not automatically restore USB Ethernet.

Host operating-system behaviour

Windows, macOS, and Linux can all add metadata to writable removable media. Examples include indexing databases, recycle-bin directories, or desktop metadata. Design the application to ignore unrelated files and never assume that only your payload changes.

Host write caching also means “copy complete” is not the same as “safe to unplug.” Require a proper eject.

Troubleshooting

The host sees no USB device

Check:

1
2
3
lsmod | grep -E 'dwc2|g_mass_storage'
journalctl -b -k --no-pager | grep -Ei 'dwc2|gadget|usb'
vcgencmd get_throttled

Confirm the data cable, correct device-mode port, board support, peripheral-mode overlay, and adequate power.

modprobe: FATAL: Module g_mass_storage is in use

The host may still have the gadget open or another function owns the controller. Eject on the host, disconnect if necessary, inspect mounts and modules, then detach deliberately.

The host asks to format the drive

Do not accept immediately. Detach safely and inspect the image:

file "$image"
sudo fsck.vfat -n "$image"

Confirm that you exported the correct file and that local/host concurrent access never occurred.

Files disappear or the filesystem becomes corrupt

The likely causes are concurrent writers, host caching, cable/power interruption, or exporting the wrong backing object. Restore the known-good image and redesign the ownership transition before trying again.

USB Ethernet stopped working

Only one gadget configuration may own the controller. Detach mass storage before enabling rpi-usb-gadget, and avoid configuring both automatically at boot.

FAQ

Can the host and Pi write the image at the same time?

No. Standard FAT/ext filesystems do not coordinate two independent kernels writing the same block device. Use USB networking and a file-transfer protocol for simultaneous access.

Which filesystem should I use?

FAT32 is a common compatibility baseline for a small cross-platform image. It lacks Unix permissions and has file-size limitations. Choose based on host support and payload requirements.

Can I export a physical USB drive instead of a file?

Technically yes, but the exclusive-ownership rule remains and the consequence of a mistake is larger. Prove the workflow with a disposable file image first.

Is g_mass_storage the same as rpi-usb-gadget?

No. g_mass_storage exposes storage blocks. The current Raspberry Pi OS package focuses on USB Ethernet networking for SSH and optional host internet sharing.

Donate