]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/random/random_harvestq.c
Wrap some policy-rich code in 'if NOTYET' until we can thresh out what it really...
[FreeBSD/FreeBSD.git] / sys / dev / random / random_harvestq.c
1 /*-
2  * Copyright (c) 2000-2013 Mark R V Murray
3  * Copyright (c) 2013 Arthur Mesh
4  * Copyright (c) 2004 Robert N. M. Watson
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer
12  *    in this position and unchanged.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  *
28  */
29
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32
33 #include <sys/param.h>
34 #include <sys/systm.h>
35 #include <sys/eventhandler.h>
36 #include <sys/kernel.h>
37 #include <sys/kthread.h>
38 #include <sys/linker.h>
39 #include <sys/lock.h>
40 #include <sys/malloc.h>
41 #include <sys/mutex.h>
42 #include <sys/random.h>
43 #include <sys/selinfo.h>
44 #include <sys/sysctl.h>
45 #include <sys/unistd.h>
46
47 #include <machine/cpu.h>
48 #include <machine/vmparam.h>
49
50 #include <dev/random/randomdev.h>
51 #include <dev/random/randomdev_soft.h>
52 #include <dev/random/random_adaptors.h>
53 #include <dev/random/random_harvestq.h>
54 #include <dev/random/live_entropy_sources.h>
55 #include <dev/random/rwfile.h>
56
57 #define RANDOM_FIFO_MAX 1024    /* How many events to queue up */
58
59 /*
60  * The harvest mutex protects the consistency of the entropy fifos and
61  * empty fifo and other associated structures.
62  */
63 struct mtx      harvest_mtx;
64
65 /* Lockable FIFO queue holding entropy buffers */
66 struct entropyfifo {
67         int count;
68         STAILQ_HEAD(harvestlist, harvest) head;
69 };
70
71 /* Empty entropy buffers */
72 static struct entropyfifo emptyfifo;
73
74 /* Harvested entropy */
75 static struct entropyfifo harvestfifo;
76
77 /* <0 to end the kthread, 0 to let it run, 1 to flush the harvest queues */
78 int random_kthread_control = 0;
79
80 static struct proc *random_kthread_proc;
81
82 static const char *entropy_files[] = {
83         "/entropy",
84         NULL
85 };
86
87 #ifdef NOTYET /* This is full of policy stuff, needs further discussion */
88 /* Deal with entropy cached externally if this is present.
89  * Lots of policy may eventually arrive in this function.
90  * Called after / is mounted.
91  */
92 static void
93 random_harvestq_cache(void *arg __unused)
94 {
95         const char **entropy_file;
96         uint8_t *keyfile, *data, *zbuf;
97         size_t size, i;
98         int error;
99
100         /* Get stuff that may have been preloaded by loader(8) */
101         keyfile = preload_search_by_type("/boot/entropy");
102         if (keyfile != NULL) {
103                 data = preload_fetch_addr(keyfile);
104                 size = preload_fetch_size(keyfile);
105                 if (data != NULL && size != 0) {
106                         for (i = 0; i < size; i += 16)
107                                 random_harvestq_internal(get_cyclecount(), data + i, 16, 16, RANDOM_CACHED);
108                         printf("random: read %zu bytes from preloaded cache\n", size);
109                         bzero(data, size);
110                 }
111                 else
112                         printf("random: no preloaded entropy cache available\n");
113         }
114
115         /* Read and attempt to overwrite the entropy cache files.
116          * If the file exists, can be read and then overwritten,
117          * then use it. Ignore it otherwise, but print out what is
118          * going on.
119          */
120         data = malloc(PAGE_SIZE, M_ENTROPY, M_WAITOK);
121         zbuf = __DECONST(void *, zero_region);
122         for (entropy_file = entropy_files; *entropy_file; entropy_file++) {
123                 error = randomdev_read_file(*entropy_file, data, PAGE_SIZE);
124                 if (error == 0) {
125                         printf("random: entropy cache '%s' provides %d bytes\n", *entropy_file, PAGE_SIZE);
126                         error = randomdev_write_file(*entropy_file, zbuf, PAGE_SIZE);
127                         if (error == 0) {
128                                 printf("random: entropy cache '%s' contents used and successfully overwritten\n", *entropy_file);
129                                 for (i = 0; i < PAGE_SIZE; i += 16)
130                                         random_harvestq_internal(get_cyclecount(), data + i, 16, 16, RANDOM_CACHED);
131                         }
132                         else
133                                 printf("random: entropy cache '%s' not overwritten and therefore not used; error = %d\n", *entropy_file, error);
134                 }
135                 else
136                         printf("random: entropy cache '%s' not present or unreadable; error = %d\n", *entropy_file, error);
137         }
138         bzero(data, PAGE_SIZE);
139         free(data, M_ENTROPY);
140 }
141 EVENTHANDLER_DEFINE(mountroot, random_harvestq_cache, NULL, 0);
142 #endif /* NOTYET */
143
144 static void
145 random_kthread(void *arg)
146 {
147         STAILQ_HEAD(, harvest) local_queue;
148         struct harvest *event = NULL;
149         int local_count;
150         event_proc_f entropy_processor = arg;
151
152         STAILQ_INIT(&local_queue);
153         local_count = 0;
154
155         /* Process until told to stop */
156         mtx_lock_spin(&harvest_mtx);
157         for (; random_kthread_control >= 0;) {
158
159                 /*
160                  * Grab all the entropy events.
161                  * Drain entropy source records into a thread-local
162                  * queue for processing while not holding the mutex.
163                  */
164                 STAILQ_CONCAT(&local_queue, &harvestfifo.head);
165                 local_count += harvestfifo.count;
166                 harvestfifo.count = 0;
167
168                 /*
169                  * Deal with events, if any.
170                  * Then transfer the used events back into the empty fifo.
171                  */
172                 if (!STAILQ_EMPTY(&local_queue)) {
173                         mtx_unlock_spin(&harvest_mtx);
174                         STAILQ_FOREACH(event, &local_queue, next)
175                                 entropy_processor(event);
176                         mtx_lock_spin(&harvest_mtx);
177                         STAILQ_CONCAT(&emptyfifo.head, &local_queue);
178                         emptyfifo.count += local_count;
179                         local_count = 0;
180                 }
181
182                 KASSERT(local_count == 0, ("random_kthread: local_count %d",
183                     local_count));
184
185                 /*
186                  * Do only one round of the hardware sources for now.
187                  * Later we'll need to make it rate-adaptive.
188                  */
189                 mtx_unlock_spin(&harvest_mtx);
190                 live_entropy_sources_feed(1, entropy_processor);
191                 mtx_lock_spin(&harvest_mtx);
192
193                 /*
194                  * If a queue flush was commanded, it has now happened,
195                  * and we can mark this by resetting the command.
196                  */
197
198                 if (random_kthread_control == 1)
199                         random_kthread_control = 0;
200
201                 /* Work done, so don't belabour the issue */
202                 msleep_spin_sbt(&random_kthread_control, &harvest_mtx,
203                     "-", SBT_1S/10, 0, C_PREL(1));
204
205         }
206         mtx_unlock_spin(&harvest_mtx);
207
208         random_set_wakeup_exit(&random_kthread_control);
209         /* NOTREACHED */
210 }
211
212 void
213 random_harvestq_init(event_proc_f cb)
214 {
215         int error, i;
216         struct harvest *np;
217
218         /* Initialise the harvest fifos */
219
220         /* Contains the currently unused event structs. */
221         STAILQ_INIT(&emptyfifo.head);
222         for (i = 0; i < RANDOM_FIFO_MAX; i++) {
223                 np = malloc(sizeof(struct harvest), M_ENTROPY, M_WAITOK);
224                 STAILQ_INSERT_TAIL(&emptyfifo.head, np, next);
225         }
226         emptyfifo.count = RANDOM_FIFO_MAX;
227
228         /* Will contain the queued-up events. */
229         STAILQ_INIT(&harvestfifo.head);
230         harvestfifo.count = 0;
231
232         mtx_init(&harvest_mtx, "entropy harvest mutex", NULL, MTX_SPIN);
233
234         /* Start the hash/reseed thread */
235         error = kproc_create(random_kthread, cb,
236             &random_kthread_proc, RFHIGHPID, 0, "rand_harvestq"); /* RANDOM_CSPRNG_NAME */
237
238         if (error != 0)
239                 panic("Cannot create entropy maintenance thread.");
240 }
241
242 void
243 random_harvestq_deinit(void)
244 {
245         struct harvest *np;
246
247         /* Destroy the harvest fifos */
248         while (!STAILQ_EMPTY(&emptyfifo.head)) {
249                 np = STAILQ_FIRST(&emptyfifo.head);
250                 STAILQ_REMOVE_HEAD(&emptyfifo.head, next);
251                 free(np, M_ENTROPY);
252         }
253         emptyfifo.count = 0;
254         while (!STAILQ_EMPTY(&harvestfifo.head)) {
255                 np = STAILQ_FIRST(&harvestfifo.head);
256                 STAILQ_REMOVE_HEAD(&harvestfifo.head, next);
257                 free(np, M_ENTROPY);
258         }
259         harvestfifo.count = 0;
260
261         mtx_destroy(&harvest_mtx);
262 }
263
264 /*
265  * Entropy harvesting routine.
266  * This is supposed to be fast; do not do anything slow in here!
267  *
268  * It is also illegal (and morally reprehensible) to insert any
269  * high-rate data here. "High-rate" is define as a data source
270  * that will usually cause lots of failures of the "Lockless read"
271  * check a few lines below. This includes the "always-on" sources
272  * like the Intel "rdrand" or the VIA Nehamiah "xstore" sources.
273  */
274 void
275 random_harvestq_internal(u_int64_t somecounter, const void *entropy,
276     u_int count, u_int bits, enum esource origin)
277 {
278         struct harvest *event;
279
280         KASSERT(origin >= RANDOM_START && origin < ENTROPYSOURCE,
281             ("random_harvest_internal: origin %d invalid\n", origin));
282
283         /* Lockless read to avoid lock operations if fifo is full. */
284         if (harvestfifo.count >= RANDOM_FIFO_MAX)
285                 return;
286
287         mtx_lock_spin(&harvest_mtx);
288
289         /*
290          * On't overfill the harvest queue; this could steal all
291          * our memory.
292          */
293         if (harvestfifo.count < RANDOM_FIFO_MAX) {
294                 event = STAILQ_FIRST(&emptyfifo.head);
295                 if (event != NULL) {
296                         /* Add the harvested data to the fifo */
297                         STAILQ_REMOVE_HEAD(&emptyfifo.head, next);
298                         emptyfifo.count--;
299                         event->somecounter = somecounter;
300                         event->size = count;
301                         event->bits = bits;
302                         event->source = origin;
303
304                         /* XXXX Come back and make this dynamic! */
305                         count = MIN(count, HARVESTSIZE);
306                         memcpy(event->entropy, entropy, count);
307
308                         STAILQ_INSERT_TAIL(&harvestfifo.head,
309                             event, next);
310                         harvestfifo.count++;
311                 }
312         }
313
314         mtx_unlock_spin(&harvest_mtx);
315 }