1/*-
2 * Copyright (c) 2013 The FreeBSD Foundation
3 * Copyright (c) 2013 David E. O'Brien <obrien@NUXI.org>
4 * Copyright (c) 2012 Konstantin Belousov <kib@FreeBSD.org>
5 * All rights reserved.
6 *
7 * Portions of this software were developed by Konstantin Belousov
8 * under sponsorship from the FreeBSD Foundation.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 *    notice, this list of conditions and the following disclaimer
15 *    in this position and unchanged.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 *    notice, this list of conditions and the following disclaimer in the
18 *    documentation and/or other materials provided with the distribution.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
21 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
22 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
23 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
24 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
29 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 *
31 */
32
33#include <sys/param.h>
34#include <sys/kernel.h>
35#include <sys/conf.h>
36#include <sys/lock.h>
37#include <sys/malloc.h>
38#include <sys/module.h>
39#include <sys/random.h>
40#include <sys/sysctl.h>
41#include <sys/systm.h>
42
43#include <machine/md_var.h>
44#include <machine/specialreg.h>
45#include <x86/ifunc.h>
46
47#include <dev/random/randomdev.h>
48
49#define	RETRY_COUNT	10
50
51static bool has_rdrand, has_rdseed;
52static u_int random_ivy_read(void *, u_int);
53
54static struct random_source random_ivy = {
55	.rs_ident = "Intel Secure Key RNG",
56	.rs_source = RANDOM_PURE_RDRAND,
57	.rs_read = random_ivy_read
58};
59
60SYSCTL_NODE(_kern_random, OID_AUTO, rdrand, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
61    "rdrand (ivy) entropy source");
62static bool acquire_independent_seed_samples = false;
63SYSCTL_BOOL(_kern_random_rdrand, OID_AUTO, rdrand_independent_seed,
64    CTLFLAG_RWTUN, &acquire_independent_seed_samples, 0,
65    "If non-zero, use more expensive and slow, but safer, seeded samples "
66    "where RDSEED is not present.");
67
68static bool
69x86_rdrand_store(u_long *buf)
70{
71	u_long rndval, seed_iterations, i;
72	int retry;
73
74	/* Per [1], "�� 5.2.6 Generating Seeds from RDRAND,"
75	 * machines lacking RDSEED will guarantee RDRAND is reseeded every 8kB
76	 * of generated output.
77	 *
78	 * [1]: https://software.intel.com/en-us/articles/intel-digital-random-number-generator-drng-software-implementation-guide#inpage-nav-6-8
79	 */
80	if (acquire_independent_seed_samples)
81		seed_iterations = 8 * 1024 / sizeof(*buf);
82	else
83		seed_iterations = 1;
84
85	for (i = 0; i < seed_iterations; i++) {
86		retry = RETRY_COUNT;
87		__asm __volatile(
88		    "1:\n\t"
89		    "rdrand	%1\n\t"	/* read randomness into rndval */
90		    "jc		2f\n\t" /* CF is set on success, exit retry loop */
91		    "dec	%0\n\t" /* otherwise, retry-- */
92		    "jne	1b\n\t" /* and loop if retries are not exhausted */
93		    "2:"
94		    : "+r" (retry), "=r" (rndval) : : "cc");
95		if (retry == 0)
96			return (false);
97	}
98	*buf = rndval;
99	return (true);
100}
101
102static bool
103x86_rdseed_store(u_long *buf)
104{
105	u_long rndval;
106	int retry;
107
108	retry = RETRY_COUNT;
109	__asm __volatile(
110	    "1:\n\t"
111	    "rdseed	%1\n\t"	/* read randomness into rndval */
112	    "jc		2f\n\t" /* CF is set on success, exit retry loop */
113	    "dec	%0\n\t" /* otherwise, retry-- */
114	    "jne	1b\n\t" /* and loop if retries are not exhausted */
115	    "2:"
116	    : "+r" (retry), "=r" (rndval) : : "cc");
117	*buf = rndval;
118	return (retry != 0);
119}
120
121static bool
122x86_unimpl_store(u_long *buf __unused)
123{
124
125	panic("%s called", __func__);
126}
127
128DEFINE_IFUNC(static, bool, x86_rng_store, (u_long *buf))
129{
130	has_rdrand = (cpu_feature2 & CPUID2_RDRAND);
131	has_rdseed = (cpu_stdext_feature & CPUID_STDEXT_RDSEED);
132
133	if (has_rdseed)
134		return (x86_rdseed_store);
135	else if (has_rdrand)
136		return (x86_rdrand_store);
137	else
138		return (x86_unimpl_store);
139}
140
141/* It is required that buf length is a multiple of sizeof(u_long). */
142static u_int
143random_ivy_read(void *buf, u_int c)
144{
145	u_long *b, rndval;
146	u_int count;
147
148	KASSERT(c % sizeof(*b) == 0, ("partial read %d", c));
149	b = buf;
150	for (count = c; count > 0; count -= sizeof(*b)) {
151		if (!x86_rng_store(&rndval))
152			break;
153		*b++ = rndval;
154	}
155	return (c - count);
156}
157
158static int
159rdrand_modevent(module_t mod, int type, void *unused)
160{
161	int error = 0;
162
163	switch (type) {
164	case MOD_LOAD:
165		if (has_rdrand || has_rdseed) {
166			random_source_register(&random_ivy);
167			printf("random: fast provider: \"%s\"\n", random_ivy.rs_ident);
168		}
169		break;
170
171	case MOD_UNLOAD:
172		if (has_rdrand || has_rdseed)
173			random_source_deregister(&random_ivy);
174		break;
175
176	case MOD_SHUTDOWN:
177		break;
178
179	default:
180		error = EOPNOTSUPP;
181		break;
182
183	}
184
185	return (error);
186}
187
188static moduledata_t rdrand_mod = {
189	"rdrand",
190	rdrand_modevent,
191	0
192};
193
194DECLARE_MODULE(rdrand, rdrand_mod, SI_SUB_RANDOM, SI_ORDER_FOURTH);
195MODULE_VERSION(rdrand, 1);
196MODULE_DEPEND(rdrand, random_harvestq, 1, 1, 1);
197