patch-2_6_7-vs1_9_1_12
[linux-2.6.git] / drivers / char / hw_random.c
1 /*
2         Hardware driver for the Intel/AMD/VIA Random Number Generators (RNG)
3         (c) Copyright 2003 Red Hat Inc <jgarzik@redhat.com>
4  
5         derived from
6  
7         Hardware driver for the AMD 768 Random Number Generator (RNG)
8         (c) Copyright 2001 Red Hat Inc <alan@redhat.com>
9
10         derived from
11  
12         Hardware driver for Intel i810 Random Number Generator (RNG)
13         Copyright 2000,2001 Jeff Garzik <jgarzik@pobox.com>
14         Copyright 2000,2001 Philipp Rumpf <prumpf@mandrakesoft.com>
15
16         Please read Documentation/hw_random.txt for details on use.
17
18         ----------------------------------------------------------
19         This software may be used and distributed according to the terms
20         of the GNU General Public License, incorporated herein by reference.
21
22  */
23
24
25 #include <linux/module.h>
26 #include <linux/kernel.h>
27 #include <linux/fs.h>
28 #include <linux/init.h>
29 #include <linux/pci.h>
30 #include <linux/interrupt.h>
31 #include <linux/spinlock.h>
32 #include <linux/random.h>
33 #include <linux/miscdevice.h>
34 #include <linux/smp_lock.h>
35 #include <linux/mm.h>
36 #include <linux/delay.h>
37
38 #ifdef __i386__
39 #include <asm/msr.h>
40 #include <asm/cpufeature.h>
41 #endif
42
43 #include <asm/io.h>
44 #include <asm/uaccess.h>
45
46
47 /*
48  * core module and version information
49  */
50 #define RNG_VERSION "1.0.0"
51 #define RNG_MODULE_NAME "hw_random"
52 #define RNG_DRIVER_NAME   RNG_MODULE_NAME " hardware driver " RNG_VERSION
53 #define PFX RNG_MODULE_NAME ": "
54
55
56 /*
57  * debugging macros
58  */
59 #undef RNG_DEBUG /* define to enable copious debugging info */
60
61 #ifdef RNG_DEBUG
62 /* note: prints function name for you */
63 #define DPRINTK(fmt, args...) printk(KERN_DEBUG "%s: " fmt, __FUNCTION__ , ## args)
64 #else
65 #define DPRINTK(fmt, args...)
66 #endif
67
68 #define RNG_NDEBUG        /* define to disable lightweight runtime checks */
69 #ifdef RNG_NDEBUG
70 #define assert(expr)
71 #else
72 #define assert(expr) \
73         if(!(expr)) {                                   \
74         printk( "Assertion failed! %s,%s,%s,line=%d\n", \
75         #expr,__FILE__,__FUNCTION__,__LINE__);          \
76         }
77 #endif
78
79 #define RNG_MISCDEV_MINOR               183 /* official */
80
81 static int rng_dev_open (struct inode *inode, struct file *filp);
82 static ssize_t rng_dev_read (struct file *filp, char __user *buf, size_t size,
83                              loff_t * offp);
84
85 static int __init intel_init (struct pci_dev *dev);
86 static void intel_cleanup(void);
87 static unsigned int intel_data_present (void);
88 static u32 intel_data_read (void);
89
90 static int __init amd_init (struct pci_dev *dev);
91 static void amd_cleanup(void);
92 static unsigned int amd_data_present (void);
93 static u32 amd_data_read (void);
94
95 #ifdef __i386__
96 static int __init via_init(struct pci_dev *dev);
97 static void via_cleanup(void);
98 static unsigned int via_data_present (void);
99 static u32 via_data_read (void);
100 #endif
101
102 struct rng_operations {
103         int (*init) (struct pci_dev *dev);
104         void (*cleanup) (void);
105         unsigned int (*data_present) (void);
106         u32 (*data_read) (void);
107         unsigned int n_bytes; /* number of bytes per ->data_read */
108 };
109 static struct rng_operations *rng_ops;
110
111 static struct file_operations rng_chrdev_ops = {
112         .owner          = THIS_MODULE,
113         .open           = rng_dev_open,
114         .read           = rng_dev_read,
115 };
116
117
118 static struct miscdevice rng_miscdev = {
119         RNG_MISCDEV_MINOR,
120         RNG_MODULE_NAME,
121         &rng_chrdev_ops,
122 };
123
124 enum {
125         rng_hw_none,
126         rng_hw_intel,
127         rng_hw_amd,
128         rng_hw_via,
129 };
130
131 static struct rng_operations rng_vendor_ops[] = {
132         /* rng_hw_none */
133         { },
134
135         /* rng_hw_intel */
136         { intel_init, intel_cleanup, intel_data_present,
137           intel_data_read, 1 },
138
139         /* rng_hw_amd */
140         { amd_init, amd_cleanup, amd_data_present, amd_data_read, 4 },
141
142 #ifdef __i386__
143         /* rng_hw_via */
144         { via_init, via_cleanup, via_data_present, via_data_read, 1 },
145 #endif
146 };
147
148 /*
149  * Data for PCI driver interface
150  *
151  * This data only exists for exporting the supported
152  * PCI ids via MODULE_DEVICE_TABLE.  We do not actually
153  * register a pci_driver, because someone else might one day
154  * want to register another driver on the same PCI id.
155  */
156 static struct pci_device_id rng_pci_tbl[] = {
157         { 0x1022, 0x7443, PCI_ANY_ID, PCI_ANY_ID, 0, 0, rng_hw_amd },
158         { 0x1022, 0x746b, PCI_ANY_ID, PCI_ANY_ID, 0, 0, rng_hw_amd },
159
160         { 0x8086, 0x2418, PCI_ANY_ID, PCI_ANY_ID, 0, 0, rng_hw_intel },
161         { 0x8086, 0x2428, PCI_ANY_ID, PCI_ANY_ID, 0, 0, rng_hw_intel },
162         { 0x8086, 0x2448, PCI_ANY_ID, PCI_ANY_ID, 0, 0, rng_hw_intel },
163         { 0x8086, 0x244e, PCI_ANY_ID, PCI_ANY_ID, 0, 0, rng_hw_intel },
164         { 0x8086, 0x245e, PCI_ANY_ID, PCI_ANY_ID, 0, 0, rng_hw_intel },
165
166         { 0, }, /* terminate list */
167 };
168 MODULE_DEVICE_TABLE (pci, rng_pci_tbl);
169
170
171 /***********************************************************************
172  *
173  * Intel RNG operations
174  *
175  */
176
177 /*
178  * RNG registers (offsets from rng_mem)
179  */
180 #define INTEL_RNG_HW_STATUS                     0
181 #define         INTEL_RNG_PRESENT               0x40
182 #define         INTEL_RNG_ENABLED               0x01
183 #define INTEL_RNG_STATUS                        1
184 #define         INTEL_RNG_DATA_PRESENT          0x01
185 #define INTEL_RNG_DATA                          2
186
187 /*
188  * Magic address at which Intel PCI bridges locate the RNG
189  */
190 #define INTEL_RNG_ADDR                          0xFFBC015F
191 #define INTEL_RNG_ADDR_LEN                      3
192
193 /* token to our ioremap'd RNG register area */
194 static void *rng_mem;
195
196 static inline u8 intel_hwstatus (void)
197 {
198         assert (rng_mem != NULL);
199         return readb (rng_mem + INTEL_RNG_HW_STATUS);
200 }
201
202 static inline u8 intel_hwstatus_set (u8 hw_status)
203 {
204         assert (rng_mem != NULL);
205         writeb (hw_status, rng_mem + INTEL_RNG_HW_STATUS);
206         return intel_hwstatus ();
207 }
208
209 static unsigned int intel_data_present(void)
210 {
211         assert (rng_mem != NULL);
212
213         return (readb (rng_mem + INTEL_RNG_STATUS) & INTEL_RNG_DATA_PRESENT) ?
214                 1 : 0;
215 }
216
217 static u32 intel_data_read(void)
218 {
219         assert (rng_mem != NULL);
220
221         return readb (rng_mem + INTEL_RNG_DATA);
222 }
223
224 static int __init intel_init (struct pci_dev *dev)
225 {
226         int rc;
227         u8 hw_status;
228
229         DPRINTK ("ENTER\n");
230
231         rng_mem = ioremap (INTEL_RNG_ADDR, INTEL_RNG_ADDR_LEN);
232         if (rng_mem == NULL) {
233                 printk (KERN_ERR PFX "cannot ioremap RNG Memory\n");
234                 rc = -EBUSY;
235                 goto err_out;
236         }
237
238         /* Check for Intel 82802 */
239         hw_status = intel_hwstatus ();
240         if ((hw_status & INTEL_RNG_PRESENT) == 0) {
241                 printk (KERN_ERR PFX "RNG not detected\n");
242                 rc = -ENODEV;
243                 goto err_out_free_map;
244         }
245
246         /* turn RNG h/w on, if it's off */
247         if ((hw_status & INTEL_RNG_ENABLED) == 0)
248                 hw_status = intel_hwstatus_set (hw_status | INTEL_RNG_ENABLED);
249         if ((hw_status & INTEL_RNG_ENABLED) == 0) {
250                 printk (KERN_ERR PFX "cannot enable RNG, aborting\n");
251                 rc = -EIO;
252                 goto err_out_free_map;
253         }
254
255         DPRINTK ("EXIT, returning 0\n");
256         return 0;
257
258 err_out_free_map:
259         iounmap (rng_mem);
260         rng_mem = NULL;
261 err_out:
262         DPRINTK ("EXIT, returning %d\n", rc);
263         return rc;
264 }
265
266 static void intel_cleanup(void)
267 {
268         u8 hw_status;
269
270         hw_status = intel_hwstatus ();
271         if (hw_status & INTEL_RNG_ENABLED)
272                 intel_hwstatus_set (hw_status & ~INTEL_RNG_ENABLED);
273         else
274                 printk(KERN_WARNING PFX "unusual: RNG already disabled\n");
275         iounmap(rng_mem);
276         rng_mem = NULL;
277 }
278
279 /***********************************************************************
280  *
281  * AMD RNG operations
282  *
283  */
284
285 static u32 pmbase;                      /* PMxx I/O base */
286 static struct pci_dev *amd_dev;
287
288 static unsigned int amd_data_present (void)
289 {
290         return inl(pmbase + 0xF4) & 1;
291 }
292
293
294 static u32 amd_data_read (void)
295 {
296         return inl(pmbase + 0xF0);
297 }
298
299 static int __init amd_init (struct pci_dev *dev)
300 {
301         int rc;
302         u8 rnen;
303
304         DPRINTK ("ENTER\n");
305
306         pci_read_config_dword(dev, 0x58, &pmbase);
307
308         pmbase &= 0x0000FF00;
309
310         if (pmbase == 0)
311         {
312                 printk (KERN_ERR PFX "power management base not set\n");
313                 rc = -EIO;
314                 goto err_out;
315         }
316
317         pci_read_config_byte(dev, 0x40, &rnen);
318         rnen |= (1 << 7);       /* RNG on */
319         pci_write_config_byte(dev, 0x40, rnen);
320
321         pci_read_config_byte(dev, 0x41, &rnen);
322         rnen |= (1 << 7);       /* PMIO enable */
323         pci_write_config_byte(dev, 0x41, rnen);
324
325         printk(KERN_INFO PFX "AMD768 system management I/O registers at 0x%X.\n", pmbase);
326
327         amd_dev = dev;
328
329         DPRINTK ("EXIT, returning 0\n");
330         return 0;
331
332 err_out:
333         DPRINTK ("EXIT, returning %d\n", rc);
334         return rc;
335 }
336
337 static void amd_cleanup(void)
338 {
339         u8 rnen;
340
341         pci_read_config_byte(amd_dev, 0x40, &rnen);
342         rnen &= ~(1 << 7);      /* RNG off */
343         pci_write_config_byte(amd_dev, 0x40, rnen);
344
345         /* FIXME: twiddle pmio, also? */
346 }
347
348 #ifdef __i386__
349 /***********************************************************************
350  *
351  * VIA RNG operations
352  *
353  */
354
355 enum {
356         VIA_STRFILT_CNT_SHIFT   = 16,
357         VIA_STRFILT_FAIL        = (1 << 15),
358         VIA_STRFILT_ENABLE      = (1 << 14),
359         VIA_RAWBITS_ENABLE      = (1 << 13),
360         VIA_RNG_ENABLE          = (1 << 6),
361         VIA_XSTORE_CNT_MASK     = 0x0F,
362
363         VIA_RNG_CHUNK_8         = 0x00, /* 64 rand bits, 64 stored bits */
364         VIA_RNG_CHUNK_4         = 0x01, /* 32 rand bits, 32 stored bits */
365         VIA_RNG_CHUNK_4_MASK    = 0xFFFFFFFF,
366         VIA_RNG_CHUNK_2         = 0x02, /* 16 rand bits, 32 stored bits */
367         VIA_RNG_CHUNK_2_MASK    = 0xFFFF,
368         VIA_RNG_CHUNK_1         = 0x03, /* 8 rand bits, 32 stored bits */
369         VIA_RNG_CHUNK_1_MASK    = 0xFF,
370 };
371
372 u32 via_rng_datum;
373
374 /*
375  * Investigate using the 'rep' prefix to obtain 32 bits of random data
376  * in one insn.  The upside is potentially better performance.  The
377  * downside is that the instruction becomes no longer atomic.  Due to
378  * this, just like familiar issues with /dev/random itself, the worst
379  * case of a 'rep xstore' could potentially pause a cpu for an
380  * unreasonably long time.  In practice, this condition would likely
381  * only occur when the hardware is failing.  (or so we hope :))
382  *
383  * Another possible performance boost may come from simply buffering
384  * until we have 4 bytes, thus returning a u32 at a time,
385  * instead of the current u8-at-a-time.
386  */
387
388 static inline u32 xstore(u32 *addr, u32 edx_in)
389 {
390         u32 eax_out;
391
392         asm(".byte 0x0F,0xA7,0xC0 /* xstore %%edi (addr=%0) */"
393                 :"=m"(*addr), "=a"(eax_out)
394                 :"D"(addr), "d"(edx_in));
395
396         return eax_out;
397 }
398
399 static unsigned int via_data_present(void)
400 {
401         u32 bytes_out;
402
403         /* We choose the recommended 1-byte-per-instruction RNG rate,
404          * for greater randomness at the expense of speed.  Larger
405          * values 2, 4, or 8 bytes-per-instruction yield greater
406          * speed at lesser randomness.
407          *
408          * If you change this to another VIA_CHUNK_n, you must also
409          * change the ->n_bytes values in rng_vendor_ops[] tables.
410          * VIA_CHUNK_8 requires further code changes.
411          *
412          * A copy of MSR_VIA_RNG is placed in eax_out when xstore
413          * completes.
414          */
415         via_rng_datum = 0; /* paranoia, not really necessary */
416         bytes_out = xstore(&via_rng_datum, VIA_RNG_CHUNK_1) & VIA_XSTORE_CNT_MASK;
417         if (bytes_out == 0)
418                 return 0;
419
420         return 1;
421 }
422
423 static u32 via_data_read(void)
424 {
425         return via_rng_datum;
426 }
427
428 static int __init via_init(struct pci_dev *dev)
429 {
430         u32 lo, hi, old_lo;
431
432         /* Control the RNG via MSR.  Tread lightly and pay very close
433          * close attention to values written, as the reserved fields
434          * are documented to be "undefined and unpredictable"; but it
435          * does not say to write them as zero, so I make a guess that
436          * we restore the values we find in the register.
437          */
438         rdmsr(MSR_VIA_RNG, lo, hi);
439
440         old_lo = lo;
441         lo &= ~(0x7f << VIA_STRFILT_CNT_SHIFT);
442         lo &= ~VIA_XSTORE_CNT_MASK;
443         lo &= ~(VIA_STRFILT_ENABLE | VIA_STRFILT_FAIL | VIA_RAWBITS_ENABLE);
444         lo |= VIA_RNG_ENABLE;
445
446         if (lo != old_lo)
447                 wrmsr(MSR_VIA_RNG, lo, hi);
448
449         /* perhaps-unnecessary sanity check; remove after testing if
450            unneeded */
451         rdmsr(MSR_VIA_RNG, lo, hi);
452         if ((lo & VIA_RNG_ENABLE) == 0) {
453                 printk(KERN_ERR PFX "cannot enable VIA C3 RNG, aborting\n");
454                 return -ENODEV;
455         }
456
457         return 0;
458 }
459
460 static void via_cleanup(void)
461 {
462         /* do nothing */
463 }
464 #endif
465
466
467 /***********************************************************************
468  *
469  * /dev/hwrandom character device handling (major 10, minor 183)
470  *
471  */
472
473 static int rng_dev_open (struct inode *inode, struct file *filp)
474 {
475         /* enforce read-only access to this chrdev */
476         if ((filp->f_mode & FMODE_READ) == 0)
477                 return -EINVAL;
478         if (filp->f_mode & FMODE_WRITE)
479                 return -EINVAL;
480
481         return 0;
482 }
483
484
485 static ssize_t rng_dev_read (struct file *filp, char __user *buf, size_t size,
486                              loff_t * offp)
487 {
488         static spinlock_t rng_lock = SPIN_LOCK_UNLOCKED;
489         unsigned int have_data;
490         u32 data = 0;
491         ssize_t ret = 0;
492
493         while (size) {
494                 spin_lock(&rng_lock);
495
496                 have_data = 0;
497                 if (rng_ops->data_present()) {
498                         data = rng_ops->data_read();
499                         have_data = rng_ops->n_bytes;
500                 }
501
502                 spin_unlock (&rng_lock);
503
504                 while (have_data && size) {
505                         if (put_user((u8)data, buf++)) {
506                                 ret = ret ? : -EFAULT;
507                                 break;
508                         }
509                         size--;
510                         ret++;
511                         have_data--;
512                         data>>=8;
513                 }
514
515                 if (filp->f_flags & O_NONBLOCK)
516                         return ret ? : -EAGAIN;
517
518                 if(need_resched())
519                 {
520                         current->state = TASK_INTERRUPTIBLE;
521                         schedule_timeout(1);
522                 }
523                 else
524                         udelay(200);    /* FIXME: We could poll for 250uS ?? */
525
526                 if (signal_pending (current))
527                         return ret ? : -ERESTARTSYS;
528         }
529         return ret;
530 }
531
532
533
534 /*
535  * rng_init_one - look for and attempt to init a single RNG
536  */
537 static int __init rng_init_one (struct pci_dev *dev)
538 {
539         int rc;
540
541         DPRINTK ("ENTER\n");
542
543         assert(rng_ops != NULL);
544
545         rc = rng_ops->init(dev);
546         if (rc)
547                 goto err_out;
548
549         rc = misc_register (&rng_miscdev);
550         if (rc) {
551                 printk (KERN_ERR PFX "misc device register failed\n");
552                 goto err_out_cleanup_hw;
553         }
554
555         DPRINTK ("EXIT, returning 0\n");
556         return 0;
557
558 err_out_cleanup_hw:
559         rng_ops->cleanup();
560 err_out:
561         DPRINTK ("EXIT, returning %d\n", rc);
562         return rc;
563 }
564
565
566
567 MODULE_AUTHOR("The Linux Kernel team");
568 MODULE_DESCRIPTION("H/W Random Number Generator (RNG) driver");
569 MODULE_LICENSE("GPL");
570
571
572 /*
573  * rng_init - initialize RNG module
574  */
575 static int __init rng_init (void)
576 {
577         int rc;
578         struct pci_dev *pdev = NULL;
579         const struct pci_device_id *ent;
580
581         DPRINTK ("ENTER\n");
582
583         /* Probe for Intel, AMD RNGs */
584         while ((pdev = pci_find_device(PCI_ANY_ID, PCI_ANY_ID, pdev)) != NULL) {
585                 ent = pci_match_device (rng_pci_tbl, pdev);
586                 if (ent) {
587                         rng_ops = &rng_vendor_ops[ent->driver_data];
588                         goto match;
589                 }
590         }
591
592 #ifdef __i386__
593         /* Probe for VIA RNG */
594         if (cpu_has_xstore) {
595                 rng_ops = &rng_vendor_ops[rng_hw_via];
596                 pdev = NULL;
597                 goto match;
598         }
599 #endif
600
601         DPRINTK ("EXIT, returning -ENODEV\n");
602         return -ENODEV;
603
604 match:
605         rc = rng_init_one (pdev);
606         if (rc)
607                 return rc;
608
609         printk (KERN_INFO RNG_DRIVER_NAME " loaded\n");
610
611         DPRINTK ("EXIT, returning 0\n");
612         return 0;
613 }
614
615
616 /*
617  * rng_init - shutdown RNG module
618  */
619 static void __exit rng_cleanup (void)
620 {
621         DPRINTK ("ENTER\n");
622
623         misc_deregister (&rng_miscdev);
624
625         if (rng_ops->cleanup)
626                 rng_ops->cleanup();
627
628         DPRINTK ("EXIT\n");
629 }
630
631
632 module_init (rng_init);
633 module_exit (rng_cleanup);