Udev

Содержание:

Persistent Device name

In this example, we want to make sure your 3G card get a persistent name.

1. Plug the «card» (or device)

2. run the following command, on the proper device;

$ udevadm info --name=/dev/ttyS1 --attribute-walk

udevadm starts with the device specified by the devpath and then walks up the chain of parent devices. It prints for every device found, all possible attributes in the udev rules key format. A rule to match, can be composed by the attributes of the device and the attributes from one single parent device.

  looking at device '/class/tty/ttyS1':
    KERNEL=="ttyS1"
    SUBSYSTEM=="tty"
    DRIVER==""
    ATTR{dev}=="4:65"

  looking at parent device '/devices/pci0000:00/0000:00:1e.0/0000:15:00.0/0.0':
    KERNELS=="0.0"
    SUBSYSTEMS=="pcmcia"
    DRIVERS=="serial_cs"
    ATTRS{modalias}=="pcmcia:m00A4c1AAFf02fn00pfn00pa32607776pbD9E73B13pcAF9C4D7Fpd00000000"
    ATTRS{prod_id3}=="NRM6831"
    ATTRS{prod_id2}=="Merlin UMTS Modem"
    ATTRS{prod_id1}=="Novatel Wireless"
    ATTRS{card_id}=="0x1aaf"
    ATTRS{manf_id}=="0x00a4"
    ATTRS{func_id}=="0x02"
    ATTRS{pm_state}=="on"
    ATTRS{function}=="0x00"

  looking at parent device '/devices/pci0000:00/0000:00:1e.0/0000:15:00.0':
    KERNELS=="0000:15:00.0"
    SUBSYSTEMS=="pci"
    DRIVERS=="yenta_cardbus"
    ATTRS{msi_bus}=="1"
    ATTRS{broken_parity_status}=="0"
    ATTRS{enable}=="2"
    ATTRS{numa_node}=="0"
    ATTRS{modalias}=="pci:v00001180d00000476sv000017AAsd000020C6bc06sc07i00"
    ATTRS{local_cpus}=="00000003"
    ATTRS{irq}=="16"
    ATTRS{class}=="0x060700"
    ATTRS{subsystem_device}=="0x20c6"
    ATTRS{subsystem_vendor}=="0x17aa"
    ATTRS{device}=="0x0476"
    ATTRS{vendor}=="0x1180"

  looking at parent device '/devices/pci0000:00/0000:00:1e.0':
    KERNELS=="0000:00:1e.0"
    SUBSYSTEMS=="pci"
    DRIVERS==""
    ATTRS{msi_bus}=="1"
    ATTRS{broken_parity_status}=="0"
    ATTRS{enable}=="1"
    ATTRS{numa_node}=="0"
    ATTRS{modalias}=="pci:v00008086d00002448sv00000000sd00000000bc06sc04i01"
    ATTRS{local_cpus}=="00000003"
    ATTRS{irq}=="0"
    ATTRS{class}=="0x060401"
    ATTRS{subsystem_device}=="0x0000"
    ATTRS{subsystem_vendor}=="0x0000"
    ATTRS{device}=="0x2448"
    ATTRS{vendor}=="0x8086"

  looking at parent device '/devices/pci0000:00':
    KERNELS=="pci0000:00"
    SUBSYSTEMS==""
    DRIVERS==""
    ATTRS{uevent}==""

3. Create a file in /etc/udev/rules.d, typically named z21_persistent-local.rules.

ATTRS{prod_id2}=="Merlin UMTS Modem", ATTRS{prod_id1}=="Novatel Wireless", SYMLINK+="MerlinUMTS"
## Alternatively we could use :
# ATTRS{card_id}=="0x1aaf", ATTRS{manf_id}=="0x00a4", SYMLINK+="MerlinUMTS"

4. Force re-running the scripts (or reboot 😉

udevadm control --reload-rules
udevadm test -a -p  $(udevadm info -q path -n /dev/ttyS1)

a more detailed example by semu5 on comp.os.linux.questions. There is also a Writing udev rules.

Example interface IDs

The default naming precedence rules are these:

  1. Names incorporating Firmware/BIOS provided index numbers for on-board devices (, example: eno1)
  2. Names incorporating Firmware/BIOS provided PCI Express hotplug slot index numbers (, example: ens1)
  3. Names incorporating physical/geographical location of the connector of the hardware (, example: enp2s0)
  4. Names incorporating the interfaces’s MAC address (, example: enx78e7d1ea46da)
  5. Classic, unpredictable kernel-native ethX naming (example: eth0)

(Rule 4 is disabled by default.) So, if output is like this:

ID_NET_NAME_MAC=enxd4a8xxxxxxxx
ID_NET_NAME_ONBOARD=eno1
ID_NET_NAME_PATH=enp1s0f1

The interface will be named eno1, because takes precedence over .

udevadm Utility

The udevadm utility is a userspace management tool for Udev. Among other functions, you can use udevadm to query sysfs and obtain device attributes to help in creating Udev rules that match a device. To display udevadm usage:

# udevadm --help
udevadm    COMMAND 

Send control commands or test the device manager.

Commands:
  info          Query sysfs or the udev database
  trigger       Request events from the kernel
  settle        Wait for pending udev events
  control       Control the udev daemon
  monitor       Listen to kernel and udev events
  test          Test an event run
  test-builtin  Test a built-in command

You can also obtain usage for each of the udevadm commands. For example, to get help on using the info command:

# udevadm info --help
udevadm info  

Query sysfs or the udev database.

  -h --help                   Print this message
     --version                Print version of the program
  -q --query=TYPE             Query device information:
       name                     Name of device node
       symlink                  Pointing to node
       path                     sysfs device path
       property                 The device properties
       all                      All values
  -p --path=SYSPATH           sysfs device path used for query or attribute walk
  -n --name=NAME              Node or symlink name used for query or attribute walk
  -r --root                   Prepend dev directory to path names
  -a --attribute-walk         Print all key matches walking along the chain
                              of parent devices
  -d --device-id-of-file=FILE Print major:minor of device containing this file
  -x --export                 Export key/value pairs
  -P --export-prefix          Export the key name with a prefix
  -e --export-db              Export the content of the udev database
  -c --cleanup-db             Clean up the udev database

Example of udevadm utility

Some examples follow. To query the Udev database for the device path of /dev/xvdd:

# udevadm info --query=path --name=/dev/xvdd 
/devices/vbd-5696/block/xvdd

To query the Udev database for all device information for /dev/xvda:

# udevadm info --query=all --name=/dev/xvda
P: /devices/vbd-768/block/xvda
N: xvda
E: DEVNAME=/dev/xvda
E: DEVPATH=/devices/vbd-768/block/xvda
E: DEVTYPE=disk
E: DM_MULTIPATH_TIMESTAMP=1524287355
E: ID_PART_TABLE_TYPE=dos
E: MAJOR=202
E: MINOR=0
E: MPATH_SBIN_PATH=/sbin
E: SUBSYSTEM=block
E: TAGS=:systemd:
E: USEC_INITIALIZED=476119

Enter the following to print all sysfs properties of /dev/xvda. These properties can be used in Udev rules to match the device. It prints all devices along the chain, up to the root of sysfs.

# udevadm info --attribute-walk --name=/dev/xvda

Udevadm info starts with the device specified by the devpath and then
walks up the chain of parent devices. It prints for every device
found, all possible attributes in the udev rules key format.
A rule to match, can be composed by the attributes of the device
and the attributes from one single parent device.

  looking at device '/devices/vbd-768/block/xvda':
    KERNEL=="xvda"
    SUBSYSTEM=="block"
    DRIVER==""
    ATTR{ro}=="0"
    ATTR{size}=="41943040"
    ATTR{stat}=="   16775        4   686095    36372     2953      313   203104    42044        0    19603    78392"
    ATTR{range}=="16"
    ATTR{discard_alignment}=="0"
    ATTR{ext_range}=="16"
    ATTR{alignment_offset}=="0"
    ATTR{badblocks}==""
    ATTR{inflight}=="       0        0"
    ATTR{removable}=="0"
    ATTR{capability}=="10"

  looking at parent device '/devices/vbd-768':
    KERNELS=="vbd-768"
    SUBSYSTEMS=="xen"
    DRIVERS=="vbd"
    ATTRS{devtype}=="vbd"
    ATTRS{nodename}=="device/vbd/768"

Troubleshooting

Linux modules missing at boot sequence

If Linux modules are required and not loaded on boot after migration, execute one or more of the following solutions:

Add Linux modules to *.conf files in /etc/modules-load.d/

Compile modules into the Linux kernel, without the need of loading them on demand.

Write a custom module loader:

FILE

#!/bin/sh
test -n "$MODALIAS" && modprobe "$MODALIAS";
exec /sbin/mdev

Install it as the hotplug handler instead of mdev. Note that the earlier this gets executed, the better. Consider naming this script /sbin/hotplug, since that is the default value of /proc/sys/kernel/hotplug (or change the default value in the kernel configuration).

Rationale

It is an operating system’s kernel that is responsible for providing an abstract interface of the hardware to the rest of the software. Being a monolithic kernel, the Linux kernel does exactly that, and device drivers are part of the Linux kernel, which make up more than 50% of its source code. Hardware can be accessed through system calls or over their device nodes.

To be able to deal with peripheral devices that are hotplug-capable in a user-friendly way, a part of handling all of these hotplug-capable hardware devices was handed over from the kernel to a daemon running in user-space. Running in user space serves security and stability purposes.

설치

중요udev를 업데이트할 때 시스템을 부팅하지 못하게 하는 상황으로 못가도록 막을 수 있는 정보를 보려면 udev 업그레이드 안내서 를 확인하십시오.

커널

udev 에서는 다음 커널 옵션이 필요합니다:

커널

General setup  --->
     Configure standard kernel features (expert users)  --->
         Enable deprecated sysfs features to support old userspace tools
         Enable signalfd() system call
Enable the block layer  --->
     Block layer SG support v4
Networking support  --->
    Networking options  --->
        <*> Unix domain sockets
Device Drivers  --->
    Generic Driver Options  --->
        ()  path to uevent helper
         Maintain a devtmpfs filesystem to mount at /dev
    < > ATA/ATAPI/MFM/RLL support (DEPRECATED)  --->
File systems  --->
     Inotify support for userspace
    Pseudo filesystems --->
         /proc file system support
         sysfs file system support

파일

USE="udev"

USE flags for
sys-fs/udev

Linux dynamic and persistent device naming support (aka userspace devfs)

Operation

udev has been incorporated into systemd 183

udev is a generic device manager running as a daemon on a Linux system and listening (via a netlink socket) to uevents the kernel sends out if a new device is initialized or a device is removed from the system. The udev package comes with an extensive set of rules that match against exported values of the event and properties of the discovered device. A matching rule will possibly name and create a device node and run configured programs to set up and configure the device.

udev rules can match on properties like the kernel subsystem, the kernel device name, the physical location of the device, or properties like the device’s serial number. Rules can also request information from external programs to name a device or specify a custom name that will always be the same, regardless of the order devices are discovered by the system.

In the past a common way to use udev on Linux systems was to let it send events through a socket to HAL, which would perform further device-specific actions. For example, HAL would notify other software running on the system that the new hardware had arrived by issuing a broadcast message on the D-Bus IPC system to all interested processes. In this way, desktops such as GNOME or K Desktop Environment 3 could start the file browser to browse the file systems of newly attached USB flash drives and SD cards.

By the middle of 2011 HAL had been deprecated by most Linux distributions as well as by the KDE, GNOME and Xfce desktop environments, among others. The functionality previously embodied in HAL has been integrated into udev itself, or moved to separate software such as udisks and upower.

  • udev provides low-level access to the linux device tree. Allows programs to enumerate devices and their properties and get notifications when devices come and go.
  • dbus is a framework to allow programs to communicate with each other, securely, reliably, and with a high-level object-oriented programming interface.
  • udisks (formerly known as DeviceKit-disks) is a daemon that sits on top of libudev and other kernel interfaces and provides a high-level interface to storage devices and is accessible via dbus to applications.
  • upower (formerly known as DeviceKit-power) is a daemon that sits on top of libudev and other kernel interfaces and provides a high-level interface to power management and is accessible via dbus to applications.
  • NetworkManager is a daemon that sits on top of libudev and other kernel interfaces (and a couple of other daemons) and provides a high-level interface to network configuration and setup and is accessible via dbus to apps.

udev receives messages from the kernel, and passes them on to subsystem daemons such as Network Manager. Applications talk to Network Manager over D-Bus.

Kernel⟶udev⟶NetworkManager↽−−⇀D−Bus↽−−⇀Firefox{\displaystyle {\ce {Kernel -> udev -> Network Manager <=> D-Bus <=> Firefox}}}

HAL is obsolete and only used by legacy code. Ubuntu 10.04 shipped without HAL. Initially a new daemon DeviceKit was planned to replace certain aspects of HAL, but in March 2009, DeviceKit was deprecated in favor of adding the same code to udev as a package: udev-extras, and some functions have now moved to udev proper.

Configuration

RC service

The RC name is udev, not eudev. It needs to be registered in the sysinit runlevel.

 * rc-update: udev already installed in runlevel `sysinit'; skipping

Optional: Keep classic network interface naming

Network device names such as eth0 or wlan0 as provided by the kernel are normally changed on system boot (see dmesg) by the /lib/udev/rules.d/80-net-name-slot.rules udev rule.

To keep the classic naming this rule can be overwritten with an equally named empty file in the /etc/udev/rules.d directory:

Alternatively add to the kernel command line, change the default policy or create a custom one.

トラブルシューティング

Log monitor messages

To log all message when udevadm monitor is ran, modify the following configuration file:

FILE

udev_monitor="YES"

It will create the new log file located at /run/udev/udevmonitor.log

デバッグモード

デバッグモードを有効にすると、詳細なメッセージをログに記録します:

FILE

udev_debug="YES"

ロギングの優先順位を設定します:

FILE

udev_log="debug"

The log file /run/udevdebug.log will be created but no messages will be logged to it. The most recent versions of udev will log all messages to dmesg.

Missing device files /dev/null and /dev/console

Some udev versions need the /dev/null and /dev/console files in order to work properly, but can not create them on their own. To manually create these files for udev run the following commands with root privileges:

NIC assigned eth0, but is moved to eth1

Those having dual network cards on their motherboards may run into a situation where ifconfig may show no eth0 or eth1. dmesg may show their NIC detected as eth0, and later moved to eth1. Performing a ifconfig -a will also show the NIC as eth1. This is caused by using the kernel assigned names in the first place. Users should write custom rules like /etc/udev/rules.d/70-my-network.rules to use free names like lan0 or wireless0 or use predictable interface names (which have been enabled by default since udev version 197).

Remember to also remove old files from old versions of udev:

Also make sure not to pass on the kernel commandline. This setting would disable the predictable interface names feature of udev altogether.

Will mdev work on my system?

The mdev application is definitely suitable as long as the system does not use a full-fledged desktop environment. Note that a desktop environment is not required to run AbiWord, Firefox, GIMP, Gnumeric, etc. However, KOffice applications like KMail seem to pull in most of KDE as a dependency. In general, when using KDE or GNOME, mdev is not suitable. Also using LVM might be troublesome.

It will work very well when using the default Gentoo profiles:

  • default/linux/x86/13.0
  • default/linux/amd64/13.0

List the currently used profile by using following command:

Current /etc/portage/make.profile symlink:
  default/linux/amd64/13.0

There is one more sanity check that Gentoo users can run to check for udev dependency.

Sanity check

Get a general overview which packages might depend on udev. The output could look similar to the one shown below:

 * These packages depend on udev:
media-libs/mesa-9.0.1 (gbm ? virtual/udev)
sys-apps/hwids-20130329 (udev ? >=virtual/udev-197-r1)
sys-apps/util-linux-2.22.2 (udev ? virtual/udev)
virtual/dev-manager-0 (virtual/udev)
x11-base/xorg-server-1.13.4 (udev ? >=virtual/udev-150)
x11-drivers/xf86-video-intel-2.20.13 (udev ? virtual/udev)
x11-libs/cairo-1.10.2-r3 (drm ? >=virtual/udev-136)

Add the following line to the /etc/portage/package.mask or /etc/portage/package.mask/mdev file (which can be created if it does not exist yet):

FILE Mask away udev

sys-fs/udev

Disable the USE flag globally in /etc/portage/make.conf:

Rebuild all packages with the new USE flag:

インストール

ImportantWhen updating udev, check the udev upgrade guide for information that can prevent unbootable systems.

カーネル

udev には、以下のカーネルオプションが必要です:

KERNEL

General setup  --->
     Configure standard kernel features (expert users)  --->
         Enable deprecated sysfs features to support old userspace tools
         Enable signalfd() system call
Enable the block layer  --->
     Block layer SG support v4
Networking support  --->
    Networking options  --->
        <*> Unix domain sockets
Device Drivers  --->
    Generic Driver Options  --->
        ()  path to uevent helper
         Maintain a devtmpfs filesystem to mount at /dev
    < > ATA/ATAPI/MFM/RLL support (DEPRECATED)  --->
File systems  --->
     Inotify support for userspace
    Pseudo filesystems --->
         /proc file system support
         sysfs file system support

FILE

USE="... udev ..."

USE flags for
sys-fs/udev

Linux dynamic and persistent device naming support (aka userspace devfs)

Add support for Access Control Lists
Enable kernel module loading/unloading support using sys-apps/kmod
!!internal use only!! Security Enhanced Linux support, this must be set by the selinux profile or breakage will occur
Enable behavior to support maintaining /bin, /lib*, /sbin and /usr/sbin separately from /usr/bin and /usr/lib*
Build static versions of dynamic libraries as well

The above template uses deprecated functionality. Help us update this template!

고급 설정

규칙

udev에서는 uevents(커널에서 보낸 이벤트)에서 내보낸 값과 발견한 장치의 속성에 일치하는 규칙 모음을 제공합니다. 일치하는 규칙은 아마도 이름일 것이며, 장치 노드를 만들고, 장치를 설치하고 설정할, 조건을 미리 갖춰놓은 프로그램을 실행합니다.

정의 규칙은 다음 두군데에 저장합니다:

  1. /lib/udev/rules.d/ — 이 디렉터리의 규칙은 각각의 꾸러미가 설치하며, 보통 사용자가 바꾸어선 안됩니다.
  2. /etc/udev/rules.d/ — 이 폴더에는 최종 사용자가 설정한 규칙이 있습니다. 어떤 새로운 규칙이든 이 디렉터리에 추가해야합니다.

이 디렉터리에서 (.rules로 끝나는) 여러 규칙 파일은 알파벳 및 숫자 순서대로 확인합니다. 규칙 파일 안에서 udev는 uevent와 상태가 일치(장치를 추가하거나 제거하기 때문에 uevent가 됩니다)하는 조건 설정과 실행할 명령을 찾습니다.

이벤트 비교는 다음과 같은 정보를 기반으로 합니다:

  • uevent SUBSYSTEM (uevent의 어떤 형식의 장치를 실행했는가)
  • 취한 ACTION (추가, 변경, 제거)
  • 장치 클래스, 제조사, 다른 장치 정보 등의 하나 이상의 속성(ATTR 또는 ATTRS)
  • sd* (SCSI/SATA 디스크) 또는 input* (마우스, 키보드 같은 입력 장치)과 같은 커널 제공 이름 (KERNEL),
  • 여러 규칙에 정보를 보낼 때 활용할 하나 이상의 환경 변수 설정(ENV)

이 정보를 기반으로 다음의 조건에 따라, 규칙을 세울 수 있습니다:

  1. 일부 정보는 (환경 변수로)최종 이벤트와 공유해야 합니다
  2. /dev에 링크를 만들어야 합니다
  3. 명령을 실행해야 합니다

udev는 유연한 장치 관리 방식을 허용하는 모든 규칙(첫번째 일치 요소가 있다고 해서 멈추진 않음)에 대해 이러한 동작을 수행합니다.

영속 장치 이름

커널은 장치를 순차적으로 발견하고 udev는 커널의 sysfs 파일 시스템을 미러링하며, 장치에 이름과 숫자를 발견한 순서대로 부여합니다. 따라서 기본적으로 udev에서는 비영속적 장치 이름을 제공합니다. 허나 일부 장치 클래스에 대한 기법에는 다음과 같은 특징이 있습니다:

udev는 장치 ID, label, UUID, 경로를 기반으로 저장장치 추가 심볼릭 링크를 만듭니다. /dev/disk/by-* 디렉터리를 살펴보십시오. 따라서, 장치 파일 /dev/sda 을 사용하는 대신 /dev/disk/by-label/SOME_LABEL 파일을 활용합니다.

/dev/input 디렉터리의 입력 장치는 동일합니다.

사용자 규칙을 활용은 사용자로 하여금 자체 장치 파일을 만들 수 있습니다.

Replacing udev with mdev

WarningThis is a critical step which might result in a non-bootable Linux system. Only proceed if the above approach has not revealed any additional udev dependencies.

Setting up the kernel for devtmpfs

Set up the kernel to support and automount a devtmpfs filesystem at /dev:

KERNEL Enabling devtmpfs

Device Drivers --->
    Generic Driver Options --->
         Maintain a devtmpfs filesystem to mount at /dev
         Automount devtmpfs at /dev, after the kernel mounted the rootfs

Once the changes have been made, rebuild the kernel. Do NOT reboot yet.

FILE

sys-apps/busybox static mdev

Now, (re)install busybox:

Mounting devpts

The devpts filesystem exhibits non-standard behavior. It does not automount, at bootup, or with mount -a. An explicit mount devpts command is required. The standard solution for udev-based systems is to run rc-update add udev-mount sysinit as root, and have the udev-mount script do the mounting at startup. An mdev-based system will probably not have udev installed. An alternative way to do this at bootup is to include the command mount devpts in a shell script in /etc/local.d/. In this example, the file will be named /etc/local.d/000.start.

Another side-effect of not using udev-mount is that /dev/shm is only writable by root. The command chmod 1777 /dev/shm is required to restore the standard behavior. This command will also be run from the script at startup.

FILE Mount of devpts at bootup and change /dev/shm permissions

#!/bin/bash
mount devpts
chmod 1777 /dev/shm

NoteScripts used in /etc/local.d/

  • must be executable
  • must have the extension «.start» in order to run at startup
  • must have the extension «.stop» in order to run at shutdown

Cleanup

Remove udev from the system:

In the /etc/portage/package.mask file (or a file in this directory), add .

This now results in a completely udev-free machine.

Udev Rule Files and Directories

Udev rules determine how to identify devices and how to assign a name that is persistent through reboots or disk changes. When Udev receives a device event, it matches the configured rules against the device attributes in sysfs to identify the device. Rules can also specify additional programs to run as part of device event handling.
Udev rules files are located in the following directories:

  • /lib/udev/rules.d/ – The default rules directory
  • /etc/udev/rules.d/ – The custom rules directory. These rules take precedence.

Rules files need to have unique names. Files in the custom rules directory override files of the same name in the default rules directory. Rules files are sorted and processed in lexical order. The following is a partial listing of rules files from the default and custom rules directories:

# ls -l /lib/udev/rules.d/
total 348
-r--r--r--. 1 root root  7266 Aug  5  2017 10-dm.rules
-r--r--r--. 1 root root  2454 Aug  5  2017 11-dm-lvm.rules
-rw-r--r--. 1 root root  2865 Jan 25 16:05 11-dm-mpath.rules
-r--r--r--. 1 root root  1499 Aug  5  2017 13-dm-disk.rules
-rw-r--r--. 1 root root   553 Aug  6  2017 39-usbmuxd.rules
-rw-r--r--. 1 root root  1622 Mar  7 13:27 40-redhat.rules
...
# ls -l /etc/udev/rules.d/
total 8
-rw-r--r--. 1 root root 709 Aug  4  2017 70-persistent-ipoib.rules
-rw-r--r--. 1 root root  96 Apr 21 05:09 70-persistent-net.rules
lrwxrwxrwx. 1 root root   9 Sep 29  2014 80-net-name-slot.rules -> /dev/null

Описание

Благодаря udev в каталоге /dev находятся файлы только тех устройств, которые в настоящий момент подключены к системе. Каждое устройство имеет свой соответствующий файл. Если устройство отключается от системы, то данный файл удаляется. Содержимое каталога /dev хранится на виртуальной файловой системе, и все файлы, находящиеся в нём, создаются при каждом запуске системы. Модифицированные или созданные вручную файлы не сохраняются после перезагрузки. Файлы и каталоги, которые необходимо сохранить или которые всегда должны присутствовать в каталоге /dev, независимо от состояния соответствующего устройства, необходимо помещать в каталог /lib/udev/devices. При запуске системы содержимое данного каталога копируется в /dev как есть (с теми же правами доступа).

Таким образом, в отличие от традиционной для Unix схемы управления каталогом /dev, где его содержимое было неизменным набором файлов, udev обеспечивает динамическое управление устройствами, действительно находящимися в системе. Хотя раньше подобная функциональность обеспечивалась devfs, сторонники udev выделяют следующие преимущества своего решения:

  • udev поддерживает неизменное именование устройств, не зависящее, например, от порядка включения устройств в систему. Конфигурация по умолчанию обеспечивает неизменное именование для накопителей: жесткие диски идентифицируются по уникальному идентификатору файловой системы, имени диска и расположению устройства, к которому подключен диск.
  • udev работает целиком в пространстве пользователя. Это приводит, в частности, к тому, что udev может выполнять произвольные программы для составления имени устройства либо его инициализации.

Overview

The udev system is composed of some kernel services and the udevd daemon. The kernel informs the udevd daemon when certain events happen. The udevd daemon is configured to respond to events with corresponding actions. The event information comes from the kernel — the actions happen in userspace. The responses to the events are configurable in «rules».

The userspace udev functionality is implemented by the systemd-udevd.service Its config file is in /etc/udev/udev.conf. The rules files (which amount to more configuration for udevd) are taken from /run/udev/rules.d, /etc/udev/rules.d or /lib/udev/rules.d. Packages install rules in /lib/udev/rules.d), while the /etc and /run locations provide a facility for the administrator to override the behavior of a package-provided rule. If a file with the same name is present in more than one of these directories then the latter(s) file will be ignored. Files in there are parsed in alpha order, as long as the name ends with «.rules». When the config file or rules files are changed, the udevadm program should be used to instruct systemd-udevd to reload the rules (see below).

udev was created to respond to hotplug type of events. Much documentation refers to creating devices in response to new devices that have appeared. But, udev is more general; it can run arbitrary userspace commands in response to a new device appearing — or to whatever events it receives from the kernel.

The times when udevd is active are:

  1. at startup, it parses all the config files and rule files and builds a rules database in memory.
  2. When an event happens, it checks its rule database and performs the appropriate actions.

Rules

Rules for rules:

  1. rules are all on one line (lines can be broken with \ just before newline)
  2. rules consist of «matches» and «actions»
  3. matches and actions are «key» «operator» «value» triplets
  4. matches have == or != for operator
  5. actions have = (assignment) for operator
  6. matches check one or more attributes of the event to see if the action will be applied
  7. actions specify what will happen
  8. example match: BUS=="usb"

  9. example action: NAME="mydev"

  10. example rule:

    KERNEL=="sd*|dasd*", ENV{ID_SERIAL}=="?*", \
            SYMLINK+="disk/by-id/$env{ID_BUS}-$env{ID_SERIAL}-part%n"
  11. all matching rules will fire
  12. earlier rules have precedence over later rules — so put your customizations early in the rules.d file list
  13. actions like key=»value» override
  14. actions like key+=»value» add to the actions that are executed, eg SYMLINK+="foo" means «in addition to any other symlinks you were going to make for this event, also make one called foo»

Rule sets

Rules for rule sets:

  1. All the rules are in one big rule space, although they are divided into several files.
  2. The only organization in the rule space is the ability to set labels, and then to skip a bunch of rules during «match this event to rules» time by jumping forward with a GOTO action.

  3. there is one other rule type called a label: eg LABEL="persistent_storage_end" These are used by regular rules that have «GOTO» actions, eg:

    ACTION!="add", GOTO="persistent_storage_end"

    Note that in this rule, the term ACTION is an attribute of an event and is being used as a condition for deciding if the GOTO action will be triggered.

  4. It is polite to keep GOTOs to jump within a file (or you will have to worry about reordering the files)
  5. Don’t jump backwards to a label (didn’t try it, but imagine it might end in an infinite loop? Maybe the udev code checks for that — but if it’s going to be ignored (at best) why bother?)
  6. You can set variables in ENV space in earlier rules and refer to them with later rules
  7. The facility for dynamic rule creation exists (example: see z45_persistent-net-generator.rules)

Заключение

В данной статье был рассмотрен основной инструмент для конфигурации устройства для его успешного распознавания в системе и придания ему тех качеств, которые требуются разработчику драйвера для этого устройства. Созданный проект драйвера почти никогда не содержит единичного модуля ядра, так как в нём обычно присутствуют дополнительные файлы с конфигурацией (для подсистемы ), утилиты пространства пользователя для настройки или управления (например, по ), тестирования и диагностики различных программных компонентов проекта и т.д.

К статье прилагается архив udev.tgz, который можно найти в разделе «Материалы для скачивания», не имеющий прямого отношения к коду модуля, но демонстрирующий, как любой пользовательский процесс может получать асинхронные уведомления о событиях ядра. Приложение регистрирует уведомления о горячих подключениях-выключениях устройств, а приложение отслеживает уведомления об изменениях в состояниях сетевых интерфейсов. Изучение этих приложений поможет лучше понять, как драйверы устройств взаимодействуют с ядром.

Похожие темы

  • Нестандартные сценарии использования модулей ядра: Часть 48. Анализ оборудования.
  • Обслуживание периферии в коде модулей ядра: Часть 50. PCI-устройства.
  • Инструкция по работе с примерами исходного кода в цикле статей «Разработка модулей ядра Linux».
Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *