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