xref: /OK3568_Linux_fs/kernel/Documentation/driver-api/usb/writing_usb_driver.rst (revision 4882a59341e53eb6f0b4789bf948001014eff981)
1*4882a593Smuzhiyun.. _writing-usb-driver:
2*4882a593Smuzhiyun
3*4882a593Smuzhiyun==========================
4*4882a593SmuzhiyunWriting USB Device Drivers
5*4882a593Smuzhiyun==========================
6*4882a593Smuzhiyun
7*4882a593Smuzhiyun:Author: Greg Kroah-Hartman
8*4882a593Smuzhiyun
9*4882a593SmuzhiyunIntroduction
10*4882a593Smuzhiyun============
11*4882a593Smuzhiyun
12*4882a593SmuzhiyunThe Linux USB subsystem has grown from supporting only two different
13*4882a593Smuzhiyuntypes of devices in the 2.2.7 kernel (mice and keyboards), to over 20
14*4882a593Smuzhiyundifferent types of devices in the 2.4 kernel. Linux currently supports
15*4882a593Smuzhiyunalmost all USB class devices (standard types of devices like keyboards,
16*4882a593Smuzhiyunmice, modems, printers and speakers) and an ever-growing number of
17*4882a593Smuzhiyunvendor-specific devices (such as USB to serial converters, digital
18*4882a593Smuzhiyuncameras, Ethernet devices and MP3 players). For a full list of the
19*4882a593Smuzhiyundifferent USB devices currently supported, see Resources.
20*4882a593Smuzhiyun
21*4882a593SmuzhiyunThe remaining kinds of USB devices that do not have support on Linux are
22*4882a593Smuzhiyunalmost all vendor-specific devices. Each vendor decides to implement a
23*4882a593Smuzhiyuncustom protocol to talk to their device, so a custom driver usually
24*4882a593Smuzhiyunneeds to be created. Some vendors are open with their USB protocols and
25*4882a593Smuzhiyunhelp with the creation of Linux drivers, while others do not publish
26*4882a593Smuzhiyunthem, and developers are forced to reverse-engineer. See Resources for
27*4882a593Smuzhiyunsome links to handy reverse-engineering tools.
28*4882a593Smuzhiyun
29*4882a593SmuzhiyunBecause each different protocol causes a new driver to be created, I
30*4882a593Smuzhiyunhave written a generic USB driver skeleton, modelled after the
31*4882a593Smuzhiyunpci-skeleton.c file in the kernel source tree upon which many PCI
32*4882a593Smuzhiyunnetwork drivers have been based. This USB skeleton can be found at
33*4882a593Smuzhiyundrivers/usb/usb-skeleton.c in the kernel source tree. In this article I
34*4882a593Smuzhiyunwill walk through the basics of the skeleton driver, explaining the
35*4882a593Smuzhiyundifferent pieces and what needs to be done to customize it to your
36*4882a593Smuzhiyunspecific device.
37*4882a593Smuzhiyun
38*4882a593SmuzhiyunLinux USB Basics
39*4882a593Smuzhiyun================
40*4882a593Smuzhiyun
41*4882a593SmuzhiyunIf you are going to write a Linux USB driver, please become familiar
42*4882a593Smuzhiyunwith the USB protocol specification. It can be found, along with many
43*4882a593Smuzhiyunother useful documents, at the USB home page (see Resources). An
44*4882a593Smuzhiyunexcellent introduction to the Linux USB subsystem can be found at the
45*4882a593SmuzhiyunUSB Working Devices List (see Resources). It explains how the Linux USB
46*4882a593Smuzhiyunsubsystem is structured and introduces the reader to the concept of USB
47*4882a593Smuzhiyunurbs (USB Request Blocks), which are essential to USB drivers.
48*4882a593Smuzhiyun
49*4882a593SmuzhiyunThe first thing a Linux USB driver needs to do is register itself with
50*4882a593Smuzhiyunthe Linux USB subsystem, giving it some information about which devices
51*4882a593Smuzhiyunthe driver supports and which functions to call when a device supported
52*4882a593Smuzhiyunby the driver is inserted or removed from the system. All of this
53*4882a593Smuzhiyuninformation is passed to the USB subsystem in the :c:type:`usb_driver`
54*4882a593Smuzhiyunstructure. The skeleton driver declares a :c:type:`usb_driver` as::
55*4882a593Smuzhiyun
56*4882a593Smuzhiyun    static struct usb_driver skel_driver = {
57*4882a593Smuzhiyun	    .name        = "skeleton",
58*4882a593Smuzhiyun	    .probe       = skel_probe,
59*4882a593Smuzhiyun	    .disconnect  = skel_disconnect,
60*4882a593Smuzhiyun	    .fops        = &skel_fops,
61*4882a593Smuzhiyun	    .minor       = USB_SKEL_MINOR_BASE,
62*4882a593Smuzhiyun	    .id_table    = skel_table,
63*4882a593Smuzhiyun    };
64*4882a593Smuzhiyun
65*4882a593Smuzhiyun
66*4882a593SmuzhiyunThe variable name is a string that describes the driver. It is used in
67*4882a593Smuzhiyuninformational messages printed to the system log. The probe and
68*4882a593Smuzhiyundisconnect function pointers are called when a device that matches the
69*4882a593Smuzhiyuninformation provided in the ``id_table`` variable is either seen or
70*4882a593Smuzhiyunremoved.
71*4882a593Smuzhiyun
72*4882a593SmuzhiyunThe fops and minor variables are optional. Most USB drivers hook into
73*4882a593Smuzhiyunanother kernel subsystem, such as the SCSI, network or TTY subsystem.
74*4882a593SmuzhiyunThese types of drivers register themselves with the other kernel
75*4882a593Smuzhiyunsubsystem, and any user-space interactions are provided through that
76*4882a593Smuzhiyuninterface. But for drivers that do not have a matching kernel subsystem,
77*4882a593Smuzhiyunsuch as MP3 players or scanners, a method of interacting with user space
78*4882a593Smuzhiyunis needed. The USB subsystem provides a way to register a minor device
79*4882a593Smuzhiyunnumber and a set of :c:type:`file_operations` function pointers that enable
80*4882a593Smuzhiyunthis user-space interaction. The skeleton driver needs this kind of
81*4882a593Smuzhiyuninterface, so it provides a minor starting number and a pointer to its
82*4882a593Smuzhiyun:c:type:`file_operations` functions.
83*4882a593Smuzhiyun
84*4882a593SmuzhiyunThe USB driver is then registered with a call to :c:func:`usb_register`,
85*4882a593Smuzhiyunusually in the driver's init function, as shown here::
86*4882a593Smuzhiyun
87*4882a593Smuzhiyun    static int __init usb_skel_init(void)
88*4882a593Smuzhiyun    {
89*4882a593Smuzhiyun	    int result;
90*4882a593Smuzhiyun
91*4882a593Smuzhiyun	    /* register this driver with the USB subsystem */
92*4882a593Smuzhiyun	    result = usb_register(&skel_driver);
93*4882a593Smuzhiyun	    if (result < 0) {
94*4882a593Smuzhiyun		    err("usb_register failed for the "__FILE__ "driver."
95*4882a593Smuzhiyun			"Error number %d", result);
96*4882a593Smuzhiyun		    return -1;
97*4882a593Smuzhiyun	    }
98*4882a593Smuzhiyun
99*4882a593Smuzhiyun	    return 0;
100*4882a593Smuzhiyun    }
101*4882a593Smuzhiyun    module_init(usb_skel_init);
102*4882a593Smuzhiyun
103*4882a593Smuzhiyun
104*4882a593SmuzhiyunWhen the driver is unloaded from the system, it needs to deregister
105*4882a593Smuzhiyunitself with the USB subsystem. This is done with the :c:func:`usb_deregister`
106*4882a593Smuzhiyunfunction::
107*4882a593Smuzhiyun
108*4882a593Smuzhiyun    static void __exit usb_skel_exit(void)
109*4882a593Smuzhiyun    {
110*4882a593Smuzhiyun	    /* deregister this driver with the USB subsystem */
111*4882a593Smuzhiyun	    usb_deregister(&skel_driver);
112*4882a593Smuzhiyun    }
113*4882a593Smuzhiyun    module_exit(usb_skel_exit);
114*4882a593Smuzhiyun
115*4882a593Smuzhiyun
116*4882a593SmuzhiyunTo enable the linux-hotplug system to load the driver automatically when
117*4882a593Smuzhiyunthe device is plugged in, you need to create a ``MODULE_DEVICE_TABLE``.
118*4882a593SmuzhiyunThe following code tells the hotplug scripts that this module supports a
119*4882a593Smuzhiyunsingle device with a specific vendor and product ID::
120*4882a593Smuzhiyun
121*4882a593Smuzhiyun    /* table of devices that work with this driver */
122*4882a593Smuzhiyun    static struct usb_device_id skel_table [] = {
123*4882a593Smuzhiyun	    { USB_DEVICE(USB_SKEL_VENDOR_ID, USB_SKEL_PRODUCT_ID) },
124*4882a593Smuzhiyun	    { }                      /* Terminating entry */
125*4882a593Smuzhiyun    };
126*4882a593Smuzhiyun    MODULE_DEVICE_TABLE (usb, skel_table);
127*4882a593Smuzhiyun
128*4882a593Smuzhiyun
129*4882a593SmuzhiyunThere are other macros that can be used in describing a struct
130*4882a593Smuzhiyun:c:type:`usb_device_id` for drivers that support a whole class of USB
131*4882a593Smuzhiyundrivers. See :ref:`usb.h <usb_header>` for more information on this.
132*4882a593Smuzhiyun
133*4882a593SmuzhiyunDevice operation
134*4882a593Smuzhiyun================
135*4882a593Smuzhiyun
136*4882a593SmuzhiyunWhen a device is plugged into the USB bus that matches the device ID
137*4882a593Smuzhiyunpattern that your driver registered with the USB core, the probe
138*4882a593Smuzhiyunfunction is called. The :c:type:`usb_device` structure, interface number and
139*4882a593Smuzhiyunthe interface ID are passed to the function::
140*4882a593Smuzhiyun
141*4882a593Smuzhiyun    static int skel_probe(struct usb_interface *interface,
142*4882a593Smuzhiyun	const struct usb_device_id *id)
143*4882a593Smuzhiyun
144*4882a593Smuzhiyun
145*4882a593SmuzhiyunThe driver now needs to verify that this device is actually one that it
146*4882a593Smuzhiyuncan accept. If so, it returns 0. If not, or if any error occurs during
147*4882a593Smuzhiyuninitialization, an errorcode (such as ``-ENOMEM`` or ``-ENODEV``) is
148*4882a593Smuzhiyunreturned from the probe function.
149*4882a593Smuzhiyun
150*4882a593SmuzhiyunIn the skeleton driver, we determine what end points are marked as
151*4882a593Smuzhiyunbulk-in and bulk-out. We create buffers to hold the data that will be
152*4882a593Smuzhiyunsent and received from the device, and a USB urb to write data to the
153*4882a593Smuzhiyundevice is initialized.
154*4882a593Smuzhiyun
155*4882a593SmuzhiyunConversely, when the device is removed from the USB bus, the disconnect
156*4882a593Smuzhiyunfunction is called with the device pointer. The driver needs to clean
157*4882a593Smuzhiyunany private data that has been allocated at this time and to shut down
158*4882a593Smuzhiyunany pending urbs that are in the USB system.
159*4882a593Smuzhiyun
160*4882a593SmuzhiyunNow that the device is plugged into the system and the driver is bound
161*4882a593Smuzhiyunto the device, any of the functions in the :c:type:`file_operations` structure
162*4882a593Smuzhiyunthat were passed to the USB subsystem will be called from a user program
163*4882a593Smuzhiyuntrying to talk to the device. The first function called will be open, as
164*4882a593Smuzhiyunthe program tries to open the device for I/O. We increment our private
165*4882a593Smuzhiyunusage count and save a pointer to our internal structure in the file
166*4882a593Smuzhiyunstructure. This is done so that future calls to file operations will
167*4882a593Smuzhiyunenable the driver to determine which device the user is addressing. All
168*4882a593Smuzhiyunof this is done with the following code::
169*4882a593Smuzhiyun
170*4882a593Smuzhiyun    /* increment our usage count for the module */
171*4882a593Smuzhiyun    ++skel->open_count;
172*4882a593Smuzhiyun
173*4882a593Smuzhiyun    /* save our object in the file's private structure */
174*4882a593Smuzhiyun    file->private_data = dev;
175*4882a593Smuzhiyun
176*4882a593Smuzhiyun
177*4882a593SmuzhiyunAfter the open function is called, the read and write functions are
178*4882a593Smuzhiyuncalled to receive and send data to the device. In the ``skel_write``
179*4882a593Smuzhiyunfunction, we receive a pointer to some data that the user wants to send
180*4882a593Smuzhiyunto the device and the size of the data. The function determines how much
181*4882a593Smuzhiyundata it can send to the device based on the size of the write urb it has
182*4882a593Smuzhiyuncreated (this size depends on the size of the bulk out end point that
183*4882a593Smuzhiyunthe device has). Then it copies the data from user space to kernel
184*4882a593Smuzhiyunspace, points the urb to the data and submits the urb to the USB
185*4882a593Smuzhiyunsubsystem. This can be seen in the following code::
186*4882a593Smuzhiyun
187*4882a593Smuzhiyun    /* we can only write as much as 1 urb will hold */
188*4882a593Smuzhiyun    bytes_written = (count > skel->bulk_out_size) ? skel->bulk_out_size : count;
189*4882a593Smuzhiyun
190*4882a593Smuzhiyun    /* copy the data from user space into our urb */
191*4882a593Smuzhiyun    copy_from_user(skel->write_urb->transfer_buffer, buffer, bytes_written);
192*4882a593Smuzhiyun
193*4882a593Smuzhiyun    /* set up our urb */
194*4882a593Smuzhiyun    usb_fill_bulk_urb(skel->write_urb,
195*4882a593Smuzhiyun		      skel->dev,
196*4882a593Smuzhiyun		      usb_sndbulkpipe(skel->dev, skel->bulk_out_endpointAddr),
197*4882a593Smuzhiyun		      skel->write_urb->transfer_buffer,
198*4882a593Smuzhiyun		      bytes_written,
199*4882a593Smuzhiyun		      skel_write_bulk_callback,
200*4882a593Smuzhiyun		      skel);
201*4882a593Smuzhiyun
202*4882a593Smuzhiyun    /* send the data out the bulk port */
203*4882a593Smuzhiyun    result = usb_submit_urb(skel->write_urb);
204*4882a593Smuzhiyun    if (result) {
205*4882a593Smuzhiyun	    err("Failed submitting write urb, error %d", result);
206*4882a593Smuzhiyun    }
207*4882a593Smuzhiyun
208*4882a593Smuzhiyun
209*4882a593SmuzhiyunWhen the write urb is filled up with the proper information using the
210*4882a593Smuzhiyun:c:func:`usb_fill_bulk_urb` function, we point the urb's completion callback
211*4882a593Smuzhiyunto call our own ``skel_write_bulk_callback`` function. This function is
212*4882a593Smuzhiyuncalled when the urb is finished by the USB subsystem. The callback
213*4882a593Smuzhiyunfunction is called in interrupt context, so caution must be taken not to
214*4882a593Smuzhiyundo very much processing at that time. Our implementation of
215*4882a593Smuzhiyun``skel_write_bulk_callback`` merely reports if the urb was completed
216*4882a593Smuzhiyunsuccessfully or not and then returns.
217*4882a593Smuzhiyun
218*4882a593SmuzhiyunThe read function works a bit differently from the write function in
219*4882a593Smuzhiyunthat we do not use an urb to transfer data from the device to the
220*4882a593Smuzhiyundriver. Instead we call the :c:func:`usb_bulk_msg` function, which can be used
221*4882a593Smuzhiyunto send or receive data from a device without having to create urbs and
222*4882a593Smuzhiyunhandle urb completion callback functions. We call the :c:func:`usb_bulk_msg`
223*4882a593Smuzhiyunfunction, giving it a buffer into which to place any data received from
224*4882a593Smuzhiyunthe device and a timeout value. If the timeout period expires without
225*4882a593Smuzhiyunreceiving any data from the device, the function will fail and return an
226*4882a593Smuzhiyunerror message. This can be shown with the following code::
227*4882a593Smuzhiyun
228*4882a593Smuzhiyun    /* do an immediate bulk read to get data from the device */
229*4882a593Smuzhiyun    retval = usb_bulk_msg (skel->dev,
230*4882a593Smuzhiyun			   usb_rcvbulkpipe (skel->dev,
231*4882a593Smuzhiyun			   skel->bulk_in_endpointAddr),
232*4882a593Smuzhiyun			   skel->bulk_in_buffer,
233*4882a593Smuzhiyun			   skel->bulk_in_size,
234*4882a593Smuzhiyun			   &count, HZ*10);
235*4882a593Smuzhiyun    /* if the read was successful, copy the data to user space */
236*4882a593Smuzhiyun    if (!retval) {
237*4882a593Smuzhiyun	    if (copy_to_user (buffer, skel->bulk_in_buffer, count))
238*4882a593Smuzhiyun		    retval = -EFAULT;
239*4882a593Smuzhiyun	    else
240*4882a593Smuzhiyun		    retval = count;
241*4882a593Smuzhiyun    }
242*4882a593Smuzhiyun
243*4882a593Smuzhiyun
244*4882a593SmuzhiyunThe :c:func:`usb_bulk_msg` function can be very useful for doing single reads
245*4882a593Smuzhiyunor writes to a device; however, if you need to read or write constantly to
246*4882a593Smuzhiyuna device, it is recommended to set up your own urbs and submit them to
247*4882a593Smuzhiyunthe USB subsystem.
248*4882a593Smuzhiyun
249*4882a593SmuzhiyunWhen the user program releases the file handle that it has been using to
250*4882a593Smuzhiyuntalk to the device, the release function in the driver is called. In
251*4882a593Smuzhiyunthis function we decrement our private usage count and wait for possible
252*4882a593Smuzhiyunpending writes::
253*4882a593Smuzhiyun
254*4882a593Smuzhiyun    /* decrement our usage count for the device */
255*4882a593Smuzhiyun    --skel->open_count;
256*4882a593Smuzhiyun
257*4882a593Smuzhiyun
258*4882a593SmuzhiyunOne of the more difficult problems that USB drivers must be able to
259*4882a593Smuzhiyunhandle smoothly is the fact that the USB device may be removed from the
260*4882a593Smuzhiyunsystem at any point in time, even if a program is currently talking to
261*4882a593Smuzhiyunit. It needs to be able to shut down any current reads and writes and
262*4882a593Smuzhiyunnotify the user-space programs that the device is no longer there. The
263*4882a593Smuzhiyunfollowing code (function ``skel_delete``) is an example of how to do
264*4882a593Smuzhiyunthis::
265*4882a593Smuzhiyun
266*4882a593Smuzhiyun    static inline void skel_delete (struct usb_skel *dev)
267*4882a593Smuzhiyun    {
268*4882a593Smuzhiyun	kfree (dev->bulk_in_buffer);
269*4882a593Smuzhiyun	if (dev->bulk_out_buffer != NULL)
270*4882a593Smuzhiyun	    usb_free_coherent (dev->udev, dev->bulk_out_size,
271*4882a593Smuzhiyun		dev->bulk_out_buffer,
272*4882a593Smuzhiyun		dev->write_urb->transfer_dma);
273*4882a593Smuzhiyun	usb_free_urb (dev->write_urb);
274*4882a593Smuzhiyun	kfree (dev);
275*4882a593Smuzhiyun    }
276*4882a593Smuzhiyun
277*4882a593Smuzhiyun
278*4882a593SmuzhiyunIf a program currently has an open handle to the device, we reset the
279*4882a593Smuzhiyunflag ``device_present``. For every read, write, release and other
280*4882a593Smuzhiyunfunctions that expect a device to be present, the driver first checks
281*4882a593Smuzhiyunthis flag to see if the device is still present. If not, it releases
282*4882a593Smuzhiyunthat the device has disappeared, and a ``-ENODEV`` error is returned to the
283*4882a593Smuzhiyunuser-space program. When the release function is eventually called, it
284*4882a593Smuzhiyundetermines if there is no device and if not, it does the cleanup that
285*4882a593Smuzhiyunthe ``skel_disconnect`` function normally does if there are no open files
286*4882a593Smuzhiyunon the device (see Listing 5).
287*4882a593Smuzhiyun
288*4882a593SmuzhiyunIsochronous Data
289*4882a593Smuzhiyun================
290*4882a593Smuzhiyun
291*4882a593SmuzhiyunThis usb-skeleton driver does not have any examples of interrupt or
292*4882a593Smuzhiyunisochronous data being sent to or from the device. Interrupt data is
293*4882a593Smuzhiyunsent almost exactly as bulk data is, with a few minor exceptions.
294*4882a593SmuzhiyunIsochronous data works differently with continuous streams of data being
295*4882a593Smuzhiyunsent to or from the device. The audio and video camera drivers are very
296*4882a593Smuzhiyungood examples of drivers that handle isochronous data and will be useful
297*4882a593Smuzhiyunif you also need to do this.
298*4882a593Smuzhiyun
299*4882a593SmuzhiyunConclusion
300*4882a593Smuzhiyun==========
301*4882a593Smuzhiyun
302*4882a593SmuzhiyunWriting Linux USB device drivers is not a difficult task as the
303*4882a593Smuzhiyunusb-skeleton driver shows. This driver, combined with the other current
304*4882a593SmuzhiyunUSB drivers, should provide enough examples to help a beginning author
305*4882a593Smuzhiyuncreate a working driver in a minimal amount of time. The linux-usb-devel
306*4882a593Smuzhiyunmailing list archives also contain a lot of helpful information.
307*4882a593Smuzhiyun
308*4882a593SmuzhiyunResources
309*4882a593Smuzhiyun=========
310*4882a593Smuzhiyun
311*4882a593SmuzhiyunThe Linux USB Project:
312*4882a593Smuzhiyunhttp://www.linux-usb.org/
313*4882a593Smuzhiyun
314*4882a593SmuzhiyunLinux Hotplug Project:
315*4882a593Smuzhiyunhttp://linux-hotplug.sourceforge.net/
316*4882a593Smuzhiyun
317*4882a593Smuzhiyunlinux-usb Mailing List Archives:
318*4882a593Smuzhiyunhttps://lore.kernel.org/linux-usb/
319*4882a593Smuzhiyun
320*4882a593SmuzhiyunProgramming Guide for Linux USB Device Drivers:
321*4882a593Smuzhiyunhttps://lmu.web.psi.ch/docu/manuals/software_manuals/linux_sl/usb_linux_programming_guide.pdf
322*4882a593Smuzhiyun
323*4882a593SmuzhiyunUSB Home Page: https://www.usb.org
324