USB: prevent char device open/deregister race
[linux-2.6] / drivers / usb / misc / usblcd.c
1 /*****************************************************************************
2  *                          USBLCD Kernel Driver                             *
3  *                            Version 1.05                                   *
4  *             (C) 2005 Georges Toth <g.toth@e-biz.lu>                       *
5  *                                                                           *
6  *     This file is licensed under the GPL. See COPYING in the package.      *
7  * Based on usb-skeleton.c 2.0 by Greg Kroah-Hartman (greg@kroah.com)        *
8  *                                                                           *
9  *                                                                           *
10  * 28.02.05 Complete rewrite of the original usblcd.c driver,                *
11  *          based on usb_skeleton.c.                                         *
12  *          This new driver allows more than one USB-LCD to be connected     *
13  *          and controlled, at once                                          *
14  *****************************************************************************/
15 #include <linux/module.h>
16 #include <linux/kernel.h>
17 #include <linux/init.h>
18 #include <linux/slab.h>
19 #include <linux/errno.h>
20 #include <asm/uaccess.h>
21 #include <linux/usb.h>
22
23 #define DRIVER_VERSION "USBLCD Driver Version 1.05"
24
25 #define USBLCD_MINOR            144
26
27 #define IOCTL_GET_HARD_VERSION  1
28 #define IOCTL_GET_DRV_VERSION   2
29
30
31 static struct usb_device_id id_table [] = {
32         { .idVendor = 0x10D2, .match_flags = USB_DEVICE_ID_MATCH_VENDOR, },
33         { },
34 };
35 MODULE_DEVICE_TABLE (usb, id_table);
36
37
38 struct usb_lcd {
39         struct usb_device *     udev;                   /* init: probe_lcd */
40         struct usb_interface *  interface;              /* the interface for this device */
41         unsigned char *         bulk_in_buffer;         /* the buffer to receive data */
42         size_t                  bulk_in_size;           /* the size of the receive buffer */
43         __u8                    bulk_in_endpointAddr;   /* the address of the bulk in endpoint */
44         __u8                    bulk_out_endpointAddr;  /* the address of the bulk out endpoint */
45         struct kref             kref;
46         struct semaphore        limit_sem;              /* to stop writes at full throttle from
47                                                          * using up all RAM */
48 };
49 #define to_lcd_dev(d) container_of(d, struct usb_lcd, kref)
50
51 #define USB_LCD_CONCURRENT_WRITES       5
52
53 static struct usb_driver lcd_driver;
54
55
56 static void lcd_delete(struct kref *kref)
57 {
58         struct usb_lcd *dev = to_lcd_dev(kref);
59
60         usb_put_dev(dev->udev);
61         kfree (dev->bulk_in_buffer);
62         kfree (dev);
63 }
64
65
66 static int lcd_open(struct inode *inode, struct file *file)
67 {
68         struct usb_lcd *dev;
69         struct usb_interface *interface;
70         int subminor;
71
72         subminor = iminor(inode);
73
74         interface = usb_find_interface(&lcd_driver, subminor);
75         if (!interface) {
76                 err ("USBLCD: %s - error, can't find device for minor %d",
77                      __FUNCTION__, subminor);
78                 return -ENODEV;
79         }
80
81         dev = usb_get_intfdata(interface);
82         if (!dev)
83                 return -ENODEV;
84
85         /* increment our usage count for the device */
86         kref_get(&dev->kref);
87
88         /* save our object in the file's private structure */
89         file->private_data = dev;
90
91         return 0;
92 }
93
94 static int lcd_release(struct inode *inode, struct file *file)
95 {
96         struct usb_lcd *dev;
97
98         dev = (struct usb_lcd *)file->private_data;
99         if (dev == NULL)
100                 return -ENODEV;
101
102         /* decrement the count on our device */
103         kref_put(&dev->kref, lcd_delete);
104         return 0;
105 }
106
107 static ssize_t lcd_read(struct file *file, char __user * buffer, size_t count, loff_t *ppos)
108 {
109         struct usb_lcd *dev;
110         int retval = 0;
111         int bytes_read;
112
113         dev = (struct usb_lcd *)file->private_data;
114
115         /* do a blocking bulk read to get data from the device */
116         retval = usb_bulk_msg(dev->udev, 
117                               usb_rcvbulkpipe(dev->udev, dev->bulk_in_endpointAddr),
118                               dev->bulk_in_buffer,
119                               min(dev->bulk_in_size, count),
120                               &bytes_read, 10000);
121
122         /* if the read was successful, copy the data to userspace */
123         if (!retval) {
124                 if (copy_to_user(buffer, dev->bulk_in_buffer, bytes_read))
125                         retval = -EFAULT;
126                 else
127                         retval = bytes_read;
128         }
129
130         return retval;
131 }
132
133 static int lcd_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
134 {
135         struct usb_lcd *dev;
136         u16 bcdDevice;
137         char buf[30];
138
139         dev = (struct usb_lcd *)file->private_data;
140         if (dev == NULL)
141                 return -ENODEV;
142         
143         switch (cmd) {
144         case IOCTL_GET_HARD_VERSION:
145                 bcdDevice = le16_to_cpu((dev->udev)->descriptor.bcdDevice);
146                 sprintf(buf,"%1d%1d.%1d%1d",
147                         (bcdDevice & 0xF000)>>12,
148                         (bcdDevice & 0xF00)>>8,
149                         (bcdDevice & 0xF0)>>4,
150                         (bcdDevice & 0xF));
151                 if (copy_to_user((void __user *)arg,buf,strlen(buf))!=0)
152                         return -EFAULT;
153                 break;
154         case IOCTL_GET_DRV_VERSION:
155                 sprintf(buf,DRIVER_VERSION);
156                 if (copy_to_user((void __user *)arg,buf,strlen(buf))!=0)
157                         return -EFAULT;
158                 break;
159         default:
160                 return -ENOTTY;
161                 break;
162         }
163
164         return 0;
165 }
166
167 static void lcd_write_bulk_callback(struct urb *urb)
168 {
169         struct usb_lcd *dev;
170
171         dev = (struct usb_lcd *)urb->context;
172
173         /* sync/async unlink faults aren't errors */
174         if (urb->status &&
175             !(urb->status == -ENOENT ||
176               urb->status == -ECONNRESET ||
177               urb->status == -ESHUTDOWN)) {
178                 dbg("USBLCD: %s - nonzero write bulk status received: %d",
179                     __FUNCTION__, urb->status);
180         }
181
182         /* free up our allocated buffer */
183         usb_buffer_free(urb->dev, urb->transfer_buffer_length,
184                         urb->transfer_buffer, urb->transfer_dma);
185         up(&dev->limit_sem);
186 }
187
188 static ssize_t lcd_write(struct file *file, const char __user * user_buffer, size_t count, loff_t *ppos)
189 {
190         struct usb_lcd *dev;
191         int retval = 0, r;
192         struct urb *urb = NULL;
193         char *buf = NULL;
194         
195         dev = (struct usb_lcd *)file->private_data;
196         
197         /* verify that we actually have some data to write */
198         if (count == 0)
199                 goto exit;
200
201         r = down_interruptible(&dev->limit_sem);
202         if (r < 0)
203                 return -EINTR;
204
205         /* create a urb, and a buffer for it, and copy the data to the urb */
206         urb = usb_alloc_urb(0, GFP_KERNEL);
207         if (!urb) {
208                 retval = -ENOMEM;
209                 goto err_no_buf;
210         }
211         
212         buf = usb_buffer_alloc(dev->udev, count, GFP_KERNEL, &urb->transfer_dma);
213         if (!buf) {
214                 retval = -ENOMEM;
215                 goto error;
216         }
217         
218         if (copy_from_user(buf, user_buffer, count)) {
219                 retval = -EFAULT;
220                 goto error;
221         }
222         
223         /* initialize the urb properly */
224         usb_fill_bulk_urb(urb, dev->udev,
225                           usb_sndbulkpipe(dev->udev, dev->bulk_out_endpointAddr),
226                           buf, count, lcd_write_bulk_callback, dev);
227         urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
228         
229         /* send the data out the bulk port */
230         retval = usb_submit_urb(urb, GFP_KERNEL);
231         if (retval) {
232                 err("USBLCD: %s - failed submitting write urb, error %d", __FUNCTION__, retval);
233                 goto error;
234         }
235         
236         /* release our reference to this urb, the USB core will eventually free it entirely */
237         usb_free_urb(urb);
238
239 exit:
240         return count;
241
242 error:
243         usb_buffer_free(dev->udev, count, buf, urb->transfer_dma);
244         usb_free_urb(urb);
245 err_no_buf:
246         up(&dev->limit_sem);
247         return retval;
248 }
249
250 static const struct file_operations lcd_fops = {
251         .owner =        THIS_MODULE,
252         .read =         lcd_read,
253         .write =        lcd_write,
254         .open =         lcd_open,
255         .ioctl =        lcd_ioctl,
256         .release =      lcd_release,
257 };
258
259 /*
260  * usb class driver info in order to get a minor number from the usb core,
261  * and to have the device registered with the driver core
262  */
263 static struct usb_class_driver lcd_class = {
264         .name =         "lcd%d",
265         .fops =         &lcd_fops,
266         .minor_base =   USBLCD_MINOR,
267 };
268
269 static int lcd_probe(struct usb_interface *interface, const struct usb_device_id *id)
270 {
271         struct usb_lcd *dev = NULL;
272         struct usb_host_interface *iface_desc;
273         struct usb_endpoint_descriptor *endpoint;
274         size_t buffer_size;
275         int i;
276         int retval = -ENOMEM;
277
278         /* allocate memory for our device state and initialize it */
279         dev = kzalloc(sizeof(*dev), GFP_KERNEL);
280         if (dev == NULL) {
281                 err("Out of memory");
282                 goto error;
283         }
284         kref_init(&dev->kref);
285         sema_init(&dev->limit_sem, USB_LCD_CONCURRENT_WRITES);
286
287         dev->udev = usb_get_dev(interface_to_usbdev(interface));
288         dev->interface = interface;
289
290         if (le16_to_cpu(dev->udev->descriptor.idProduct) != 0x0001) {
291                 warn(KERN_INFO "USBLCD model not supported.");
292                 return -ENODEV;
293         }
294         
295         /* set up the endpoint information */
296         /* use only the first bulk-in and bulk-out endpoints */
297         iface_desc = interface->cur_altsetting;
298         for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) {
299                 endpoint = &iface_desc->endpoint[i].desc;
300
301                 if (!dev->bulk_in_endpointAddr &&
302                     usb_endpoint_is_bulk_in(endpoint)) {
303                         /* we found a bulk in endpoint */
304                         buffer_size = le16_to_cpu(endpoint->wMaxPacketSize);
305                         dev->bulk_in_size = buffer_size;
306                         dev->bulk_in_endpointAddr = endpoint->bEndpointAddress;
307                         dev->bulk_in_buffer = kmalloc(buffer_size, GFP_KERNEL);
308                         if (!dev->bulk_in_buffer) {
309                                 err("Could not allocate bulk_in_buffer");
310                                 goto error;
311                         }
312                 }
313
314                 if (!dev->bulk_out_endpointAddr &&
315                     usb_endpoint_is_bulk_out(endpoint)) {
316                         /* we found a bulk out endpoint */
317                         dev->bulk_out_endpointAddr = endpoint->bEndpointAddress;
318                 }
319         }
320         if (!(dev->bulk_in_endpointAddr && dev->bulk_out_endpointAddr)) {
321                 err("Could not find both bulk-in and bulk-out endpoints");
322                 goto error;
323         }
324
325         /* save our data pointer in this interface device */
326         usb_set_intfdata(interface, dev);
327
328         /* we can register the device now, as it is ready */
329         retval = usb_register_dev(interface, &lcd_class);
330         if (retval) {
331                 /* something prevented us from registering this driver */
332                 err("Not able to get a minor for this device.");
333                 usb_set_intfdata(interface, NULL);
334                 goto error;
335         }
336
337         i = le16_to_cpu(dev->udev->descriptor.bcdDevice);
338
339         info("USBLCD Version %1d%1d.%1d%1d found at address %d",
340                 (i & 0xF000)>>12,(i & 0xF00)>>8,(i & 0xF0)>>4,(i & 0xF),
341                 dev->udev->devnum);
342
343         /* let the user know what node this device is now attached to */
344         info("USB LCD device now attached to USBLCD-%d", interface->minor);
345         return 0;
346
347 error:
348         if (dev)
349                 kref_put(&dev->kref, lcd_delete);
350         return retval;
351 }
352
353 static void lcd_disconnect(struct usb_interface *interface)
354 {
355         struct usb_lcd *dev;
356         int minor = interface->minor;
357
358         dev = usb_get_intfdata(interface);
359         usb_set_intfdata(interface, NULL);
360
361         /* give back our minor */
362         usb_deregister_dev(interface, &lcd_class);
363  
364         /* decrement our usage count */
365         kref_put(&dev->kref, lcd_delete);
366
367         info("USB LCD #%d now disconnected", minor);
368 }
369
370 static struct usb_driver lcd_driver = {
371         .name =         "usblcd",
372         .probe =        lcd_probe,
373         .disconnect =   lcd_disconnect,
374         .id_table =     id_table,
375 };
376
377 static int __init usb_lcd_init(void)
378 {
379         int result;
380         
381         result = usb_register(&lcd_driver);
382         if (result)
383                 err("usb_register failed. Error number %d", result);
384
385         return result;
386 }
387
388
389 static void __exit usb_lcd_exit(void)
390 {
391         usb_deregister(&lcd_driver);
392 }
393
394 module_init(usb_lcd_init);
395 module_exit(usb_lcd_exit);
396
397 MODULE_AUTHOR("Georges Toth <g.toth@e-biz.lu>");
398 MODULE_DESCRIPTION(DRIVER_VERSION);
399 MODULE_LICENSE("GPL");