出處:http://www.redhat.com/magazine/002dec04/features/udev/
Introduction
As more and more users become aware of the many advantages Linux has over other operating system such as security and flexibility, its ease of use must be improved to increase its adoption rate. One significant improvement is the introduction of udev. udev allows a Linux system to use consistent device names for devices such as removable drives and printers, which in turn allows users to experience predictable behavior when devices are added or removed from the system.
Starting with Fedora Core 3 and the upcoming release of Red Hat Enterprise Linux 4, all system device nodes in the /dev directory are managed by the udev program. In all previous Red Hat releases, the /dev directory was a static list of all possible devices that might be connected to the system. This meant that there were over 18,000 different device nodes in that directory. Now, with udev, only the devices that are present and available to use in the system appear in the /dev directory.
udev manages the /dev directory by monitoring the /sys directory. The /sys directory is where the sysfs file system is mounted. Through the information present in sysfs, udev knows what devices need to have a /dev entry created and what to name the entry.
Configuration Files
udev has different configuration files to control how it works and how it creates the different/dev nodes. There are three basic types of udev configuration files: the main udev configuration file, udev permission files, and udev rules files.
The main udev configuration file, /etc/udev/udev.conf, controls what directory contains the udev permission and rules files, where to put the udev database, and where udev creates the device nodes.
Example 1, “udev.conf Example” shows an example udev.conf file.
# /etc/udev/udev.conf: main config file for udev
#
# This file can be used to override some of udev's default values
# for where it looks for files, and where it places device nodes.
# udev_root - where in the filesystem to place the device nodes
udev_root="/dev/"
# udev_db - The name and location of the udev database.
# NOTE: this should be somewhere that is writable before
# / is mounted rw, like /dev ...
udev_db="/dev/.udevdb"
# udev_rules - The name and location of the udev rules file
udev_rules="/etc/udev/rules.d/"
# udev_permissions - The name and location of the udev permission file
udev_permissions="/etc/udev/permissions.d/"
# default_mode - set the default mode for all nodes that have no
# explicit match in the permissions file
# NOTE: do not set to anything else if you are not
# sure you have everything needed for normal
# user to function in the permissions file!
default_mode="0660"
# udev_log - set to "yes" if you want logging
udev_log="no"
Example 1. udev.conf Example
udev permission files specify what the permissions should be set to for specific device nodes. For details on how this file can be modified, refer to the udev documentation. For almost all users, the default permissions that Red Hat has specified are adequate.
udev rules files are used by udev to determine the device names used for devices present in the system. Every line in the rules files defines how a specific device attribute is mapped to a device file. If all keys that are specified in a rule match the device that was found, the specified device file is created.
The default udev rule file in Fedora Core 3 and Red Hat Enterprise Linux 4 is located at/etc/udev/rules.d/50-udev.rules. This file should not be modified by a user. To create new rules, create a new file in the /etc/udev/rules.d/ directory. All rules files must have a filename that ends with the .rules extension. Files are read in sorted order, so to use a custom rule, create a file for it that is read before the default rules files, such as /etc/udev/rules.d/10-my.rules.
Rules
The basic form of a udev rule is
key, [key, ...] name [, symlink]
Every key is a field that must match with the specific device. These fields are specified in the form of type=value. The different types of fields are:
BUS
This matches the bus type of the device. Common values for this field are usb, scsi, and ide.
KERNEL
This matches the default device name assigned to the device by the kernel. Examples includehda, ttyUSB0, and lp0.
SUBSYSTEM
This matches the kernel subsystem name for the device. This is usually the same as the BUSvalue but can sometimes be different. Examples of this are usb and scsi.
DRIVER
This matches the name of the kernel driver that is controlling the device. Examples of this areorinoco and usb-storage.
ID
This matches the device number on the bus to which it is attached. Examples include the PCI bus id or USB id for the device.
PLACE
This matches the device’s topological position on the bus to which the device is attached. This is usually only valid for USB devices, as they encode their topology within the USB bus id value.
SYSFS{filename}
udev reads the specified sysfs filename in the directory for the device and tries to match the value read from it. This is useful in determining the vendor, label, serial number, UUID, or system label of a device. Anything that is in the sysfs tree can be matched against. Up to 5 different sysfs files can be checked in the same rule, and any trailing space characters in the sysfs file are ignored, even if the key does not have any trailing spaces either.
PROGRAM
This allows udev to call any external program and use the output of the program in naming a device. This key is valid if the external program returns successfully. When the program is called, all environment variables that were passed to udev are also available for the program to evaluate. The string returned by the program can also be matched with the RESULT key.
RESULT
This is used to match the return string of the last PROGRAM call. This key may be used in any following rule, after a PROGRAM call, enabling different rules to match a previous PROGRAM call.
If all of the specified keys are valid in a rule, then the following values are used to specify what udev does with the device:
NAME
This is the name of the device node that udev should create.
SYMLINK
This is the name of a symlink created to point back to the specified NAME. Multiple symlinks may be specified by separating them by a space character. If there is a SYMLINK field in a rule without a NAME field, the rule is not applied immediately. Instead, the symlink value is added to the symlink list for any future rule that might create a device node. This is useful for adding a user-specified symlink to a device node that is later specified in a different rules file.
Example Rules
Now that all of the different ways a rule can be written have been described, let us look at some sample rules to better understand how to put the different fields together.
A simple rule to create the device node for the CPU microcode driver might look like:
KERNEL="microcode", NAME="cpu/microcode"
This rule is valid if the kernel name is microcode. If so, it creates the device nodecpu/microcode putting the device node in a separate subdirectory.
Another simple rule is the one to match up the sound control device:
KERNEL="controlC[0-9]*", NAME="snd/%k"
This rule matches any device that starts with controlC, followed by a single digit which is then followed by any number of characters. This type of rule uses a simple form of a regular expression to match the name of the device. Refer to the udev man page for more details on how to specify a regular expression that udev understands. The NAME field for this rules specifies that it should be placed in the snd subdirectory and use the kernel name. The %kdirectory name is replaced with the kernel name. For the full list of modifier types that udev supports, consult the udev man page.
Now for a more advanced rule. Most digital cameras are USB devices and use the usb-storage kernel driver to talk to the system. To always name a specific digital camera the same device node no matter when it is plugged into the computer, use the following rule:
BUS="scsi", SYSFS{vendor}="FUJIFILM", NAME="camera"
This rule states that if the BUS value is scsi and the sysfs file vendor in the device directory contains the value FUJIFILM, than the device name should be set to camera.
Using the SYSFS{filename} type of key, we can solve a common problem for anyone who has more than one USB printers. Depending on the order in which the printers are plugged into the computer or on the order in which they power on when rebooting the computer, they could get different device nodes every other time. This makes determining which printer is connected to which printer queue quite difficult at times. If we can specify a way for a printer to always have the same name, no matter which order in which it was plugged in, that would solve the problem.
Here are two rules that users can use to always bind a specific printer to a specific name:
BUS="usb", SYSFS{serial}="W09090207101241330", NAME="lp_color"
BUS="usb", SYSFS{serial}="HXOLL0012202323480", NAME="lp_bw"
These rules cause the printer with the serial number W09090207101241330 to be always accessed through the device node lp_color and the printer with the serial numberHXOLL0012202323480 always accessed through the device node lp_bw. These serial numbers can be found in sysfs in the directory for the usb device, as described in
the section called “Writing New Rule”.
Writing New Rule
The previous examples demonstrate simple rules, but how does the user know what fields are best to use to specify within a rule to uniquely identify the device? Using the program udevinfothat comes bundled with the udev program, a wide range of information can be determined about a device that can be used to create a new udev rule.
udevinfo can be used to list all of the sysfs information about a specific device. For example, to name your green USB mouse, mouse_green, refer to the the sysfs information about the USB mouse using udevinfo:
udevinfo -a -p /sys/class/input/mouse0/
udevinfo starts with the device the node belongs to and then walks up the
device chain, to print for every device found, all possibly useful attributes
in the udev key format.
Only attributes within one device section may be used together in one rule,
to match the device for which the node will be created.
device '/sys/class/input/mouse0' has major:minor 13:32
looking at class device '/sys/class/input/mouse0':
SYSFS{dev}="13:33"
follow the class device's "device"
looking at the device chain at '/sys/devices/pci0000:00/0000:00:09.0/usb2/2-1/2-1:1.0':
BUS="usb"
ID="2-1:1.0"
SYSFS{bAlternateSetting}=" 0"
SYSFS{bInterfaceClass}="03"
SYSFS{bInterfaceNumber}="00"
SYSFS{bInterfaceProtocol}="02"
SYSFS{bInterfaceSubClass}="01"
SYSFS{bNumEndpoints}="01"
SYSFS{detach_state}="0"
looking at the device chain at '/sys/devices/pci0000:00/0000:00:09.0/usb2/2-1':
BUS="usb"
ID="2-1"
SYSFS{bConfigurationValue}="1"
SYSFS{bDeviceClass}="00"
SYSFS{bDeviceProtocol}="00"
SYSFS{bDeviceSubClass}="00"
SYSFS{bMaxPower}="100mA"
SYSFS{bNumConfigurations}="1"
SYSFS{bNumInterfaces}=" 1"
SYSFS{bcdDevice}="0100"
SYSFS{bmAttributes}="a0"
SYSFS{configuration}="HID-Mouse"
SYSFS{detach_state}="0"
SYSFS{devnum}="2"
SYSFS{idProduct}="1035"
SYSFS{idVendor}="047d"
SYSFS{manufacturer}="Kensington"
SYSFS{maxchild}="0"
SYSFS{product}="Kensington USB Mouse"
SYSFS{speed}="1.5"
SYSFS{version}=" 1.10"
looking at the device chain at '/sys/devices/pci0000:00/0000:00:09.0/usb2':
BUS="usb"
ID="usb2"
SYSFS{bConfigurationValue}="1"
SYSFS{bDeviceClass}="09"
SYSFS{bDeviceProtocol}="00"
SYSFS{bDeviceSubClass}="00"
SYSFS{bMaxPower}=" 0mA"
SYSFS{bNumConfigurations}="1"
SYSFS{bNumInterfaces}=" 1"
SYSFS{bcdDevice}="0206"
SYSFS{bmAttributes}="c0"
SYSFS{detach_state}="0"
SYSFS{devnum}="1"
SYSFS{idProduct}="0000"
SYSFS{idVendor}="0000"
SYSFS{manufacturer}="Linux 2.6.10-rc2 ohci_hcd"
SYSFS{maxchild}="1"
SYSFS{product}="NEC Corporation USB"
SYSFS{serial}="0000:00:09.0"
SYSFS{speed}="12"
SYSFS{version}=" 1.10"
looking at the device chain at '/sys/devices/pci0000:00/0000:00:09.0':
BUS="pci"
ID="0000:00:09.0"
SYSFS{class}="0x0c0310"
SYSFS{detach_state}="0"
SYSFS{device}="0x0035"
SYSFS{irq}="9"
SYSFS{subsystem_device}="0x11a3"
SYSFS{subsystem_vendor}="0x10cf"
SYSFS{vendor}="0x1033"
looking at the device chain at '/sys/devices/pci0000:00':
BUS=""
ID="pci0000:00"
SYSFS{detach_state}="0"
Example 2. Example udevinfo Output
So, from the output of the udevinfo program, all of the sysfs files and other udev fields are described. To write the best type of rule for a device, determine the most unique way a device can be described from the output.. For example, from
Example 2, “Example udevinfo Output”, the following line shows a unique field that distinguishes it from all other mice that might be connected to the system:
SYSFS{product}="Kensington USB Mouse"
However, this is not true if a user has more than one kind of the same mouse. In that case, the ID value should be used since it is unique:
ID="2-1:1.0"
Using the product sysfs file, a udev rule to always name this mouse mouse_green is as follows:
BUS="usb", SYSFS{product}="Kensington USB Mouse", NAME="mouse_green"
Calling External Programs
One of the most powerful features of udev is its ability to call other programs to determine what to name a device or if a device should be matched. This is useful if the built-in keys and rule matching sequences are not flexible enough.
As an example, what if you want to use the artist name from the currently inserted CD as the CD-ROM device name? There is no way that sysfs will be extended to provide this kind of information about the data within the device, so an external program must be used. The following rule causes udev to call the program name_cdrom.pl whenever a block device is found by the kernel:
KERNEL="[hs]d[a-z]", PROGRAM="name_cdrom.pl %M %m", NAME="%c{1}", SYMLINK="cdrom"
This rule matches any device that starts with h or s followed by a d and then followed by any lowercase alphabetic character. If that name matches, the Perl script, name_cdrom.pl is called. This script is shown in
Example 3, “name_cdrom.pl Script”. There are two arguments passed in for this script, the major and minor number of the device being matched by udev (as specified by the %M and %m modifiers). If this program returns a success, then the first return value of the script is used to name the device (that is the %c{1} modifier). A symlink to the filecdrom is also created so that other programs are still able to find the cdrom device in the system.
#!/usr/bin/perl
# a horribly funny script that shows how flexible udev can really be
# This is to be executed by udev with the following rules:
# KERNEL="[hs]d[a-z]", PROGRAM="name_cdrom.pl %M %m", NAME="%c{1}", SYMLINK="cdrom"
use strict;
use warnings;
use CDDB_get qw( get_cddb );
my $dev_node = "/tmp/cd_foo";
# following variables just need to be declared if different from defaults
my %config;
$config{CDDB_HOST}="freedb.freedb.org"; # set cddb host
$config{CDDB_PORT}=8880; # set cddb port
$config{CDDB_MODE}="cddb"; # set cddb mode: cddb or http
$config{CD_DEVICE}="$dev_node"; # set cd device
# No user interaction, this is a automated script!
$config{input}=0;
my $major = $ARGV[0];
my $minor = $ARGV[1];
# create our temp device node to read the cd info from
unlink($dev_node);
if (system("mknod $dev_node b $major $minor")) {
die "bad mknod failed";
}
# get it on
my %cd=get_cddb(%config);
# remove the dev node we just created
unlink($dev_node);
# print out our cd name if we have found it or skip rule by nonzero exit
if (defined $cd{title}) {
$cd{artist} =~ s/ /_/g;
$cd{title} =~ s/ /_/g;
print "$cd{artist}-$cd{title}n";
} else {
exit -1;
}
Example 3. name_cdrom.pl Script
The name_cdrom.pl script queries the
freedb database (assuming the system has an Internet connection) to determine the artist name of the currently inserted CD. Such a complex functionality would never have been built into udev but because of the PROGRAM feature, udev can rely on helper programs to create complex rules if it is desired.
Conclusion
There are many ways to create new udev rules, due to its wide range of key matching abilities and ability to call other programs. To learn more about how to create custom udev rules, refer to the udev documentation that comes with the program. In it are full descriptions of all of the different keys that can be used, an explanation of the regular expressions that are supported by udev, and a tutorial on how to create udev rules based on many different types of devices.
The author would like to thank Kay Sievers for all of his udev development and documentation work and Daniel Drake who created the udev tutorial provided with the program.
About the Author
Greg Kroah-Hartman is currently the Linux kernel maintainer for a variety of different driver subsystems. He works for IBM, doing Linux kernel-related things, and can be reached at <
[email protected]>.