How to enable usb_gadget support to emulate a USB Mass Storage device

Traditionally, with Raspberry Pi OS, I’d be able to leverage configfs and libcomposite to open the usb_gadget tree and config from there. I haven’t found an easy way to enable in the host OS or a container to enable the mass storage gadget feature. Any thoughts?

It’s possible to use usb_gadget modules with configfs on Raspberry Pi 4/5 BalenaOS builds. See GitHub - 30block/gadget: Turn your Raspberry Pi into a USB Gadget as an example with g_ether.

The issue however is that there seems to be some discrepancy between Raspberry Pi builds. I attempted to create a g_mass_storage container on a Pi Zero W 2 and found that the build does not include CONFIG_GADGET_CONFIGFS so it cannot be configured: No CONFIG_USB_GADGETFS with latest BalenaOS · Issue #11 · 30block/gadget · GitHub

Copied from ticket:

My image fails with mkdir: can't create directory '/sys/kernel/config/usb_gadget/': Operation not permitted. The docker-compose.yml has the correct privileges so it’s not a permissions issue really. The permission issue is I believe because configfs is not enabled.

On the target:

root@115ffec:~# zcat /proc/config.gz | grep -i -E "CONFIG_USB_GADGET"
CONFIG_USB_GADGET=y
# CONFIG_USB_GADGET_DEBUG is not set
# CONFIG_USB_GADGET_DEBUG_FILES is not set
# CONFIG_USB_GADGET_DEBUG_FS is not set
CONFIG_USB_GADGET_VBUS_DRAW=2
CONFIG_USB_GADGET_STORAGE_NUM_BUFFERS=2
# CONFIG_USB_GADGET_XILINX is not set
# CONFIG_USB_GADGETFS is not set
root@115ffec:~# modinfo g_ether
modinfo: ERROR: Module g_ether not found.
root@115ffec:~# modinfo dwc2
name:           dwc2
filename:       (builtin)
license:        Dual BSD/GPL
file:           drivers/usb/dwc2/dwc2
author:         Synopsys, Inc.
description:    DESIGNWARE HS OTG Core

Compared to test Raspbian image (and BalenaOS on Pi5) which I also tested the image to work, we see CONFIG_USB_GADGETFS=m is configured as module:

❯ zcat /proc/config.gz | grep -i -E "CONFIG_USB_GADGET"
CONFIG_USB_GADGET=y
# CONFIG_USB_GADGET_DEBUG is not set
# CONFIG_USB_GADGET_DEBUG_FILES is not set
# CONFIG_USB_GADGET_DEBUG_FS is not set
CONFIG_USB_GADGET_VBUS_DRAW=2
CONFIG_USB_GADGET_STORAGE_NUM_BUFFERS=2
# CONFIG_USB_GADGET_XILINX is not set
CONFIG_USB_GADGETFS=m

Can anyone from Balena explain the reason for different build and whether the Zero W 2 can be built with CONFIG_USB_GADGETFS=m? It’s a useful platform to have USB gadget support.