1 /* 2 * Nomadik RNG support 3 * Copyright 2009 Alessandro Rubini 4 * 5 * This program is free software; you can redistribute it and/or modify 6 * it under the terms of the GNU General Public License as published by 7 * the Free Software Foundation; either version 2 of the License, or 8 * (at your option) any later version. 9 */ 10 11 #include <linux/kernel.h> 12 #include <linux/module.h> 13 #include <linux/device.h> 14 #include <linux/amba/bus.h> 15 #include <linux/hw_random.h> 16 #include <linux/io.h> 17 #include <linux/clk.h> 18 #include <linux/err.h> 19 20 static struct clk *rng_clk; 21 22 static int nmk_rng_read(struct hwrng *rng, void *data, size_t max, bool wait) 23 { 24 void __iomem *base = (void __iomem *)rng->priv; 25 26 /* 27 * The register is 32 bits and gives 16 random bits (low half). 28 * A subsequent read will delay the core for 400ns, so we just read 29 * once and accept the very unlikely very small delay, even if wait==0. 30 */ 31 *(u16 *)data = __raw_readl(base + 8) & 0xffff; 32 return 2; 33 } 34 35 /* we have at most one RNG per machine, granted */ 36 static struct hwrng nmk_rng = { 37 .name = "nomadik", 38 .read = nmk_rng_read, 39 }; 40 41 static int nmk_rng_probe(struct amba_device *dev, const struct amba_id *id) 42 { 43 void __iomem *base; 44 int ret; 45 46 rng_clk = clk_get(&dev->dev, NULL); 47 if (IS_ERR(rng_clk)) { 48 dev_err(&dev->dev, "could not get rng clock\n"); 49 ret = PTR_ERR(rng_clk); 50 return ret; 51 } 52 53 clk_prepare_enable(rng_clk); 54 55 ret = amba_request_regions(dev, dev->dev.init_name); 56 if (ret) 57 goto out_clk; 58 ret = -ENOMEM; 59 base = ioremap(dev->res.start, resource_size(&dev->res)); 60 if (!base) 61 goto out_release; 62 nmk_rng.priv = (unsigned long)base; 63 ret = hwrng_register(&nmk_rng); 64 if (ret) 65 goto out_unmap; 66 return 0; 67 68 out_unmap: 69 iounmap(base); 70 out_release: 71 amba_release_regions(dev); 72 out_clk: 73 clk_disable(rng_clk); 74 clk_put(rng_clk); 75 return ret; 76 } 77 78 static int nmk_rng_remove(struct amba_device *dev) 79 { 80 void __iomem *base = (void __iomem *)nmk_rng.priv; 81 hwrng_unregister(&nmk_rng); 82 iounmap(base); 83 amba_release_regions(dev); 84 clk_disable(rng_clk); 85 clk_put(rng_clk); 86 return 0; 87 } 88 89 static struct amba_id nmk_rng_ids[] = { 90 { 91 .id = 0x000805e1, 92 .mask = 0x000fffff, /* top bits are rev and cfg: accept all */ 93 }, 94 {0, 0}, 95 }; 96 97 MODULE_DEVICE_TABLE(amba, nmk_rng_ids); 98 99 static struct amba_driver nmk_rng_driver = { 100 .drv = { 101 .owner = THIS_MODULE, 102 .name = "rng", 103 }, 104 .probe = nmk_rng_probe, 105 .remove = nmk_rng_remove, 106 .id_table = nmk_rng_ids, 107 }; 108 109 module_amba_driver(nmk_rng_driver); 110 111 MODULE_LICENSE("GPL"); 112