writing_usb_driver.rst 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. .. _writing-usb-driver:
  2. ==========================
  3. Writing USB Device Drivers
  4. ==========================
  5. :Author: Greg Kroah-Hartman
  6. Introduction
  7. ============
  8. The Linux USB subsystem has grown from supporting only two different
  9. types of devices in the 2.2.7 kernel (mice and keyboards), to over 20
  10. different types of devices in the 2.4 kernel. Linux currently supports
  11. almost all USB class devices (standard types of devices like keyboards,
  12. mice, modems, printers and speakers) and an ever-growing number of
  13. vendor-specific devices (such as USB to serial converters, digital
  14. cameras, Ethernet devices and MP3 players). For a full list of the
  15. different USB devices currently supported, see Resources.
  16. The remaining kinds of USB devices that do not have support on Linux are
  17. almost all vendor-specific devices. Each vendor decides to implement a
  18. custom protocol to talk to their device, so a custom driver usually
  19. needs to be created. Some vendors are open with their USB protocols and
  20. help with the creation of Linux drivers, while others do not publish
  21. them, and developers are forced to reverse-engineer. See Resources for
  22. some links to handy reverse-engineering tools.
  23. Because each different protocol causes a new driver to be created, I
  24. have written a generic USB driver skeleton, modelled after the
  25. pci-skeleton.c file in the kernel source tree upon which many PCI
  26. network drivers have been based. This USB skeleton can be found at
  27. drivers/usb/usb-skeleton.c in the kernel source tree. In this article I
  28. will walk through the basics of the skeleton driver, explaining the
  29. different pieces and what needs to be done to customize it to your
  30. specific device.
  31. Linux USB Basics
  32. ================
  33. If you are going to write a Linux USB driver, please become familiar
  34. with the USB protocol specification. It can be found, along with many
  35. other useful documents, at the USB home page (see Resources). An
  36. excellent introduction to the Linux USB subsystem can be found at the
  37. USB Working Devices List (see Resources). It explains how the Linux USB
  38. subsystem is structured and introduces the reader to the concept of USB
  39. urbs (USB Request Blocks), which are essential to USB drivers.
  40. The first thing a Linux USB driver needs to do is register itself with
  41. the Linux USB subsystem, giving it some information about which devices
  42. the driver supports and which functions to call when a device supported
  43. by the driver is inserted or removed from the system. All of this
  44. information is passed to the USB subsystem in the :c:type:`usb_driver`
  45. structure. The skeleton driver declares a :c:type:`usb_driver` as::
  46. static struct usb_driver skel_driver = {
  47. .name = "skeleton",
  48. .probe = skel_probe,
  49. .disconnect = skel_disconnect,
  50. .fops = &skel_fops,
  51. .minor = USB_SKEL_MINOR_BASE,
  52. .id_table = skel_table,
  53. };
  54. The variable name is a string that describes the driver. It is used in
  55. informational messages printed to the system log. The probe and
  56. disconnect function pointers are called when a device that matches the
  57. information provided in the ``id_table`` variable is either seen or
  58. removed.
  59. The fops and minor variables are optional. Most USB drivers hook into
  60. another kernel subsystem, such as the SCSI, network or TTY subsystem.
  61. These types of drivers register themselves with the other kernel
  62. subsystem, and any user-space interactions are provided through that
  63. interface. But for drivers that do not have a matching kernel subsystem,
  64. such as MP3 players or scanners, a method of interacting with user space
  65. is needed. The USB subsystem provides a way to register a minor device
  66. number and a set of :c:type:`file_operations` function pointers that enable
  67. this user-space interaction. The skeleton driver needs this kind of
  68. interface, so it provides a minor starting number and a pointer to its
  69. :c:type:`file_operations` functions.
  70. The USB driver is then registered with a call to :c:func:`usb_register`,
  71. usually in the driver's init function, as shown here::
  72. static int __init usb_skel_init(void)
  73. {
  74. int result;
  75. /* register this driver with the USB subsystem */
  76. result = usb_register(&skel_driver);
  77. if (result < 0) {
  78. err("usb_register failed for the "__FILE__ "driver."
  79. "Error number %d", result);
  80. return -1;
  81. }
  82. return 0;
  83. }
  84. module_init(usb_skel_init);
  85. When the driver is unloaded from the system, it needs to deregister
  86. itself with the USB subsystem. This is done with the :c:func:`usb_deregister`
  87. function::
  88. static void __exit usb_skel_exit(void)
  89. {
  90. /* deregister this driver with the USB subsystem */
  91. usb_deregister(&skel_driver);
  92. }
  93. module_exit(usb_skel_exit);
  94. To enable the linux-hotplug system to load the driver automatically when
  95. the device is plugged in, you need to create a ``MODULE_DEVICE_TABLE``.
  96. The following code tells the hotplug scripts that this module supports a
  97. single device with a specific vendor and product ID::
  98. /* table of devices that work with this driver */
  99. static struct usb_device_id skel_table [] = {
  100. { USB_DEVICE(USB_SKEL_VENDOR_ID, USB_SKEL_PRODUCT_ID) },
  101. { } /* Terminating entry */
  102. };
  103. MODULE_DEVICE_TABLE (usb, skel_table);
  104. There are other macros that can be used in describing a struct
  105. :c:type:`usb_device_id` for drivers that support a whole class of USB
  106. drivers. See :ref:`usb.h <usb_header>` for more information on this.
  107. Device operation
  108. ================
  109. When a device is plugged into the USB bus that matches the device ID
  110. pattern that your driver registered with the USB core, the probe
  111. function is called. The :c:type:`usb_device` structure, interface number and
  112. the interface ID are passed to the function::
  113. static int skel_probe(struct usb_interface *interface,
  114. const struct usb_device_id *id)
  115. The driver now needs to verify that this device is actually one that it
  116. can accept. If so, it returns 0. If not, or if any error occurs during
  117. initialization, an errorcode (such as ``-ENOMEM`` or ``-ENODEV``) is
  118. returned from the probe function.
  119. In the skeleton driver, we determine what end points are marked as
  120. bulk-in and bulk-out. We create buffers to hold the data that will be
  121. sent and received from the device, and a USB urb to write data to the
  122. device is initialized.
  123. Conversely, when the device is removed from the USB bus, the disconnect
  124. function is called with the device pointer. The driver needs to clean
  125. any private data that has been allocated at this time and to shut down
  126. any pending urbs that are in the USB system.
  127. Now that the device is plugged into the system and the driver is bound
  128. to the device, any of the functions in the :c:type:`file_operations` structure
  129. that were passed to the USB subsystem will be called from a user program
  130. trying to talk to the device. The first function called will be open, as
  131. the program tries to open the device for I/O. We increment our private
  132. usage count and save a pointer to our internal structure in the file
  133. structure. This is done so that future calls to file operations will
  134. enable the driver to determine which device the user is addressing. All
  135. of this is done with the following code::
  136. /* increment our usage count for the module */
  137. ++skel->open_count;
  138. /* save our object in the file's private structure */
  139. file->private_data = dev;
  140. After the open function is called, the read and write functions are
  141. called to receive and send data to the device. In the ``skel_write``
  142. function, we receive a pointer to some data that the user wants to send
  143. to the device and the size of the data. The function determines how much
  144. data it can send to the device based on the size of the write urb it has
  145. created (this size depends on the size of the bulk out end point that
  146. the device has). Then it copies the data from user space to kernel
  147. space, points the urb to the data and submits the urb to the USB
  148. subsystem. This can be seen in the following code::
  149. /* we can only write as much as 1 urb will hold */
  150. bytes_written = (count > skel->bulk_out_size) ? skel->bulk_out_size : count;
  151. /* copy the data from user space into our urb */
  152. copy_from_user(skel->write_urb->transfer_buffer, buffer, bytes_written);
  153. /* set up our urb */
  154. usb_fill_bulk_urb(skel->write_urb,
  155. skel->dev,
  156. usb_sndbulkpipe(skel->dev, skel->bulk_out_endpointAddr),
  157. skel->write_urb->transfer_buffer,
  158. bytes_written,
  159. skel_write_bulk_callback,
  160. skel);
  161. /* send the data out the bulk port */
  162. result = usb_submit_urb(skel->write_urb);
  163. if (result) {
  164. err("Failed submitting write urb, error %d", result);
  165. }
  166. When the write urb is filled up with the proper information using the
  167. :c:func:`usb_fill_bulk_urb` function, we point the urb's completion callback
  168. to call our own ``skel_write_bulk_callback`` function. This function is
  169. called when the urb is finished by the USB subsystem. The callback
  170. function is called in interrupt context, so caution must be taken not to
  171. do very much processing at that time. Our implementation of
  172. ``skel_write_bulk_callback`` merely reports if the urb was completed
  173. successfully or not and then returns.
  174. The read function works a bit differently from the write function in
  175. that we do not use an urb to transfer data from the device to the
  176. driver. Instead we call the :c:func:`usb_bulk_msg` function, which can be used
  177. to send or receive data from a device without having to create urbs and
  178. handle urb completion callback functions. We call the :c:func:`usb_bulk_msg`
  179. function, giving it a buffer into which to place any data received from
  180. the device and a timeout value. If the timeout period expires without
  181. receiving any data from the device, the function will fail and return an
  182. error message. This can be shown with the following code::
  183. /* do an immediate bulk read to get data from the device */
  184. retval = usb_bulk_msg (skel->dev,
  185. usb_rcvbulkpipe (skel->dev,
  186. skel->bulk_in_endpointAddr),
  187. skel->bulk_in_buffer,
  188. skel->bulk_in_size,
  189. &count, HZ*10);
  190. /* if the read was successful, copy the data to user space */
  191. if (!retval) {
  192. if (copy_to_user (buffer, skel->bulk_in_buffer, count))
  193. retval = -EFAULT;
  194. else
  195. retval = count;
  196. }
  197. The :c:func:`usb_bulk_msg` function can be very useful for doing single reads
  198. or writes to a device; however, if you need to read or write constantly to
  199. a device, it is recommended to set up your own urbs and submit them to
  200. the USB subsystem.
  201. When the user program releases the file handle that it has been using to
  202. talk to the device, the release function in the driver is called. In
  203. this function we decrement our private usage count and wait for possible
  204. pending writes::
  205. /* decrement our usage count for the device */
  206. --skel->open_count;
  207. One of the more difficult problems that USB drivers must be able to
  208. handle smoothly is the fact that the USB device may be removed from the
  209. system at any point in time, even if a program is currently talking to
  210. it. It needs to be able to shut down any current reads and writes and
  211. notify the user-space programs that the device is no longer there. The
  212. following code (function ``skel_delete``) is an example of how to do
  213. this::
  214. static inline void skel_delete (struct usb_skel *dev)
  215. {
  216. kfree (dev->bulk_in_buffer);
  217. if (dev->bulk_out_buffer != NULL)
  218. usb_free_coherent (dev->udev, dev->bulk_out_size,
  219. dev->bulk_out_buffer,
  220. dev->write_urb->transfer_dma);
  221. usb_free_urb (dev->write_urb);
  222. kfree (dev);
  223. }
  224. If a program currently has an open handle to the device, we reset the
  225. flag ``device_present``. For every read, write, release and other
  226. functions that expect a device to be present, the driver first checks
  227. this flag to see if the device is still present. If not, it releases
  228. that the device has disappeared, and a ``-ENODEV`` error is returned to the
  229. user-space program. When the release function is eventually called, it
  230. determines if there is no device and if not, it does the cleanup that
  231. the ``skel_disconnect`` function normally does if there are no open files
  232. on the device (see Listing 5).
  233. Isochronous Data
  234. ================
  235. This usb-skeleton driver does not have any examples of interrupt or
  236. isochronous data being sent to or from the device. Interrupt data is
  237. sent almost exactly as bulk data is, with a few minor exceptions.
  238. Isochronous data works differently with continuous streams of data being
  239. sent to or from the device. The audio and video camera drivers are very
  240. good examples of drivers that handle isochronous data and will be useful
  241. if you also need to do this.
  242. Conclusion
  243. ==========
  244. Writing Linux USB device drivers is not a difficult task as the
  245. usb-skeleton driver shows. This driver, combined with the other current
  246. USB drivers, should provide enough examples to help a beginning author
  247. create a working driver in a minimal amount of time. The linux-usb-devel
  248. mailing list archives also contain a lot of helpful information.
  249. Resources
  250. =========
  251. The Linux USB Project:
  252. http://www.linux-usb.org/
  253. Linux Hotplug Project:
  254. http://linux-hotplug.sourceforge.net/
  255. Linux USB Working Devices List:
  256. http://www.qbik.ch/usb/devices/
  257. linux-usb-devel Mailing List Archives:
  258. http://marc.theaimsgroup.com/?l=linux-usb-devel
  259. Programming Guide for Linux USB Device Drivers:
  260. http://lmu.web.psi.ch/docu/manuals/software_manuals/linux_sl/usb_linux_programming_guide.pdf
  261. USB Home Page: http://www.usb.org