source: src/linux/universal/linux-4.9/drivers/char/random.c @ 31859

Last change on this file since 31859 was 31859, checked in by brainslayer, 2 months ago

kernel update

File size: 63.0 KB
Line 
1/*
2 * random.c -- A strong random number generator
3 *
4 * Copyright Matt Mackall <mpm@selenic.com>, 2003, 2004, 2005
5 *
6 * Copyright Theodore Ts'o, 1994, 1995, 1996, 1997, 1998, 1999.  All
7 * rights reserved.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 *    notice, and the entire permission notice in its entirety,
14 *    including the disclaimer of warranties.
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 * 3. The name of the author may not be used to endorse or promote
19 *    products derived from this software without specific prior
20 *    written permission.
21 *
22 * ALTERNATIVELY, this product may be distributed under the terms of
23 * the GNU General Public License, in which case the provisions of the GPL are
24 * required INSTEAD OF the above restrictions.  (This clause is
25 * necessary due to a potential bad interaction between the GPL and
26 * the restrictions contained in a BSD-style copyright.)
27 *
28 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
29 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
30 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF
31 * WHICH ARE HEREBY DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE
32 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
33 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
34 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
35 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
36 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
38 * USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH
39 * DAMAGE.
40 */
41
42/*
43 * (now, with legal B.S. out of the way.....)
44 *
45 * This routine gathers environmental noise from device drivers, etc.,
46 * and returns good random numbers, suitable for cryptographic use.
47 * Besides the obvious cryptographic uses, these numbers are also good
48 * for seeding TCP sequence numbers, and other places where it is
49 * desirable to have numbers which are not only random, but hard to
50 * predict by an attacker.
51 *
52 * Theory of operation
53 * ===================
54 *
55 * Computers are very predictable devices.  Hence it is extremely hard
56 * to produce truly random numbers on a computer --- as opposed to
57 * pseudo-random numbers, which can easily generated by using a
58 * algorithm.  Unfortunately, it is very easy for attackers to guess
59 * the sequence of pseudo-random number generators, and for some
60 * applications this is not acceptable.  So instead, we must try to
61 * gather "environmental noise" from the computer's environment, which
62 * must be hard for outside attackers to observe, and use that to
63 * generate random numbers.  In a Unix environment, this is best done
64 * from inside the kernel.
65 *
66 * Sources of randomness from the environment include inter-keyboard
67 * timings, inter-interrupt timings from some interrupts, and other
68 * events which are both (a) non-deterministic and (b) hard for an
69 * outside observer to measure.  Randomness from these sources are
70 * added to an "entropy pool", which is mixed using a CRC-like function.
71 * This is not cryptographically strong, but it is adequate assuming
72 * the randomness is not chosen maliciously, and it is fast enough that
73 * the overhead of doing it on every interrupt is very reasonable.
74 * As random bytes are mixed into the entropy pool, the routines keep
75 * an *estimate* of how many bits of randomness have been stored into
76 * the random number generator's internal state.
77 *
78 * When random bytes are desired, they are obtained by taking the SHA
79 * hash of the contents of the "entropy pool".  The SHA hash avoids
80 * exposing the internal state of the entropy pool.  It is believed to
81 * be computationally infeasible to derive any useful information
82 * about the input of SHA from its output.  Even if it is possible to
83 * analyze SHA in some clever way, as long as the amount of data
84 * returned from the generator is less than the inherent entropy in
85 * the pool, the output data is totally unpredictable.  For this
86 * reason, the routine decreases its internal estimate of how many
87 * bits of "true randomness" are contained in the entropy pool as it
88 * outputs random numbers.
89 *
90 * If this estimate goes to zero, the routine can still generate
91 * random numbers; however, an attacker may (at least in theory) be
92 * able to infer the future output of the generator from prior
93 * outputs.  This requires successful cryptanalysis of SHA, which is
94 * not believed to be feasible, but there is a remote possibility.
95 * Nonetheless, these numbers should be useful for the vast majority
96 * of purposes.
97 *
98 * Exported interfaces ---- output
99 * ===============================
100 *
101 * There are three exported interfaces; the first is one designed to
102 * be used from within the kernel:
103 *
104 *      void get_random_bytes(void *buf, int nbytes);
105 *
106 * This interface will return the requested number of random bytes,
107 * and place it in the requested buffer.
108 *
109 * The two other interfaces are two character devices /dev/random and
110 * /dev/urandom.  /dev/random is suitable for use when very high
111 * quality randomness is desired (for example, for key generation or
112 * one-time pads), as it will only return a maximum of the number of
113 * bits of randomness (as estimated by the random number generator)
114 * contained in the entropy pool.
115 *
116 * The /dev/urandom device does not have this limit, and will return
117 * as many bytes as are requested.  As more and more random bytes are
118 * requested without giving time for the entropy pool to recharge,
119 * this will result in random numbers that are merely cryptographically
120 * strong.  For many applications, however, this is acceptable.
121 *
122 * Exported interfaces ---- input
123 * ==============================
124 *
125 * The current exported interfaces for gathering environmental noise
126 * from the devices are:
127 *
128 *      void add_input_randomness(unsigned int type, unsigned int code,
129 *                                unsigned int value);
130 *      void add_interrupt_randomness(int irq);
131 *      void add_disk_randomness(struct gendisk *disk);
132 *
133 *      void random_input_words(__u32 *buf, size_t wordcount, int ent_count)
134 *      int random_input_wait(void);
135 *
136 * add_input_randomness() uses the input layer interrupt timing, as well as
137 * the event type information from the hardware.
138 *
139 * add_interrupt_randomness() uses the inter-interrupt timing as random
140 * inputs to the entropy pool.  Note that not all interrupts are good
141 * sources of randomness!  For example, the timer interrupts is not a
142 * good choice, because the periodicity of the interrupts is too
143 * regular, and hence predictable to an attacker.  Network Interface
144 * Controller interrupts are a better measure, since the timing of the
145 * NIC interrupts are more unpredictable.
146 *
147 * add_disk_randomness() uses what amounts to the seek time of block
148 * layer request events, on a per-disk_devt basis, as input to the
149 * entropy pool. Note that high-speed solid state drives with very low
150 * seek times do not make for good sources of entropy, as their seek
151 * times are usually fairly consistent.
152 *
153 * random_input_words() just provides a raw block of entropy to the input
154 * pool, such as from a hardware entropy generator.
155 *
156 * random_input_wait() suspends the caller until such time as the
157 * entropy pool falls below the write threshold, and returns a count of how
158 * much entropy (in bits) is needed to sustain the pool.
159 *
160 * All of these routines try to estimate how many bits of randomness a
161 * particular randomness source.  They do this by keeping track of the
162 * first and second order deltas of the event timings.
163 *
164 * Ensuring unpredictability at system startup
165 * ============================================
166 *
167 * When any operating system starts up, it will go through a sequence
168 * of actions that are fairly predictable by an adversary, especially
169 * if the start-up does not involve interaction with a human operator.
170 * This reduces the actual number of bits of unpredictability in the
171 * entropy pool below the value in entropy_count.  In order to
172 * counteract this effect, it helps to carry information in the
173 * entropy pool across shut-downs and start-ups.  To do this, put the
174 * following lines an appropriate script which is run during the boot
175 * sequence:
176 *
177 *      echo "Initializing random number generator..."
178 *      random_seed=/var/run/random-seed
179 *      # Carry a random seed from start-up to start-up
180 *      # Load and then save the whole entropy pool
181 *      if [ -f $random_seed ]; then
182 *              cat $random_seed >/dev/urandom
183 *      else
184 *              touch $random_seed
185 *      fi
186 *      chmod 600 $random_seed
187 *      dd if=/dev/urandom of=$random_seed count=1 bs=512
188 *
189 * and the following lines in an appropriate script which is run as
190 * the system is shutdown:
191 *
192 *      # Carry a random seed from shut-down to start-up
193 *      # Save the whole entropy pool
194 *      echo "Saving random seed..."
195 *      random_seed=/var/run/random-seed
196 *      touch $random_seed
197 *      chmod 600 $random_seed
198 *      dd if=/dev/urandom of=$random_seed count=1 bs=512
199 *
200 * For example, on most modern systems using the System V init
201 * scripts, such code fragments would be found in
202 * /etc/rc.d/init.d/random.  On older Linux systems, the correct script
203 * location might be in /etc/rcb.d/rc.local or /etc/rc.d/rc.0.
204 *
205 * Effectively, these commands cause the contents of the entropy pool
206 * to be saved at shut-down time and reloaded into the entropy pool at
207 * start-up.  (The 'dd' in the addition to the bootup script is to
208 * make sure that /etc/random-seed is different for every start-up,
209 * even if the system crashes without executing rc.0.)  Even with
210 * complete knowledge of the start-up activities, predicting the state
211 * of the entropy pool requires knowledge of the previous history of
212 * the system.
213 *
214 * Configuring the /dev/random driver under Linux
215 * ==============================================
216 *
217 * The /dev/random driver under Linux uses minor numbers 8 and 9 of
218 * the /dev/mem major number (#1).  So if your system does not have
219 * /dev/random and /dev/urandom created already, they can be created
220 * by using the commands:
221 *
222 *      mknod /dev/random c 1 8
223 *      mknod /dev/urandom c 1 9
224 *
225 * Acknowledgements:
226 * =================
227 *
228 * Ideas for constructing this random number generator were derived
229 * from Pretty Good Privacy's random number generator, and from private
230 * discussions with Phil Karn.  Colin Plumb provided a faster random
231 * number generator, which speed up the mixing function of the entropy
232 * pool, taken from PGPfone.  Dale Worley has also contributed many
233 * useful ideas and suggestions to improve this driver.
234 *
235 * Any flaws in the design are solely my responsibility, and should
236 * not be attributed to the Phil, Colin, or any of authors of PGP.
237 *
238 * Further background information on this topic may be obtained from
239 * RFC 1750, "Randomness Recommendations for Security", by Donald
240 * Eastlake, Steve Crocker, and Jeff Schiller.
241 */
242
243#include <linux/utsname.h>
244#include <linux/module.h>
245#include <linux/kernel.h>
246#include <linux/major.h>
247#include <linux/string.h>
248#include <linux/fcntl.h>
249#include <linux/slab.h>
250#include <linux/random.h>
251#include <linux/poll.h>
252#include <linux/init.h>
253#include <linux/fs.h>
254#include <linux/genhd.h>
255#include <linux/interrupt.h>
256#include <linux/mm.h>
257#include <linux/nodemask.h>
258#include <linux/spinlock.h>
259#include <linux/kthread.h>
260#include <linux/percpu.h>
261#include <linux/cryptohash.h>
262#include <linux/fips.h>
263#include <linux/ptrace.h>
264#include <linux/kmemcheck.h>
265#include <linux/workqueue.h>
266#include <linux/irq.h>
267#include <linux/syscalls.h>
268#include <linux/completion.h>
269#include <linux/uuid.h>
270#include <crypto/chacha20.h>
271
272#include <asm/processor.h>
273#include <asm/uaccess.h>
274#include <asm/irq.h>
275#include <asm/irq_regs.h>
276#include <asm/io.h>
277
278#define CREATE_TRACE_POINTS
279#include <trace/events/random.h>
280
281/* #define ADD_INTERRUPT_BENCH */
282
283/*
284 * Configuration information
285 */
286#define INPUT_POOL_SHIFT        12
287#define INPUT_POOL_WORDS        (1 << (INPUT_POOL_SHIFT-5))
288#define OUTPUT_POOL_SHIFT       10
289#define OUTPUT_POOL_WORDS       (1 << (OUTPUT_POOL_SHIFT-5))
290#define SEC_XFER_SIZE           512
291#define EXTRACT_SIZE            10
292
293#define DEBUG_RANDOM_BOOT 0
294
295#define LONGS(x) (((x) + sizeof(unsigned long) - 1)/sizeof(unsigned long))
296
297/*
298 * To allow fractional bits to be tracked, the entropy_count field is
299 * denominated in units of 1/8th bits.
300 *
301 * 2*(ENTROPY_SHIFT + log2(poolbits)) must <= 31, or the multiply in
302 * credit_entropy_bits() needs to be 64 bits wide.
303 */
304#define ENTROPY_SHIFT 3
305#define ENTROPY_BITS(r) ((r)->entropy_count >> ENTROPY_SHIFT)
306
307/*
308 * The minimum number of bits of entropy before we wake up a read on
309 * /dev/random.  Should be enough to do a significant reseed.
310 */
311static int random_read_wakeup_bits = 64;
312
313/*
314 * If the entropy count falls under this number of bits, then we
315 * should wake up processes which are selecting or polling on write
316 * access to /dev/random.
317 */
318static int random_write_wakeup_bits = 28 * OUTPUT_POOL_WORDS;
319
320/*
321 * The minimum number of seconds between urandom pool reseeding.  We
322 * do this to limit the amount of entropy that can be drained from the
323 * input pool even if there are heavy demands on /dev/urandom.
324 */
325static int random_min_urandom_seed = 60;
326
327/*
328 * Originally, we used a primitive polynomial of degree .poolwords
329 * over GF(2).  The taps for various sizes are defined below.  They
330 * were chosen to be evenly spaced except for the last tap, which is 1
331 * to get the twisting happening as fast as possible.
332 *
333 * For the purposes of better mixing, we use the CRC-32 polynomial as
334 * well to make a (modified) twisted Generalized Feedback Shift
335 * Register.  (See M. Matsumoto & Y. Kurita, 1992.  Twisted GFSR
336 * generators.  ACM Transactions on Modeling and Computer Simulation
337 * 2(3):179-194.  Also see M. Matsumoto & Y. Kurita, 1994.  Twisted
338 * GFSR generators II.  ACM Transactions on Modeling and Computer
339 * Simulation 4:254-266)
340 *
341 * Thanks to Colin Plumb for suggesting this.
342 *
343 * The mixing operation is much less sensitive than the output hash,
344 * where we use SHA-1.  All that we want of mixing operation is that
345 * it be a good non-cryptographic hash; i.e. it not produce collisions
346 * when fed "random" data of the sort we expect to see.  As long as
347 * the pool state differs for different inputs, we have preserved the
348 * input entropy and done a good job.  The fact that an intelligent
349 * attacker can construct inputs that will produce controlled
350 * alterations to the pool's state is not important because we don't
351 * consider such inputs to contribute any randomness.  The only
352 * property we need with respect to them is that the attacker can't
353 * increase his/her knowledge of the pool's state.  Since all
354 * additions are reversible (knowing the final state and the input,
355 * you can reconstruct the initial state), if an attacker has any
356 * uncertainty about the initial state, he/she can only shuffle that
357 * uncertainty about, but never cause any collisions (which would
358 * decrease the uncertainty).
359 *
360 * Our mixing functions were analyzed by Lacharme, Roeck, Strubel, and
361 * Videau in their paper, "The Linux Pseudorandom Number Generator
362 * Revisited" (see: http://eprint.iacr.org/2012/251.pdf).  In their
363 * paper, they point out that we are not using a true Twisted GFSR,
364 * since Matsumoto & Kurita used a trinomial feedback polynomial (that
365 * is, with only three taps, instead of the six that we are using).
366 * As a result, the resulting polynomial is neither primitive nor
367 * irreducible, and hence does not have a maximal period over
368 * GF(2**32).  They suggest a slight change to the generator
369 * polynomial which improves the resulting TGFSR polynomial to be
370 * irreducible, which we have made here.
371 */
372static struct poolinfo {
373        int poolbitshift, poolwords, poolbytes, poolbits, poolfracbits;
374#define S(x) ilog2(x)+5, (x), (x)*4, (x)*32, (x) << (ENTROPY_SHIFT+5)
375        int tap1, tap2, tap3, tap4, tap5;
376} poolinfo_table[] = {
377        /* was: x^128 + x^103 + x^76 + x^51 +x^25 + x + 1 */
378        /* x^128 + x^104 + x^76 + x^51 +x^25 + x + 1 */
379        { S(128),       104,    76,     51,     25,     1 },
380        /* was: x^32 + x^26 + x^20 + x^14 + x^7 + x + 1 */
381        /* x^32 + x^26 + x^19 + x^14 + x^7 + x + 1 */
382        { S(32),        26,     19,     14,     7,      1 },
383#if 0
384        /* x^2048 + x^1638 + x^1231 + x^819 + x^411 + x + 1  -- 115 */
385        { S(2048),      1638,   1231,   819,    411,    1 },
386
387        /* x^1024 + x^817 + x^615 + x^412 + x^204 + x + 1 -- 290 */
388        { S(1024),      817,    615,    412,    204,    1 },
389
390        /* x^1024 + x^819 + x^616 + x^410 + x^207 + x^2 + 1 -- 115 */
391        { S(1024),      819,    616,    410,    207,    2 },
392
393        /* x^512 + x^411 + x^308 + x^208 + x^104 + x + 1 -- 225 */
394        { S(512),       411,    308,    208,    104,    1 },
395
396        /* x^512 + x^409 + x^307 + x^206 + x^102 + x^2 + 1 -- 95 */
397        { S(512),       409,    307,    206,    102,    2 },
398        /* x^512 + x^409 + x^309 + x^205 + x^103 + x^2 + 1 -- 95 */
399        { S(512),       409,    309,    205,    103,    2 },
400
401        /* x^256 + x^205 + x^155 + x^101 + x^52 + x + 1 -- 125 */
402        { S(256),       205,    155,    101,    52,     1 },
403
404        /* x^128 + x^103 + x^78 + x^51 + x^27 + x^2 + 1 -- 70 */
405        { S(128),       103,    78,     51,     27,     2 },
406
407        /* x^64 + x^52 + x^39 + x^26 + x^14 + x + 1 -- 15 */
408        { S(64),        52,     39,     26,     14,     1 },
409#endif
410};
411
412/*
413 * Static global variables
414 */
415static DECLARE_WAIT_QUEUE_HEAD(random_read_wait);
416static DECLARE_WAIT_QUEUE_HEAD(random_write_wait);
417static DECLARE_WAIT_QUEUE_HEAD(urandom_init_wait);
418static struct fasync_struct *fasync;
419
420static DEFINE_SPINLOCK(random_ready_list_lock);
421static LIST_HEAD(random_ready_list);
422
423struct crng_state {
424        __u32           state[16];
425        unsigned long   init_time;
426        spinlock_t      lock;
427};
428
429struct crng_state primary_crng = {
430        .lock = __SPIN_LOCK_UNLOCKED(primary_crng.lock),
431};
432
433/*
434 * crng_init =  0 --> Uninitialized
435 *              1 --> Initialized
436 *              2 --> Initialized from input_pool
437 *
438 * crng_init is protected by primary_crng->lock, and only increases
439 * its value (from 0->1->2).
440 */
441static int crng_init = 0;
442#define crng_ready() (likely(crng_init > 0))
443static int crng_init_cnt = 0;
444#define CRNG_INIT_CNT_THRESH (2*CHACHA20_KEY_SIZE)
445static void _extract_crng(struct crng_state *crng,
446                          __u8 out[CHACHA20_BLOCK_SIZE]);
447static void _crng_backtrack_protect(struct crng_state *crng,
448                                    __u8 tmp[CHACHA20_BLOCK_SIZE], int used);
449static void process_random_ready_list(void);
450
451/**********************************************************************
452 *
453 * OS independent entropy store.   Here are the functions which handle
454 * storing entropy in an entropy pool.
455 *
456 **********************************************************************/
457
458struct entropy_store;
459struct entropy_store {
460        /* read-only data: */
461        const struct poolinfo *poolinfo;
462        __u32 *pool;
463        const char *name;
464        struct entropy_store *pull;
465        struct work_struct push_work;
466
467        /* read-write data: */
468        unsigned long last_pulled;
469        spinlock_t lock;
470        unsigned short add_ptr;
471        unsigned short input_rotate;
472        int entropy_count;
473        int entropy_total;
474        unsigned int initialized:1;
475        unsigned int limit:1;
476        unsigned int last_data_init:1;
477        __u8 last_data[EXTRACT_SIZE];
478};
479
480static ssize_t extract_entropy(struct entropy_store *r, void *buf,
481                               size_t nbytes, int min, int rsvd);
482static ssize_t _extract_entropy(struct entropy_store *r, void *buf,
483                                size_t nbytes, int fips);
484
485static void crng_reseed(struct crng_state *crng, struct entropy_store *r);
486static void push_to_pool(struct work_struct *work);
487static __u32 input_pool_data[INPUT_POOL_WORDS] __latent_entropy;
488static __u32 blocking_pool_data[OUTPUT_POOL_WORDS] __latent_entropy;
489
490static struct entropy_store input_pool = {
491        .poolinfo = &poolinfo_table[0],
492        .name = "input",
493        .limit = 1,
494        .lock = __SPIN_LOCK_UNLOCKED(input_pool.lock),
495        .pool = input_pool_data
496};
497
498static struct entropy_store blocking_pool = {
499        .poolinfo = &poolinfo_table[1],
500        .name = "blocking",
501        .limit = 1,
502        .pull = &input_pool,
503        .lock = __SPIN_LOCK_UNLOCKED(blocking_pool.lock),
504        .pool = blocking_pool_data,
505        .push_work = __WORK_INITIALIZER(blocking_pool.push_work,
506                                        push_to_pool),
507};
508
509static __u32 const twist_table[8] = {
510        0x00000000, 0x3b6e20c8, 0x76dc4190, 0x4db26158,
511        0xedb88320, 0xd6d6a3e8, 0x9b64c2b0, 0xa00ae278 };
512
513/*
514 * This function adds bytes into the entropy "pool".  It does not
515 * update the entropy estimate.  The caller should call
516 * credit_entropy_bits if this is appropriate.
517 *
518 * The pool is stirred with a primitive polynomial of the appropriate
519 * degree, and then twisted.  We twist by three bits at a time because
520 * it's cheap to do so and helps slightly in the expected case where
521 * the entropy is concentrated in the low-order bits.
522 */
523static void _mix_pool_bytes(struct entropy_store *r, const void *in,
524                            int nbytes)
525{
526        unsigned long i, tap1, tap2, tap3, tap4, tap5;
527        int input_rotate;
528        int wordmask = r->poolinfo->poolwords - 1;
529        const char *bytes = in;
530        __u32 w;
531
532        tap1 = r->poolinfo->tap1;
533        tap2 = r->poolinfo->tap2;
534        tap3 = r->poolinfo->tap3;
535        tap4 = r->poolinfo->tap4;
536        tap5 = r->poolinfo->tap5;
537
538        input_rotate = r->input_rotate;
539        i = r->add_ptr;
540
541        /* mix one byte at a time to simplify size handling and churn faster */
542        while (nbytes--) {
543                w = rol32(*bytes++, input_rotate);
544                i = (i - 1) & wordmask;
545
546                /* XOR in the various taps */
547                w ^= r->pool[i];
548                w ^= r->pool[(i + tap1) & wordmask];
549                w ^= r->pool[(i + tap2) & wordmask];
550                w ^= r->pool[(i + tap3) & wordmask];
551                w ^= r->pool[(i + tap4) & wordmask];
552                w ^= r->pool[(i + tap5) & wordmask];
553
554                /* Mix the result back in with a twist */
555                r->pool[i] = (w >> 3) ^ twist_table[w & 7];
556
557                /*
558                 * Normally, we add 7 bits of rotation to the pool.
559                 * At the beginning of the pool, add an extra 7 bits
560                 * rotation, so that successive passes spread the
561                 * input bits across the pool evenly.
562                 */
563                input_rotate = (input_rotate + (i ? 7 : 14)) & 31;
564        }
565
566        r->input_rotate = input_rotate;
567        r->add_ptr = i;
568}
569
570static void __mix_pool_bytes(struct entropy_store *r, const void *in,
571                             int nbytes)
572{
573        trace_mix_pool_bytes_nolock(r->name, nbytes, _RET_IP_);
574        _mix_pool_bytes(r, in, nbytes);
575}
576
577static void mix_pool_bytes(struct entropy_store *r, const void *in,
578                           int nbytes)
579{
580        unsigned long flags;
581
582        trace_mix_pool_bytes(r->name, nbytes, _RET_IP_);
583        spin_lock_irqsave(&r->lock, flags);
584        _mix_pool_bytes(r, in, nbytes);
585        spin_unlock_irqrestore(&r->lock, flags);
586}
587
588struct fast_pool {
589        __u32           pool[4];
590        unsigned long   last;
591        unsigned short  reg_idx;
592        unsigned char   count;
593};
594
595/*
596 * This is a fast mixing routine used by the interrupt randomness
597 * collector.  It's hardcoded for an 128 bit pool and assumes that any
598 * locks that might be needed are taken by the caller.
599 */
600static void fast_mix(struct fast_pool *f)
601{
602        __u32 a = f->pool[0],   b = f->pool[1];
603        __u32 c = f->pool[2],   d = f->pool[3];
604
605        a += b;                 c += d;
606        b = rol32(b, 6);        d = rol32(d, 27);
607        d ^= a;                 b ^= c;
608
609        a += b;                 c += d;
610        b = rol32(b, 16);       d = rol32(d, 14);
611        d ^= a;                 b ^= c;
612
613        a += b;                 c += d;
614        b = rol32(b, 6);        d = rol32(d, 27);
615        d ^= a;                 b ^= c;
616
617        a += b;                 c += d;
618        b = rol32(b, 16);       d = rol32(d, 14);
619        d ^= a;                 b ^= c;
620
621        f->pool[0] = a;  f->pool[1] = b;
622        f->pool[2] = c;  f->pool[3] = d;
623        f->count++;
624}
625
626static void process_random_ready_list(void)
627{
628        unsigned long flags;
629        struct random_ready_callback *rdy, *tmp;
630
631        spin_lock_irqsave(&random_ready_list_lock, flags);
632        list_for_each_entry_safe(rdy, tmp, &random_ready_list, list) {
633                struct module *owner = rdy->owner;
634
635                list_del_init(&rdy->list);
636                rdy->func(rdy);
637                module_put(owner);
638        }
639        spin_unlock_irqrestore(&random_ready_list_lock, flags);
640}
641
642/*
643 * Credit (or debit) the entropy store with n bits of entropy.
644 * Use credit_entropy_bits_safe() if the value comes from userspace
645 * or otherwise should be checked for extreme values.
646 */
647static void credit_entropy_bits(struct entropy_store *r, int nbits)
648{
649        int entropy_count, orig;
650        const int pool_size = r->poolinfo->poolfracbits;
651        int nfrac = nbits << ENTROPY_SHIFT;
652
653        if (!nbits)
654                return;
655
656retry:
657        entropy_count = orig = ACCESS_ONCE(r->entropy_count);
658        if (nfrac < 0) {
659                /* Debit */
660                entropy_count += nfrac;
661        } else {
662                /*
663                 * Credit: we have to account for the possibility of
664                 * overwriting already present entropy.  Even in the
665                 * ideal case of pure Shannon entropy, new contributions
666                 * approach the full value asymptotically:
667                 *
668                 * entropy <- entropy + (pool_size - entropy) *
669                 *      (1 - exp(-add_entropy/pool_size))
670                 *
671                 * For add_entropy <= pool_size/2 then
672                 * (1 - exp(-add_entropy/pool_size)) >=
673                 *    (add_entropy/pool_size)*0.7869...
674                 * so we can approximate the exponential with
675                 * 3/4*add_entropy/pool_size and still be on the
676                 * safe side by adding at most pool_size/2 at a time.
677                 *
678                 * The use of pool_size-2 in the while statement is to
679                 * prevent rounding artifacts from making the loop
680                 * arbitrarily long; this limits the loop to log2(pool_size)*2
681                 * turns no matter how large nbits is.
682                 */
683                int pnfrac = nfrac;
684                const int s = r->poolinfo->poolbitshift + ENTROPY_SHIFT + 2;
685                /* The +2 corresponds to the /4 in the denominator */
686
687                do {
688                        unsigned int anfrac = min(pnfrac, pool_size/2);
689                        unsigned int add =
690                                ((pool_size - entropy_count)*anfrac*3) >> s;
691
692                        entropy_count += add;
693                        pnfrac -= anfrac;
694                } while (unlikely(entropy_count < pool_size-2 && pnfrac));
695        }
696
697        if (unlikely(entropy_count < 0)) {
698                pr_warn("random: negative entropy/overflow: pool %s count %d\n",
699                        r->name, entropy_count);
700                WARN_ON(1);
701                entropy_count = 0;
702        } else if (entropy_count > pool_size)
703                entropy_count = pool_size;
704        if (cmpxchg(&r->entropy_count, orig, entropy_count) != orig)
705                goto retry;
706
707        r->entropy_total += nbits;
708        if (!r->initialized && r->entropy_total > 128) {
709                r->initialized = 1;
710                r->entropy_total = 0;
711        }
712
713        trace_credit_entropy_bits(r->name, nbits,
714                                  entropy_count >> ENTROPY_SHIFT,
715                                  r->entropy_total, _RET_IP_);
716
717        if (r == &input_pool) {
718                int entropy_bits = entropy_count >> ENTROPY_SHIFT;
719
720                if (crng_init < 2 && entropy_bits >= 128) {
721                        crng_reseed(&primary_crng, r);
722                        entropy_bits = r->entropy_count >> ENTROPY_SHIFT;
723                }
724
725                /* should we wake readers? */
726                if (entropy_bits >= random_read_wakeup_bits) {
727                        wake_up_interruptible(&random_read_wait);
728                        kill_fasync(&fasync, SIGIO, POLL_IN);
729                }
730                /* If the input pool is getting full, send some
731                 * entropy to the blocking pool until it is 75% full.
732                 */
733                if (entropy_bits > random_write_wakeup_bits &&
734                    r->initialized &&
735                    r->entropy_total >= 2*random_read_wakeup_bits) {
736                        struct entropy_store *other = &blocking_pool;
737
738                        if (other->entropy_count <=
739                            3 * other->poolinfo->poolfracbits / 4) {
740                                schedule_work(&other->push_work);
741                                r->entropy_total = 0;
742                        }
743                }
744        }
745}
746
747static int credit_entropy_bits_safe(struct entropy_store *r, int nbits)
748{
749        const int nbits_max = (int)(~0U >> (ENTROPY_SHIFT + 1));
750
751        if (nbits < 0)
752                return -EINVAL;
753
754        /* Cap the value to avoid overflows */
755        nbits = min(nbits,  nbits_max);
756
757        credit_entropy_bits(r, nbits);
758        return 0;
759}
760
761/*********************************************************************
762 *
763 * CRNG using CHACHA20
764 *
765 *********************************************************************/
766
767#define CRNG_RESEED_INTERVAL (300*HZ)
768
769static DECLARE_WAIT_QUEUE_HEAD(crng_init_wait);
770
771#ifdef CONFIG_NUMA
772/*
773 * Hack to deal with crazy userspace progams when they are all trying
774 * to access /dev/urandom in parallel.  The programs are almost
775 * certainly doing something terribly wrong, but we'll work around
776 * their brain damage.
777 */
778static struct crng_state **crng_node_pool __read_mostly;
779#endif
780
781static void crng_initialize(struct crng_state *crng)
782{
783        int             i;
784        unsigned long   rv;
785
786        memcpy(&crng->state[0], "expand 32-byte k", 16);
787        if (crng == &primary_crng)
788                _extract_entropy(&input_pool, &crng->state[4],
789                                 sizeof(__u32) * 12, 0);
790        else
791                get_random_bytes(&crng->state[4], sizeof(__u32) * 12);
792        for (i = 4; i < 16; i++) {
793                if (!arch_get_random_seed_long(&rv) &&
794                    !arch_get_random_long(&rv))
795                        rv = random_get_entropy();
796                crng->state[i] ^= rv;
797        }
798        crng->init_time = jiffies - CRNG_RESEED_INTERVAL - 1;
799}
800
801static int crng_fast_load(const char *cp, size_t len)
802{
803        unsigned long flags;
804        char *p;
805
806        if (!spin_trylock_irqsave(&primary_crng.lock, flags))
807                return 0;
808        if (crng_ready()) {
809                spin_unlock_irqrestore(&primary_crng.lock, flags);
810                return 0;
811        }
812        p = (unsigned char *) &primary_crng.state[4];
813        while (len > 0 && crng_init_cnt < CRNG_INIT_CNT_THRESH) {
814                p[crng_init_cnt % CHACHA20_KEY_SIZE] ^= *cp;
815                cp++; crng_init_cnt++; len--;
816        }
817        if (crng_init_cnt >= CRNG_INIT_CNT_THRESH) {
818                crng_init = 1;
819                wake_up_interruptible(&crng_init_wait);
820                pr_notice("random: fast init done\n");
821        }
822        spin_unlock_irqrestore(&primary_crng.lock, flags);
823        return 1;
824}
825
826static void crng_reseed(struct crng_state *crng, struct entropy_store *r)
827{
828        unsigned long   flags;
829        int             i, num;
830        union {
831                __u8    block[CHACHA20_BLOCK_SIZE];
832                __u32   key[8];
833        } buf;
834
835        if (r) {
836                num = extract_entropy(r, &buf, 32, 16, 0);
837                if (num == 0)
838                        return;
839        } else {
840                _extract_crng(&primary_crng, buf.block);
841                _crng_backtrack_protect(&primary_crng, buf.block,
842                                        CHACHA20_KEY_SIZE);
843        }
844        spin_lock_irqsave(&primary_crng.lock, flags);
845        for (i = 0; i < 8; i++) {
846                unsigned long   rv;
847                if (!arch_get_random_seed_long(&rv) &&
848                    !arch_get_random_long(&rv))
849                        rv = random_get_entropy();
850                crng->state[i+4] ^= buf.key[i] ^ rv;
851        }
852        memzero_explicit(&buf, sizeof(buf));
853        crng->init_time = jiffies;
854        if (crng == &primary_crng && crng_init < 2) {
855                crng_init = 2;
856                process_random_ready_list();
857                wake_up_interruptible(&crng_init_wait);
858                pr_notice("random: crng init done\n");
859        }
860        spin_unlock_irqrestore(&primary_crng.lock, flags);
861}
862
863static inline void maybe_reseed_primary_crng(void)
864{
865        if (crng_init > 2 &&
866            time_after(jiffies, primary_crng.init_time + CRNG_RESEED_INTERVAL))
867                crng_reseed(&primary_crng, &input_pool);
868}
869
870static inline void crng_wait_ready(void)
871{
872        wait_event_interruptible(crng_init_wait, crng_ready());
873}
874
875static void _extract_crng(struct crng_state *crng,
876                          __u8 out[CHACHA20_BLOCK_SIZE])
877{
878        unsigned long v, flags;
879
880        if (crng_init > 1 &&
881            time_after(jiffies, crng->init_time + CRNG_RESEED_INTERVAL))
882                crng_reseed(crng, crng == &primary_crng ? &input_pool : NULL);
883        spin_lock_irqsave(&crng->lock, flags);
884        if (arch_get_random_long(&v))
885                crng->state[14] ^= v;
886        chacha20_block(&crng->state[0], out);
887        if (crng->state[12] == 0)
888                crng->state[13]++;
889        spin_unlock_irqrestore(&crng->lock, flags);
890}
891
892static void extract_crng(__u8 out[CHACHA20_BLOCK_SIZE])
893{
894        struct crng_state *crng = NULL;
895
896#ifdef CONFIG_NUMA
897        if (crng_node_pool)
898                crng = crng_node_pool[numa_node_id()];
899        if (crng == NULL)
900#endif
901                crng = &primary_crng;
902        _extract_crng(crng, out);
903}
904
905/*
906 * Use the leftover bytes from the CRNG block output (if there is
907 * enough) to mutate the CRNG key to provide backtracking protection.
908 */
909static void _crng_backtrack_protect(struct crng_state *crng,
910                                    __u8 tmp[CHACHA20_BLOCK_SIZE], int used)
911{
912        unsigned long   flags;
913        __u32           *s, *d;
914        int             i;
915
916        used = round_up(used, sizeof(__u32));
917        if (used + CHACHA20_KEY_SIZE > CHACHA20_BLOCK_SIZE) {
918                extract_crng(tmp);
919                used = 0;
920        }
921        spin_lock_irqsave(&crng->lock, flags);
922        s = (__u32 *) &tmp[used];
923        d = &crng->state[4];
924        for (i=0; i < 8; i++)
925                *d++ ^= *s++;
926        spin_unlock_irqrestore(&crng->lock, flags);
927}
928
929static void crng_backtrack_protect(__u8 tmp[CHACHA20_BLOCK_SIZE], int used)
930{
931        struct crng_state *crng = NULL;
932
933#ifdef CONFIG_NUMA
934        if (crng_node_pool)
935                crng = crng_node_pool[numa_node_id()];
936        if (crng == NULL)
937#endif
938                crng = &primary_crng;
939        _crng_backtrack_protect(crng, tmp, used);
940}
941
942static ssize_t extract_crng_user(void __user *buf, size_t nbytes)
943{
944        ssize_t ret = 0, i = CHACHA20_BLOCK_SIZE;
945        __u8 tmp[CHACHA20_BLOCK_SIZE];
946        int large_request = (nbytes > 256);
947
948        while (nbytes) {
949                if (large_request && need_resched()) {
950                        if (signal_pending(current)) {
951                                if (ret == 0)
952                                        ret = -ERESTARTSYS;
953                                break;
954                        }
955                        schedule();
956                }
957
958                extract_crng(tmp);
959                i = min_t(int, nbytes, CHACHA20_BLOCK_SIZE);
960                if (copy_to_user(buf, tmp, i)) {
961                        ret = -EFAULT;
962                        break;
963                }
964
965                nbytes -= i;
966                buf += i;
967                ret += i;
968        }
969        crng_backtrack_protect(tmp, i);
970
971        /* Wipe data just written to memory */
972        memzero_explicit(tmp, sizeof(tmp));
973
974        return ret;
975}
976
977
978/*********************************************************************
979 *
980 * Entropy input management
981 *
982 *********************************************************************/
983
984/* There is one of these per entropy source */
985struct timer_rand_state {
986        cycles_t last_time;
987        long last_delta, last_delta2;
988        unsigned dont_count_entropy:1;
989};
990
991#define INIT_TIMER_RAND_STATE { INITIAL_JIFFIES, };
992
993/*
994 * Add device- or boot-specific data to the input pool to help
995 * initialize it.
996 *
997 * None of this adds any entropy; it is meant to avoid the problem of
998 * the entropy pool having similar initial state across largely
999 * identical devices.
1000 */
1001void add_device_randomness(const void *buf, unsigned int size)
1002{
1003        unsigned long time = random_get_entropy() ^ jiffies;
1004        unsigned long flags;
1005
1006        trace_add_device_randomness(size, _RET_IP_);
1007        spin_lock_irqsave(&input_pool.lock, flags);
1008        _mix_pool_bytes(&input_pool, buf, size);
1009        _mix_pool_bytes(&input_pool, &time, sizeof(time));
1010        spin_unlock_irqrestore(&input_pool.lock, flags);
1011}
1012EXPORT_SYMBOL(add_device_randomness);
1013
1014static struct timer_rand_state input_timer_state = INIT_TIMER_RAND_STATE;
1015
1016/*
1017 * This function adds entropy to the entropy "pool" by using timing
1018 * delays.  It uses the timer_rand_state structure to make an estimate
1019 * of how many bits of entropy this call has added to the pool.
1020 *
1021 * The number "num" is also added to the pool - it should somehow describe
1022 * the type of event which just happened.  This is currently 0-255 for
1023 * keyboard scan codes, and 256 upwards for interrupts.
1024 *
1025 */
1026static void add_timer_randomness(struct timer_rand_state *state, unsigned num)
1027{
1028        struct entropy_store    *r;
1029        struct {
1030                long jiffies;
1031                unsigned cycles;
1032                unsigned num;
1033        } sample;
1034        long delta, delta2, delta3;
1035
1036        preempt_disable();
1037
1038        sample.jiffies = jiffies;
1039        sample.cycles = random_get_entropy();
1040        sample.num = num;
1041        r = &input_pool;
1042        mix_pool_bytes(r, &sample, sizeof(sample));
1043
1044        /*
1045         * Calculate number of bits of randomness we probably added.
1046         * We take into account the first, second and third-order deltas
1047         * in order to make our estimate.
1048         */
1049
1050        if (!state->dont_count_entropy) {
1051                delta = sample.jiffies - state->last_time;
1052                state->last_time = sample.jiffies;
1053
1054                delta2 = delta - state->last_delta;
1055                state->last_delta = delta;
1056
1057                delta3 = delta2 - state->last_delta2;
1058                state->last_delta2 = delta2;
1059
1060                if (delta < 0)
1061                        delta = -delta;
1062                if (delta2 < 0)
1063                        delta2 = -delta2;
1064                if (delta3 < 0)
1065                        delta3 = -delta3;
1066                if (delta > delta2)
1067                        delta = delta2;
1068                if (delta > delta3)
1069                        delta = delta3;
1070
1071                /*
1072                 * delta is now minimum absolute delta.
1073                 * Round down by 1 bit on general principles,
1074                 * and limit entropy entimate to 12 bits.
1075                 */
1076                credit_entropy_bits(r, min_t(int, fls(delta>>1), 11));
1077        }
1078        preempt_enable();
1079}
1080
1081void add_input_randomness(unsigned int type, unsigned int code,
1082                                 unsigned int value)
1083{
1084        static unsigned char last_value;
1085
1086        /* ignore autorepeat and the like */
1087        if (value == last_value)
1088                return;
1089
1090        last_value = value;
1091        add_timer_randomness(&input_timer_state,
1092                             (type << 4) ^ code ^ (code >> 4) ^ value);
1093        trace_add_input_randomness(ENTROPY_BITS(&input_pool));
1094}
1095EXPORT_SYMBOL_GPL(add_input_randomness);
1096
1097static DEFINE_PER_CPU(struct fast_pool, irq_randomness);
1098
1099#ifdef ADD_INTERRUPT_BENCH
1100static unsigned long avg_cycles, avg_deviation;
1101
1102#define AVG_SHIFT 8     /* Exponential average factor k=1/256 */
1103#define FIXED_1_2 (1 << (AVG_SHIFT-1))
1104
1105static void add_interrupt_bench(cycles_t start)
1106{
1107        long delta = random_get_entropy() - start;
1108
1109        /* Use a weighted moving average */
1110        delta = delta - ((avg_cycles + FIXED_1_2) >> AVG_SHIFT);
1111        avg_cycles += delta;
1112        /* And average deviation */
1113        delta = abs(delta) - ((avg_deviation + FIXED_1_2) >> AVG_SHIFT);
1114        avg_deviation += delta;
1115}
1116#else
1117#define add_interrupt_bench(x)
1118#endif
1119
1120static __u32 get_reg(struct fast_pool *f, struct pt_regs *regs)
1121{
1122        __u32 *ptr = (__u32 *) regs;
1123
1124        if (regs == NULL)
1125                return 0;
1126        if (f->reg_idx >= sizeof(struct pt_regs) / sizeof(__u32))
1127                f->reg_idx = 0;
1128        return *(ptr + f->reg_idx++);
1129}
1130
1131void add_interrupt_randomness(int irq, int irq_flags)
1132{
1133        struct entropy_store    *r;
1134        struct fast_pool        *fast_pool = this_cpu_ptr(&irq_randomness);
1135        struct pt_regs          *regs = get_irq_regs();
1136        unsigned long           now = jiffies;
1137        cycles_t                cycles = random_get_entropy();
1138        __u32                   c_high, j_high;
1139        __u64                   ip;
1140        unsigned long           seed;
1141        int                     credit = 0;
1142
1143        if (cycles == 0)
1144                cycles = get_reg(fast_pool, regs);
1145        c_high = (sizeof(cycles) > 4) ? cycles >> 32 : 0;
1146        j_high = (sizeof(now) > 4) ? now >> 32 : 0;
1147        fast_pool->pool[0] ^= cycles ^ j_high ^ irq;
1148        fast_pool->pool[1] ^= now ^ c_high;
1149        ip = regs ? instruction_pointer(regs) : _RET_IP_;
1150        fast_pool->pool[2] ^= ip;
1151        fast_pool->pool[3] ^= (sizeof(ip) > 4) ? ip >> 32 :
1152                get_reg(fast_pool, regs);
1153
1154        fast_mix(fast_pool);
1155        add_interrupt_bench(cycles);
1156
1157        if (!crng_ready()) {
1158                if ((fast_pool->count >= 64) &&
1159                    crng_fast_load((char *) fast_pool->pool,
1160                                   sizeof(fast_pool->pool))) {
1161                        fast_pool->count = 0;
1162                        fast_pool->last = now;
1163                }
1164                return;
1165        }
1166
1167        if ((fast_pool->count < 64) &&
1168            !time_after(now, fast_pool->last + HZ))
1169                return;
1170
1171        r = &input_pool;
1172        if (!spin_trylock(&r->lock))
1173                return;
1174
1175        fast_pool->last = now;
1176        __mix_pool_bytes(r, &fast_pool->pool, sizeof(fast_pool->pool));
1177
1178        /*
1179         * If we have architectural seed generator, produce a seed and
1180         * add it to the pool.  For the sake of paranoia don't let the
1181         * architectural seed generator dominate the input from the
1182         * interrupt noise.
1183         */
1184        if (arch_get_random_seed_long(&seed)) {
1185                __mix_pool_bytes(r, &seed, sizeof(seed));
1186                credit = 1;
1187        }
1188        spin_unlock(&r->lock);
1189
1190        fast_pool->count = 0;
1191
1192        /* award one bit for the contents of the fast pool */
1193        credit_entropy_bits(r, credit + 1);
1194}
1195EXPORT_SYMBOL_GPL(add_interrupt_randomness);
1196
1197#ifdef CONFIG_BLOCK
1198void add_disk_randomness(struct gendisk *disk)
1199{
1200        if (!disk || !disk->random)
1201                return;
1202        /* first major is 1, so we get >= 0x200 here */
1203        add_timer_randomness(disk->random, 0x100 + disk_devt(disk));
1204        trace_add_disk_randomness(disk_devt(disk), ENTROPY_BITS(&input_pool));
1205}
1206EXPORT_SYMBOL_GPL(add_disk_randomness);
1207#endif
1208
1209/*
1210 * random_input_words - add bulk entropy to pool
1211 *
1212 * @buf: buffer to add
1213 * @wordcount: number of __u32 words to add
1214 * @ent_count: total amount of entropy (in bits) to credit
1215 *
1216 * this provides bulk input of entropy to the input pool
1217 *
1218 */
1219void random_input_words(__u32 *buf, size_t wordcount, int ent_count)
1220{
1221        mix_pool_bytes(&input_pool, buf, wordcount*4);
1222
1223        credit_entropy_bits(&input_pool, ent_count);
1224        /*
1225         * Wake up waiting processes if we have enough
1226         * entropy.
1227         */
1228        if (input_pool.entropy_count >= random_read_wakeup_bits)
1229                wake_up_interruptible(&random_read_wait);
1230}
1231EXPORT_SYMBOL(random_input_words);
1232
1233/*
1234 * random_input_wait - wait until random needs entropy
1235 *
1236 * this function sleeps until the /dev/random subsystem actually
1237 * needs more entropy, and then return the amount of entropy
1238 * that it would be nice to have added to the system.
1239 */
1240int random_input_wait(void)
1241{
1242        int count;
1243
1244        wait_event_interruptible(random_write_wait,
1245                input_pool.entropy_count < random_write_wakeup_bits);
1246
1247        count = random_write_wakeup_bits - input_pool.entropy_count;
1248
1249        /* likely we got woken up due to a signal */
1250        if (count <= 0) count = random_read_wakeup_bits;
1251
1252        return count;
1253}
1254EXPORT_SYMBOL(random_input_wait);
1255
1256
1257/*********************************************************************
1258 *
1259 * Entropy extraction routines
1260 *
1261 *********************************************************************/
1262
1263/*
1264 * This utility inline function is responsible for transferring entropy
1265 * from the primary pool to the secondary extraction pool. We make
1266 * sure we pull enough for a 'catastrophic reseed'.
1267 */
1268static void _xfer_secondary_pool(struct entropy_store *r, size_t nbytes);
1269static void xfer_secondary_pool(struct entropy_store *r, size_t nbytes)
1270{
1271        if (!r->pull ||
1272            r->entropy_count >= (nbytes << (ENTROPY_SHIFT + 3)) ||
1273            r->entropy_count > r->poolinfo->poolfracbits)
1274                return;
1275
1276        if (r->limit == 0 && random_min_urandom_seed) {
1277                unsigned long now = jiffies;
1278
1279                if (time_before(now,
1280                                r->last_pulled + random_min_urandom_seed * HZ))
1281                        return;
1282                r->last_pulled = now;
1283        }
1284
1285        _xfer_secondary_pool(r, nbytes);
1286}
1287
1288static void _xfer_secondary_pool(struct entropy_store *r, size_t nbytes)
1289{
1290        __u32   tmp[OUTPUT_POOL_WORDS];
1291
1292        /* For /dev/random's pool, always leave two wakeups' worth */
1293        int rsvd_bytes = r->limit ? 0 : random_read_wakeup_bits / 4;
1294        int bytes = nbytes;
1295
1296        /* pull at least as much as a wakeup */
1297        bytes = max_t(int, bytes, random_read_wakeup_bits / 8);
1298        /* but never more than the buffer size */
1299        bytes = min_t(int, bytes, sizeof(tmp));
1300
1301        trace_xfer_secondary_pool(r->name, bytes * 8, nbytes * 8,
1302                                  ENTROPY_BITS(r), ENTROPY_BITS(r->pull));
1303        bytes = extract_entropy(r->pull, tmp, bytes,
1304                                random_read_wakeup_bits / 8, rsvd_bytes);
1305        mix_pool_bytes(r, tmp, bytes);
1306        credit_entropy_bits(r, bytes*8);
1307}
1308
1309/*
1310 * Used as a workqueue function so that when the input pool is getting
1311 * full, we can "spill over" some entropy to the output pools.  That
1312 * way the output pools can store some of the excess entropy instead
1313 * of letting it go to waste.
1314 */
1315static void push_to_pool(struct work_struct *work)
1316{
1317        struct entropy_store *r = container_of(work, struct entropy_store,
1318                                              push_work);
1319        BUG_ON(!r);
1320        _xfer_secondary_pool(r, random_read_wakeup_bits/8);
1321        trace_push_to_pool(r->name, r->entropy_count >> ENTROPY_SHIFT,
1322                           r->pull->entropy_count >> ENTROPY_SHIFT);
1323}
1324
1325/*
1326 * This function decides how many bytes to actually take from the
1327 * given pool, and also debits the entropy count accordingly.
1328 */
1329static size_t account(struct entropy_store *r, size_t nbytes, int min,
1330                      int reserved)
1331{
1332        int entropy_count, orig;
1333        size_t ibytes, nfrac;
1334
1335        BUG_ON(r->entropy_count > r->poolinfo->poolfracbits);
1336
1337        /* Can we pull enough? */
1338retry:
1339        entropy_count = orig = ACCESS_ONCE(r->entropy_count);
1340        ibytes = nbytes;
1341        /* If limited, never pull more than available */
1342        if (r->limit) {
1343                int have_bytes = entropy_count >> (ENTROPY_SHIFT + 3);
1344
1345                if ((have_bytes -= reserved) < 0)
1346                        have_bytes = 0;
1347                ibytes = min_t(size_t, ibytes, have_bytes);
1348        }
1349        if (ibytes < min)
1350                ibytes = 0;
1351
1352        if (unlikely(entropy_count < 0)) {
1353                pr_warn("random: negative entropy count: pool %s count %d\n",
1354                        r->name, entropy_count);
1355                WARN_ON(1);
1356                entropy_count = 0;
1357        }
1358        nfrac = ibytes << (ENTROPY_SHIFT + 3);
1359        if ((size_t) entropy_count > nfrac)
1360                entropy_count -= nfrac;
1361        else
1362                entropy_count = 0;
1363
1364        if (cmpxchg(&r->entropy_count, orig, entropy_count) != orig)
1365                goto retry;
1366
1367        trace_debit_entropy(r->name, 8 * ibytes);
1368        if (ibytes &&
1369            (r->entropy_count >> ENTROPY_SHIFT) < random_write_wakeup_bits) {
1370                wake_up_interruptible(&random_write_wait);
1371                kill_fasync(&fasync, SIGIO, POLL_OUT);
1372        }
1373
1374        return ibytes;
1375}
1376
1377/*
1378 * This function does the actual extraction for extract_entropy and
1379 * extract_entropy_user.
1380 *
1381 * Note: we assume that .poolwords is a multiple of 16 words.
1382 */
1383static void extract_buf(struct entropy_store *r, __u8 *out)
1384{
1385        int i;
1386        union {
1387                __u32 w[5];
1388                unsigned long l[LONGS(20)];
1389        } hash;
1390        __u32 workspace[SHA_WORKSPACE_WORDS];
1391        unsigned long flags;
1392
1393        /*
1394         * If we have an architectural hardware random number
1395         * generator, use it for SHA's initial vector
1396         */
1397        sha_init(hash.w);
1398        for (i = 0; i < LONGS(20); i++) {
1399                unsigned long v;
1400                if (!arch_get_random_long(&v))
1401                        break;
1402                hash.l[i] = v;
1403        }
1404
1405        /* Generate a hash across the pool, 16 words (512 bits) at a time */
1406        spin_lock_irqsave(&r->lock, flags);
1407        for (i = 0; i < r->poolinfo->poolwords; i += 16)
1408                sha_transform(hash.w, (__u8 *)(r->pool + i), workspace);
1409
1410        /*
1411         * We mix the hash back into the pool to prevent backtracking
1412         * attacks (where the attacker knows the state of the pool
1413         * plus the current outputs, and attempts to find previous
1414         * ouputs), unless the hash function can be inverted. By
1415         * mixing at least a SHA1 worth of hash data back, we make
1416         * brute-forcing the feedback as hard as brute-forcing the
1417         * hash.
1418         */
1419        __mix_pool_bytes(r, hash.w, sizeof(hash.w));
1420        spin_unlock_irqrestore(&r->lock, flags);
1421
1422        memzero_explicit(workspace, sizeof(workspace));
1423
1424        /*
1425         * In case the hash function has some recognizable output
1426         * pattern, we fold it in half. Thus, we always feed back
1427         * twice as much data as we output.
1428         */
1429        hash.w[0] ^= hash.w[3];
1430        hash.w[1] ^= hash.w[4];
1431        hash.w[2] ^= rol32(hash.w[2], 16);
1432
1433        memcpy(out, &hash, EXTRACT_SIZE);
1434        memzero_explicit(&hash, sizeof(hash));
1435}
1436
1437static ssize_t _extract_entropy(struct entropy_store *r, void *buf,
1438                                size_t nbytes, int fips)
1439{
1440        ssize_t ret = 0, i;
1441        __u8 tmp[EXTRACT_SIZE];
1442        unsigned long flags;
1443
1444        while (nbytes) {
1445                extract_buf(r, tmp);
1446
1447                if (fips) {
1448                        spin_lock_irqsave(&r->lock, flags);
1449                        if (!memcmp(tmp, r->last_data, EXTRACT_SIZE))
1450                                panic("Hardware RNG duplicated output!\n");
1451                        memcpy(r->last_data, tmp, EXTRACT_SIZE);
1452                        spin_unlock_irqrestore(&r->lock, flags);
1453                }
1454                i = min_t(int, nbytes, EXTRACT_SIZE);
1455                memcpy(buf, tmp, i);
1456                nbytes -= i;
1457                buf += i;
1458                ret += i;
1459        }
1460
1461        /* Wipe data just returned from memory */
1462        memzero_explicit(tmp, sizeof(tmp));
1463
1464        return ret;
1465}
1466
1467/*
1468 * This function extracts randomness from the "entropy pool", and
1469 * returns it in a buffer.
1470 *
1471 * The min parameter specifies the minimum amount we can pull before
1472 * failing to avoid races that defeat catastrophic reseeding while the
1473 * reserved parameter indicates how much entropy we must leave in the
1474 * pool after each pull to avoid starving other readers.
1475 */
1476static ssize_t extract_entropy(struct entropy_store *r, void *buf,
1477                                 size_t nbytes, int min, int reserved)
1478{
1479        __u8 tmp[EXTRACT_SIZE];
1480        unsigned long flags;
1481
1482        /* if last_data isn't primed, we need EXTRACT_SIZE extra bytes */
1483        if (fips_enabled) {
1484                spin_lock_irqsave(&r->lock, flags);
1485                if (!r->last_data_init) {
1486                        r->last_data_init = 1;
1487                        spin_unlock_irqrestore(&r->lock, flags);
1488                        trace_extract_entropy(r->name, EXTRACT_SIZE,
1489                                              ENTROPY_BITS(r), _RET_IP_);
1490                        xfer_secondary_pool(r, EXTRACT_SIZE);
1491                        extract_buf(r, tmp);
1492                        spin_lock_irqsave(&r->lock, flags);
1493                        memcpy(r->last_data, tmp, EXTRACT_SIZE);
1494                }
1495                spin_unlock_irqrestore(&r->lock, flags);
1496        }
1497
1498        trace_extract_entropy(r->name, nbytes, ENTROPY_BITS(r), _RET_IP_);
1499        xfer_secondary_pool(r, nbytes);
1500        nbytes = account(r, nbytes, min, reserved);
1501
1502        return _extract_entropy(r, buf, nbytes, fips_enabled);
1503}
1504
1505/*
1506 * This function extracts randomness from the "entropy pool", and
1507 * returns it in a userspace buffer.
1508 */
1509static ssize_t extract_entropy_user(struct entropy_store *r, void __user *buf,
1510                                    size_t nbytes)
1511{
1512        ssize_t ret = 0, i;
1513        __u8 tmp[EXTRACT_SIZE];
1514        int large_request = (nbytes > 256);
1515
1516        trace_extract_entropy_user(r->name, nbytes, ENTROPY_BITS(r), _RET_IP_);
1517        xfer_secondary_pool(r, nbytes);
1518        nbytes = account(r, nbytes, 0, 0);
1519
1520        while (nbytes) {
1521                if (large_request && need_resched()) {
1522                        if (signal_pending(current)) {
1523                                if (ret == 0)
1524                                        ret = -ERESTARTSYS;
1525                                break;
1526                        }
1527                        schedule();
1528                }
1529
1530                extract_buf(r, tmp);
1531                i = min_t(int, nbytes, EXTRACT_SIZE);
1532                if (copy_to_user(buf, tmp, i)) {
1533                        ret = -EFAULT;
1534                        break;
1535                }
1536
1537                nbytes -= i;
1538                buf += i;
1539                ret += i;
1540        }
1541
1542        /* Wipe data just returned from memory */
1543        memzero_explicit(tmp, sizeof(tmp));
1544
1545        return ret;
1546}
1547
1548/*
1549 * This function is the exported kernel interface.  It returns some
1550 * number of good random numbers, suitable for key generation, seeding
1551 * TCP sequence numbers, etc.  It does not rely on the hardware random
1552 * number generator.  For random bytes direct from the hardware RNG
1553 * (when available), use get_random_bytes_arch().
1554 */
1555void get_random_bytes(void *buf, int nbytes)
1556{
1557        __u8 tmp[CHACHA20_BLOCK_SIZE];
1558
1559#if DEBUG_RANDOM_BOOT > 0
1560        if (!crng_ready())
1561                printk(KERN_NOTICE "random: %pF get_random_bytes called "
1562                       "with crng_init = %d\n", (void *) _RET_IP_, crng_init);
1563#endif
1564        trace_get_random_bytes(nbytes, _RET_IP_);
1565
1566        while (nbytes >= CHACHA20_BLOCK_SIZE) {
1567                extract_crng(buf);
1568                buf += CHACHA20_BLOCK_SIZE;
1569                nbytes -= CHACHA20_BLOCK_SIZE;
1570        }
1571
1572        if (nbytes > 0) {
1573                extract_crng(tmp);
1574                memcpy(buf, tmp, nbytes);
1575                crng_backtrack_protect(tmp, nbytes);
1576        } else
1577                crng_backtrack_protect(tmp, CHACHA20_BLOCK_SIZE);
1578        memzero_explicit(tmp, sizeof(tmp));
1579}
1580EXPORT_SYMBOL(get_random_bytes);
1581
1582/*
1583 * Add a callback function that will be invoked when the nonblocking
1584 * pool is initialised.
1585 *
1586 * returns: 0 if callback is successfully added
1587 *          -EALREADY if pool is already initialised (callback not called)
1588 *          -ENOENT if module for callback is not alive
1589 */
1590int add_random_ready_callback(struct random_ready_callback *rdy)
1591{
1592        struct module *owner;
1593        unsigned long flags;
1594        int err = -EALREADY;
1595
1596        if (crng_ready())
1597                return err;
1598
1599        owner = rdy->owner;
1600        if (!try_module_get(owner))
1601                return -ENOENT;
1602
1603        spin_lock_irqsave(&random_ready_list_lock, flags);
1604        if (crng_ready())
1605                goto out;
1606
1607        owner = NULL;
1608
1609        list_add(&rdy->list, &random_ready_list);
1610        err = 0;
1611
1612out:
1613        spin_unlock_irqrestore(&random_ready_list_lock, flags);
1614
1615        module_put(owner);
1616
1617        return err;
1618}
1619EXPORT_SYMBOL(add_random_ready_callback);
1620
1621/*
1622 * Delete a previously registered readiness callback function.
1623 */
1624void del_random_ready_callback(struct random_ready_callback *rdy)
1625{
1626        unsigned long flags;
1627        struct module *owner = NULL;
1628
1629        spin_lock_irqsave(&random_ready_list_lock, flags);
1630        if (!list_empty(&rdy->list)) {
1631                list_del_init(&rdy->list);
1632                owner = rdy->owner;
1633        }
1634        spin_unlock_irqrestore(&random_ready_list_lock, flags);
1635
1636        module_put(owner);
1637}
1638EXPORT_SYMBOL(del_random_ready_callback);
1639
1640/*
1641 * This function will use the architecture-specific hardware random
1642 * number generator if it is available.  The arch-specific hw RNG will
1643 * almost certainly be faster than what we can do in software, but it
1644 * is impossible to verify that it is implemented securely (as
1645 * opposed, to, say, the AES encryption of a sequence number using a
1646 * key known by the NSA).  So it's useful if we need the speed, but
1647 * only if we're willing to trust the hardware manufacturer not to
1648 * have put in a back door.
1649 */
1650void get_random_bytes_arch(void *buf, int nbytes)
1651{
1652        char *p = buf;
1653
1654        trace_get_random_bytes_arch(nbytes, _RET_IP_);
1655        while (nbytes) {
1656                unsigned long v;
1657                int chunk = min(nbytes, (int)sizeof(unsigned long));
1658
1659                if (!arch_get_random_long(&v))
1660                        break;
1661               
1662                memcpy(p, &v, chunk);
1663                p += chunk;
1664                nbytes -= chunk;
1665        }
1666
1667        if (nbytes)
1668                get_random_bytes(p, nbytes);
1669}
1670EXPORT_SYMBOL(get_random_bytes_arch);
1671
1672
1673/*
1674 * init_std_data - initialize pool with system data
1675 *
1676 * @r: pool to initialize
1677 *
1678 * This function clears the pool's entropy count and mixes some system
1679 * data into the pool to prepare it for use. The pool is not cleared
1680 * as that can only decrease the entropy in the pool.
1681 */
1682static void init_std_data(struct entropy_store *r)
1683{
1684        int i;
1685        ktime_t now = ktime_get_real();
1686        unsigned long rv;
1687
1688        r->last_pulled = jiffies;
1689        mix_pool_bytes(r, &now, sizeof(now));
1690        for (i = r->poolinfo->poolbytes; i > 0; i -= sizeof(rv)) {
1691                if (!arch_get_random_seed_long(&rv) &&
1692                    !arch_get_random_long(&rv))
1693                        rv = random_get_entropy();
1694                mix_pool_bytes(r, &rv, sizeof(rv));
1695        }
1696        mix_pool_bytes(r, utsname(), sizeof(*(utsname())));
1697}
1698
1699/*
1700 * Note that setup_arch() may call add_device_randomness()
1701 * long before we get here. This allows seeding of the pools
1702 * with some platform dependent data very early in the boot
1703 * process. But it limits our options here. We must use
1704 * statically allocated structures that already have all
1705 * initializations complete at compile time. We should also
1706 * take care not to overwrite the precious per platform data
1707 * we were given.
1708 */
1709static int rand_initialize(void)
1710{
1711#ifdef CONFIG_NUMA
1712        int i;
1713        struct crng_state *crng;
1714        struct crng_state **pool;
1715#endif
1716
1717        init_std_data(&input_pool);
1718        init_std_data(&blocking_pool);
1719        crng_initialize(&primary_crng);
1720
1721#ifdef CONFIG_NUMA
1722        pool = kcalloc(nr_node_ids, sizeof(*pool), GFP_KERNEL|__GFP_NOFAIL);
1723        for_each_online_node(i) {
1724                crng = kmalloc_node(sizeof(struct crng_state),
1725                                    GFP_KERNEL | __GFP_NOFAIL, i);
1726                spin_lock_init(&crng->lock);
1727                crng_initialize(crng);
1728                pool[i] = crng;
1729        }
1730        mb();
1731        crng_node_pool = pool;
1732#endif
1733        return 0;
1734}
1735early_initcall(rand_initialize);
1736
1737#ifdef CONFIG_BLOCK
1738void rand_initialize_disk(struct gendisk *disk)
1739{
1740        struct timer_rand_state *state;
1741
1742        /*
1743         * If kzalloc returns null, we just won't use that entropy
1744         * source.
1745         */
1746        state = kzalloc(sizeof(struct timer_rand_state), GFP_KERNEL);
1747        if (state) {
1748                state->last_time = INITIAL_JIFFIES;
1749                disk->random = state;
1750        }
1751}
1752#endif
1753
1754static ssize_t
1755_random_read(int nonblock, char __user *buf, size_t nbytes)
1756{
1757        ssize_t n;
1758
1759        if (nbytes == 0)
1760                return 0;
1761
1762        nbytes = min_t(size_t, nbytes, SEC_XFER_SIZE);
1763        while (1) {
1764                n = extract_entropy_user(&blocking_pool, buf, nbytes);
1765                if (n < 0)
1766                        return n;
1767                trace_random_read(n*8, (nbytes-n)*8,
1768                                  ENTROPY_BITS(&blocking_pool),
1769                                  ENTROPY_BITS(&input_pool));
1770                if (n > 0)
1771                        return n;
1772
1773                /* Pool is (near) empty.  Maybe wait and retry. */
1774                if (nonblock)
1775                        return -EAGAIN;
1776
1777                wait_event_interruptible(random_read_wait,
1778                        ENTROPY_BITS(&input_pool) >=
1779                        random_read_wakeup_bits);
1780                if (signal_pending(current))
1781                        return -ERESTARTSYS;
1782        }
1783}
1784
1785static ssize_t
1786random_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
1787{
1788        return _random_read(file->f_flags & O_NONBLOCK, buf, nbytes);
1789}
1790
1791static ssize_t
1792urandom_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
1793{
1794        unsigned long flags;
1795        static int maxwarn = 10;
1796        int ret;
1797
1798        if (!crng_ready() && maxwarn > 0) {
1799                maxwarn--;
1800                printk(KERN_NOTICE "random: %s: uninitialized urandom read "
1801                       "(%zd bytes read)\n",
1802                       current->comm, nbytes);
1803                spin_lock_irqsave(&primary_crng.lock, flags);
1804                crng_init_cnt = 0;
1805                spin_unlock_irqrestore(&primary_crng.lock, flags);
1806        }
1807        nbytes = min_t(size_t, nbytes, INT_MAX >> (ENTROPY_SHIFT + 3));
1808        ret = extract_crng_user(buf, nbytes);
1809        trace_urandom_read(8 * nbytes, 0, ENTROPY_BITS(&input_pool));
1810        return ret;
1811}
1812
1813static unsigned int
1814random_poll(struct file *file, poll_table * wait)
1815{
1816        unsigned int mask;
1817
1818        poll_wait(file, &random_read_wait, wait);
1819        poll_wait(file, &random_write_wait, wait);
1820        mask = 0;
1821        if (ENTROPY_BITS(&input_pool) >= random_read_wakeup_bits)
1822                mask |= POLLIN | POLLRDNORM;
1823        if (ENTROPY_BITS(&input_pool) < random_write_wakeup_bits)
1824                mask |= POLLOUT | POLLWRNORM;
1825        return mask;
1826}
1827
1828static int
1829write_pool(struct entropy_store *r, const char __user *buffer, size_t count)
1830{
1831        size_t bytes;
1832        __u32 buf[16];
1833        const char __user *p = buffer;
1834
1835        while (count > 0) {
1836                bytes = min(count, sizeof(buf));
1837                if (copy_from_user(&buf, p, bytes))
1838                        return -EFAULT;
1839
1840                count -= bytes;
1841                p += bytes;
1842
1843                mix_pool_bytes(r, buf, bytes);
1844                cond_resched();
1845        }
1846
1847        return 0;
1848}
1849
1850static ssize_t random_write(struct file *file, const char __user *buffer,
1851                            size_t count, loff_t *ppos)
1852{
1853        size_t ret;
1854
1855        ret = write_pool(&input_pool, buffer, count);
1856        if (ret)
1857                return ret;
1858
1859        return (ssize_t)count;
1860}
1861
1862static long random_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
1863{
1864        int size, ent_count;
1865        int __user *p = (int __user *)arg;
1866        int retval;
1867
1868        switch (cmd) {
1869        case RNDGETENTCNT:
1870                /* inherently racy, no point locking */
1871                ent_count = ENTROPY_BITS(&input_pool);
1872                if (put_user(ent_count, p))
1873                        return -EFAULT;
1874                return 0;
1875        case RNDADDTOENTCNT:
1876                if (!capable(CAP_SYS_ADMIN))
1877                        return -EPERM;
1878                if (get_user(ent_count, p))
1879                        return -EFAULT;
1880                return credit_entropy_bits_safe(&input_pool, ent_count);
1881        case RNDADDENTROPY:
1882                if (!capable(CAP_SYS_ADMIN))
1883                        return -EPERM;
1884                if (get_user(ent_count, p++))
1885                        return -EFAULT;
1886                if (ent_count < 0)
1887                        return -EINVAL;
1888                if (get_user(size, p++))
1889                        return -EFAULT;
1890                retval = write_pool(&input_pool, (const char __user *)p,
1891                                    size);
1892                if (retval < 0)
1893                        return retval;
1894                return credit_entropy_bits_safe(&input_pool, ent_count);
1895        case RNDZAPENTCNT:
1896        case RNDCLEARPOOL:
1897                /*
1898                 * Clear the entropy pool counters. We no longer clear
1899                 * the entropy pool, as that's silly.
1900                 */
1901                if (!capable(CAP_SYS_ADMIN))
1902                        return -EPERM;
1903                input_pool.entropy_count = 0;
1904                blocking_pool.entropy_count = 0;
1905                return 0;
1906        default:
1907                return -EINVAL;
1908        }
1909}
1910
1911static int random_fasync(int fd, struct file *filp, int on)
1912{
1913        return fasync_helper(fd, filp, on, &fasync);
1914}
1915
1916const struct file_operations random_fops = {
1917        .read  = random_read,
1918        .write = random_write,
1919        .poll  = random_poll,
1920        .unlocked_ioctl = random_ioctl,
1921        .fasync = random_fasync,
1922        .llseek = noop_llseek,
1923};
1924
1925const struct file_operations urandom_fops = {
1926        .read  = urandom_read,
1927        .write = random_write,
1928        .unlocked_ioctl = random_ioctl,
1929        .fasync = random_fasync,
1930        .llseek = noop_llseek,
1931};
1932
1933SYSCALL_DEFINE3(getrandom, char __user *, buf, size_t, count,
1934                unsigned int, flags)
1935{
1936        if (flags & ~(GRND_NONBLOCK|GRND_RANDOM))
1937                return -EINVAL;
1938
1939        if (count > INT_MAX)
1940                count = INT_MAX;
1941
1942        if (flags & GRND_RANDOM)
1943                return _random_read(flags & GRND_NONBLOCK, buf, count);
1944
1945        if (!crng_ready()) {
1946                if (flags & GRND_NONBLOCK)
1947                        return -EAGAIN;
1948                crng_wait_ready();
1949                if (signal_pending(current))
1950                        return -ERESTARTSYS;
1951        }
1952        return urandom_read(NULL, buf, count, NULL);
1953}
1954
1955/********************************************************************
1956 *
1957 * Sysctl interface
1958 *
1959 ********************************************************************/
1960
1961#ifdef CONFIG_SYSCTL
1962
1963#include <linux/sysctl.h>
1964
1965static int min_read_thresh = 8, min_write_thresh;
1966static int max_read_thresh = OUTPUT_POOL_WORDS * 32;
1967static int max_write_thresh = INPUT_POOL_WORDS * 32;
1968static char sysctl_bootid[16];
1969
1970/*
1971 * This function is used to return both the bootid UUID, and random
1972 * UUID.  The difference is in whether table->data is NULL; if it is,
1973 * then a new UUID is generated and returned to the user.
1974 *
1975 * If the user accesses this via the proc interface, the UUID will be
1976 * returned as an ASCII string in the standard UUID format; if via the
1977 * sysctl system call, as 16 bytes of binary data.
1978 */
1979static int proc_do_uuid(struct ctl_table *table, int write,
1980                        void __user *buffer, size_t *lenp, loff_t *ppos)
1981{
1982        struct ctl_table fake_table;
1983        unsigned char buf[64], tmp_uuid[16], *uuid;
1984
1985        uuid = table->data;
1986        if (!uuid) {
1987                uuid = tmp_uuid;
1988                generate_random_uuid(uuid);
1989        } else {
1990                static DEFINE_SPINLOCK(bootid_spinlock);
1991
1992                spin_lock(&bootid_spinlock);
1993                if (!uuid[8])
1994                        generate_random_uuid(uuid);
1995                spin_unlock(&bootid_spinlock);
1996        }
1997
1998        sprintf(buf, "%pU", uuid);
1999
2000        fake_table.data = buf;
2001        fake_table.maxlen = sizeof(buf);
2002
2003        return proc_dostring(&fake_table, write, buffer, lenp, ppos);
2004}
2005
2006/*
2007 * Return entropy available scaled to integral bits
2008 */
2009static int proc_do_entropy(struct ctl_table *table, int write,
2010                           void __user *buffer, size_t *lenp, loff_t *ppos)
2011{
2012        struct ctl_table fake_table;
2013        int entropy_count;
2014
2015        entropy_count = *(int *)table->data >> ENTROPY_SHIFT;
2016
2017        fake_table.data = &entropy_count;
2018        fake_table.maxlen = sizeof(entropy_count);
2019
2020        return proc_dointvec(&fake_table, write, buffer, lenp, ppos);
2021}
2022
2023static int sysctl_poolsize = INPUT_POOL_WORDS * 32;
2024extern struct ctl_table random_table[];
2025struct ctl_table random_table[] = {
2026        {
2027                .procname       = "poolsize",
2028                .data           = &sysctl_poolsize,
2029                .maxlen         = sizeof(int),
2030                .mode           = 0444,
2031                .proc_handler   = proc_dointvec,
2032        },
2033        {
2034                .procname       = "entropy_avail",
2035                .maxlen         = sizeof(int),
2036                .mode           = 0444,
2037                .proc_handler   = proc_do_entropy,
2038                .data           = &input_pool.entropy_count,
2039        },
2040        {
2041                .procname       = "read_wakeup_threshold",
2042                .data           = &random_read_wakeup_bits,
2043                .maxlen         = sizeof(int),
2044                .mode           = 0644,
2045                .proc_handler   = proc_dointvec_minmax,
2046                .extra1         = &min_read_thresh,
2047                .extra2         = &max_read_thresh,
2048        },
2049        {
2050                .procname       = "write_wakeup_threshold",
2051                .data           = &random_write_wakeup_bits,
2052                .maxlen         = sizeof(int),
2053                .mode           = 0644,
2054                .proc_handler   = proc_dointvec_minmax,
2055                .extra1         = &min_write_thresh,
2056                .extra2         = &max_write_thresh,
2057        },
2058        {
2059                .procname       = "urandom_min_reseed_secs",
2060                .data           = &random_min_urandom_seed,
2061                .maxlen         = sizeof(int),
2062                .mode           = 0644,
2063                .proc_handler   = proc_dointvec,
2064        },
2065        {
2066                .procname       = "boot_id",
2067                .data           = &sysctl_bootid,
2068                .maxlen         = 16,
2069                .mode           = 0444,
2070                .proc_handler   = proc_do_uuid,
2071        },
2072        {
2073                .procname       = "uuid",
2074                .maxlen         = 16,
2075                .mode           = 0444,
2076                .proc_handler   = proc_do_uuid,
2077        },
2078#ifdef ADD_INTERRUPT_BENCH
2079        {
2080                .procname       = "add_interrupt_avg_cycles",
2081                .data           = &avg_cycles,
2082                .maxlen         = sizeof(avg_cycles),
2083                .mode           = 0444,
2084                .proc_handler   = proc_doulongvec_minmax,
2085        },
2086        {
2087                .procname       = "add_interrupt_avg_deviation",
2088                .data           = &avg_deviation,
2089                .maxlen         = sizeof(avg_deviation),
2090                .mode           = 0444,
2091                .proc_handler   = proc_doulongvec_minmax,
2092        },
2093#endif
2094        { }
2095};
2096#endif  /* CONFIG_SYSCTL */
2097
2098struct batched_entropy {
2099        union {
2100                unsigned long entropy_long[CHACHA20_BLOCK_SIZE / sizeof(unsigned long)];
2101                unsigned int entropy_int[CHACHA20_BLOCK_SIZE / sizeof(unsigned int)];
2102        };
2103        unsigned int position;
2104};
2105
2106/*
2107 * Get a random word for internal kernel use only. The quality of the random
2108 * number is either as good as RDRAND or as good as /dev/urandom, with the
2109 * goal of being quite fast and not depleting entropy.
2110 */
2111static DEFINE_PER_CPU(struct batched_entropy, batched_entropy_long);
2112unsigned long get_random_long(void)
2113{
2114        unsigned long ret;
2115        struct batched_entropy *batch;
2116
2117        if (arch_get_random_long(&ret))
2118                return ret;
2119
2120        batch = &get_cpu_var(batched_entropy_long);
2121        if (batch->position % ARRAY_SIZE(batch->entropy_long) == 0) {
2122                extract_crng((u8 *)batch->entropy_long);
2123                batch->position = 0;
2124        }
2125        ret = batch->entropy_long[batch->position++];
2126        put_cpu_var(batched_entropy_long);
2127        return ret;
2128}
2129EXPORT_SYMBOL(get_random_long);
2130
2131#if BITS_PER_LONG == 32
2132unsigned int get_random_int(void)
2133{
2134        return get_random_long();
2135}
2136#else
2137static DEFINE_PER_CPU(struct batched_entropy, batched_entropy_int);
2138unsigned int get_random_int(void)
2139{
2140        unsigned int ret;
2141        struct batched_entropy *batch;
2142
2143        if (arch_get_random_int(&ret))
2144                return ret;
2145
2146        batch = &get_cpu_var(batched_entropy_int);
2147        if (batch->position % ARRAY_SIZE(batch->entropy_int) == 0) {
2148                extract_crng((u8 *)batch->entropy_int);
2149                batch->position = 0;
2150        }
2151        ret = batch->entropy_int[batch->position++];
2152        put_cpu_var(batched_entropy_int);
2153        return ret;
2154}
2155#endif
2156EXPORT_SYMBOL(get_random_int);
2157
2158/**
2159 * randomize_page - Generate a random, page aligned address
2160 * @start:      The smallest acceptable address the caller will take.
2161 * @range:      The size of the area, starting at @start, within which the
2162 *              random address must fall.
2163 *
2164 * If @start + @range would overflow, @range is capped.
2165 *
2166 * NOTE: Historical use of randomize_range, which this replaces, presumed that
2167 * @start was already page aligned.  We now align it regardless.
2168 *
2169 * Return: A page aligned address within [start, start + range).  On error,
2170 * @start is returned.
2171 */
2172unsigned long
2173randomize_page(unsigned long start, unsigned long range)
2174{
2175        if (!PAGE_ALIGNED(start)) {
2176                range -= PAGE_ALIGN(start) - start;
2177                start = PAGE_ALIGN(start);
2178        }
2179
2180        if (start > ULONG_MAX - range)
2181                range = ULONG_MAX - start;
2182
2183        range >>= PAGE_SHIFT;
2184
2185        if (range == 0)
2186                return start;
2187
2188        return start + (get_random_long() % range << PAGE_SHIFT);
2189}
2190
2191/* Interface for in-kernel drivers of true hardware RNGs.
2192 * Those devices may produce endless random bits and will be throttled
2193 * when our pool is full.
2194 */
2195void add_hwgenerator_randomness(const char *buffer, size_t count,
2196                                size_t entropy)
2197{
2198        struct entropy_store *poolp = &input_pool;
2199
2200        if (!crng_ready()) {
2201                crng_fast_load(buffer, count);
2202                return;
2203        }
2204
2205        /* Suspend writing if we're above the trickle threshold.
2206         * We'll be woken up again once below random_write_wakeup_thresh,
2207         * or when the calling thread is about to terminate.
2208         */
2209        wait_event_interruptible(random_write_wait, kthread_should_stop() ||
2210                        ENTROPY_BITS(&input_pool) <= random_write_wakeup_bits);
2211        mix_pool_bytes(poolp, buffer, count);
2212        credit_entropy_bits(poolp, entropy);
2213}
2214EXPORT_SYMBOL_GPL(add_hwgenerator_randomness);
Note: See TracBrowser for help on using the repository browser.