Device Drivers, Part 11: USB Drivers in Linux

Let's ride the USB

This article, which is part of the series on Linux device drivers, gets you started with writing your first USB driver in Linux.

Pugs’ pen drive was the device Shweta was playing with, when both of them sat down to explore the world of USB drivers in Linux. The fastest way to get the hang of it, and Pugs’ usual way, was to pick up a USB device, and write a driver for it, to experiment with. So they chose a pen drive (a.k.a. USB stick) that was at hand — a JetFlash from Transcend, with vendor ID 0x058f and product ID 0x6387.

USB device detection in Linux

Whether a driver for a USB device is there or not on a Linux system, a valid USB device will always be detected at the hardware and kernel spaces of a USB-enabled Linux system, since it is designed (and detected) as per the USB protocol specifications. Hardware-space detection is done by the USB host controller — typically a native bus device, like a PCI device on x86 systems. The corresponding host controller driver would pick and translate the low-level physical layer information into higher-level USB protocol-specific information. The USB protocol formatted information about the USB device is then populated into the generic USB core layer (the usbcore driver) in kernel-space, thus enabling the detection of a USB device in kernel-space, even without having its specific driver.

After this, it is up to various drivers, interfaces, and applications (which are dependent on the various Linux distributions), to have the user-space view of the detected devices. Figure 1 shows a top-to-bottom view of the USB subsystem in Linux.

USB subsystem in Linux

Figure 1: USB subsystem in Linux

A basic listing of all detected USB devices can be obtained using the lsusb command, as root. Figure 2 shows this, with and without the pen drive plugged in. A -v option to lsusbprovides detailed information.

Output of lsusb

Figure 2: Output of lsusb

In many Linux distributions like Mandriva, Fedora,… the usbfs driver is loaded as part of the default configuration. This enables the detected USB device details to be viewed in a more techno-friendly way through the /proc window, using cat /proc/bus/usb/devices. Figure 3 shows a typical snippet of the same, clipped around the pen drive-specific section. The listing basically contains one such section for each valid USB device detected on the system.

USB's proc window snippet

Figure 3: USB's proc window snippet

Decoding a USB device section

To further decode these sections, a valid USB device needs to be understood first. All valid USB devices contain one or more configurations. A configuration of a USB device is like a profile, where the default one is the commonly used one. As such, Linux supports only one configuration per device — the default one. For every configuration, the device may have one or more interfaces. An interface corresponds to a function provided by the device.

There would be as many interfaces as the number of functions provided by the device. So, say an MFD (multi-function device) USB printer can do printing, scanning and faxing, then it most likely would have at least three interfaces, one for each of the functions. So, unlike other device drivers, a USB device driver is typically associated/written per interface, rather than the device as a whole — meaning that one USB device may have multiple device drivers, and different device interfaces may have the same driver — though, of course, one interface can have a maximum of one driver only.

It is okay and fairly common to have a single USB device driver for all the interfaces of a USB device. The Driver=... entry in the proc window output (Figure 3) shows the interface to driver mapping — a (none) indicating no associated driver.

For every interface, there would be one or more end-points. An end-point is like a pipe for transferring information either into or from the interface of the device, depending on the functionality. Based on the type of information, the endpoints have four types: Control, Interrupt, Bulk and Isochronous.

As per the USB protocol specification, all valid USB devices have an implicit special control end-point zero, the only bi-directional end-point. Figure 4 shows the complete pictorial representation of a valid USB device, based on the above explanation.

USB device overview

Figure 4: USB device overview

Coming back to the USB device sections (Figure 3), the first letter on each line represents the various parts of the USB device specification just explained. For example, D for device, C for configuration, I for interface, E for endpoint, etc. Details about these and various others are available in the kernel source, in Documentation/usb/proc_usb_info.txt.

The USB pen drive driver registration

“Seems like there are so many things to know about the USB protocol, to be able to write the first USB driver itself — device configuration, interfaces, transfer pipes, their four types, and so many other symbols like T, B, S, … under a USB device specification,” sighed Shweta.

“Yes, but don’t you worry — all of that can be covered in detail later. Let’s do first things first — get the pen drive’s interface associated with our USB device driver (pen_register.ko),” consoled Pugs.

Like any other Linux device driver, here, too, the constructor and the destructor are required — basically the same driver template that has been used for all the drivers. However, the content would vary, as this is a hardware protocol layer driver, i.e., a horizontal driver, unlike a character driver, which was one of the vertical drivers discussed earlier. The difference would be that instead of registering with and unregistering from VFS, here this would be done with the corresponding protocol layer — the USB core in this case; instead of providing a user-space interface like a device file, it would get connected with the actual device in hardware-space.

The USB core APIs for the same are as follows (prototyped in <linux/usb.h>):

int usb_register(struct usb_driver *driver);
void usb_deregister(struct usb_driver *);

As part of the usb_driver structure, the fields to be provided are the driver’s name, ID table for auto-detecting the particular device, and the two callback functions to be invoked by the USB core during a hot plugging and a hot removal of the device, respectively.

Putting it all together, pen_register.c would look like what follows:

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/usb.h>

static int pen_probe(struct usb_interface *interface, const struct usb_device_id *id)
{
    printk(KERN_INFO "Pen drive (%04X:%04X) plugged\n", id->idVendor, id->idProduct);
    return 0;
}

static void pen_disconnect(struct usb_interface *interface)
{
    printk(KERN_INFO "Pen drive removed\n");
}

static struct usb_device_id pen_table[] =
{
    { USB_DEVICE(0x058F, 0x6387) },
    {} /* Terminating entry */
};
MODULE_DEVICE_TABLE (usb, pen_table);

static struct usb_driver pen_driver =
{
    .name = "pen_driver",
    .id_table = pen_table,
    .probe = pen_probe,
    .disconnect = pen_disconnect,
};

static int __init pen_init(void)
{
    return usb_register(&pen_driver);
}

static void __exit pen_exit(void)
{
    usb_deregister(&pen_driver);
}

module_init(pen_init);
module_exit(pen_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Anil Kumar Pugalia <email_at_sarika-pugs_dot_com>");
MODULE_DESCRIPTION("USB Pen Registration Driver");

Then, the usual steps for any Linux device driver may be repeated:

  • Build the driver (.ko file) by running make.
  • Load the driver using insmod.
  • List the loaded modules using lsmod.
  • Unload the driver using rmmod.

But surprisingly, the results wouldn’t be as expected. Check dmesg and the proc window to see the various logs and details. This is not because a USB driver is different from a character driver — but there’s a catch. Figure 3 shows that the pen drive has one interface (numbered 0), which is already associated with the usual usb-storage driver.

Now, in order to get our driver associated with that interface, we need to unload the usb-storage driver (i.e., rmmod usb-storage) and replug the pen drive. Once that’s done, the results would be as expected. Figure 5 shows a glimpse of the possible logs and a procwindow snippet. Repeat hot-plugging in and hot-plugging out the pen drive to observe the probe and disconnect calls in action.

Pen driver in action

Figure 5: Pen driver in action

Summing up

“Finally! Something in action!” a relieved Shweta said. “But it seems like there are so many things (like the device ID table, probe, disconnect, etc.), yet to be understood to get a complete USB device driver in place.”

“Yes, you are right. Let’s take them up, one by one, with breaks,” replied Pugs, taking a break himself.

  • Baban Gaigole

    Learn how to create drivers for Micromax mmx 352g for ubuntu 11.04

  • Baban Gaigole
  • Pingback: driver for a device in linux

  • Karan86 Mehra

    I am trying to implement the above module but when i do rmmod usb-storage it shows me following error:
    ERROR: Module usb_storage does not exist in /proc/modules
    could anyone help me out

    • http://twitter.com/anil_pugalia Anil Pugalia

      usb_storage might be built into the kernel. You might have to recompile the kernel with usb_storage built as a module.

  • http://sosaysharis.wordpress.com/ Haris Ibrahim K. V.

    This is weird. I do not have the ‘usb’ folder within my /proc/bus ! I have folders ‘input’ and ‘pci’ there. Why is there this mismatch? My kernel is 2.6.32-40-generic

    • free4freedom

      I tried using older kernel( I used Ubuntu 8.04, with 2.6.24.x ) , but surprisingly it showed me /proc/bus/usb/ , thats all , no device file !!

      Anyway, I found another way out, use command :
      udevadm info –attribute-walk –name
      where : could be /dev/sdb1 etc. It gives a lengthy o/p , try using a pipe & then grep to get what ever u want.

    • akash

      i am facing same problm … I do not have the ‘usb’ folder within my /proc/bus ..

      do i need to custumize ma kernel or here is any other way also ..bcos i hv not done this before …m kind of afraid ..

      • http://twitter.com/anil_pugalia Anil Pugalia

        Follow the instructions as mentioned above. Ubuntu doesn’t have it by default. Or, use lsusb -v

        • akash

          root@ubuntu:/home/ayush# sudo apt-get install linux-source-3.2.0 kernel-package libncurses5-dev fakeroot
          Reading package lists… Error!
          E: Encountered a section with no Package: header
          E: Problem with MergeList /var/lib/apt/lists/us.archive.ubuntu.com_ubuntu_dists_precise_main_binary-i386_Packages
          E: The package lists or status file could not be parsed or opened.

          I was trying 1st command mentioned in above link …. can u tell wht is the problm in above cmmnd

          • http://twitter.com/anil_pugalia Anil Pugalia

            Not really sure. But looks like something to do with your package management on ubuntu. Check out & resolve by googling for the error.

  • chipGIR

    @twitter-41866709:disqus ,
    Many thanks for sharing the post and everything you explained works like charm, but I might be doing something stupid or probably not aware if some other things need to be tweaked.

    device driver: insmod pen_register.ko triggers probe and I confirmed by dmesg but I’m not able to see the pen drive neither in nautilus nor in file system disk usage( df -h).

    Secondly, issuing #cat /dev/pen1 results in -110 results is connection timeout.

    here is the strace of read

    #strace -e trace=read cat /dev/pen1
    read(3, “177ELF111331000m1004″…, 512) = 512
    read(3, “# Locale name alias data base.n#”…, 4096) = 2570
    read(3, “”, 4096) = 0
    read(3, 0x8d4f000, 32768) = -1 ETIMEDOUT (Connection timed out)
    cat: /dev/pen1: Connection timed out
    #

    Please let know further steps to perform a read/write on the usb drive

    • http://www.facebook.com/anil.pugalia Anil Pugalia

      I believe if you have followed the article – you are anyway not expected to be able to read & write yet. I am doubtful as what is this /dev/pen1 referring to – it might be the one exposed by the usb-storage driver. Read the next articles in series to get the next steps

  • bill

    thank you for the article !
    I think that “lsusb -v” has a sufficient output for those who have usbfs disabled. isn’t it ?

    • anil_pugalia

      Yes, at least what ever is required for the first level.

      • akash

        my kernel version is new ..so i did lsusb -v ….bt by using this command how can i check which driver is associated with the my pendrive … i want to see that my pendrive is connected to driver = usb-storage ..

        result(partial) of lsusb -v :
        Bus 001 Device 004: ID 0951:1643 Kingston Technology DataTraveler G3 4GB
        Device Descriptor:
        bLength 18
        bDescriptorType 1
        bcdUSB 2.00
        bDeviceClass 0 (Defined at Interface level)
        bDeviceSubClass 0
        bDeviceProtocol 0
        bMaxPacketSize0 64
        idVendor 0×0951 Kingston Technology
        idProduct 0×1643 DataTraveler G3 4GB
        bcdDevice 1.00
        iManufacturer 1 Kingston
        iProduct 2 DataTraveler G3
        iSerial 3 001CC0EC32BCBB611712008E
        bNumConfigurations 1
        Configuration Descriptor:
        bLength 9
        bDescriptorType 2
        wTotalLength 32
        bNumInterfaces 1
        bConfigurationValue 1
        iConfiguration 0
        bmAttributes 0×80
        (Bus Powered)
        MaxPower 200mA
        Interface Descriptor:
        bLength 9
        bDescriptorType 4
        bInterfaceNumber 0
        bAlternateSetting 0
        bNumEndpoints 2
        bInterfaceClass 8 Mass Storage
        bInterfaceSubClass 6 SCSI
        bInterfaceProtocol 80 Bulk-Only
        iInterface 0
        Endpoint Descriptor:
        bLength 7
        bDescriptorType 5
        bEndpointAddress 0×81 EP 1 IN
        bmAttributes 2
        Transfer Type Bulk
        Synch Type None
        Usage Type Data
        wMaxPacketSize 0×0200 1x 512 bytes
        bInterval 0
        Endpoint Descriptor:
        bLength 7
        bDescriptorType 5
        bEndpointAddress 0×02 EP 2 OUT
        bmAttributes 2
        Transfer Type Bulk
        Synch Type None
        Usage Type Data
        wMaxPacketSize 0×0200 1x 512 bytes
        bInterval 0
        Device Qualifier (for other device speed):
        bLength 10
        bDescriptorType 6
        bcdUSB 2.00
        bDeviceClass 0 (Defined at Interface level)
        bDeviceSubClass 0
        bDeviceProtocol 0
        bMaxPacketSize0 64
        bNumConfigurations 1
        Device Status: 0×0000
        (Bus Powered)

        pls reply :)

        • http://twitter.com/anil_pugalia Anil Pugalia

          Install & try the usbview app.

          • akash

            hi .. i hav downloaded this usbview app ..bt how to install it on ubuntu ..pls help.. i knw i m asking very silly questions bt i m a begginer pls help

          • akash

            i was trying to install using ubuntu software centre bt some erreor : System program problem detected is coming and ubuntu software centre get stopped unexpectedly
            also Could not determine the package or source package name. this error is coming pls help

          • http://twitter.com/anil_pugalia Anil Pugalia

            I think you do not need to download or so. As you are on ubuntu, you may just type the following command on the shell: sudo apt-get install usbview

          • akash

            i got this error while using : sudo apt-get install usbview

            Reading package lists… Error!
            E: Encountered a section with no Package: header
            E: Problem with MergeList /var/lib/apt/lists/us.archive.ubuntu.com_ubuntu_dists_precise_main_binary-i386_Packages
            E: The package lists or status file could not be parsed or open: do apt-get install usbview

          • http://twitter.com/anil_pugalia Anil Pugalia

            Something wrong with the network or the installation. Please check & fix.

  • shivang

    it gives me following error when it insert module by writing insmod command

    insmod: error inserting ‘usbstick.ko’: -1 Unknown symbol in module

    • anil_pugalia

      Check out the dmesg output for which symbol in your driver is not yet resolved. And then, fix that. Possibly, you might have got warnings while compilation and have ignored them.

      • akash

        i also got the same error … bt in my case it was bcos i hav not included

        MODULE_LICENSE(“GPL”); this line …. can u explain me why it was giving this error insmod: error inserting usb.ko :-1 Unknown symbol in module
        for not including license macro

        • http://twitter.com/anil_pugalia Anil Pugalia

          That may be just a coincidence. You may have fixed it somewhere else.

  • jaya

    thanks for this awesome post .. yesterday i tried it and it worked fine … but i have a small doubt if u can help :

    1) when i plugs in my pen drive it is getting detected by my driver . but when i am using another pen drive usb-storage module(which i removed by rmmod usb-storage) get inserted by itself . how it is happening ??

    2) and is there any way so that all the pendrive get detected by my module only not by usb-storage ..

    • http://twitter.com/anil_pugalia Anil Pugalia

      1) module autoload rules under /lib/modules//modules.usbmap, typically get the modules loaded automatically.
      2) Change the above file.

All published articles are released under Creative Commons Attribution-NonCommercial 3.0 Unported License, unless otherwise noted.
LINUX For You is powered by WordPress, which gladly sits on top of a CentOS-based LEMP stack.

Creative Commons License.