ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[linux-2.6.git] / Documentation / DocBook / writing_usb_driver.tmpl
1 <!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook V3.1//EN"[]>
2
3 <book id="USBDeviceDriver">
4  <bookinfo>
5   <title>Writing USB Device Drivers</title>
6   
7   <authorgroup>
8    <author>
9     <firstname>Greg</firstname>
10     <surname>Kroah-Hartman</surname>
11     <affiliation>
12      <address>
13       <email>greg@kroah.com</email>
14      </address>
15     </affiliation>
16    </author>
17   </authorgroup>
18
19   <copyright>
20    <year>2001-2002</year>
21    <holder>Greg Kroah-Hartman</holder>
22   </copyright>
23
24   <legalnotice>
25    <para>
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
30      version.
31    </para>
32       
33    <para>
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.
38    </para>
39       
40    <para>
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,
44      MA 02111-1307 USA
45    </para>
46       
47    <para>
48      For more details see the file COPYING in the source
49      distribution of Linux.
50    </para>
51
52    <para>
53      This documentation is based on an article published in 
54      Linux Journal Magazine, October 2001, Issue 90.
55    </para>
56   </legalnotice>
57  </bookinfo>
58
59 <toc></toc>
60
61   <chapter id="intro">
62       <title>Introduction</title>
63   <para>
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.
72   </para>
73   <para>
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.
81   </para>
82   <para>
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.
90   </para>
91   </chapter>
92
93   <chapter id="basics">
94       <title>Linux USB Basics</title>
95   <para>
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.
103   </para>
104   <para>
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:
111   </para>
112   <programlisting>
113 static struct usb_driver skel_driver = {
114         .name        = "skeleton",
115         .probe       = skel_probe,
116         .disconnect  = skel_disconnect,
117         .fops        = &amp;skel_fops,
118         .minor       = USB_SKEL_MINOR_BASE,
119         .id_table    = skel_table,
120 };
121   </programlisting>
122   <para>
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.
127   </para>
128   <para>
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.
140   </para>
141   <para>
142       The USB driver is then registered with a call to usb_register, usually in
143       the driver's init function, as shown here:
144   </para>
145   <programlisting>
146 static int __init usb_skel_init(void)
147 {
148         int result;
149
150         /* register this driver with the USB subsystem */
151         result = usb_register(&amp;skel_driver);
152         if (result &lt; 0) {
153                 err(&quot;usb_register failed for the &quot;__FILE__ &quot;driver.&quot;
154                     &quot;Error number %d&quot;, result);
155                 return -1;
156         }
157
158         return 0;
159 }
160 module_init(usb_skel_init);
161   </programlisting>
162   <para>
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
165       function:
166   </para>
167   <programlisting>
168 static void __exit usb_skel_exit(void)
169 {
170         /* deregister this driver with the USB subsystem */
171         usb_deregister(&amp;skel_driver);
172 }
173 module_exit(usb_skel_exit);
174   </programlisting>
175   <para>
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:
180   </para>
181   <programlisting>
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 */
186 };
187 MODULE_DEVICE_TABLE (usb, skel_table);
188   </programlisting>
189   <para>
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
192      information on this.
193   </para>
194   </chapter>
195
196   <chapter id="device">
197       <title>Device operation</title>
198   <para>
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:
203   </para>
204   <programlisting>
205 static int skel_probe(struct usb_interface *interface,
206     const struct usb_device_id *id)
207   </programlisting>
208   <para>
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.
214   </para>
215   <para>
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
219      initialized.
220   </para>
221   <para>
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:
227   </para>
228   <programlisting>
229 /* remove our devfs node */
230 devfs_unregister(skel->devfs);
231   </programlisting>
232   <para>
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:
242   </para>
243   <programlisting>
244 /* increment our usage count for the module */
245 ++skel->open_count;
246
247 /* save our object in the file's private structure */
248 file->private_data = dev;
249   </programlisting>
250   <para>
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
259      he following code:
260   </para>
261   <programlisting>
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;
264
265 /* copy the data from user space into our urb */
266 copy_from_user(skel->write_urb->transfer_buffer, buffer, bytes_written);
267
268 /* set up our urb */
269 usb_fill_bulk_urb(skel->write_urb,
270                   skel->dev,
271                   usb_sndbulkpipe(skel->dev, skel->bulk_out_endpointAddr),
272                   skel->write_urb->transfer_buffer,
273                   bytes_written,
274                   skel_write_bulk_callback,
275                   skel);
276
277 /* send the data out the bulk port */
278 result = usb_submit_urb(skel->write_urb);
279 if (result) {
280         err(&quot;Failed submitting write urb, error %d&quot;, result);
281 }
282   </programlisting>
283   <para>
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.
291   </para>
292   <para>
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:
302   </para>
303   <programlisting>
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,
309                        skel->bulk_in_size,
310                        &amp;count, HZ*10);
311 /* if the read was successful, copy the data to user space */
312 if (!retval) {
313         if (copy_to_user (buffer, skel->bulk_in_buffer, count))
314                 retval = -EFAULT;
315         else
316                 retval = count;
317 }
318   </programlisting>
319   <para>
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
323      USB subsystem.
324   </para>
325   <para>
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
329      pending writes:
330   </para>
331   <programlisting>
332 /* decrement our usage count for the device */
333 --skel->open_count;
334   </programlisting>
335   <para>
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>
343   <programlisting>
344 static inline void skel_delete (struct usb_skel *dev)
345 {
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);
354     kfree (dev);
355 }
356   </programlisting>
357   <para>
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
367      Listing 5).
368   </para>
369   </chapter>
370
371   <chapter id="iso">
372       <title>Isochronous Data</title>
373   <para>
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
380      need to do this.
381   </para>
382   </chapter>
383   
384   <chapter id="Conclusion">
385       <title>Conclusion</title>
386   <para>
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.
392   </para>
393   </chapter>
394
395   <chapter id="resources">
396       <title>Resources</title>
397   <para>
398      The Linux USB Project: <ulink url="http://www.linux-usb.org">http://www.linux-usb.org/</ulink>
399   </para>
400   <para>
401      Linux Hotplug Project: <ulink url="http://linux-hotplug.sourceforge.net">http://linux-hotplug.sourceforge.net/</ulink>
402   </para>
403   <para>
404      Linux USB Working Devices List: <ulink url="http://www.qbik.ch/usb/devices">http://www.qbik.ch/usb/devices/</ulink>
405   </para>
406   <para>
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>
408   </para>
409   <para>
410      Programming Guide for Linux USB Device Drivers: <ulink url="http://usb.cs.tum.edu/usbdoc">http://usb.cs.tum.edu/usbdoc</ulink>
411   </para>
412   <para>
413      USB Home Page: <ulink url="http://www.usb.org">http://www.usb.org</ulink>
414   </para>
415   </chapter>
416
417 </book>