writing_usb_driver.tmpl 17 KB

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