Search code examples
linuxusbyoctoautomount

Auto mounting USB on a yocto linux embedded project with udev


I have a linux embedded system based on yocto up and running and need to get it to automount USB devices. The system uses udev and the following is the /etc/udev/rules.d/99-auto-mount.rules.

KERNEL!="sd[a-z][0-9]", GOTO="media_by_label_auto_mount_end"
# Import FS infos
IMPORT{program}="/sbin/blkid -o udev -p %N"

ENV{ID_PATH}!="*-usb-*", GOTO="media_by_label_auto_mount_end"

# Get a label if present, otherwise specify one
ENV{dir_name}="USB%k"

# Global mount options
ACTION=="add", ENV{mount_options}="relatime"
# Filesystem-specific mount options
ACTION=="add", ENV{ID_FS_TYPE}=="vfat|ntfs", ENV{mount_options}="$env{mount_options},utf8,gid=100,umask=002", ENV{DISPLAY}=":0", RUN+="/usr/local/bin/announce /media/%E{dir_name} 1"

# Mount the device
ACTION=="add", RUN+="/bin/mkdir -p /media/%E{dir_name}", RUN+="/bin/mount -o $env{mount_options} /dev/%k /media/%E{dir_name}"

# Clean up after removal
ACTION=="remove", ENV{dir_name}!="", RUN+="/bin/umount -l /media/%E{dir_name}", RUN+="/bin/rmdir /media/%E{dir_name}", ENV{DISPLAY}=":0", RUN+="/usr/local/bin/announce /media/%E{dir_name} 0"

# Exit
LABEL="media_by_label_auto_mount_end"

It works, after a fashion, but is unable to do all I want it to do. When an USB memory stick is inserted (/dev/sda1 for the partition) it does create the folder /media/USBsda1 during add and delete the folder /media/USBsda1 during remove when the USB memory stick is yanked.

But it never mounts the USB memory stick.

I boiled the rules file down to the following bare bones file just to try and get it to mount the USB memory stick.

A USB memory stick is inserted and it's partition is then located at /dev/sda1 in the system.

KERNEL!="sd[a-z][0-9]", GOTO="media_by_label_auto_mount_end"

# Mount the device
ACTION=="add", RUN+="/bin/mkdir -p /media/USBsda1", RUN+="/bin/mount /dev/sda1 /media/USBsda1"

# Exit
LABEL="media_by_label_auto_mount_end"

The folder gets created, but the stick is not mounted.

However, right after inserting the stick and the folder is created I can mount it manually in the console with the exact command from the rules

$> /bin/mount /dev/sda1 /media/USBsda1

and it mounts just fine?

Does anyone have any idea as to what could possibly be the problem (or more likely what is missing) or any suggestion of lines of investigations to conduct?

  • Yocto version = 2.1.3

  • udevadm version = 229


Solution

  • After much tinkering and reading information on the web I found a solution that worked on my system.

    I had to insert a systemd service after the udev rule and then a bash script called from the service that did the heavy lifting.

    So a thanks goes out to Mike Blackwell for his excellent answer to a similar question over on stackexchange. https://serverfault.com/a/767079

    I used his suggestion with a few tweeks for my own system and it worked perfectly.