1 <!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook V3.1//EN"[]>
3 <book id="USBDeviceDriver">
5 <title>Writing USB Device Drivers</title>
9 <firstname>Greg</firstname>
10 <surname>Kroah-Hartman</surname>
13 <email>greg@kroah.com</email>
20 <year>2001-2002</year>
21 <holder>Greg Kroah-Hartman</holder>
26 This documentation is free software; you can redistribute
27 it and/or modify it under the terms of the GNU General Public
28 License as published by the Free Software Foundation; either
29 version 2 of the License, or (at your option) any later
34 This program is distributed in the hope that it will be
35 useful, but WITHOUT ANY WARRANTY; without even the implied
36 warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
37 See the GNU General Public License for more details.
41 You should have received a copy of the GNU General Public
42 License along with this program; if not, write to the Free
43 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
48 For more details see the file COPYING in the source
49 distribution of Linux.
53 This documentation is based on an article published in
54 Linux Journal Magazine, October 2001, Issue 90.
62 <title>Introduction</title>
64 The Linux USB subsystem has grown from supporting only two different
65 types of devices in the 2.2.7 kernel (mice and keyboards), to over 20
66 different types of devices in the 2.4 kernel. Linux currently supports
67 almost all USB class devices (standard types of devices like keyboards,
68 mice, modems, printers and speakers) and an ever-growing number of
69 vendor-specific devices (such as USB to serial converters, digital
70 cameras, Ethernet devices and MP3 players). For a full list of the
71 different USB devices currently supported, see Resources.
74 The remaining kinds of USB devices that do not have support on Linux are
75 almost all vendor-specific devices. Each vendor decides to implement a
76 custom protocol to talk to their device, so a custom driver usually needs
77 to be created. Some vendors are open with their USB protocols and help
78 with the creation of Linux drivers, while others do not publish them, and
79 developers are forced to reverse-engineer. See Resources for some links
80 to handy reverse-engineering tools.
83 Because each different protocol causes a new driver to be created, I have
84 written a generic USB driver skeleton, modeled after the pci-skeleton.c
85 file in the kernel source tree upon which many PCI network drivers have
86 been based. This USB skeleton can be found at drivers/usb/usb-skeleton.c
87 in the kernel source tree. In this article I will walk through the basics
88 of the skeleton driver, explaining the different pieces and what needs to
89 be done to customize it to your specific device.
94 <title>Linux USB Basics</title>
96 If you are going to write a Linux USB driver, please become familiar with
97 the USB protocol specification. It can be found, along with many other
98 useful documents, at the USB home page (see Resources). An excellent
99 introduction to the Linux USB subsystem can be found at the USB Working
100 Devices List (see Resources). It explains how the Linux USB subsystem is
101 structured and introduces the reader to the concept of USB urbs, which
102 are essential to USB drivers.
105 The first thing a Linux USB driver needs to do is register itself with
106 the Linux USB subsystem, giving it some information about which devices
107 the driver supports and which functions to call when a device supported
108 by the driver is inserted or removed from the system. All of this
109 information is passed to the USB subsystem in the usb_driver structure.
110 The skeleton driver declares a usb_driver as:
113 static struct usb_driver skel_driver = {
116 .disconnect = skel_disconnect,
117 .fops = &skel_fops,
118 .minor = USB_SKEL_MINOR_BASE,
119 .id_table = skel_table,
123 The variable name is a string that describes the driver. It is used in
124 informational messages printed to the system log. The probe and
125 disconnect function pointers are called when a device that matches the
126 information provided in the id_table variable is either seen or removed.
129 The fops and minor variables are optional. Most USB drivers hook into
130 another kernel subsystem, such as the SCSI, network or TTY subsystem.
131 These types of drivers register themselves with the other kernel
132 subsystem, and any user-space interactions are provided through that
133 interface. But for drivers that do not have a matching kernel subsystem,
134 such as MP3 players or scanners, a method of interacting with user space
135 is needed. The USB subsystem provides a way to register a minor device
136 number and a set of file_operations function pointers that enable this
137 user-space interaction. The skeleton driver needs this kind of interface,
138 so it provides a minor starting number and a pointer to its
139 file_operations functions.
142 The USB driver is then registered with a call to usb_register, usually in
143 the driver's init function, as shown here:
146 static int __init usb_skel_init(void)
150 /* register this driver with the USB subsystem */
151 result = usb_register(&skel_driver);
153 err("usb_register failed for the "__FILE__ "driver."
154 "Error number %d", result);
160 module_init(usb_skel_init);
163 When the driver is unloaded from the system, it needs to unregister
164 itself with the USB subsystem. This is done with the usb_unregister
168 static void __exit usb_skel_exit(void)
170 /* deregister this driver with the USB subsystem */
171 usb_deregister(&skel_driver);
173 module_exit(usb_skel_exit);
176 To enable the linux-hotplug system to load the driver automatically when
177 the device is plugged in, you need to create a MODULE_DEVICE_TABLE. The
178 following code tells the hotplug scripts that this module supports a
179 single device with a specific vendor and product ID:
182 /* table of devices that work with this driver */
183 static struct usb_device_id skel_table [] = {
184 { USB_DEVICE(USB_SKEL_VENDOR_ID, USB_SKEL_PRODUCT_ID) },
185 { } /* Terminating entry */
187 MODULE_DEVICE_TABLE (usb, skel_table);
190 There are other macros that can be used in describing a usb_device_id for
191 drivers that support a whole class of USB drivers. See usb.h for more
196 <chapter id="device">
197 <title>Device operation</title>
199 When a device is plugged into the USB bus that matches the device ID
200 pattern that your driver registered with the USB core, the probe function
201 is called. The usb_device structure, interface number and the interface ID
202 are passed to the function:
205 static int skel_probe(struct usb_interface *interface,
206 const struct usb_device_id *id)
209 The driver now needs to verify that this device is actually one that it
210 can accept. If so, it returns 0.
211 If not, or if any error occurs during initialization, an errorcode
212 (such as <literal>-ENOMEM</literal> or <literal>-ENODEV</literal>)
213 is returned from the probe function.
216 In the skeleton driver, we determine what end points are marked as bulk-in
217 and bulk-out. We create buffers to hold the data that will be sent and
218 received from the device, and a USB urb to write data to the device is
222 Conversely, when the device is removed from the USB bus, the disconnect
223 function is called with the device pointer. The driver needs to clean any
224 private data that has been allocated at this time and to shut down any
225 pending urbs that are in the USB system. The driver also unregisters
226 itself from the devfs subsystem with the call:
229 /* remove our devfs node */
230 devfs_unregister(skel->devfs);
233 Now that the device is plugged into the system and the driver is bound to
234 the device, any of the functions in the file_operations structure that
235 were passed to the USB subsystem will be called from a user program trying
236 to talk to the device. The first function called will be open, as the
237 program tries to open the device for I/O. We increment our private usage
238 count and save off a pointer to our internal structure in the file
239 structure. This is done so that future calls to file operations will
240 enable the driver to determine which device the user is addressing. All
241 of this is done with the following code:
244 /* increment our usage count for the module */
247 /* save our object in the file's private structure */
248 file->private_data = dev;
251 After the open function is called, the read and write functions are called
252 to receive and send data to the device. In the skel_write function, we
253 receive a pointer to some data that the user wants to send to the device
254 and the size of the data. The function determines how much data it can
255 send to the device based on the size of the write urb it has created (this
256 size depends on the size of the bulk out end point that the device has).
257 Then it copies the data from user space to kernel space, points the urb to
258 the data and submits the urb to the USB subsystem. This can be shown in
262 /* we can only write as much as 1 urb will hold */
263 bytes_written = (count > skel->bulk_out_size) ? skel->bulk_out_size : count;
265 /* copy the data from user space into our urb */
266 copy_from_user(skel->write_urb->transfer_buffer, buffer, bytes_written);
269 usb_fill_bulk_urb(skel->write_urb,
271 usb_sndbulkpipe(skel->dev, skel->bulk_out_endpointAddr),
272 skel->write_urb->transfer_buffer,
274 skel_write_bulk_callback,
277 /* send the data out the bulk port */
278 result = usb_submit_urb(skel->write_urb);
280 err("Failed submitting write urb, error %d", result);
284 When the write urb is filled up with the proper information using the
285 usb_fill_bulk_urb function, we point the urb's completion callback to call our
286 own skel_write_bulk_callback function. This function is called when the
287 urb is finished by the USB subsystem. The callback function is called in
288 interrupt context, so caution must be taken not to do very much processing
289 at that time. Our implementation of skel_write_bulk_callback merely
290 reports if the urb was completed successfully or not and then returns.
293 The read function works a bit differently from the write function in that
294 we do not use an urb to transfer data from the device to the driver.
295 Instead we call the usb_bulk_msg function, which can be used to send or
296 receive data from a device without having to create urbs and handle
297 urb completion callback functions. We call the usb_bulk_msg function,
298 giving it a buffer into which to place any data received from the device
299 and a timeout value. If the timeout period expires without receiving any
300 data from the device, the function will fail and return an error message.
301 This can be shown with the following code:
304 /* do an immediate bulk read to get data from the device */
305 retval = usb_bulk_msg (skel->dev,
306 usb_rcvbulkpipe (skel->dev,
307 skel->bulk_in_endpointAddr),
308 skel->bulk_in_buffer,
311 /* if the read was successful, copy the data to user space */
313 if (copy_to_user (buffer, skel->bulk_in_buffer, count))
320 The usb_bulk_msg function can be very useful for doing single reads or
321 writes to a device; however, if you need to read or write constantly to a
322 device, it is recommended to set up your own urbs and submit them to the
326 When the user program releases the file handle that it has been using to
327 talk to the device, the release function in the driver is called. In this
328 function we decrement our private usage count and wait for possible
332 /* decrement our usage count for the device */
336 One of the more difficult problems that USB drivers must be able to handle
337 smoothly is the fact that the USB device may be removed from the system at
338 any point in time, even if a program is currently talking to it. It needs
339 to be able to shut down any current reads and writes and notify the
340 user-space programs that the device is no longer there. The following
341 code (function <function>skel_delete</function>)
342 is an example of how to do this: </para>
344 static inline void skel_delete (struct usb_skel *dev)
346 if (dev->bulk_in_buffer != NULL)
347 kfree (dev->bulk_in_buffer);
348 if (dev->bulk_out_buffer != NULL)
349 usb_buffer_free (dev->udev, dev->bulk_out_size,
350 dev->bulk_out_buffer,
351 dev->write_urb->transfer_dma);
352 if (dev->write_urb != NULL)
353 usb_free_urb (dev->write_urb);
358 If a program currently has an open handle to the device, we reset the flag
359 <literal>device_present</literal>. For
360 every read, write, release and other functions that expect a device to be
361 present, the driver first checks this flag to see if the device is
362 still present. If not, it releases that the device has disappeared, and a
363 -ENODEV error is returned to the user-space program. When the release
364 function is eventually called, it determines if there is no device
365 and if not, it does the cleanup that the skel_disconnect
366 function normally does if there are no open files on the device (see
372 <title>Isochronous Data</title>
374 This usb-skeleton driver does not have any examples of interrupt or
375 isochronous data being sent to or from the device. Interrupt data is sent
376 almost exactly as bulk data is, with a few minor exceptions. Isochronous
377 data works differently with continuous streams of data being sent to or
378 from the device. The audio and video camera drivers are very good examples
379 of drivers that handle isochronous data and will be useful if you also
384 <chapter id="Conclusion">
385 <title>Conclusion</title>
387 Writing Linux USB device drivers is not a difficult task as the
388 usb-skeleton driver shows. This driver, combined with the other current
389 USB drivers, should provide enough examples to help a beginning author
390 create a working driver in a minimal amount of time. The linux-usb-devel
391 mailing list archives also contain a lot of helpful information.
395 <chapter id="resources">
396 <title>Resources</title>
398 The Linux USB Project: <ulink url="http://www.linux-usb.org">http://www.linux-usb.org/</ulink>
401 Linux Hotplug Project: <ulink url="http://linux-hotplug.sourceforge.net">http://linux-hotplug.sourceforge.net/</ulink>
404 Linux USB Working Devices List: <ulink url="http://www.qbik.ch/usb/devices">http://www.qbik.ch/usb/devices/</ulink>
407 linux-usb-devel Mailing List Archives: <ulink url="http://marc.theaimsgroup.com/?l=linux-usb-devel">http://marc.theaimsgroup.com/?l=linux-usb-devel</ulink>
410 Programming Guide for Linux USB Device Drivers: <ulink url="http://usb.cs.tum.edu/usbdoc">http://usb.cs.tum.edu/usbdoc</ulink>
413 USB Home Page: <ulink url="http://www.usb.org">http://www.usb.org</ulink>