Documentation/driver-api/usb/hotplug.rst GitHub 원문 ↗

Linux 6.18.37 · Driver API

USB Hotplugging

Linux USB hotplug helper와 policy agent, 환경 변수, module-init-tools 및 MODULE_DEVICE_TABLE 기반 driver matching을 설명하는 한국어 전문 번역입니다.

Source pathDocumentation/driver-api/usb/hotplug.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.

1. 요약·해설

원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.

요약·해설

hotplug.rst:1-154

USB hotplug은 kernel의 device 감지와 probe, user-space policy agent의 module·서비스 설정을 연결합니다. ID table의 match_flags와 descriptor 비교 결과가 probe 대상과 전달되는 usb_device_id를 결정합니다.

문서 구성
원문 줄핵심 내용
1-37Linux hotplug orchestration
38-58kernel hotplug helper
59-86USB policy agent와 환경 변수
87-154modutils와 device ID matching

2. 영어 원문 전체

번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.

원문 전체 펼치기
1 USB hotplugging
2 ~~~~~~~~~~~~~~~
3
4 Linux Hotplugging
5 =================
6
7
8 In hotpluggable buses like USB (and Cardbus PCI), end-users plug devices
9 into the bus with power on. In most cases, users expect the devices to become
10 immediately usable. That means the system must do many things, including:
11
12 - Find a driver that can handle the device. That may involve
13 loading a kernel module; newer drivers can use module-init-tools
14 to publish their device (and class) support to user utilities.
15
16 - Bind a driver to that device. Bus frameworks do that using a
17 device driver's probe() routine.
18
19 - Tell other subsystems to configure the new device. Print
20 queues may need to be enabled, networks brought up, disk
21 partitions mounted, and so on. In some cases these will
22 be driver-specific actions.
23
24 This involves a mix of kernel mode and user mode actions. Making devices
25 be immediately usable means that any user mode actions can't wait for an
26 administrator to do them: the kernel must trigger them, either passively
27 (triggering some monitoring daemon to invoke a helper program) or
28 actively (calling such a user mode helper program directly).
29
30 Those triggered actions must support a system's administrative policies;
31 such programs are called "policy agents" here. Typically they involve
32 shell scripts that dispatch to more familiar administration tools.
33
34 Because some of those actions rely on information about drivers (metadata)
35 that is currently available only when the drivers are dynamically linked,
36 you get the best hotplugging when you configure a highly modular system.
37
38 Kernel Hotplug Helper (``/sbin/hotplug``)
39 =========================================
40
41 There is a kernel parameter: ``/proc/sys/kernel/hotplug``, which normally
42 holds the pathname ``/sbin/hotplug``. That parameter names a program
43 which the kernel may invoke at various times.
44
45 The /sbin/hotplug program can be invoked by any subsystem as part of its
46 reaction to a configuration change, from a thread in that subsystem.
47 Only one parameter is required: the name of a subsystem being notified of
48 some kernel event. That name is used as the first key for further event
49 dispatch; any other argument and environment parameters are specified by
50 the subsystem making that invocation.
51
52 Hotplug software and other resources is available at:
53
54 http://linux-hotplug.sourceforge.net
55
56 Mailing list information is also available at that site.
57
58
59 USB Policy Agent
60 ================
61
62 The USB subsystem currently invokes ``/sbin/hotplug`` when USB devices
63 are added or removed from system. The invocation is done by the kernel
64 hub workqueue [hub_wq], or else as part of root hub initialization
65 (done by init, modprobe, kapmd, etc). Its single command line parameter
66 is the string "usb", and it passes these environment variables:
67
68 ========== ============================================
69 ACTION ``add``, ``remove``
70 PRODUCT USB vendor, product, and version codes (hex)
71 TYPE device class codes (decimal)
72 INTERFACE interface 0 class codes (decimal)
73 ========== ============================================
74
75 If "usbdevfs" is configured, DEVICE and DEVFS are also passed. DEVICE is
76 the pathname of the device, and is useful for devices with multiple and/or
77 alternate interfaces that complicate driver selection. By design, USB
78 hotplugging is independent of ``usbdevfs``: you can do most essential parts
79 of USB device setup without using that filesystem, and without running a
80 user mode daemon to detect changes in system configuration.
81
82 Currently available policy agent implementations can load drivers for
83 modules, and can invoke driver-specific setup scripts. The newest ones
84 leverage USB module-init-tools support. Later agents might unload drivers.
85
86
87 USB Modutils Support
88 ====================
89
90 Current versions of module-init-tools will create a ``modules.usbmap`` file
91 which contains the entries from each driver's ``MODULE_DEVICE_TABLE``. Such
92 files can be used by various user mode policy agents to make sure all the
93 right driver modules get loaded, either at boot time or later.
94
95 See ``linux/usb.h`` for full information about such table entries; or look
96 at existing drivers. Each table entry describes one or more criteria to
97 be used when matching a driver to a device or class of devices. The
98 specific criteria are identified by bits set in "match_flags", paired
99 with field values. You can construct the criteria directly, or with
100 macros such as these, and use driver_info to store more information::
101
102 USB_DEVICE (vendorId, productId)
103 ... matching devices with specified vendor and product ids
104 USB_DEVICE_VER (vendorId, productId, lo, hi)
105 ... like USB_DEVICE with lo <= productversion <= hi
106 USB_INTERFACE_INFO (class, subclass, protocol)
107 ... matching specified interface class info
108 USB_DEVICE_INFO (class, subclass, protocol)
109 ... matching specified device class info
110
111 A short example, for a driver that supports several specific USB devices
112 and their quirks, might have a MODULE_DEVICE_TABLE like this::
113
114 static const struct usb_device_id mydriver_id_table[] = {
115 { USB_DEVICE (0x9999, 0xaaaa), driver_info: QUIRK_X },
116 { USB_DEVICE (0xbbbb, 0x8888), driver_info: QUIRK_Y|QUIRK_Z },
117 ...
118 { } /* end with an all-zeroes entry */
119 };
120 MODULE_DEVICE_TABLE(usb, mydriver_id_table);
121
122 Most USB device drivers should pass these tables to the USB subsystem as
123 well as to the module management subsystem. Not all, though: some driver
124 frameworks connect using interfaces layered over USB, and so they won't
125 need such a struct usb_driver.
126
127 Drivers that connect directly to the USB subsystem should be declared
128 something like this::
129
130 static struct usb_driver mydriver = {
131 .name = "mydriver",
132 .id_table = mydriver_id_table,
133 .probe = my_probe,
134 .disconnect = my_disconnect,
135
136 /*
137 if using the usb chardev framework:
138 .minor = MY_USB_MINOR_START,
139 .fops = my_file_ops,
140 if exposing any operations through usbdevfs:
141 .ioctl = my_ioctl,
142 */
143 };
144
145 When the USB subsystem knows about a driver's device ID table, it's used when
146 choosing drivers to probe(). The thread doing new device processing checks
147 drivers' device ID entries from the ``MODULE_DEVICE_TABLE`` against interface
148 and device descriptors for the device. It will only call ``probe()`` if there
149 is a match, and the third argument to ``probe()`` will be the entry that
150 matched.
151
152 If you don't provide an ``id_table`` for your driver, then your driver may get
153 probed for each new device; the third parameter to ``probe()`` will be
154 ``NULL``.
155

3. 한국어 전문 번역

영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.

Linux hotplug 처리 흐름

1-37

USB와 CardBus PCI 같은 hotpluggable bus에서는 전원이 켜진 상태로 사용자가 device를 연결하며, 보통 즉시 사용할 수 있기를 기대합니다.

System은 device를 처리할 driver를 찾아야 합니다. 이 과정에서 kernel module을 load할 수 있고, 새 driver는 `module-init-tools`를 통해 지원 device와 class 정보를 user utility에 공개할 수 있습니다.

그다음 bus framework가 device driver의 `probe()` routine으로 driver를 device에 bind합니다. 이어 print queue 활성화, network 시작, disk partition mount 같은 작업을 다른 subsystem에 요청하며 일부는 driver-specific action일 수 있습니다.

이 흐름에는 kernel mode와 user mode 작업이 섞입니다. Device를 즉시 사용하려면 administrator의 수동 작업을 기다릴 수 없으므로 kernel은 monitoring daemon이 helper program을 실행하게 하는 passive 방식이나 user-mode helper를 직접 호출하는 active 방식으로 이를 trigger해야 합니다.

Trigger된 action은 system의 administrative policy를 따라야 하며, 여기서는 이를 수행하는 program을 `policy agent`라고 부릅니다. 보통 shell script가 익숙한 administration tool로 작업을 dispatch합니다.

일부 action은 driver가 dynamic link될 때만 현재 이용할 수 있는 metadata에 의존하므로 highly modular system으로 구성할 때 hotplugging이 가장 잘 동작합니다.

Linux hotplug orchestration
Device 연결전원이 켜진 hotpluggable bus에서 감지
Driver 검색module metadata와 `module-init-tools` 사용
Driver bindbus framework가 `probe()` 호출
Policy agentkernel event를 받아 user-mode helper·script 실행
Subsystem 설정network·print queue·mount 등 device별 서비스 활성화

Device 연결부터 실제 서비스 활성화까지 kernel과 user space가 협력하는 흐름입니다.

USB hotplugging
~~~~~~~~~~~~~~~

Linux Hotplugging
=================


In hotpluggable buses like USB (and Cardbus PCI), end-users plug devices
into the bus with power on.  In most cases, users expect the devices to become
immediately usable.  That means the system must do many things, including:

    - Find a driver that can handle the device.  That may involve
      loading a kernel module; newer drivers can use module-init-tools
      to publish their device (and class) support to user utilities.

    - Bind a driver to that device.  Bus frameworks do that using a
      device driver's probe() routine.

    - Tell other subsystems to configure the new device.  Print
      queues may need to be enabled, networks brought up, disk
      partitions mounted, and so on.  In some cases these will
      be driver-specific actions.

This involves a mix of kernel mode and user mode actions.  Making devices
be immediately usable means that any user mode actions can't wait for an
administrator to do them:  the kernel must trigger them, either passively
(triggering some monitoring daemon to invoke a helper program) or
actively (calling such a user mode helper program directly).

Those triggered actions must support a system's administrative policies;
such programs are called "policy agents" here.  Typically they involve
shell scripts that dispatch to more familiar administration tools.

Because some of those actions rely on information about drivers (metadata)
that is currently available only when the drivers are dynamically linked,
you get the best hotplugging when you configure a highly modular system.

Kernel Hotplug Helper

38-58

Kernel parameter `/proc/sys/kernel/hotplug`은 보통 `/sbin/hotplug` 경로를 담고 있으며, kernel이 여러 시점에 호출할 program을 지정합니다.

어떤 subsystem도 configuration change에 반응하는 자기 thread에서 `/sbin/hotplug`를 호출할 수 있습니다. 필수 parameter는 kernel event를 통지받는 subsystem 이름 하나이며, 이후 event dispatch의 첫 key로 사용됩니다.

나머지 argument와 environment parameter는 호출하는 subsystem이 정의합니다.

Hotplug software, resource와 mailing list 정보는 `http://linux-hotplug.sourceforge.net`에서 제공됩니다.

`/sbin/hotplug` 호출 계약
항목내용
설정 경로`/proc/sys/kernel/hotplug`
기본 helper`/sbin/hotplug`
호출 주체configuration change를 처리하는 subsystem thread
필수 argumentsubsystem 이름
추가 정보subsystem이 argument와 environment variable 정의

Kernel Hotplug Helper (``/sbin/hotplug``)
=========================================

There is a kernel parameter: ``/proc/sys/kernel/hotplug``, which normally
holds the pathname ``/sbin/hotplug``.  That parameter names a program
which the kernel may invoke at various times.

The /sbin/hotplug program can be invoked by any subsystem as part of its
reaction to a configuration change, from a thread in that subsystem.
Only one parameter is required: the name of a subsystem being notified of
some kernel event.  That name is used as the first key for further event
dispatch; any other argument and environment parameters are specified by
the subsystem making that invocation.

Hotplug software and other resources is available at:

        http://linux-hotplug.sourceforge.net

Mailing list information is also available at that site.

USB Policy Agent와 환경 변수

59-86

USB subsystem은 USB device가 system에 추가되거나 제거될 때 `/sbin/hotplug`를 호출합니다. 호출은 kernel hub workqueue `hub_wq` 또는 init·modprobe·kapmd 등이 수행하는 root hub 초기화 과정에서 일어납니다.

Command-line parameter는 문자열 `usb` 하나이며 `ACTION`, `PRODUCT`, `TYPE`, `INTERFACE` environment variable을 전달합니다.

`usbdevfs`가 설정되어 있으면 `DEVICE`와 `DEVFS`도 전달됩니다. `DEVICE`는 device pathname이며 여러 interface 또는 alternate interface 때문에 driver 선택이 복잡한 device에 유용합니다.

USB hotplugging은 설계상 `usbdevfs`와 독립적입니다. 이 filesystem이나 system configuration 변경을 감지하는 user-mode daemon 없이도 USB device setup의 핵심 부분을 수행할 수 있습니다.

현재 policy agent 구현은 module driver를 load하고 driver-specific setup script를 호출할 수 있으며 최신 구현은 USB `module-init-tools` 지원을 활용합니다. 이후 agent는 driver unload도 수행할 수 있습니다.

USB hotplug 환경 변수
변수값과 의미
`ACTION``add` 또는 `remove`
`PRODUCT`USB vendor·product·version code, 16진수
`TYPE`device class code, 10진수
`INTERFACE`interface 0 class code, 10진수
`DEVICE``usbdevfs` 사용 시 device pathname
`DEVFS``usbdevfs` 사용 시 추가 전달

USB Policy Agent
================

The USB subsystem currently invokes ``/sbin/hotplug`` when USB devices
are added or removed from system.  The invocation is done by the kernel
hub workqueue [hub_wq], or else as part of root hub initialization
(done by init, modprobe, kapmd, etc).  Its single command line parameter
is the string "usb", and it passes these environment variables:

========== ============================================
ACTION     ``add``, ``remove``
PRODUCT    USB vendor, product, and version codes (hex)
TYPE       device class codes (decimal)
INTERFACE  interface 0 class codes (decimal)
========== ============================================

If "usbdevfs" is configured, DEVICE and DEVFS are also passed.  DEVICE is
the pathname of the device, and is useful for devices with multiple and/or
alternate interfaces that complicate driver selection.  By design, USB
hotplugging is independent of ``usbdevfs``:  you can do most essential parts
of USB device setup without using that filesystem, and without running a
user mode daemon to detect changes in system configuration.

Currently available policy agent implementations can load drivers for
modules, and can invoke driver-specific setup scripts.  The newest ones
leverage USB module-init-tools support.  Later agents might unload drivers.

USB Modutils와 device ID matching

87-154

현재 `module-init-tools`는 각 driver의 `MODULE_DEVICE_TABLE` entry를 모아 `modules.usbmap`을 만듭니다. User-mode policy agent는 이 file로 boot 시점이나 이후에 필요한 driver module이 모두 load되도록 할 수 있습니다.

Table entry의 전체 형식은 `linux/usb.h` 또는 기존 driver를 참고합니다. 각 entry는 driver를 특정 device 또는 device class와 match할 하나 이상의 기준을 설명합니다. `match_flags`에 설정된 bit가 어떤 field value를 비교할지 지정하고 `driver_info`에는 추가 정보를 저장할 수 있습니다.

`USB_DEVICE(vendorId, productId)`는 vendor·product ID가 같은 device를, `USB_DEVICE_VER(vendorId, productId, lo, hi)`는 product version이 `lo` 이상 `hi` 이하인 device를 match합니다. `USB_INTERFACE_INFO(class, subclass, protocol)`은 interface class 정보를, `USB_DEVICE_INFO(class, subclass, protocol)`은 device class 정보를 비교합니다.

여러 device와 quirk를 지원하는 table은 `static const struct usb_device_id` 배열에 `USB_DEVICE` entry와 `driver_info`를 두고 all-zero entry로 끝낸 뒤 `MODULE_DEVICE_TABLE(usb, mydriver_id_table)`로 공개합니다.

대부분 USB device driver는 이 table을 module management subsystem뿐 아니라 USB subsystem에도 전달해야 합니다. 다만 USB 위에 계층화된 interface로 연결되는 framework는 `struct usb_driver`가 필요하지 않을 수 있습니다.

USB subsystem에 직접 연결하는 driver는 `struct usb_driver`에 `.name`, `.id_table`, `.probe`, `.disconnect`를 지정합니다. USB chardev framework를 쓰면 `.minor`와 `.fops`, usbdevfs로 operation을 노출하면 `.ioctl`도 둘 수 있습니다.

USB subsystem이 ID table을 알고 있으면 새 device 처리 thread가 `MODULE_DEVICE_TABLE` entry를 interface·device descriptor와 비교합니다. Match가 있을 때만 `probe()`를 호출하며 세 번째 argument로 match된 entry를 넘깁니다. `id_table`이 없으면 모든 새 device에 대해 probe될 수 있고 세 번째 parameter는 `NULL`입니다.

USB ID matching macro
Macro·fieldMatching 기준
`USB_DEVICE`vendor ID와 product ID
`USB_DEVICE_VER`vendor·product ID와 product version 범위
`USB_INTERFACE_INFO`interface class·subclass·protocol
`USB_DEVICE_INFO`device class·subclass·protocol
`match_flags`실제로 비교할 field 선택
`driver_info`device별 quirk 등 추가 정보

USB Modutils Support
====================

Current versions of module-init-tools will create a ``modules.usbmap`` file
which contains the entries from each driver's ``MODULE_DEVICE_TABLE``.  Such
files can be used by various user mode policy agents to make sure all the
right driver modules get loaded, either at boot time or later.

See ``linux/usb.h`` for full information about such table entries; or look
at existing drivers.  Each table entry describes one or more criteria to
be used when matching a driver to a device or class of devices.  The
specific criteria are identified by bits set in "match_flags", paired
with field values.  You can construct the criteria directly, or with
macros such as these, and use driver_info to store more information::

    USB_DEVICE (vendorId, productId)
        ... matching devices with specified vendor and product ids
    USB_DEVICE_VER (vendorId, productId, lo, hi)
        ... like USB_DEVICE with lo <= productversion <= hi
    USB_INTERFACE_INFO (class, subclass, protocol)
        ... matching specified interface class info
    USB_DEVICE_INFO (class, subclass, protocol)
        ... matching specified device class info

A short example, for a driver that supports several specific USB devices
and their quirks, might have a MODULE_DEVICE_TABLE like this::

    static const struct usb_device_id mydriver_id_table[] = {
        { USB_DEVICE (0x9999, 0xaaaa), driver_info: QUIRK_X },
        { USB_DEVICE (0xbbbb, 0x8888), driver_info: QUIRK_Y|QUIRK_Z },
        ...
        { } /* end with an all-zeroes entry */
    };
    MODULE_DEVICE_TABLE(usb, mydriver_id_table);

Most USB device drivers should pass these tables to the USB subsystem as
well as to the module management subsystem.  Not all, though: some driver
frameworks connect using interfaces layered over USB, and so they won't
need such a struct usb_driver.

Drivers that connect directly to the USB subsystem should be declared
something like this::

    static struct usb_driver mydriver = {
        .name                = "mydriver",
        .id_table        = mydriver_id_table,
        .probe                = my_probe,
        .disconnect        = my_disconnect,

        /*
        if using the usb chardev framework:
            .minor                = MY_USB_MINOR_START,
            .fops                = my_file_ops,
        if exposing any operations through usbdevfs:
            .ioctl                = my_ioctl,
        */
    };

When the USB subsystem knows about a driver's device ID table, it's used when
choosing drivers to probe().  The thread doing new device processing checks
drivers' device ID entries from the ``MODULE_DEVICE_TABLE`` against interface
and device descriptors for the device.  It will only call ``probe()`` if there
is a match, and the third argument to ``probe()`` will be the entry that
matched.

If you don't provide an ``id_table`` for your driver, then your driver may get
probed for each new device; the third parameter to ``probe()`` will be
``NULL``.