OpenCores
URL https://opencores.org/ocsvn/test_project/test_project/trunk

Subversion Repositories test_project

[/] [test_project/] [trunk/] [linux_sd_driver/] [Documentation/] [DocBook/] [writing_usb_driver.tmpl] - Blame information for rev 78

Go to most recent revision | Details | Compare with Previous | View Log

Line No. Rev Author Line
1 62 marcus.erl
2
3
        "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd" []>
4
 
5
6
 
7
  Writing USB Device Drivers
8
 
9
  
10
   
11
    Greg
12
    Kroah-Hartman
13
    
14
     
15
      greg@kroah.com
16
     
17
    
18
   
19
  
20
 
21
  
22
   2001-2002
23
   Greg Kroah-Hartman
24
  
25
 
26
  
27
   
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
   
34
 
35
   
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
   
41
 
42
   
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
   
48
 
49
   
50
     For more details see the file COPYING in the source
51
     distribution of Linux.
52
   
53
 
54
   
55
     This documentation is based on an article published in
56
     Linux Journal Magazine, October 2001, Issue 90.
57
   
58
  
59
 
60
 
61
62
 
63
  
64
      Introduction
65
  
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
  
75
  
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
  
84
  
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
  
93
  
94
 
95
  
96
      Linux USB Basics
97
  
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, which
104
      are essential to USB drivers.
105
  
106
  
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
  
114
  
115
static struct usb_driver skel_driver = {
116
        .name        = "skeleton",
117
        .probe       = skel_probe,
118
        .disconnect  = skel_disconnect,
119
        .fops        = &skel_fops,
120
        .minor       = USB_SKEL_MINOR_BASE,
121
        .id_table    = skel_table,
122
};
123
  
124
  
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
  
130
  
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
  
143
  
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
  
147
  
148
static int __init usb_skel_init(void)
149
{
150
        int result;
151
 
152
        /* register this driver with the USB subsystem */
153
        result = usb_register(&skel_driver);
154
        if (result < 0) {
155
                err("usb_register failed for the "__FILE__ "driver."
156
                    "Error number %d", result);
157
                return -1;
158
        }
159
 
160
        return 0;
161
}
162
module_init(usb_skel_init);
163
  
164
  
165
      When the driver is unloaded from the system, it needs to unregister
166
      itself with the USB subsystem. This is done with the usb_unregister
167
      function:
168
  
169
  
170
static void __exit usb_skel_exit(void)
171
{
172
        /* deregister this driver with the USB subsystem */
173
        usb_deregister(&skel_driver);
174
}
175
module_exit(usb_skel_exit);
176
  
177
  
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
  
183
  
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 */
188
};
189
MODULE_DEVICE_TABLE (usb, skel_table);
190
  
191
  
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
  
196
  
197
 
198
  
199
      Device operation
200
  
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
  
206
  
207
static int skel_probe(struct usb_interface *interface,
208
    const struct usb_device_id *id)
209
  
210
  
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 -ENOMEM or -ENODEV)
215
     is returned from the probe function.
216
  
217
  
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
  
223
  
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
  
229
  
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 off 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
  
240
  
241
/* increment our usage count for the module */
242
++skel->open_count;
243
 
244
/* save our object in the file's private structure */
245
file->private_data = dev;
246
  
247
  
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 shown in
256
     he following code:
257
  
258
  
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;
261
 
262
/* copy the data from user space into our urb */
263
copy_from_user(skel->write_urb->transfer_buffer, buffer, bytes_written);
264
 
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);
273
 
274
/* send the data out the bulk port */
275
result = usb_submit_urb(skel->write_urb);
276
if (result) {
277
        err("Failed submitting write urb, error %d", result);
278
}
279
  
280
  
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
  
289
  
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
  
300
  
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
                       &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;
314
}
315
  
316
  
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
  
322
  
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
  
328
  
329
/* decrement our usage count for the device */
330
--skel->open_count;
331
  
332
  
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 skel_delete)
339
     is an example of how to do this: 
340
  
341
static inline void skel_delete (struct usb_skel *dev)
342
{
343
    kfree (dev->bulk_in_buffer);
344
    if (dev->bulk_out_buffer != NULL)
345
        usb_buffer_free (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);
350
}
351
  
352
  
353
     If a program currently has an open handle to the device, we reset the flag
354
     device_present. 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
  
364
  
365
 
366
  
367
      Isochronous Data
368
  
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
  
377
  
378
 
379
  
380
      Conclusion
381
  
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
  
388
  
389
 
390
  
391
      Resources
392
  
393
     The Linux USB Project: http://www.linux-usb.org/
394
  
395
  
396
     Linux Hotplug Project: http://linux-hotplug.sourceforge.net/
397
  
398
  
399
     Linux USB Working Devices List: http://www.qbik.ch/usb/devices/
400
  
401
  
402
     linux-usb-devel Mailing List Archives: http://marc.theaimsgroup.com/?l=linux-usb-devel
403
  
404
  
405
     Programming Guide for Linux USB Device Drivers: http://usb.cs.tum.edu/usbdoc
406
  
407
  
408
     USB Home Page: http://www.usb.org
409
  
410
  
411
 
412

powered by: WebSVN 2.1.0

© copyright 1999-2025 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.