Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0
0002 /*
0003  * USB Skeleton driver - 2.2
0004  *
0005  * Copyright (C) 2001-2004 Greg Kroah-Hartman (greg@kroah.com)
0006  *
0007  * This driver is based on the 2.6.3 version of drivers/usb/usb-skeleton.c
0008  * but has been rewritten to be easier to read and use.
0009  */
0010 
0011 #include <linux/kernel.h>
0012 #include <linux/errno.h>
0013 #include <linux/slab.h>
0014 #include <linux/module.h>
0015 #include <linux/kref.h>
0016 #include <linux/uaccess.h>
0017 #include <linux/usb.h>
0018 #include <linux/mutex.h>
0019 
0020 
0021 /* Define these values to match your devices */
0022 #define USB_SKEL_VENDOR_ID  0xfff0
0023 #define USB_SKEL_PRODUCT_ID 0xfff0
0024 
0025 /* table of devices that work with this driver */
0026 static const struct usb_device_id skel_table[] = {
0027     { USB_DEVICE(USB_SKEL_VENDOR_ID, USB_SKEL_PRODUCT_ID) },
0028     { }                 /* Terminating entry */
0029 };
0030 MODULE_DEVICE_TABLE(usb, skel_table);
0031 
0032 
0033 /* Get a minor range for your devices from the usb maintainer */
0034 #define USB_SKEL_MINOR_BASE 192
0035 
0036 /* our private defines. if this grows any larger, use your own .h file */
0037 #define MAX_TRANSFER        (PAGE_SIZE - 512)
0038 /*
0039  * MAX_TRANSFER is chosen so that the VM is not stressed by
0040  * allocations > PAGE_SIZE and the number of packets in a page
0041  * is an integer 512 is the largest possible packet on EHCI
0042  */
0043 #define WRITES_IN_FLIGHT    8
0044 /* arbitrarily chosen */
0045 
0046 /* Structure to hold all of our device specific stuff */
0047 struct usb_skel {
0048     struct usb_device   *udev;          /* the usb device for this device */
0049     struct usb_interface    *interface;     /* the interface for this device */
0050     struct semaphore    limit_sem;      /* limiting the number of writes in progress */
0051     struct usb_anchor   submitted;      /* in case we need to retract our submissions */
0052     struct urb      *bulk_in_urb;       /* the urb to read data with */
0053     unsigned char           *bulk_in_buffer;    /* the buffer to receive data */
0054     size_t          bulk_in_size;       /* the size of the receive buffer */
0055     size_t          bulk_in_filled;     /* number of bytes in the buffer */
0056     size_t          bulk_in_copied;     /* already copied to user space */
0057     __u8            bulk_in_endpointAddr;   /* the address of the bulk in endpoint */
0058     __u8            bulk_out_endpointAddr;  /* the address of the bulk out endpoint */
0059     int         errors;         /* the last request tanked */
0060     bool            ongoing_read;       /* a read is going on */
0061     spinlock_t      err_lock;       /* lock for errors */
0062     struct kref     kref;
0063     struct mutex        io_mutex;       /* synchronize I/O with disconnect */
0064     unsigned long       disconnected:1;
0065     wait_queue_head_t   bulk_in_wait;       /* to wait for an ongoing read */
0066 };
0067 #define to_skel_dev(d) container_of(d, struct usb_skel, kref)
0068 
0069 static struct usb_driver skel_driver;
0070 static void skel_draw_down(struct usb_skel *dev);
0071 
0072 static void skel_delete(struct kref *kref)
0073 {
0074     struct usb_skel *dev = to_skel_dev(kref);
0075 
0076     usb_free_urb(dev->bulk_in_urb);
0077     usb_put_intf(dev->interface);
0078     usb_put_dev(dev->udev);
0079     kfree(dev->bulk_in_buffer);
0080     kfree(dev);
0081 }
0082 
0083 static int skel_open(struct inode *inode, struct file *file)
0084 {
0085     struct usb_skel *dev;
0086     struct usb_interface *interface;
0087     int subminor;
0088     int retval = 0;
0089 
0090     subminor = iminor(inode);
0091 
0092     interface = usb_find_interface(&skel_driver, subminor);
0093     if (!interface) {
0094         pr_err("%s - error, can't find device for minor %d\n",
0095             __func__, subminor);
0096         retval = -ENODEV;
0097         goto exit;
0098     }
0099 
0100     dev = usb_get_intfdata(interface);
0101     if (!dev) {
0102         retval = -ENODEV;
0103         goto exit;
0104     }
0105 
0106     retval = usb_autopm_get_interface(interface);
0107     if (retval)
0108         goto exit;
0109 
0110     /* increment our usage count for the device */
0111     kref_get(&dev->kref);
0112 
0113     /* save our object in the file's private structure */
0114     file->private_data = dev;
0115 
0116 exit:
0117     return retval;
0118 }
0119 
0120 static int skel_release(struct inode *inode, struct file *file)
0121 {
0122     struct usb_skel *dev;
0123 
0124     dev = file->private_data;
0125     if (dev == NULL)
0126         return -ENODEV;
0127 
0128     /* allow the device to be autosuspended */
0129     usb_autopm_put_interface(dev->interface);
0130 
0131     /* decrement the count on our device */
0132     kref_put(&dev->kref, skel_delete);
0133     return 0;
0134 }
0135 
0136 static int skel_flush(struct file *file, fl_owner_t id)
0137 {
0138     struct usb_skel *dev;
0139     int res;
0140 
0141     dev = file->private_data;
0142     if (dev == NULL)
0143         return -ENODEV;
0144 
0145     /* wait for io to stop */
0146     mutex_lock(&dev->io_mutex);
0147     skel_draw_down(dev);
0148 
0149     /* read out errors, leave subsequent opens a clean slate */
0150     spin_lock_irq(&dev->err_lock);
0151     res = dev->errors ? (dev->errors == -EPIPE ? -EPIPE : -EIO) : 0;
0152     dev->errors = 0;
0153     spin_unlock_irq(&dev->err_lock);
0154 
0155     mutex_unlock(&dev->io_mutex);
0156 
0157     return res;
0158 }
0159 
0160 static void skel_read_bulk_callback(struct urb *urb)
0161 {
0162     struct usb_skel *dev;
0163     unsigned long flags;
0164 
0165     dev = urb->context;
0166 
0167     spin_lock_irqsave(&dev->err_lock, flags);
0168     /* sync/async unlink faults aren't errors */
0169     if (urb->status) {
0170         if (!(urb->status == -ENOENT ||
0171             urb->status == -ECONNRESET ||
0172             urb->status == -ESHUTDOWN))
0173             dev_err(&dev->interface->dev,
0174                 "%s - nonzero write bulk status received: %d\n",
0175                 __func__, urb->status);
0176 
0177         dev->errors = urb->status;
0178     } else {
0179         dev->bulk_in_filled = urb->actual_length;
0180     }
0181     dev->ongoing_read = 0;
0182     spin_unlock_irqrestore(&dev->err_lock, flags);
0183 
0184     wake_up_interruptible(&dev->bulk_in_wait);
0185 }
0186 
0187 static int skel_do_read_io(struct usb_skel *dev, size_t count)
0188 {
0189     int rv;
0190 
0191     /* prepare a read */
0192     usb_fill_bulk_urb(dev->bulk_in_urb,
0193             dev->udev,
0194             usb_rcvbulkpipe(dev->udev,
0195                 dev->bulk_in_endpointAddr),
0196             dev->bulk_in_buffer,
0197             min(dev->bulk_in_size, count),
0198             skel_read_bulk_callback,
0199             dev);
0200     /* tell everybody to leave the URB alone */
0201     spin_lock_irq(&dev->err_lock);
0202     dev->ongoing_read = 1;
0203     spin_unlock_irq(&dev->err_lock);
0204 
0205     /* submit bulk in urb, which means no data to deliver */
0206     dev->bulk_in_filled = 0;
0207     dev->bulk_in_copied = 0;
0208 
0209     /* do it */
0210     rv = usb_submit_urb(dev->bulk_in_urb, GFP_KERNEL);
0211     if (rv < 0) {
0212         dev_err(&dev->interface->dev,
0213             "%s - failed submitting read urb, error %d\n",
0214             __func__, rv);
0215         rv = (rv == -ENOMEM) ? rv : -EIO;
0216         spin_lock_irq(&dev->err_lock);
0217         dev->ongoing_read = 0;
0218         spin_unlock_irq(&dev->err_lock);
0219     }
0220 
0221     return rv;
0222 }
0223 
0224 static ssize_t skel_read(struct file *file, char *buffer, size_t count,
0225              loff_t *ppos)
0226 {
0227     struct usb_skel *dev;
0228     int rv;
0229     bool ongoing_io;
0230 
0231     dev = file->private_data;
0232 
0233     if (!count)
0234         return 0;
0235 
0236     /* no concurrent readers */
0237     rv = mutex_lock_interruptible(&dev->io_mutex);
0238     if (rv < 0)
0239         return rv;
0240 
0241     if (dev->disconnected) {        /* disconnect() was called */
0242         rv = -ENODEV;
0243         goto exit;
0244     }
0245 
0246     /* if IO is under way, we must not touch things */
0247 retry:
0248     spin_lock_irq(&dev->err_lock);
0249     ongoing_io = dev->ongoing_read;
0250     spin_unlock_irq(&dev->err_lock);
0251 
0252     if (ongoing_io) {
0253         /* nonblocking IO shall not wait */
0254         if (file->f_flags & O_NONBLOCK) {
0255             rv = -EAGAIN;
0256             goto exit;
0257         }
0258         /*
0259          * IO may take forever
0260          * hence wait in an interruptible state
0261          */
0262         rv = wait_event_interruptible(dev->bulk_in_wait, (!dev->ongoing_read));
0263         if (rv < 0)
0264             goto exit;
0265     }
0266 
0267     /* errors must be reported */
0268     rv = dev->errors;
0269     if (rv < 0) {
0270         /* any error is reported once */
0271         dev->errors = 0;
0272         /* to preserve notifications about reset */
0273         rv = (rv == -EPIPE) ? rv : -EIO;
0274         /* report it */
0275         goto exit;
0276     }
0277 
0278     /*
0279      * if the buffer is filled we may satisfy the read
0280      * else we need to start IO
0281      */
0282 
0283     if (dev->bulk_in_filled) {
0284         /* we had read data */
0285         size_t available = dev->bulk_in_filled - dev->bulk_in_copied;
0286         size_t chunk = min(available, count);
0287 
0288         if (!available) {
0289             /*
0290              * all data has been used
0291              * actual IO needs to be done
0292              */
0293             rv = skel_do_read_io(dev, count);
0294             if (rv < 0)
0295                 goto exit;
0296             else
0297                 goto retry;
0298         }
0299         /*
0300          * data is available
0301          * chunk tells us how much shall be copied
0302          */
0303 
0304         if (copy_to_user(buffer,
0305                  dev->bulk_in_buffer + dev->bulk_in_copied,
0306                  chunk))
0307             rv = -EFAULT;
0308         else
0309             rv = chunk;
0310 
0311         dev->bulk_in_copied += chunk;
0312 
0313         /*
0314          * if we are asked for more than we have,
0315          * we start IO but don't wait
0316          */
0317         if (available < count)
0318             skel_do_read_io(dev, count - chunk);
0319     } else {
0320         /* no data in the buffer */
0321         rv = skel_do_read_io(dev, count);
0322         if (rv < 0)
0323             goto exit;
0324         else
0325             goto retry;
0326     }
0327 exit:
0328     mutex_unlock(&dev->io_mutex);
0329     return rv;
0330 }
0331 
0332 static void skel_write_bulk_callback(struct urb *urb)
0333 {
0334     struct usb_skel *dev;
0335     unsigned long flags;
0336 
0337     dev = urb->context;
0338 
0339     /* sync/async unlink faults aren't errors */
0340     if (urb->status) {
0341         if (!(urb->status == -ENOENT ||
0342             urb->status == -ECONNRESET ||
0343             urb->status == -ESHUTDOWN))
0344             dev_err(&dev->interface->dev,
0345                 "%s - nonzero write bulk status received: %d\n",
0346                 __func__, urb->status);
0347 
0348         spin_lock_irqsave(&dev->err_lock, flags);
0349         dev->errors = urb->status;
0350         spin_unlock_irqrestore(&dev->err_lock, flags);
0351     }
0352 
0353     /* free up our allocated buffer */
0354     usb_free_coherent(urb->dev, urb->transfer_buffer_length,
0355               urb->transfer_buffer, urb->transfer_dma);
0356     up(&dev->limit_sem);
0357 }
0358 
0359 static ssize_t skel_write(struct file *file, const char *user_buffer,
0360               size_t count, loff_t *ppos)
0361 {
0362     struct usb_skel *dev;
0363     int retval = 0;
0364     struct urb *urb = NULL;
0365     char *buf = NULL;
0366     size_t writesize = min_t(size_t, count, MAX_TRANSFER);
0367 
0368     dev = file->private_data;
0369 
0370     /* verify that we actually have some data to write */
0371     if (count == 0)
0372         goto exit;
0373 
0374     /*
0375      * limit the number of URBs in flight to stop a user from using up all
0376      * RAM
0377      */
0378     if (!(file->f_flags & O_NONBLOCK)) {
0379         if (down_interruptible(&dev->limit_sem)) {
0380             retval = -ERESTARTSYS;
0381             goto exit;
0382         }
0383     } else {
0384         if (down_trylock(&dev->limit_sem)) {
0385             retval = -EAGAIN;
0386             goto exit;
0387         }
0388     }
0389 
0390     spin_lock_irq(&dev->err_lock);
0391     retval = dev->errors;
0392     if (retval < 0) {
0393         /* any error is reported once */
0394         dev->errors = 0;
0395         /* to preserve notifications about reset */
0396         retval = (retval == -EPIPE) ? retval : -EIO;
0397     }
0398     spin_unlock_irq(&dev->err_lock);
0399     if (retval < 0)
0400         goto error;
0401 
0402     /* create a urb, and a buffer for it, and copy the data to the urb */
0403     urb = usb_alloc_urb(0, GFP_KERNEL);
0404     if (!urb) {
0405         retval = -ENOMEM;
0406         goto error;
0407     }
0408 
0409     buf = usb_alloc_coherent(dev->udev, writesize, GFP_KERNEL,
0410                  &urb->transfer_dma);
0411     if (!buf) {
0412         retval = -ENOMEM;
0413         goto error;
0414     }
0415 
0416     if (copy_from_user(buf, user_buffer, writesize)) {
0417         retval = -EFAULT;
0418         goto error;
0419     }
0420 
0421     /* this lock makes sure we don't submit URBs to gone devices */
0422     mutex_lock(&dev->io_mutex);
0423     if (dev->disconnected) {        /* disconnect() was called */
0424         mutex_unlock(&dev->io_mutex);
0425         retval = -ENODEV;
0426         goto error;
0427     }
0428 
0429     /* initialize the urb properly */
0430     usb_fill_bulk_urb(urb, dev->udev,
0431               usb_sndbulkpipe(dev->udev, dev->bulk_out_endpointAddr),
0432               buf, writesize, skel_write_bulk_callback, dev);
0433     urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
0434     usb_anchor_urb(urb, &dev->submitted);
0435 
0436     /* send the data out the bulk port */
0437     retval = usb_submit_urb(urb, GFP_KERNEL);
0438     mutex_unlock(&dev->io_mutex);
0439     if (retval) {
0440         dev_err(&dev->interface->dev,
0441             "%s - failed submitting write urb, error %d\n",
0442             __func__, retval);
0443         goto error_unanchor;
0444     }
0445 
0446     /*
0447      * release our reference to this urb, the USB core will eventually free
0448      * it entirely
0449      */
0450     usb_free_urb(urb);
0451 
0452 
0453     return writesize;
0454 
0455 error_unanchor:
0456     usb_unanchor_urb(urb);
0457 error:
0458     if (urb) {
0459         usb_free_coherent(dev->udev, writesize, buf, urb->transfer_dma);
0460         usb_free_urb(urb);
0461     }
0462     up(&dev->limit_sem);
0463 
0464 exit:
0465     return retval;
0466 }
0467 
0468 static const struct file_operations skel_fops = {
0469     .owner =    THIS_MODULE,
0470     .read =     skel_read,
0471     .write =    skel_write,
0472     .open =     skel_open,
0473     .release =  skel_release,
0474     .flush =    skel_flush,
0475     .llseek =   noop_llseek,
0476 };
0477 
0478 /*
0479  * usb class driver info in order to get a minor number from the usb core,
0480  * and to have the device registered with the driver core
0481  */
0482 static struct usb_class_driver skel_class = {
0483     .name =     "skel%d",
0484     .fops =     &skel_fops,
0485     .minor_base =   USB_SKEL_MINOR_BASE,
0486 };
0487 
0488 static int skel_probe(struct usb_interface *interface,
0489               const struct usb_device_id *id)
0490 {
0491     struct usb_skel *dev;
0492     struct usb_endpoint_descriptor *bulk_in, *bulk_out;
0493     int retval;
0494 
0495     /* allocate memory for our device state and initialize it */
0496     dev = kzalloc(sizeof(*dev), GFP_KERNEL);
0497     if (!dev)
0498         return -ENOMEM;
0499 
0500     kref_init(&dev->kref);
0501     sema_init(&dev->limit_sem, WRITES_IN_FLIGHT);
0502     mutex_init(&dev->io_mutex);
0503     spin_lock_init(&dev->err_lock);
0504     init_usb_anchor(&dev->submitted);
0505     init_waitqueue_head(&dev->bulk_in_wait);
0506 
0507     dev->udev = usb_get_dev(interface_to_usbdev(interface));
0508     dev->interface = usb_get_intf(interface);
0509 
0510     /* set up the endpoint information */
0511     /* use only the first bulk-in and bulk-out endpoints */
0512     retval = usb_find_common_endpoints(interface->cur_altsetting,
0513             &bulk_in, &bulk_out, NULL, NULL);
0514     if (retval) {
0515         dev_err(&interface->dev,
0516             "Could not find both bulk-in and bulk-out endpoints\n");
0517         goto error;
0518     }
0519 
0520     dev->bulk_in_size = usb_endpoint_maxp(bulk_in);
0521     dev->bulk_in_endpointAddr = bulk_in->bEndpointAddress;
0522     dev->bulk_in_buffer = kmalloc(dev->bulk_in_size, GFP_KERNEL);
0523     if (!dev->bulk_in_buffer) {
0524         retval = -ENOMEM;
0525         goto error;
0526     }
0527     dev->bulk_in_urb = usb_alloc_urb(0, GFP_KERNEL);
0528     if (!dev->bulk_in_urb) {
0529         retval = -ENOMEM;
0530         goto error;
0531     }
0532 
0533     dev->bulk_out_endpointAddr = bulk_out->bEndpointAddress;
0534 
0535     /* save our data pointer in this interface device */
0536     usb_set_intfdata(interface, dev);
0537 
0538     /* we can register the device now, as it is ready */
0539     retval = usb_register_dev(interface, &skel_class);
0540     if (retval) {
0541         /* something prevented us from registering this driver */
0542         dev_err(&interface->dev,
0543             "Not able to get a minor for this device.\n");
0544         usb_set_intfdata(interface, NULL);
0545         goto error;
0546     }
0547 
0548     /* let the user know what node this device is now attached to */
0549     dev_info(&interface->dev,
0550          "USB Skeleton device now attached to USBSkel-%d",
0551          interface->minor);
0552     return 0;
0553 
0554 error:
0555     /* this frees allocated memory */
0556     kref_put(&dev->kref, skel_delete);
0557 
0558     return retval;
0559 }
0560 
0561 static void skel_disconnect(struct usb_interface *interface)
0562 {
0563     struct usb_skel *dev;
0564     int minor = interface->minor;
0565 
0566     dev = usb_get_intfdata(interface);
0567     usb_set_intfdata(interface, NULL);
0568 
0569     /* give back our minor */
0570     usb_deregister_dev(interface, &skel_class);
0571 
0572     /* prevent more I/O from starting */
0573     mutex_lock(&dev->io_mutex);
0574     dev->disconnected = 1;
0575     mutex_unlock(&dev->io_mutex);
0576 
0577     usb_kill_urb(dev->bulk_in_urb);
0578     usb_kill_anchored_urbs(&dev->submitted);
0579 
0580     /* decrement our usage count */
0581     kref_put(&dev->kref, skel_delete);
0582 
0583     dev_info(&interface->dev, "USB Skeleton #%d now disconnected", minor);
0584 }
0585 
0586 static void skel_draw_down(struct usb_skel *dev)
0587 {
0588     int time;
0589 
0590     time = usb_wait_anchor_empty_timeout(&dev->submitted, 1000);
0591     if (!time)
0592         usb_kill_anchored_urbs(&dev->submitted);
0593     usb_kill_urb(dev->bulk_in_urb);
0594 }
0595 
0596 static int skel_suspend(struct usb_interface *intf, pm_message_t message)
0597 {
0598     struct usb_skel *dev = usb_get_intfdata(intf);
0599 
0600     if (!dev)
0601         return 0;
0602     skel_draw_down(dev);
0603     return 0;
0604 }
0605 
0606 static int skel_resume(struct usb_interface *intf)
0607 {
0608     return 0;
0609 }
0610 
0611 static int skel_pre_reset(struct usb_interface *intf)
0612 {
0613     struct usb_skel *dev = usb_get_intfdata(intf);
0614 
0615     mutex_lock(&dev->io_mutex);
0616     skel_draw_down(dev);
0617 
0618     return 0;
0619 }
0620 
0621 static int skel_post_reset(struct usb_interface *intf)
0622 {
0623     struct usb_skel *dev = usb_get_intfdata(intf);
0624 
0625     /* we are sure no URBs are active - no locking needed */
0626     dev->errors = -EPIPE;
0627     mutex_unlock(&dev->io_mutex);
0628 
0629     return 0;
0630 }
0631 
0632 static struct usb_driver skel_driver = {
0633     .name =     "skeleton",
0634     .probe =    skel_probe,
0635     .disconnect =   skel_disconnect,
0636     .suspend =  skel_suspend,
0637     .resume =   skel_resume,
0638     .pre_reset =    skel_pre_reset,
0639     .post_reset =   skel_post_reset,
0640     .id_table = skel_table,
0641     .supports_autosuspend = 1,
0642 };
0643 
0644 module_usb_driver(skel_driver);
0645 
0646 MODULE_LICENSE("GPL v2");