Udev efficiently and dynamically manages Linux Device Files

Source: Internet
Author: User
Tags symlink

Overview:

Linux users often have difficulty identifying device names of the same type, such as eth0, eth1, sda, and sdb. By observing the kernel device names of these devices, users usually know what types of devices they want, but do not know which devices they want. For example, in a device name list filled with ephemeral disks and Fiber-Optic Disks (/dev/sd*), You cannot find a disk with the serial number "35000c50000a7ef67. In this case, udev can dynamically/devDirectory to generate your desired and identified device files or device links, so that you can easily and quickly find the required device files.

Udev Introduction

What is udev?

Udev is a function in Linux kernel. It replaces the original devfs and becomes the default device management tool in Linux. Udev runs as a daemon and manages it by listening to uevents sent from the kernel./devDirectory. Unlike the previous device management tools, udev runs in user space instead of kernel space.

Benefits of using udev:

We all know that all devices exist in Linux as device files. In earlier Linux versions,/devThe directory contains all possible device files. It is hard to imagine how Linux users can find matching device files in these large numbers of device files. Now udev only generates device files for devices connected to the Linux operating system. In addition, udev can define a udev rule (rule) to generate device files that match device properties, these device attributes can be the kernel device name, bus path, vendor name, model, serial number, or disk size.

  • Dynamic Management: When a device is added/deleted, the udev daemon listens to uevents from the kernel to add or delete the device./devSo udev only generates device files for connected devices, instead/devGenerate a large number of device files.
  • Custom naming rules: In the default Linux rule file, udev defines the kernel device name for all devices in/dev/, such/dev/sda、/dev/hda、/dev/fdAnd so on. Because udev runs in user space, Linux users can flexibly generate device file names with strong identifiers through custom rule files, such/dev/boot_disk、/dev/root_disk、/dev/color_printerAnd so on.
  • Set Device Permissions and owner/group: udev can set the permission and owner/Group of device files according to certain conditions. In different udev versions, the implementation methods are different. We will explain in "how to configure and use udev.

The following flowchart shows how udev adds/deletes device files.

Figure 1. udev workflow:
 

Related Terms:

  • Device Files: As this document describes udev in a more popular way, the device file/dev/Files that can be used by applications to interact with device drivers. In this case, device files, device nodes, and device files are not classified into special regions.
  • Devfs:DevfsIt is an early Linux device management tool and has been replaced by udev.
  • Sysfs:SysfsIs a Virtual File System in the Linux 2.6 kernel.(/sys). It exports device and driver information from the kernel device module to the user space (userspace ). In this file system, Linux users can obtain the attributes of many devices.
  • Devpath:DevpathIndicates that a deviceSysfsFile System(/sys)The relative path of the device. The path contains the property file of the device. Most of the commands in udev areDevpathOperation. For example:SdaOfDevpathYes/block/sda, Sda2DevpathYes/block/sda/sda2.
  • Kernel device name: The device is onSysfsIs the default device file name used by udev.
 

Back to Top

How to configure and use udev

The following describes the udev configuration and usage on the rhel4.8 and rhel5.3 platforms:

Download and install udev

Udev is the default device management tool starting from fedora3 and Red Hat enterprise4. You do not need to download and install it.


Listing 1. Check the udev version and running status in RHEL4.8.

 [root@HOST_RHEL4 dev]# rpm -qa |grep -i udev  udev-039-10.29.el4  [root@HOST_RHEL4 ~]# uname -r  2.6.9-89.ELsmp  [root@HOST_RHEL4 ~]# ps -ef |grep udev  root     21826     1  0 Dec09 ?        00:00:00 udevd 

Listing 2. Check the udev version and running status in RHEL5.3.

 [root@HOST_RHEL5 ~]# rpm -qa |grep -i udev  udev-095-14.19.el5  [root@HOST_RHEL5 sysconfig]# uname -r  2.6.18-128.el5  [root@HOST_RHEL5 sysconfig]# ps -ef|grep udev  root      5466     1  0 18:32 ?      00:00:00 /sbin/udevd -d 

 

If you want to update the udev package, you can download and install it at http://www.kernel.org/pub/linux/utils/kernel/hotplug.

Udev configuration file (/etc/udev. conf)


Listing 3. udev configuration file under RHEL 4.8

 [root@HOST_RHEL4 dev]# cat /etc/udev/udev.conf  # udev.conf  # The 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.  #  # WARNING: changing any value, can cause serious system breakage!  #  # udev_root - where in the filesystem to place the device nodes  udev_root="/dev/" # udev_db - The name and location of the udev database.  udev_db="/dev/.udev.tdb" # 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  default_mode="0600" # default_owner - set the default owner for all nodes that have no  #                 explicit match in the permissions file  default_owner="root" # default_group - set the default group for all nodes that have no  #                 explicit match in the permissions file  default_group="root" # udev_log - set to "yes" if you want logging, else "no" udev_log="no"

 

Linux users can set the following parameters through this file:

  • UDev_root: The directory where the devices generated by udev are stored. The default value is/dev/. We recommend that you do not modify this parameter because many applications call device files from this directory by default.
  • Udev_db: The database or directory where udev information is stored. The default value is/dev/.udev.tdb.
  • Udev_rules: Name or directory of the udev rule file. The default value is/etc/udev/rules.d/.
  • Udev_permissions: Name or directory of the udev permission file. The default value is/etc/udev/permissions.d/.
  • DefauLt_mode/default_owner/default_group: If the permission of the device file is not specified in the permission file, use this parameter as the default permission. The default values are:0600/root/root.
  • Udev_log: Required or notSyslogThe switch that records udev logs. The default value is no.


Listing 4. udev configuration file under RHEL5.3

 [root@HOST_RHEL5 ~]# cat /etc/udev/udev.conf  # udev.conf  # The initial syslog(3) priority: "err", "info", "debug" or its  # numerical equivalent. For runtime debugging, the daemons internal  # state can be changed with: "udevcontrol log_priority=<value>".  udev_log="err"

 

Udev_log:SyslogThe log record level. The default value is err. If it is changed to info or debug, lengthy udev logs will be recorded.

In fact, in rhel5.3, apart from the parameters listed in the configuration fileUdev_logIn addition, Linux users can modify parameters.Udev_rootAndUdev_rules(Refer to the above "rhel4.8 udev configuration file"), but these two parameters are not recommended to be modified, so they are not displayed in udev. conf.

It can be seen that the udev. conf changes of this version are not small:SyslogUdev logs are recorded by default. Linux users can only modify the log level (ERR, info, degub, and so on). The device permission cannot be set in udev. conf, but in the Rule file (*. rules.

Use udev to set the permission for a device file

In the udev of RHEL4.8, the permission of the device is set through the permission file.


Listing 5. udev permission file under rhel4.8

 [root@HOST_RHEL4 ~]# cat /etc/udev/permissions.d/50-udev.permissions …… # disk devices  hd*:root:disk:0660  sd*:root:disk:0660  dasd*:root:disk:0660  ataraid*:root:disk:0660  loop*:root:disk:0660  md*:root:disk:0660  ide/*/*/*/*/*:root:disk:0660  discs/*/*:root:disk:0660  loop/*:root:disk:0660  md/*:root:disk:0660  # tape devices  ht*:root:disk:0660  nht*:root:disk:0660  pt[0-9]*:root:disk:0660  npt*:root:disk:0660  st*:root:disk:0660  nst*:root:disk:0660 ……

 

In RHEL4.8, The udev permission file sets the permission and ownership for all common devices. If a device is not configured with the permission file, udev will follow udev. the default permission value in conf sets permissions for these devices. Due to space limitations, only part of the udev permission file is displayed.SetPermission and ownership for all disk devices and tape devices that may be connected.

In RHEL5.3, The udev has no permission file and all permissions are obtained through the rule file.(*.rules)In the following rule file configuration process.

Udev rules and rules File

Rule files are the most important part of udev, which are stored in/etc/udev/rules.d/. All rule files must start with".rules"Is the suffix. RHEL has default rule files. These default rule files not only generate kernel device names for devices, but also generate symbolic links with strong identifiers. For example:

 [root@HOST_RHEL5 ~]# ls /dev/disk/by-uuid/  16afe28a-9da0-482d-93e8-1a9474e7245c 

 

However, these links have long names and are not easy to call. Therefore, you usually need to customize rule files to generate easy-to-use and distinguished device files or symbolic links.

In addition, some applications/dev/Generate some convenient symbolic links. For example, the 40-multipath.rules rule generates the following symbolic link for the disk:

 [root@ HOST_RHEL5 ~]# ls /dev/mpath/*  /dev/mpath/mpath0  /dev/mpath/mpath0p1  /dev/mpath/mpath0p2 

 

Udev queries all rule files alphabetically by the rule file name, and then manages its device files or file links for devices that match the rule. Although udev does not stop parsing the rule file after a device matches a rule, the parsing sequence is still important. In general, we recommend that you first parse the desired rule file. For example, create/etc/udev/rules.d/10-myrule.rulesFile, and write your rules to this file, so that udev will parse your file before parsing the default rule file of the system.

RHEL5.3's udev rule file is better than RHEL4.8. Due to space limitations, this article will not elaborate on the Rule file in RHEL4.8 to avoid confusion. The configuration and instance of the Rule file below are all performed on RHEL5.3. If you need to configure the RHEL4 udev rule file, you can first refer to the following RHEL5.3 configuration process, and then query the user manual (man udev) in RHEL4 for configuration.

In the rule file, except for the rows (comments) starting with "#", all non-empty rows are regarded as one rule, but one rule cannot be extended to multiple rows. All rules are composed of multipleKey-value pairs(Key-value pairs), separated by commas. key-value pairs can be dividedCondition matching key-value pairs(Hereinafter referred to as "Matching key"") AndValue assignment key-value pairs(Hereinafter referred to as "value assignment key""), A rule can have multiple matching keys and multiple value assignment keys. A matching key is a condition that matches all the properties of a device. When a property of a device matches all the matching keys in the rule, the rule takes effect and then follows the value assignment key, assign a value to execute this rule. The following is a simple rule:


Listing 6. A simple example of a key-Value Pair

 KERNEL=="sda", NAME="my_root_disk", MODE="0660"

 

KERNEL is the matching key, and NAME and MODE are the value assignment keys. This rule indicates that if the kernel device name of a device is sda, the condition takes effect and the value assigned after the condition is/devGeneratemy_root_diskAnd set the permission of the device file to 0660.

With this simple rule, you should have an intuitive understanding of the udev rule. However, it may be confusing why the KERNEL is the matching key and the NAME and MODE are the value assignment keys? This is determined by the operator in the middle.

Only when the operator is "=" or "! = ", It is the matching key; if it is another operator, it is the value assignment key.

  • All operators of udev rules in rhel5.3:

    "=": Comparison key and value. If the value is equal to, the condition is met;

    "!=": Comparison key and value. If it is not equal to, the condition is met;

    "=": Assigns a value to a key;

    "+ =": Assign a value to a key that represents multiple entries.

    ": =": Assign a value to a key, and reject all subsequent changes to the key. The purpose is to prevent subsequent rule files from assigning values to this key.

  • Matching key of udev rules in rhel5.3

    ACTION: Event (uevent) behavior, such as: add (add device), remove (delete device ).

    KERNEL: Kernel device name, such as SDA and CDROM.

    DEVPATH: Devpath of the device.

    SUBSYSTEMThe name of the sub-system of the device. For example, the sub-system of SDA is block.

    BUS: The name of the bus of the device in devpath, for example, USB.

    DRIVER: The name of the device driver in the devpath, for example, IDE-CDROM.

    ID: ID of the device in devpath.

    SYSFS {filename}: Content in the property file "FILENAME" of the device in the devpath path of the device.

    For example, sysfs {model }== "st936701ss" indicates that if the device model is st936701ss, the device matches thisMatching key.

    You can set up to five sysfsMatching key.

    ENV {key}: Environment variable. You can set up to five environment variables in a rule.Matching key.

    PROGRAM: Call External commands.

    RESULT: The returned results of the external command program. For example:

     PROGRAM=="/lib/udev/scsi_id -g -s $devpath", RESULT=="35000c50000a7ef67"

    Call External commands/lib/udev/scsi_idQuery the scsi id of a device. If the returned result is 35000c50000a7ef67, the device matchesMatching key.

  • Important udev value assignment key in rhel5.3

    NAME:In/devThe file name of the device. Only the assignment of the NAME of a device takes effect for the first time, and the assignment of the NAME of the device by matching rules will be ignored. If no rule is assigned to the device NAME, udev uses the kernel device NAME to generate the device file.

    SYMLINK:/dev/The device file under generates a symbolic link. Because udev can only generate one device file for a device, we recommend that you use Symbolic Links to avoid overwriting the files generated by the system's default udev rules.

    OWNER, GROUP, MODE:Set permissions for devices.

    ENV {key}: Import an environment variable.

  • The udev value in rhel5.3 and the substitution operator that can be called

    The key-value pairs and operators are all described, and finally the value ). Linux users can customize the value of the udev rule file at will. For example:my_root_disk, my_printer. You can also reference the following replacement operators:

    $ Kernel, % k: The name of the device's kernel device, such as sda and cdrom.

    $ Number, % n: The kernel number of the device. For example, the kernel number of sda3 is 3.

    $ Devpath, % p:DeviceDevpathPath.

    $ Id, % B:The device is onDevpathID.

    $ Sysfs {file}, % s {file}:DeviceSysfsFile. It is actually the property value of the device.
    For example, $ sysfs {size} indicates the size of the device (Disk.

    $ Env {key}, % E {key}:The value of an environment variable.

    $ Major, % M:The major number of the device.

    $ Minor % m:The minor number of the device.

    $ Result, % c:The result returned by the PROGRAM.

    $Parent, % P:The name of the parent device.

    $ Root, % r: Udev_rootValue. The default value is/dev/.

    $ Tempnode, % N:Temporary device name.

    %:Symbol % itself.

    $:Symbol $ itself.

    Listing 7. Example of rules for replacing Operators

     KERNEL=="sd*", PROGRAM="/lib/udev/scsi_id -g -s %p", \ RESULT=="35000c50000a7ef67", SYMLINK="%k_%c"

    Execution of this rule: if a kernel device name starts with SD and the scsi id is35000c50000a7ef67Generates a symbolic link "sda_35000c50000a7ef67" for the device file ".

 

Back to Top

Create udev rules and query instance information:

How to find device information (attributes) to develop udev rules:

When setting rules for a specified device, you must first know the properties of the device, such as the device serial number, disk size, vendor ID, and device path. Generally, we can use the following methods:

  • QuerySysfsFile System:

    As mentioned earlier, sysfs contains many device and driver information.

    For example, the sysfs {size} of the SDA device can pass throughcat /sys/block/sda/sizeThe sysfs {model} information can be obtained throughcat /sys/block/sda/device/model.

  • UdevinfoCommand:

    Udevinfo can query the device information in the udev database. For example, you can use udevinfo to query the model and size information of the SDA:

    Listing 8. Example of querying device properties through udevinfo

     [root@HOST_RHEL5 rules.d]# udevinfo -a -p /block/sda | egrep "model|size"    SYSFS{size}=="71096640"    SYSFS{model}=="ST936701SS      "
  • Other external commands:

    Listing 9. An example of querying a disk's scsi_id through SCSI_ID

     [root@HOST_RHEL5 ~]# scsi_id -g -s /block/sda  35000c50000a7ef67 

Simple udev rules:

Listing 10. Rules for generating Nic Device Files

 SUBSYSTEM=="net", SYSFS{address}=="AA:BB:CC:DD:EE:FF", NAME="public_NIC"

 

This rule indicates that if the sub-system of the device is net and the address (MAC address) is "AA: BB: CC: DD: EE: FF ", generate a device file named public_NIC for the device.


Listing 11. Rules for generating symbolic links for disks of the specified size

 SUBSYSTEM=="block", SYSFS{size}=="71096640", SYMLINK ="my_disk"

 

If the sub-system of a device is block and the size is 71096640 (block), a symbolic link named my_disk is generated for the device file name.


Listing 12. Rules for generating device files for disks with specified serial numbers using external commands

 KERNEL=="sd*[0-9]", PROGRAM=="/lib/udev/scsi_id -g -s %p", \ RESULT=="35000c50000a7ef67", NAME +="root_disk%n"

 

This rule indicates that if a device's kernel device name starts with sd (disk device) and ends with a number (disk partition ), run an external command to query the SCSI_ID of the device as "35000c50000a7ef67", generate a device file starting with root_disk and ending with the kernel number, and replace the original device file (if any ). For example, the device name is generated./dev/root_disk2, Replace the original device name/dev/sda2.

Using this rule, you can/etc/fstabTo ensure the consistency of the system partition names, without being affected by the driver loading sequence or disk label destruction. As a result, the system partition cannot be found when the operating system starts.

Other commonly used udev commands:

  • Udevtest:

    udevtestIt is simulated once for a device without a uevent.udevAnd output the process of querying the rule file, the executed behavior, and the execution result of the rule file. GenerallyudevtestTo debug the rule file. The following isudevtestExample. BecauseudevtestIs to scan all the rule files (including the built-in rule files), so it will produce lengthy output. To give readers a clear understandingudevtestIn this example, only one rule is retained in the Rule directory:

    Listing 13. Rules reserved for udevtest

     KERNEL=="sd*", PROGRAM="/lib/udev/scsi_id -g -s %p", RESULT=="35000c50000a7ef67", \ NAME="root_disk%n", SYMLINK="symlink_root_disk%n"

    Listing 14. udevtest Execution Process

     [root@HOST_RHEL5 rules.d]# udevtest /block/sda  main: looking at device '/block/sda' from subsystem 'block' run_program: '/lib/udev/scsi_id -g -s /block/sda' run_program: '/lib/udev/scsi_id' (stdout) '35000c50000a7ef67' run_program: '/lib/udev/scsi_id' returned with status 0  udev_rules_get_name: reset symlink list  udev_rules_get_name: add symlink 'symlink_root_disk' udev_rules_get_name: rule applied, 'sda' becomes 'root_disk' udev_device_event: device '/block/sda' already in database, \                  validate currently present symlinks  udev_node_add: creating device node '/dev/root_disk', major = '8', \            minor = '0', mode = '0660', uid = '0', gid = '0' udev_node_add: creating symlink '/dev/symlink_root_disk' to 'root_disk'

    As you can see,udevtestAn external command is executed on SDA.scsi_id. Then (simulate) generate the Device File/dev/root_diskAnd Symbolic Links/dev/symlink_root_diskAnd set permissions for it.

  • Start_udev:

    start_devCommand restartudevDaemon, re-query all rule files in the Rule directory for all devices, and then execute the actions in the matched rules. This command is usually used to make the new rule file take effect immediately:

    Listing 15. Execution of start_udev

     [root@HOST_RHEL5 rules.d]# start_udev  Starting udev:                                             [  OK  ] 

    start_udevAverageThere is no standard output, and all udev-related information follows the configuration file (udev.conf)BySyslogRecord.

 

Back to Top

Summary:

Udev is an efficient device management tool. Its biggest advantage is the dynamic management of devices and custom device naming rules. Therefore, replacing devfs becomes the default device management tool in Linux. By reading this article, Linux users can learn how udev works and processes, and use udev rule files flexibly to conveniently manage Linux Device Files.

 

References

  • For more information about udev, see http://www.kernel.org/pub/linux/utils/kernel/hotplug/udev.html.

  • In the developerworks Linux area, find more references for Linux developers (including new Linux beginners) and refer to our most popular articles and tutorials.
  • Read all Linux tips and Linux tutorials on developerWorks.

About the author

Zookeeper, a member of the Open Systems Interoperability validation lab storage testing team at IBM China Systems and Technology Lab. 3-4 years experience in testing Linux/Unix platforms and San/NAS storage products.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.