blob: d43e9fab05a769db0dfa53f84aa93527732a6155 [file] [log] [blame]
Linus Torvalds1da177e2005-04-16 15:20:36 -07001/* Much of this ripped from hw_random.c */
2
3#include <linux/module.h>
4#include <linux/fs.h>
5#include <linux/miscdevice.h>
6#include <linux/delay.h>
7#include <asm/uaccess.h>
8#include "os.h"
9
10/*
11 * core module and version information
12 */
13#define RNG_VERSION "1.0.0"
14#define RNG_MODULE_NAME "random"
15#define RNG_DRIVER_NAME RNG_MODULE_NAME " virtual driver " RNG_VERSION
16#define PFX RNG_MODULE_NAME ": "
17
18#define RNG_MISCDEV_MINOR 183 /* official */
19
20static int random_fd = -1;
21
22static int rng_dev_open (struct inode *inode, struct file *filp)
23{
24 /* enforce read-only access to this chrdev */
25 if ((filp->f_mode & FMODE_READ) == 0)
26 return -EINVAL;
27 if (filp->f_mode & FMODE_WRITE)
28 return -EINVAL;
29
30 return 0;
31}
32
33static ssize_t rng_dev_read (struct file *filp, char __user *buf, size_t size,
34 loff_t * offp)
35{
36 u32 data;
37 int n, ret = 0, have_data;
38
39 while(size){
40 n = os_read_file(random_fd, &data, sizeof(data));
41 if(n > 0){
42 have_data = n;
43 while (have_data && size) {
44 if (put_user((u8)data, buf++)) {
45 ret = ret ? : -EFAULT;
46 break;
47 }
48 size--;
49 ret++;
50 have_data--;
51 data>>=8;
52 }
53 }
54 else if(n == -EAGAIN){
55 if (filp->f_flags & O_NONBLOCK)
56 return ret ? : -EAGAIN;
57
58 if(need_resched()){
59 current->state = TASK_INTERRUPTIBLE;
60 schedule_timeout(1);
61 }
62 }
63 else return n;
64 if (signal_pending (current))
65 return ret ? : -ERESTARTSYS;
66 }
67 return ret;
68}
69
70static struct file_operations rng_chrdev_ops = {
71 .owner = THIS_MODULE,
72 .open = rng_dev_open,
73 .read = rng_dev_read,
74};
75
76static struct miscdevice rng_miscdev = {
77 RNG_MISCDEV_MINOR,
78 RNG_MODULE_NAME,
79 &rng_chrdev_ops,
80};
81
82/*
83 * rng_init - initialize RNG module
84 */
85static int __init rng_init (void)
86{
87 int err;
88
89 err = os_open_file("/dev/random", of_read(OPENFLAGS()), 0);
90 if(err < 0)
91 goto out;
92
93 random_fd = err;
94
95 err = os_set_fd_block(random_fd, 0);
96 if(err)
97 goto err_out_cleanup_hw;
98
99 err = misc_register (&rng_miscdev);
100 if (err) {
101 printk (KERN_ERR PFX "misc device register failed\n");
102 goto err_out_cleanup_hw;
103 }
104
105 out:
106 return err;
107
108 err_out_cleanup_hw:
109 random_fd = -1;
110 goto out;
111}
112
113/*
114 * rng_cleanup - shutdown RNG module
115 */
116static void __exit rng_cleanup (void)
117{
118 misc_deregister (&rng_miscdev);
119}
120
121module_init (rng_init);
122module_exit (rng_cleanup);