Softpanorama

May the source be with you, but remember the KISS principle ;-)
Home Switchboard Unix Administration Red Hat TCP/IP Networks Neoliberalism Toxic Managers
(slightly skeptical) Educational society promoting "Back to basics" movement against IT overcomplexity and  bastardization of classic Unix

udev — Persistent Device Naming in Linux

News

Recommended Books

Recommended Links

Biosdevname and renaming of Ethernet interfaces

Reference

Managing Disks by UUID

 Managing Disks by ID
Partition labels Linux Multipath   Logical Volume Manager (LVM) Admin Horror Stories Humor Etc

Linux has mind boggling variety of  disk mapping schemes. Among them

  1. Regular Unix device path
  2. UUID
  3. Disk ID
  4. Partition labels

  5. udev
  6. Logical manager mapping (LVM - mapping)

Traditionally, device nodes were stored in the /dev directory on Linux systems. There was a node for every possible type of device, regardless of whether it actually existed in the system.  The command devfs  has brought a significant improvement, because now only devices that really exist are given a device node in /dev.  Linux kernel 2.6 introduced a new user space solution for a dynamic device directory /dev with consistent device designations: udev. The previous implementation of /dev with devfs  has been abandoned.

udev  introduces a new way of creating device nodes. It compares the information made available by sysfs  with data provided by the user in the form of rules. sysfs  is a new pseudo file system in kernel 2.6 similar to /proc. It provides basic information about devices connected to the system. sysfs  is mounted under /sys.

It is not absolutely necessary for the user to create rules. If a device is connected, the appropriate device node is created. However, the rules introduce the possibility of changing the names for the nodes. This offers the convenience of replacing a cryptic device name with a name that is easy to remember and also of having consistent device names where two devices of the same type have been connected.

Unless otherwise specified, two printers are given the designations /dev/lp0 and /dev/lp1. Which device is given which device node depends on the order in which they are switched on. Another example is external mass storage devices, such as USB hard disks. The udev  command allows exact device paths to be entered in /etc/fstab.

Suse uses (and abuses) udev starting from Suse 10 SP3. See SUSE Linux SUSE Linux Enterprise Server (SLES 10) Installation and Administration. Specifically Dynamic Kernel Device Management with udev

The device nodes in the /dev directory provide access to the corresponding kernel devices. With udev, the /dev directory reflects the current state of the kernel. Every kernel device has one corresponding device file. If a device is disconnected from the system, the device node is removed.

The content of the /dev directory is kept on a temporary file system and all files are created from scratch at every system start-up. Manually created or changed files intentionally do not survive a reboot. Static files and directories that should always be present in the /dev directory regardless of the state of the corresponding kernel device can be placed in the /lib/udev/devices directory. At system start-up, the contents of that directory is copied to the /dev directory with the same ownership and permissions as the files in /lib/udev/devices.

The required device information is exported by the sysfs file system. For every device the kernel has detected and initialized, a directory with the device name is created. It contains attribute files with device-specific properties. Every time a device is added or removed, the kernel sends a uevent to notify udev of the change.

The udev daemon reads and parses all provided rules from the /etc/udev/rules.d/*.rules files once at start-up and keeps them in memory. If rules files are changed, added, or removed, the daemon receives an event and updates the in-memory representation of the rules.

Every received event is matched against the set of provides rules. The rules can add or change event environment keys, request a specific name for the device node to create, add symlinks pointing to the node, or add programs to run after the device node is created. The driver core uevents are received from a kernel netlink socket.

The kernel bus drivers probe for devices. For every detected device, the kernel creates an internal device structure and the driver core sends a uevent to the udev daemon. Bus devices identify themselves by a specially-formatted ID, which tells what kind of device it is. Usually these IDs consist of vendor and product ID and other subsystem-specific values. Every bus has its own scheme for these IDs, called MODALIAS. The kernel takes the device information, composes a MODALIAS ID string from it, and sends that string along with the event. For a USB mouse, it looks like this:

MODALIAS=usb:v046DpC03Ed2000dc00dsc00dp00ic03isc01ip02

Every device driver carries a list of known aliases for devices it can handle. The list is contained in the kernel module file itself. The program depmod reads the ID lists and creates the file modules.alias in the kernel's /lib/modules directory for all currently available modules. With this infrastructure, module loading is as easy as calling modprobe for every event that carries a MODALIAS key. If modprobe $MODALIAS is called, it matches the device alias composed for the device with the aliases provided by the modules. If a matching entry is found, that module is loaded. All this is triggered by udev and happens automatically.

All device events happening during the boot process before the udev daemon is running are lost, because the infrastructure to handle these events lives on the root file system and is not available at that time. To cover that loss, the kernel provides a uevent file for every device in the sysfs file system. By writing add to that file, the kernel resends the same event as the one lost during boot. A simple loop over all uevent files in /sys triggers all events again to create the device nodes and perform device setup.

As an example, a USB mouse present during boot may not be initialized by the early boot logic, because the driver is not available that time. The event for the device discovery was lost and failed to find a kernel module for the device. Instead of manually searching for possibly connected devices, udev just requests all device events from the kernel after the root file system is available, so the event for the USB mouse device just runs again. Now it finds the kernel module on the mounted root file system and the USB mouse can be initialized.

From userspace, there is no visible difference between a device coldplug sequence and a device discovery during runtime. In both cases, the same rules are used to match and the same configured programs are run.

The program udevmonitor can be used to visualize the driver core events and the timing of the udev event processes.

UEVENT[1132632714.285362] add@/devices/pci0000:00/0000:00:1d.1/usb2/2-2
UEVENT[1132632714.288166] add@/devices/pci0000:00/0000:00:1d.1/usb2/2-2/2-2:1.0
UEVENT[1132632714.309485] add@/class/input/input6
UEVENT[1132632714.309511] add@/class/input/input6/mouse2
UEVENT[1132632714.309524] add@/class/usb_device/usbdev2.12
UDEV  [1132632714.348966] add@/devices/pci0000:00/0000:00:1d.1/usb2/2-2
UDEV  [1132632714.420947] add@/devices/pci0000:00/0000:00:1d.1/usb2/2-2/2-2:1.0
UDEV  [1132632714.427298] add@/class/input/input6
UDEV  [1132632714.434223] add@/class/usb_device/usbdev2.12
UDEV  [1132632714.439934] add@/class/input/input6/mouse2

The UEVENT lines show the events the kernel has sent over netlink. The UDEV lines show the finished udev event handlers. The timing is printed in microseconds. The time between UEVENT and UDEV is the time udev took to process this event or the udev daemon has delayed its execution to synchronize this event with related and already running events. For example, events for hard disk partitions always wait for the main disk device event to finish, because the partition events may rely on the data the main disk event has queried from the hardware.

udevmonitor --env shows the complete event environment:

UDEV  [1132633002.937243] add@/class/input/input7
UDEV_LOG=3
ACTION=add
DEVPATH=/class/input/input7
SUBSYSTEM=input
SEQNUM=1043
PHYSDEVPATH=/devices/pci0000:00/0000:00:1d.1/usb2/2-2/2-2:1.0
PHYSDEVBUS=usb
PHYSDEVDRIVER=usbhid
PRODUCT=3/46d/c03e/2000
NAME="Logitech USB-PS/2 Optical Mouse"
PHYS="usb-0000:00:1d.1-2/input0"
UNIQ=""
EV=7
KEY=70000 0 0 0 0 0 0 0 0
REL=103

udev also sends messages to syslog. The default syslog priority that controls which messages are sent to syslog is specified in the udev configuration file /etc/udev/udev.conf. The log priority of the running daemon can be changed with udevcontrol log_priority=level/number

A udev rule can match any property the kernel adds to the event itself or any information that the kernel exports to sysfs. The rule can also request additional information from external programs. Every event is matched against all provided rules. All rules are located in the /etc/udev/rules.d directory.

Every line in the rules file contains at least one key value pair. There are two kinds of keys, match and assignment keys. If all match keys match their values, the rule is applied and the assignment keys are assigned the specified value. A matching rule may specify the name of the device node, add symlinks pointing to the node, or run a specified program as part of the event handling. If no matching rule is found, the default device node name is used to create the device node. The rule syntax and the provided keys to match or import data are described in the udev man page.

The dynamic device directory and the udev rules infrastructure make it possible to provide stable names for all disk devices—regardless of their order of recognition or the connection used for the device. Every appropriate block device the kernel creates is examined by tools with special knowledge about certain buses, drive types, or file systems. Along with the dynamic kernel-provided device node name, udev maintains classes of persistent symbolic links pointing to the device:

/dev/disk
|-- by-id
|   |-- scsi-SATA_HTS726060M9AT00_MRH453M4HWHG7B -> ../../sda
|   |-- scsi-SATA_HTS726060M9AT00_MRH453M4HWHG7B-part1 -> ../../sda1
|   |-- scsi-SATA_HTS726060M9AT00_MRH453M4HWHG7B-part6 -> ../../sda6
|   |-- scsi-SATA_HTS726060M9AT00_MRH453M4HWHG7B-part7 -> ../../sda7
|   |-- usb-Generic_STORAGE_DEVICE_02773 -> ../../sdd
|   `-- usb-Generic_STORAGE_DEVICE_02773-part1 -> ../../sdd1
|-- by-label
|   |-- Photos -> ../../sdd1
|   |-- SUSE10 -> ../../sda7
|   `-- devel -> ../../sda6
|-- by-path
|   |-- pci-0000:00:1f.2-scsi-0:0:0:0 -> ../../sda
|   |-- pci-0000:00:1f.2-scsi-0:0:0:0-part1 -> ../../sda1
|   |-- pci-0000:00:1f.2-scsi-0:0:0:0-part6 -> ../../sda6
|   |-- pci-0000:00:1f.2-scsi-0:0:0:0-part7 -> ../../sda7
|   |-- pci-0000:00:1f.2-scsi-1:0:0:0 -> ../../sr0
|   |-- usb-02773:0:0:2 -> ../../sdd
|   |-- usb-02773:0:0:2-part1 -> ../../sdd1
`-- by-uuid
    |-- 159a47a4-e6e6-40be-a757-a629991479ae -> ../../sda7
    |-- 3e999973-00c9-4917-9442-b7633bd95b9e -> ../../sda6
    `-- 4210-8F8C -> ../../sdd1

The formerly used hotplug package is entirely replaced by udev and the udev-related kernel infrastructure. The following parts of the former hotplug infrastructure have been made obsolete or had their functionality taken over by udev:

/etc/hotplug/*.agent
No longer needed or moved to /lib/udev
/etc/hotplug/*.rc
Replaced by the /sys/*/uevent trigger
/etc/hotplug/blacklist
Replaced by the blacklist option in modprobe.conf
/etc/dev.d/*
Replaced by the udev rule RUN key
/etc/hotplug.d/*
Replaced by the udev rule RUN key
/sbin/hotplug
Replaced by udevd listening to netlink; only used in the initial RAM file system until the root file system can be mounted, then it is disabled
/dev/*
Replaced by dynamic udev and static content in /lib/udev/devices/*

The following files and directories contain the crucial elements of the udev infrastructure:

/etc/udev/udev.conf
Main udev configuration file
/etc/udev/rules.d/*
udev event matching rules
/lib/udev/devices/*
Static /dev content
/lib/udev/*
Helper programs called from udev rules

For more information about the udev infrastructure, refer to the following man pages:

udev
General information about udev, keys, rules, and other important configuration issues.
udevinfo
udevinfo can be used to query device information from the udev database.
udevd
Information about the udev event managing daemon.
udevmonitor
udevmonitor prints the kernel and udev event sequence to the console. This tool is mainly used for debugging purposes.

Top Visited
Switchboard
Latest
Past week
Past month

NEWS CONTENTS

Old News ;-)

[Apr 8, 2008] Manage Linux Hardware with udev By Carla Schroder

In the olden days Linux administrators had a static /dev directory. It was inflexible and obese, containing 99% irrelevant entries, and we liked it that way. We didn't mind hassling with makedev and struggling with major and minor numbers to enter the devices we actually wanted, or manually deleting the 1,000 useless /dev entries, because Real System Administrators love doing things the hard way. It makes us feel close to our hardware. The best part of the job is spending years acquiring and hoarding arcane bits of knowledge, which are then passed on to eager, fresh-faced noobs with the magical incantation, "RTFM, luser."

Then came devfs, which attempted to replace this increasingly arthritic system with something that was less complex, more efficient, and which was a bit more based in reality. The creator of devfs, Richard Gooch, had this radical idea that the /dev directory should contain only devices actually present on the system, and aim for better performance and simplified device management.

Then descended the unbearded prophet Greg Kroah-Hartman from his mountaintop lair with yet another dev filesystem, called thereforth udev. Since kernel 2.6.13, devfs is no longer included in the mainline kernel.

Endless debates rage about devfs vs. udev, which you can read about in Resources. Chances are you still have /etc/devfs/ on your system, and a few devices that depend on it. A famous example is NVidia drivers. So when you see this directory, don't think you can go on a mad housecleaning spree and get rid of it.

udev handles the task of detecting hardware and creating nodes for it in /dev, and also managing device permissions. It works in concert with the Linux Hardware Abstraction Layer (HAL) and the hotplug subsystem. In effect, all devices, even internal drives and expansion cards, are treated as removable hotplug devices. "Oh no," you say, "this is not good, because removable devices receive different kernel names every time you plug them in."

No problem, for udev lets you create fixed device names so you can make static entries in /etc/fstab, and don't have to play hunt-the-widget every time you reboot. In fact your Linux distribution probably comes with a nice pre-fab configuration that assigns static names to certain devices, like hard drives and PCI network cards.

It's a nice flexible, highly adaptable system, and when it's configured correctly by your distribution maintainer your computing life is easy and fun.

I'm Sorry, Dave, I Can't Allow You to do That

The downside to all this udev goodness is it's still just a youth, so when you need to make some manual tweaks you have to figure out weirdo command syntax and how to uncover the device information you need. It's simple when you know how. Well, maybe not even then. But let's take a look under the hood anyway.

We still have a /dev directory. This is no longer a static directory, but rather is populated at boot with entries generated by udev rules.

udev's rules are stored in configuration files in /etc/udev. Different distributions mangle this in different ways. Fedora and Ubuntu are sensible. There is /etc/udev/udev.conf, which contains program options, then all rules files are kept in /etc/udev/rules.d/ like they're supposed to. Debian Etch, for gosh-knows-why, puts all the rules files in the top-level directory, and then has to symlink them all to /etc/udev/rules.d. udev rules must go in /etc/udev/rules.d.

The /sys directory is a cousin to /proc, only it's well-organized rather than a chaotic mess. It exports kernel information into a human-browseable and program-parseable structure. Just like /proc uses the /proc filesystem, the /sys directory uses sysfs. You can see this with the mount command:

 # mount proc on /proc type proc (rw) /sys on /sys type
sysfs (rw) udev on /dev type tmpfs (rw) 

Notice how /dev uses tmpfs, which means wipeout on reboot.

/sys is chock full o symlinks, as you can see with the find /sys -type l command. You can browse /sys just like any other directory. Whether you'll understand the contents is another question, but it doesn't hurt to get familiar with its structure.

Because sysfs is a virtual filesystem like /proc, it doesn't occupy any physical disk space. The Konqueror file browser on my system says it occupies 129.4 megabytes, but du tells a different story:

 $ du -sh /sys 0 /sys 

Writing udev Rules

Current releases of udev come with bales of man pages, and several different useful commands. On Debian systems, find them all with dpkg:

 $ dpkg -L udev 

On Fedora, use the rpm command:

 $ rpm -ql udev 

You'll see there are different command sets for each distribution, and a pox on both of them for sowing useless confusion, so we'll look at the important commands they have in common.

The first step for writing or modifying udev rules is to make sure that your kernel sees the device you want to make the rule for. (If the kernel doesn't see it, you need to find out if your device is supported in Linux at all, then how to enable that support.) First try running the udevinfo command. This example dumps all devices in the udev database:

 $ udevinfo -e 

You may query individual devices, if you know the device path, as this example for an SATA partition shows:

 $ udevinfo -a -p /block/sda/sda1 

How do you know the device path? From udevinfo. You already know the node name for some of your devices, and can query it this way:

 $ udevinfo -q all -n sda 

Both of these commands spit out a lot of information. Just for fun, you can run lspci and match up the disk/by-path/pci values from udevinfo:

 0000:00:0f.0 RAID bus controller: VIA Technologies, Inc.  VIA
VT6420 SATA RAID Controller (rev 80)

S: disk/by-path/pci-0000:00:0f.0-scsi-0:0:0:0-part1 

The output of udevinfo is pretty cryptic, so this is one way to match it up to devices with names you recognize. For USB devices compare with the output of lsusb. SCSI devices compare to lsscsi.

Come back next week to learn how to nail down USB network cards, straighten out device permissions, and manage multiple storage drives painlessly with udev.

Resources

[Aug 15, 2006] The Linux Device Model Linux Magazine by Sreekrishnan Venkateswaran

August 15, 2006

Many Linux subsystems, such as the /dev filesystem, hotplug, module autoload, and microcode download have undergone significant changes with the introduction of the new device model. Learn about udev, sysfs, kobjects, classes, and more.

The Linux 2.6 kernel features a new device model built around concepts like sysfs, kobjects, device classes, and udev. The new model makes it easier to develop device drivers by introducing C++- like abstractions that distill commonalities from device drivers into bus and core layers. It also weeds policies out of kernel space and pushes them to user space, which has resulted in a total revamp of many features, including /dev node management, hotplug, coldplug, module autoload and firmware download.

This month, let's look at the different pieces that constiture the device model and how each piece affects key kernel subsystems. But let's start by learning about udev with the help of some examples.

Tinkering with Udev

Years ago, when Linux was young, it wasn't fun to administer device nodes. All the needed nodes (which could run into thousands) had to be statically created under the /dev directory. With the advent of the 2.4 kernels came devfs, which introduced dynamic device node creation. Devfs provided kernel interfaces to request generation of device nodes in an in-memory filesystem, but the onus of naming the nodes still rested with device drivers. However, device naming policy is administrative and doesn't mix well with the kernel. Udev arrived on the scene to push device management entirely to user space.

Udev depends on the following to do its work:

1.Kernel sysfs support, which is an important part of the Linux device model. We'll look at sysfs later on, but for now, take the corresponding sysfs file accesses for granted.

2.A set of user space daemons and utilities, such as udevd and udevinfo.

3.User-specified rules located in the /etc/udev/rules.d directory. You can write rules to get a consistent view of your devices.

To understand how to use udev, let's start off with an example. Assume that you have a USB DVD drive and a USB CD-RW drive. Depending on the order in which you hotplug these devices, one of them is assigned the name sr0, while the other gets the name sr1. During pre-udev days, you had to figure out the associated names before you could use the devices. But with udev, you can consistently view the DVD (say, as /dev/usbdvd) and the CD-RW (say, as /dev/usbcdrw) irrespective of the order in which they are plugged in or out.

First, pull product attributes from corresponding files in sysfs. Use udevinfo to collect device information:

udev-Persistent Device Naming in User Space By Greg Kroah-Hartman

2004-06-01 01:00

Starting with the 2.5 kernel, all physical and virtual devices in a system are visible to user space in a hierarchal fashion through sysfs. /sbin/hotplug provides a notification to user space when any device is added or removed from the system. Using these two features, a user-space implementation of a dynamic /dev now is possible that can provide a flexible device naming policy.

This article discusses udev, a program that replaces the functionality of devfs. It provides /dev entries for devices in the system at any moment in time. It also provides features previously unavailable through devfs alone, such as persistent naming for devices when they move around the device tree, a flexible device naming scheme, notification of external systems of device changes and moving all naming policy out of the kernel.

The /dev directory on a Linux machine is where all of the device files for the system should be located. A device file details how a user program can access a specific hardware device or function. For example, the device file /dev/hda traditionally is used to represent the first IDE drive in the system. The name hda corresponds to both a major and a minor number, which are used by the kernel to determine what hardware device to talk to. Currently, a wide range of names that match up to different major and minor numbers has been defined.

All major and minor numbers are assigned a name that matches up with a type of device. This allocation is done by the Linux assigned names and numbers authority (LANANA), and the current device list can be found on its Web site (see the on-line Resources section).

As Linux begins supporting new kinds of devices, these devices need to be assigned a major and minor number range in order for users to access them through the /dev directory. An alternative is to provide access through a filesystem; my 2002 linux.conf.au paper provides more details on how to do this (see the on-line Resources section). In kernel versions 2.4 and earlier, the valid range of major numbers was 1–255, and the valid range of minor numbers was 1–255. Because of this limited range, a freeze was placed on allocating new major and minor numbers during the 2.3 development cycle. This freeze since has been lifted, and the 2.6 kernel had the valid range of major numbers increased to 4,095. More than a million minor numbers are available per major number.

What /dev Entry Is Which Device

When the kernel finds a new piece of hardware, it typically assigns the next major/minor pair for that kind of hardware to the device. So, on boot, the first USB printer found would be assigned the major number 180 and minor number 0, which is referenced in /dev as /dev/usb/lp0. The second USB printer would be assigned major number 180 and minor number 1, which is referenced in /dev as /dev/usb/lp1. If the user rearranges the USB topology, perhaps adding a USB hub to support more USB devices in the system, the USB probing order of the printers might change the next time the computer is booted, reversing the assignment of the different minor numbers to the two printers.

This same situation holds true for almost any kind of device that can be removed or added while the computer is powered up. With the advent of PCI hot-plug-enabled systems and hot-pluggable buses, such as IEEE 1394, USB and CardBus, almost all devices have this problem.

With the advent of the sysfs filesystem in the 2.5 kernel, the problem of determining which device minor number is assigned to which physical device is much easier to determine. For a system having two different USB printers plugged in to it, the sysfs /sys/class/usb directory tree would look like this:

/sys/class/usb/
|-- lp0
|   |-- dev
|   |-- device -> ../../../devices/pci0/00:09.0/usb1/1-1/1-1:0
|   `-- driver -> ../../../bus/usb/drivers/usblp
`-- lp1
    |-- dev
    |-- device -> ../../../devices/pci0/00:0d.0/usb3/3-1/3-1:0
    `-- driver -> ../../../bus/usb/drivers/usblp

$ cat /sys/class/usb/lp0/device/serial
HXOLL0012202323480
$ cat /sys/class/usb/lp1/device/serial
W09090207101241330

Within the individual USB device directories pointed to by the lp0/device and lp1/device symbolic links, a lot of USB-specific information can be determined, such as the manufacturer of the device and the (hopefully unique) serial number.

As can be seen by the serial files in the above description, the /dev/usb/lp0 device file is associated with the USB printer with serial number HXOLL0012202323480, and the /dev/usb/lp1 device file is associated with the USB printer with serial number W09090207101241330. If these printers are moved around, say by placing them both behind a USB hub, they might be renamed, as they are probed in a different order on startup:

$ tree /sys/class/usb/
/sys/class/usb/
|-- lp0
|   |-- dev
|   |-- device -> ../../../devices/pci0/00:09.0/usb1/1-1/1-1.1/1-1.1:0
|   `-- driver -> ../../../bus/usb/drivers/usblp
`-- lp1
    |-- dev
    |-- device -> ../../../devices/pci0/00:09.0/usb1/1-1/1-1.4/1-1.4:0
    `-- driver -> ../../../bus/usb/drivers/usblp

$ cat /sys/class/usb/lp0/device/serial
W09090207101241330
$ cat /sys/class/usb/lp1/device/serial
HXOLL0012202323480

As this description shows, the /dev/usb/lp0 device now is assigned to the USB printer with the serial number W09090207101241330 due to this different probing order.

sysfs enables a user to determine which device has been assigned by the kernel to which device file. This is a powerful association that previously had not been easily available. However, a user generally does not care that /dev/usb/lp0 and /dev/usb/lp1 are now reversed and should be changed in a configuration file somewhere. The user simply wants to be able to print to the proper printer, no matter where it is in the USB device tree.

/dev Is Too Big

Not all device files in the /dev directory of most distributions match up to a physical device that is currently connected to the computer. Instead, the /dev directory is created when the operating system is initialized on the machine, populating the /dev directory with all known possible names. On a machine running Red Hat's Fedora release 1, the /dev directory holds more than 18,000 different entries. This many entries soon become unwieldy for users trying to determine exactly what devices currently are present.

devfs

Because of the large numbers of device files in the /dev directory, a number of operating systems have moved to having the kernel itself manage the /dev directory, as the kernel always knows exactly what devices are present on the system. It does this by creating a RAM-based filesystem called devfs. Linux also has this option, and it has become popular over time in a number of different distributions, including Gentoo.

For a number of people, devfs solves their immediate needs. However, the Linux-based devfs implementation still has a number of unsolved problems. Most notably, it does not provide the ability to create device nodes with a persistent name.

udev's goals

In light of the previously mentioned problems, the udev Project was started. Its goals are to run in user space; create a dynamic /dev; provide consistent device naming, if wanted; and provide a user-space API to access information about current system devices. For more on how udev compares with devfs, see the on-line Resources section.

The first item, run in user space, is accomplished by harnessing the fact that /sbin/hotplug generates an event for every device added to or removed from the system with sysfs' ability to show all the needed information about all devices.

The second item, create a dynamic /dev, is handled by catching all /sbin/hotplug events, looking up the major and minor number in sysfs for the added device and creating a /dev file with the kernel name the device was assigned. If the device was removed from the system, it is easy to remove the /dev entry for that device.

udev achieved these first two goals back in April 2003 in an extremely tiny 6Kb of compiled code, proving that this scheme of catching hot-plug events and using sysfs was feasible and quite simple to implement. Since that humble beginning in early 2003, udev has achieved all of its goals. It provides users with the ability to name devices in a persistent manner using a flexible rule-based system.

udev's rules are contained in the /etc/udev/udev.rules file and describe any devices the user wants to name in a way that differs from the default kernel name. Here's an example of a udev.rules file:

# if /sbin/scsi_id returns "OEM 0815" device will
# be called disk1
BUS="scsi", PROGRAM="/sbin/scsi_id", \
RESULT="OEM 0815", NAME="disk1"

# USB printer to be called lp_color
BUS="usb", SYSFS_serial="W09090207101241330", \
NAME="lp_color"

# SCSI disk with a specific vendor and model number
# is to be called boot
BUS="scsi", SYSFS_vendor="IBM", \
SYSFS_model="ST336", NAME="boot"

# sound card with PCI bus id 00:0b.0 to be called dsp
BUS="pci", ID="00:0b.0", NAME="dsp"

# USB mouse at third port of the second hub to
# be called mouse1
BUS="usb", PLACE="2.3", NAME="mouse1"

# ttyUSB1 should always be called pda with two
# additional symlinks
KERNEL="ttyUSB1", NAME="pda", \
SYMLINK="palmtop handheld"

# multiple USB webcams with symlinks to be called
# webcam0, webcam1, ...
BUS="usb", SYSFS_model="XV3", NAME="video%n", \
SYMLINK="webcam%n"

A udev rule defines the mapping between a device's attributes and the desired device filename. To do this, a number of keys can be queried from the device to determine a match. If no match is found in the udev.rules file, the default kernel name is used. Below is a list of the different types of keys that udev understands:

After the different keys, a NAME and optional SYMLINK are specified. The NAME is what udev uses to call the device if the rule matches, and the SYMLINK specifies what, if any, symlinks also are generated. More than one symlink can be specified at once, with spaces between multiple symlinks. Both the NAME and SYMLINK files can contain directories to allow /dev to be simplified.

Example

So, back to our two-printer example. To name both of these devices in a consistent manner, the following two udev rules might be used:

BUS="usb", SYSFS_serial="W09090207101241330", \
NAME="lp_color"
BUS="usb", SYSFS_serial="HXOLL0012202323480", \
NAME="lp_plain"

These rules cause udev to look at the sysfs file serial for both printers and, depending on the value in the file, name the printer either lp_color or lp_plain. This ensures that no matter which device was plugged in first or detected first or whether another USB printer is added to the system, both of the printers have the same persistent name.

Advanced udev Rules

udev allows a number of printf-like string substitutions to be used in the NAME, SYMLINK and PROGRAM fields in the udev.rules file. These fields are:

Also, a number of the different keys support a simple form of shell-style pattern matching. These patterns are:

Because of the ability to do these simple string substitutions and string pattern matching, combined with the ability to have udev run any other program and use its result, udev has become an extremely flexible tool for naming devices. As an example of this power, take a look at the following rule:

KERNEL="[hs]d[a-z]", PROGRAM="name_cdrom.pl %M %m", \
NAME="%1c", SYMLINK="cdrom"

This rule matches any block device and calls the Perl script name_cdrom.pl with the major and minor number of the device. If this program is successful, udev uses the first word of the program's output to name the device and creates a symlink called cdrom. The name_cdrom.pl script can be found in the udev release.

What this script does is determine whether the device is a CD-ROM device. If it is, it queries the Free CDDB database to see if the CD-ROM present in the device is known in the database. If it is, it then names the device based on the CD. For example, my /dev looks like the following when using this rule:

$ ls -l /dev/S* /dev/cdrom
brw-------  1 root root 22, 64 Feb 15 08:26 /dev/Samiam-Astray
lrwxrwxrwx  1 root root      8 Feb 15 08:26 /dev/cdrom ->
/dev/Samiam-Astray

This shows how udev can query a database across the Internet to determine how to name a device. Yes, it's a crazy naming scheme to try to use, but it shows how powerful and flexible udev can be.

Acknowledgements

The author would like to thank Daniel Stekloff of IBM, who has helped shape the design of udev in many ways. Without his perseverance, udev would not be available at all. Also, Kay Sievers has been instrumental in implementing the majority of the advanced features in udev, most notably the ability to have string modifiers and pattern matching, both of which are essential for using udev in the real world. Without his help, udev would not be anywhere near as powerful and useful as it is.

Also, without Pat Mochel's sysfs and driver model core, udev would not have been possible to implement. The author is indebted to him for undertaking what most thought of as an impossible task and for allowing others to build easily on his common framework, allowing all users to see the "Web woven by a spider on drugs" that the kernel keeps track of.

This article is based on the Ottawa Linux Symposium 2002 paper on udev (see Resources).

Resources for this article: /article/7496 [1].

Greg Kroah-Hartman currently is 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] [2].

Linux udev tip Assign Static SCSI Device Name

udev is the device manager for the Linux 2.6 kernel series. Its primary function is managing device nodes in /dev. Old UNIX system creates device in the /dev with static files. udev dynamically provides only the nodes for the devices actually present on a system.

Note following configuration is only tested on Gentoo / RHEL 5.x / CentOS 5.x Linux server systems but it should work with other distros with udev support.

Step # 1: Get WWID of the SCSI device

To get the WWID of /dev/sdd, type:
# scsi_id -g -u -s /block/sdd
Where,

Step # 2: Create /etc/udev/rules.d/25-names.rules file

Open /etc/udev/rules.d/25-names.rules and append following text (replace WWID with actual id obtained from above command):

KERNEL=="sd*", BUS=="scsi", PROGRAM=="/sbin/scsi_id -g -u -s %p", RESULT=="WWID", SYMLINK+="scsiharddisk%n"

Above rule will create /dev/scsiharddisk (a symlink - select any other meaningful name as per your proecjet ) for the SCSI device with a given WWID. Please note that partitions on this device will be assigned the device names like /dev/scsiharddisk1, /dev/scsiharddisk2 and so on. Next, verify that everything is correct order, enter:
# udevtest
Start initialize /dev for new devices:
# start_udev
Verify symbolic links are created, enter:
# ls -l /dev/scsiharddisk*

Read the man pages for more information:
man scsi_id
man udevtest
man 7 udev

Recommended Links



Etc

Society

Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers :   Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism  : The Iron Law of Oligarchy : Libertarian Philosophy

Quotes

War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda  : SE quotes : Language Design and Programming Quotes : Random IT-related quotesSomerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose BierceBernard Shaw : Mark Twain Quotes

Bulletin:

Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 :  Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method  : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law

History:

Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds  : Larry Wall  : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOSProgramming Languages History : PL/1 : Simula 67 : C : History of GCC developmentScripting Languages : Perl history   : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history

Classic books:

The Peter Principle : Parkinson Law : 1984 : The Mythical Man-MonthHow to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Hater’s Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite

Most popular humor pages:

Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor

The Last but not Least Technology is dominated by two types of people: those who understand what they do not manage and those who manage what they do not understand ~Archibald Putt. Ph.D


Copyright © 1996-2021 by Softpanorama Society. www.softpanorama.org was initially created as a service to the (now defunct) UN Sustainable Development Networking Programme (SDNP) without any remuneration. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License. Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.

FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available to advance understanding of computer science, IT technology, economic, scientific, and social issues. We believe this constitutes a 'fair use' of any such copyrighted material as provided by section 107 of the US Copyright Law according to which such material can be distributed without profit exclusively for research and educational purposes.

This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...

You can use PayPal to to buy a cup of coffee for authors of this site

Disclaimer:

The statements, views and opinions presented on this web page are those of the author (or referenced source) and are not endorsed by, nor do they necessarily reflect, the opinions of the Softpanorama society. We do not warrant the correctness of the information provided or its fitness for any purpose. The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be tracked by Google please disable Javascript for this site. This site is perfectly usable without Javascript.

Last modified: March 12, 2019