X-Git-Url: https://www.chiark.greenend.org.uk/ucgi/~ianmdlvl/git?a=blobdiff_plain;f=docs%2Fwriting_udev_rules%2Findex.html;h=ca4fb9d311f0f8b09fc9db6ca06c818f713ea559;hb=b02140b6bcd080c5fd60306a493447ce7afdad64;hp=1c5c89b3c91d512dd515f57621bd56aec2954c4a;hpb=731f0aec41e3f46f5b630e70166ab384976d52c6;p=elogind.git diff --git a/docs/writing_udev_rules/index.html b/docs/writing_udev_rules/index.html index 1c5c89b3c..ca4fb9d31 100644 --- a/docs/writing_udev_rules/index.html +++ b/docs/writing_udev_rules/index.html @@ -1,490 +1,892 @@ - + + + + Writing udev rules -

Writing udev rules

by Daniel Drake (dsd)
-Version 0.6

+Version 0.74

The most recent version of this document can always be found at:
-http://www.reactivated.net/udevrules.php + +http://www.reactivated.net/writing_udev_rules.html

Contents

-
    -
  1. About this document
  2. -
  3. History
  4. -
  5. Software versions used at time of writing
  6. -
  7. Terminology: devfs, sysfs, nodes, etc.
  8. - -
  9. Why? (The purpose of this document)
  10. -
  11. The basics of writing rules
  12. -
  13. Additional automated customisation for NAME and SYMLINK parameters
  14. -
  15. Using shell-style pattern matching in keys
  16. -
  17. Key-writing basics
  18. -
  19. Identifying devices through basic keys
  20. -
  21. Identifying devices through SYSFS files
  22. -
  23. Using multiple SYMLINK style rules
  24. -
  25. Controlling ownership and permissions
  26. -
  27. Example: Writing a rule for my USB printer
  28. -
  29. Example: Writing a rule for my USB-Storage digital camera
  30. - -
  31. Additional notes on writing rules for USB storage
  32. -
  33. Example: Writing convenience rules for my CD drives
  34. -
  35. Example: Writing a rule to name my network interface
  36. -
  37. Tips for finding the appropriate places in SYSFS
  38. -
  39. Debugging your rules
  40. -
  41. Author and credits
  42. -
+ + +

Introduction

-

About this document

-udev is targetted at Linux kernels 2.6 and beyond to provide a userspace solution for a dynamic /dev directory, with persistent device naming. The previous /dev implementation, devfs, is now deprecated, and udev is seen as the successor. udev vs devfs is a sensitive area of conversation - you should read this document before making comparisons.

+

About this document

-udev is a well thought out solution, but I was initially very confused how I might customise it for my system. This document attempts to make the process of rule writing a little bit clearer.

+

+udev is targeted at Linux kernels 2.6 and beyond to provide a userspace solution for a dynamic /dev directory, with persistent device naming. The previous /dev implementation, devfs, is now deprecated, and udev is seen as the successor. udev vs devfs is a sensitive area of conversation - you should read this document before making comparisons. +

-I'm all open to feedback - please contact me with any comments, problems, and suggested improvements.

+

+Over the years, the things that you might use udev rules for has changed, as well as the flexibility of rules themselves. On a modern system, udev provides persistent naming for some device types out-of-the-box, eliminating the need for custom rules for those devices. However, some users will still require the extra level of customisation. +

-This document assumes that you have udev/hotplug installed and running OK with default configurations. If you do not yet have udev configured and running, I would suggest that you follow Decibels udev Primer to get to this stage (contains some Gentoo Linux specifics, but should be useful for other distro's too).

+

+This document assumes that you have udev installed and running OK with default configurations. This is usually handled by your Linux distribution. +

+ +

+This document does not cover every single detail of rule writing, but does aim to introduce all of the main concepts. The finer details can be found in the udev man page. +

+ +

+This document uses various examples (many of which are entirely fictional) to illustrate ideas and concepts. Not all syntax is explicitly described in the accompanying text, be sure to look at the example rules to get a complete understanding. +

+

History

-

History

- -May 9th 2005 v0.6: Misc updates, including information about udevinfo, groups and permissions, logging, and udevtest.

-June 20th 2004 v0.55: Added info on multiple symlinks, and some minor changes/updates.

-April 26th 2004 v0.54: Added some Debian info. Minor corrections. Re-reverted information about what to call your rule file. Added info about naming network interfaces.

-April 15th 2004 v0.53: Minor corrections. Added info about NAME{all_partitions}. Added info about other udevinfo tricks.

-April 14th 2004 v0.52: Reverted to suggesting using "udev.rules" until the udev defaults allow for other files. Minor work.

-April 6th 2004 v0.51: I now write suggest users to use their own "local.rules" file rather than prepending "udev.rules".

-April 3rd 2004 v0.5: Minor cleanups and preparations for possible inclusion in the udev distribution.

-March 20th 2004 v0.4: General improvements, clarifications, and cleanups. Added more information about writing rules for usb-storage.

-February 23rd 2004 v0.3: Rewrote some parts to emphasise how sysfs naming works, and how it can be matched. Updated rule-writing parts to represent udev 018s new SYSFS{filename} naming scheme. Improved sectioning, and clarified many points. Added info about KDE.

-February 18th 2004 v0.2: Fixed a small omission in an example. Updated section on identifying mass-storage devices. Updated section on nvidia.

-February 15th 2004 v0.1: Initial publication.

- - -

Software versions used at time of writing

-Linux Kernel 2.6.11
-udev 056

+ + +

The concepts

-

Terminology: devfs, sysfs, nodes, etc.

-A basic introduction only, might not be totally accurate.

+

Terminology: devfs, sysfs, nodes, etc.

+ +

+A basic introduction only, might not be totally accurate. +

-On typical linux-based systems, the /dev directory is used to store file-like device nodes which refer to certain devices in the system. Each node points to a part of the system (a device), which might or might not exist. Userspace applications can use these device nodes to interface with the systems hardware, for example, XFree86 will "listen to" /dev/input/mice so that it can relate the users mouse movements to moving the visual mouse pointer.

+

+On typical Linux-based systems, the /dev directory is used to store file-like device nodes which refer to certain devices in the system. Each node points to a part of the system (a device), which might or might not exist. Userspace applications can use these device nodes to interface with the systems hardware, for example, the X server will "listen to" /dev/input/mice so that it can relate the user's mouse movements to moving the visual mouse pointer. +

-The original /dev directories were just populated with every device that might possibly appear in the system. /dev directories were typically very large because of this. devfs came along to provide a more managable approach (noticably, it only populated /dev with hardware that is plugged into the system), as well as some other functionality, but the system proved to have problems which could not be easily fixed.

+

+The original /dev directories were just populated with every device that might possibly appear in the system. /dev directories were typically very large because of this. devfs came along to provide a more manageable approach (noticeably, it only populated /dev with hardware that is plugged into the system), as well as some other functionality, but the system proved to have problems which could not be easily fixed. +

-udev is the "new" way of managing /dev directories, designed to clear up some issues with previous /dev implementations, and provide a robust path forward. In order to create and name /dev device nodes corresponding to devices that are present in the system, udev relies on matching information provided by sysfs with rules provided by the user. This documentation aims to detail the process of rule-writing, one of the only udev-related tasks that must (optionally) be performed by the user.

+

+udev is the "new" way of managing /dev directories, designed to clear up some issues with previous /dev implementations, and provide a robust path forward. In order to create and name /dev device nodes corresponding to devices that are present in the system, udev relies on matching information provided by sysfs with rules provided by the user. This documentation aims to detail the process of rule-writing, one of the only udev-related tasks that must (optionally) be performed by the user. +

-sysfs is a new filesystem to the 2.6 kernels. It is managed by the kernel, and exports basic information about the devices currently plugged into your system. udev can use this information to create device nodes corresponding to your hardware. sysfs is mounted at /sys and is browsable. You may wish to investigate some of the files stored there before getting to grips with udev. Throughout this document, I will use the terms /sys and SYSFS interchangeably.


+

+sysfs is a new filesystem to the 2.6 kernels. It is managed by the kernel, and exports basic information about the devices currently plugged into your system. udev can use this information to create device nodes corresponding to your hardware. sysfs is mounted at /sys and is browseable. You may wish to investigate some of the files stored there before getting to grips with udev. Throughout this document, I will use the terms /sys and sysfs interchangeably. +

-

Why?

+

Why?

-As stated above, writing rules for udev is an optional process. By default, you can plug a device in, and the a relevant node (e.g. /dev/sda for a mass-storage device) will be there, just like in previous /dev implementations.

+

+udev rules are flexible and very powerful. Here are some of the things you can use rules to achieve: +

-However, udev allows you to customise the naming of device nodes. There are two reasons why you might want to do this: convenience, and persistent naming.

+ -Take the example of using udev, so that when your printer is plugged in, it gets named as /dev/printer and also as the usual /dev/lp0. It's not only convenience (e.g. reading and interpreting "printer" as opposed to "lp0"), its a solution for non-persistent naming. Say that I have two printers - a HP laser printer and an Epson inkjet. When they are both plugged in and on, I have /dev/lp0 and /dev/lp1.
+

+Writing rules is not a workaround for the problem where no device nodes for your particular device exist. Even if there are no matching rules, udev will create the device node with the default name supplied by the kernel. +

-How do I know which node refers to which printer? There is no easy way. The first printer that got connected was assigned name "lp0", and the second "lp1". Plugging in my printers in a different order would swap the names here, and that would mess up my scripts that always expect my HP laser printer to be lp1.

+

+Having persistently named device nodes has several advantages. Assume you own two USB storage devices: a digital camera and a USB flash disk. These devices are typically assigned device nodes /dev/sda and /dev/sdb but the exact assignment depends on the order which they were originally connected. This may cause problems to some users, who would benefit greatly if each device could be named persistently every time, e.g. /dev/camera and /dev/flashdisk. +

-However, if my HP laser printer got named lp_hp (as well as lpX) and my other printer got named lp_epson (as well as lpY), then my scripts could just refer to those names. udev magic can control this and ensure that these persistent names always point to the device that I intended.

+ +

Built-in persistent naming schemes

-For external mass-storage devices (e.g. usb hard disks), persistent naming is very helpful in that it allows you to hardcode accurate device paths into your /etc/fstab.

+

+udev provides persistent naming for some device types out of the box. This is a very useful feature, and in many circumstances means that your journey ends here: you do not have to write any rules. +

-It is important to understand that writing rules is simply a means of customizing udev behaviour. Writing rules is not a workaround for the problem where no device nodes for your particular device exist. If no matching rules exist, udev will create the node anyway, using the name that was supplied by the kernel.

+

+udev provides out-of-the-box persistent naming for storage devices in the /dev/disk directory. To view the persistent names which have been created for your storage hardware, you can use the following command: +

- -

The basics of writing rules

+
# ls -lR /dev/disk
-When populating /dev, udev decides which nodes to include, and how to name them, by reading a series of rules files.

+

+This works for all storage types. As an example, udev has created /dev/disk/by-id/scsi-SATA_ST3120827AS_4MS1NDXZ-part3 which is a persistent-named symbolic link to my root partition. udev creates /dev/disk/by-id/usb-Prolific_Technology_Inc._USB_Mass_Storage_Device-part1 when I plug my USB flash disk in, which is also a persistent name. +

-Default udev rules are stored in /etc/udev/rules.d/50-udev.rules. You may find it interesting to look over this file - it includes a few examples, and then some default rules proving a devfs-style /dev layout. However, you should not write rules into this file directly, to reduce hassle while updating your udev installation in the future.

+ -Files in /etc/udev/rules.d/ are parsed in lexical order. udev will stop processing rules as soon as it finds a matching rule in a file for the new item of hardware that has been detected. It is important that your own rules get processed before the udev defaults, otherwise your own naming schemes will not take effect! I suggest that you keep your own rules in a file at /etc/udev/rules.d/10-local.rules (this doesn't exist by default - create it). As 10 comes before 50, you know that your rules will be looked at first. It is important that the filenames of your rule files end with the .rules suffix, otherwise they will not be used.

+

Rule writing

-As your own rules will effectively mask out the udev defaults which create the base /dev layout, it is recommended that you also specify devfs-style names/symlinks for the rules you write, so that you get the sensible defaults plus your own names.

+ +

Rule files and semantics

-In rule files, lines starting with a "#" are treated as comments. Every uncommented line in the file corresponds to a rule.

+

+When deciding how to name a device and which additional actions to perform, udev reads a series of rules files. These files are kept in the /etc/udev/rules.d directory, and they all must have the .rules suffix. +

-Rules are composed of keys. Keys are seperated by commas. Some keys are used for reading and matching information, others are used for assigning information and performing actions. Matches and assignments are carried out with the expected operators (= and ==). +

+Default udev rules are stored in /etc/udev/rules.d/50-udev.rules. You may find it interesting to look over this file - it includes a few examples, and then some default rules proving a devfs-style /dev layout. However, you should not write rules into this file directly. +

-
    -
  1. At least one identification key should be provided, which will match the rule to any number of devices in the system. These are listed in the later section: Identifying devices through basic keys.
  2. -
  3. At least one assignment key should be provided, to control how the resultant device node is created. These include NAME, SYMLINK, OWNER, GROUP and MODE, all of which are described in this document.
  4. -
+

+Files in /etc/udev/rules.d/ are parsed in lexical order, and in some circumstances, the order in which rules are parsed is important. In general, you want your own rules to be parsed before the defaults, so I suggest you create a file at /etc/udev/rules.d/10-local.rules and write all your rules into this file. +

-Common rules will use basic identification keys to determine the device to name, and then have a NAME assignement key to define the device node name. udev will only create one node for one device, so if you want it to be accessible through multiple nodes, then you have to specify the other nodes in the SYMLINK assignment key.

+

+In a rules file, lines starting with "#" are treated as comments. Every other non-blank line is a rule. Rules cannot span multiple lines. +

-I'll take a slightly modified udev example rule to illustrate this: -
BUS=="usb", SYSFS{serial}=="HXOLL0012202323480", NAME="lp_epson", SYMLINK="printers/epson_stylus"
+

+One device can be matched by more than one rule. This has it's practical advantages, for example, we can write two rules which match the same device, where each one provides its own alternate name for the device. Both alternate names will be created, even if the rules are in separate files. It is important to understand that udev will not stop processing when it finds a matching rule, it will continue searching and attempt to apply every rule that it knows about. +

-The identification keys here are BUS and SYSFS{serial}. The assignment keys here are NAME and SYMLINK. udev will match this rule against a device that is connected through the USB bus and with a serial number of HXOLL0012202323480. Note that all (as opposed to any) specified keys must be matched for udev to use the rule to name a device.
+ +

Rule syntax

-udev will name this node lp_epson, and it will be located at /dev/lp_epson.
-udev will also create a symlink to /dev/lp_epson, located at /dev/printers/epson_stylus (the printers directory will be automatically created). You can now print to your Epson printer by sending data to /dev/printers/epson_stylus or /dev/lp_epson.

+

+Each rule is constructed from a series of key-value pairs, which are separated by commas. match keys are conditions used to identify the device which the rule is acting upon. When all match keys in a rule correspond to the device being handled, then the rule is applied and the actions of the assignment keys are invoked. Every rule should consist of at least one match key and at least one assignment key. +

-Any rules that you have added or modified will not take effect until you notify udev of this. Make sure you remember to run the following every time you modify any rule files: -
# udevstart
+

+Here is an example rule to illustrate the above: +

- -

Additional automated customisation for NAME and SYMLINK parameters

+
KERNEL=="hdb", NAME="my_spare_disk"
-In the NAME and SYMLINK parameters of your rules, you are able to use basic operators to assist the naming of devices. Hackers will know this sort of thing as printf-like string substitution. +

+The above rule includes one match key (KERNEL) and one assignment key (NAME). The semantics of these keys and their properties will be detailed later. It is important to note that the match key is related to its value through the equality operator (==), whereas the assignment key is related to its value through the assignment operator (=). +

-There are a number of operators which can compose some or all of your NAME/SYMLINK parameters. These operators refer to kernel-data relating to the device. Take this example: +

+Be aware that udev does not support any form of line continuation. Do not insert any line breaks in your rules, as this will cause udev to see your one rule as multiple rules and will not work as expected. +

-
BUS=="usb", SYSFS{vendor}=="FUJIFILM", SYSFS{model}=="M100", NAME="camera%n"
+ +

Basic Rules

-The %n operator will be replaced with the "kernel number" for the camera device, to produce a NAME such as camera0, camera1, etc.

+

+udev provides several different match keys which can be used to write rules which match devices very precisely. Some of the most common keys are introduced below, others will be introduced later in this document. For a complete list, see the udev man page. +

-Another common operator is %k. This represents what the kernel would name the device, e.g. "hda1". You may often see rules which have NAME="%k" to produce the default names for the hardware. In these rules, customisation is usually done through the SYMLINK parameter.

+ -A full list of operators, with explanations, can be found in the udev man page.

+

+After you have used a series of match keys to precisely match a device, udev gives you fine control over what happens next, through a range of assignment keys. For a complete list of possible assignment keys, see the udev man page. The most basic assignment keys are introduced below. Others will be introduced later in this document. +

- -

Using shell-style pattern matching in keys

+ -You can use shell style pattern matching to provide even more flexibility when writing keys. Taking a default udev rule: +

+As hinted above, udev only creates one true device node for one device. If you wish to provide alternate names for this device node, you use the symbolic link functionality. With the SYMLINK assignment, you are actually maintaining a list of symbolic links, all of which will be pointed at the real device node. To manipulate these links, we introduce a new operator for appending to lists: +=. You can append multiple symlinks to the list from any one rule by separating each one with a space. +

-
KERNEL=="ts*", NAME="input/%k"
+
KERNEL=="hdb", NAME="my_spare_disk"
-The * operator is used here, which matches literally anything - zero, one, or more characters of any kind. The rule literally says:
+

+The above rule says: match a device which was named by the kernel as hdb, and instead of calling it hdb, name the device node as my_spare_disk. The device node appears at /dev/my_spare_disk. +

-
Match a device identified by a KERNEL name starting with the letters "ts" optionally followed by anything at all, and name it with the KERNEL name (%k) under the input directory.
+
KERNEL=="hdb", DRIVER=="ide-disk", SYMLINK+="sparedisk"
-The ? operator is similar, and matches any single character (but not zero characters).

+

+The above rule says: match a device which was named by the kernel as hdb AND where the driver is ide-disk. Name the device node with the default name and create a symbolic link to it named sparedisk. Note that we did not specify a device node name, so udev uses the default. In order to preserve the standard /dev layout, your own rules will typically leave the NAME alone but create some SYMLINKs and/or perform other assignments. +

-You can also use square brackets [ ] to match any single character. Direct quote from udev man page:
-
For example, the pattern string "tty[SR]" would match either "ttyS" or "ttyR".
+
KERNEL=="hdc", SYMLINK+="cdrom cdrom0"
-You can also specify ranges that can be matched, e.g. [0-9] would match any single digit. Using an example rule from a default udev installation: +

+The above rule is probably more typical of the types of rules you might be writing. It creates two symbolic links at /dev/cdrom and /dev/cdrom0, both of which point at /dev/hdc. Again, no NAME assignment was specified, so the default kernel name (hdc) is used. +

-
KERNEL=="fd[0-9]*", NAME="floppy/%n"
+ +

Matching sysfs attributes

-This rule says:
+

+The match keys introduced so far only provide limited matching capabilities. Realistically we require much finer control: we want to identify devices based on advanced properties such as vendor codes, exact product numbers, serial numbers, storage capacities, number of partitions, etc. +

-
Match a device identified by a KERNEL name starting with the letters "fd", followed by any single digit, optionally followed by anything at all. Name the device with the kernel number of the device (%n) under the floppy directory.
+

+Many drivers export information like this into sysfs, and udev allows us to incorporate sysfs-matching into our rules, using the ATTR key with a slightly different syntax. +

-You can use these wildcards/pattern matches in any type of key, including both basic keys and sysfs-based identification (see below for explanations of these key types).

+

+Here is an example rule which matches a single attribute from sysfs. Further detail will be provided later in this document which will aid you in writing rules based on sysfs attributes. +

-I have purposely left out some information on this topic (particularly the flexibility of using [ ] operators) that is out of the scope of basic rule-writing documentation. More information on this topic can be found in the udev man page.

+
+SUBSYSTEM=="block", ATTR{size}=="234441648", SYMLINK+="my_disk"
+
- -

Key-writing basics

+ +

Device hierarchy

-udev provides a few basic key matching methods, and also provides flexible ways of matching information in SYSFS. A typical rule will match both normal keys (e.g. BUS and KERNEL), as well as SYSFS keys to differentiate between different hardware plugged in throught the same port.

+

+The Linux kernel actually represents devices in a tree-like structure, and this information is exposed through sysfs and useful when writing rules. For example, the device representation of my hard disk device is a child of the SCSI disk device, which is in turn a child of the Serial ATA controller device, which is in turn a child of the PCI bus device. It is likely that you will find yourself needing to refer to information from a parent of the device in question, for example the serial number of my hard disk device is not exposed at the device level, it is exposed by its direct parent at the SCSI disk level. +

-You may be wondering, "How do I find the serial number of my printer? What is the model of my camera?". Rule writing isn't as hard as it sounds. The trickiest bit is finding your device in /sys, and deciding which info to use.

+

+The four main match keys introduced so far (KERNEL/SUBSYSTEM/DRIVER/ATTR) only match against values corresponding to the device in question, and do not match values from parent devices. udev provides variants of the match keys that will search upwards through the tree: +

- -

Identifying devices through basic keys

+ -See the udev man page for more info on these keys.

+

+With hierarchy considerations in mind, you may feel that rule writing is becoming a little complicated. Rest assured that there are tools that help out here, which will be introduced later. +

-The valid keys are: - +

+When writing rules which will potentially handle multiple similar devices, udev's printf-like string substitution operators are very useful. You can simply include these operators in any assignments your rule makes, and udev will evaluate them when they are executed. +

-The ID and PLACE keys do have their uses, but they are not commonly used in rules. This document focuses on using BUS and KERNEL keys, as well as SYSFS{...} keys (detailed in the next section). I will show how to use these keys by example.

+

+The most common operators are %k and %n. %k evaluates to the kernel name for the device, e.g. "sda3" for a device that would (by default) appear at /dev/sda3. %n evaluates to the kernel number for the device (the partition number for storage devices), e.g. "3" for /dev/sda3. +

-For extra flexibility, udev also provides keys to call external scripts and examine their result, and to examine environment variables. This is out of scope of this document. Look at the udev man page for more details. +

+udev also provides several other substitution operators for more advanced functionality. Consult the udev man page after reading the rest of this document. There is also an alternative syntax for these operators - $kernel and $number for the examples above. For this reason, if you wish to match a literal % in a rule then you must write %%, and if you wish to match a literal $ then you must write $$. +

- -

Identifying devices through SYSFS files

+

+To illustrate the concept of string substitution, some example rules are shown below. +

-Background information: SYSFS stores many small files under a tree of directories which provide information about your hardware. One file typically contains just one "data item" - e.g. device name, manufacturer, or product ID.

-Note that SYSFS{...} keys can be combined with the basic keys described in the previous section.


+
+KERNEL=="mice", NAME="input/%k"
+KERNEL=="loop0", NAME="loop/%n", SYMLINK+="%k"
+
-You can use keys in the format SYSFS{filename} to match specific info from SYSFS, where filename corresponds to a file in your SYSFS tree. For example, when my camera is connected, there is a file located at /sys/block/sda/device/model which contains "USB 2.0M DSC". To match this, I could use the following key: SYSFS{model} == "USB 2.0M DSC"

+

+The first rule ensures that the mice device node appears exclusively in the /dev/input directory (by default it would be at /dev/mice). The second rule ensures that the device node named loop0 is created at /dev/loop/0 but also creates a symbolic link at /dev/loop0 as usual. +

-Note that any file in sysfs can be matched in this manner, but if you match more than one file (through multiple keys), then you must only match files that exist in the same directory. Typically, there will be several directories giving information about one device. You cannot mix and match (as shown by example below).

+

+The use of the above rules is questionable, as they all could be rewritten without using any substitution operators. The true power of these substitutions will become apparent in the next section. +

-Luckily, the process of rule writing does not entail hunting through millions of files in SYSFS, the udevinfo utility does the hard work. This program is included in the udev distribution.

+ +

String matching

-The first thing you need to do is find a directory somewhere in /sys that corresponds to your hardware, and includes a file named "dev", as udevinfo can only work on directories of this type. These directories are all found under either /sys/block or /sys/class - there is no point looking anywhere else! However, udevinfo will follow links through this directory and read info found from other sections of sysfs.

+

+As well as matching strings exactly, udev allows you to use shell-style pattern matching. There are 3 patterns supported: +

-Once you have found a directory of this type, you can use the following command to assist you in the creation of writing keys for udev rules: -
# udevinfo -a -p /sys/path/to/hardware/info
+ + +

+Here are some examples which incorporate the above patterns. Note the use of the string substitution operators. +

-You may find that finding the correct place in /sys to run udevinfo on is not obvious. Chances are the device you just plugged in has already careted a device node (e.g. /dev/sda), in which case, udevinfo can be helpful! Taking the example of my /dev/sda node, running the following command will point you to the appropriate area of sysfs:
-# udevinfo -q path -n /dev/sda
+KERNEL=="fd[0-9]*", NAME="floppy/%n", SYMLINK+="%k"
+KERNEL=="hiddev*", NAME="usb/%k"
+
+ +

+The first rule matches all floppy disk drives, and ensures that the device nodes are placed in the /dev/floppy directory, as well as creating a symbolic link from the default name. The second rule ensures that hiddev devices are only present in the /dev/usb directory. +

+ +

Finding information from sysfs

+ + +

The sysfs tree

+ +

+The concept of using interesting information from sysfs was briefly touched upon above. In order to write rules based on this information, you first need to know the names of the attributes and their current values. +

-/block/sda +

+sysfs is actually a very simple structure. It is logically divided into directories. Each directory contains a number of files (attributes) which typically contain just one value. Some symbolic links are present, which link devices to their parents. The hierarchical structure was touched upon above. +

+ +

+Some directories are referred to as top-level device paths. These directories represent actual devices that have corresponding device nodes. Top-level device paths can be classified as sysfs directories which contain a dev file, the following command will list these for you: +

+ +
# find /sys -name dev
+ +

+For example, on my system, the /sys/block/sda directory is the device path for my hard disk. It is linked to it's parent, the SCSI disk device, through the /sys/block/sda/device symbolic link. +

+ +

+When you write rules based on sysfs information, you are simply matching attribute contents of some files in one part of the chain. For example, I can read the size of my hard disk as follows: +

+ +
+# cat /sys/block/sda/size
+234441648
 
-The output of the command (shown above) is telling me that the sysfs path to start at is /sys/block/sda. I would now run "udevinfo -a -p /sys/block/sda". These two commands can be chained together, like so: +

+In a udev rule, I could use ATTR{size}=="234441648" to identify this disk. As udev iterates through the entire device chain, I could alternatively opt to match attributes in another part of the chain (e.g. attributes in /sys/class/block/sda/device/) using ATTRS, however there are some caveats when dealing with different parts of the chain which are described later. +

-
# udevinfo -a -p $(udevinfo -q path -n /dev/sda)
+

+Although this serves as a useful introduction as to the structure of sysfs and exactly how udev matches values, manually trawling through sysfs is both time consuming and unnecessary. +

-Sidenote: You may notice that we previously provided full paths (/sys/some/path) to udevinfo beforehand, but now we are providing sysfs-relative paths (/some/path) by chaining these commands. This does not matter - both types of path are accepted.

+ +

udevadm info

-Moving on to rule-writing, some snipped output of the results of my "udevinfo -a -p /sys/block/sda" command is shown below, with colour added.
+

+Enter udevadm info, which is probably the most straightforward tool you can use to construct rules. All you need to know is the sysfs device path of the device in question. A trimmed example is shown below: +

-

-follow the class device's "device"
-  looking at the device chain at '/sys/devices/pci0000:00/0000:00:02.1/usb3/3-3/3-3:1.0/host0/0:0:0:0':
-    BUS=="scsi"
-    ID=="0:0:0:0"
-    SYSFS{detach_state}=="0"
-    SYSFS{type}=="0"
-    SYSFS{max_sectors}=="240"
-    SYSFS{device_blocked}=="0"
-    SYSFS{queue_depth}=="1"
-    SYSFS{scsi_level}=="3"
-    SYSFS{vendor}=="        "
-    SYSFS{model}=="USB 2.0M DSC    "
-    SYSFS{rev}=="1.00"
-    SYSFS{online}=="1"
-
-  looking at the device chain at '/sys/devices/pci0000:00/0000:00:02.1/usb3/3-3':
-    BUS=="usb"
-    ID=="3-3"
-    SYSFS{detach_state}=="0"
-    SYSFS{bNumInterfaces}==" 1"
-    SYSFS{bConfigurationValue}=="1"
-    SYSFS{bmAttributes}=="c0"
-    SYSFS{bMaxPower}=="  0mA"
-    SYSFS{idVendor}=="052b"
-    SYSFS{idProduct}=="1514"
-    SYSFS{bcdDevice}=="0100"
-    SYSFS{bDeviceClass}=="00"
-    SYSFS{bDeviceSubClass}=="00"
-    SYSFS{bDeviceProtocol}=="00"
-    SYSFS{bNumConfigurations}=="1"
-    SYSFS{speed}=="12"
-    SYSFS{manufacturer}=="Tekom Technologies, Inc"
-    SYSFS{product}=="USB 2.0M DSC"
-
+
+# udevadm info -a -p /sys/block/sda
+
+  looking at device '/block/sda':
+    KERNEL=="sda"
+    SUBSYSTEM=="block"
+    ATTR{stat}=="  128535     2246  2788977   766188    73998   317300  3132216  5735004        0   516516  6503316"
+    ATTR{size}=="234441648"
+    ATTR{removable}=="0"
+    ATTR{range}=="16"
+    ATTR{dev}=="8:0"
+
+  looking at parent device '/devices/pci0000:00/0000:00:07.0/host0/target0:0:0/0:0:0:0':
+    KERNELS=="0:0:0:0"
+    SUBSYSTEMS=="scsi"
+    DRIVERS=="sd"
+    ATTRS{ioerr_cnt}=="0x0"
+    ATTRS{iodone_cnt}=="0x31737"
+    ATTRS{iorequest_cnt}=="0x31737"
+    ATTRS{iocounterbits}=="32"
+    ATTRS{timeout}=="30"
+    ATTRS{state}=="running"
+    ATTRS{rev}=="3.42"
+    ATTRS{model}=="ST3120827AS     "
+    ATTRS{vendor}=="ATA     "
+    ATTRS{scsi_level}=="6"
+    ATTRS{type}=="0"
+    ATTRS{queue_type}=="none"
+    ATTRS{queue_depth}=="1"
+    ATTRS{device_blocked}=="0"
+
+  looking at parent device '/devices/pci0000:00/0000:00:07.0':
+    KERNELS=="0000:00:07.0"
+    SUBSYSTEMS=="pci"
+    DRIVERS=="sata_nv"
+    ATTRS{vendor}=="0x10de"
+    ATTRS{device}=="0x037f"
+
-The udevinfo tool provides a lot of information which you can simply copy-paste as udev rules. The reason that I have colour coded the above output is to point out that you generally cannot mix and match information from different parts of the udevinfo output. In the above output, I could not combine information from the different coloured sections - this is because each section of output refers to a different directory in SYSFS. For example, the following rule would not work: -
BUS=="scsi", SYSFS{manufacturer}=="Tekom Technologies, Inc", NAME="%k"
-This rule would not work because I am combining information found in the section beginning with BUS=="scsi" (green) with information only found in the blue section. The rule would work if I used BUS=="usb", sticking only to information found in the blue section above.

+

+As you can see, udevadm info simply produces a list of attributes you can use as-is as match keys in your udev rules. From the above example, I could produce (e.g.) either of the following two rules for this device: +

-You will notice that a lot of information is not relevant for writing basic rules (there is so much of it!), you should generally be looking for information that you recognise and know will not change (e.g. model name).

+
+SUBSYSTEM=="block", ATTR{size}=="234441648", NAME="my_hard_disk"
+SUBSYSTEM=="block", SUBSYSTEMS=="scsi", ATTRS{model}=="ST3120827AS", NAME="my_hard_disk"
-Note that if you write your own rule to identify a device, the default devfs-style rules will not take effect! It is usually sensible to use NAME="%k" and specify your own extra names in the SYMLINK parameter so that you do not lose the default sensible names.

+

+You may have noted the use of colour in the above examples. This is to demonstrate that while it is legal to combine the attributes from the device in question and a single parent device, you cannot mix-and-match attributes from multiple parent devices - your rule will not work. For example, the following rule is invalid as it attempts to match attributes from two parent devices: +

-I will show three examples of this rule writing based on udevinfo output process below. I will then attempt to list some device-dependant tips and tricks for locating the correct info.

+
+SUBSYSTEM=="block", ATTRS{model}=="ST3120827AS", DRIVERS=="sata_nv", NAME="my_hard_disk"
-A reader wrote to me and informed me that he found KDE's control centre useful for writing rules. Apparently, information about USB devices (and others) can be found in the "Info Centre" section of the KDE Control Centre. This interface shows information such as serial number, vendor ID, etc. If you prefer a GUI-like approach, you might want to investigate this.

+

+You are usually provided with a large number of attributes, and you must pick a number of them to construct your rule. In general, you want to choose attributes which identify your device in a persistent and human-recognisable way. In the examples above, I chose the size of my disk and its model number. I did not use meaningless numbers such as ATTRS{iodone_cnt}=="0x31737". +

-The current releases of gnome-volume-manager are unable to treat symlink-nodes as real devices. Conversely as described above, you may wish to specify your own naming in the NAME parameter and specify %k in the SYMLINK parameter.

+

+Observe the effects of hierarchy in the udevadm info output. The green section corresponding to the device in question uses the standard match keys such as KERNEL and ATTR. The blue and maroon sections corresponding to parent devices use the parent-traversing variants such as SUBSYSTEMS and ATTRS. This is why the complexity introduced by the hierarchical structure is actually quite easy to deal with, just be sure to use the exact values that udevadm info suggests. +

-The behaviour of your own rules masking the defaults can be overcome if you write multiple-SYMLINK style rules. +

+Another point to note is that it is common for text attributes to appear in the udevadm info output to be padded with spaces (e.g. see ST3120827AS above). In your rules, you can either specify the extra spaces, or you can cut them off as I have done. +

-
+

+The only complication with using udevadm info is that you are required to know the top-level device path (/sys/block/sda in the example above). This is not always obvious. However, as you are generally writing rules for device nodes which already exist, you can use udevadm info to look up the device path for you: +

- -

Using multiple SYMLINK style rules

-Another recent feature is the ability to write rules that do not specify a NAME, but instead they simply specify SYMLINK keys. This allows you to avoid the issue where your own rules effectively mask the udev defaults.

+
# udevadm info -a -p $(udevadm info -q path -n /dev/sda)
-Take the rule:
-
KERNEL=="hdc", SYMLINK="dvd"
+ +

Alternative methods

-When udev finds this rule, it will take a mental note of it. Upon finding another rule matching the same device which also includes a NAME parameter, udev will create the node as specified by the NAME parameter, plus symbolic links as specified by the SYMLINK parameters of both rules.
-To put it into practical terms, when udev is naming nodes for my hdc device, it will use the default rules for block devices as usual, with the addition of my personal symlink "dvd".

+

+Although udevadm info is almost certainly the most straightforward way of listing the exact attributes you can build rules from, some users are happier with other tools. Utilities such as usbview display a similar set of information, most of which can be used in rules. +

-Similarly to normal rules, rules of this type will only take effect if udev is able to find them before it finds a rule specifying a NAME parameter.

+

Advanced topics

- -

Controlling ownership and permissions

+ +

Controlling permissions and ownership

-As well as controlling the naming of the device nodes which are created, udev rules also allow you to control ownership and permission attributes on that device node.

+

+udev allows you to use additional assignments in rules to control ownership and permission attributes on each device. +

-The GROUP key allows you to define which unix group should own the device node. Here's an example from the udev defaults, which defines that the video group will own framebuffer (fb) devices: +

+The GROUP assignment allows you to define which Unix group should own the device node. Here is an example rule which defines that the video group will own the framebuffer devices: +

-
KERNEL=="fb[0-9]*", NAME="fb/%n", SYMLINK="%k", GROUP="video"
+
KERNEL=="fb[0-9]*", NAME="fb/%n", SYMLINK+="%k", GROUP="video"
-The OWNER key, perhaps less useful, allows you to define which unix user should own the device node. Assuming the slightly odd situation where you would want "john" to own your floppy devices, you could use: +

+The OWNER key, perhaps less useful, allows you to define which Unix user should have ownership permissions on the device node. Assuming the slightly odd situation where you would want john to own your floppy devices, you could use: +

KERNEL=="fd[0-9]*", OWNER="john"
-You'll notice in the above rule that we didn't specify any NAME or SYMLINK keys. This is similar to the multiple symlink style where udev will take a mental note that we want john to own floppy nodes, and will apply that ownership once it finds a rule which defines a NAME for the floppy device nodes.

+

+udev defaults to creating nodes with Unix permissions of 0660 (read/write to owner and group). If you need to, you can override these defaults on certain devices using rules including the MODE assignment. As an example, the following rule defines that the inotify node shall be readable and writable to everyone: +

+ +
KERNEL=="inotify", NAME="misc/%k", SYMLINK+="%k", MODE="0666"
+ + +

Using external programs to name devices

+ +

+Under some circumstances, you may require more flexibility than standard udev rules can provide. In this case, you can ask udev to run a program and use the standard output from that program to provide device naming. +

+ +

+To use this functionality, you simply specify the absolute path of the program to run (and any parameters) in the PROGRAM assignment, and you then use some variant of the %c substitution in the NAME/SYMLINK assignments. +

+ +

+The following examples refer to a fictional program found at /bin/device_namer. device_namer takes one command line argument which is the kernel name for the device. Based upon this kernel name, device_namer does its magic and produces some output to the usual stdout pipe, split into several parts. Each part is just a single word, and parts are separated by a single space. +

+ +

+In our first example, we assume that device_namer outputs a number of parts, each one to form a symbolic link (alternative name) for the device in question. +

+ +
KERNEL=="hda", PROGRAM="/bin/device_namer %k", SYMLINK+="%c"
+ +

+The next example assumes that device_namer outputs two parts, the first being the device name, and the second being the name for an additional symbolic link. We now introduce the %c{N} substitution, which refers to part N of the output: +

-Building on the style mentioned above, you can do even more flashy things. The udev defaults use the following rule to define that all the sound device nodes shall be owned by the "audio" group: +
KERNEL=="hda", PROGRAM="/bin/device_namer %k", NAME="%c{1}", SYMLINK+="%c{2}"
-
SUBSYSTEM=="sound", GROUP="audio"
+

+The next example assumes that device_namer outputs one part for the device name, followed by any number of parts which will form additional symbolic links. We now introduce the %c{N+} substitution, which evaluates to part N, N+1, N+2, ... until the end of the output. +

-This prevents the need to excessively provide a GROUP=="audio" key on every following rule which names sound devices.

+
KERNEL=="hda", PROGRAM="/bin/device_namer %k", NAME="%c{1}", SYMLINK+="%c{2+}"
-udev defaults to creating nodes with unix permissions of 0660 (read/write to owner and group). There may be some situations where you do not want to use the default permissions on your device node. Fortunately, you can easily override the permissions in your rules using the MODE assignment key. As an example, the following rule defines that the inotify node shall be readable and writable to everyone: +

+Output parts can be used in any assignment key, not only NAME and SYMLINK. The example below uses a fictional program to determine the Unix group which should own the device: +

-
KERNEL=="inotify", NAME="misc/%k", SYMLINK="%k", MODE="0666"
+
KERNEL=="hda", PROGRAM="/bin/who_owns_device %k", GROUP="%c"
+ + +

Running external programs upon certain events

+ +

+Yet another reason for writing udev rules is to run a particular program when a device is connected or disconnected. For example, you might want to execute a script to automatically download all of your photos from your digital camera when it is connected. +

+ +

+Do not confuse this with the PROGRAM functionality described above. PROGRAM is used for running programs which produce device names (and they shouldn't do anything other than that). When those programs are being executed, the device node has not yet been created, so acting upon the device in any way is not possible. +

+ +

+The functionality introduced here allows you to run a program after the device node is put in place. This program can act on the device, however it must not run for any extended period of time, because udev is effectively paused while these programs are running. One workaround for this limitation is to make sure your program immediately detaches itself. +

+ +

+Here is an example rule which demonstrates the use of the RUN list assignment: +

+ +
KERNEL=="sdb", RUN+="/usr/bin/my_program"
+ +

+When /usr/bin/my_program is executed, various parts of the udev environment are available as environment variables, including key values such as SUBSYSTEM. You can also use the ACTION environment variable to detect whether the device is being connected or disconnected - ACTION will be either "add" or "remove" respectively. +

+ +

+udev does not run these programs on any active terminal, and it does not execute them under the context of a shell. Be sure to ensure your program is marked executable, if it is a shell script ensure it starts with an appropriate shebang (e.g. #!/bin/sh), and do not expect any standard output to appear on your terminal. +

+ + +

Environment interaction

+ +

+udev provides an ENV key for environment variables which can be used for both matching and assignment. +

+ +

+In the assignment case, you can set environment variables which you can then match against later. You can also set environment variables which can be used by any external programs invoked using the techniques mentioned above. A fictional example rule which sets an environment variable is shown below. +

+ +
KERNEL=="fd0", SYMLINK+="floppy", ENV{some_var}="value"
+ +

+In the matching case, you can ensure that rules only run depending on the value of an environment variable. Note that the environment that udev sees will not be the same user environment as you get on the console. A fictional rule involving an environment match is shown below. +

+ +
KERNEL=="fd0", ENV{an_env_var}=="yes", SYMLINK+="floppy"
+ +

+The above rule only creates the /dev/floppy link if $an_env_var is set to "yes" in udev's environment. +

+ + +

Additional options

+ +

+Another assignment which can prove useful is the OPTIONS list. A few options are available: +

+ + + +

+For example, the rule below sets the group ownership on my hard disk node, and ensures that no later rule can have any effect: +

+ +
KERNEL=="sda", GROUP="disk", OPTIONS+="last_rule"
+ + +

Examples

-

Example: Writing a rule for my USB printer

+

USB Printer

-After plugging in my printer, I started looking around some /sys directories for a relevant place to start. I didn't get anywhere, but I noticed that my printer had been given device node /dev/lp0. udevinfo was able to provide me with a useful path: -
-# udevinfo -q path -n /dev/lp0
-/class/usb/lp0
-
+

+I power on my printer, and it is assigned device node /dev/lp0. Not satisfied with such a bland name, I decide to use udevadm info to aid me in writing a rule which will provide an alternative name: +

-Running "udevinfo -a -p /sys/class/usb/lp0" provided me with a heap of info, as usual. I picked out the relevant bits for unique device identification:
-looking at the device chain at '/sys/devices/pci0000:00/0000:00:02.1/usb3/3-3':
-BUS=="usb"
-SYSFS{manufacturer}=="EPSON"
-SYSFS{product}=="USB Printer"
-SYSFS{serial}=="L72010011070626380"
+# udevadm info -a -p $(udevadm info -q path -n /dev/lp0)
+  looking at device '/class/usb/lp0':
+    KERNEL=="lp0"
+    SUBSYSTEM=="usb"
+    DRIVER==""
+    ATTR{dev}=="180:0"
+
+  looking at parent device '/devices/pci0000:00/0000:00:1d.0/usb1/1-1':
+    SUBSYSTEMS=="usb"
+    ATTRS{manufacturer}=="EPSON"
+    ATTRS{product}=="USB Printer"
+    ATTRS{serial}=="L72010011070626380"
 
-My udev rule becomes: -
BUS=="usb", SYSFS{serial}=="L72010011070626380", NAME="%k", SYMLINK="epson_680"
+

+My rule becomes: +

-And my printer nodes exist at /dev/lp0 (or /dev/lp1 if another printer was plugged in beforehand) and /dev/epson_680 always points at the device node for that particular printer.

+
SUBSYSTEM=="usb", ATTRS{serial}=="L72010011070626380", SYMLINK+="epson_680"
-

Example: Writing a rule for my USB-Storage digital camera

- -Quick Intro: My camera identifies itself as an external SCSI hard disk (it uses the usb-storage driver which is also used by devices such as USB hard disks and flash-card readers). I can then mount the partition on that disk and copy images over. Not all cameras work like this - many require external software (e.g. gphoto2) to be able to access photos.

- -This one is a bit tricky. Several nodes are created by default when my camera is connected : /dev/sda and /dev/sda1, and possibly even /dev/sg1. This is an example where specifity is important - if your rule is not specific enough, it could match any of the above 3 nodes.

+

USB Camera

-sda1 is the node that I would like as my /dev/camera, as that is what gets mounted. udevinfo did not point out any useful differences between sda, sda1, and sg1. I decided that a reliable way to differentiate between these 3 nodes would be to look at the KERNEL name.

+

+Like most, my camera identifies itself as an external hard disk connected over the USB bus, using the SCSI transport. To access my photos, I mount the drive and copy the image files onto my hard disk. +

-A key such as KERNEL=="sd?1" would match KERNEL names such as "sda1", "sdb1", "sdc1", and equally importantly, it will not match KERNEL names such as sda, sdb, or sg1. The purpose of this key is to ignore the /dev/sda and /dev/sg1 nodes. The device is a digital camera - I would not dream of fdisking it or anything like that, so these 2 nodes are pretty useless to me. The key attempts to capture the /dev/sda1 node, which is mountable and therefore useful!

+

+Not all cameras work in this way: some of them use a non-storage protocol such as cameras supported by gphoto2. In the gphoto case, you do not want to be writing rules for your device, as is it controlled purely through userspace (rather than a specific kernel driver). +

-As this node (sda1) is treated as a block device, looking in /sys/block would be a good place to start.

+

+A common complication with USB camera devices is that they usually identify themselves as a disk with a single partition, in this case /dev/sdb with /dev/sdb1. The sdb node is useless to me, but sdb1 is interesting - this is the one I want to mount. There is a problem here that because sysfs is chained, the useful attributes which udevadm info produces for /dev/sdb1 are identical to the ones for /dev/sdb. This results in your rule potentially matching both the raw disk and the partition, which is not what you want, your rule should be specific. +

-In my /sys/block, I have a directory named sda. In my /sys/block/sda, I have a directory named sda1. Both of these directories have dev files in, so they are OK to run udevinfo on. Running the following dumps a lot of information about my camera and the USB port it is connected through. +

+To get around this, you simply need to think about what differs between sdb and sdb1. It is surprisingly simple: the name itself differs, so we can use a simple pattern match on the NAME field. +

-
# udevinfo -a -p /sys/block/sda/sda1
+
+# udevadm info -a -p $(udevadm info -q path -n /dev/sdb1)
+  looking at device '/block/sdb/sdb1':
+    KERNEL=="sdb1"
+    SUBSYSTEM=="block"
+
+  looking at parent device '/devices/pci0000:00/0000:00:02.1/usb1/1-1/1-1:1.0/host6/target6:0:0/6:0:0:0':
+    KERNELS=="6:0:0:0"
+    SUBSYSTEMS=="scsi"
+    DRIVERS=="sd"
+    ATTRS{rev}=="1.00"
+    ATTRS{model}=="X250,D560Z,C350Z"
+    ATTRS{vendor}=="OLYMPUS "
+    ATTRS{scsi_level}=="3"
+    ATTRS{type}=="0"
+
-In the udevinfo output, I also noticed this bit of useful and understandable information: -
SYSFS{product}=="USB 2.0M DSC"
+

+My rule: +

-So that gives me my rule. For completeness, I also include a BUS key (this was also found in the udevinfo output). -
BUS=="usb", SYSFS{product}=="USB 2.0M DSC", KERNEL=="sd?1", NAME="%k", SYMLINK="camera"
+
KERNEL=="sd?1", SUBSYSTEMS=="scsi", ATTRS{model}=="X250,D560Z,C350Z", SYMLINK+="camera"
-Now, when my camera is plugged in, it will be named /dev/sda1 (or, if sda1 isnt available, it might be called /dev/sdb1) and will always be correctly linked to from /dev/camera. The /dev/sda (or sdb) node still appears as normal, but the important thing is that my custom persistent "camera" symlink points to the mountable partition.

+ +

USB Hard Disk

- -

Additional notes on writing rules for USB storage

+

+A USB hard disk is comparable to the USB camera I described above, however typical usage patterns are different. In the camera example, I explained that I am not interested in the sdb node - it's only real use is for partitioning (e.g. with fdisk), but why would I want to partition my camera!? +

-Carl Streeter, the owner of a large USB hard disk, wrote to me and explained that unlike in my digital camera example, the /dev/sda node is useful to him. He pointed out that he does occasionally need to use tools such as fdisk and hdparm on that node.

+

+Of course, if you have a 100GB USB hard disk, it is perfectly understandable that you might want to partition it, in which case we can take advantage of udev's string substitutions: +

-Carl's rule is: -
BUS=="usb", KERNEL=="sd*", SYSFS{product}=="USB 2.0 Storage Device", NAME="%k", SYMLINK="usbhd%n"
+
KERNEL=="sd*", SUBSYSTEMS=="scsi", ATTRS{model}=="USB 2.0 Storage Device", SYMLINK+="usbhd%n"
+

This rule creates symlinks such as: -