GNU Linux-libre 4.4.288-gnu1
[releases.git] / drivers / usb / misc / chaoskey.c
1 /*
2  * chaoskey - driver for ChaosKey device from Altus Metrum.
3  *
4  * This device provides true random numbers using a noise source based
5  * on a reverse-biased p-n junction in avalanche breakdown. More
6  * details can be found at http://chaoskey.org
7  *
8  * The driver connects to the kernel hardware RNG interface to provide
9  * entropy for /dev/random and other kernel activities. It also offers
10  * a separate /dev/ entry to allow for direct access to the random
11  * bit stream.
12  *
13  * Copyright © 2015 Keith Packard <keithp@keithp.com>
14  *
15  * This program is free software; you can redistribute it and/or modify
16  * it under the terms of the GNU General Public License as published by
17  * the Free Software Foundation; version 2 of the License.
18  *
19  * This program is distributed in the hope that it will be useful, but
20  * WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
22  * General Public License for more details.
23  */
24
25 #include <linux/module.h>
26 #include <linux/slab.h>
27 #include <linux/usb.h>
28 #include <linux/wait.h>
29 #include <linux/hw_random.h>
30 #include <linux/mutex.h>
31 #include <linux/uaccess.h>
32
33 static struct usb_driver chaoskey_driver;
34 static struct usb_class_driver chaoskey_class;
35 static int chaoskey_rng_read(struct hwrng *rng, void *data,
36                              size_t max, bool wait);
37
38 #define usb_dbg(usb_if, format, arg...) \
39         dev_dbg(&(usb_if)->dev, format, ## arg)
40
41 #define usb_err(usb_if, format, arg...) \
42         dev_err(&(usb_if)->dev, format, ## arg)
43
44 /* Version Information */
45 #define DRIVER_VERSION  "v0.1"
46 #define DRIVER_AUTHOR   "Keith Packard, keithp@keithp.com"
47 #define DRIVER_DESC     "Altus Metrum ChaosKey driver"
48 #define DRIVER_SHORT    "chaoskey"
49
50 MODULE_VERSION(DRIVER_VERSION);
51 MODULE_AUTHOR(DRIVER_AUTHOR);
52 MODULE_DESCRIPTION(DRIVER_DESC);
53 MODULE_LICENSE("GPL");
54
55 #define CHAOSKEY_VENDOR_ID      0x1d50  /* OpenMoko */
56 #define CHAOSKEY_PRODUCT_ID     0x60c6  /* ChaosKey */
57
58 #define CHAOSKEY_BUF_LEN        64      /* max size of USB full speed packet */
59
60 #define NAK_TIMEOUT (HZ)                /* stall/wait timeout for device */
61
62 #ifdef CONFIG_USB_DYNAMIC_MINORS
63 #define USB_CHAOSKEY_MINOR_BASE 0
64 #else
65
66 /* IOWARRIOR_MINOR_BASE + 16, not official yet */
67 #define USB_CHAOSKEY_MINOR_BASE 224
68 #endif
69
70 static const struct usb_device_id chaoskey_table[] = {
71         { USB_DEVICE(CHAOSKEY_VENDOR_ID, CHAOSKEY_PRODUCT_ID) },
72         { },
73 };
74 MODULE_DEVICE_TABLE(usb, chaoskey_table);
75
76 /* Driver-local specific stuff */
77 struct chaoskey {
78         struct usb_interface *interface;
79         char in_ep;
80         struct mutex lock;
81         struct mutex rng_lock;
82         int open;                       /* open count */
83         int present;                    /* device not disconnected */
84         int size;                       /* size of buf */
85         int valid;                      /* bytes of buf read */
86         int used;                       /* bytes of buf consumed */
87         char *name;                     /* product + serial */
88         struct hwrng hwrng;             /* Embedded struct for hwrng */
89         int hwrng_registered;           /* registered with hwrng API */
90         wait_queue_head_t wait_q;       /* for timeouts */
91         char *buf;
92 };
93
94 static void chaoskey_free(struct chaoskey *dev)
95 {
96         usb_dbg(dev->interface, "free");
97         kfree(dev->name);
98         kfree(dev->buf);
99         usb_put_intf(dev->interface);
100         kfree(dev);
101 }
102
103 static int chaoskey_probe(struct usb_interface *interface,
104                           const struct usb_device_id *id)
105 {
106         struct usb_device *udev = interface_to_usbdev(interface);
107         struct usb_host_interface *altsetting = interface->cur_altsetting;
108         int i;
109         int in_ep = -1;
110         struct chaoskey *dev;
111         int result;
112         int size;
113
114         usb_dbg(interface, "probe %s-%s", udev->product, udev->serial);
115
116         /* Find the first bulk IN endpoint and its packet size */
117         for (i = 0; i < altsetting->desc.bNumEndpoints; i++) {
118                 if (usb_endpoint_is_bulk_in(&altsetting->endpoint[i].desc)) {
119                         in_ep = usb_endpoint_num(&altsetting->endpoint[i].desc);
120                         size = usb_endpoint_maxp(&altsetting->endpoint[i].desc);
121                         break;
122                 }
123         }
124
125         /* Validate endpoint and size */
126         if (in_ep == -1) {
127                 usb_dbg(interface, "no IN endpoint found");
128                 return -ENODEV;
129         }
130         if (size <= 0) {
131                 usb_dbg(interface, "invalid size (%d)", size);
132                 return -ENODEV;
133         }
134
135         if (size > CHAOSKEY_BUF_LEN) {
136                 usb_dbg(interface, "size reduced from %d to %d\n",
137                         size, CHAOSKEY_BUF_LEN);
138                 size = CHAOSKEY_BUF_LEN;
139         }
140
141         /* Looks good, allocate and initialize */
142
143         dev = kzalloc(sizeof(struct chaoskey), GFP_KERNEL);
144
145         if (dev == NULL)
146                 return -ENOMEM;
147
148         dev->interface = usb_get_intf(interface);
149
150         dev->buf = kmalloc(size, GFP_KERNEL);
151
152         if (dev->buf == NULL) {
153                 kfree(dev);
154                 return -ENOMEM;
155         }
156
157         /* Construct a name using the product and serial values. Each
158          * device needs a unique name for the hwrng code
159          */
160
161         if (udev->product && udev->serial) {
162                 dev->name = kmalloc(strlen(udev->product) + 1 +
163                                     strlen(udev->serial) + 1, GFP_KERNEL);
164                 if (dev->name == NULL) {
165                         kfree(dev->buf);
166                         kfree(dev);
167                         return -ENOMEM;
168                 }
169
170                 strcpy(dev->name, udev->product);
171                 strcat(dev->name, "-");
172                 strcat(dev->name, udev->serial);
173         }
174
175         dev->in_ep = in_ep;
176
177         dev->size = size;
178         dev->present = 1;
179
180         init_waitqueue_head(&dev->wait_q);
181
182         mutex_init(&dev->lock);
183         mutex_init(&dev->rng_lock);
184
185         usb_set_intfdata(interface, dev);
186
187         result = usb_register_dev(interface, &chaoskey_class);
188         if (result) {
189                 usb_err(interface, "Unable to allocate minor number.");
190                 usb_set_intfdata(interface, NULL);
191                 chaoskey_free(dev);
192                 return result;
193         }
194
195         dev->hwrng.name = dev->name ? dev->name : chaoskey_driver.name;
196         dev->hwrng.read = chaoskey_rng_read;
197
198         /* Set the 'quality' metric.  Quality is measured in units of
199          * 1/1024's of a bit ("mills"). This should be set to 1024,
200          * but there is a bug in the hwrng core which masks it with
201          * 1023.
202          *
203          * The patch that has been merged to the crypto development
204          * tree for that bug limits the value to 1024 at most, so by
205          * setting this to 1024 + 1023, we get 1023 before the fix is
206          * merged and 1024 afterwards. We'll patch this driver once
207          * both bits of code are in the same tree.
208          */
209         dev->hwrng.quality = 1024 + 1023;
210
211         dev->hwrng_registered = (hwrng_register(&dev->hwrng) == 0);
212         if (!dev->hwrng_registered)
213                 usb_err(interface, "Unable to register with hwrng");
214
215         usb_enable_autosuspend(udev);
216
217         usb_dbg(interface, "chaoskey probe success, size %d", dev->size);
218         return 0;
219 }
220
221 static void chaoskey_disconnect(struct usb_interface *interface)
222 {
223         struct chaoskey *dev;
224
225         usb_dbg(interface, "disconnect");
226         dev = usb_get_intfdata(interface);
227         if (!dev) {
228                 usb_dbg(interface, "disconnect failed - no dev");
229                 return;
230         }
231
232         if (dev->hwrng_registered)
233                 hwrng_unregister(&dev->hwrng);
234
235         usb_deregister_dev(interface, &chaoskey_class);
236
237         usb_set_intfdata(interface, NULL);
238         mutex_lock(&dev->lock);
239
240         dev->present = 0;
241
242         if (!dev->open) {
243                 mutex_unlock(&dev->lock);
244                 chaoskey_free(dev);
245         } else
246                 mutex_unlock(&dev->lock);
247
248         usb_dbg(interface, "disconnect done");
249 }
250
251 static int chaoskey_open(struct inode *inode, struct file *file)
252 {
253         struct chaoskey *dev;
254         struct usb_interface *interface;
255
256         /* get the interface from minor number and driver information */
257         interface = usb_find_interface(&chaoskey_driver, iminor(inode));
258         if (!interface)
259                 return -ENODEV;
260
261         usb_dbg(interface, "open");
262
263         dev = usb_get_intfdata(interface);
264         if (!dev) {
265                 usb_dbg(interface, "open (dev)");
266                 return -ENODEV;
267         }
268
269         file->private_data = dev;
270         mutex_lock(&dev->lock);
271         ++dev->open;
272         mutex_unlock(&dev->lock);
273
274         usb_dbg(interface, "open success");
275         return 0;
276 }
277
278 static int chaoskey_release(struct inode *inode, struct file *file)
279 {
280         struct chaoskey *dev = file->private_data;
281         struct usb_interface *interface;
282
283         if (dev == NULL)
284                 return -ENODEV;
285
286         interface = dev->interface;
287
288         usb_dbg(interface, "release");
289
290         mutex_lock(&dev->lock);
291
292         usb_dbg(interface, "open count at release is %d", dev->open);
293
294         if (dev->open <= 0) {
295                 usb_dbg(interface, "invalid open count (%d)", dev->open);
296                 mutex_unlock(&dev->lock);
297                 return -ENODEV;
298         }
299
300         --dev->open;
301
302         if (!dev->present) {
303                 if (dev->open == 0) {
304                         mutex_unlock(&dev->lock);
305                         chaoskey_free(dev);
306                 } else
307                         mutex_unlock(&dev->lock);
308         } else
309                 mutex_unlock(&dev->lock);
310
311         usb_dbg(interface, "release success");
312         return 0;
313 }
314
315 /* Fill the buffer. Called with dev->lock held
316  */
317 static int _chaoskey_fill(struct chaoskey *dev)
318 {
319         DEFINE_WAIT(wait);
320         int result;
321         int this_read;
322         struct usb_device *udev = interface_to_usbdev(dev->interface);
323
324         usb_dbg(dev->interface, "fill");
325
326         /* Return immediately if someone called before the buffer was
327          * empty */
328         if (dev->valid != dev->used) {
329                 usb_dbg(dev->interface, "not empty yet (valid %d used %d)",
330                         dev->valid, dev->used);
331                 return 0;
332         }
333
334         /* Bail if the device has been removed */
335         if (!dev->present) {
336                 usb_dbg(dev->interface, "device not present");
337                 return -ENODEV;
338         }
339
340         /* Make sure the device is awake */
341         result = usb_autopm_get_interface(dev->interface);
342         if (result) {
343                 usb_dbg(dev->interface, "wakeup failed (result %d)", result);
344                 return result;
345         }
346
347         result = usb_bulk_msg(udev,
348                               usb_rcvbulkpipe(udev, dev->in_ep),
349                               dev->buf, dev->size, &this_read,
350                               NAK_TIMEOUT);
351
352         /* Let the device go back to sleep eventually */
353         usb_autopm_put_interface(dev->interface);
354
355         if (result == 0) {
356                 dev->valid = this_read;
357                 dev->used = 0;
358         }
359
360         usb_dbg(dev->interface, "bulk_msg result %d this_read %d",
361                 result, this_read);
362
363         return result;
364 }
365
366 static ssize_t chaoskey_read(struct file *file,
367                              char __user *buffer,
368                              size_t count,
369                              loff_t *ppos)
370 {
371         struct chaoskey *dev;
372         ssize_t read_count = 0;
373         int this_time;
374         int result = 0;
375         unsigned long remain;
376
377         dev = file->private_data;
378
379         if (dev == NULL || !dev->present)
380                 return -ENODEV;
381
382         usb_dbg(dev->interface, "read %zu", count);
383
384         while (count > 0) {
385
386                 /* Grab the rng_lock briefly to ensure that the hwrng interface
387                  * gets priority over other user access
388                  */
389                 result = mutex_lock_interruptible(&dev->rng_lock);
390                 if (result)
391                         goto bail;
392                 mutex_unlock(&dev->rng_lock);
393
394                 result = mutex_lock_interruptible(&dev->lock);
395                 if (result)
396                         goto bail;
397                 if (dev->valid == dev->used) {
398                         result = _chaoskey_fill(dev);
399                         if (result) {
400                                 mutex_unlock(&dev->lock);
401                                 goto bail;
402                         }
403
404                         /* Read returned zero bytes */
405                         if (dev->used == dev->valid) {
406                                 mutex_unlock(&dev->lock);
407                                 goto bail;
408                         }
409                 }
410
411                 this_time = dev->valid - dev->used;
412                 if (this_time > count)
413                         this_time = count;
414
415                 remain = copy_to_user(buffer, dev->buf + dev->used, this_time);
416                 if (remain) {
417                         result = -EFAULT;
418
419                         /* Consume the bytes that were copied so we don't leak
420                          * data to user space
421                          */
422                         dev->used += this_time - remain;
423                         mutex_unlock(&dev->lock);
424                         goto bail;
425                 }
426
427                 count -= this_time;
428                 read_count += this_time;
429                 buffer += this_time;
430                 dev->used += this_time;
431                 mutex_unlock(&dev->lock);
432         }
433 bail:
434         if (read_count) {
435                 usb_dbg(dev->interface, "read %zu bytes", read_count);
436                 return read_count;
437         }
438         usb_dbg(dev->interface, "empty read, result %d", result);
439         return result;
440 }
441
442 static int chaoskey_rng_read(struct hwrng *rng, void *data,
443                              size_t max, bool wait)
444 {
445         struct chaoskey *dev = container_of(rng, struct chaoskey, hwrng);
446         int this_time;
447
448         usb_dbg(dev->interface, "rng_read max %zu wait %d", max, wait);
449
450         if (!dev->present) {
451                 usb_dbg(dev->interface, "device not present");
452                 return 0;
453         }
454
455         /* Hold the rng_lock until we acquire the device lock so that
456          * this operation gets priority over other user access to the
457          * device
458          */
459         mutex_lock(&dev->rng_lock);
460
461         mutex_lock(&dev->lock);
462
463         mutex_unlock(&dev->rng_lock);
464
465         /* Try to fill the buffer if empty. It doesn't actually matter
466          * if _chaoskey_fill works; we'll just return zero bytes as
467          * the buffer will still be empty
468          */
469         if (dev->valid == dev->used)
470                 (void) _chaoskey_fill(dev);
471
472         this_time = dev->valid - dev->used;
473         if (this_time > max)
474                 this_time = max;
475
476         memcpy(data, dev->buf + dev->used, this_time);
477
478         dev->used += this_time;
479
480         mutex_unlock(&dev->lock);
481
482         usb_dbg(dev->interface, "rng_read this_time %d\n", this_time);
483         return this_time;
484 }
485
486 #ifdef CONFIG_PM
487 static int chaoskey_suspend(struct usb_interface *interface,
488                             pm_message_t message)
489 {
490         usb_dbg(interface, "suspend");
491         return 0;
492 }
493
494 static int chaoskey_resume(struct usb_interface *interface)
495 {
496         usb_dbg(interface, "resume");
497         return 0;
498 }
499 #else
500 #define chaoskey_suspend NULL
501 #define chaoskey_resume NULL
502 #endif
503
504 /* file operation pointers */
505 static const struct file_operations chaoskey_fops = {
506         .owner = THIS_MODULE,
507         .read = chaoskey_read,
508         .open = chaoskey_open,
509         .release = chaoskey_release,
510         .llseek = default_llseek,
511 };
512
513 /* class driver information */
514 static struct usb_class_driver chaoskey_class = {
515         .name = "chaoskey%d",
516         .fops = &chaoskey_fops,
517         .minor_base = USB_CHAOSKEY_MINOR_BASE,
518 };
519
520 /* usb specific object needed to register this driver with the usb subsystem */
521 static struct usb_driver chaoskey_driver = {
522         .name = DRIVER_SHORT,
523         .probe = chaoskey_probe,
524         .disconnect = chaoskey_disconnect,
525         .suspend = chaoskey_suspend,
526         .resume = chaoskey_resume,
527         .reset_resume = chaoskey_resume,
528         .id_table = chaoskey_table,
529         .supports_autosuspend = 1,
530 };
531
532 module_usb_driver(chaoskey_driver);
533