"./drivers/usb/usb-skeleton.c" It's the kernel that provides usb Mass storage for device driven developers usb Device template program , The program is not long , It's very versatile , Very classic , An in-depth understanding of this document can help us better understand usb Subsystem and usb Device drive frame , Write better usb Mass storage device drivers .

Before matching

Since it's a usb Device driven templates , Then it's necessary to construct a usb_driver Object and register it in the kernel ,

650 static struct usb_driver skel_driver = {
651         .name =         "skeleton",
652         .probe =        skel_probe,
653         .disconnect =   skel_disconnect,
654         .suspend =      skel_suspend,
655         .resume =       skel_resume,
656         .pre_reset =    skel_pre_reset,
657         .post_reset =   skel_post_reset,
658         .id_table =     skel_table,
659         .supports_autosuspend = 1,
660 };
661 
662 module_usb_driver(skel_driver);

About the domain of this object , As explained in the last article , here , Our main concern is skel_table, It determines which device the driver matches , As can be seen from the following definition , This drive is based on device Matching ,

 30 static const struct usb_device_id skel_table[] = {
 31         { USB_DEVICE(USB_SKEL_VENDOR_ID, USB_SKEL_PRODUCT_ID) },
 32         { }                                     /* Terminating entry */
 33 };
 34 MODULE_DEVICE_TABLE(usb, skel_table);

After the match

Resource class

Next , Take a look at the definition of resource class in this driver , It's the link of the whole driver , It manages the resources shared by each function and interface of the whole driver , I have to say that this annotation is really rare in the kernel , skeleton Mainly for mass storage devices , So the resource object encapsulates a lot of buffer information VS Just one interrupt device urb The data transmission problem can be solved

 49 struct usb_skel {
 50         struct usb_device       *udev;                  /* the usb device for this device */
 51         struct usb_interface    *interface;             /* the interface for this device */
 52         struct semaphore        limit_sem;              /* limiting the number of writes in progress
 53         struct usb_anchor       submitted;              /* in case we need to retract our submission
 54         struct urb              *bulk_in_urb;           /* the urb to read data with */
 55         unsigned char           *bulk_in_buffer;        /* the buffer to receive data */
 56         size_t                  bulk_in_size;           /* the size of the receive buffer */
 57         size_t                  bulk_in_filled;         /* number of bytes in the buffer */
 58         size_t                  bulk_in_copied;         /* already copied to user space */
 59         __u8                    bulk_in_endpointAddr;   /* the address of the bulk in endpoint */
 60         __u8                    bulk_out_endpointAddr;  /* the address of the bulk out endpoint */
 61         int                     errors;                 /* the last request tanked */
 62         bool                    ongoing_read;           /* a read is going on */
 63         spinlock_t              err_lock;               /* lock for errors */
 64         struct kref             kref;
 65         struct mutex            io_mutex;               /* synchronize I/O with disconnect */
 66         wait_queue_head_t       bulk_in_wait;           /* to wait for an ongoing read */
 67 };

struct usb_skel
--50--> Driving operation of usb_device object
--51--> Driving operation of usb_interface object , Both of these are device information , VS i2c-s3c2410.c By putting device information in probe To save to the driver resource object , Here's the same idea . struct usb_interface->dev Domain to usb_skel And other interface functions , amount to struct device Domain to s3c24xx_i2c And other interface functions , They all flow in various interface functions
--54--> The use of urb object
--55--> For receiving data buf The pointer
--56--> Identify the domain to receive the data length
--57--> A field that identifies how much valid data there is in the current buffer
--58--> A field that identifies how much data has been copied from the current buffer ,skeleton It doesn't empty the buffer , Instead, it uses various length representations to determine how much has been taken up , Beyond the length , It doesn't matter whether it's cleared or not . The relationship between them is shown in the figure below
--59-->bulk The input endpoint of the device
--60-->bulk The output endpoint of the device
--62--> Device readable flag bits ,0 Means to read ,1 Means unreadable
--64-->kref For kernel reference counting

usb_skeleton Also refer to what's already in the kernel to_platform_device And so on encapsulate a to_skel_dev, This writing method is worth learning

 68 #define to_skel_dev(d) container_of(d, struct usb_skel, kref)

probe

After matching successfully , According to the routine, please probe Come on.

490 static int skel_probe(struct usb_interface *interface,
491                       const struct usb_device_id *id)
492 {
493         struct usb_skel *dev;
494         struct usb_host_interface *iface_desc;
495         struct usb_endpoint_descriptor *endpoint;
496         size_t buffer_size;
497         int i;
498         int retval = -ENOMEM;
499 
500         /* allocate memory for our device state and initialize it */
501         dev = kzalloc(sizeof(*dev), GFP_KERNEL);
506         kref_init(&dev->kref);
507         sema_init(&dev->limit_sem, WRITES_IN_FLIGHT);
508         mutex_init(&dev->io_mutex);
509         spin_lock_init(&dev->err_lock);
510         init_usb_anchor(&dev->submitted);
511         init_waitqueue_head(&dev->bulk_in_wait);
512 
513         dev->udev = usb_get_dev(interface_to_usbdev(interface));
514         dev->interface = interface;
515 
516         /* set up the endpoint information */
517         /* use only the first bulk-in and bulk-out endpoints */
518         iface_desc = interface->cur_altsetting;
519         for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) {
520                 endpoint = &iface_desc->endpoint[i].desc;
521 
522                 if (!dev->bulk_in_endpointAddr &&
523                     usb_endpoint_is_bulk_in(endpoint)) {
524                         /* we found a bulk in endpoint */
525                         buffer_size = usb_endpoint_maxp(endpoint);
526                         dev->bulk_in_size = buffer_size;
527                         dev->bulk_in_endpointAddr = endpoint->bEndpointAddress;
528                         dev->bulk_in_buffer = kmalloc(buffer_size, GFP_KERNEL);
534                         dev->bulk_in_urb = usb_alloc_urb(0, GFP_KERNEL);
540                 }
542                 if (!dev->bulk_out_endpointAddr &&
543                     usb_endpoint_is_bulk_out(endpoint)) {
544                         /* we found a bulk out endpoint */
545                         dev->bulk_out_endpointAddr = endpoint->bEndpointAddress;
546                 }
547         }
553 
554         /* save our data pointer in this interface device */
555         usb_set_intfdata(interface, dev);
556 
557         /* we can register the device now, as it is ready */
558         retval = usb_register_dev(interface, &skel_class);
566 
567         /* let the user know what node this device is now attached to */
568         dev_info(&interface->dev,
569                  "USB Skeleton device now attached to USBSkel-%d",
570                  interface->minor);
571         return 0;
578 }
579

skel_probe
--501--> Apply for space for resource objects , Pay attention to the writing here : dev = kzalloc(sizeof(*dev), GFP_KERNEL);
--506--> initialization usb_skel->kref
--507--> initialization usb_skel->limit_sem
--508--> initialization usb_skel->io_mutex);
--509--> initialization usb_skel->err_lock);
--510--> initialization usb_skel->submitted);
--511--> initialization usb_skel->bulk_in_wait
--513--> initialization usb_skel->udev, Will match to usb_device The address is stored
--514-519--> initialization usb_skel Objects other domains .
--555--> Hide our resource objects in interface->dev->p->driver_data in
--558--> Sign up for a usb_device Object to kernel 、 Apply for a secondary device number and create a device file , ==>intf->usb_dev = device_create(usb_class->class, &intf->dev,MKDEV(USB_MAJOR, minor), class_driver,"%s", temp);

Through the above analysis , We found a skeleton and usbmouse Something different :skeleton constructed usb_class_driver Object and use usb_register_dev Sign up for a usb equipment , and usbmouse As input Subsystem , Only required input_register(input_dev) that will do , no need usb Device registration issues , The reason for this difference is skeleton Is aimed at bulk urb The equipment , and usbmouse Is aimed at interrupt urb The equipment . about bulk equipment , We'll read and write to the device , Not just read operations , So in bulk urb The device driver should implement the corresponding operation method set, bind to the device file and register with the kernel , This job is done by usb_register_dev To complete . To use this function , We need to construct a usb_class_driver object , The most important of these is what this section will discuss skel_fops 了 . This domain is also struct file_operations Type of , The implementation of all read-write methods should be registered in this domain .
Now that it's mentioned fops, We are mainly concerned with the implementation of three methods :open, read and write, in consideration of read and write The operation logic is similar to , So this article only discusses open and read

open

 83 static int skel_open(struct inode *inode, struct file *file)
 84 {
 85         struct usb_skel *dev;
 86         struct usb_interface *interface;
 87         int subminor;
 88         int retval = 0;
 89 
 90         subminor = iminor(inode);
 91 
 92         interface = usb_find_interface(&skel_driver, subminor);
100         dev = usb_get_intfdata(interface);
106         retval = usb_autopm_get_interface(interface);
110         /* increment our usage count for the device */
111         kref_get(&dev->kref);
112 
113         /* save our object in the file's private structure */
114         file->private_data = dev;
115 
117         return retval;
118 }

skel_open()
--90--> from inode Get secondary device number from
--92--> according to skel_driver Object and secondary device number usb_interface object , So here we have the device
--100--> from interface->dev->p->driver_data Get the address of the resource object in , This address is in probe--555-- It's hidden here
--110--> Reference count plus one
--114--> The key , Hide the address of the previously obtained resource object in file->private_data in , So in all cdev Resource objects can be used between interfaces , And hide the resource object address in interface In order to be in usb_driver The idea of flow between interface functions is the same .

read

Turn on the device , Then you can read and write ,skeleton The key function calls for read operations in are as follows , We analyze it in turn according to the call tree

skel_read()
skel_do_read_io(dev, count)
usb_fill_bulk_urb(...);
usb_submit_urb(dev->bulk_in_urb, GFP_KERNEL);

First of all skel_read(), This function is the callback function when the application layer reads the device , It's trying to achieve such a function : If there is data in the kernel buffer, copy the appropriate data to the application layer , Call if not skel_do_read_io To request data from the device

226 static ssize_t skel_read(struct file *file, char *buffer, size_t count,
227                          loff_t *ppos)
228 {
229         struct usb_skel *dev;
230         int rv;
231         bool ongoing_io;
232 
233         dev = file->private_data;
255         if (ongoing_io) {
256                 /* nonblocking IO shall not wait */
257                 if (file->f_flags & O_NONBLOCK) {
258                         rv = -EAGAIN;
259                         goto exit;
260                 }
265                 rv = wait_event_interruptible(dev->bulk_in_wait, (!dev->ongoing_read));
266                 if (rv < 0)
267                         goto exit;
268         }
269 
270         /* errors must be reported */
271         rv = dev->errors;
272         if (rv < 0) {
273                 /* any error is reported once */
274                 dev->errors = 0;
275                 /* to preserve notifications about reset */
276                 rv = (rv == -EPIPE) ? rv : -EIO;
277                 /* report it */
278                 goto exit;
279         }
286         if (dev->bulk_in_filled) {
287                 /* we had read data */
288                 size_t available = dev->bulk_in_filled - dev->bulk_in_copied;
289                 size_t chunk = min(available, count);
290 
291                 if (!available) {
296                         rv = skel_do_read_io(dev, count);
297                         if (rv < 0)
298                                 goto exit;
299                         else
300                                 goto retry;
301                 }
307                 if (copy_to_user(buffer,
308                                  dev->bulk_in_buffer + dev->bulk_in_copied,
309                                  chunk))
310                         rv = -EFAULT;
311                 else
312                         rv = chunk;
313 
314                 dev->bulk_in_copied += chunk;
320                 if (available < count)
321                         skel_do_read_io(dev, count - chunk);
322         } else {
323                 /* no data in the buffer */
324                 rv = skel_do_read_io(dev, count);
325                 if (rv < 0)
326                         goto exit;
327                 else
328                         goto retry;
329         }
330 exit:
331         mutex_unlock(&dev->io_mutex);
332         return rv;
333 }

skel_read()
--233--> It's all routine. , First hide in file_private_data Take out the resource objects in
--255-268--> Readable flag bits in resource objects , When it's unreadable , Judge IO Whether blocking is allowed , If not, go straight back , Allow blocking to use the waiting queue header in the resource object , Add the process to the waiting queue , It uses interruptible Version of wait, If the process in sleep is interrupted and awakened , that rv==-1, Function directly returns .
--286--> There's only one case in this line : The device is readable ! If the buffer is full, execute the first statement block , Otherwise, execute the following statement block
--288--> When the buffer is full , Get the size of the data that can be copied .
--289--> The smaller of the size that can be copied and the size that is expected to be copied is given to chunk
--291--> The data that can be copied is 0, and usb_skel->bulk_in_filled It's set to get in here , So there's only one situation : The data in the buffer has been copied
--292--> Now that the data has been copied , call skel_do_read_io Initiate request
--300--> Requested data , The device also gave feedback , But there's no data , retry
307--> From the kernel buffer usb_skel->bulk_in_buffer + usb_skel->bulk_in_copied Start ( Is the first address of the remaining uncopy data ) Copy chunk byte To the application layer
--314--> to update usb_skel->bulk_in_copied Value
--320--> If you can copy the size of the data < The size of the expected copy , So obviously just now chunk=availible, All data has been copied to the application layer , But it can not meet the needs of the application layer , call skel_do_read_io To continue to get data from the device , Of course , The size of the claim is the unsatisfied part , namely count-chunk
--324-->usb_skel->bulk_in_filled Not set , Indicates that there is no data in the kernel buffer , call skel_do_read_io Ask for data , Of course , The size of the claim is all the data , namely count

I just said , If the buffer can not meet the requirements of the application layer , You call the following function to bulk usb Device request data , After getting the data, put the data into the buffer and put the corresponding flag position 1/ Set up 0

189 static int skel_do_read_io(struct usb_skel *dev, size_t count)
190 {
191         int rv;
193         /* prepare a read */
194         usb_fill_bulk_urb(dev->bulk_in_urb,dev->udev,usb_rcvbulkpipe(dev->udev,dev->bulk_in_endpointAddr),dev->bulk_in_buffer, min(dev->bulk_in_size, count),skel_read_bulk_callback,dev);
204         dev->ongoing_read = 1;
206 
207         /* submit bulk in urb, which means no data to deliver */
208         dev->bulk_in_filled = 0;
209         dev->bulk_in_copied = 0;
210 
211         /* do it */
212         rv = usb_submit_urb(dev->bulk_in_urb, GFP_KERNEL);
223         return rv;
224 }

skel_do_read_io()
--194--> towards usb The core submits a urb, Put the resource object dev Hidden in the urb->context With urb Pass in the function callback , and usb_fill_int_urb Different , usb_fill_bulk_urb When registering, the first address of the buffer and the size and size of the request data need to be changed urb Bind together and submit together , Only in this way can we know to bulk The size of the data requested by the device , bulk Only when the device has data returned can it know where to put it .
--204--> take usb_skel->ongoing_read Set up 1, Indicates that there is no data to read
--208--> take usb_skel->bulk_in_filled Set up 0, Indicates that the kernel buffer has no data to read
--209--> take usb_skel->bulk_in_copied Set up 0, No data has been copied
--212--> After getting ready , command usb The core sends urb

After the request is sent , usb The bus will wait for feedback from the device , When the device has feedback, it will call back urb Registration function for , Let's see what this callback function does

163 static void skel_read_bulk_callback(struct urb *urb)
164 {
165         struct usb_skel *dev;
166 
167         dev = urb->context;
168 
169         spin_lock(&dev->err_lock);
170         /* sync/async unlink faults aren't errors */
181                 dev->bulk_in_filled = urb->actual_length;
183         dev->ongoing_read = 0;
184         spin_unlock(&dev->err_lock);
185 
186         wake_up_interruptible(&dev->bulk_in_wait);
187 }

skel_read_bulk_callback
--167--> tricks , Take out the resource object first
--181--> Will represent the data length of the device feedback urb->actual_length Assign a value to usb_skel->bulk_in_filled, Indicates that the buffer has data
--183--> take usb_skel->ongoing_read Set up 0, It's readable !
--186--> Wake up processes that fall asleep because there is no data to read

So that's the analysis , The application layer can use usb_skeleton Drive from USB Massive storage device to obtain data !!! The idea of writing data is the same , I don't want to talk about it here .

Use of locks

In addition to the ingenuity of buffer management , usb_skeleton.c It's also worth learning about concurrency control , In constructing resource objects usb_skel When , This driver uses semaphore ,spinlock,mutex Three common concurrency control lock mechanisms , Next, let's discuss how the kernel masters use these technologies in different application scenarios .

semaphore

semaphore It's in progress , Its typical feature is when a process can't get semaphores , Will fall into sleep and give up CPU, So interrupt context cannot be used semaphore. stay usb_skeleton.c in ,semaphore It is used in the following scenarios

335 static void skel_write_bulk_callback(struct urb *urb)
336 {
358         up(&dev->limit_sem);                                                                        
359 }
361 static ssize_t skel_write(struct file *file, const char *user_buffer,
362                           size_t count, loff_t *ppos)
363 {
376         /*
377          * limit the number of URBs in flight to stop a user from using up all
378          * RAM
379          */
380         if (!(file->f_flags & O_NONBLOCK)) {
381                 if (down_interruptible(&dev->limit_sem)) {
382                         retval = -ERESTARTSYS;
383                         goto exit;
384                 }
385         } else {
386                 if (down_trylock(&dev->limit_sem)) {
387                         retval = -EAGAIN;
388                         goto exit;
389                 }
390         }
467         return retval;
468 }

spinlock

When critical resources are not available , Use spinlock You don't fall asleep , It's busy waiting , therefore spinlock Can be used in interrupt context , But if you can't get resources and don't sell them CPU, Waste system resources , So be spinlock The critical zone of protection cannot be too long .usb_skeleton Mainly used in the following scenarios spinlock

226 static ssize_t skel_read(struct file *file, char *buffer, size_t count,
227                          loff_t *ppos)
228 {
250 retry:
251         spin_lock_irq(&dev->err_lock);
252         ongoing_io = dev->ongoing_read;
253         spin_unlock_irq(&dev->err_lock);
332         return rv;
333 }

mutex

mutex It's just for mutual exclusion , Without using trylock When , and semaphore I'll sleep when I can't get the lock .usb_skeleton Use... In the following scenarios mutex

226 static ssize_t skel_read(struct file *file, char *buffer, size_t count,
227                          loff_t *ppos)
228 {
239         /* no concurrent readers */
240         rv = mutex_lock_interruptible(&dev->io_mutex);
330 exit:
331         mutex_unlock(&dev->io_mutex);
332         return rv;
333 }