GNU Linux-libre 4.9.309-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 ALEA_VENDOR_ID          0x12d8  /* Araneus */
59 #define ALEA_PRODUCT_ID         0x0001  /* Alea I */
60
61 #define CHAOSKEY_BUF_LEN        64      /* max size of USB full speed packet */
62
63 #define NAK_TIMEOUT (HZ)                /* normal stall/wait timeout */
64 #define ALEA_FIRST_TIMEOUT (HZ*3)       /* first stall/wait timeout for Alea */
65
66 #ifdef CONFIG_USB_DYNAMIC_MINORS
67 #define USB_CHAOSKEY_MINOR_BASE 0
68 #else
69
70 /* IOWARRIOR_MINOR_BASE + 16, not official yet */
71 #define USB_CHAOSKEY_MINOR_BASE 224
72 #endif
73
74 static const struct usb_device_id chaoskey_table[] = {
75         { USB_DEVICE(CHAOSKEY_VENDOR_ID, CHAOSKEY_PRODUCT_ID) },
76         { USB_DEVICE(ALEA_VENDOR_ID, ALEA_PRODUCT_ID) },
77         { },
78 };
79 MODULE_DEVICE_TABLE(usb, chaoskey_table);
80
81 static void chaos_read_callback(struct urb *urb);
82
83 /* Driver-local specific stuff */
84 struct chaoskey {
85         struct usb_interface *interface;
86         char in_ep;
87         struct mutex lock;
88         struct mutex rng_lock;
89         int open;                       /* open count */
90         bool present;                   /* device not disconnected */
91         bool reading;                   /* ongoing IO */
92         bool reads_started;             /* track first read for Alea */
93         int size;                       /* size of buf */
94         int valid;                      /* bytes of buf read */
95         int used;                       /* bytes of buf consumed */
96         char *name;                     /* product + serial */
97         struct hwrng hwrng;             /* Embedded struct for hwrng */
98         int hwrng_registered;           /* registered with hwrng API */
99         wait_queue_head_t wait_q;       /* for timeouts */
100         struct urb *urb;                /* for performing IO */
101         char *buf;
102 };
103
104 static void chaoskey_free(struct chaoskey *dev)
105 {
106         if (dev) {
107                 usb_dbg(dev->interface, "free");
108                 usb_free_urb(dev->urb);
109                 kfree(dev->name);
110                 kfree(dev->buf);
111                 usb_put_intf(dev->interface);
112                 kfree(dev);
113         }
114 }
115
116 static int chaoskey_probe(struct usb_interface *interface,
117                           const struct usb_device_id *id)
118 {
119         struct usb_device *udev = interface_to_usbdev(interface);
120         struct usb_host_interface *altsetting = interface->cur_altsetting;
121         int i;
122         int in_ep = -1;
123         struct chaoskey *dev;
124         int result = -ENOMEM;
125         int size;
126
127         usb_dbg(interface, "probe %s-%s", udev->product, udev->serial);
128
129         /* Find the first bulk IN endpoint and its packet size */
130         for (i = 0; i < altsetting->desc.bNumEndpoints; i++) {
131                 if (usb_endpoint_is_bulk_in(&altsetting->endpoint[i].desc)) {
132                         in_ep = usb_endpoint_num(&altsetting->endpoint[i].desc);
133                         size = usb_endpoint_maxp(&altsetting->endpoint[i].desc);
134                         break;
135                 }
136         }
137
138         /* Validate endpoint and size */
139         if (in_ep == -1) {
140                 usb_dbg(interface, "no IN endpoint found");
141                 return -ENODEV;
142         }
143         if (size <= 0) {
144                 usb_dbg(interface, "invalid size (%d)", size);
145                 return -ENODEV;
146         }
147
148         if (size > CHAOSKEY_BUF_LEN) {
149                 usb_dbg(interface, "size reduced from %d to %d\n",
150                         size, CHAOSKEY_BUF_LEN);
151                 size = CHAOSKEY_BUF_LEN;
152         }
153
154         /* Looks good, allocate and initialize */
155
156         dev = kzalloc(sizeof(struct chaoskey), GFP_KERNEL);
157
158         if (dev == NULL)
159                 goto out;
160
161         dev->interface = usb_get_intf(interface);
162
163         dev->buf = kmalloc(size, GFP_KERNEL);
164
165         if (dev->buf == NULL)
166                 goto out;
167
168         dev->urb = usb_alloc_urb(0, GFP_KERNEL);
169
170         if (!dev->urb)
171                 goto out;
172
173         usb_fill_bulk_urb(dev->urb,
174                 udev,
175                 usb_rcvbulkpipe(udev, in_ep),
176                 dev->buf,
177                 size,
178                 chaos_read_callback,
179                 dev);
180
181         /* Construct a name using the product and serial values. Each
182          * device needs a unique name for the hwrng code
183          */
184
185         if (udev->product && udev->serial) {
186                 dev->name = kmalloc(strlen(udev->product) + 1 +
187                                     strlen(udev->serial) + 1, GFP_KERNEL);
188                 if (dev->name == NULL)
189                         goto out;
190
191                 strcpy(dev->name, udev->product);
192                 strcat(dev->name, "-");
193                 strcat(dev->name, udev->serial);
194         }
195
196         dev->in_ep = in_ep;
197
198         if (le16_to_cpu(udev->descriptor.idVendor) != ALEA_VENDOR_ID)
199                 dev->reads_started = 1;
200
201         dev->size = size;
202         dev->present = 1;
203
204         init_waitqueue_head(&dev->wait_q);
205
206         mutex_init(&dev->lock);
207         mutex_init(&dev->rng_lock);
208
209         usb_set_intfdata(interface, dev);
210
211         result = usb_register_dev(interface, &chaoskey_class);
212         if (result) {
213                 usb_err(interface, "Unable to allocate minor number.");
214                 goto out;
215         }
216
217         dev->hwrng.name = dev->name ? dev->name : chaoskey_driver.name;
218         dev->hwrng.read = chaoskey_rng_read;
219
220         /* Set the 'quality' metric.  Quality is measured in units of
221          * 1/1024's of a bit ("mills"). This should be set to 1024,
222          * but there is a bug in the hwrng core which masks it with
223          * 1023.
224          *
225          * The patch that has been merged to the crypto development
226          * tree for that bug limits the value to 1024 at most, so by
227          * setting this to 1024 + 1023, we get 1023 before the fix is
228          * merged and 1024 afterwards. We'll patch this driver once
229          * both bits of code are in the same tree.
230          */
231         dev->hwrng.quality = 1024 + 1023;
232
233         dev->hwrng_registered = (hwrng_register(&dev->hwrng) == 0);
234         if (!dev->hwrng_registered)
235                 usb_err(interface, "Unable to register with hwrng");
236
237         usb_enable_autosuspend(udev);
238
239         usb_dbg(interface, "chaoskey probe success, size %d", dev->size);
240         return 0;
241
242 out:
243         usb_set_intfdata(interface, NULL);
244         chaoskey_free(dev);
245         return result;
246 }
247
248 static void chaoskey_disconnect(struct usb_interface *interface)
249 {
250         struct chaoskey *dev;
251
252         usb_dbg(interface, "disconnect");
253         dev = usb_get_intfdata(interface);
254         if (!dev) {
255                 usb_dbg(interface, "disconnect failed - no dev");
256                 return;
257         }
258
259         if (dev->hwrng_registered)
260                 hwrng_unregister(&dev->hwrng);
261
262         usb_deregister_dev(interface, &chaoskey_class);
263
264         usb_set_intfdata(interface, NULL);
265         mutex_lock(&dev->lock);
266
267         dev->present = 0;
268         usb_poison_urb(dev->urb);
269
270         if (!dev->open) {
271                 mutex_unlock(&dev->lock);
272                 chaoskey_free(dev);
273         } else
274                 mutex_unlock(&dev->lock);
275
276         usb_dbg(interface, "disconnect done");
277 }
278
279 static int chaoskey_open(struct inode *inode, struct file *file)
280 {
281         struct chaoskey *dev;
282         struct usb_interface *interface;
283
284         /* get the interface from minor number and driver information */
285         interface = usb_find_interface(&chaoskey_driver, iminor(inode));
286         if (!interface)
287                 return -ENODEV;
288
289         usb_dbg(interface, "open");
290
291         dev = usb_get_intfdata(interface);
292         if (!dev) {
293                 usb_dbg(interface, "open (dev)");
294                 return -ENODEV;
295         }
296
297         file->private_data = dev;
298         mutex_lock(&dev->lock);
299         ++dev->open;
300         mutex_unlock(&dev->lock);
301
302         usb_dbg(interface, "open success");
303         return 0;
304 }
305
306 static int chaoskey_release(struct inode *inode, struct file *file)
307 {
308         struct chaoskey *dev = file->private_data;
309         struct usb_interface *interface;
310
311         if (dev == NULL)
312                 return -ENODEV;
313
314         interface = dev->interface;
315
316         usb_dbg(interface, "release");
317
318         mutex_lock(&dev->lock);
319
320         usb_dbg(interface, "open count at release is %d", dev->open);
321
322         if (dev->open <= 0) {
323                 usb_dbg(interface, "invalid open count (%d)", dev->open);
324                 mutex_unlock(&dev->lock);
325                 return -ENODEV;
326         }
327
328         --dev->open;
329
330         if (!dev->present) {
331                 if (dev->open == 0) {
332                         mutex_unlock(&dev->lock);
333                         chaoskey_free(dev);
334                 } else
335                         mutex_unlock(&dev->lock);
336         } else
337                 mutex_unlock(&dev->lock);
338
339         usb_dbg(interface, "release success");
340         return 0;
341 }
342
343 static void chaos_read_callback(struct urb *urb)
344 {
345         struct chaoskey *dev = urb->context;
346         int status = urb->status;
347
348         usb_dbg(dev->interface, "callback status (%d)", status);
349
350         if (status == 0)
351                 dev->valid = urb->actual_length;
352         else
353                 dev->valid = 0;
354
355         dev->used = 0;
356
357         /* must be seen first before validity is announced */
358         smp_wmb();
359
360         dev->reading = false;
361         wake_up(&dev->wait_q);
362 }
363
364 /* Fill the buffer. Called with dev->lock held
365  */
366 static int _chaoskey_fill(struct chaoskey *dev)
367 {
368         DEFINE_WAIT(wait);
369         int result;
370         bool started;
371
372         usb_dbg(dev->interface, "fill");
373
374         /* Return immediately if someone called before the buffer was
375          * empty */
376         if (dev->valid != dev->used) {
377                 usb_dbg(dev->interface, "not empty yet (valid %d used %d)",
378                         dev->valid, dev->used);
379                 return 0;
380         }
381
382         /* Bail if the device has been removed */
383         if (!dev->present) {
384                 usb_dbg(dev->interface, "device not present");
385                 return -ENODEV;
386         }
387
388         /* Make sure the device is awake */
389         result = usb_autopm_get_interface(dev->interface);
390         if (result) {
391                 usb_dbg(dev->interface, "wakeup failed (result %d)", result);
392                 return result;
393         }
394
395         dev->reading = true;
396         result = usb_submit_urb(dev->urb, GFP_KERNEL);
397         if (result < 0) {
398                 result = usb_translate_errors(result);
399                 dev->reading = false;
400                 goto out;
401         }
402
403         /* The first read on the Alea takes a little under 2 seconds.
404          * Reads after the first read take only a few microseconds
405          * though.  Presumably the entropy-generating circuit needs
406          * time to ramp up.  So, we wait longer on the first read.
407          */
408         started = dev->reads_started;
409         dev->reads_started = true;
410         result = wait_event_interruptible_timeout(
411                 dev->wait_q,
412                 !dev->reading,
413                 (started ? NAK_TIMEOUT : ALEA_FIRST_TIMEOUT) );
414
415         if (result < 0) {
416                 usb_kill_urb(dev->urb);
417                 goto out;
418         }
419
420         if (result == 0) {
421                 result = -ETIMEDOUT;
422                 usb_kill_urb(dev->urb);
423         } else {
424                 result = dev->valid;
425         }
426 out:
427         /* Let the device go back to sleep eventually */
428         usb_autopm_put_interface(dev->interface);
429
430         usb_dbg(dev->interface, "read %d bytes", dev->valid);
431
432         return result;
433 }
434
435 static ssize_t chaoskey_read(struct file *file,
436                              char __user *buffer,
437                              size_t count,
438                              loff_t *ppos)
439 {
440         struct chaoskey *dev;
441         ssize_t read_count = 0;
442         int this_time;
443         int result = 0;
444         unsigned long remain;
445
446         dev = file->private_data;
447
448         if (dev == NULL || !dev->present)
449                 return -ENODEV;
450
451         usb_dbg(dev->interface, "read %zu", count);
452
453         while (count > 0) {
454
455                 /* Grab the rng_lock briefly to ensure that the hwrng interface
456                  * gets priority over other user access
457                  */
458                 result = mutex_lock_interruptible(&dev->rng_lock);
459                 if (result)
460                         goto bail;
461                 mutex_unlock(&dev->rng_lock);
462
463                 result = mutex_lock_interruptible(&dev->lock);
464                 if (result)
465                         goto bail;
466                 if (dev->valid == dev->used) {
467                         result = _chaoskey_fill(dev);
468                         if (result < 0) {
469                                 mutex_unlock(&dev->lock);
470                                 goto bail;
471                         }
472                 }
473
474                 this_time = dev->valid - dev->used;
475                 if (this_time > count)
476                         this_time = count;
477
478                 remain = copy_to_user(buffer, dev->buf + dev->used, this_time);
479                 if (remain) {
480                         result = -EFAULT;
481
482                         /* Consume the bytes that were copied so we don't leak
483                          * data to user space
484                          */
485                         dev->used += this_time - remain;
486                         mutex_unlock(&dev->lock);
487                         goto bail;
488                 }
489
490                 count -= this_time;
491                 read_count += this_time;
492                 buffer += this_time;
493                 dev->used += this_time;
494                 mutex_unlock(&dev->lock);
495         }
496 bail:
497         if (read_count) {
498                 usb_dbg(dev->interface, "read %zu bytes", read_count);
499                 return read_count;
500         }
501         usb_dbg(dev->interface, "empty read, result %d", result);
502         if (result == -ETIMEDOUT)
503                 result = -EAGAIN;
504         return result;
505 }
506
507 static int chaoskey_rng_read(struct hwrng *rng, void *data,
508                              size_t max, bool wait)
509 {
510         struct chaoskey *dev = container_of(rng, struct chaoskey, hwrng);
511         int this_time;
512
513         usb_dbg(dev->interface, "rng_read max %zu wait %d", max, wait);
514
515         if (!dev->present) {
516                 usb_dbg(dev->interface, "device not present");
517                 return 0;
518         }
519
520         /* Hold the rng_lock until we acquire the device lock so that
521          * this operation gets priority over other user access to the
522          * device
523          */
524         mutex_lock(&dev->rng_lock);
525
526         mutex_lock(&dev->lock);
527
528         mutex_unlock(&dev->rng_lock);
529
530         /* Try to fill the buffer if empty. It doesn't actually matter
531          * if _chaoskey_fill works; we'll just return zero bytes as
532          * the buffer will still be empty
533          */
534         if (dev->valid == dev->used)
535                 (void) _chaoskey_fill(dev);
536
537         this_time = dev->valid - dev->used;
538         if (this_time > max)
539                 this_time = max;
540
541         memcpy(data, dev->buf + dev->used, this_time);
542
543         dev->used += this_time;
544
545         mutex_unlock(&dev->lock);
546
547         usb_dbg(dev->interface, "rng_read this_time %d\n", this_time);
548         return this_time;
549 }
550
551 #ifdef CONFIG_PM
552 static int chaoskey_suspend(struct usb_interface *interface,
553                             pm_message_t message)
554 {
555         usb_dbg(interface, "suspend");
556         return 0;
557 }
558
559 static int chaoskey_resume(struct usb_interface *interface)
560 {
561         struct chaoskey *dev;
562         struct usb_device *udev = interface_to_usbdev(interface);
563
564         usb_dbg(interface, "resume");
565         dev = usb_get_intfdata(interface);
566
567         /*
568          * We may have lost power.
569          * In that case the device that needs a long time
570          * for the first requests needs an extended timeout
571          * again
572          */
573         if (le16_to_cpu(udev->descriptor.idVendor) == ALEA_VENDOR_ID)
574                 dev->reads_started = false;
575
576         return 0;
577 }
578 #else
579 #define chaoskey_suspend NULL
580 #define chaoskey_resume NULL
581 #endif
582
583 /* file operation pointers */
584 static const struct file_operations chaoskey_fops = {
585         .owner = THIS_MODULE,
586         .read = chaoskey_read,
587         .open = chaoskey_open,
588         .release = chaoskey_release,
589         .llseek = default_llseek,
590 };
591
592 /* class driver information */
593 static struct usb_class_driver chaoskey_class = {
594         .name = "chaoskey%d",
595         .fops = &chaoskey_fops,
596         .minor_base = USB_CHAOSKEY_MINOR_BASE,
597 };
598
599 /* usb specific object needed to register this driver with the usb subsystem */
600 static struct usb_driver chaoskey_driver = {
601         .name = DRIVER_SHORT,
602         .probe = chaoskey_probe,
603         .disconnect = chaoskey_disconnect,
604         .suspend = chaoskey_suspend,
605         .resume = chaoskey_resume,
606         .reset_resume = chaoskey_resume,
607         .id_table = chaoskey_table,
608         .supports_autosuspend = 1,
609 };
610
611 module_usb_driver(chaoskey_driver);
612