1 /* 2 * Copyright 2013, Michael Ellerman, IBM Corporation. 3 * 4 * This program is free software; you can redistribute it and/or 5 * modify it under the terms of the GNU General Public License 6 * as published by the Free Software Foundation; either version 7 * 2 of the License, or (at your option) any later version. 8 */ 9 10 #define pr_fmt(fmt) "powernv-rng: " fmt 11 12 #include <linux/kernel.h> 13 #include <linux/of.h> 14 #include <linux/of_address.h> 15 #include <linux/of_platform.h> 16 #include <linux/slab.h> 17 #include <linux/smp.h> 18 #include <asm/archrandom.h> 19 #include <asm/io.h> 20 #include <asm/prom.h> 21 #include <asm/machdep.h> 22 23 24 struct powernv_rng { 25 void __iomem *regs; 26 unsigned long mask; 27 }; 28 29 static DEFINE_PER_CPU(struct powernv_rng *, powernv_rng); 30 31 32 static unsigned long rng_whiten(struct powernv_rng *rng, unsigned long val) 33 { 34 unsigned long parity; 35 36 /* Calculate the parity of the value */ 37 asm ("popcntd %0,%1" : "=r" (parity) : "r" (val)); 38 39 /* xor our value with the previous mask */ 40 val ^= rng->mask; 41 42 /* update the mask based on the parity of this value */ 43 rng->mask = (rng->mask << 1) | (parity & 1); 44 45 return val; 46 } 47 48 int powernv_get_random_long(unsigned long *v) 49 { 50 struct powernv_rng *rng; 51 52 rng = get_cpu_var(powernv_rng); 53 54 *v = rng_whiten(rng, in_be64(rng->regs)); 55 56 put_cpu_var(rng); 57 58 return 1; 59 } 60 EXPORT_SYMBOL_GPL(powernv_get_random_long); 61 62 static __init void rng_init_per_cpu(struct powernv_rng *rng, 63 struct device_node *dn) 64 { 65 int chip_id, cpu; 66 67 chip_id = of_get_ibm_chip_id(dn); 68 if (chip_id == -1) 69 pr_warn("No ibm,chip-id found for %s.\n", dn->full_name); 70 71 for_each_possible_cpu(cpu) { 72 if (per_cpu(powernv_rng, cpu) == NULL || 73 cpu_to_chip_id(cpu) == chip_id) { 74 per_cpu(powernv_rng, cpu) = rng; 75 } 76 } 77 } 78 79 static __init int rng_create(struct device_node *dn) 80 { 81 struct powernv_rng *rng; 82 unsigned long val; 83 84 rng = kzalloc(sizeof(*rng), GFP_KERNEL); 85 if (!rng) 86 return -ENOMEM; 87 88 rng->regs = of_iomap(dn, 0); 89 if (!rng->regs) { 90 kfree(rng); 91 return -ENXIO; 92 } 93 94 val = in_be64(rng->regs); 95 rng->mask = val; 96 97 rng_init_per_cpu(rng, dn); 98 99 pr_info_once("Registering arch random hook.\n"); 100 101 ppc_md.get_random_long = powernv_get_random_long; 102 103 return 0; 104 } 105 106 static __init int rng_init(void) 107 { 108 struct device_node *dn; 109 int rc; 110 111 for_each_compatible_node(dn, NULL, "ibm,power-rng") { 112 rc = rng_create(dn); 113 if (rc) { 114 pr_err("Failed creating rng for %s (%d).\n", 115 dn->full_name, rc); 116 continue; 117 } 118 119 /* Create devices for hwrng driver */ 120 of_platform_device_create(dn, NULL, NULL); 121 } 122 123 return 0; 124 } 125 subsys_initcall(rng_init); 126