Home | History | Annotate | Line # | Download | only in kern
kern_entropy.c revision 1.1
      1 /*	$NetBSD: kern_entropy.c,v 1.1 2020/04/30 03:28:18 riastradh Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2019 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Taylor R. Campbell.
      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  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  * POSSIBILITY OF SUCH DAMAGE.
     30  */
     31 
     32 /*
     33  * Entropy subsystem
     34  *
     35  *	* Each CPU maintains a per-CPU entropy pool so that gathering
     36  *	  entropy requires no interprocessor synchronization, except
     37  *	  early at boot when we may be scrambling to gather entropy as
     38  *	  soon as possible.
     39  *
     40  *	  - entropy_enter gathers entropy and never drops it on the
     41  *	    floor, at the cost of sometimes having to do cryptography.
     42  *
     43  *	  - entropy_enter_intr gathers entropy or drops it on the
     44  *	    floor, with low latency.  Work to stir the pool or kick the
     45  *	    housekeeping thread is scheduled in soft interrupts.
     46  *
     47  *	* entropy_enter immediately enters into the global pool if it
     48  *	  can transition to full entropy in one swell foop.  Otherwise,
     49  *	  it defers to a housekeeping thread that consolidates entropy,
     50  *	  but only when the CPUs collectively have full entropy, in
     51  *	  order to mitigate iterative-guessing attacks.
     52  *
     53  *	* The entropy housekeeping thread continues to consolidate
     54  *	  entropy even after we think we have full entropy, in case we
     55  *	  are wrong, but is limited to one discretionary consolidation
     56  *	  per minute, and only when new entropy is actually coming in,
     57  *	  to limit performance impact.
     58  *
     59  *	* The entropy epoch is the number that changes when we
     60  *	  transition from partial entropy to full entropy, so that
     61  *	  users can easily determine when to reseed.  This also
     62  *	  facilitates an operator explicitly causing everything to
     63  *	  reseed by sysctl -w kern.entropy.consolidate=1, e.g. if they
     64  *	  just flipped a coin 256 times and wrote `echo tthhhhhthh... >
     65  *	  /dev/random'.
     66  *
     67  *	* No entropy estimation based on the sample values, which is a
     68  *	  contradiction in terms and a potential source of side
     69  *	  channels.  It is the responsibility of the driver author to
     70  *	  study how predictable the physical source of input can ever
     71  *	  be, and to furnish a lower bound on the amount of entropy it
     72  *	  has.
     73  *
     74  *	* Entropy depletion is available for testing (or if you're into
     75  *	  that sort of thing), with sysctl -w kern.entropy.depletion=1;
     76  *	  the logic to support it is small, to minimize chance of bugs.
     77  */
     78 
     79 #include <sys/cdefs.h>
     80 __KERNEL_RCSID(0, "$NetBSD: kern_entropy.c,v 1.1 2020/04/30 03:28:18 riastradh Exp $");
     81 
     82 #include <sys/param.h>
     83 #include <sys/types.h>
     84 #include <sys/atomic.h>
     85 #include <sys/compat_stub.h>
     86 #include <sys/condvar.h>
     87 #include <sys/cpu.h>
     88 #include <sys/entropy.h>
     89 #include <sys/errno.h>
     90 #include <sys/evcnt.h>
     91 #include <sys/event.h>
     92 #include <sys/file.h>
     93 #include <sys/intr.h>
     94 #include <sys/kauth.h>
     95 #include <sys/kernel.h>
     96 #include <sys/kmem.h>
     97 #include <sys/kthread.h>
     98 #include <sys/module_hook.h>
     99 #include <sys/mutex.h>
    100 #include <sys/percpu.h>
    101 #include <sys/poll.h>
    102 #include <sys/queue.h>
    103 #include <sys/rnd.h>		/* legacy kernel API */
    104 #include <sys/rndio.h>		/* userland ioctl interface */
    105 #include <sys/rndsource.h>	/* kernel rndsource driver API */
    106 #include <sys/select.h>
    107 #include <sys/selinfo.h>
    108 #include <sys/sha1.h>		/* for boot seed checksum */
    109 #include <sys/stdint.h>
    110 #include <sys/sysctl.h>
    111 #include <sys/systm.h>
    112 #include <sys/time.h>
    113 #include <sys/xcall.h>
    114 
    115 #include <lib/libkern/entpool.h>
    116 
    117 #include <machine/limits.h>
    118 
    119 #ifdef __HAVE_CPU_COUNTER
    120 #include <machine/cpu_counter.h>
    121 #endif
    122 
    123 /*
    124  * struct entropy_cpu
    125  *
    126  *	Per-CPU entropy state.  The pool is allocated separately
    127  *	because percpu(9) sometimes moves per-CPU objects around
    128  *	without zeroing them, which would lead to unwanted copies of
    129  *	sensitive secrets.  The evcnt is allocated separately becuase
    130  *	evcnt(9) assumes it stays put in memory.
    131  */
    132 struct entropy_cpu {
    133 	struct evcnt		*ec_softint_evcnt;
    134 	struct entpool		*ec_pool;
    135 	unsigned		ec_pending;
    136 	bool			ec_locked;
    137 };
    138 
    139 /*
    140  * struct rndsource_cpu
    141  *
    142  *	Per-CPU rndsource state.
    143  */
    144 struct rndsource_cpu {
    145 	unsigned		rc_nbits; /* bits of entropy added */
    146 };
    147 
    148 /*
    149  * entropy_global (a.k.a. E for short in this file)
    150  *
    151  *	Global entropy state.  Writes protected by the global lock.
    152  *	Some fields, marked (A), can be read outside the lock, and are
    153  *	maintained with atomic_load/store_relaxed.
    154  */
    155 struct {
    156 	kmutex_t	lock;		/* covers all global state */
    157 	struct entpool	pool;		/* global pool for extraction */
    158 	unsigned	needed;		/* (A) needed globally */
    159 	unsigned	pending;	/* (A) pending in per-CPU pools */
    160 	unsigned	timestamp;	/* (A) time of last consolidation */
    161 	unsigned	epoch;		/* (A) changes when needed -> 0 */
    162 	kcondvar_t	cv;		/* notifies state changes */
    163 	struct selinfo	selq;		/* notifies needed -> 0 */
    164 	LIST_HEAD(,krndsource) sources;	/* list of entropy sources */
    165 	enum entropy_stage {
    166 		ENTROPY_COLD = 0, /* single-threaded */
    167 		ENTROPY_WARM,	  /* multi-threaded at boot before CPUs */
    168 		ENTROPY_HOT,	  /* multi-threaded multi-CPU */
    169 	}		stage;
    170 	bool		requesting;	/* busy requesting from sources */
    171 	bool		consolidate;	/* kick thread to consolidate */
    172 	bool		seed_rndsource;	/* true if seed source is attached */
    173 	bool		seeded;		/* true if seed file already loaded */
    174 } entropy_global __cacheline_aligned = {
    175 	/* Fields that must be initialized when the kernel is loaded.  */
    176 	.needed = ENTROPY_CAPACITY*NBBY,
    177 	.epoch = (unsigned)-1,	/* -1 means not yet full entropy */
    178 	.sources = LIST_HEAD_INITIALIZER(entropy_global.sources),
    179 	.stage = ENTROPY_COLD,
    180 };
    181 
    182 #define	E	(&entropy_global)	/* declutter */
    183 
    184 /* Read-mostly globals */
    185 static struct percpu	*entropy_percpu __read_mostly; /* struct entropy_cpu */
    186 static void		*entropy_sih __read_mostly; /* softint handler */
    187 static struct lwp	*entropy_lwp __read_mostly; /* housekeeping thread */
    188 
    189 int rnd_initial_entropy __read_mostly; /* XXX legacy */
    190 
    191 static struct krndsource seed_rndsource __read_mostly;
    192 
    193 /*
    194  * Event counters
    195  *
    196  *	Must be careful with adding these because they can serve as
    197  *	side channels.
    198  */
    199 static struct evcnt entropy_discretionary_evcnt =
    200     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "entropy", "discretionary");
    201 EVCNT_ATTACH_STATIC(entropy_discretionary_evcnt);
    202 static struct evcnt entropy_immediate_evcnt =
    203     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "entropy", "immediate");
    204 EVCNT_ATTACH_STATIC(entropy_immediate_evcnt);
    205 static struct evcnt entropy_partial_evcnt =
    206     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "entropy", "partial");
    207 EVCNT_ATTACH_STATIC(entropy_partial_evcnt);
    208 static struct evcnt entropy_consolidate_evcnt =
    209     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "entropy", "consolidate");
    210 EVCNT_ATTACH_STATIC(entropy_consolidate_evcnt);
    211 static struct evcnt entropy_extract_intr_evcnt =
    212     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "entropy", "extract intr");
    213 EVCNT_ATTACH_STATIC(entropy_extract_intr_evcnt);
    214 static struct evcnt entropy_extract_fail_evcnt =
    215     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "entropy", "extract fail");
    216 EVCNT_ATTACH_STATIC(entropy_extract_fail_evcnt);
    217 static struct evcnt entropy_request_evcnt =
    218     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "entropy", "request");
    219 EVCNT_ATTACH_STATIC(entropy_request_evcnt);
    220 static struct evcnt entropy_deplete_evcnt =
    221     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "entropy", "deplete");
    222 EVCNT_ATTACH_STATIC(entropy_deplete_evcnt);
    223 static struct evcnt entropy_notify_evcnt =
    224     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "entropy", "notify");
    225 EVCNT_ATTACH_STATIC(entropy_notify_evcnt);
    226 
    227 /* Sysctl knobs */
    228 bool	entropy_collection = 1;
    229 bool	entropy_depletion = 0; /* Silly!  */
    230 
    231 static const struct sysctlnode	*entropy_sysctlroot;
    232 static struct sysctllog		*entropy_sysctllog;
    233 
    234 /* Forward declarations */
    235 static void	entropy_init_cpu(void *, void *, struct cpu_info *);
    236 static void	entropy_fini_cpu(void *, void *, struct cpu_info *);
    237 static void	entropy_account_cpu(struct entropy_cpu *);
    238 static void	entropy_enter(const void *, size_t, unsigned);
    239 static bool	entropy_enter_intr(const void *, size_t, unsigned);
    240 static void	entropy_softintr(void *);
    241 static void	entropy_thread(void *);
    242 static uint32_t	entropy_pending(void);
    243 static void	entropy_pending_cpu(void *, void *, struct cpu_info *);
    244 static void	entropy_consolidate(void);
    245 static void	entropy_gather_xc(void *, void *);
    246 static void	entropy_notify(void);
    247 static int	sysctl_entropy_consolidate(SYSCTLFN_ARGS);
    248 static void	filt_entropy_read_detach(struct knote *);
    249 static int	filt_entropy_read_event(struct knote *, long);
    250 static void	entropy_request(size_t);
    251 static void	rnd_add_data_1(struct krndsource *, const void *, uint32_t,
    252 		    uint32_t);
    253 static unsigned	rndsource_entropybits(struct krndsource *);
    254 static void	rndsource_entropybits_cpu(void *, void *, struct cpu_info *);
    255 static void	rndsource_to_user(struct krndsource *, rndsource_t *);
    256 static void	rndsource_to_user_est(struct krndsource *, rndsource_est_t *);
    257 
    258 /*
    259  * curcpu_available()
    260  *
    261  *	True if we can inspect the current CPU.  Early on this may not
    262  *	work.  XXX On most if not all ports, this should work earlier.
    263  */
    264 static inline bool
    265 curcpu_available(void)
    266 {
    267 
    268 	return __predict_true(!cold);
    269 }
    270 
    271 /*
    272  * entropy_timer()
    273  *
    274  *	Cycle counter, time counter, or anything that changes a wee bit
    275  *	unpredictably.
    276  */
    277 static inline uint32_t
    278 entropy_timer(void)
    279 {
    280 	struct bintime bt;
    281 	uint32_t v;
    282 
    283 	/* Very early on, cpu_counter32() may not be available.  */
    284 	if (!curcpu_available())
    285 		return 0;
    286 
    287 	/* If we have a CPU cycle counter, use the low 32 bits.  */
    288 #ifdef __HAVE_CPU_COUNTER
    289 	if (__predict_true(cpu_hascounter()))
    290 		return cpu_counter32();
    291 #endif	/* __HAVE_CPU_COUNTER */
    292 
    293 	/* If we're cold, tough.  Can't binuptime while cold.  */
    294 	if (__predict_false(cold))
    295 		return 0;
    296 
    297 	/* Fold the 128 bits of binuptime into 32 bits.  */
    298 	binuptime(&bt);
    299 	v = bt.frac;
    300 	v ^= bt.frac >> 32;
    301 	v ^= bt.sec;
    302 	v ^= bt.sec >> 32;
    303 	return v;
    304 }
    305 
    306 static void
    307 attach_seed_rndsource(void)
    308 {
    309 
    310 	/*
    311 	 * First called no later than entropy_init, while we are still
    312 	 * single-threaded, so no need for RUN_ONCE.
    313 	 */
    314 	if (E->stage >= ENTROPY_WARM || E->seed_rndsource)
    315 		return;
    316 	rnd_attach_source(&seed_rndsource, "seed", RND_TYPE_UNKNOWN,
    317 	    RND_FLAG_COLLECT_VALUE);
    318 	E->seed_rndsource = true;
    319 }
    320 
    321 /*
    322  * entropy_init()
    323  *
    324  *	Initialize the entropy subsystem.  Panic on failure.
    325  *
    326  *	Requires percpu(9) and sysctl(9) to be initialized.
    327  */
    328 static void
    329 entropy_init(void)
    330 {
    331 	uint32_t extra[2];
    332 	struct krndsource *rs;
    333 	unsigned i = 0;
    334 
    335 	KASSERT(E->stage == ENTROPY_COLD);
    336 
    337 	/* Grab some cycle counts early at boot.  */
    338 	extra[i++] = entropy_timer();
    339 
    340 	/* Run the entropy pool cryptography self-test.  */
    341 	if (entpool_selftest() == -1)
    342 		panic("entropy pool crypto self-test failed");
    343 
    344 	/* Create the sysctl directory.  */
    345 	sysctl_createv(&entropy_sysctllog, 0, NULL, &entropy_sysctlroot,
    346 	    CTLFLAG_PERMANENT, CTLTYPE_NODE, "entropy",
    347 	    SYSCTL_DESCR("Entropy (random number sources) options"),
    348 	    NULL, 0, NULL, 0,
    349 	    CTL_KERN, CTL_CREATE, CTL_EOL);
    350 
    351 	/* Create the sysctl knobs.  */
    352 	/* XXX These shouldn't be writable at securelevel>0.  */
    353 	sysctl_createv(&entropy_sysctllog, 0, &entropy_sysctlroot, NULL,
    354 	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE, CTLTYPE_BOOL, "collection",
    355 	    SYSCTL_DESCR("Automatically collect entropy from hardware"),
    356 	    NULL, 0, &entropy_collection, 0, CTL_CREATE, CTL_EOL);
    357 	sysctl_createv(&entropy_sysctllog, 0, &entropy_sysctlroot, NULL,
    358 	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE, CTLTYPE_BOOL, "depletion",
    359 	    SYSCTL_DESCR("`Deplete' entropy pool when observed"),
    360 	    NULL, 0, &entropy_depletion, 0, CTL_CREATE, CTL_EOL);
    361 	sysctl_createv(&entropy_sysctllog, 0, &entropy_sysctlroot, NULL,
    362 	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE, CTLTYPE_INT, "consolidate",
    363 	    SYSCTL_DESCR("Trigger entropy consolidation now"),
    364 	    sysctl_entropy_consolidate, 0, NULL, 0, CTL_CREATE, CTL_EOL);
    365 	/* XXX These should maybe not be readable at securelevel>0.  */
    366 	sysctl_createv(&entropy_sysctllog, 0, &entropy_sysctlroot, NULL,
    367 	    CTLFLAG_PERMANENT|CTLFLAG_READONLY|CTLFLAG_PRIVATE, CTLTYPE_INT,
    368 	    "needed", SYSCTL_DESCR("Systemwide entropy deficit"),
    369 	    NULL, 0, &E->needed, 0, CTL_CREATE, CTL_EOL);
    370 	sysctl_createv(&entropy_sysctllog, 0, &entropy_sysctlroot, NULL,
    371 	    CTLFLAG_PERMANENT|CTLFLAG_READONLY|CTLFLAG_PRIVATE, CTLTYPE_INT,
    372 	    "pending", SYSCTL_DESCR("Entropy pending on CPUs"),
    373 	    NULL, 0, &E->pending, 0, CTL_CREATE, CTL_EOL);
    374 	sysctl_createv(&entropy_sysctllog, 0, &entropy_sysctlroot, NULL,
    375 	    CTLFLAG_PERMANENT|CTLFLAG_READONLY|CTLFLAG_PRIVATE, CTLTYPE_INT,
    376 	    "epoch", SYSCTL_DESCR("Entropy epoch"),
    377 	    NULL, 0, &E->epoch, 0, CTL_CREATE, CTL_EOL);
    378 
    379 	/* Initialize the global state for multithreaded operation.  */
    380 	mutex_init(&E->lock, MUTEX_DEFAULT, IPL_VM);
    381 	cv_init(&E->cv, "entropy");
    382 	selinit(&E->selq);
    383 
    384 	/* Make sure the seed source is attached.  */
    385 	attach_seed_rndsource();
    386 
    387 	/* Note if the bootloader didn't provide a seed.  */
    388 	if (!E->seeded)
    389 		printf("entropy: no seed from bootloader\n");
    390 
    391 	/* Allocate the per-CPU records for all early entropy sources.  */
    392 	LIST_FOREACH(rs, &E->sources, list)
    393 		rs->state = percpu_alloc(sizeof(struct rndsource_cpu));
    394 
    395 	/* Enter the boot cycle count to get started.  */
    396 	extra[i++] = entropy_timer();
    397 	KASSERT(i == __arraycount(extra));
    398 	entropy_enter(extra, sizeof extra, 0);
    399 	explicit_memset(extra, 0, sizeof extra);
    400 
    401 	/* We are now ready for multi-threaded operation.  */
    402 	E->stage = ENTROPY_WARM;
    403 }
    404 
    405 /*
    406  * entropy_init_late()
    407  *
    408  *	Late initialization.  Panic on failure.
    409  *
    410  *	Requires CPUs to have been detected and LWPs to have started.
    411  */
    412 static void
    413 entropy_init_late(void)
    414 {
    415 	int error;
    416 
    417 	KASSERT(E->stage == ENTROPY_WARM);
    418 
    419 	/* Allocate and initialize the per-CPU state.  */
    420 	entropy_percpu = percpu_create(sizeof(struct entropy_cpu),
    421 	    entropy_init_cpu, entropy_fini_cpu, NULL);
    422 
    423 	/*
    424 	 * Establish the softint at the highest softint priority level.
    425 	 * Must happen after CPU detection.
    426 	 */
    427 	entropy_sih = softint_establish(SOFTINT_SERIAL|SOFTINT_MPSAFE,
    428 	    &entropy_softintr, NULL);
    429 	if (entropy_sih == NULL)
    430 		panic("unable to establish entropy softint");
    431 
    432 	/*
    433 	 * Create the entropy housekeeping thread.  Must happen after
    434 	 * lwpinit.
    435 	 */
    436 	error = kthread_create(PRI_NONE, KTHREAD_MPSAFE|KTHREAD_TS, NULL,
    437 	    entropy_thread, NULL, &entropy_lwp, "entbutler");
    438 	if (error)
    439 		panic("unable to create entropy housekeeping thread: %d",
    440 		    error);
    441 
    442 	/*
    443 	 * Wait until the per-CPU initialization has hit all CPUs
    444 	 * before proceeding to mark the entropy system hot.
    445 	 */
    446 	xc_barrier(XC_HIGHPRI);
    447 	E->stage = ENTROPY_HOT;
    448 }
    449 
    450 /*
    451  * entropy_init_cpu(ptr, cookie, ci)
    452  *
    453  *	percpu(9) constructor for per-CPU entropy pool.
    454  */
    455 static void
    456 entropy_init_cpu(void *ptr, void *cookie, struct cpu_info *ci)
    457 {
    458 	struct entropy_cpu *ec = ptr;
    459 
    460 	ec->ec_softint_evcnt = kmem_alloc(sizeof(*ec->ec_softint_evcnt),
    461 	    KM_SLEEP);
    462 	ec->ec_pool = kmem_zalloc(sizeof(*ec->ec_pool), KM_SLEEP);
    463 	ec->ec_pending = 0;
    464 	ec->ec_locked = false;
    465 
    466 	evcnt_attach_dynamic(ec->ec_softint_evcnt, EVCNT_TYPE_MISC, NULL,
    467 	    ci->ci_cpuname, "entropy softint");
    468 }
    469 
    470 /*
    471  * entropy_fini_cpu(ptr, cookie, ci)
    472  *
    473  *	percpu(9) destructor for per-CPU entropy pool.
    474  */
    475 static void
    476 entropy_fini_cpu(void *ptr, void *cookie, struct cpu_info *ci)
    477 {
    478 	struct entropy_cpu *ec = ptr;
    479 
    480 	/*
    481 	 * Zero any lingering data.  Disclosure of the per-CPU pool
    482 	 * shouldn't retroactively affect the security of any keys
    483 	 * generated, because entpool(9) erases whatever we have just
    484 	 * drawn out of any pool, but better safe than sorry.
    485 	 */
    486 	explicit_memset(ec->ec_pool, 0, sizeof(*ec->ec_pool));
    487 
    488 	evcnt_detach(ec->ec_softint_evcnt);
    489 
    490 	kmem_free(ec->ec_pool, sizeof(*ec->ec_pool));
    491 	kmem_free(ec->ec_softint_evcnt, sizeof(*ec->ec_softint_evcnt));
    492 }
    493 
    494 /*
    495  * entropy_seed(seed)
    496  *
    497  *	Seed the entropy pool with seed.  Meant to be called as early
    498  *	as possible by the bootloader; may be called before or after
    499  *	entropy_init.  Must be called before system reaches userland.
    500  *	Must be called in thread or soft interrupt context, not in hard
    501  *	interrupt context.  Must be called at most once.
    502  *
    503  *	Overwrites the seed in place.  Caller may then free the memory.
    504  */
    505 static void
    506 entropy_seed(rndsave_t *seed)
    507 {
    508 	SHA1_CTX ctx;
    509 	uint8_t digest[SHA1_DIGEST_LENGTH];
    510 	bool seeded;
    511 
    512 	/*
    513 	 * Verify the checksum.  If the checksum fails, take the data
    514 	 * but ignore the entropy estimate -- the file may have been
    515 	 * incompletely written with garbage, which is harmless to add
    516 	 * but may not be as unpredictable as alleged.
    517 	 *
    518 	 * XXX There is a byte order dependency here...
    519 	 */
    520 	SHA1Init(&ctx);
    521 	SHA1Update(&ctx, (const void *)&seed->entropy, sizeof(seed->entropy));
    522 	SHA1Update(&ctx, seed->data, sizeof(seed->data));
    523 	SHA1Final(digest, &ctx);
    524 	CTASSERT(sizeof(seed->digest) == sizeof(digest));
    525 	if (!consttime_memequal(digest, seed->digest, sizeof(digest))) {
    526 		printf("entropy: invalid seed checksum\n");
    527 		seed->entropy = 0;
    528 	}
    529 	explicit_memset(&ctx, 0, sizeof &ctx);
    530 	explicit_memset(digest, 0, sizeof digest);
    531 
    532 	/* Make sure the seed source is attached.  */
    533 	attach_seed_rndsource();
    534 
    535 	/* Test and set E->seeded.  */
    536 	if (E->stage >= ENTROPY_WARM)
    537 		mutex_enter(&E->lock);
    538 	seeded = E->seeded;
    539 	E->seeded = true;
    540 	if (E->stage >= ENTROPY_WARM)
    541 		mutex_exit(&E->lock);
    542 
    543 	/*
    544 	 * If we've been seeded, may be re-entering the same seed
    545 	 * (e.g., bootloader vs module init, or something).  No harm in
    546 	 * entering it twice, but it contributes no additional entropy.
    547 	 */
    548 	if (seeded) {
    549 		printf("entropy: double-seeded by bootloader\n");
    550 		seed->entropy = 0;
    551 	} else {
    552 		printf("entropy: entering seed from bootloader\n");
    553 	}
    554 
    555 	/* Enter it into the pool and promptly zero it.  */
    556 	rnd_add_data(&seed_rndsource, seed->data, sizeof(seed->data),
    557 	    seed->entropy);
    558 	explicit_memset(seed, 0, sizeof(*seed));
    559 }
    560 
    561 /*
    562  * entropy_bootrequest()
    563  *
    564  *	Request entropy from all sources at boot, once config is
    565  *	complete and interrupts are running.
    566  */
    567 void
    568 entropy_bootrequest(void)
    569 {
    570 
    571 	KASSERT(E->stage >= ENTROPY_WARM);
    572 
    573 	/*
    574 	 * Request enough to satisfy the maximum entropy shortage.
    575 	 * This is harmless overkill if the bootloader provided a seed.
    576 	 */
    577 	mutex_enter(&E->lock);
    578 	entropy_request(ENTROPY_CAPACITY);
    579 	mutex_exit(&E->lock);
    580 }
    581 
    582 /*
    583  * entropy_epoch()
    584  *
    585  *	Returns the current entropy epoch.  If this changes, you should
    586  *	reseed.  If -1, means the system has not yet reached full
    587  *	entropy; never reverts back to -1 after full entropy has been
    588  *	reached.  Never zero, so you can always use zero as an
    589  *	uninitialized sentinel value meaning `reseed ASAP'.
    590  *
    591  *	Usage model:
    592  *
    593  *		struct foo {
    594  *			struct crypto_prng prng;
    595  *			unsigned epoch;
    596  *		} *foo;
    597  *
    598  *		unsigned epoch = entropy_epoch();
    599  *		if (__predict_false(epoch != foo->epoch)) {
    600  *			uint8_t seed[32];
    601  *			if (entropy_extract(seed, sizeof seed, 0) != 0)
    602  *				warn("no entropy");
    603  *			crypto_prng_reseed(&foo->prng, seed, sizeof seed);
    604  *			foo->epoch = epoch;
    605  *		}
    606  */
    607 unsigned
    608 entropy_epoch(void)
    609 {
    610 
    611 	/*
    612 	 * Unsigned int, so no need for seqlock for an atomic read, but
    613 	 * make sure we read it afresh each time.
    614 	 */
    615 	return atomic_load_relaxed(&E->epoch);
    616 }
    617 
    618 /*
    619  * entropy_account_cpu(ec)
    620  *
    621  *	Consider whether to consolidate entropy into the global pool
    622  *	after we just added some into the current CPU's pending pool.
    623  *
    624  *	- If this CPU can provide enough entropy now, do so.
    625  *
    626  *	- If this and whatever else is available on other CPUs can
    627  *	  provide enough entropy, kick the consolidation thread.
    628  *
    629  *	- Otherwise, do as little as possible, except maybe consolidate
    630  *	  entropy at most once a minute.
    631  *
    632  *	Caller must be bound to a CPU and therefore have exclusive
    633  *	access to ec.  Will acquire and release the global lock.
    634  */
    635 static void
    636 entropy_account_cpu(struct entropy_cpu *ec)
    637 {
    638 	unsigned diff;
    639 
    640 	KASSERT(E->stage == ENTROPY_HOT);
    641 
    642 	/*
    643 	 * If there's no entropy needed, and entropy has been
    644 	 * consolidated in the last minute, do nothing.
    645 	 */
    646 	if (__predict_true(atomic_load_relaxed(&E->needed) == 0) &&
    647 	    __predict_true(!atomic_load_relaxed(&entropy_depletion)) &&
    648 	    __predict_true((time_uptime - E->timestamp) <= 60))
    649 		return;
    650 
    651 	/* If there's nothing pending, stop here.  */
    652 	if (ec->ec_pending == 0)
    653 		return;
    654 
    655 	/* Consider consolidation, under the lock.  */
    656 	mutex_enter(&E->lock);
    657 	if (E->needed != 0 && E->needed <= ec->ec_pending) {
    658 		/*
    659 		 * If we have not yet attained full entropy but we can
    660 		 * now, do so.  This way we disseminate entropy
    661 		 * promptly when it becomes available early at boot;
    662 		 * otherwise we leave it to the entropy consolidation
    663 		 * thread, which is rate-limited to mitigate side
    664 		 * channels and abuse.
    665 		 */
    666 		uint8_t buf[ENTPOOL_CAPACITY];
    667 
    668 		/* Transfer from the local pool to the global pool.  */
    669 		entpool_extract(ec->ec_pool, buf, sizeof buf);
    670 		entpool_enter(&E->pool, buf, sizeof buf);
    671 		atomic_store_relaxed(&ec->ec_pending, 0);
    672 		atomic_store_relaxed(&E->needed, 0);
    673 
    674 		/* Notify waiters that we now have full entropy.  */
    675 		entropy_notify();
    676 		entropy_immediate_evcnt.ev_count++;
    677 	} else if (ec->ec_pending) {
    678 		/* Record how much we can add to the global pool.  */
    679 		diff = MIN(ec->ec_pending, ENTROPY_CAPACITY*NBBY - E->pending);
    680 		E->pending += diff;
    681 		atomic_store_relaxed(&ec->ec_pending, ec->ec_pending - diff);
    682 
    683 		/*
    684 		 * This should have made a difference unless we were
    685 		 * already saturated.
    686 		 */
    687 		KASSERT(diff || E->pending == ENTROPY_CAPACITY*NBBY);
    688 		KASSERT(E->pending);
    689 
    690 		if (E->needed <= E->pending) {
    691 			/*
    692 			 * Enough entropy between all the per-CPU
    693 			 * pools.  Wake up the housekeeping thread.
    694 			 *
    695 			 * If we don't need any entropy, this doesn't
    696 			 * mean much, but it is the only time we ever
    697 			 * gather additional entropy in case the
    698 			 * accounting has been overly optimistic.  This
    699 			 * happens at most once a minute, so there's
    700 			 * negligible performance cost.
    701 			 */
    702 			E->consolidate = true;
    703 			cv_broadcast(&E->cv);
    704 			if (E->needed == 0)
    705 				entropy_discretionary_evcnt.ev_count++;
    706 		} else {
    707 			/* Can't get full entropy.  Keep gathering.  */
    708 			entropy_partial_evcnt.ev_count++;
    709 		}
    710 	}
    711 	mutex_exit(&E->lock);
    712 }
    713 
    714 /*
    715  * entropy_enter_early(buf, len, nbits)
    716  *
    717  *	Do entropy bookkeeping globally, before we have established
    718  *	per-CPU pools.  Enter directly into the global pool in the hope
    719  *	that we enter enough before the first entropy_extract to thwart
    720  *	iterative-guessing attacks; entropy_extract will warn if not.
    721  */
    722 static void
    723 entropy_enter_early(const void *buf, size_t len, unsigned nbits)
    724 {
    725 	bool notify = false;
    726 
    727 	if (E->stage >= ENTROPY_WARM)
    728 		mutex_enter(&E->lock);
    729 
    730 	/* Enter it into the pool.  */
    731 	entpool_enter(&E->pool, buf, len);
    732 
    733 	/*
    734 	 * Decide whether to notify reseed -- we will do so if either:
    735 	 * (a) we transition from partial entropy to full entropy, or
    736 	 * (b) we get a batch of full entropy all at once.
    737 	 */
    738 	notify |= (E->needed && E->needed <= nbits);
    739 	notify |= (nbits >= ENTROPY_CAPACITY*NBBY);
    740 
    741 	/* Subtract from the needed count and notify if appropriate.  */
    742 	E->needed -= MIN(E->needed, nbits);
    743 	if (notify) {
    744 		entropy_notify();
    745 		entropy_immediate_evcnt.ev_count++;
    746 	}
    747 
    748 	if (E->stage >= ENTROPY_WARM)
    749 		mutex_exit(&E->lock);
    750 }
    751 
    752 /*
    753  * entropy_enter(buf, len, nbits)
    754  *
    755  *	Enter len bytes of data from buf into the system's entropy
    756  *	pool, stirring as necessary when the internal buffer fills up.
    757  *	nbits is a lower bound on the number of bits of entropy in the
    758  *	process that led to this sample.
    759  */
    760 static void
    761 entropy_enter(const void *buf, size_t len, unsigned nbits)
    762 {
    763 	struct entropy_cpu *ec;
    764 	uint32_t pending;
    765 	int s;
    766 
    767 	KASSERTMSG(!curcpu_available() || !cpu_intr_p(),
    768 	    "use entropy_enter_intr from interrupt context");
    769 	KASSERTMSG(howmany(nbits, NBBY) <= len,
    770 	    "impossible entropy rate: %u bits in %zu-byte string", nbits, len);
    771 
    772 	/* If it's too early after boot, just use entropy_enter_early.  */
    773 	if (__predict_false(E->stage < ENTROPY_HOT)) {
    774 		entropy_enter_early(buf, len, nbits);
    775 		return;
    776 	}
    777 
    778 	/*
    779 	 * Acquire the per-CPU state, blocking soft interrupts and
    780 	 * causing hard interrupts to drop samples on the floor.
    781 	 */
    782 	ec = percpu_getref(entropy_percpu);
    783 	s = splsoftserial();
    784 	KASSERT(!ec->ec_locked);
    785 	ec->ec_locked = true;
    786 	__insn_barrier();
    787 
    788 	/* Enter into the per-CPU pool.  */
    789 	entpool_enter(ec->ec_pool, buf, len);
    790 
    791 	/* Count up what we can add.  */
    792 	pending = ec->ec_pending;
    793 	pending += MIN(ENTROPY_CAPACITY*NBBY - pending, nbits);
    794 	atomic_store_relaxed(&ec->ec_pending, pending);
    795 
    796 	/* Consolidate globally if appropriate based on what we added.  */
    797 	entropy_account_cpu(ec);
    798 
    799 	/* Release the per-CPU state.  */
    800 	KASSERT(ec->ec_locked);
    801 	__insn_barrier();
    802 	ec->ec_locked = false;
    803 	splx(s);
    804 	percpu_putref(entropy_percpu);
    805 }
    806 
    807 /*
    808  * entropy_enter_intr(buf, len, nbits)
    809  *
    810  *	Enter up to len bytes of data from buf into the system's
    811  *	entropy pool without stirring.  nbits is a lower bound on the
    812  *	number of bits of entropy in the process that led to this
    813  *	sample.  If the sample could be entered completely, assume
    814  *	nbits of entropy pending; otherwise assume none, since we don't
    815  *	know whether some parts of the sample are constant, for
    816  *	instance.  Schedule a softint to stir the entropy pool if
    817  *	needed.  Return true if used fully, false if truncated at all.
    818  *
    819  *	Using this in thread context will work, but you might as well
    820  *	use entropy_enter in that case.
    821  */
    822 static bool
    823 entropy_enter_intr(const void *buf, size_t len, unsigned nbits)
    824 {
    825 	struct entropy_cpu *ec;
    826 	bool fullyused = false;
    827 	uint32_t pending;
    828 
    829 	KASSERTMSG(howmany(nbits, NBBY) <= len,
    830 	    "impossible entropy rate: %u bits in %zu-byte string", nbits, len);
    831 
    832 	/* If it's too early after boot, just use entropy_enter_early.  */
    833 	if (__predict_false(E->stage < ENTROPY_HOT)) {
    834 		entropy_enter_early(buf, len, nbits);
    835 		return true;
    836 	}
    837 
    838 	/*
    839 	 * Acquire the per-CPU state.  If someone is in the middle of
    840 	 * using it, drop the sample.  Otherwise, take the lock so that
    841 	 * higher-priority interrupts will drop their samples.
    842 	 */
    843 	ec = percpu_getref(entropy_percpu);
    844 	if (ec->ec_locked)
    845 		goto out0;
    846 	ec->ec_locked = true;
    847 	__insn_barrier();
    848 
    849 	/*
    850 	 * Enter as much as we can into the per-CPU pool.  If it was
    851 	 * truncated, schedule a softint to stir the pool and stop.
    852 	 */
    853 	if (!entpool_enter_nostir(ec->ec_pool, buf, len)) {
    854 		softint_schedule(entropy_sih);
    855 		goto out1;
    856 	}
    857 	fullyused = true;
    858 
    859 	/* Count up what we can contribute.  */
    860 	pending = ec->ec_pending;
    861 	pending += MIN(ENTROPY_CAPACITY*NBBY - pending, nbits);
    862 	atomic_store_relaxed(&ec->ec_pending, pending);
    863 
    864 	/* Schedule a softint if we added anything and it matters.  */
    865 	if (__predict_false((atomic_load_relaxed(&E->needed) != 0) ||
    866 		atomic_load_relaxed(&entropy_depletion)) &&
    867 	    nbits != 0)
    868 		softint_schedule(entropy_sih);
    869 
    870 out1:	/* Release the per-CPU state.  */
    871 	KASSERT(ec->ec_locked);
    872 	__insn_barrier();
    873 	ec->ec_locked = false;
    874 out0:	percpu_putref(entropy_percpu);
    875 
    876 	return fullyused;
    877 }
    878 
    879 /*
    880  * entropy_softintr(cookie)
    881  *
    882  *	Soft interrupt handler for entering entropy.  Takes care of
    883  *	stirring the local CPU's entropy pool if it filled up during
    884  *	hard interrupts, and promptly crediting entropy from the local
    885  *	CPU's entropy pool to the global entropy pool if needed.
    886  */
    887 static void
    888 entropy_softintr(void *cookie)
    889 {
    890 	struct entropy_cpu *ec;
    891 
    892 	/*
    893 	 * Acquire the per-CPU state.  Other users can lock this only
    894 	 * while soft interrupts are blocked.  Cause hard interrupts to
    895 	 * drop samples on the floor.
    896 	 */
    897 	ec = percpu_getref(entropy_percpu);
    898 	KASSERT(!ec->ec_locked);
    899 	ec->ec_locked = true;
    900 	__insn_barrier();
    901 
    902 	/* Count statistics.  */
    903 	ec->ec_softint_evcnt->ev_count++;
    904 
    905 	/* Stir the pool if necessary.  */
    906 	entpool_stir(ec->ec_pool);
    907 
    908 	/* Consolidate globally if appropriate based on what we added.  */
    909 	entropy_account_cpu(ec);
    910 
    911 	/* Release the per-CPU state.  */
    912 	KASSERT(ec->ec_locked);
    913 	__insn_barrier();
    914 	ec->ec_locked = false;
    915 	percpu_putref(entropy_percpu);
    916 }
    917 
    918 /*
    919  * entropy_thread(cookie)
    920  *
    921  *	Handle any asynchronous entropy housekeeping.
    922  */
    923 static void
    924 entropy_thread(void *cookie)
    925 {
    926 
    927 	for (;;) {
    928 		/*
    929 		 * Wait until someone wants to consolidate or there's
    930 		 * full entropy somewhere among the CPUs, as confirmed
    931 		 * at most once per minute.
    932 		 */
    933 		mutex_enter(&E->lock);
    934 		for (;;) {
    935 			if (E->consolidate ||
    936 			    entropy_pending() >= ENTROPY_CAPACITY*NBBY) {
    937 				E->consolidate = false;
    938 				break;
    939 			}
    940 			cv_timedwait(&E->cv, &E->lock, 60*hz);
    941 		}
    942 		mutex_exit(&E->lock);
    943 
    944 		/* Do it.  */
    945 		entropy_consolidate();
    946 
    947 		/* Mitigate abuse.  */
    948 		kpause("entropy", false, hz, NULL);
    949 	}
    950 }
    951 
    952 /*
    953  * entropy_pending()
    954  *
    955  *	Count up the amount of entropy pending on other CPUs.
    956  */
    957 static uint32_t
    958 entropy_pending(void)
    959 {
    960 	uint32_t pending = 0;
    961 
    962 	percpu_foreach(entropy_percpu, &entropy_pending_cpu, &pending);
    963 
    964 	return pending;
    965 }
    966 
    967 static void
    968 entropy_pending_cpu(void *ptr, void *cookie, struct cpu_info *ci)
    969 {
    970 	struct entropy_cpu *ec = ptr;
    971 	uint32_t *pendingp = cookie;
    972 	uint32_t cpu_pending;
    973 
    974 	cpu_pending = atomic_load_relaxed(&ec->ec_pending);
    975 	*pendingp += MIN(ENTROPY_CAPACITY*NBBY - *pendingp, cpu_pending);
    976 }
    977 
    978 /*
    979  * entropy_consolidate()
    980  *
    981  *	Issue a cross-call to gather entropy on all CPUs and advance
    982  *	the entropy epoch.
    983  */
    984 static void
    985 entropy_consolidate(void)
    986 {
    987 	static const struct timeval interval = {.tv_sec = 60, .tv_usec = 0};
    988 	static struct timeval lasttime; /* serialized by E->lock */
    989 	unsigned diff;
    990 	uint64_t ticket;
    991 
    992 	/* Gather entropy on all CPUs.  */
    993 	ticket = xc_broadcast(0, &entropy_gather_xc, NULL, NULL);
    994 	xc_wait(ticket);
    995 
    996 	/* Acquire the lock to notify waiters.  */
    997 	mutex_enter(&E->lock);
    998 
    999 	/* Count another consolidation.  */
   1000 	entropy_consolidate_evcnt.ev_count++;
   1001 
   1002 	/* Note when we last consolidated, i.e. now.  */
   1003 	E->timestamp = time_uptime;
   1004 
   1005 	/* Count the entropy that was gathered.  */
   1006 	diff = MIN(E->needed, E->pending);
   1007 	atomic_store_relaxed(&E->needed, E->needed - diff);
   1008 	E->pending -= diff;
   1009 	if (__predict_false(E->needed > 0)) {
   1010 		if (ratecheck(&lasttime, &interval))
   1011 			printf("entropy: WARNING:"
   1012 			    " consolidating less than full entropy\n");
   1013 	}
   1014 
   1015 	/* Advance the epoch and notify waiters.  */
   1016 	entropy_notify();
   1017 
   1018 	/* Release the lock.  */
   1019 	mutex_exit(&E->lock);
   1020 }
   1021 
   1022 /*
   1023  * entropy_gather_xc(arg1, arg2)
   1024  *
   1025  *	Extract output from the local CPU's input pool and enter it
   1026  *	into the global pool.
   1027  */
   1028 static void
   1029 entropy_gather_xc(void *arg1 __unused, void *arg2 __unused)
   1030 {
   1031 	struct entropy_cpu *ec;
   1032 	uint8_t buf[ENTPOOL_CAPACITY];
   1033 	uint32_t extra[7];
   1034 	unsigned i = 0;
   1035 	int s;
   1036 
   1037 	/* Grab CPU number and cycle counter to mix extra into the pool.  */
   1038 	extra[i++] = cpu_number();
   1039 	extra[i++] = entropy_timer();
   1040 
   1041 	/*
   1042 	 * Acquire the per-CPU state, blocking soft interrupts and
   1043 	 * discarding entropy in hard interrupts, so that we can
   1044 	 * extract from the per-CPU pool.
   1045 	 */
   1046 	ec = percpu_getref(entropy_percpu);
   1047 	s = splsoftserial();
   1048 	KASSERT(!ec->ec_locked);
   1049 	ec->ec_locked = true;
   1050 	__insn_barrier();
   1051 	extra[i++] = entropy_timer();
   1052 
   1053 	/* Extract the data.  */
   1054 	entpool_extract(ec->ec_pool, buf, sizeof buf);
   1055 	extra[i++] = entropy_timer();
   1056 
   1057 	/* Release the per-CPU state.  */
   1058 	KASSERT(ec->ec_locked);
   1059 	__insn_barrier();
   1060 	ec->ec_locked = false;
   1061 	splx(s);
   1062 	percpu_putref(entropy_percpu);
   1063 	extra[i++] = entropy_timer();
   1064 
   1065 	/*
   1066 	 * Copy over statistics, and enter the per-CPU extract and the
   1067 	 * extra timing into the global pool, under the global lock.
   1068 	 */
   1069 	mutex_enter(&E->lock);
   1070 	extra[i++] = entropy_timer();
   1071 	entpool_enter(&E->pool, buf, sizeof buf);
   1072 	explicit_memset(buf, 0, sizeof buf);
   1073 	extra[i++] = entropy_timer();
   1074 	KASSERT(i == __arraycount(extra));
   1075 	entpool_enter(&E->pool, extra, sizeof extra);
   1076 	explicit_memset(extra, 0, sizeof extra);
   1077 	mutex_exit(&E->lock);
   1078 }
   1079 
   1080 /*
   1081  * entropy_notify()
   1082  *
   1083  *	Caller just contributed entropy to the global pool.  Advance
   1084  *	the entropy epoch and notify waiters.
   1085  *
   1086  *	Caller must hold the global entropy lock.  Except for the
   1087  *	`sysctl -w kern.entropy.consolidate=1` trigger, the caller must
   1088  *	have just have transitioned from partial entropy to full
   1089  *	entropy -- E->needed should be zero now.
   1090  */
   1091 static void
   1092 entropy_notify(void)
   1093 {
   1094 	unsigned epoch;
   1095 
   1096 	KASSERT(E->stage == ENTROPY_COLD || mutex_owned(&E->lock));
   1097 
   1098 	/*
   1099 	 * If this is the first time, print a message to the console
   1100 	 * that we're ready so operators can compare it to the timing
   1101 	 * of other events.
   1102 	 */
   1103 	if (E->epoch == (unsigned)-1)
   1104 		printf("entropy: ready\n");
   1105 
   1106 	/* Set the epoch; roll over from UINTMAX-1 to 1.  */
   1107 	rnd_initial_entropy = 1; /* XXX legacy */
   1108 	epoch = E->epoch + 1;
   1109 	if (epoch == 0 || epoch == (unsigned)-1)
   1110 		epoch = 1;
   1111 	atomic_store_relaxed(&E->epoch, epoch);
   1112 
   1113 	/* Notify waiters.  */
   1114 	if (E->stage >= ENTROPY_WARM) {
   1115 		cv_broadcast(&E->cv);
   1116 		selnotify(&E->selq, POLLIN|POLLRDNORM, NOTE_SUBMIT);
   1117 	}
   1118 
   1119 	/* Count another notification.  */
   1120 	entropy_notify_evcnt.ev_count++;
   1121 }
   1122 
   1123 /*
   1124  * sysctl -w kern.entropy.consolidate=1
   1125  *
   1126  *	Trigger entropy consolidation and wait for it to complete.
   1127  *	Writable only by superuser.  This is the only way for the
   1128  *	system to consolidate entropy if the operator knows something
   1129  *	the kernel doesn't about how unpredictable the pending entropy
   1130  *	pools are.
   1131  */
   1132 static int
   1133 sysctl_entropy_consolidate(SYSCTLFN_ARGS)
   1134 {
   1135 	struct sysctlnode node = *rnode;
   1136 	uint64_t ticket;
   1137 	int arg;
   1138 	int error;
   1139 
   1140 	KASSERT(E->stage == ENTROPY_HOT);
   1141 
   1142 	node.sysctl_data = &arg;
   1143 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
   1144 	if (error || newp == NULL)
   1145 		return error;
   1146 	if (arg) {
   1147 		mutex_enter(&E->lock);
   1148 		ticket = entropy_consolidate_evcnt.ev_count;
   1149 		E->consolidate = true;
   1150 		cv_broadcast(&E->cv);
   1151 		while (ticket == entropy_consolidate_evcnt.ev_count) {
   1152 			error = cv_wait_sig(&E->cv, &E->lock);
   1153 			if (error)
   1154 				break;
   1155 		}
   1156 		mutex_exit(&E->lock);
   1157 	}
   1158 
   1159 	return error;
   1160 }
   1161 
   1162 /*
   1163  * entropy_extract(buf, len, flags)
   1164  *
   1165  *	Extract len bytes from the global entropy pool into buf.
   1166  *
   1167  *	Flags may have:
   1168  *
   1169  *		ENTROPY_WAIT	Wait for entropy if not available yet.
   1170  *		ENTROPY_SIG	Allow interruption by a signal during wait.
   1171  *
   1172  *	Return zero on success, or error on failure:
   1173  *
   1174  *		EWOULDBLOCK	No entropy and ENTROPY_WAIT not set.
   1175  *		EINTR/ERESTART	No entropy, ENTROPY_SIG set, and interrupted.
   1176  *
   1177  *	If ENTROPY_WAIT is set, allowed only in thread context.  If
   1178  *	ENTROPY_WAIT is not set, allowed up to IPL_VM.  (XXX That's
   1179  *	awfully high...  Do we really need it in hard interrupts?  This
   1180  *	arises from use of cprng_strong(9).)
   1181  */
   1182 int
   1183 entropy_extract(void *buf, size_t len, int flags)
   1184 {
   1185 	static const struct timeval interval = {.tv_sec = 60, .tv_usec = 0};
   1186 	static struct timeval lasttime; /* serialized by E->lock */
   1187 	int error;
   1188 
   1189 	if (ISSET(flags, ENTROPY_WAIT)) {
   1190 		ASSERT_SLEEPABLE();
   1191 		KASSERTMSG(E->stage >= ENTROPY_WARM,
   1192 		    "can't wait for entropy until warm");
   1193 	}
   1194 
   1195 	/* Acquire the global lock to get at the global pool.  */
   1196 	if (E->stage >= ENTROPY_WARM)
   1197 		mutex_enter(&E->lock);
   1198 
   1199 	/* Count up request for entropy in interrupt context.  */
   1200 	if (curcpu_available() && cpu_intr_p())
   1201 		entropy_extract_intr_evcnt.ev_count++;
   1202 
   1203 	/* Wait until there is enough entropy in the system.  */
   1204 	error = 0;
   1205 	while (E->needed) {
   1206 		/* Ask for more, synchronously if possible.  */
   1207 		entropy_request(len);
   1208 
   1209 		/* If we got enough, we're done.  */
   1210 		if (E->needed == 0) {
   1211 			KASSERT(error == 0);
   1212 			break;
   1213 		}
   1214 
   1215 		/* If not waiting, stop here.  */
   1216 		if (!ISSET(flags, ENTROPY_WAIT)) {
   1217 			error = EWOULDBLOCK;
   1218 			break;
   1219 		}
   1220 
   1221 		/* Wait for some entropy to come in and try again.  */
   1222 		KASSERT(E->stage >= ENTROPY_WARM);
   1223 		if (ISSET(flags, ENTROPY_SIG)) {
   1224 			error = cv_wait_sig(&E->cv, &E->lock);
   1225 			if (error)
   1226 				break;
   1227 		} else {
   1228 			cv_wait(&E->cv, &E->lock);
   1229 		}
   1230 	}
   1231 
   1232 	/* Count failure -- but fill the buffer nevertheless.  */
   1233 	if (error)
   1234 		entropy_extract_fail_evcnt.ev_count++;
   1235 
   1236 	/*
   1237 	 * Report a warning if we have never yet reached full entropy.
   1238 	 * This is the only case where we consider entropy to be
   1239 	 * `depleted' without kern.entropy.depletion enabled -- when we
   1240 	 * only have partial entropy, an adversary may be able to
   1241 	 * narrow the state of the pool down to a small number of
   1242 	 * possibilities; the output then enables them to confirm a
   1243 	 * guess, reducing its entropy from the adversary's perspective
   1244 	 * to zero.
   1245 	 */
   1246 	if (__predict_false(E->epoch == (unsigned)-1)) {
   1247 		if (ratecheck(&lasttime, &interval))
   1248 			printf("entropy: WARNING:"
   1249 			    " extracting entropy too early\n");
   1250 		atomic_store_relaxed(&E->needed, ENTROPY_CAPACITY*NBBY);
   1251 	}
   1252 
   1253 	/* Extract data from the pool, and `deplete' if we're doing that.  */
   1254 	entpool_extract(&E->pool, buf, len);
   1255 	if (__predict_false(atomic_load_relaxed(&entropy_depletion)) &&
   1256 	    error == 0) {
   1257 		unsigned cost = MIN(len, ENTROPY_CAPACITY)*NBBY;
   1258 
   1259 		atomic_store_relaxed(&E->needed,
   1260 		    E->needed + MIN(ENTROPY_CAPACITY*NBBY - E->needed, cost));
   1261 		entropy_deplete_evcnt.ev_count++;
   1262 	}
   1263 
   1264 	/* Release the global lock and return the error.  */
   1265 	if (E->stage >= ENTROPY_WARM)
   1266 		mutex_exit(&E->lock);
   1267 	return error;
   1268 }
   1269 
   1270 /*
   1271  * entropy_poll(events)
   1272  *
   1273  *	Return the subset of events ready, and if it is not all of
   1274  *	events, record curlwp as waiting for entropy.
   1275  */
   1276 int
   1277 entropy_poll(int events)
   1278 {
   1279 	int revents = 0;
   1280 
   1281 	KASSERT(E->stage >= ENTROPY_WARM);
   1282 
   1283 	/* Always ready for writing.  */
   1284 	revents |= events & (POLLOUT|POLLWRNORM);
   1285 
   1286 	/* Narrow it down to reads.  */
   1287 	events &= POLLIN|POLLRDNORM;
   1288 	if (events == 0)
   1289 		return revents;
   1290 
   1291 	/*
   1292 	 * If we have reached full entropy and we're not depleting
   1293 	 * entropy, we are forever ready.
   1294 	 */
   1295 	if (__predict_true(atomic_load_relaxed(&E->needed) == 0) &&
   1296 	    __predict_true(!atomic_load_relaxed(&entropy_depletion)))
   1297 		return revents | events;
   1298 
   1299 	/*
   1300 	 * Otherwise, check whether we need entropy under the lock.  If
   1301 	 * we don't, we're ready; if we do, add ourselves to the queue.
   1302 	 */
   1303 	mutex_enter(&E->lock);
   1304 	if (E->needed == 0)
   1305 		revents |= events;
   1306 	else
   1307 		selrecord(curlwp, &E->selq);
   1308 	mutex_exit(&E->lock);
   1309 
   1310 	return revents;
   1311 }
   1312 
   1313 /*
   1314  * filt_entropy_read_detach(kn)
   1315  *
   1316  *	struct filterops::f_detach callback for entropy read events:
   1317  *	remove kn from the list of waiters.
   1318  */
   1319 static void
   1320 filt_entropy_read_detach(struct knote *kn)
   1321 {
   1322 
   1323 	KASSERT(E->stage >= ENTROPY_WARM);
   1324 
   1325 	mutex_enter(&E->lock);
   1326 	SLIST_REMOVE(&E->selq.sel_klist, kn, knote, kn_selnext);
   1327 	mutex_exit(&E->lock);
   1328 }
   1329 
   1330 /*
   1331  * filt_entropy_read_event(kn, hint)
   1332  *
   1333  *	struct filterops::f_event callback for entropy read events:
   1334  *	poll for entropy.  Caller must hold the global entropy lock if
   1335  *	hint is NOTE_SUBMIT, and must not if hint is not NOTE_SUBMIT.
   1336  */
   1337 static int
   1338 filt_entropy_read_event(struct knote *kn, long hint)
   1339 {
   1340 	int ret;
   1341 
   1342 	KASSERT(E->stage >= ENTROPY_WARM);
   1343 
   1344 	/* Acquire the lock, if caller is outside entropy subsystem.  */
   1345 	if (hint == NOTE_SUBMIT)
   1346 		KASSERT(mutex_owned(&E->lock));
   1347 	else
   1348 		mutex_enter(&E->lock);
   1349 
   1350 	/*
   1351 	 * If we still need entropy, can't read anything; if not, can
   1352 	 * read arbitrarily much.
   1353 	 */
   1354 	if (E->needed != 0) {
   1355 		ret = 0;
   1356 	} else {
   1357 		if (atomic_load_relaxed(&entropy_depletion))
   1358 			kn->kn_data = ENTROPY_CAPACITY*NBBY;
   1359 		else
   1360 			kn->kn_data = MIN(INT64_MAX, SSIZE_MAX);
   1361 		ret = 1;
   1362 	}
   1363 
   1364 	/* Release the lock, if caller is outside entropy subsystem.  */
   1365 	if (hint == NOTE_SUBMIT)
   1366 		KASSERT(mutex_owned(&E->lock));
   1367 	else
   1368 		mutex_exit(&E->lock);
   1369 
   1370 	return ret;
   1371 }
   1372 
   1373 static const struct filterops entropy_read_filtops = {
   1374 	.f_isfd = 1,		/* XXX Makes sense only for /dev/u?random.  */
   1375 	.f_attach = NULL,
   1376 	.f_detach = filt_entropy_read_detach,
   1377 	.f_event = filt_entropy_read_event,
   1378 };
   1379 
   1380 /*
   1381  * entropy_kqfilter(kn)
   1382  *
   1383  *	Register kn to receive entropy event notifications.  May be
   1384  *	EVFILT_READ or EVFILT_WRITE; anything else yields EINVAL.
   1385  */
   1386 int
   1387 entropy_kqfilter(struct knote *kn)
   1388 {
   1389 
   1390 	KASSERT(E->stage >= ENTROPY_WARM);
   1391 
   1392 	switch (kn->kn_filter) {
   1393 	case EVFILT_READ:
   1394 		/* Enter into the global select queue.  */
   1395 		mutex_enter(&E->lock);
   1396 		kn->kn_fop = &entropy_read_filtops;
   1397 		SLIST_INSERT_HEAD(&E->selq.sel_klist, kn, kn_selnext);
   1398 		mutex_exit(&E->lock);
   1399 		return 0;
   1400 	case EVFILT_WRITE:
   1401 		/* Can always dump entropy into the system.  */
   1402 		kn->kn_fop = &seltrue_filtops;
   1403 		return 0;
   1404 	default:
   1405 		return EINVAL;
   1406 	}
   1407 }
   1408 
   1409 /*
   1410  * rndsource_setcb(rs, get, getarg)
   1411  *
   1412  *	Set the request callback for the entropy source rs, if it can
   1413  *	provide entropy on demand.  Must precede rnd_attach_source.
   1414  */
   1415 void
   1416 rndsource_setcb(struct krndsource *rs, void (*get)(size_t, void *),
   1417     void *getarg)
   1418 {
   1419 
   1420 	rs->get = get;
   1421 	rs->getarg = getarg;
   1422 }
   1423 
   1424 /*
   1425  * rnd_attach_source(rs, name, type, flags)
   1426  *
   1427  *	Attach the entropy source rs.  Must be done after
   1428  *	rndsource_setcb, if any, and before any calls to rnd_add_data.
   1429  */
   1430 void
   1431 rnd_attach_source(struct krndsource *rs, const char *name, uint32_t type,
   1432     uint32_t flags)
   1433 {
   1434 	uint32_t extra[4];
   1435 	unsigned i = 0;
   1436 
   1437 	/* Grab cycle counter to mix extra into the pool.  */
   1438 	extra[i++] = entropy_timer();
   1439 
   1440 	/*
   1441 	 * Apply some standard flags:
   1442 	 *
   1443 	 * - We do not bother with network devices by default, for
   1444 	 *   hysterical raisins (perhaps: because it is often the case
   1445 	 *   that an adversary can influence network packet timings).
   1446 	 */
   1447 	switch (type) {
   1448 	case RND_TYPE_NET:
   1449 		flags |= RND_FLAG_NO_COLLECT;
   1450 		break;
   1451 	}
   1452 
   1453 	/* Sanity-check the callback if RND_FLAG_HASCB is set.  */
   1454 	KASSERT(!ISSET(flags, RND_FLAG_HASCB) || rs->get != NULL);
   1455 
   1456 	/* Initialize the random source.  */
   1457 	memset(rs->name, 0, sizeof(rs->name)); /* paranoia */
   1458 	strlcpy(rs->name, name, sizeof(rs->name));
   1459 	rs->type = type;
   1460 	rs->flags = flags;
   1461 	if (E->stage >= ENTROPY_WARM)
   1462 		rs->state = percpu_alloc(sizeof(struct rndsource_cpu));
   1463 	extra[i++] = entropy_timer();
   1464 
   1465 	/* Wire it into the global list of random sources.  */
   1466 	if (E->stage >= ENTROPY_WARM)
   1467 		mutex_enter(&E->lock);
   1468 	LIST_INSERT_HEAD(&E->sources, rs, list);
   1469 	if (E->stage >= ENTROPY_WARM)
   1470 		mutex_exit(&E->lock);
   1471 	extra[i++] = entropy_timer();
   1472 
   1473 	/* Request that it provide entropy ASAP, if we can.  */
   1474 	if (ISSET(flags, RND_FLAG_HASCB))
   1475 		(*rs->get)(ENTROPY_CAPACITY, rs->getarg);
   1476 	extra[i++] = entropy_timer();
   1477 
   1478 	/* Mix the extra into the pool.  */
   1479 	KASSERT(i == __arraycount(extra));
   1480 	entropy_enter(extra, sizeof extra, 0);
   1481 	explicit_memset(extra, 0, sizeof extra);
   1482 }
   1483 
   1484 /*
   1485  * rnd_detach_source(rs)
   1486  *
   1487  *	Detach the entropy source rs.  May sleep waiting for users to
   1488  *	drain.  Further use is not allowed.
   1489  */
   1490 void
   1491 rnd_detach_source(struct krndsource *rs)
   1492 {
   1493 
   1494 	/*
   1495 	 * If we're cold (shouldn't happen, but hey), just remove it
   1496 	 * from the list -- there's nothing allocated.
   1497 	 */
   1498 	if (E->stage == ENTROPY_COLD) {
   1499 		LIST_REMOVE(rs, list);
   1500 		return;
   1501 	}
   1502 
   1503 	/* We may have to wait for entropy_request.  */
   1504 	ASSERT_SLEEPABLE();
   1505 
   1506 	/* Remove it from the list and wait for entropy_request.  */
   1507 	mutex_enter(&E->lock);
   1508 	LIST_REMOVE(rs, list);
   1509 	while (E->requesting)
   1510 		cv_wait(&E->cv, &E->lock);
   1511 	mutex_exit(&E->lock);
   1512 
   1513 	/* Free the per-CPU data.  */
   1514 	percpu_free(rs->state, sizeof(struct rndsource_cpu));
   1515 }
   1516 
   1517 /*
   1518  * entropy_request(nbytes)
   1519  *
   1520  *	Request nbytes bytes of entropy from all sources in the system.
   1521  *	OK if we overdo it.  Caller must hold the global entropy lock;
   1522  *	will release and re-acquire it.
   1523  */
   1524 static void
   1525 entropy_request(size_t nbytes)
   1526 {
   1527 	struct krndsource *rs, *next;
   1528 
   1529 	KASSERT(E->stage == ENTROPY_COLD || mutex_owned(&E->lock));
   1530 
   1531 	/*
   1532 	 * If there is a request in progress, let it proceed.
   1533 	 * Otherwise, note that a request is in progress to avoid
   1534 	 * reentry and to block rnd_detach_source until we're done.
   1535 	 */
   1536 	if (E->requesting)
   1537 		return;
   1538 	E->requesting = true;
   1539 	entropy_request_evcnt.ev_count++;
   1540 
   1541 	/* Clamp to the maximum reasonable request.  */
   1542 	nbytes = MIN(nbytes, ENTROPY_CAPACITY);
   1543 
   1544 	/* Walk the list of sources.  */
   1545 	LIST_FOREACH_SAFE(rs, &E->sources, list, next) {
   1546 		/* Skip sources without callbacks.  */
   1547 		if (!ISSET(rs->flags, RND_FLAG_HASCB))
   1548 			continue;
   1549 
   1550 		/* Drop the lock while we call the callback.  */
   1551 		if (E->stage >= ENTROPY_WARM)
   1552 			mutex_exit(&E->lock);
   1553 		(*rs->get)(nbytes, rs->getarg);
   1554 		if (E->stage >= ENTROPY_WARM)
   1555 			mutex_enter(&E->lock);
   1556 	}
   1557 
   1558 	/* Notify rnd_detach_source that the request is done.  */
   1559 	E->requesting = false;
   1560 	if (E->stage >= ENTROPY_WARM)
   1561 		cv_broadcast(&E->cv);
   1562 }
   1563 
   1564 /*
   1565  * rnd_add_uint32(rs, value)
   1566  *
   1567  *	Enter 32 bits of data from an entropy source into the pool.
   1568  *
   1569  *	If rs is NULL, may not be called from interrupt context.
   1570  *
   1571  *	If rs is non-NULL, may be called from any context.  May drop
   1572  *	data if called from interrupt context.
   1573  */
   1574 void
   1575 rnd_add_uint32(struct krndsource *rs, uint32_t value)
   1576 {
   1577 
   1578 	rnd_add_data(rs, &value, sizeof value, 0);
   1579 }
   1580 
   1581 void
   1582 _rnd_add_uint32(struct krndsource *rs, uint32_t value)
   1583 {
   1584 
   1585 	rnd_add_data(rs, &value, sizeof value, 0);
   1586 }
   1587 
   1588 void
   1589 _rnd_add_uint64(struct krndsource *rs, uint64_t value)
   1590 {
   1591 
   1592 	rnd_add_data(rs, &value, sizeof value, 0);
   1593 }
   1594 
   1595 /*
   1596  * rnd_add_data(rs, buf, len, entropybits)
   1597  *
   1598  *	Enter data from an entropy source into the pool, with a
   1599  *	driver's estimate of how much entropy the physical source of
   1600  *	the data has.  If RND_FLAG_NO_ESTIMATE, we ignore the driver's
   1601  *	estimate and treat it as zero.
   1602  *
   1603  *	If rs is NULL, may not be called from interrupt context.
   1604  *
   1605  *	If rs is non-NULL, may be called from any context.  May drop
   1606  *	data if called from interrupt context.
   1607  */
   1608 void
   1609 rnd_add_data(struct krndsource *rs, const void *buf, uint32_t len,
   1610     uint32_t entropybits)
   1611 {
   1612 	uint32_t extra;
   1613 	uint32_t flags;
   1614 
   1615 	KASSERTMSG(howmany(entropybits, NBBY) <= len,
   1616 	    "%s: impossible entropy rate:"
   1617 	    " %"PRIu32" bits in %"PRIu32"-byte string",
   1618 	    rs ? rs->name : "(anonymous)", entropybits, len);
   1619 
   1620 	/* If there's no rndsource, just enter the data and time now.  */
   1621 	if (rs == NULL) {
   1622 		entropy_enter(buf, len, entropybits);
   1623 		extra = entropy_timer();
   1624 		entropy_enter(&extra, sizeof extra, 0);
   1625 		explicit_memset(&extra, 0, sizeof extra);
   1626 		return;
   1627 	}
   1628 
   1629 	/* Load a snapshot of the flags.  Ioctl may change them under us.  */
   1630 	flags = atomic_load_relaxed(&rs->flags);
   1631 
   1632 	/*
   1633 	 * Skip if:
   1634 	 * - we're not collecting entropy, or
   1635 	 * - the operator doesn't want to collect entropy from this, or
   1636 	 * - neither data nor timings are being collected from this.
   1637 	 */
   1638 	if (!atomic_load_relaxed(&entropy_collection) ||
   1639 	    ISSET(flags, RND_FLAG_NO_COLLECT) ||
   1640 	    !ISSET(flags, RND_FLAG_COLLECT_VALUE|RND_FLAG_COLLECT_TIME))
   1641 		return;
   1642 
   1643 	/* If asked, ignore the estimate.  */
   1644 	if (ISSET(flags, RND_FLAG_NO_ESTIMATE))
   1645 		entropybits = 0;
   1646 
   1647 	/* If we are collecting data, enter them.  */
   1648 	if (ISSET(flags, RND_FLAG_COLLECT_VALUE))
   1649 		rnd_add_data_1(rs, buf, len, entropybits);
   1650 
   1651 	/* If we are collecting timings, enter one.  */
   1652 	if (ISSET(flags, RND_FLAG_COLLECT_TIME)) {
   1653 		extra = entropy_timer();
   1654 		rnd_add_data_1(rs, &extra, sizeof extra, 0);
   1655 	}
   1656 }
   1657 
   1658 /*
   1659  * rnd_add_data_1(rs, buf, len, entropybits)
   1660  *
   1661  *	Internal subroutine to call either entropy_enter_intr, if we're
   1662  *	in interrupt context, or entropy_enter if not, and to count the
   1663  *	entropy in an rndsource.
   1664  */
   1665 static void
   1666 rnd_add_data_1(struct krndsource *rs, const void *buf, uint32_t len,
   1667     uint32_t entropybits)
   1668 {
   1669 	bool fullyused;
   1670 
   1671 	/*
   1672 	 * If we're in interrupt context, use entropy_enter_intr and
   1673 	 * take note of whether it consumed the full sample; if not,
   1674 	 * use entropy_enter, which always consumes the full sample.
   1675 	 */
   1676 	if (curcpu_available() && cpu_intr_p()) {
   1677 		fullyused = entropy_enter_intr(buf, len, entropybits);
   1678 	} else {
   1679 		entropy_enter(buf, len, entropybits);
   1680 		fullyused = true;
   1681 	}
   1682 
   1683 	/*
   1684 	 * If we used the full sample, note how many bits were
   1685 	 * contributed from this source.
   1686 	 */
   1687 	if (fullyused) {
   1688 		if (E->stage < ENTROPY_HOT) {
   1689 			if (E->stage >= ENTROPY_WARM)
   1690 				mutex_enter(&E->lock);
   1691 			rs->total += MIN(UINT_MAX - rs->total, entropybits);
   1692 			if (E->stage >= ENTROPY_WARM)
   1693 				mutex_exit(&E->lock);
   1694 		} else {
   1695 			struct rndsource_cpu *rc = percpu_getref(rs->state);
   1696 			unsigned nbits = rc->rc_nbits;
   1697 
   1698 			nbits += MIN(UINT_MAX - nbits, entropybits);
   1699 			atomic_store_relaxed(&rc->rc_nbits, nbits);
   1700 			percpu_putref(rs->state);
   1701 		}
   1702 	}
   1703 }
   1704 
   1705 /*
   1706  * rnd_add_data_sync(rs, buf, len, entropybits)
   1707  *
   1708  *	Same as rnd_add_data.  Originally used in rndsource callbacks,
   1709  *	to break an unnecessary cycle; no longer really needed.
   1710  */
   1711 void
   1712 rnd_add_data_sync(struct krndsource *rs, const void *buf, uint32_t len,
   1713     uint32_t entropybits)
   1714 {
   1715 
   1716 	rnd_add_data(rs, buf, len, entropybits);
   1717 }
   1718 
   1719 /*
   1720  * rndsource_entropybits(rs)
   1721  *
   1722  *	Return approximately the number of bits of entropy that have
   1723  *	been contributed via rs so far.  Approximate if other CPUs may
   1724  *	be calling rnd_add_data concurrently.
   1725  */
   1726 static unsigned
   1727 rndsource_entropybits(struct krndsource *rs)
   1728 {
   1729 	unsigned nbits = rs->total;
   1730 
   1731 	KASSERT(E->stage >= ENTROPY_WARM);
   1732 	KASSERT(mutex_owned(&E->lock));
   1733 	percpu_foreach(rs->state, rndsource_entropybits_cpu, &nbits);
   1734 	return nbits;
   1735 }
   1736 
   1737 static void
   1738 rndsource_entropybits_cpu(void *ptr, void *cookie, struct cpu_info *ci)
   1739 {
   1740 	struct rndsource_cpu *rc = ptr;
   1741 	unsigned *nbitsp = cookie;
   1742 	unsigned cpu_nbits;
   1743 
   1744 	cpu_nbits = atomic_load_relaxed(&rc->rc_nbits);
   1745 	*nbitsp += MIN(UINT_MAX - *nbitsp, cpu_nbits);
   1746 }
   1747 
   1748 /*
   1749  * rndsource_to_user(rs, urs)
   1750  *
   1751  *	Copy a description of rs out to urs for userland.
   1752  */
   1753 static void
   1754 rndsource_to_user(struct krndsource *rs, rndsource_t *urs)
   1755 {
   1756 
   1757 	KASSERT(E->stage >= ENTROPY_WARM);
   1758 	KASSERT(mutex_owned(&E->lock));
   1759 
   1760 	/* Avoid kernel memory disclosure.  */
   1761 	memset(urs, 0, sizeof(*urs));
   1762 
   1763 	CTASSERT(sizeof(urs->name) == sizeof(rs->name));
   1764 	strlcpy(urs->name, rs->name, sizeof(urs->name));
   1765 	urs->total = rndsource_entropybits(rs);
   1766 	urs->type = rs->type;
   1767 	urs->flags = atomic_load_relaxed(&rs->flags);
   1768 }
   1769 
   1770 /*
   1771  * rndsource_to_user_est(rs, urse)
   1772  *
   1773  *	Copy a description of rs and estimation statistics out to urse
   1774  *	for userland.
   1775  */
   1776 static void
   1777 rndsource_to_user_est(struct krndsource *rs, rndsource_est_t *urse)
   1778 {
   1779 
   1780 	KASSERT(E->stage >= ENTROPY_WARM);
   1781 	KASSERT(mutex_owned(&E->lock));
   1782 
   1783 	/* Avoid kernel memory disclosure.  */
   1784 	memset(urse, 0, sizeof(*urse));
   1785 
   1786 	/* Copy out the rndsource description.  */
   1787 	rndsource_to_user(rs, &urse->rt);
   1788 
   1789 	/* Zero out the statistics because we don't do estimation.  */
   1790 	urse->dt_samples = 0;
   1791 	urse->dt_total = 0;
   1792 	urse->dv_samples = 0;
   1793 	urse->dv_total = 0;
   1794 }
   1795 
   1796 /*
   1797  * entropy_ioctl(cmd, data)
   1798  *
   1799  *	Handle various /dev/random ioctl queries.
   1800  */
   1801 int
   1802 entropy_ioctl(unsigned long cmd, void *data)
   1803 {
   1804 	struct krndsource *rs;
   1805 	bool privileged;
   1806 	int error;
   1807 
   1808 	KASSERT(E->stage >= ENTROPY_WARM);
   1809 
   1810 	/* Verify user's authorization to perform the ioctl.  */
   1811 	switch (cmd) {
   1812 	case RNDGETENTCNT:
   1813 	case RNDGETPOOLSTAT:
   1814 	case RNDGETSRCNUM:
   1815 	case RNDGETSRCNAME:
   1816 	case RNDGETESTNUM:
   1817 	case RNDGETESTNAME:
   1818 		error = kauth_authorize_device(curlwp->l_cred,
   1819 		    KAUTH_DEVICE_RND_GETPRIV, NULL, NULL, NULL, NULL);
   1820 		break;
   1821 	case RNDCTL:
   1822 		error = kauth_authorize_device(curlwp->l_cred,
   1823 		    KAUTH_DEVICE_RND_SETPRIV, NULL, NULL, NULL, NULL);
   1824 		break;
   1825 	case RNDADDDATA:
   1826 		error = kauth_authorize_device(curlwp->l_cred,
   1827 		    KAUTH_DEVICE_RND_ADDDATA, NULL, NULL, NULL, NULL);
   1828 		/* Ascertain whether the user's inputs should be counted.  */
   1829 		if (kauth_authorize_device(curlwp->l_cred,
   1830 			KAUTH_DEVICE_RND_ADDDATA_ESTIMATE,
   1831 			NULL, NULL, NULL, NULL) == 0)
   1832 			privileged = true;
   1833 		break;
   1834 	default: {
   1835 		/*
   1836 		 * XXX Hack to avoid changing module ABI so this can be
   1837 		 * pulled up.  Later, we can just remove the argument.
   1838 		 */
   1839 		static const struct fileops fops = {
   1840 			.fo_ioctl = rnd_system_ioctl,
   1841 		};
   1842 		struct file f = {
   1843 			.f_ops = &fops,
   1844 		};
   1845 		MODULE_HOOK_CALL(rnd_ioctl_50_hook, (&f, cmd, data),
   1846 		    enosys(), error);
   1847 #if defined(_LP64)
   1848 		if (error == ENOSYS)
   1849 			MODULE_HOOK_CALL(rnd_ioctl32_50_hook, (&f, cmd, data),
   1850 			    enosys(), error);
   1851 #endif
   1852 		if (error == ENOSYS)
   1853 			error = ENOTTY;
   1854 		break;
   1855 	}
   1856 	}
   1857 
   1858 	/* If anything went wrong with authorization, stop here.  */
   1859 	if (error)
   1860 		return error;
   1861 
   1862 	/* Dispatch on the command.  */
   1863 	switch (cmd) {
   1864 	case RNDGETENTCNT: {	/* Get current entropy count in bits.  */
   1865 		uint32_t *countp = data;
   1866 
   1867 		mutex_enter(&E->lock);
   1868 		*countp = ENTROPY_CAPACITY*NBBY - E->needed;
   1869 		mutex_exit(&E->lock);
   1870 
   1871 		break;
   1872 	}
   1873 	case RNDGETPOOLSTAT: {	/* Get entropy pool statistics.  */
   1874 		rndpoolstat_t *pstat = data;
   1875 
   1876 		mutex_enter(&E->lock);
   1877 
   1878 		/* parameters */
   1879 		pstat->poolsize = ENTPOOL_SIZE/sizeof(uint32_t); /* words */
   1880 		pstat->threshold = ENTROPY_CAPACITY*1; /* bytes */
   1881 		pstat->maxentropy = ENTROPY_CAPACITY*NBBY; /* bits */
   1882 
   1883 		/* state */
   1884 		pstat->added = 0; /* XXX total entropy_enter count */
   1885 		pstat->curentropy = ENTROPY_CAPACITY*NBBY - E->needed;
   1886 		pstat->removed = 0; /* XXX total entropy_extract count */
   1887 		pstat->discarded = 0; /* XXX bits of entropy beyond capacity */
   1888 		pstat->generated = 0; /* XXX bits of data...fabricated? */
   1889 
   1890 		mutex_exit(&E->lock);
   1891 		break;
   1892 	}
   1893 	case RNDGETSRCNUM: {	/* Get entropy sources by number.  */
   1894 		rndstat_t *stat = data;
   1895 		uint32_t start = 0, i = 0;
   1896 
   1897 		/* Skip if none requested; fail if too many requested.  */
   1898 		if (stat->count == 0)
   1899 			break;
   1900 		if (stat->count > RND_MAXSTATCOUNT)
   1901 			return EINVAL;
   1902 
   1903 		/*
   1904 		 * Under the lock, find the first one, copy out as many
   1905 		 * as requested, and report how many we copied out.
   1906 		 */
   1907 		mutex_enter(&E->lock);
   1908 		LIST_FOREACH(rs, &E->sources, list) {
   1909 			if (start++ == stat->start)
   1910 				break;
   1911 		}
   1912 		while (i < stat->count && rs != NULL) {
   1913 			rndsource_to_user(rs, &stat->source[i++]);
   1914 			rs = LIST_NEXT(rs, list);
   1915 		}
   1916 		KASSERT(i <= stat->count);
   1917 		stat->count = i;
   1918 		mutex_exit(&E->lock);
   1919 		break;
   1920 	}
   1921 	case RNDGETESTNUM: {	/* Get sources and estimates by number.  */
   1922 		rndstat_est_t *estat = data;
   1923 		uint32_t start = 0, i = 0;
   1924 
   1925 		/* Skip if none requested; fail if too many requested.  */
   1926 		if (estat->count == 0)
   1927 			break;
   1928 		if (estat->count > RND_MAXSTATCOUNT)
   1929 			return EINVAL;
   1930 
   1931 		/*
   1932 		 * Under the lock, find the first one, copy out as many
   1933 		 * as requested, and report how many we copied out.
   1934 		 */
   1935 		mutex_enter(&E->lock);
   1936 		LIST_FOREACH(rs, &E->sources, list) {
   1937 			if (start++ == estat->start)
   1938 				break;
   1939 		}
   1940 		while (i < estat->count && rs != NULL) {
   1941 			rndsource_to_user_est(rs, &estat->source[i++]);
   1942 			rs = LIST_NEXT(rs, list);
   1943 		}
   1944 		KASSERT(i <= estat->count);
   1945 		estat->count = i;
   1946 		mutex_exit(&E->lock);
   1947 		break;
   1948 	}
   1949 	case RNDGETSRCNAME: {	/* Get entropy sources by name.  */
   1950 		rndstat_name_t *nstat = data;
   1951 		const size_t n = sizeof(rs->name);
   1952 
   1953 		CTASSERT(sizeof(rs->name) == sizeof(nstat->name));
   1954 
   1955 		/*
   1956 		 * Under the lock, search by name.  If found, copy it
   1957 		 * out; if not found, fail with ENOENT.
   1958 		 */
   1959 		mutex_enter(&E->lock);
   1960 		LIST_FOREACH(rs, &E->sources, list) {
   1961 			if (strncmp(rs->name, nstat->name, n) == 0)
   1962 				break;
   1963 		}
   1964 		if (rs != NULL)
   1965 			rndsource_to_user(rs, &nstat->source);
   1966 		else
   1967 			error = ENOENT;
   1968 		mutex_exit(&E->lock);
   1969 		break;
   1970 	}
   1971 	case RNDGETESTNAME: {	/* Get sources and estimates by name.  */
   1972 		rndstat_est_name_t *enstat = data;
   1973 		const size_t n = sizeof(rs->name);
   1974 
   1975 		CTASSERT(sizeof(rs->name) == sizeof(enstat->name));
   1976 
   1977 		/*
   1978 		 * Under the lock, search by name.  If found, copy it
   1979 		 * out; if not found, fail with ENOENT.
   1980 		 */
   1981 		mutex_enter(&E->lock);
   1982 		LIST_FOREACH(rs, &E->sources, list) {
   1983 			if (strncmp(rs->name, enstat->name, n) == 0)
   1984 				break;
   1985 		}
   1986 		if (rs != NULL)
   1987 			rndsource_to_user_est(rs, &enstat->source);
   1988 		else
   1989 			error = ENOENT;
   1990 		mutex_exit(&E->lock);
   1991 		break;
   1992 	}
   1993 	case RNDCTL: {		/* Modify entropy source flags.  */
   1994 		rndctl_t *rndctl = data;
   1995 		const size_t n = sizeof(rs->name);
   1996 		uint32_t flags;
   1997 
   1998 		CTASSERT(sizeof(rs->name) == sizeof(rndctl->name));
   1999 
   2000 		/* Whitelist the flags that user can change.  */
   2001 		rndctl->mask &= RND_FLAG_NO_ESTIMATE|RND_FLAG_NO_COLLECT;
   2002 
   2003 		/*
   2004 		 * For each matching rndsource, either by type if
   2005 		 * specified or by name if not, set the masked flags.
   2006 		 */
   2007 		mutex_enter(&E->lock);
   2008 		LIST_FOREACH(rs, &E->sources, list) {
   2009 			if (rndctl->type != 0xff) {
   2010 				if (rs->type != rndctl->type)
   2011 					continue;
   2012 			} else {
   2013 				if (strncmp(rs->name, rndctl->name, n) != 0)
   2014 					continue;
   2015 			}
   2016 			flags = rs->flags & ~rndctl->mask;
   2017 			flags |= rndctl->flags & rndctl->mask;
   2018 			atomic_store_relaxed(&rs->flags, flags);
   2019 		}
   2020 		mutex_exit(&E->lock);
   2021 		break;
   2022 	}
   2023 	case RNDADDDATA: {	/* Enter seed into entropy pool.  */
   2024 		rnddata_t *rdata = data;
   2025 		unsigned entropybits = 0;
   2026 
   2027 		if (!atomic_load_relaxed(&entropy_collection))
   2028 			break;	/* thanks but no thanks */
   2029 		if (rdata->len > MIN(sizeof(rdata->data), UINT32_MAX/NBBY))
   2030 			return EINVAL;
   2031 
   2032 		/*
   2033 		 * This ioctl serves as the userland alternative a
   2034 		 * bootloader-provided seed -- typically furnished by
   2035 		 * /etc/rc.d/random_seed.  We accept the user's entropy
   2036 		 * claim only if
   2037 		 *
   2038 		 * (a) the user is privileged, and
   2039 		 * (b) we have not entered a bootloader seed.
   2040 		 *
   2041 		 * under the assumption that the user may use this to
   2042 		 * load a seed from disk that we have already loaded
   2043 		 * from the bootloader, so we don't double-count it.
   2044 		 */
   2045 		if (privileged) {
   2046 			mutex_enter(&E->lock);
   2047 			if (!E->seeded) {
   2048 				entropybits = MIN(rdata->entropy,
   2049 				    MIN(rdata->len, ENTROPY_CAPACITY)*NBBY);
   2050 				E->seeded = true;
   2051 			}
   2052 			mutex_exit(&E->lock);
   2053 		}
   2054 
   2055 		/* Enter the data.  */
   2056 		rnd_add_data(&seed_rndsource, rdata->data, rdata->len,
   2057 		    entropybits);
   2058 		break;
   2059 	}
   2060 	default:
   2061 		error = ENOTTY;
   2062 	}
   2063 
   2064 	/* Return any error that may have come up.  */
   2065 	return error;
   2066 }
   2067 
   2068 /* Legacy entry points */
   2069 
   2070 void
   2071 rnd_seed(void *seed, size_t len)
   2072 {
   2073 
   2074 	if (len != sizeof(rndsave_t)) {
   2075 		printf("entropy: invalid seed length: %zu,"
   2076 		    " expected sizeof(rndsave_t) = %zu\n",
   2077 		    len, sizeof(rndsave_t));
   2078 		return;
   2079 	}
   2080 	entropy_seed(seed);
   2081 }
   2082 
   2083 void
   2084 rnd_init(void)
   2085 {
   2086 
   2087 	entropy_init();
   2088 }
   2089 
   2090 void
   2091 rnd_init_softint(void)
   2092 {
   2093 
   2094 	entropy_init_late();
   2095 }
   2096 
   2097 int
   2098 rnd_system_ioctl(struct file *fp, unsigned long cmd, void *data)
   2099 {
   2100 
   2101 	return entropy_ioctl(cmd, data);
   2102 }
   2103