r6040: implement phylib
[linux/fpc-iii.git] / Documentation / DocBook / writing_usb_driver.tmpl
blobbd97a13fa5aebcd24a4382b6dc84e872f24b9b86
1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN"
3 "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd" []>
5 <book id="USBDeviceDriver">
6 <bookinfo>
7 <title>Writing USB Device Drivers</title>
9 <authorgroup>
10 <author>
11 <firstname>Greg</firstname>
12 <surname>Kroah-Hartman</surname>
13 <affiliation>
14 <address>
15 <email>greg@kroah.com</email>
16 </address>
17 </affiliation>
18 </author>
19 </authorgroup>
21 <copyright>
22 <year>2001-2002</year>
23 <holder>Greg Kroah-Hartman</holder>
24 </copyright>
26 <legalnotice>
27 <para>
28 This documentation is free software; you can redistribute
29 it and/or modify it under the terms of the GNU General Public
30 License as published by the Free Software Foundation; either
31 version 2 of the License, or (at your option) any later
32 version.
33 </para>
35 <para>
36 This program is distributed in the hope that it will be
37 useful, but WITHOUT ANY WARRANTY; without even the implied
38 warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
39 See the GNU General Public License for more details.
40 </para>
42 <para>
43 You should have received a copy of the GNU General Public
44 License along with this program; if not, write to the Free
45 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
46 MA 02111-1307 USA
47 </para>
49 <para>
50 For more details see the file COPYING in the source
51 distribution of Linux.
52 </para>
54 <para>
55 This documentation is based on an article published in
56 Linux Journal Magazine, October 2001, Issue 90.
57 </para>
58 </legalnotice>
59 </bookinfo>
61 <toc></toc>
63 <chapter id="intro">
64 <title>Introduction</title>
65 <para>
66 The Linux USB subsystem has grown from supporting only two different
67 types of devices in the 2.2.7 kernel (mice and keyboards), to over 20
68 different types of devices in the 2.4 kernel. Linux currently supports
69 almost all USB class devices (standard types of devices like keyboards,
70 mice, modems, printers and speakers) and an ever-growing number of
71 vendor-specific devices (such as USB to serial converters, digital
72 cameras, Ethernet devices and MP3 players). For a full list of the
73 different USB devices currently supported, see Resources.
74 </para>
75 <para>
76 The remaining kinds of USB devices that do not have support on Linux are
77 almost all vendor-specific devices. Each vendor decides to implement a
78 custom protocol to talk to their device, so a custom driver usually needs
79 to be created. Some vendors are open with their USB protocols and help
80 with the creation of Linux drivers, while others do not publish them, and
81 developers are forced to reverse-engineer. See Resources for some links
82 to handy reverse-engineering tools.
83 </para>
84 <para>
85 Because each different protocol causes a new driver to be created, I have
86 written a generic USB driver skeleton, modeled after the pci-skeleton.c
87 file in the kernel source tree upon which many PCI network drivers have
88 been based. This USB skeleton can be found at drivers/usb/usb-skeleton.c
89 in the kernel source tree. In this article I will walk through the basics
90 of the skeleton driver, explaining the different pieces and what needs to
91 be done to customize it to your specific device.
92 </para>
93 </chapter>
95 <chapter id="basics">
96 <title>Linux USB Basics</title>
97 <para>
98 If you are going to write a Linux USB driver, please become familiar with
99 the USB protocol specification. It can be found, along with many other
100 useful documents, at the USB home page (see Resources). An excellent
101 introduction to the Linux USB subsystem can be found at the USB Working
102 Devices List (see Resources). It explains how the Linux USB subsystem is
103 structured and introduces the reader to the concept of USB urbs
104 (USB Request Blocks), which are essential to USB drivers.
105 </para>
106 <para>
107 The first thing a Linux USB driver needs to do is register itself with
108 the Linux USB subsystem, giving it some information about which devices
109 the driver supports and which functions to call when a device supported
110 by the driver is inserted or removed from the system. All of this
111 information is passed to the USB subsystem in the usb_driver structure.
112 The skeleton driver declares a usb_driver as:
113 </para>
114 <programlisting>
115 static struct usb_driver skel_driver = {
116 .name = "skeleton",
117 .probe = skel_probe,
118 .disconnect = skel_disconnect,
119 .fops = &amp;skel_fops,
120 .minor = USB_SKEL_MINOR_BASE,
121 .id_table = skel_table,
123 </programlisting>
124 <para>
125 The variable name is a string that describes the driver. It is used in
126 informational messages printed to the system log. The probe and
127 disconnect function pointers are called when a device that matches the
128 information provided in the id_table variable is either seen or removed.
129 </para>
130 <para>
131 The fops and minor variables are optional. Most USB drivers hook into
132 another kernel subsystem, such as the SCSI, network or TTY subsystem.
133 These types of drivers register themselves with the other kernel
134 subsystem, and any user-space interactions are provided through that
135 interface. But for drivers that do not have a matching kernel subsystem,
136 such as MP3 players or scanners, a method of interacting with user space
137 is needed. The USB subsystem provides a way to register a minor device
138 number and a set of file_operations function pointers that enable this
139 user-space interaction. The skeleton driver needs this kind of interface,
140 so it provides a minor starting number and a pointer to its
141 file_operations functions.
142 </para>
143 <para>
144 The USB driver is then registered with a call to usb_register, usually in
145 the driver's init function, as shown here:
146 </para>
147 <programlisting>
148 static int __init usb_skel_init(void)
150 int result;
152 /* register this driver with the USB subsystem */
153 result = usb_register(&amp;skel_driver);
154 if (result &lt; 0) {
155 err(&quot;usb_register failed for the &quot;__FILE__ &quot;driver.&quot;
156 &quot;Error number %d&quot;, result);
157 return -1;
160 return 0;
162 module_init(usb_skel_init);
163 </programlisting>
164 <para>
165 When the driver is unloaded from the system, it needs to deregister
166 itself with the USB subsystem. This is done with the usb_deregister
167 function:
168 </para>
169 <programlisting>
170 static void __exit usb_skel_exit(void)
172 /* deregister this driver with the USB subsystem */
173 usb_deregister(&amp;skel_driver);
175 module_exit(usb_skel_exit);
176 </programlisting>
177 <para>
178 To enable the linux-hotplug system to load the driver automatically when
179 the device is plugged in, you need to create a MODULE_DEVICE_TABLE. The
180 following code tells the hotplug scripts that this module supports a
181 single device with a specific vendor and product ID:
182 </para>
183 <programlisting>
184 /* table of devices that work with this driver */
185 static struct usb_device_id skel_table [] = {
186 { USB_DEVICE(USB_SKEL_VENDOR_ID, USB_SKEL_PRODUCT_ID) },
187 { } /* Terminating entry */
189 MODULE_DEVICE_TABLE (usb, skel_table);
190 </programlisting>
191 <para>
192 There are other macros that can be used in describing a usb_device_id for
193 drivers that support a whole class of USB drivers. See usb.h for more
194 information on this.
195 </para>
196 </chapter>
198 <chapter id="device">
199 <title>Device operation</title>
200 <para>
201 When a device is plugged into the USB bus that matches the device ID
202 pattern that your driver registered with the USB core, the probe function
203 is called. The usb_device structure, interface number and the interface ID
204 are passed to the function:
205 </para>
206 <programlisting>
207 static int skel_probe(struct usb_interface *interface,
208 const struct usb_device_id *id)
209 </programlisting>
210 <para>
211 The driver now needs to verify that this device is actually one that it
212 can accept. If so, it returns 0.
213 If not, or if any error occurs during initialization, an errorcode
214 (such as <literal>-ENOMEM</literal> or <literal>-ENODEV</literal>)
215 is returned from the probe function.
216 </para>
217 <para>
218 In the skeleton driver, we determine what end points are marked as bulk-in
219 and bulk-out. We create buffers to hold the data that will be sent and
220 received from the device, and a USB urb to write data to the device is
221 initialized.
222 </para>
223 <para>
224 Conversely, when the device is removed from the USB bus, the disconnect
225 function is called with the device pointer. The driver needs to clean any
226 private data that has been allocated at this time and to shut down any
227 pending urbs that are in the USB system.
228 </para>
229 <para>
230 Now that the device is plugged into the system and the driver is bound to
231 the device, any of the functions in the file_operations structure that
232 were passed to the USB subsystem will be called from a user program trying
233 to talk to the device. The first function called will be open, as the
234 program tries to open the device for I/O. We increment our private usage
235 count and save a pointer to our internal structure in the file
236 structure. This is done so that future calls to file operations will
237 enable the driver to determine which device the user is addressing. All
238 of this is done with the following code:
239 </para>
240 <programlisting>
241 /* increment our usage count for the module */
242 ++skel->open_count;
244 /* save our object in the file's private structure */
245 file->private_data = dev;
246 </programlisting>
247 <para>
248 After the open function is called, the read and write functions are called
249 to receive and send data to the device. In the skel_write function, we
250 receive a pointer to some data that the user wants to send to the device
251 and the size of the data. The function determines how much data it can
252 send to the device based on the size of the write urb it has created (this
253 size depends on the size of the bulk out end point that the device has).
254 Then it copies the data from user space to kernel space, points the urb to
255 the data and submits the urb to the USB subsystem. This can be seen in
256 the following code:
257 </para>
258 <programlisting>
259 /* we can only write as much as 1 urb will hold */
260 bytes_written = (count > skel->bulk_out_size) ? skel->bulk_out_size : count;
262 /* copy the data from user space into our urb */
263 copy_from_user(skel->write_urb->transfer_buffer, buffer, bytes_written);
265 /* set up our urb */
266 usb_fill_bulk_urb(skel->write_urb,
267 skel->dev,
268 usb_sndbulkpipe(skel->dev, skel->bulk_out_endpointAddr),
269 skel->write_urb->transfer_buffer,
270 bytes_written,
271 skel_write_bulk_callback,
272 skel);
274 /* send the data out the bulk port */
275 result = usb_submit_urb(skel->write_urb);
276 if (result) {
277 err(&quot;Failed submitting write urb, error %d&quot;, result);
279 </programlisting>
280 <para>
281 When the write urb is filled up with the proper information using the
282 usb_fill_bulk_urb function, we point the urb's completion callback to call our
283 own skel_write_bulk_callback function. This function is called when the
284 urb is finished by the USB subsystem. The callback function is called in
285 interrupt context, so caution must be taken not to do very much processing
286 at that time. Our implementation of skel_write_bulk_callback merely
287 reports if the urb was completed successfully or not and then returns.
288 </para>
289 <para>
290 The read function works a bit differently from the write function in that
291 we do not use an urb to transfer data from the device to the driver.
292 Instead we call the usb_bulk_msg function, which can be used to send or
293 receive data from a device without having to create urbs and handle
294 urb completion callback functions. We call the usb_bulk_msg function,
295 giving it a buffer into which to place any data received from the device
296 and a timeout value. If the timeout period expires without receiving any
297 data from the device, the function will fail and return an error message.
298 This can be shown with the following code:
299 </para>
300 <programlisting>
301 /* do an immediate bulk read to get data from the device */
302 retval = usb_bulk_msg (skel->dev,
303 usb_rcvbulkpipe (skel->dev,
304 skel->bulk_in_endpointAddr),
305 skel->bulk_in_buffer,
306 skel->bulk_in_size,
307 &amp;count, HZ*10);
308 /* if the read was successful, copy the data to user space */
309 if (!retval) {
310 if (copy_to_user (buffer, skel->bulk_in_buffer, count))
311 retval = -EFAULT;
312 else
313 retval = count;
315 </programlisting>
316 <para>
317 The usb_bulk_msg function can be very useful for doing single reads or
318 writes to a device; however, if you need to read or write constantly to a
319 device, it is recommended to set up your own urbs and submit them to the
320 USB subsystem.
321 </para>
322 <para>
323 When the user program releases the file handle that it has been using to
324 talk to the device, the release function in the driver is called. In this
325 function we decrement our private usage count and wait for possible
326 pending writes:
327 </para>
328 <programlisting>
329 /* decrement our usage count for the device */
330 --skel->open_count;
331 </programlisting>
332 <para>
333 One of the more difficult problems that USB drivers must be able to handle
334 smoothly is the fact that the USB device may be removed from the system at
335 any point in time, even if a program is currently talking to it. It needs
336 to be able to shut down any current reads and writes and notify the
337 user-space programs that the device is no longer there. The following
338 code (function <function>skel_delete</function>)
339 is an example of how to do this: </para>
340 <programlisting>
341 static inline void skel_delete (struct usb_skel *dev)
343 kfree (dev->bulk_in_buffer);
344 if (dev->bulk_out_buffer != NULL)
345 usb_free_coherent (dev->udev, dev->bulk_out_size,
346 dev->bulk_out_buffer,
347 dev->write_urb->transfer_dma);
348 usb_free_urb (dev->write_urb);
349 kfree (dev);
351 </programlisting>
352 <para>
353 If a program currently has an open handle to the device, we reset the flag
354 <literal>device_present</literal>. For
355 every read, write, release and other functions that expect a device to be
356 present, the driver first checks this flag to see if the device is
357 still present. If not, it releases that the device has disappeared, and a
358 -ENODEV error is returned to the user-space program. When the release
359 function is eventually called, it determines if there is no device
360 and if not, it does the cleanup that the skel_disconnect
361 function normally does if there are no open files on the device (see
362 Listing 5).
363 </para>
364 </chapter>
366 <chapter id="iso">
367 <title>Isochronous Data</title>
368 <para>
369 This usb-skeleton driver does not have any examples of interrupt or
370 isochronous data being sent to or from the device. Interrupt data is sent
371 almost exactly as bulk data is, with a few minor exceptions. Isochronous
372 data works differently with continuous streams of data being sent to or
373 from the device. The audio and video camera drivers are very good examples
374 of drivers that handle isochronous data and will be useful if you also
375 need to do this.
376 </para>
377 </chapter>
379 <chapter id="Conclusion">
380 <title>Conclusion</title>
381 <para>
382 Writing Linux USB device drivers is not a difficult task as the
383 usb-skeleton driver shows. This driver, combined with the other current
384 USB drivers, should provide enough examples to help a beginning author
385 create a working driver in a minimal amount of time. The linux-usb-devel
386 mailing list archives also contain a lot of helpful information.
387 </para>
388 </chapter>
390 <chapter id="resources">
391 <title>Resources</title>
392 <para>
393 The Linux USB Project: <ulink url="http://www.linux-usb.org">http://www.linux-usb.org/</ulink>
394 </para>
395 <para>
396 Linux Hotplug Project: <ulink url="http://linux-hotplug.sourceforge.net">http://linux-hotplug.sourceforge.net/</ulink>
397 </para>
398 <para>
399 Linux USB Working Devices List: <ulink url="http://www.qbik.ch/usb/devices">http://www.qbik.ch/usb/devices/</ulink>
400 </para>
401 <para>
402 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>
403 </para>
404 <para>
405 Programming Guide for Linux USB Device Drivers: <ulink url="http://usb.cs.tum.edu/usbdoc">http://usb.cs.tum.edu/usbdoc</ulink>
406 </para>
407 <para>
408 USB Home Page: <ulink url="http://www.usb.org">http://www.usb.org</ulink>
409 </para>
410 </chapter>
412 </book>