2 * hw_random/core.c: HWRNG core API
4 * Copyright 2006 Michael Buesch <m@bues.ch>
5 * Copyright 2005 (c) MontaVista Software, Inc.
7 * Please read Documentation/admin-guide/hw_random.rst for details on use.
9 * This software may be used and distributed according to the terms
10 * of the GNU General Public License, incorporated herein by reference.
13 #include <linux/delay.h>
14 #include <linux/device.h>
15 #include <linux/err.h>
17 #include <linux/hw_random.h>
18 #include <linux/kernel.h>
19 #include <linux/kthread.h>
20 #include <linux/miscdevice.h>
21 #include <linux/module.h>
22 #include <linux/random.h>
23 #include <linux/sched.h>
24 #include <linux/sched/signal.h>
25 #include <linux/slab.h>
26 #include <linux/uaccess.h>
28 #define RNG_MODULE_NAME "hw_random"
30 static struct hwrng *current_rng;
31 /* the current rng has been explicitly chosen by user via sysfs */
32 static int cur_rng_set_by_user;
33 static struct task_struct *hwrng_fill;
34 /* list of registered rngs */
35 static LIST_HEAD(rng_list);
36 /* Protects rng_list and current_rng */
37 static DEFINE_MUTEX(rng_mutex);
38 /* Protects rng read functions, data_avail, rng_buffer and rng_fillbuf */
39 static DEFINE_MUTEX(reading_mutex);
40 static int data_avail;
41 static u8 *rng_buffer, *rng_fillbuf;
42 static unsigned short current_quality;
43 static unsigned short default_quality = 1024; /* default to maximum */
45 module_param(current_quality, ushort, 0644);
46 MODULE_PARM_DESC(current_quality,
47 "current hwrng entropy estimation per 1024 bits of input -- obsolete, use rng_quality instead");
48 module_param(default_quality, ushort, 0644);
49 MODULE_PARM_DESC(default_quality,
50 "default maximum entropy content of hwrng per 1024 bits of input");
52 static void drop_current_rng(void);
53 static int hwrng_init(struct hwrng *rng);
54 static int hwrng_fillfn(void *unused);
56 static inline int rng_get_data(struct hwrng *rng, u8 *buffer, size_t size,
59 static size_t rng_buffer_size(void)
61 return SMP_CACHE_BYTES < 32 ? 32 : SMP_CACHE_BYTES;
64 static void add_early_randomness(struct hwrng *rng)
68 mutex_lock(&reading_mutex);
69 bytes_read = rng_get_data(rng, rng_fillbuf, 32, 0);
70 mutex_unlock(&reading_mutex);
72 size_t entropy = bytes_read * 8 * rng->quality / 1024;
73 add_hwgenerator_randomness(rng_fillbuf, bytes_read, entropy, false);
77 static inline void cleanup_rng(struct kref *kref)
79 struct hwrng *rng = container_of(kref, struct hwrng, ref);
84 complete(&rng->cleanup_done);
87 static int set_current_rng(struct hwrng *rng)
91 BUG_ON(!mutex_is_locked(&rng_mutex));
93 err = hwrng_init(rng);
100 /* if necessary, start hwrng thread */
102 hwrng_fill = kthread_run(hwrng_fillfn, NULL, "hwrng");
103 if (IS_ERR(hwrng_fill)) {
104 pr_err("hwrng_fill thread creation failed\n");
112 static void drop_current_rng(void)
114 BUG_ON(!mutex_is_locked(&rng_mutex));
118 /* decrease last reference for triggering the cleanup */
119 kref_put(¤t_rng->ref, cleanup_rng);
123 /* Returns ERR_PTR(), NULL or refcounted hwrng */
124 static struct hwrng *get_current_rng_nolock(void)
127 kref_get(¤t_rng->ref);
132 static struct hwrng *get_current_rng(void)
136 if (mutex_lock_interruptible(&rng_mutex))
137 return ERR_PTR(-ERESTARTSYS);
139 rng = get_current_rng_nolock();
141 mutex_unlock(&rng_mutex);
145 static void put_rng(struct hwrng *rng)
148 * Hold rng_mutex here so we serialize in case they set_current_rng
149 * on rng again immediately.
151 mutex_lock(&rng_mutex);
153 kref_put(&rng->ref, cleanup_rng);
154 mutex_unlock(&rng_mutex);
157 static int hwrng_init(struct hwrng *rng)
159 if (kref_get_unless_zero(&rng->ref))
165 ret = rng->init(rng);
170 kref_init(&rng->ref);
171 reinit_completion(&rng->cleanup_done);
174 rng->quality = min_t(u16, min_t(u16, default_quality, 1024), rng->quality ?: 1024);
175 current_quality = rng->quality; /* obsolete */
180 static int rng_dev_open(struct inode *inode, struct file *filp)
182 /* enforce read-only access to this chrdev */
183 if ((filp->f_mode & FMODE_READ) == 0)
185 if (filp->f_mode & FMODE_WRITE)
190 static inline int rng_get_data(struct hwrng *rng, u8 *buffer, size_t size,
194 BUG_ON(!mutex_is_locked(&reading_mutex));
196 return rng->read(rng, (void *)buffer, size, wait);
198 if (rng->data_present)
199 present = rng->data_present(rng, wait);
204 return rng->data_read(rng, (u32 *)buffer);
209 static ssize_t rng_dev_read(struct file *filp, char __user *buf,
210 size_t size, loff_t *offp)
218 rng = get_current_rng();
228 if (mutex_lock_interruptible(&reading_mutex)) {
233 bytes_read = rng_get_data(rng, rng_buffer,
235 !(filp->f_flags & O_NONBLOCK));
236 if (bytes_read < 0) {
238 goto out_unlock_reading;
240 data_avail = bytes_read;
244 if (filp->f_flags & O_NONBLOCK) {
246 goto out_unlock_reading;
255 if (copy_to_user(buf + ret, rng_buffer + data_avail,
258 goto out_unlock_reading;
265 mutex_unlock(&reading_mutex);
269 schedule_timeout_interruptible(1);
271 if (signal_pending(current)) {
280 mutex_unlock(&reading_mutex);
286 static const struct file_operations rng_chrdev_ops = {
287 .owner = THIS_MODULE,
288 .open = rng_dev_open,
289 .read = rng_dev_read,
290 .llseek = noop_llseek,
293 static const struct attribute_group *rng_dev_groups[];
295 static struct miscdevice rng_miscdev = {
296 .minor = HWRNG_MINOR,
297 .name = RNG_MODULE_NAME,
299 .fops = &rng_chrdev_ops,
300 .groups = rng_dev_groups,
303 static int enable_best_rng(void)
305 struct hwrng *rng, *new_rng = NULL;
308 BUG_ON(!mutex_is_locked(&rng_mutex));
311 if (list_empty(&rng_list)) {
313 cur_rng_set_by_user = 0;
317 /* use the rng which offers the best quality */
318 list_for_each_entry(rng, &rng_list, list) {
319 if (!new_rng || rng->quality > new_rng->quality)
323 ret = ((new_rng == current_rng) ? 0 : set_current_rng(new_rng));
325 cur_rng_set_by_user = 0;
330 static ssize_t rng_current_store(struct device *dev,
331 struct device_attribute *attr,
332 const char *buf, size_t len)
335 struct hwrng *rng, *old_rng, *new_rng;
337 err = mutex_lock_interruptible(&rng_mutex);
341 old_rng = current_rng;
342 if (sysfs_streq(buf, "")) {
343 err = enable_best_rng();
345 list_for_each_entry(rng, &rng_list, list) {
346 if (sysfs_streq(rng->name, buf)) {
347 err = set_current_rng(rng);
349 cur_rng_set_by_user = 1;
354 new_rng = get_current_rng_nolock();
355 mutex_unlock(&rng_mutex);
358 if (new_rng != old_rng)
359 add_early_randomness(new_rng);
366 static ssize_t rng_current_show(struct device *dev,
367 struct device_attribute *attr,
373 rng = get_current_rng();
377 ret = snprintf(buf, PAGE_SIZE, "%s\n", rng ? rng->name : "none");
383 static ssize_t rng_available_show(struct device *dev,
384 struct device_attribute *attr,
390 err = mutex_lock_interruptible(&rng_mutex);
394 list_for_each_entry(rng, &rng_list, list) {
395 strlcat(buf, rng->name, PAGE_SIZE);
396 strlcat(buf, " ", PAGE_SIZE);
398 strlcat(buf, "\n", PAGE_SIZE);
399 mutex_unlock(&rng_mutex);
404 static ssize_t rng_selected_show(struct device *dev,
405 struct device_attribute *attr,
408 return sysfs_emit(buf, "%d\n", cur_rng_set_by_user);
411 static ssize_t rng_quality_show(struct device *dev,
412 struct device_attribute *attr,
418 rng = get_current_rng();
422 if (!rng) /* no need to put_rng */
425 ret = sysfs_emit(buf, "%hu\n", rng->quality);
431 static ssize_t rng_quality_store(struct device *dev,
432 struct device_attribute *attr,
433 const char *buf, size_t len)
441 ret = mutex_lock_interruptible(&rng_mutex);
445 ret = kstrtou16(buf, 0, &quality);
446 if (ret || quality > 1024) {
456 current_rng->quality = quality;
457 current_quality = quality; /* obsolete */
459 /* the best available RNG may have changed */
460 ret = enable_best_rng();
463 mutex_unlock(&rng_mutex);
464 return ret ? ret : len;
467 static DEVICE_ATTR_RW(rng_current);
468 static DEVICE_ATTR_RO(rng_available);
469 static DEVICE_ATTR_RO(rng_selected);
470 static DEVICE_ATTR_RW(rng_quality);
472 static struct attribute *rng_dev_attrs[] = {
473 &dev_attr_rng_current.attr,
474 &dev_attr_rng_available.attr,
475 &dev_attr_rng_selected.attr,
476 &dev_attr_rng_quality.attr,
480 ATTRIBUTE_GROUPS(rng_dev);
482 static void __exit unregister_miscdev(void)
484 misc_deregister(&rng_miscdev);
487 static int __init register_miscdev(void)
489 return misc_register(&rng_miscdev);
492 static int hwrng_fillfn(void *unused)
494 size_t entropy, entropy_credit = 0; /* in 1/1024 of a bit */
497 while (!kthread_should_stop()) {
498 unsigned short quality;
501 rng = get_current_rng();
502 if (IS_ERR(rng) || !rng)
504 mutex_lock(&reading_mutex);
505 rc = rng_get_data(rng, rng_fillbuf,
506 rng_buffer_size(), 1);
507 if (current_quality != rng->quality)
508 rng->quality = current_quality; /* obsolete */
509 quality = rng->quality;
510 mutex_unlock(&reading_mutex);
513 hwrng_msleep(rng, 10000);
520 /* If we cannot credit at least one bit of entropy,
521 * keep track of the remainder for the next iteration
523 entropy = rc * quality * 8 + entropy_credit;
524 if ((entropy >> 10) == 0)
525 entropy_credit = entropy;
527 /* Outside lock, sure, but y'know: randomness. */
528 add_hwgenerator_randomness((void *)rng_fillbuf, rc,
529 entropy >> 10, true);
535 int hwrng_register(struct hwrng *rng)
539 bool is_new_current = false;
541 if (!rng->name || (!rng->data_read && !rng->read))
544 mutex_lock(&rng_mutex);
546 /* Must not register two RNGs with the same name. */
548 list_for_each_entry(tmp, &rng_list, list) {
549 if (strcmp(tmp->name, rng->name) == 0)
552 list_add_tail(&rng->list, &rng_list);
554 init_completion(&rng->cleanup_done);
555 complete(&rng->cleanup_done);
556 init_completion(&rng->dying);
559 (!cur_rng_set_by_user && rng->quality > current_rng->quality)) {
561 * Set new rng as current as the new rng source
562 * provides better entropy quality and was not
563 * chosen by userspace.
565 err = set_current_rng(rng);
568 /* to use current_rng in add_early_randomness() we need
571 is_new_current = true;
574 mutex_unlock(&rng_mutex);
575 if (is_new_current || !rng->init) {
577 * Use a new device's input to add some randomness to
578 * the system. If this rng device isn't going to be
579 * used right away, its init function hasn't been
580 * called yet by set_current_rng(); so only use the
581 * randomness from devices that don't need an init callback
583 add_early_randomness(rng);
589 mutex_unlock(&rng_mutex);
593 EXPORT_SYMBOL_GPL(hwrng_register);
595 void hwrng_unregister(struct hwrng *rng)
597 struct hwrng *old_rng, *new_rng;
600 mutex_lock(&rng_mutex);
602 old_rng = current_rng;
603 list_del(&rng->list);
604 complete_all(&rng->dying);
605 if (current_rng == rng) {
606 err = enable_best_rng();
609 cur_rng_set_by_user = 0;
613 new_rng = get_current_rng_nolock();
614 if (list_empty(&rng_list)) {
615 mutex_unlock(&rng_mutex);
617 kthread_stop(hwrng_fill);
619 mutex_unlock(&rng_mutex);
622 if (old_rng != new_rng)
623 add_early_randomness(new_rng);
627 wait_for_completion(&rng->cleanup_done);
629 EXPORT_SYMBOL_GPL(hwrng_unregister);
631 static void devm_hwrng_release(struct device *dev, void *res)
633 hwrng_unregister(*(struct hwrng **)res);
636 static int devm_hwrng_match(struct device *dev, void *res, void *data)
638 struct hwrng **r = res;
640 if (WARN_ON(!r || !*r))
646 int devm_hwrng_register(struct device *dev, struct hwrng *rng)
651 ptr = devres_alloc(devm_hwrng_release, sizeof(*ptr), GFP_KERNEL);
655 error = hwrng_register(rng);
662 devres_add(dev, ptr);
665 EXPORT_SYMBOL_GPL(devm_hwrng_register);
667 void devm_hwrng_unregister(struct device *dev, struct hwrng *rng)
669 devres_release(dev, devm_hwrng_release, devm_hwrng_match, rng);
671 EXPORT_SYMBOL_GPL(devm_hwrng_unregister);
673 long hwrng_msleep(struct hwrng *rng, unsigned int msecs)
675 unsigned long timeout = msecs_to_jiffies(msecs) + 1;
677 return wait_for_completion_interruptible_timeout(&rng->dying, timeout);
679 EXPORT_SYMBOL_GPL(hwrng_msleep);
681 long hwrng_yield(struct hwrng *rng)
683 return wait_for_completion_interruptible_timeout(&rng->dying, 1);
685 EXPORT_SYMBOL_GPL(hwrng_yield);
687 static int __init hwrng_modinit(void)
691 /* kmalloc makes this safe for virt_to_page() in virtio_rng.c */
692 rng_buffer = kmalloc(rng_buffer_size(), GFP_KERNEL);
696 rng_fillbuf = kmalloc(rng_buffer_size(), GFP_KERNEL);
702 ret = register_miscdev();
711 static void __exit hwrng_modexit(void)
713 mutex_lock(&rng_mutex);
717 mutex_unlock(&rng_mutex);
719 unregister_miscdev();
722 fs_initcall(hwrng_modinit); /* depends on misc_register() */
723 module_exit(hwrng_modexit);
725 MODULE_DESCRIPTION("H/W Random Number Generator (RNG) driver");
726 MODULE_LICENSE("GPL");