1 /*
   2  * CDDL HEADER START
   3  *
   4  * The contents of this file are subject to the terms of the
   5  * Common Development and Distribution License (the "License").
   6  * You may not use this file except in compliance with the License.
   7  *
   8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
   9  * or http://www.opensolaris.org/os/licensing.
  10  * See the License for the specific language governing permissions
  11  * and limitations under the License.
  12  *
  13  * When distributing Covered Code, include this CDDL HEADER in each
  14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
  15  * If applicable, add the following below this CDDL HEADER, with the
  16  * fields enclosed by brackets "[]" replaced with your own identifying
  17  * information: Portions Copyright [yyyy] [name of copyright owner]
  18  *
  19  * CDDL HEADER END
  20  */
  21 /*
  22  * Copyright 2010 Sun Microsystems, Inc.  All rights reserved.
  23  * Use is subject to license terms.
  24  */
  25 
  26 /*
  27  * Software based random number provider for the Kernel Cryptographic
  28  * Framework (KCF). This provider periodically collects unpredictable input
  29  * from external sources and processes it into a pool of entropy (randomness)
  30  * in order to satisfy requests for random bits from kCF. It implements
  31  * software-based mixing, extraction, and generation algorithms.
  32  *
  33  * A history note: The software-based algorithms in this file used to be
  34  * part of the /dev/random driver.
  35  */
  36 
  37 #include <sys/types.h>
  38 #include <sys/errno.h>
  39 #include <sys/debug.h>
  40 #include <vm/seg_kmem.h>
  41 #include <vm/hat.h>
  42 #include <sys/systm.h>
  43 #include <sys/memlist.h>
  44 #include <sys/cmn_err.h>
  45 #include <sys/ksynch.h>
  46 #include <sys/random.h>
  47 #include <sys/ddi.h>
  48 #include <sys/mman.h>
  49 #include <sys/sysmacros.h>
  50 #include <sys/mem_config.h>
  51 #include <sys/time.h>
  52 #include <sys/crypto/spi.h>
  53 #include <sys/sha1.h>
  54 #include <sys/sunddi.h>
  55 #include <sys/modctl.h>
  56 #include <sys/hold_page.h>
  57 #include <rng/fips_random.h>
  58 
  59 #define RNDPOOLSIZE             1024    /* Pool size in bytes */
  60 #define HASHBUFSIZE             64      /* Buffer size used for pool mixing */
  61 #define MAXMEMBLOCKS            16384   /* Number of memory blocks to scan */
  62 #define MEMBLOCKSIZE            4096    /* Size of memory block to read */
  63 #define MINEXTRACTBITS          160     /* Min entropy level for extraction */
  64 #define TIMEOUT_INTERVAL        5       /* Periodic mixing interval in secs */
  65 
  66 /* Hash-algo generic definitions. For now, they are SHA1's. */
  67 #define HASHSIZE                20
  68 #define HASH_CTX                SHA1_CTX
  69 #define HashInit(ctx)           SHA1Init((ctx))
  70 #define HashUpdate(ctx, p, s)   SHA1Update((ctx), (p), (s))
  71 #define HashFinal(d, ctx)       SHA1Final((d), (ctx))
  72 
  73 /* Physical memory entropy source */
  74 typedef struct physmem_entsrc_s {
  75         uint8_t *parity;                /* parity bit vector */
  76         caddr_t pmbuf;                  /* buffer for memory block */
  77         uint32_t nblocks;               /* number of  memory blocks */
  78         int entperblock;                /* entropy bits per block read */
  79         hrtime_t last_diff;             /* previous time to process a block */
  80         hrtime_t last_delta;            /* previous time delta */
  81         hrtime_t last_delta2;           /* previous 2nd order time delta */
  82 } physmem_entsrc_t;
  83 
  84 static uint32_t srndpool[RNDPOOLSIZE/4];        /* Pool of random bits */
  85 static uint32_t buffer[RNDPOOLSIZE/4];  /* entropy mixed in later */
  86 static int buffer_bytes;                /* bytes written to buffer */
  87 static uint32_t entropy_bits;           /* pool's current amount of entropy */
  88 static kmutex_t srndpool_lock;          /* protects r/w accesses to the pool, */
  89                                         /* and the global variables */
  90 static kmutex_t buffer_lock;            /* protects r/w accesses to buffer */
  91 static kcondvar_t srndpool_read_cv;     /* serializes poll/read syscalls */
  92 static int pindex;                      /* Global index for adding/extracting */
  93                                         /* from the pool */
  94 static int bstart, bindex;              /* Global vars for adding/extracting */
  95                                         /* from the buffer */
  96 static uint8_t leftover[HASHSIZE];      /* leftover output */
  97 static uint32_t swrand_XKEY[6];         /* one extra word for getentropy */
  98 static int leftover_bytes;              /* leftover length */
  99 static uint32_t previous_bytes[HASHSIZE/BYTES_IN_WORD]; /* prev random bytes */
 100 
 101 static physmem_entsrc_t entsrc;         /* Physical mem as an entropy source */
 102 static timeout_id_t rnd_timeout_id;
 103 static int snum_waiters;
 104 static crypto_kcf_provider_handle_t swrand_prov_handle = NULL;
 105 swrand_stats_t swrand_stats;
 106 
 107 static int physmem_ent_init(physmem_entsrc_t *);
 108 static void physmem_ent_fini(physmem_entsrc_t *);
 109 static void physmem_ent_gen(physmem_entsrc_t *);
 110 static int physmem_parity_update(uint8_t *, uint32_t, int);
 111 static void physmem_count_blocks();
 112 static void rnd_dr_callback_post_add(void *, pgcnt_t);
 113 static int rnd_dr_callback_pre_del(void *, pgcnt_t);
 114 static void rnd_dr_callback_post_del(void *, pgcnt_t, int);
 115 static void rnd_handler(void *arg);
 116 static void swrand_init();
 117 static void swrand_schedule_timeout(void);
 118 static int swrand_get_entropy(uint8_t *ptr, size_t len, boolean_t);
 119 static void swrand_add_entropy(uint8_t *ptr, size_t len, uint16_t entropy_est);
 120 static void swrand_add_entropy_later(uint8_t *ptr, size_t len);
 121 
 122 /* Dynamic Reconfiguration related declarations */
 123 kphysm_setup_vector_t rnd_dr_callback_vec = {
 124         KPHYSM_SETUP_VECTOR_VERSION,
 125         rnd_dr_callback_post_add,
 126         rnd_dr_callback_pre_del,
 127         rnd_dr_callback_post_del
 128 };
 129 
 130 extern struct mod_ops mod_cryptoops;
 131 
 132 /*
 133  * Module linkage information for the kernel.
 134  */
 135 static struct modlcrypto modlcrypto = {
 136         &mod_cryptoops,
 137         "Kernel Random number Provider"
 138 };
 139 
 140 static struct modlinkage modlinkage = {
 141         MODREV_1,
 142         {   (void *)&modlcrypto,
 143             NULL }
 144 };
 145 
 146 /*
 147  * CSPI information (entry points, provider info, etc.)
 148  */
 149 static void swrand_provider_status(crypto_provider_handle_t, uint_t *);
 150 
 151 static crypto_control_ops_t swrand_control_ops = {
 152         swrand_provider_status
 153 };
 154 
 155 static int swrand_seed_random(crypto_provider_handle_t, crypto_session_id_t,
 156     uchar_t *, size_t, uint_t, uint32_t, crypto_req_handle_t);
 157 static int swrand_generate_random(crypto_provider_handle_t,
 158     crypto_session_id_t, uchar_t *, size_t, crypto_req_handle_t);
 159 
 160 static crypto_random_number_ops_t swrand_random_number_ops = {
 161         swrand_seed_random,
 162         swrand_generate_random
 163 };
 164 
 165 static crypto_ops_t swrand_crypto_ops = {
 166         .co_control_ops = &swrand_control_ops,
 167         .co_random_ops = &swrand_random_number_ops
 168 };
 169 
 170 static crypto_provider_info_t swrand_prov_info = {{{{
 171         CRYPTO_SPI_VERSION_4,
 172         "Kernel Random Number Provider",
 173         CRYPTO_SW_PROVIDER,
 174         {&modlinkage},
 175         NULL,
 176         &swrand_crypto_ops,
 177         0,
 178         NULL
 179 }}}};
 180 
 181 int
 182 _init(void)
 183 {
 184         int ret;
 185         hrtime_t ts;
 186         time_t now;
 187 
 188         mutex_init(&srndpool_lock, NULL, MUTEX_DEFAULT, NULL);
 189         mutex_init(&buffer_lock, NULL, MUTEX_DEFAULT, NULL);
 190         cv_init(&srndpool_read_cv, NULL, CV_DEFAULT, NULL);
 191         entropy_bits = 0;
 192         pindex = 0;
 193         bindex = 0;
 194         bstart = 0;
 195         snum_waiters = 0;
 196         leftover_bytes = 0;
 197         buffer_bytes = 0;
 198 
 199         /*
 200          * Initialize the pool using
 201          * . 2 unpredictable times: high resolution time since the boot-time,
 202          *   and the current time-of-the day.
 203          * . The initial physical memory state.
 204          */
 205         ts = gethrtime();
 206         swrand_add_entropy((uint8_t *)&ts, sizeof (ts), 0);
 207 
 208         (void) drv_getparm(TIME, &now);
 209         swrand_add_entropy((uint8_t *)&now, sizeof (now), 0);
 210 
 211         ret = kphysm_setup_func_register(&rnd_dr_callback_vec, NULL);
 212         ASSERT(ret == 0);
 213 
 214         if (physmem_ent_init(&entsrc) != 0) {
 215                 ret = ENOMEM;
 216                 goto exit1;
 217         }
 218 
 219         if ((ret = mod_install(&modlinkage)) != 0)
 220                 goto exit2;
 221 
 222         /* Schedule periodic mixing of the pool. */
 223         mutex_enter(&srndpool_lock);
 224         swrand_schedule_timeout();
 225         mutex_exit(&srndpool_lock);
 226         (void) swrand_get_entropy((uint8_t *)swrand_XKEY, HASHSIZE, B_TRUE);
 227         bcopy(swrand_XKEY, previous_bytes, HASHSIZE);
 228 
 229         /* Register with KCF. If the registration fails, return error. */
 230         if (crypto_register_provider(&swrand_prov_info, &swrand_prov_handle)) {
 231                 (void) mod_remove(&modlinkage);
 232                 ret = EACCES;
 233                 goto exit2;
 234         }
 235 
 236         return (0);
 237 
 238 exit2:
 239         physmem_ent_fini(&entsrc);
 240 exit1:
 241         mutex_destroy(&srndpool_lock);
 242         mutex_destroy(&buffer_lock);
 243         cv_destroy(&srndpool_read_cv);
 244         return (ret);
 245 }
 246 
 247 int
 248 _info(struct modinfo *modinfop)
 249 {
 250         return (mod_info(&modlinkage, modinfop));
 251 }
 252 
 253 /*
 254  * Control entry points.
 255  */
 256 /* ARGSUSED */
 257 static void
 258 swrand_provider_status(crypto_provider_handle_t provider, uint_t *status)
 259 {
 260         *status = CRYPTO_PROVIDER_READY;
 261 }
 262 
 263 /*
 264  * Random number entry points.
 265  */
 266 /* ARGSUSED */
 267 static int
 268 swrand_seed_random(crypto_provider_handle_t provider, crypto_session_id_t sid,
 269     uchar_t *buf, size_t len, uint_t entropy_est, uint32_t flags,
 270     crypto_req_handle_t req)
 271 {
 272         /* The entropy estimate is always 0 in this path */
 273         if (flags & CRYPTO_SEED_NOW)
 274                 swrand_add_entropy(buf, len, 0);
 275         else
 276                 swrand_add_entropy_later(buf, len);
 277         return (CRYPTO_SUCCESS);
 278 }
 279 
 280 /* ARGSUSED */
 281 static int
 282 swrand_generate_random(crypto_provider_handle_t provider,
 283     crypto_session_id_t sid, uchar_t *buf, size_t len, crypto_req_handle_t req)
 284 {
 285         if (crypto_kmflag(req) == KM_NOSLEEP)
 286                 (void) swrand_get_entropy(buf, len, B_TRUE);
 287         else
 288                 (void) swrand_get_entropy(buf, len, B_FALSE);
 289 
 290         return (CRYPTO_SUCCESS);
 291 }
 292 
 293 /*
 294  * Extraction of entropy from the pool.
 295  *
 296  * Returns "len" random bytes in *ptr.
 297  * Try to gather some more entropy by calling physmem_ent_gen() when less than
 298  * MINEXTRACTBITS are present in the pool.
 299  * Will block if not enough entropy was available and the call is blocking.
 300  */
 301 static int
 302 swrand_get_entropy(uint8_t *ptr, size_t len, boolean_t nonblock)
 303 {
 304         int i, bytes;
 305         HASH_CTX hashctx;
 306         uint8_t digest[HASHSIZE], *pool;
 307         uint32_t tempout[HASHSIZE/BYTES_IN_WORD];
 308         int size;
 309 
 310         mutex_enter(&srndpool_lock);
 311         if (leftover_bytes > 0) {
 312                 bytes = min(len, leftover_bytes);
 313                 bcopy(leftover, ptr, bytes);
 314                 len -= bytes;
 315                 ptr += bytes;
 316                 leftover_bytes -= bytes;
 317                 if (leftover_bytes > 0)
 318                         ovbcopy(leftover+bytes, leftover, leftover_bytes);
 319         }
 320 
 321         while (len > 0) {
 322                 /* Check if there is enough entropy */
 323                 while (entropy_bits < MINEXTRACTBITS) {
 324 
 325                         physmem_ent_gen(&entsrc);
 326 
 327                         if (entropy_bits < MINEXTRACTBITS &&
 328                             nonblock == B_TRUE) {
 329                                 mutex_exit(&srndpool_lock);
 330                                 return (EAGAIN);
 331                         }
 332 
 333                         if (entropy_bits < MINEXTRACTBITS) {
 334                                 ASSERT(nonblock == B_FALSE);
 335                                 snum_waiters++;
 336                                 if (cv_wait_sig(&srndpool_read_cv,
 337                                     &srndpool_lock) == 0) {
 338                                         snum_waiters--;
 339                                         mutex_exit(&srndpool_lock);
 340                                         return (EINTR);
 341                                 }
 342                                 snum_waiters--;
 343                         }
 344                 }
 345 
 346                 /* Figure out how many bytes to extract */
 347                 bytes = min(HASHSIZE, len);
 348                 bytes = min(bytes, CRYPTO_BITS2BYTES(entropy_bits));
 349                 entropy_bits -= CRYPTO_BYTES2BITS(bytes);
 350                 BUMP_SWRAND_STATS(ss_entOut, CRYPTO_BYTES2BITS(bytes));
 351                 swrand_stats.ss_entEst = entropy_bits;
 352 
 353                 /* Extract entropy by hashing pool content */
 354                 HashInit(&hashctx);
 355                 HashUpdate(&hashctx, (uint8_t *)srndpool, RNDPOOLSIZE);
 356                 HashFinal(digest, &hashctx);
 357 
 358                 /*
 359                  * Feed the digest back into the pool so next
 360                  * extraction produces different result
 361                  */
 362                 pool = (uint8_t *)srndpool;
 363                 for (i = 0; i < HASHSIZE; i++) {
 364                         pool[pindex++] ^= digest[i];
 365                         /* pindex modulo RNDPOOLSIZE */
 366                         pindex &= (RNDPOOLSIZE - 1);
 367                 }
 368 
 369                 /* LINTED E_BAD_PTR_CAST_ALIGN */
 370                 fips_random_inner(swrand_XKEY, tempout, (uint32_t *)digest);
 371 
 372                 if (len >= HASHSIZE) {
 373                         size = HASHSIZE;
 374                 } else {
 375                         size = min(bytes, HASHSIZE);
 376                 }
 377 
 378                 /*
 379                  * FIPS 140-2: Continuous RNG test - each generation
 380                  * of an n-bit block shall be compared with the previously
 381                  * generated block. Test shall fail if any two compared
 382                  * n-bit blocks are equal.
 383                  */
 384                 for (i = 0; i < HASHSIZE/BYTES_IN_WORD; i++) {
 385                         if (tempout[i] != previous_bytes[i])
 386                                 break;
 387                 }
 388 
 389                 if (i == HASHSIZE/BYTES_IN_WORD) {
 390                         cmn_err(CE_WARN, "swrand: The value of 160-bit block "
 391                             "random bytes are same as the previous one.\n");
 392                         /* discard random bytes and return error */
 393                         return (EIO);
 394                 }
 395 
 396                 bcopy(tempout, previous_bytes, HASHSIZE);
 397 
 398                 bcopy(tempout, ptr, size);
 399                 if (len < HASHSIZE) {
 400                         leftover_bytes = HASHSIZE - bytes;
 401                         bcopy((uint8_t *)tempout + bytes, leftover,
 402                             leftover_bytes);
 403                 }
 404 
 405                 ptr += size;
 406                 len -= size;
 407                 BUMP_SWRAND_STATS(ss_bytesOut, size);
 408         }
 409 
 410         /* Zero out sensitive information */
 411         bzero(digest, HASHSIZE);
 412         bzero(tempout, HASHSIZE);
 413         mutex_exit(&srndpool_lock);
 414         return (0);
 415 }
 416 
 417 #define SWRAND_ADD_BYTES(ptr, len, i, pool)             \
 418         ASSERT((ptr) != NULL && (len) > 0);          \
 419         BUMP_SWRAND_STATS(ss_bytesIn, (len));           \
 420         while ((len)--) {                               \
 421                 (pool)[(i)++] ^= *(ptr);                \
 422                 (ptr)++;                                \
 423                 (i) &= (RNDPOOLSIZE - 1);           \
 424         }
 425 
 426 /* Write some more user-provided entropy to the pool */
 427 static void
 428 swrand_add_bytes(uint8_t *ptr, size_t len)
 429 {
 430         uint8_t *pool = (uint8_t *)srndpool;
 431 
 432         ASSERT(MUTEX_HELD(&srndpool_lock));
 433         SWRAND_ADD_BYTES(ptr, len, pindex, pool);
 434 }
 435 
 436 /*
 437  * Add bytes to buffer. Adding the buffer to the random pool
 438  * is deferred until the random pool is mixed.
 439  */
 440 static void
 441 swrand_add_bytes_later(uint8_t *ptr, size_t len)
 442 {
 443         uint8_t *pool = (uint8_t *)buffer;
 444 
 445         ASSERT(MUTEX_HELD(&buffer_lock));
 446         SWRAND_ADD_BYTES(ptr, len, bindex, pool);
 447         buffer_bytes += len;
 448 }
 449 
 450 #undef SWRAND_ADD_BYTES
 451 
 452 /* Mix the pool */
 453 static void
 454 swrand_mix_pool(uint16_t entropy_est)
 455 {
 456         int i, j, k, start;
 457         HASH_CTX hashctx;
 458         uint8_t digest[HASHSIZE];
 459         uint8_t *pool = (uint8_t *)srndpool;
 460         uint8_t *bp = (uint8_t *)buffer;
 461 
 462         ASSERT(MUTEX_HELD(&srndpool_lock));
 463 
 464         /* add deferred bytes */
 465         mutex_enter(&buffer_lock);
 466         if (buffer_bytes > 0) {
 467                 if (buffer_bytes >= RNDPOOLSIZE) {
 468                         for (i = 0; i < RNDPOOLSIZE/4; i++) {
 469                                 srndpool[i] ^= buffer[i];
 470                                 buffer[i] = 0;
 471                         }
 472                         bstart = bindex = 0;
 473                 } else {
 474                         for (i = 0; i < buffer_bytes; i++) {
 475                                 pool[pindex++] ^= bp[bstart];
 476                                 bp[bstart++] = 0;
 477                                 pindex &= (RNDPOOLSIZE - 1);
 478                                 bstart &= (RNDPOOLSIZE - 1);
 479                         }
 480                         ASSERT(bstart == bindex);
 481                 }
 482                 buffer_bytes = 0;
 483         }
 484         mutex_exit(&buffer_lock);
 485 
 486         start = 0;
 487         for (i = 0; i < RNDPOOLSIZE/HASHSIZE + 1; i++) {
 488                 HashInit(&hashctx);
 489 
 490                 /* Hash a buffer centered on a block in the pool */
 491                 if (start + HASHBUFSIZE <= RNDPOOLSIZE)
 492                         HashUpdate(&hashctx, &pool[start], HASHBUFSIZE);
 493                 else {
 494                         HashUpdate(&hashctx, &pool[start],
 495                             RNDPOOLSIZE - start);
 496                         HashUpdate(&hashctx, pool,
 497                             HASHBUFSIZE - RNDPOOLSIZE + start);
 498                 }
 499                 HashFinal(digest, &hashctx);
 500 
 501                 /* XOR the hash result back into the block */
 502                 k = (start + HASHSIZE) & (RNDPOOLSIZE - 1);
 503                 for (j = 0; j < HASHSIZE; j++) {
 504                         pool[k++] ^= digest[j];
 505                         k &= (RNDPOOLSIZE - 1);
 506                 }
 507 
 508                 /* Slide the hash buffer and repeat with next block */
 509                 start = (start + HASHSIZE) & (RNDPOOLSIZE - 1);
 510         }
 511 
 512         entropy_bits += entropy_est;
 513         if (entropy_bits > CRYPTO_BYTES2BITS(RNDPOOLSIZE))
 514                 entropy_bits = CRYPTO_BYTES2BITS(RNDPOOLSIZE);
 515 
 516         swrand_stats.ss_entEst = entropy_bits;
 517         BUMP_SWRAND_STATS(ss_entIn, entropy_est);
 518 }
 519 
 520 static void
 521 swrand_add_entropy_later(uint8_t *ptr, size_t len)
 522 {
 523         mutex_enter(&buffer_lock);
 524         swrand_add_bytes_later(ptr, len);
 525         mutex_exit(&buffer_lock);
 526 }
 527 
 528 static void
 529 swrand_add_entropy(uint8_t *ptr, size_t len, uint16_t entropy_est)
 530 {
 531         mutex_enter(&srndpool_lock);
 532         swrand_add_bytes(ptr, len);
 533         swrand_mix_pool(entropy_est);
 534         mutex_exit(&srndpool_lock);
 535 }
 536 
 537 /*
 538  * The physmem_* routines below generate entropy by reading blocks of
 539  * physical memory.  Entropy is gathered in a couple of ways:
 540  *
 541  *  - By reading blocks of physical memory and detecting if changes
 542  *    occurred in the blocks read.
 543  *
 544  *  - By measuring the time it takes to load and hash a block of memory
 545  *    and computing the differences in the measured time.
 546  *
 547  * The first method was used in the CryptoRand implementation.  Physical
 548  * memory is divided into blocks of fixed size.  A block of memory is
 549  * chosen from the possible blocks and hashed to produce a digest.  This
 550  * digest is then mixed into the pool.  A single bit from the digest is
 551  * used as a parity bit or "checksum" and compared against the previous
 552  * "checksum" computed for the block.  If the single-bit checksum has not
 553  * changed, no entropy is credited to the pool.  If there is a change,
 554  * then the assumption is that at least one bit in the block has changed.
 555  * The possible locations within the memory block of where the bit change
 556  * occurred is used as a measure of entropy.  For example, if a block
 557  * size of 4096 bytes is used, about log_2(4096*8)=15 bits worth of
 558  * entropy is available.  Because the single-bit checksum will miss half
 559  * of the changes, the amount of entropy credited to the pool is doubled
 560  * when a change is detected.  With a 4096 byte block size, a block
 561  * change will add a total of 30 bits of entropy to the pool.
 562  *
 563  * The second method measures the amount of time it takes to read and
 564  * hash a physical memory block (as described above).  The time measured
 565  * can vary depending on system load, scheduling and other factors.
 566  * Differences between consecutive measurements are computed to come up
 567  * with an entropy estimate.  The first, second, and third order delta is
 568  * calculated to determine the minimum delta value.  The number of bits
 569  * present in this minimum delta value is the entropy estimate.  This
 570  * entropy estimation technique using time deltas is similar to that used
 571  * in /dev/random implementations from Linux/BSD.
 572  */
 573 
 574 static int
 575 physmem_ent_init(physmem_entsrc_t *entsrc)
 576 {
 577         uint8_t *ptr;
 578         int i;
 579 
 580         bzero(entsrc, sizeof (*entsrc));
 581 
 582         /*
 583          * The maximum entropy amount in bits per block of memory read is
 584          * log_2(MEMBLOCKSIZE * 8);
 585          */
 586         i = CRYPTO_BYTES2BITS(MEMBLOCKSIZE);
 587         while (i >>= 1)
 588                 entsrc->entperblock++;
 589 
 590         /* Initialize entsrc->nblocks */
 591         physmem_count_blocks();
 592 
 593         if (entsrc->nblocks == 0) {
 594                 cmn_err(CE_WARN, "no memory blocks to scan!");
 595                 return (-1);
 596         }
 597 
 598         /* Allocate space for the parity vector and memory page */
 599         entsrc->parity = kmem_alloc(howmany(entsrc->nblocks, 8),
 600             KM_SLEEP);
 601         entsrc->pmbuf = vmem_alloc(heap_arena, PAGESIZE, VM_SLEEP);
 602 
 603 
 604         /* Initialize parity vector with bits from the pool */
 605         i = howmany(entsrc->nblocks, 8);
 606         ptr = entsrc->parity;
 607         while (i > 0) {
 608                 if (i > RNDPOOLSIZE) {
 609                         bcopy(srndpool, ptr, RNDPOOLSIZE);
 610                         mutex_enter(&srndpool_lock);
 611                         swrand_mix_pool(0);
 612                         mutex_exit(&srndpool_lock);
 613                         ptr += RNDPOOLSIZE;
 614                         i -= RNDPOOLSIZE;
 615                 } else {
 616                         bcopy(srndpool, ptr, i);
 617                         break;
 618                 }
 619         }
 620 
 621         /* Generate some entropy to further initialize the pool */
 622         mutex_enter(&srndpool_lock);
 623         physmem_ent_gen(entsrc);
 624         entropy_bits = 0;
 625         mutex_exit(&srndpool_lock);
 626 
 627         return (0);
 628 }
 629 
 630 static void
 631 physmem_ent_fini(physmem_entsrc_t *entsrc)
 632 {
 633         if (entsrc->pmbuf != NULL)
 634                 vmem_free(heap_arena, entsrc->pmbuf, PAGESIZE);
 635         if (entsrc->parity != NULL)
 636                 kmem_free(entsrc->parity, howmany(entsrc->nblocks, 8));
 637         bzero(entsrc, sizeof (*entsrc));
 638 }
 639 
 640 static void
 641 physmem_ent_gen(physmem_entsrc_t *entsrc)
 642 {
 643         struct memlist *pmem;
 644         offset_t offset, poffset;
 645         pfn_t pfn;
 646         int i, nbytes, len, ent = 0;
 647         uint32_t block, oblock;
 648         hrtime_t ts1, ts2, diff, delta, delta2, delta3;
 649         uint8_t digest[HASHSIZE];
 650         HASH_CTX ctx;
 651         page_t *pp;
 652 
 653         /*
 654          * Use each 32-bit quantity in the pool to pick a memory
 655          * block to read.
 656          */
 657         for (i = 0; i < RNDPOOLSIZE/4; i++) {
 658 
 659                 /* If the pool is "full", stop after one block */
 660                 if (entropy_bits + ent >= CRYPTO_BYTES2BITS(RNDPOOLSIZE)) {
 661                         if (i > 0)
 662                                 break;
 663                 }
 664 
 665                 /*
 666                  * This lock protects reading of phys_install.
 667                  * Any changes to this list, by DR, are done while
 668                  * holding this lock. So, holding this lock is sufficient
 669                  * to handle DR also.
 670                  */
 671                 memlist_read_lock();
 672 
 673                 /* We're left with less than 4K of memory after DR */
 674                 ASSERT(entsrc->nblocks > 0);
 675 
 676                 /* Pick a memory block to read */
 677                 block = oblock = srndpool[i] % entsrc->nblocks;
 678 
 679                 for (pmem = phys_install; pmem != NULL; pmem = pmem->ml_next) {
 680                         if (block < pmem->ml_size / MEMBLOCKSIZE)
 681                                 break;
 682                         block -= pmem->ml_size / MEMBLOCKSIZE;
 683                 }
 684 
 685                 ASSERT(pmem != NULL);
 686 
 687                 offset = pmem->ml_address + block * MEMBLOCKSIZE;
 688 
 689                 if (!address_in_memlist(phys_install, offset, MEMBLOCKSIZE)) {
 690                         memlist_read_unlock();
 691                         continue;
 692                 }
 693 
 694                 /*
 695                  * Do an initial check to see if the address is safe
 696                  */
 697                 if (plat_hold_page(offset >> PAGESHIFT, PLAT_HOLD_NO_LOCK, NULL)
 698                     == PLAT_HOLD_FAIL) {
 699                         memlist_read_unlock();
 700                         continue;
 701                 }
 702 
 703                 /*
 704                  * Figure out which page to load to read the
 705                  * memory block.  Load the page and compute the
 706                  * hash of the memory block.
 707                  */
 708                 len = MEMBLOCKSIZE;
 709                 ts1 = gethrtime();
 710                 HashInit(&ctx);
 711                 while (len) {
 712                         pfn = offset >> PAGESHIFT;
 713                         poffset = offset & PAGEOFFSET;
 714                         nbytes = PAGESIZE - poffset < len ?
 715                             PAGESIZE - poffset : len;
 716 
 717                         /*
 718                          * Re-check the offset, and lock the frame.  If the
 719                          * page was given away after the above check, we'll
 720                          * just bail out.
 721                          */
 722                         if (plat_hold_page(pfn, PLAT_HOLD_LOCK, &pp) ==
 723                             PLAT_HOLD_FAIL)
 724                                 break;
 725 
 726                         hat_devload(kas.a_hat, entsrc->pmbuf,
 727                             PAGESIZE, pfn, PROT_READ,
 728                             HAT_LOAD_NOCONSIST | HAT_LOAD_LOCK);
 729 
 730                         HashUpdate(&ctx, (uint8_t *)entsrc->pmbuf + poffset,
 731                             nbytes);
 732 
 733                         hat_unload(kas.a_hat, entsrc->pmbuf, PAGESIZE,
 734                             HAT_UNLOAD_UNLOCK);
 735 
 736                         plat_release_page(pp);
 737 
 738                         len -= nbytes;
 739                         offset += nbytes;
 740                 }
 741                 /* We got our pages. Let the DR roll */
 742                 memlist_read_unlock();
 743 
 744                 /* See if we had to bail out due to a page being given away */
 745                 if (len)
 746                         continue;
 747 
 748                 HashFinal(digest, &ctx);
 749                 ts2 = gethrtime();
 750 
 751                 /*
 752                  * Compute the time it took to load and hash the
 753                  * block and compare it against the previous
 754                  * measurement. The delta of the time values
 755                  * provides a small amount of entropy.  The
 756                  * minimum of the first, second, and third order
 757                  * delta is used to estimate how much entropy
 758                  * is present.
 759                  */
 760                 diff = ts2 - ts1;
 761                 delta = diff - entsrc->last_diff;
 762                 if (delta < 0)
 763                         delta = -delta;
 764                 delta2 = delta - entsrc->last_delta;
 765                 if (delta2 < 0)
 766                         delta2 = -delta2;
 767                 delta3 = delta2 - entsrc->last_delta2;
 768                 if (delta3 < 0)
 769                         delta3 = -delta3;
 770                 entsrc->last_diff = diff;
 771                 entsrc->last_delta = delta;
 772                 entsrc->last_delta2 = delta2;
 773 
 774                 if (delta > delta2)
 775                         delta = delta2;
 776                 if (delta > delta3)
 777                         delta = delta3;
 778                 delta2 = 0;
 779                 while (delta >>= 1)
 780                         delta2++;
 781                 ent += delta2;
 782 
 783                 /*
 784                  * If the memory block has changed, credit the pool with
 785                  * the entropy estimate.  The entropy estimate is doubled
 786                  * because the single-bit checksum misses half the change
 787                  * on average.
 788                  */
 789                 if (physmem_parity_update(entsrc->parity, oblock,
 790                     digest[0] & 1))
 791                         ent += 2 * entsrc->entperblock;
 792 
 793                 /* Add the entropy bytes to the pool */
 794                 swrand_add_bytes(digest, HASHSIZE);
 795                 swrand_add_bytes((uint8_t *)&ts1, sizeof (ts1));
 796                 swrand_add_bytes((uint8_t *)&ts2, sizeof (ts2));
 797         }
 798 
 799         swrand_mix_pool(ent);
 800 }
 801 
 802 static int
 803 physmem_parity_update(uint8_t *parity_vec, uint32_t block, int parity)
 804 {
 805         /* Test and set the parity bit, return 1 if changed */
 806         if (parity == ((parity_vec[block >> 3] >> (block & 7)) & 1))
 807                 return (0);
 808         parity_vec[block >> 3] ^= 1 << (block & 7);
 809         return (1);
 810 }
 811 
 812 /* Compute number of memory blocks available to scan */
 813 static void
 814 physmem_count_blocks()
 815 {
 816         struct memlist *pmem;
 817 
 818         memlist_read_lock();
 819         entsrc.nblocks = 0;
 820         for (pmem = phys_install; pmem != NULL; pmem = pmem->ml_next) {
 821                 entsrc.nblocks += pmem->ml_size / MEMBLOCKSIZE;
 822                 if (entsrc.nblocks > MAXMEMBLOCKS) {
 823                         entsrc.nblocks = MAXMEMBLOCKS;
 824                         break;
 825                 }
 826         }
 827         memlist_read_unlock();
 828 }
 829 
 830 /*
 831  * Dynamic Reconfiguration call-back functions
 832  */
 833 
 834 /* ARGSUSED */
 835 static void
 836 rnd_dr_callback_post_add(void *arg, pgcnt_t delta)
 837 {
 838         /* More memory is available now, so update entsrc->nblocks. */
 839         physmem_count_blocks();
 840 }
 841 
 842 /* Call-back routine invoked before the DR starts a memory removal. */
 843 /* ARGSUSED */
 844 static int
 845 rnd_dr_callback_pre_del(void *arg, pgcnt_t delta)
 846 {
 847         return (0);
 848 }
 849 
 850 /* Call-back routine invoked after the DR starts a memory removal. */
 851 /* ARGSUSED */
 852 static void
 853 rnd_dr_callback_post_del(void *arg, pgcnt_t delta, int cancelled)
 854 {
 855         /* Memory has shrunk, so update entsrc->nblocks. */
 856         physmem_count_blocks();
 857 }
 858 
 859 /* Timeout handling to gather entropy from physmem events */
 860 static void
 861 swrand_schedule_timeout(void)
 862 {
 863         clock_t ut;     /* time in microseconds */
 864 
 865         ASSERT(MUTEX_HELD(&srndpool_lock));
 866         /*
 867          * The new timeout value is taken from the pool of random bits.
 868          * We're merely reading the first 32 bits from the pool here, not
 869          * consuming any entropy.
 870          * This routine is usually called right after stirring the pool, so
 871          * srndpool[0] will have a *fresh* random value each time.
 872          * The timeout multiplier value is a random value between 0.7 sec and
 873          * 1.748575 sec (0.7 sec + 0xFFFFF microseconds).
 874          * The new timeout is TIMEOUT_INTERVAL times that multiplier.
 875          */
 876         ut = 700000 + (clock_t)(srndpool[0] & 0xFFFFF);
 877         rnd_timeout_id = timeout(rnd_handler, NULL,
 878             TIMEOUT_INTERVAL * drv_usectohz(ut));
 879 }
 880 
 881 /*ARGSUSED*/
 882 static void
 883 rnd_handler(void *arg)
 884 {
 885         mutex_enter(&srndpool_lock);
 886 
 887         physmem_ent_gen(&entsrc);
 888         if (snum_waiters > 0)
 889                 cv_broadcast(&srndpool_read_cv);
 890         swrand_schedule_timeout();
 891 
 892         mutex_exit(&srndpool_lock);
 893 }