USB device driver 4: USB-skeleton routine

Source: Internet
Author: User

With the basic knowledge of the device driver and USB, you can easily understand the USB-skeleton routine and easily write your own simple USB driver.

The following is a simple analysis of the USB-skeleton routine:

/*
* USB skeleton driver-2.0
*
* Copyright (c) 2001-2004 Greg kroah-Harman (greg@kroah.com)
*
* This program is free software; you can redistribute it and/or
* Modify it under the terms of the GNU General Public License
* Published by the Free Software Foundation, version 2.
*
* This driver is based on the 2.6.3 version of drivers/USB/usb-skeleton.c
* But has been rewritten to be easy to read and use, as no locks are now
* Needed anymore.
*
*/

# Include <Linux/kernel. h>
# Include <Linux/errno. h>
# Include <Linux/init. h>
# Include <Linux/slab. h>
# Include <Linux/module. h>
# Include <Linux/kref. h>
# Include <ASM/uaccess. h>
# Include <Linux/USB. h>

/* Define these values to match your devices */
# Define usb_skel_vendor_id 0xfff0
# Define usb_skel_product_id 0xfff0

/* Table of devices that work with this driver */
Static struct usb_device_id skel_table [] = {
{Usb_device (usb_skel_vendor_id, usb_skel_product_id )},
{}/* Terminating entry */
};
Module_device_table (USB, skel_table );

/* Get a minor range for your devices from the USB maintainer */
# Define usb_skel_minor_base 192

/* Our private defines. If this grows any larger, use your own. h file */
# Define max_transfer (page_size-512)
# Define writes_in_flight 8

/* Structure to hold all of our device specific stuff */
Struct usb_skel {
Struct usb_device * udev;/* the USB device for this device */
Struct usb_interface * interface;/* the interface for this device */
Struct semaphore limit_sem;/* limiting the number of writes in progress */
Unsigned char * bulk_in_buffer;/* the buffer to receive data */
Size_t bulk_in_size;/* the size of the Receive Buffer */
_ U8 bulk_in_endpointaddr;/* the address of the bulk in endpoint */
_ U8 bulk_out_endpointaddr;/* the address of the bulk out endpoint */
Struct kref;
};
# Define to_skel_dev (d) container_of (D, struct usb_skel, kref)

Static struct usb_driver skel_driver;

Static void skel_delete (struct kref * kref)
{
/*
1. Get the device
2. Reduce the number of device references
3. Release allocated data space
4. Release the allocated drive space
*/
Struct usb_skel * Dev = to_skel_dev (kref );

Usb_put_dev (Dev-> udev );
Kfree (Dev-> bulk_in_buffer );
Kfree (Dev );
}

Static int skel_open (struct inode * inode, struct file * file)
{
/*
1. Obtain the device interface through the driver struct and the device ID.
2. Obtain the device struct through the interface
3. Increase the number of device references
4. Associate the device driver with the file handle for later use
5.
6.
*/
Struct usb_skel * dev;
Struct usb_interface * interface;
Int subminor;
Int retval = 0;

Subminor = iminor (inode );

Interface = usb_find_interface (& skel_driver, subminor );
If (! Interface ){
Err ("% s-error, can't find device for minor % d ",
_ FUNCTION __, subminor );
Retval =-enodev;
Goto exit;
}

Dev = usb_get_intfdata (Interface );
If (! Dev ){
Retval =-enodev;
Goto exit;
}

/* Increment our usage count for the device */
Kref_get (& Dev-> kref );

/* Save Our object in the file's private structure */
File-> private_data = dev;

Exit:
Return retval;
}

Static int skel_release (struct inode * inode, struct file * file)
{
/*
Reduces the number of device references.
*/
Struct usb_skel * dev;

Dev = (struct usb_skel *) file-> private_data;
If (Dev = NULL)
Return-enodev;

/* Decrement the count on our device */
Kref_put (& Dev-> kref, skel_delete );
Return 0;
}

Static ssize_t skel_read (struct file * file, char * buffer, size_t count, loff_t * PPOs)
{
/*
The function of reading data functions is mainly implemented as follows:
1. Get Device Driver data through file handle
2. Send the command to get data to the device through the operation set of the device driver data
3. Get the data returned from the device
4. Copy data from the kernel space to the user space
5.
*/
Struct usb_skel * dev;
Int retval = 0;
Int bytes_read;

Dev = (struct usb_skel *) file-> private_data;
 
/* Do a blocking bulk read to get data from the device */
Retval = usb_bulk_msg (Dev-> udev,
Usb_rcvbulkpipe (Dev-> udev, Dev-> bulk_in_endpointaddr ),
Dev-> bulk_in_buffer,
Min (Dev-> bulk_in_size, count ),
& Bytes_read, 10000 );

/* If the read was successful, copy the data to userspace */
If (! Retval ){
If (copy_to_user (buffer, Dev-> bulk_in_buffer, bytes_read ))
Retval =-efault;
Else
Retval = bytes_read;
}

Return retval;
}

Static void skel_write_bulk_callback (struct urb * urb, struct pt_regs * regs)
{
/*
The calling function submitted to urb for processing by the master controller mainly reflects data processing.
*/
Struct usb_skel * dev;

Dev = (struct usb_skel *) urb-> context;

/* Sync/async unlink faults aren't errors */
If (urb-> Status &&
! (Urb-> Status =-enoent |
Urb-> Status =-econnreset |
Urb-> Status =-eshudown )){
Dbg ("% s-nonzero write bulk status terminated ed: % d ",
_ FUNCTION __, urb-> status );
}

/* Free up our allocated buffer */
Usb_buffer_free (urb-> Dev, urb-> transfer_buffer_length,
Urb-> transfer_buffer, urb-> transfer_dma );
Up (& Dev-> limit_sem );
}

Tatic ssize_t skel_write (struct file * file, const char * user_buffer, size_t count, loff_t * PPOs)
{
/*
1. To write data to a device file, first use the file handle to obtain the device file pointed to by the handle, that is, the device file we registered in the probe function.
2. You can obtain the file operation set of the device through the file handle. This operation set is generally placed at the position pointed to by the private_data pointer.
3. Allocate urb Space
4. kernel space allocated to user data space for receiving user data
5. Fill in the relationship between urb and sent data
6. Submit urb data
7. Check whether the message is sent normally based on the returned information.
*/
Struct usb_skel * dev;
Int retval = 0;
Struct urb * urb = NULL;
Char * Buf = NULL;
Size_t writesize = min (count, (size_t) max_transfer );

Dev = (struct usb_skel *) file-> private_data;

/* Verify that we actually have some data to write */
If (COUNT = 0)
Goto exit;

/* Limit the number of URBS in flight to stop a user from using up all Ram */
If (down_interruptible (& Dev-> limit_sem )){

Retval =-erestartsys;
Goto exit;
}

/* Create a urb, and a buffer for it, and copy the data to the urb */
Urb = usb_alloc_urb (0, gfp_kernel );
If (! Urb ){
Retval =-enomem;
Goto error;
}

Buf = usb_buffer_alloc (Dev-> udev, writesize, gfp_kernel, & urb-> transfer_dma );
If (! Buf ){
Retval =-enomem;
Goto error;
}

If (copy_from_user (BUF, user_buffer, writesize )){
Retval =-efault;
Goto error;
}

/* Initialize the urb properly */
Usb_fill_bulk_urb (urb, Dev-> udev,
Usb_sndbulkpipe (Dev-> udev, Dev-> bulk_out_endpointaddr ),
Buf, writesize, skel_write_bulk_callback, Dev );
Urb-> transfer_flags | = urb_no_transfer_dma_map;

/* Send the data out the bulk port */
Retval = usb_submit_urb (urb, gfp_kernel );

If (retval ){
Err ("% s-Failed submitting write urb, error % d", _ FUNCTION __, retval );
Goto error;
}

/* Release our reference to this urb, the USB core will eventually free it entirely */
Usb_free_urb (urb );

Exit:
Return writesize;

Error:
Usb_buffer_free (Dev-> udev, writesize, Buf, urb-> transfer_dma );
Usb_free_urb (urb );
Up (& Dev-> limit_sem );
Return retval;
}

Static struct file_operations skel_fops = {
. Owner = this_module,
. Read = skel_read,
. Write = skel_write,
. Open = skel_open,
. Release = skel_release,
};

/*
* USB class driver info in order to get a minor number from the USB core,
* And to have the device registered with the driver Core
*/
Static struct usb_class_driver skel_class = {
. Name = "skel % d ",
. Fops = & skel_fops,
. Minor_base = usb_skel_minor_base,
};

Static int skel_probe (struct usb_interface * interface, const struct usb_device_id * ID)
{
/*
The probe function mainly performs the following tasks:
1. Allocate a device driver space and reference the device for counting
2. the USB device and interface members in the device space are assigned values by real members to associate these members with the new device space.
3. Determine the endpoint features included in the interface to see if they are consistent with the hardware. If they are inconsistent, an error occurs, that is, the returned value is not equal to 0.
4. Register a file device. This file device is provided to applications for device operations, including opening, disabling, reading, and writing.
5. If the call succeeds, 0 is returned.
*/
Struct usb_skel * Dev = NULL;
Struct usb_host_interface * iface_desc;
Struct usb_endpoint_descriptor * endpoint;
Size_t buffer_size;
Int I;
Int retval =-enomem;

/* Allocate memory for our device state and initialize it */
Dev = kzarloc (sizeof (* Dev), gfp_kernel );
If (Dev = NULL ){
Err ("out of memory ");
Goto error;
}
Kref_init (& Dev-> kref );
Sema_init (& Dev-> limit_sem, writes_in_flight );

Dev-> udev = usb_get_dev (interface_to_usbdev (Interface);/* obtain the device corresponding to this interface through the device interface and increase the number of device references */
Dev-> interface = interface;

/* Set up the endpoint information */
/* Use only the first bulk-in and bulk-out endpoints */
Iface_desc = interface-> cur_altsetting;
For (I = 0; I <iface_desc-> DESC. bnumendpoints; ++ I ){
Endpoint = & iface_desc-> endpoint [I]. DESC;

If (! Dev-> bulk_in_endpointaddr &&
(Endpoint-> bendpointaddress & usb_endpoint_dir_mask)
= Usb_dir_in )&&
(Endpoint-> bmattributes & usb_endpoint_xfertype_mask)
= Usb_endpoint_xfer_bulk )){
/* We found a bulk in endpoint */
Buffer_size = le16_to_cpu (endpoint-> wmaxpacketsize );
Dev-> bulk_in_size = buffer_size;
Dev-> bulk_in_endpointaddr = endpoint-> bendpointaddress;
Dev-> bulk_in_buffer = kmalloc (buffer_size, gfp_kernel );
If (! Dev-> bulk_in_buffer ){
Err ("cocould not allocate bulk_in_buffer ");
Goto error;
}
}

If (! Dev-> bulk_out_endpointaddr &&
(Endpoint-> bendpointaddress & usb_endpoint_dir_mask)
= Usb_dir_out )&&
(Endpoint-> bmattributes & usb_endpoint_xfertype_mask)
= Usb_endpoint_xfer_bulk )){
/* We found a bulk out endpoint */
Dev-> bulk_out_endpointaddr = endpoint-> bendpointaddress;
}
}
If (! (Dev-> bulk_in_endpointaddr & Dev-> bulk_out_endpointaddr )){
Err ("cocould not find both bulk-in and bulk-out endpoints ");
Goto error;
}

/* Save Our Data Pointer in this interface device */
Usb_set_intfdata (interface, Dev );

/* We can register the device now, as it is ready */
Retval = usb_register_dev (interface, & skel_class );
If (retval ){
/* Something prevented us from registering this driver */
Err ("not able to get a minor for this device .");
Usb_set_intfdata (interface, null );
Goto error;
}

/* Let the user know what node this device is now attached */
Info ("USB skeleton device now attached to usbskel-% d", interface-> minor );
Return 0;

Error:
If (Dev)
Kref_put (& Dev-> kref, skel_delete );
Return retval;
}

Static void skel_disconnect (struct usb_interface * interface)
{
Struct usb_skel * dev;
Int minor = interface-> minor;

/* Prevent skel_open () from racing skel_disconnect ()*/
Lock_kernel ();

Dev = usb_get_intfdata (Interface );
Usb_set_intfdata (interface, null );

/* Give back our minor */
Usb_deregister_dev (interface, & skel_class );

Unlock_kernel ();

/* Decrement our usage count */
Kref_put (& Dev-> kref, skel_delete );

Info ("USB skeleton # % d now disconnected", minor );
}

Static struct usb_driver skel_driver = {
. Name = "skeleton ",
. Probe = skel_probe,
. Disconnect = skel_disconnect,
. Id_table = skel_table,
};

Static int _ init usb_skel_init (void)
{
Int result;

/* Register this driver with the USB subsystem */
Result = usb_register (& skel_driver );

If (result)
Err ("usb_register failed. Error Number % d", result );

Return result;
}

Static void _ exit usb_skel_exit (void)
{
/* Deregister this driver with the USB subsystem */
Usb_deregister (& skel_driver );
}

Module_init (usb_skel_init );
Module_exit (usb_skel_exit );

Module_license ("GPL ");

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.