Udev

From miki
Jump to navigation Jump to search

Reference

  • udev man page (man udev)

udev rules

  • Rules are contained in files located in /etc/udev/rules. Files must have .rules extensions, and are processed in lexical order. Files usually starts with 2 figures (like 10-local.rules)

Examples

This basic rule simply changes group of all usb hub devices to plugdev.

# Basic rule - set group 'plugdev' for all USB HUB
#SUBSYSTEMS=="usb", ATTR{bDeviceClass}=="09", MODE="660", GROUP="plugdev"

This rule is more advanced. Whenever a specific usb device (here, an usb serial device) is inserted, it changes the group of the hub device the first device is attached to.

# More advanced rule, only set 'plugdev' grp for hub that have an FTDI board connected to them
# SUBSYSTEM=="tty", DRIVERS=="ftdi_sio", RUN+="/etc/udev/rules.d/plugdev_hub.sh"
#
# Even better, this rules also detects board removal, which allow to reset grp to 'root'
SUBSYSTEM=="tty", KERNEL=="ttyUSB*", RUN+="/etc/udev/rules.d/plugdev_hub.sh"

File plugdev_hub.sh:

#! /bin/bash

# Set group to 'plugdev' for given hub device
function setgrp()
{
    DEVNAME=/dev/$(udevadm info -q name -p $1)
    chgrp plugdev $DEVNAME
}

# Reset group to 'root' if no ttyUSB device found for given hub
function resetgrp()
{
    TTYDEVS=$(find $1 -lname "*/ttyUSB*")
    if [ -z "$TTYDEVS" ]; then
        DEVNAME=/dev/$(udevadm info -q name -p $1)
        chgrp root $DEVNAME
    fi
}

if [ "$ACTION" = "add" -o "$ACTION" = "remove" ]; then
    F=/sys$DEVPATH
    while [ "$F" != "/sys" ] ; do 
        if [ -a "$F/bDeviceClass" ] ; then
            if [ "$(cat $F/bDeviceClass)" == "09" ] ; then
                if [ "$ACTION" = "add" ]; then
                    setgrp $F                           # add
                else
                    resetgrp $F                         # remove
                fi
                break
            fi
        fi
        F=$(dirname $F)
    done
fi

Detecting device removal

Note that many attributes are no longer available during udev rules processing when a device is removed. To know which variables are still available in the environment, try

udevadm monitor --property

Troubleshooting

udevadm monitor
udevadm monitor --environment --udev        # To also get the env var. before each udev actions

chmod 644 99-myrule.rules
chown root:root 99-myrule.rules
udevadm test -a add $(udevadm info -q path -n /dev/ttyACM0)
Remove not executing
See [1]. Maybe are using an attribute that no longer exists.
More troubleshooting
https://stackoverflow.com/questions/67123997/how-to-find-reasons-why-an-udev-rule-is-not-applied

Development