aboutsummaryrefslogtreecommitdiff
path: root/sys/dev/random/random_harvestq.c
blob: 84ec174bd08ed35703827d27ef33b4b56f06fbc1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
/*-
 * Copyright (c) 2017 Oliver Pinter
 * Copyright (c) 2017 W. Dean Freeman
 * Copyright (c) 2000-2015 Mark R V Murray
 * Copyright (c) 2013 Arthur Mesh
 * Copyright (c) 2004 Robert N. M. Watson
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer
 *    in this position and unchanged.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/ck.h>
#include <sys/conf.h>
#include <sys/epoch.h>
#include <sys/eventhandler.h>
#include <sys/hash.h>
#include <sys/kernel.h>
#include <sys/kthread.h>
#include <sys/linker.h>
#include <sys/lock.h>
#include <sys/malloc.h>
#include <sys/module.h>
#include <sys/mutex.h>
#include <sys/random.h>
#include <sys/sbuf.h>
#include <sys/sysctl.h>
#include <sys/unistd.h>

#include <machine/atomic.h>
#include <machine/cpu.h>

#include <crypto/rijndael/rijndael-api-fst.h>
#include <crypto/sha2/sha256.h>

#include <dev/random/fortuna.h>
#include <dev/random/hash.h>
#include <dev/random/randomdev.h>
#include <dev/random/random_harvestq.h>

#if defined(RANDOM_ENABLE_ETHER)
#define _RANDOM_HARVEST_ETHER_OFF 0
#else
#define _RANDOM_HARVEST_ETHER_OFF (1u << RANDOM_NET_ETHER)
#endif
#if defined(RANDOM_ENABLE_UMA)
#define _RANDOM_HARVEST_UMA_OFF 0
#else
#define _RANDOM_HARVEST_UMA_OFF (1u << RANDOM_UMA)
#endif

/*
 * Note that random_sources_feed() will also use this to try and split up
 * entropy into a subset of pools per iteration with the goal of feeding
 * HARVESTSIZE into every pool at least once per second.
 */
#define	RANDOM_KTHREAD_HZ	10

static void random_kthread(void);
static void random_sources_feed(void);

/*
 * Random must initialize much earlier than epoch, but we can initialize the
 * epoch code before SMP starts.  Prior to SMP, we can safely bypass
 * concurrency primitives.
 */
static __read_mostly bool epoch_inited;
static __read_mostly epoch_t rs_epoch;

static const char *random_source_descr[ENTROPYSOURCE];

/*
 * How many events to queue up. We create this many items in
 * an 'empty' queue, then transfer them to the 'harvest' queue with
 * supplied junk. When used, they are transferred back to the
 * 'empty' queue.
 */
#define	RANDOM_RING_MAX		1024
#define	RANDOM_ACCUM_MAX	8

/* 1 to let the kernel thread run, 0 to terminate, -1 to mark completion */
volatile int random_kthread_control;


/* Allow the sysadmin to select the broad category of
 * entropy types to harvest.
 */
__read_frequently u_int hc_source_mask;

struct random_sources {
	CK_LIST_ENTRY(random_sources)	 rrs_entries;
	const struct random_source	*rrs_source;
};

static CK_LIST_HEAD(sources_head, random_sources) source_list =
    CK_LIST_HEAD_INITIALIZER(source_list);

SYSCTL_NODE(_kern_random, OID_AUTO, harvest, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
    "Entropy Device Parameters");

/*
 * Put all the harvest queue context stuff in one place.
 * this make is a bit easier to lock and protect.
 */
static struct harvest_context {
	/* The harvest mutex protects all of harvest_context and
	 * the related data.
	 */
	struct mtx hc_mtx;
	/* Round-robin destination cache. */
	u_int hc_destination[ENTROPYSOURCE];
	/* The context of the kernel thread processing harvested entropy */
	struct proc *hc_kthread_proc;
	/*
	 * A pair of buffers for queued events.  New events are added to the
	 * active queue while the kthread processes the other one in parallel.
	 */
	struct entropy_buffer {
		struct harvest_event ring[RANDOM_RING_MAX];
		u_int pos;
	} hc_entropy_buf[2];
	u_int hc_active_buf;
	struct fast_entropy_accumulator {
		volatile u_int pos;
		uint32_t buf[RANDOM_ACCUM_MAX];
	} hc_entropy_fast_accumulator;
} harvest_context;

#define	RANDOM_HARVEST_INIT_LOCK()	mtx_init(&harvest_context.hc_mtx, \
					    "entropy harvest mutex", NULL, MTX_SPIN)
#define	RANDOM_HARVEST_LOCK()		mtx_lock_spin(&harvest_context.hc_mtx)
#define	RANDOM_HARVEST_UNLOCK()		mtx_unlock_spin(&harvest_context.hc_mtx)

static struct kproc_desc random_proc_kp = {
	"rand_harvestq",
	random_kthread,
	&harvest_context.hc_kthread_proc,
};

/* Pass the given event straight through to Fortuna/Whatever. */
static __inline void
random_harvestq_fast_process_event(struct harvest_event *event)
{
	p_random_alg_context->ra_event_processor(event);
	explicit_bzero(event, sizeof(*event));
}

static void
random_kthread(void)
{
	struct harvest_context *hc;

	hc = &harvest_context;
	for (random_kthread_control = 1; random_kthread_control;) {
		struct entropy_buffer *buf;
		u_int entries;

		/* Deal with queued events. */
		RANDOM_HARVEST_LOCK();
		buf = &hc->hc_entropy_buf[hc->hc_active_buf];
		entries = buf->pos;
		buf->pos = 0;
		hc->hc_active_buf = (hc->hc_active_buf + 1) %
		    nitems(hc->hc_entropy_buf);
		RANDOM_HARVEST_UNLOCK();
		for (u_int i = 0; i < entries; i++)
			random_harvestq_fast_process_event(&buf->ring[i]);

		/* Poll sources of noise. */
		random_sources_feed();

		/* XXX: FIX!! Increase the high-performance data rate? Need some measurements first. */
		for (u_int i = 0; i < RANDOM_ACCUM_MAX; i++) {
			if (hc->hc_entropy_fast_accumulator.buf[i]) {
				random_harvest_direct(&hc->hc_entropy_fast_accumulator.buf[i],
				    sizeof(hc->hc_entropy_fast_accumulator.buf[0]), RANDOM_UMA);
				hc->hc_entropy_fast_accumulator.buf[i] = 0;
			}
		}
		/* XXX: FIX!! This is a *great* place to pass hardware/live entropy to random(9) */
		tsleep_sbt(&hc->hc_kthread_proc, 0, "-",
		    SBT_1S/RANDOM_KTHREAD_HZ, 0, C_PREL(1));
	}
	random_kthread_control = -1;
	wakeup(&hc->hc_kthread_proc);
	kproc_exit(0);
	/* NOTREACHED */
}
SYSINIT(random_device_h_proc, SI_SUB_KICK_SCHEDULER, SI_ORDER_ANY, kproc_start,
    &random_proc_kp);
_Static_assert(SI_SUB_KICK_SCHEDULER > SI_SUB_RANDOM,
    "random kthread starting before subsystem initialization");

static void
rs_epoch_init(void *dummy __unused)
{
	rs_epoch = epoch_alloc("Random Sources", EPOCH_PREEMPT);
	epoch_inited = true;
}
SYSINIT(rs_epoch_init, SI_SUB_EPOCH, SI_ORDER_ANY, rs_epoch_init, NULL);

/*
 * Run through all fast sources reading entropy for the given
 * number of rounds, which should be a multiple of the number
 * of entropy accumulation pools in use; it is 32 for Fortuna.
 */
static void
random_sources_feed(void)
{
	uint32_t entropy[HARVESTSIZE];
	struct epoch_tracker et;
	struct random_sources *rrs;
	u_int i, n, npools;
	bool rse_warm;

	rse_warm = epoch_inited;

	/*
	 * Evenly-ish distribute pool population across the second based on how
	 * frequently random_kthread iterates.
	 *
	 * For Fortuna, the math currently works out as such:
	 *
	 * 64 bits * 4 pools = 256 bits per iteration
	 * 256 bits * 10 Hz = 2560 bits per second, 320 B/s
	 *
	 */
	npools = howmany(p_random_alg_context->ra_poolcount, RANDOM_KTHREAD_HZ);

	/*-
	 * If we're not seeded yet, attempt to perform a "full seed", filling
	 * all of the PRNG's pools with entropy; if there is enough entropy
	 * available from "fast" entropy sources this will allow us to finish
	 * seeding and unblock the boot process immediately rather than being
	 * stuck for a few seconds with random_kthread gradually collecting a
	 * small chunk of entropy every 1 / RANDOM_KTHREAD_HZ seconds.
	 *
	 * We collect RANDOM_FORTUNA_DEFPOOLSIZE bytes per pool, i.e. enough
	 * to fill Fortuna's pools in the default configuration.  With another
	 * PRNG or smaller pools for Fortuna, we might collect more entropy
	 * than needed to fill the pools, but this is harmless; alternatively,
	 * a different PRNG, larger pools, or fast entropy sources which are
	 * not able to provide as much entropy as we request may result in the
	 * not being fully seeded (and thus remaining blocked) but in that
	 * case we will return here after 1 / RANDOM_KTHREAD_HZ seconds and
	 * try again for a large amount of entropy.
	 */
	if (!p_random_alg_context->ra_seeded())
		npools = howmany(p_random_alg_context->ra_poolcount *
		    RANDOM_FORTUNA_DEFPOOLSIZE, sizeof(entropy));

	/*
	 * Step over all of live entropy sources, and feed their output
	 * to the system-wide RNG.
	 */
	if (rse_warm)
		epoch_enter_preempt(rs_epoch, &et);
	CK_LIST_FOREACH(rrs, &source_list, rrs_entries) {
		for (i = 0; i < npools; i++) {
			n = rrs->rrs_source->rs_read(entropy, sizeof(entropy));
			KASSERT((n <= sizeof(entropy)), ("%s: rs_read returned too much data (%u > %zu)", __func__, n, sizeof(entropy)));
			/*
			 * Sometimes the HW entropy source doesn't have anything
			 * ready for us.  This isn't necessarily untrustworthy.
			 * We don't perform any other verification of an entropy
			 * source (i.e., length is allowed to be anywhere from 1
			 * to sizeof(entropy), quality is unchecked, etc), so
			 * don't balk verbosely at slow random sources either.
			 * There are reports that RDSEED on x86 metal falls
			 * behind the rate at which we query it, for example.
			 * But it's still a better entropy source than RDRAND.
			 */
			if (n == 0)
				continue;
			random_harvest_direct(entropy, n, rrs->rrs_source->rs_source);
		}
	}
	if (rse_warm)
		epoch_exit_preempt(rs_epoch, &et);
	explicit_bzero(entropy, sizeof(entropy));
}

/*
 * State used for conducting NIST SP 800-90B health tests on entropy sources.
 */
static struct health_test_softc {
	uint32_t ht_rct_value[HARVESTSIZE + 1];
	u_int ht_rct_count;	/* number of samples with the same value */
	u_int ht_rct_limit;	/* constant after init */

	uint32_t ht_apt_value[HARVESTSIZE + 1];
	u_int ht_apt_count;	/* number of samples with the same value */
	u_int ht_apt_seq;	/* sequence number of the last sample */
	u_int ht_apt_cutoff;	/* constant after init */

	uint64_t ht_total_samples;
	bool ondemand;		/* Set to true to restart the state machine */
	enum {
		INIT = 0,	/* initial state */
		DISABLED,	/* health checking is disabled */
		STARTUP,	/* doing startup tests, samples are discarded */
		STEADY,		/* steady-state operation */
		FAILED,		/* health check failed, discard samples */
	} ht_state;
} healthtest[ENTROPYSOURCE];

#define	RANDOM_SELFTEST_STARTUP_SAMPLES	1024	/* 4.3, requirement 4 */
#define	RANDOM_SELFTEST_APT_WINDOW	512	/* 4.4.2 */

static void
copy_event(uint32_t dst[static HARVESTSIZE + 1],
    const struct harvest_event *event)
{
	memset(dst, 0, sizeof(uint32_t) * (HARVESTSIZE + 1));
	memcpy(dst, event->he_entropy, event->he_size);
	dst[HARVESTSIZE] = event->he_somecounter;
}

static void
random_healthtest_rct_init(struct health_test_softc *ht,
    const struct harvest_event *event)
{
	ht->ht_rct_count = 1;
	copy_event(ht->ht_rct_value, event);
}

/*
 * Apply the repitition count test to a sample.
 *
 * Return false if the test failed, i.e., we observed >= C consecutive samples
 * with the same value, and true otherwise.
 */
static bool
random_healthtest_rct_next(struct health_test_softc *ht,
    const struct harvest_event *event)
{
	uint32_t val[HARVESTSIZE + 1];

	copy_event(val, event);
	if (memcmp(val, ht->ht_rct_value, sizeof(ht->ht_rct_value)) != 0) {
		ht->ht_rct_count = 1;
		memcpy(ht->ht_rct_value, val, sizeof(ht->ht_rct_value));
		return (true);
	} else {
		ht->ht_rct_count++;
		return (ht->ht_rct_count < ht->ht_rct_limit);
	}
}

static void
random_healthtest_apt_init(struct health_test_softc *ht,
    const struct harvest_event *event)
{
	ht->ht_apt_count = 1;
	ht->ht_apt_seq = 1;
	copy_event(ht->ht_apt_value, event);
}

static bool
random_healthtest_apt_next(struct health_test_softc *ht,
    const struct harvest_event *event)
{
	uint32_t val[HARVESTSIZE + 1];

	if (ht->ht_apt_seq == 0) {
		random_healthtest_apt_init(ht, event);
		return (true);
	}

	copy_event(val, event);
	if (memcmp(val, ht->ht_apt_value, sizeof(ht->ht_apt_value)) == 0) {
		ht->ht_apt_count++;
		if (ht->ht_apt_count >= ht->ht_apt_cutoff)
			return (false);
	}

	ht->ht_apt_seq++;
	if (ht->ht_apt_seq == RANDOM_SELFTEST_APT_WINDOW)
		ht->ht_apt_seq = 0;

	return (true);
}

/*
 * Run the health tests for the given event.  This is assumed to be called from
 * a serialized context.
 */
bool
random_harvest_healthtest(const struct harvest_event *event)
{
	struct health_test_softc *ht;

	ht = &healthtest[event->he_source];

	/*
	 * Was on-demand testing requested?  Restart the state machine if so,
	 * restarting the startup tests.
	 */
	if (atomic_load_bool(&ht->ondemand)) {
		atomic_store_bool(&ht->ondemand, false);
		ht->ht_state = INIT;
	}

	switch (ht->ht_state) {
	case __predict_false(INIT):
		/* Store the first sample and initialize test state. */
		random_healthtest_rct_init(ht, event);
		random_healthtest_apt_init(ht, event);
		ht->ht_total_samples = 0;
		ht->ht_state = STARTUP;
		return (false);
	case DISABLED:
		/* No health testing for this source. */
		return (true);
	case STEADY:
	case STARTUP:
		ht->ht_total_samples++;
		if (random_healthtest_rct_next(ht, event) &&
		    random_healthtest_apt_next(ht, event)) {
			if (ht->ht_state == STARTUP &&
			    ht->ht_total_samples >=
			    RANDOM_SELFTEST_STARTUP_SAMPLES) {
				printf(
			    "random: health test passed for source %s\n",
				    random_source_descr[event->he_source]);
				ht->ht_state = STEADY;
			}
			return (ht->ht_state == STEADY);
		}
		ht->ht_state = FAILED;
		printf(
	    "random: health test failed for source %s, discarding samples\n",
		    random_source_descr[event->he_source]);
		/* FALLTHROUGH */
	case FAILED:
		return (false);
	}
}

static bool nist_healthtest_enabled = false;
SYSCTL_BOOL(_kern_random, OID_AUTO, nist_healthtest_enabled,
    CTLFLAG_RDTUN, &nist_healthtest_enabled, 0,
    "Enable NIST SP 800-90B health tests for noise sources");

static void
random_healthtest_init(enum random_entropy_source source)
{
	struct health_test_softc *ht;

	ht = &healthtest[source];
	KASSERT(ht->ht_state == INIT,
	    ("%s: health test state is %d for source %d",
	    __func__, ht->ht_state, source));

	/*
	 * If health-testing is enabled, validate all sources except CACHED and
	 * VMGENID: they are deterministic sources used only a small, fixed
	 * number of times, so statistical testing is not applicable.
	 */
	if (!nist_healthtest_enabled ||
	    source == RANDOM_CACHED || source == RANDOM_PURE_VMGENID) {
		ht->ht_state = DISABLED;
		return;
	}

	/*
	 * Set cutoff values for the two tests, assuming that each sample has
	 * min-entropy of 1 bit and allowing for an error rate of 1 in 2^{34}.
	 * With a sample rate of RANDOM_KTHREAD_HZ, we expect to see an false
	 * positive once in ~54.5 years.
	 *
	 * The RCT limit comes from the formula in section 4.4.1.
	 *
	 * The APT cutoff is calculated using the formula in section 4.4.2
	 * footnote 10 with the number of Bernoulli trials changed from W to
	 * W-1, since the test as written counts the number of samples equal to
	 * the first sample in the window, and thus tests W-1 samples.
	 */
	ht->ht_rct_limit = 35;
	ht->ht_apt_cutoff = 330;
}

static int
random_healthtest_ondemand(SYSCTL_HANDLER_ARGS)
{
	u_int mask, source;
	int error;

	mask = 0;
	error = sysctl_handle_int(oidp, &mask, 0, req);
	if (error != 0 || req->newptr == NULL)
		return (error);

	while (mask != 0) {
		source = ffs(mask) - 1;
		if (source < nitems(healthtest))
			atomic_store_bool(&healthtest[source].ondemand, true);
		mask &= ~(1u << source);
	}
	return (0);
}
SYSCTL_PROC(_kern_random, OID_AUTO, nist_healthtest_ondemand,
    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, NULL, 0,
    random_healthtest_ondemand, "I",
    "Re-run NIST SP 800-90B startup health tests for a noise source");

static int
random_check_uint_harvestmask(SYSCTL_HANDLER_ARGS)
{
	static const u_int user_immutable_mask =
	    (((1 << ENTROPYSOURCE) - 1) & (-1UL << RANDOM_PURE_START)) |
	    _RANDOM_HARVEST_ETHER_OFF | _RANDOM_HARVEST_UMA_OFF;

	int error;
	u_int value, orig_value;

	orig_value = value = hc_source_mask;
	error = sysctl_handle_int(oidp, &value, 0, req);
	if (error != 0 || req->newptr == NULL)
		return (error);

	if (flsl(value) > ENTROPYSOURCE)
		return (EINVAL);

	/*
	 * Disallow userspace modification of pure entropy sources.
	 */
	hc_source_mask = (value & ~user_immutable_mask) |
	    (orig_value & user_immutable_mask);
	return (0);
}
SYSCTL_PROC(_kern_random_harvest, OID_AUTO, mask,
    CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_NEEDGIANT, NULL, 0,
    random_check_uint_harvestmask, "IU",
    "Entropy harvesting mask");

static int
random_print_harvestmask(SYSCTL_HANDLER_ARGS)
{
	struct sbuf sbuf;
	int error, i;

	error = sysctl_wire_old_buffer(req, 0);
	if (error == 0) {
		sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
		for (i = ENTROPYSOURCE - 1; i >= 0; i--)
			sbuf_cat(&sbuf, (hc_source_mask & (1 << i)) ? "1" : "0");
		error = sbuf_finish(&sbuf);
		sbuf_delete(&sbuf);
	}
	return (error);
}
SYSCTL_PROC(_kern_random_harvest, OID_AUTO, mask_bin,
    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
    random_print_harvestmask, "A",
    "Entropy harvesting mask (printable)");

static const char *random_source_descr[ENTROPYSOURCE] = {
	[RANDOM_CACHED] = "CACHED",
	[RANDOM_ATTACH] = "ATTACH",
	[RANDOM_KEYBOARD] = "KEYBOARD",
	[RANDOM_MOUSE] = "MOUSE",
	[RANDOM_NET_TUN] = "NET_TUN",
	[RANDOM_NET_ETHER] = "NET_ETHER",
	[RANDOM_NET_NG] = "NET_NG",
	[RANDOM_INTERRUPT] = "INTERRUPT",
	[RANDOM_SWI] = "SWI",
	[RANDOM_FS_ATIME] = "FS_ATIME",
	[RANDOM_UMA] = "UMA",
	[RANDOM_CALLOUT] = "CALLOUT",
	[RANDOM_RANDOMDEV] = "RANDOMDEV", /* ENVIRONMENTAL_END */
	[RANDOM_PURE_OCTEON] = "PURE_OCTEON", /* PURE_START */
	[RANDOM_PURE_SAFE] = "PURE_SAFE",
	[RANDOM_PURE_GLXSB] = "PURE_GLXSB",
	[RANDOM_PURE_HIFN] = "PURE_HIFN",
	[RANDOM_PURE_RDRAND] = "PURE_RDRAND",
	[RANDOM_PURE_NEHEMIAH] = "PURE_NEHEMIAH",
	[RANDOM_PURE_RNDTEST] = "PURE_RNDTEST",
	[RANDOM_PURE_VIRTIO] = "PURE_VIRTIO",
	[RANDOM_PURE_BROADCOM] = "PURE_BROADCOM",
	[RANDOM_PURE_CCP] = "PURE_CCP",
	[RANDOM_PURE_DARN] = "PURE_DARN",
	[RANDOM_PURE_TPM] = "PURE_TPM",
	[RANDOM_PURE_VMGENID] = "PURE_VMGENID",
	[RANDOM_PURE_QUALCOMM] = "PURE_QUALCOMM",
	[RANDOM_PURE_ARMV8] = "PURE_ARMV8",
	[RANDOM_PURE_ARM_TRNG] = "PURE_ARM_TRNG",
	/* "ENTROPYSOURCE" */
};

static int
random_print_harvestmask_symbolic(SYSCTL_HANDLER_ARGS)
{
	struct sbuf sbuf;
	int error, i;
	bool first;

	first = true;
	error = sysctl_wire_old_buffer(req, 0);
	if (error == 0) {
		sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
		for (i = ENTROPYSOURCE - 1; i >= 0; i--) {
			if (i >= RANDOM_PURE_START &&
			    (hc_source_mask & (1 << i)) == 0)
				continue;
			if (!first)
				sbuf_cat(&sbuf, ",");
			sbuf_cat(&sbuf, !(hc_source_mask & (1 << i)) ? "[" : "");
			sbuf_cat(&sbuf, random_source_descr[i]);
			sbuf_cat(&sbuf, !(hc_source_mask & (1 << i)) ? "]" : "");
			first = false;
		}
		error = sbuf_finish(&sbuf);
		sbuf_delete(&sbuf);
	}
	return (error);
}
SYSCTL_PROC(_kern_random_harvest, OID_AUTO, mask_symbolic,
    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
    random_print_harvestmask_symbolic, "A",
    "Entropy harvesting mask (symbolic)");

static void
random_harvestq_init(void *unused __unused)
{
	static const u_int almost_everything_mask =
	    (((1 << (RANDOM_ENVIRONMENTAL_END + 1)) - 1) &
	    ~_RANDOM_HARVEST_ETHER_OFF & ~_RANDOM_HARVEST_UMA_OFF);

	hc_source_mask = almost_everything_mask;
	RANDOM_HARVEST_INIT_LOCK();
	harvest_context.hc_active_buf = 0;

	for (int i = 0; i < ENTROPYSOURCE; i++)
		random_healthtest_init(i);
}
SYSINIT(random_device_h_init, SI_SUB_RANDOM, SI_ORDER_THIRD, random_harvestq_init, NULL);

/*
 * Subroutine to slice up a contiguous chunk of 'entropy' and feed it into the
 * underlying algorithm.  Returns number of bytes actually fed into underlying
 * algorithm.
 */
static size_t
random_early_prime(char *entropy, size_t len)
{
	struct harvest_event event;
	size_t i;

	len = rounddown(len, sizeof(event.he_entropy));
	if (len == 0)
		return (0);

	for (i = 0; i < len; i += sizeof(event.he_entropy)) {
		event.he_somecounter = random_get_cyclecount();
		event.he_size = sizeof(event.he_entropy);
		event.he_source = RANDOM_CACHED;
		event.he_destination =
		    harvest_context.hc_destination[RANDOM_CACHED]++;
		memcpy(event.he_entropy, entropy + i, sizeof(event.he_entropy));
		random_harvestq_fast_process_event(&event);
	}
	explicit_bzero(entropy, len);
	return (len);
}

/*
 * Subroutine to search for known loader-loaded files in memory and feed them
 * into the underlying algorithm early in boot.  Returns the number of bytes
 * loaded (zero if none were loaded).
 */
static size_t
random_prime_loader_file(const char *type)
{
	uint8_t *keyfile, *data;
	size_t size;

	keyfile = preload_search_by_type(type);
	if (keyfile == NULL)
		return (0);

	data = preload_fetch_addr(keyfile);
	size = preload_fetch_size(keyfile);
	if (data == NULL)
		return (0);

	return (random_early_prime(data, size));
}

/*
 * This is used to prime the RNG by grabbing any early random stuff
 * known to the kernel, and inserting it directly into the hashing
 * module, currently Fortuna.
 */
static void
random_harvestq_prime(void *unused __unused)
{
	size_t size;

	/*
	 * Get entropy that may have been preloaded by loader(8)
	 * and use it to pre-charge the entropy harvest queue.
	 */
	size = random_prime_loader_file(RANDOM_CACHED_BOOT_ENTROPY_MODULE);
	if (bootverbose) {
		if (size > 0)
			printf("random: read %zu bytes from preloaded cache\n",
			    size);
		else
			printf("random: no preloaded entropy cache\n");
	}
	size = random_prime_loader_file(RANDOM_PLATFORM_BOOT_ENTROPY_MODULE);
	if (bootverbose) {
		if (size > 0)
			printf("random: read %zu bytes from platform bootloader\n",
			    size);
		else
			printf("random: no platform bootloader entropy\n");
	}
}
SYSINIT(random_device_prime, SI_SUB_RANDOM, SI_ORDER_MIDDLE, random_harvestq_prime, NULL);

static void
random_harvestq_deinit(void *unused __unused)
{

	/* Command the hash/reseed thread to end and wait for it to finish */
	random_kthread_control = 0;
	while (random_kthread_control >= 0)
		tsleep(&harvest_context.hc_kthread_proc, 0, "harvqterm", hz/5);
}
SYSUNINIT(random_device_h_init, SI_SUB_RANDOM, SI_ORDER_THIRD, random_harvestq_deinit, NULL);

/*-
 * Entropy harvesting queue routine.
 *
 * This is supposed to be fast; do not do anything slow in here!
 * It is also illegal (and morally reprehensible) to insert any
 * high-rate data here. "High-rate" is defined as a data source
 * that is likely to fill up the buffer in much less than 100ms.
 * This includes the "always-on" sources like the Intel "rdrand"
 * or the VIA Nehamiah "xstore" sources.
 */
/* XXXRW: get_cyclecount() is cheap on most modern hardware, where cycle
 * counters are built in, but on older hardware it will do a real time clock
 * read which can be quite expensive.
 */
void
random_harvest_queue_(const void *entropy, u_int size, enum random_entropy_source origin)
{
	struct harvest_context *hc;
	struct entropy_buffer *buf;
	struct harvest_event *event;

	KASSERT(origin >= RANDOM_START && origin < ENTROPYSOURCE,
	    ("%s: origin %d invalid", __func__, origin));

	hc = &harvest_context;
	RANDOM_HARVEST_LOCK();
	buf = &hc->hc_entropy_buf[hc->hc_active_buf];
	if (buf->pos < RANDOM_RING_MAX) {
		event = &buf->ring[buf->pos++];
		event->he_somecounter = random_get_cyclecount();
		event->he_source = origin;
		event->he_destination = hc->hc_destination[origin]++;
		if (size <= sizeof(event->he_entropy)) {
			event->he_size = size;
			memcpy(event->he_entropy, entropy, size);
		} else {
			/* Big event, so squash it */
			event->he_size = sizeof(event->he_entropy[0]);
			event->he_entropy[0] = jenkins_hash(entropy, size, (uint32_t)(uintptr_t)event);
		}
	}
	RANDOM_HARVEST_UNLOCK();
}

/*-
 * Entropy harvesting fast routine.
 *
 * This is supposed to be very fast; do not do anything slow in here!
 * This is the right place for high-rate harvested data.
 */
void
random_harvest_fast_(const void *entropy, u_int size)
{
	u_int pos;

	pos = harvest_context.hc_entropy_fast_accumulator.pos;
	harvest_context.hc_entropy_fast_accumulator.buf[pos] ^=
	    jenkins_hash(entropy, size, random_get_cyclecount());
	harvest_context.hc_entropy_fast_accumulator.pos = (pos + 1)%RANDOM_ACCUM_MAX;
}

/*-
 * Entropy harvesting direct routine.
 *
 * This is not supposed to be fast, but will only be used during
 * (e.g.) booting when initial entropy is being gathered.
 */
void
random_harvest_direct_(const void *entropy, u_int size, enum random_entropy_source origin)
{
	struct harvest_event event;

	KASSERT(origin >= RANDOM_START && origin < ENTROPYSOURCE, ("%s: origin %d invalid\n", __func__, origin));
	size = MIN(size, sizeof(event.he_entropy));
	event.he_somecounter = random_get_cyclecount();
	event.he_size = size;
	event.he_source = origin;
	event.he_destination = harvest_context.hc_destination[origin]++;
	memcpy(event.he_entropy, entropy, size);
	random_harvestq_fast_process_event(&event);
}

void
random_harvest_register_source(enum random_entropy_source source)
{

	hc_source_mask |= (1 << source);
}

void
random_harvest_deregister_source(enum random_entropy_source source)
{

	hc_source_mask &= ~(1 << source);
}

void
random_source_register(const struct random_source *rsource)
{
	struct random_sources *rrs;

	KASSERT(rsource != NULL, ("invalid input to %s", __func__));

	rrs = malloc(sizeof(*rrs), M_ENTROPY, M_WAITOK);
	rrs->rrs_source = rsource;

	random_harvest_register_source(rsource->rs_source);

	printf("random: registering fast source %s\n", rsource->rs_ident);

	RANDOM_HARVEST_LOCK();
	CK_LIST_INSERT_HEAD(&source_list, rrs, rrs_entries);
	RANDOM_HARVEST_UNLOCK();
}

void
random_source_deregister(const struct random_source *rsource)
{
	struct random_sources *rrs = NULL;

	KASSERT(rsource != NULL, ("invalid input to %s", __func__));

	random_harvest_deregister_source(rsource->rs_source);

	RANDOM_HARVEST_LOCK();
	CK_LIST_FOREACH(rrs, &source_list, rrs_entries)
		if (rrs->rrs_source == rsource) {
			CK_LIST_REMOVE(rrs, rrs_entries);
			break;
		}
	RANDOM_HARVEST_UNLOCK();

	if (rrs != NULL && epoch_inited)
		epoch_wait_preempt(rs_epoch);
	free(rrs, M_ENTROPY);
}

static int
random_source_handler(SYSCTL_HANDLER_ARGS)
{
	struct epoch_tracker et;
	struct random_sources *rrs;
	struct sbuf sbuf;
	int error, count;

	error = sysctl_wire_old_buffer(req, 0);
	if (error != 0)
		return (error);

	sbuf_new_for_sysctl(&sbuf, NULL, 64, req);
	count = 0;
	epoch_enter_preempt(rs_epoch, &et);
	CK_LIST_FOREACH(rrs, &source_list, rrs_entries) {
		sbuf_cat(&sbuf, (count++ ? ",'" : "'"));
		sbuf_cat(&sbuf, rrs->rrs_source->rs_ident);
		sbuf_cat(&sbuf, "'");
	}
	epoch_exit_preempt(rs_epoch, &et);
	error = sbuf_finish(&sbuf);
	sbuf_delete(&sbuf);
	return (error);
}
SYSCTL_PROC(_kern_random, OID_AUTO, random_sources, CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
	    NULL, 0, random_source_handler, "A",
	    "List of active fast entropy sources.");

MODULE_VERSION(random_harvestq, 1);