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