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/random.h>
19 #include <linux/kernel.h>
20 #include <linux/kthread.h>
21 #include <linux/sched/signal.h>
22 #include <linux/miscdevice.h>
23 #include <linux/module.h>
24 #include <linux/random.h>
25 #include <linux/sched.h>
26 #include <linux/slab.h>
27 #include <linux/uaccess.h>
29 #define RNG_MODULE_NAME "hw_random"
31 static struct hwrng *current_rng;
32 /* the current rng has been explicitly chosen by user via sysfs */
33 static int cur_rng_set_by_user;
34 static struct task_struct *hwrng_fill;
35 /* list of registered rngs */
36 static LIST_HEAD(rng_list);
37 /* Protects rng_list and current_rng */
38 static DEFINE_MUTEX(rng_mutex);
39 /* Protects rng read functions, data_avail, rng_buffer and rng_fillbuf */
40 static DEFINE_MUTEX(reading_mutex);
41 static int data_avail;
42 static u8 *rng_buffer, *rng_fillbuf;
43 static unsigned short current_quality;
44 static unsigned short default_quality; /* = 0; default to "off" */
46 module_param(current_quality, ushort, 0644);
47 MODULE_PARM_DESC(current_quality,
48 "current hwrng entropy estimation per 1024 bits of input -- obsolete, use rng_quality instead");
49 module_param(default_quality, ushort, 0644);
50 MODULE_PARM_DESC(default_quality,
51 "default entropy content of hwrng per 1024 bits of input");
53 static void drop_current_rng(void);
54 static int hwrng_init(struct hwrng *rng);
55 static void hwrng_manage_rngd(struct hwrng *rng);
57 static inline int rng_get_data(struct hwrng *rng, u8 *buffer, size_t size,
60 static size_t rng_buffer_size(void)
62 return SMP_CACHE_BYTES < 32 ? 32 : SMP_CACHE_BYTES;
65 static void add_early_randomness(struct hwrng *rng)
69 mutex_lock(&reading_mutex);
70 bytes_read = rng_get_data(rng, rng_fillbuf, 32, 0);
71 mutex_unlock(&reading_mutex);
73 add_device_randomness(rng_fillbuf, bytes_read);
76 static inline void cleanup_rng(struct kref *kref)
78 struct hwrng *rng = container_of(kref, struct hwrng, ref);
83 complete(&rng->cleanup_done);
86 static int set_current_rng(struct hwrng *rng)
90 BUG_ON(!mutex_is_locked(&rng_mutex));
92 err = hwrng_init(rng);
102 static void drop_current_rng(void)
104 BUG_ON(!mutex_is_locked(&rng_mutex));
108 /* decrease last reference for triggering the cleanup */
109 kref_put(¤t_rng->ref, cleanup_rng);
113 /* Returns ERR_PTR(), NULL or refcounted hwrng */
114 static struct hwrng *get_current_rng_nolock(void)
117 kref_get(¤t_rng->ref);
122 static struct hwrng *get_current_rng(void)
126 if (mutex_lock_interruptible(&rng_mutex))
127 return ERR_PTR(-ERESTARTSYS);
129 rng = get_current_rng_nolock();
131 mutex_unlock(&rng_mutex);
135 static void put_rng(struct hwrng *rng)
138 * Hold rng_mutex here so we serialize in case they set_current_rng
139 * on rng again immediately.
141 mutex_lock(&rng_mutex);
143 kref_put(&rng->ref, cleanup_rng);
144 mutex_unlock(&rng_mutex);
147 static int hwrng_init(struct hwrng *rng)
149 if (kref_get_unless_zero(&rng->ref))
155 ret = rng->init(rng);
160 kref_init(&rng->ref);
161 reinit_completion(&rng->cleanup_done);
165 rng->quality = default_quality;
166 if (rng->quality > 1024)
168 current_quality = rng->quality; /* obsolete */
170 hwrng_manage_rngd(rng);
175 static int rng_dev_open(struct inode *inode, struct file *filp)
177 /* enforce read-only access to this chrdev */
178 if ((filp->f_mode & FMODE_READ) == 0)
180 if (filp->f_mode & FMODE_WRITE)
185 static inline int rng_get_data(struct hwrng *rng, u8 *buffer, size_t size,
189 BUG_ON(!mutex_is_locked(&reading_mutex));
191 return rng->read(rng, (void *)buffer, size, wait);
193 if (rng->data_present)
194 present = rng->data_present(rng, wait);
199 return rng->data_read(rng, (u32 *)buffer);
204 static ssize_t rng_dev_read(struct file *filp, char __user *buf,
205 size_t size, loff_t *offp)
213 rng = get_current_rng();
223 if (mutex_lock_interruptible(&reading_mutex)) {
228 bytes_read = rng_get_data(rng, rng_buffer,
230 !(filp->f_flags & O_NONBLOCK));
231 if (bytes_read < 0) {
233 goto out_unlock_reading;
235 data_avail = bytes_read;
239 if (filp->f_flags & O_NONBLOCK) {
241 goto out_unlock_reading;
250 if (copy_to_user(buf + ret, rng_buffer + data_avail,
253 goto out_unlock_reading;
260 mutex_unlock(&reading_mutex);
264 schedule_timeout_interruptible(1);
266 if (signal_pending(current)) {
275 mutex_unlock(&reading_mutex);
281 static const struct file_operations rng_chrdev_ops = {
282 .owner = THIS_MODULE,
283 .open = rng_dev_open,
284 .read = rng_dev_read,
285 .llseek = noop_llseek,
288 static const struct attribute_group *rng_dev_groups[];
290 static struct miscdevice rng_miscdev = {
291 .minor = HWRNG_MINOR,
292 .name = RNG_MODULE_NAME,
294 .fops = &rng_chrdev_ops,
295 .groups = rng_dev_groups,
298 static int enable_best_rng(void)
300 struct hwrng *rng, *new_rng = NULL;
303 BUG_ON(!mutex_is_locked(&rng_mutex));
306 if (list_empty(&rng_list)) {
308 cur_rng_set_by_user = 0;
312 /* use the rng which offers the best quality */
313 list_for_each_entry(rng, &rng_list, list) {
314 if (!new_rng || rng->quality > new_rng->quality)
318 ret = ((new_rng == current_rng) ? 0 : set_current_rng(new_rng));
320 cur_rng_set_by_user = 0;
325 static ssize_t rng_current_store(struct device *dev,
326 struct device_attribute *attr,
327 const char *buf, size_t len)
330 struct hwrng *rng, *old_rng, *new_rng;
332 err = mutex_lock_interruptible(&rng_mutex);
336 old_rng = current_rng;
337 if (sysfs_streq(buf, "")) {
338 err = enable_best_rng();
340 list_for_each_entry(rng, &rng_list, list) {
341 if (sysfs_streq(rng->name, buf)) {
342 err = set_current_rng(rng);
344 cur_rng_set_by_user = 1;
349 new_rng = get_current_rng_nolock();
350 mutex_unlock(&rng_mutex);
353 if (new_rng != old_rng)
354 add_early_randomness(new_rng);
361 static ssize_t rng_current_show(struct device *dev,
362 struct device_attribute *attr,
368 rng = get_current_rng();
372 ret = snprintf(buf, PAGE_SIZE, "%s\n", rng ? rng->name : "none");
378 static ssize_t rng_available_show(struct device *dev,
379 struct device_attribute *attr,
385 err = mutex_lock_interruptible(&rng_mutex);
389 list_for_each_entry(rng, &rng_list, list) {
390 strlcat(buf, rng->name, PAGE_SIZE);
391 strlcat(buf, " ", PAGE_SIZE);
393 strlcat(buf, "\n", PAGE_SIZE);
394 mutex_unlock(&rng_mutex);
399 static ssize_t rng_selected_show(struct device *dev,
400 struct device_attribute *attr,
403 return sysfs_emit(buf, "%d\n", cur_rng_set_by_user);
406 static ssize_t rng_quality_show(struct device *dev,
407 struct device_attribute *attr,
413 rng = get_current_rng();
417 if (!rng) /* no need to put_rng */
420 ret = sysfs_emit(buf, "%hu\n", rng->quality);
426 static ssize_t rng_quality_store(struct device *dev,
427 struct device_attribute *attr,
428 const char *buf, size_t len)
436 ret = mutex_lock_interruptible(&rng_mutex);
440 ret = kstrtou16(buf, 0, &quality);
441 if (ret || quality > 1024) {
451 current_rng->quality = quality;
452 current_quality = quality; /* obsolete */
454 /* the best available RNG may have changed */
455 ret = enable_best_rng();
457 /* start/stop rngd if necessary */
459 hwrng_manage_rngd(current_rng);
462 mutex_unlock(&rng_mutex);
463 return ret ? ret : len;
466 static DEVICE_ATTR_RW(rng_current);
467 static DEVICE_ATTR_RO(rng_available);
468 static DEVICE_ATTR_RO(rng_selected);
469 static DEVICE_ATTR_RW(rng_quality);
471 static struct attribute *rng_dev_attrs[] = {
472 &dev_attr_rng_current.attr,
473 &dev_attr_rng_available.attr,
474 &dev_attr_rng_selected.attr,
475 &dev_attr_rng_quality.attr,
479 ATTRIBUTE_GROUPS(rng_dev);
481 static void __exit unregister_miscdev(void)
483 misc_deregister(&rng_miscdev);
486 static int __init register_miscdev(void)
488 return misc_register(&rng_miscdev);
491 static int hwrng_fillfn(void *unused)
493 size_t entropy, entropy_credit = 0; /* in 1/1024 of a bit */
496 while (!kthread_should_stop()) {
497 unsigned short quality;
500 rng = get_current_rng();
501 if (IS_ERR(rng) || !rng)
503 mutex_lock(&reading_mutex);
504 rc = rng_get_data(rng, rng_fillbuf,
505 rng_buffer_size(), 1);
506 if (current_quality != rng->quality)
507 rng->quality = current_quality; /* obsolete */
508 quality = rng->quality;
509 mutex_unlock(&reading_mutex);
512 hwrng_msleep(rng, 10000);
522 /* If we cannot credit at least one bit of entropy,
523 * keep track of the remainder for the next iteration
525 entropy = rc * quality * 8 + entropy_credit;
526 if ((entropy >> 10) == 0)
527 entropy_credit = entropy;
529 /* Outside lock, sure, but y'know: randomness. */
530 add_hwgenerator_randomness((void *)rng_fillbuf, rc,
537 static void hwrng_manage_rngd(struct hwrng *rng)
539 if (WARN_ON(!mutex_is_locked(&rng_mutex)))
542 if (rng->quality == 0 && hwrng_fill)
543 kthread_stop(hwrng_fill);
544 if (rng->quality > 0 && !hwrng_fill) {
545 hwrng_fill = kthread_run(hwrng_fillfn, NULL, "hwrng");
546 if (IS_ERR(hwrng_fill)) {
547 pr_err("hwrng_fill thread creation failed\n");
553 int hwrng_register(struct hwrng *rng)
557 bool is_new_current = false;
559 if (!rng->name || (!rng->data_read && !rng->read))
562 mutex_lock(&rng_mutex);
564 /* Must not register two RNGs with the same name. */
566 list_for_each_entry(tmp, &rng_list, list) {
567 if (strcmp(tmp->name, rng->name) == 0)
570 list_add_tail(&rng->list, &rng_list);
572 init_completion(&rng->cleanup_done);
573 complete(&rng->cleanup_done);
574 init_completion(&rng->dying);
577 (!cur_rng_set_by_user && rng->quality > current_rng->quality)) {
579 * Set new rng as current as the new rng source
580 * provides better entropy quality and was not
581 * chosen by userspace.
583 err = set_current_rng(rng);
586 /* to use current_rng in add_early_randomness() we need
589 is_new_current = true;
592 mutex_unlock(&rng_mutex);
593 if (is_new_current || !rng->init) {
595 * Use a new device's input to add some randomness to
596 * the system. If this rng device isn't going to be
597 * used right away, its init function hasn't been
598 * called yet by set_current_rng(); so only use the
599 * randomness from devices that don't need an init callback
601 add_early_randomness(rng);
607 mutex_unlock(&rng_mutex);
611 EXPORT_SYMBOL_GPL(hwrng_register);
613 void hwrng_unregister(struct hwrng *rng)
615 struct hwrng *old_rng, *new_rng;
618 mutex_lock(&rng_mutex);
620 old_rng = current_rng;
621 list_del(&rng->list);
622 complete_all(&rng->dying);
623 if (current_rng == rng) {
624 err = enable_best_rng();
627 cur_rng_set_by_user = 0;
631 new_rng = get_current_rng_nolock();
632 if (list_empty(&rng_list)) {
633 mutex_unlock(&rng_mutex);
635 kthread_stop(hwrng_fill);
637 mutex_unlock(&rng_mutex);
640 if (old_rng != new_rng)
641 add_early_randomness(new_rng);
645 wait_for_completion(&rng->cleanup_done);
647 EXPORT_SYMBOL_GPL(hwrng_unregister);
649 static void devm_hwrng_release(struct device *dev, void *res)
651 hwrng_unregister(*(struct hwrng **)res);
654 static int devm_hwrng_match(struct device *dev, void *res, void *data)
656 struct hwrng **r = res;
658 if (WARN_ON(!r || !*r))
664 int devm_hwrng_register(struct device *dev, struct hwrng *rng)
669 ptr = devres_alloc(devm_hwrng_release, sizeof(*ptr), GFP_KERNEL);
673 error = hwrng_register(rng);
680 devres_add(dev, ptr);
683 EXPORT_SYMBOL_GPL(devm_hwrng_register);
685 void devm_hwrng_unregister(struct device *dev, struct hwrng *rng)
687 devres_release(dev, devm_hwrng_release, devm_hwrng_match, rng);
689 EXPORT_SYMBOL_GPL(devm_hwrng_unregister);
691 long hwrng_msleep(struct hwrng *rng, unsigned int msecs)
693 unsigned long timeout = msecs_to_jiffies(msecs) + 1;
695 return wait_for_completion_interruptible_timeout(&rng->dying, timeout);
697 EXPORT_SYMBOL_GPL(hwrng_msleep);
699 static int __init hwrng_modinit(void)
703 /* kmalloc makes this safe for virt_to_page() in virtio_rng.c */
704 rng_buffer = kmalloc(rng_buffer_size(), GFP_KERNEL);
708 rng_fillbuf = kmalloc(rng_buffer_size(), GFP_KERNEL);
714 ret = register_miscdev();
723 static void __exit hwrng_modexit(void)
725 mutex_lock(&rng_mutex);
729 mutex_unlock(&rng_mutex);
731 unregister_miscdev();
734 fs_initcall(hwrng_modinit); /* depends on misc_register() */
735 module_exit(hwrng_modexit);
737 MODULE_DESCRIPTION("H/W Random Number Generator (RNG) driver");
738 MODULE_LICENSE("GPL");