xref: /openbmc/linux/crypto/jitterentropy.c (revision 70d391a8)
1 /*
2  * Non-physical true random number generator based on timing jitter --
3  * Jitter RNG standalone code.
4  *
5  * Copyright Stephan Mueller <smueller@chronox.de>, 2015 - 2023
6  *
7  * Design
8  * ======
9  *
10  * See https://www.chronox.de/jent.html
11  *
12  * License
13  * =======
14  *
15  * Redistribution and use in source and binary forms, with or without
16  * modification, are permitted provided that the following conditions
17  * are met:
18  * 1. Redistributions of source code must retain the above copyright
19  *    notice, and the entire permission notice in its entirety,
20  *    including the disclaimer of warranties.
21  * 2. Redistributions in binary form must reproduce the above copyright
22  *    notice, this list of conditions and the following disclaimer in the
23  *    documentation and/or other materials provided with the distribution.
24  * 3. The name of the author may not be used to endorse or promote
25  *    products derived from this software without specific prior
26  *    written permission.
27  *
28  * ALTERNATIVELY, this product may be distributed under the terms of
29  * the GNU General Public License, in which case the provisions of the GPL2 are
30  * required INSTEAD OF the above restrictions.  (This clause is
31  * necessary due to a potential bad interaction between the GPL and
32  * the restrictions contained in a BSD-style copyright.)
33  *
34  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
35  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
36  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF
37  * WHICH ARE HEREBY DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE
38  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
39  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
40  * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
41  * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
42  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
43  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
44  * USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH
45  * DAMAGE.
46  */
47 
48 /*
49  * This Jitterentropy RNG is based on the jitterentropy library
50  * version 3.4.0 provided at https://www.chronox.de/jent.html
51  */
52 
53 #ifdef __OPTIMIZE__
54  #error "The CPU Jitter random number generator must not be compiled with optimizations. See documentation. Use the compiler switch -O0 for compiling jitterentropy.c."
55 #endif
56 
57 typedef	unsigned long long	__u64;
58 typedef	long long		__s64;
59 typedef	unsigned int		__u32;
60 typedef unsigned char		u8;
61 #define NULL    ((void *) 0)
62 
63 /* The entropy pool */
64 struct rand_data {
65 	/* SHA3-256 is used as conditioner */
66 #define DATA_SIZE_BITS 256
67 	/* all data values that are vital to maintain the security
68 	 * of the RNG are marked as SENSITIVE. A user must not
69 	 * access that information while the RNG executes its loops to
70 	 * calculate the next random value. */
71 	void *hash_state;		/* SENSITIVE hash state entropy pool */
72 	__u64 prev_time;		/* SENSITIVE Previous time stamp */
73 	__u64 last_delta;		/* SENSITIVE stuck test */
74 	__s64 last_delta2;		/* SENSITIVE stuck test */
75 	unsigned int osr;		/* Oversample rate */
76 #define JENT_MEMORY_BLOCKS 64
77 #define JENT_MEMORY_BLOCKSIZE 32
78 #define JENT_MEMORY_ACCESSLOOPS 128
79 #define JENT_MEMORY_SIZE (JENT_MEMORY_BLOCKS*JENT_MEMORY_BLOCKSIZE)
80 	unsigned char *mem;	/* Memory access location with size of
81 				 * memblocks * memblocksize */
82 	unsigned int memlocation; /* Pointer to byte in *mem */
83 	unsigned int memblocks;	/* Number of memory blocks in *mem */
84 	unsigned int memblocksize; /* Size of one memory block in bytes */
85 	unsigned int memaccessloops; /* Number of memory accesses per random
86 				      * bit generation */
87 
88 	/* Repetition Count Test */
89 	unsigned int rct_count;			/* Number of stuck values */
90 
91 	/* Intermittent health test failure threshold of 2^-30 */
92 #define JENT_RCT_CUTOFF		30	/* Taken from SP800-90B sec 4.4.1 */
93 #define JENT_APT_CUTOFF		325	/* Taken from SP800-90B sec 4.4.2 */
94 	/* Permanent health test failure threshold of 2^-60 */
95 #define JENT_RCT_CUTOFF_PERMANENT	60
96 #define JENT_APT_CUTOFF_PERMANENT	355
97 #define JENT_APT_WINDOW_SIZE	512	/* Data window size */
98 	/* LSB of time stamp to process */
99 #define JENT_APT_LSB		16
100 #define JENT_APT_WORD_MASK	(JENT_APT_LSB - 1)
101 	unsigned int apt_observations;	/* Number of collected observations */
102 	unsigned int apt_count;		/* APT counter */
103 	unsigned int apt_base;		/* APT base reference */
104 	unsigned int apt_base_set:1;	/* APT base reference set? */
105 };
106 
107 /* Flags that can be used to initialize the RNG */
108 #define JENT_DISABLE_MEMORY_ACCESS (1<<2) /* Disable memory access for more
109 					   * entropy, saves MEMORY_SIZE RAM for
110 					   * entropy collector */
111 
112 /* -- error codes for init function -- */
113 #define JENT_ENOTIME		1 /* Timer service not available */
114 #define JENT_ECOARSETIME	2 /* Timer too coarse for RNG */
115 #define JENT_ENOMONOTONIC	3 /* Timer is not monotonic increasing */
116 #define JENT_EVARVAR		5 /* Timer does not produce variations of
117 				   * variations (2nd derivation of time is
118 				   * zero). */
119 #define JENT_ESTUCK		8 /* Too many stuck results during init. */
120 #define JENT_EHEALTH		9 /* Health test failed during initialization */
121 #define JENT_ERCT		10 /* RCT failed during initialization */
122 
123 /*
124  * The output n bits can receive more than n bits of min entropy, of course,
125  * but the fixed output of the conditioning function can only asymptotically
126  * approach the output size bits of min entropy, not attain that bound. Random
127  * maps will tend to have output collisions, which reduces the creditable
128  * output entropy (that is what SP 800-90B Section 3.1.5.1.2 attempts to bound).
129  *
130  * The value "64" is justified in Appendix A.4 of the current 90C draft,
131  * and aligns with NIST's in "epsilon" definition in this document, which is
132  * that a string can be considered "full entropy" if you can bound the min
133  * entropy in each bit of output to at least 1-epsilon, where epsilon is
134  * required to be <= 2^(-32).
135  */
136 #define JENT_ENTROPY_SAFETY_FACTOR	64
137 
138 #include <linux/fips.h>
139 #include "jitterentropy.h"
140 
141 /***************************************************************************
142  * Adaptive Proportion Test
143  *
144  * This test complies with SP800-90B section 4.4.2.
145  ***************************************************************************/
146 
147 /*
148  * Reset the APT counter
149  *
150  * @ec [in] Reference to entropy collector
151  */
152 static void jent_apt_reset(struct rand_data *ec, unsigned int delta_masked)
153 {
154 	/* Reset APT counter */
155 	ec->apt_count = 0;
156 	ec->apt_base = delta_masked;
157 	ec->apt_observations = 0;
158 }
159 
160 /*
161  * Insert a new entropy event into APT
162  *
163  * @ec [in] Reference to entropy collector
164  * @delta_masked [in] Masked time delta to process
165  */
166 static void jent_apt_insert(struct rand_data *ec, unsigned int delta_masked)
167 {
168 	/* Initialize the base reference */
169 	if (!ec->apt_base_set) {
170 		ec->apt_base = delta_masked;
171 		ec->apt_base_set = 1;
172 		return;
173 	}
174 
175 	if (delta_masked == ec->apt_base)
176 		ec->apt_count++;
177 
178 	ec->apt_observations++;
179 
180 	if (ec->apt_observations >= JENT_APT_WINDOW_SIZE)
181 		jent_apt_reset(ec, delta_masked);
182 }
183 
184 /* APT health test failure detection */
185 static int jent_apt_permanent_failure(struct rand_data *ec)
186 {
187 	return (ec->apt_count >= JENT_APT_CUTOFF_PERMANENT) ? 1 : 0;
188 }
189 
190 static int jent_apt_failure(struct rand_data *ec)
191 {
192 	return (ec->apt_count >= JENT_APT_CUTOFF) ? 1 : 0;
193 }
194 
195 /***************************************************************************
196  * Stuck Test and its use as Repetition Count Test
197  *
198  * The Jitter RNG uses an enhanced version of the Repetition Count Test
199  * (RCT) specified in SP800-90B section 4.4.1. Instead of counting identical
200  * back-to-back values, the input to the RCT is the counting of the stuck
201  * values during the generation of one Jitter RNG output block.
202  *
203  * The RCT is applied with an alpha of 2^{-30} compliant to FIPS 140-2 IG 9.8.
204  *
205  * During the counting operation, the Jitter RNG always calculates the RCT
206  * cut-off value of C. If that value exceeds the allowed cut-off value,
207  * the Jitter RNG output block will be calculated completely but discarded at
208  * the end. The caller of the Jitter RNG is informed with an error code.
209  ***************************************************************************/
210 
211 /*
212  * Repetition Count Test as defined in SP800-90B section 4.4.1
213  *
214  * @ec [in] Reference to entropy collector
215  * @stuck [in] Indicator whether the value is stuck
216  */
217 static void jent_rct_insert(struct rand_data *ec, int stuck)
218 {
219 	if (stuck) {
220 		ec->rct_count++;
221 	} else {
222 		/* Reset RCT */
223 		ec->rct_count = 0;
224 	}
225 }
226 
227 static inline __u64 jent_delta(__u64 prev, __u64 next)
228 {
229 #define JENT_UINT64_MAX		(__u64)(~((__u64) 0))
230 	return (prev < next) ? (next - prev) :
231 			       (JENT_UINT64_MAX - prev + 1 + next);
232 }
233 
234 /*
235  * Stuck test by checking the:
236  * 	1st derivative of the jitter measurement (time delta)
237  * 	2nd derivative of the jitter measurement (delta of time deltas)
238  * 	3rd derivative of the jitter measurement (delta of delta of time deltas)
239  *
240  * All values must always be non-zero.
241  *
242  * @ec [in] Reference to entropy collector
243  * @current_delta [in] Jitter time delta
244  *
245  * @return
246  * 	0 jitter measurement not stuck (good bit)
247  * 	1 jitter measurement stuck (reject bit)
248  */
249 static int jent_stuck(struct rand_data *ec, __u64 current_delta)
250 {
251 	__u64 delta2 = jent_delta(ec->last_delta, current_delta);
252 	__u64 delta3 = jent_delta(ec->last_delta2, delta2);
253 
254 	ec->last_delta = current_delta;
255 	ec->last_delta2 = delta2;
256 
257 	/*
258 	 * Insert the result of the comparison of two back-to-back time
259 	 * deltas.
260 	 */
261 	jent_apt_insert(ec, current_delta);
262 
263 	if (!current_delta || !delta2 || !delta3) {
264 		/* RCT with a stuck bit */
265 		jent_rct_insert(ec, 1);
266 		return 1;
267 	}
268 
269 	/* RCT with a non-stuck bit */
270 	jent_rct_insert(ec, 0);
271 
272 	return 0;
273 }
274 
275 /* RCT health test failure detection */
276 static int jent_rct_permanent_failure(struct rand_data *ec)
277 {
278 	return (ec->rct_count >= JENT_RCT_CUTOFF_PERMANENT) ? 1 : 0;
279 }
280 
281 static int jent_rct_failure(struct rand_data *ec)
282 {
283 	return (ec->rct_count >= JENT_RCT_CUTOFF) ? 1 : 0;
284 }
285 
286 /* Report of health test failures */
287 static int jent_health_failure(struct rand_data *ec)
288 {
289 	return jent_rct_failure(ec) | jent_apt_failure(ec);
290 }
291 
292 static int jent_permanent_health_failure(struct rand_data *ec)
293 {
294 	return jent_rct_permanent_failure(ec) | jent_apt_permanent_failure(ec);
295 }
296 
297 /***************************************************************************
298  * Noise sources
299  ***************************************************************************/
300 
301 /*
302  * Update of the loop count used for the next round of
303  * an entropy collection.
304  *
305  * Input:
306  * @bits is the number of low bits of the timer to consider
307  * @min is the number of bits we shift the timer value to the right at
308  *	the end to make sure we have a guaranteed minimum value
309  *
310  * @return Newly calculated loop counter
311  */
312 static __u64 jent_loop_shuffle(unsigned int bits, unsigned int min)
313 {
314 	__u64 time = 0;
315 	__u64 shuffle = 0;
316 	unsigned int i = 0;
317 	unsigned int mask = (1<<bits) - 1;
318 
319 	jent_get_nstime(&time);
320 
321 	/*
322 	 * We fold the time value as much as possible to ensure that as many
323 	 * bits of the time stamp are included as possible.
324 	 */
325 	for (i = 0; ((DATA_SIZE_BITS + bits - 1) / bits) > i; i++) {
326 		shuffle ^= time & mask;
327 		time = time >> bits;
328 	}
329 
330 	/*
331 	 * We add a lower boundary value to ensure we have a minimum
332 	 * RNG loop count.
333 	 */
334 	return (shuffle + (1<<min));
335 }
336 
337 /*
338  * CPU Jitter noise source -- this is the noise source based on the CPU
339  *			      execution time jitter
340  *
341  * This function injects the individual bits of the time value into the
342  * entropy pool using a hash.
343  *
344  * ec [in] entropy collector
345  * time [in] time stamp to be injected
346  * stuck [in] Is the time stamp identified as stuck?
347  *
348  * Output:
349  * updated hash context in the entropy collector or error code
350  */
351 static int jent_condition_data(struct rand_data *ec, __u64 time, int stuck)
352 {
353 #define SHA3_HASH_LOOP (1<<3)
354 	struct {
355 		int rct_count;
356 		unsigned int apt_observations;
357 		unsigned int apt_count;
358 		unsigned int apt_base;
359 	} addtl = {
360 		ec->rct_count,
361 		ec->apt_observations,
362 		ec->apt_count,
363 		ec->apt_base
364 	};
365 
366 	return jent_hash_time(ec->hash_state, time, (u8 *)&addtl, sizeof(addtl),
367 			      SHA3_HASH_LOOP, stuck);
368 }
369 
370 /*
371  * Memory Access noise source -- this is a noise source based on variations in
372  *				 memory access times
373  *
374  * This function performs memory accesses which will add to the timing
375  * variations due to an unknown amount of CPU wait states that need to be
376  * added when accessing memory. The memory size should be larger than the L1
377  * caches as outlined in the documentation and the associated testing.
378  *
379  * The L1 cache has a very high bandwidth, albeit its access rate is  usually
380  * slower than accessing CPU registers. Therefore, L1 accesses only add minimal
381  * variations as the CPU has hardly to wait. Starting with L2, significant
382  * variations are added because L2 typically does not belong to the CPU any more
383  * and therefore a wider range of CPU wait states is necessary for accesses.
384  * L3 and real memory accesses have even a wider range of wait states. However,
385  * to reliably access either L3 or memory, the ec->mem memory must be quite
386  * large which is usually not desirable.
387  *
388  * @ec [in] Reference to the entropy collector with the memory access data -- if
389  *	    the reference to the memory block to be accessed is NULL, this noise
390  *	    source is disabled
391  * @loop_cnt [in] if a value not equal to 0 is set, use the given value
392  *		  number of loops to perform the LFSR
393  */
394 static void jent_memaccess(struct rand_data *ec, __u64 loop_cnt)
395 {
396 	unsigned int wrap = 0;
397 	__u64 i = 0;
398 #define MAX_ACC_LOOP_BIT 7
399 #define MIN_ACC_LOOP_BIT 0
400 	__u64 acc_loop_cnt =
401 		jent_loop_shuffle(MAX_ACC_LOOP_BIT, MIN_ACC_LOOP_BIT);
402 
403 	if (NULL == ec || NULL == ec->mem)
404 		return;
405 	wrap = ec->memblocksize * ec->memblocks;
406 
407 	/*
408 	 * testing purposes -- allow test app to set the counter, not
409 	 * needed during runtime
410 	 */
411 	if (loop_cnt)
412 		acc_loop_cnt = loop_cnt;
413 
414 	for (i = 0; i < (ec->memaccessloops + acc_loop_cnt); i++) {
415 		unsigned char *tmpval = ec->mem + ec->memlocation;
416 		/*
417 		 * memory access: just add 1 to one byte,
418 		 * wrap at 255 -- memory access implies read
419 		 * from and write to memory location
420 		 */
421 		*tmpval = (*tmpval + 1) & 0xff;
422 		/*
423 		 * Addition of memblocksize - 1 to pointer
424 		 * with wrap around logic to ensure that every
425 		 * memory location is hit evenly
426 		 */
427 		ec->memlocation = ec->memlocation + ec->memblocksize - 1;
428 		ec->memlocation = ec->memlocation % wrap;
429 	}
430 }
431 
432 /***************************************************************************
433  * Start of entropy processing logic
434  ***************************************************************************/
435 /*
436  * This is the heart of the entropy generation: calculate time deltas and
437  * use the CPU jitter in the time deltas. The jitter is injected into the
438  * entropy pool.
439  *
440  * WARNING: ensure that ->prev_time is primed before using the output
441  *	    of this function! This can be done by calling this function
442  *	    and not using its result.
443  *
444  * @ec [in] Reference to entropy collector
445  *
446  * @return result of stuck test
447  */
448 static int jent_measure_jitter(struct rand_data *ec)
449 {
450 	__u64 time = 0;
451 	__u64 current_delta = 0;
452 	int stuck;
453 
454 	/* Invoke one noise source before time measurement to add variations */
455 	jent_memaccess(ec, 0);
456 
457 	/*
458 	 * Get time stamp and calculate time delta to previous
459 	 * invocation to measure the timing variations
460 	 */
461 	jent_get_nstime(&time);
462 	current_delta = jent_delta(ec->prev_time, time);
463 	ec->prev_time = time;
464 
465 	/* Check whether we have a stuck measurement. */
466 	stuck = jent_stuck(ec, current_delta);
467 
468 	/* Now call the next noise sources which also injects the data */
469 	if (jent_condition_data(ec, current_delta, stuck))
470 		stuck = 1;
471 
472 	return stuck;
473 }
474 
475 /*
476  * Generator of one 64 bit random number
477  * Function fills rand_data->hash_state
478  *
479  * @ec [in] Reference to entropy collector
480  */
481 static void jent_gen_entropy(struct rand_data *ec)
482 {
483 	unsigned int k = 0, safety_factor = 0;
484 
485 	if (fips_enabled)
486 		safety_factor = JENT_ENTROPY_SAFETY_FACTOR;
487 
488 	/* priming of the ->prev_time value */
489 	jent_measure_jitter(ec);
490 
491 	while (!jent_health_failure(ec)) {
492 		/* If a stuck measurement is received, repeat measurement */
493 		if (jent_measure_jitter(ec))
494 			continue;
495 
496 		/*
497 		 * We multiply the loop value with ->osr to obtain the
498 		 * oversampling rate requested by the caller
499 		 */
500 		if (++k >= ((DATA_SIZE_BITS + safety_factor) * ec->osr))
501 			break;
502 	}
503 }
504 
505 /*
506  * Entry function: Obtain entropy for the caller.
507  *
508  * This function invokes the entropy gathering logic as often to generate
509  * as many bytes as requested by the caller. The entropy gathering logic
510  * creates 64 bit per invocation.
511  *
512  * This function truncates the last 64 bit entropy value output to the exact
513  * size specified by the caller.
514  *
515  * @ec [in] Reference to entropy collector
516  * @data [in] pointer to buffer for storing random data -- buffer must already
517  *	      exist
518  * @len [in] size of the buffer, specifying also the requested number of random
519  *	     in bytes
520  *
521  * @return 0 when request is fulfilled or an error
522  *
523  * The following error codes can occur:
524  *	-1	entropy_collector is NULL or the generation failed
525  *	-2	Intermittent health failure
526  *	-3	Permanent health failure
527  */
528 int jent_read_entropy(struct rand_data *ec, unsigned char *data,
529 		      unsigned int len)
530 {
531 	unsigned char *p = data;
532 
533 	if (!ec)
534 		return -1;
535 
536 	while (len > 0) {
537 		unsigned int tocopy;
538 
539 		jent_gen_entropy(ec);
540 
541 		if (jent_permanent_health_failure(ec)) {
542 			/*
543 			 * At this point, the Jitter RNG instance is considered
544 			 * as a failed instance. There is no rerun of the
545 			 * startup test any more, because the caller
546 			 * is assumed to not further use this instance.
547 			 */
548 			return -3;
549 		} else if (jent_health_failure(ec)) {
550 			/*
551 			 * Perform startup health tests and return permanent
552 			 * error if it fails.
553 			 */
554 			if (jent_entropy_init(ec->hash_state))
555 				return -3;
556 
557 			return -2;
558 		}
559 
560 		if ((DATA_SIZE_BITS / 8) < len)
561 			tocopy = (DATA_SIZE_BITS / 8);
562 		else
563 			tocopy = len;
564 		if (jent_read_random_block(ec->hash_state, p, tocopy))
565 			return -1;
566 
567 		len -= tocopy;
568 		p += tocopy;
569 	}
570 
571 	return 0;
572 }
573 
574 /***************************************************************************
575  * Initialization logic
576  ***************************************************************************/
577 
578 struct rand_data *jent_entropy_collector_alloc(unsigned int osr,
579 					       unsigned int flags,
580 					       void *hash_state)
581 {
582 	struct rand_data *entropy_collector;
583 
584 	entropy_collector = jent_zalloc(sizeof(struct rand_data));
585 	if (!entropy_collector)
586 		return NULL;
587 
588 	if (!(flags & JENT_DISABLE_MEMORY_ACCESS)) {
589 		/* Allocate memory for adding variations based on memory
590 		 * access
591 		 */
592 		entropy_collector->mem = jent_zalloc(JENT_MEMORY_SIZE);
593 		if (!entropy_collector->mem) {
594 			jent_zfree(entropy_collector);
595 			return NULL;
596 		}
597 		entropy_collector->memblocksize = JENT_MEMORY_BLOCKSIZE;
598 		entropy_collector->memblocks = JENT_MEMORY_BLOCKS;
599 		entropy_collector->memaccessloops = JENT_MEMORY_ACCESSLOOPS;
600 	}
601 
602 	/* verify and set the oversampling rate */
603 	if (osr == 0)
604 		osr = 1; /* minimum sampling rate is 1 */
605 	entropy_collector->osr = osr;
606 
607 	entropy_collector->hash_state = hash_state;
608 
609 	/* fill the data pad with non-zero values */
610 	jent_gen_entropy(entropy_collector);
611 
612 	return entropy_collector;
613 }
614 
615 void jent_entropy_collector_free(struct rand_data *entropy_collector)
616 {
617 	jent_zfree(entropy_collector->mem);
618 	entropy_collector->mem = NULL;
619 	jent_zfree(entropy_collector);
620 }
621 
622 int jent_entropy_init(void *hash_state)
623 {
624 	int i;
625 	__u64 delta_sum = 0;
626 	__u64 old_delta = 0;
627 	unsigned int nonstuck = 0;
628 	int time_backwards = 0;
629 	int count_mod = 0;
630 	int count_stuck = 0;
631 	struct rand_data ec = { 0 };
632 
633 	/* Required for RCT */
634 	ec.osr = 1;
635 	ec.hash_state = hash_state;
636 
637 	/* We could perform statistical tests here, but the problem is
638 	 * that we only have a few loop counts to do testing. These
639 	 * loop counts may show some slight skew and we produce
640 	 * false positives.
641 	 *
642 	 * Moreover, only old systems show potentially problematic
643 	 * jitter entropy that could potentially be caught here. But
644 	 * the RNG is intended for hardware that is available or widely
645 	 * used, but not old systems that are long out of favor. Thus,
646 	 * no statistical tests.
647 	 */
648 
649 	/*
650 	 * We could add a check for system capabilities such as clock_getres or
651 	 * check for CONFIG_X86_TSC, but it does not make much sense as the
652 	 * following sanity checks verify that we have a high-resolution
653 	 * timer.
654 	 */
655 	/*
656 	 * TESTLOOPCOUNT needs some loops to identify edge systems. 100 is
657 	 * definitely too little.
658 	 *
659 	 * SP800-90B requires at least 1024 initial test cycles.
660 	 */
661 #define TESTLOOPCOUNT 1024
662 #define CLEARCACHE 100
663 	for (i = 0; (TESTLOOPCOUNT + CLEARCACHE) > i; i++) {
664 		__u64 time = 0;
665 		__u64 time2 = 0;
666 		__u64 delta = 0;
667 		unsigned int lowdelta = 0;
668 		int stuck;
669 
670 		/* Invoke core entropy collection logic */
671 		jent_get_nstime(&time);
672 		ec.prev_time = time;
673 		jent_condition_data(&ec, time, 0);
674 		jent_get_nstime(&time2);
675 
676 		/* test whether timer works */
677 		if (!time || !time2)
678 			return JENT_ENOTIME;
679 		delta = jent_delta(time, time2);
680 		/*
681 		 * test whether timer is fine grained enough to provide
682 		 * delta even when called shortly after each other -- this
683 		 * implies that we also have a high resolution timer
684 		 */
685 		if (!delta)
686 			return JENT_ECOARSETIME;
687 
688 		stuck = jent_stuck(&ec, delta);
689 
690 		/*
691 		 * up to here we did not modify any variable that will be
692 		 * evaluated later, but we already performed some work. Thus we
693 		 * already have had an impact on the caches, branch prediction,
694 		 * etc. with the goal to clear it to get the worst case
695 		 * measurements.
696 		 */
697 		if (i < CLEARCACHE)
698 			continue;
699 
700 		if (stuck)
701 			count_stuck++;
702 		else {
703 			nonstuck++;
704 
705 			/*
706 			 * Ensure that the APT succeeded.
707 			 *
708 			 * With the check below that count_stuck must be less
709 			 * than 10% of the overall generated raw entropy values
710 			 * it is guaranteed that the APT is invoked at
711 			 * floor((TESTLOOPCOUNT * 0.9) / 64) == 14 times.
712 			 */
713 			if ((nonstuck % JENT_APT_WINDOW_SIZE) == 0) {
714 				jent_apt_reset(&ec,
715 					       delta & JENT_APT_WORD_MASK);
716 				if (jent_health_failure(&ec))
717 					return JENT_EHEALTH;
718 			}
719 		}
720 
721 		/* Validate RCT */
722 		if (jent_rct_failure(&ec))
723 			return JENT_ERCT;
724 
725 		/* test whether we have an increasing timer */
726 		if (!(time2 > time))
727 			time_backwards++;
728 
729 		/* use 32 bit value to ensure compilation on 32 bit arches */
730 		lowdelta = time2 - time;
731 		if (!(lowdelta % 100))
732 			count_mod++;
733 
734 		/*
735 		 * ensure that we have a varying delta timer which is necessary
736 		 * for the calculation of entropy -- perform this check
737 		 * only after the first loop is executed as we need to prime
738 		 * the old_data value
739 		 */
740 		if (delta > old_delta)
741 			delta_sum += (delta - old_delta);
742 		else
743 			delta_sum += (old_delta - delta);
744 		old_delta = delta;
745 	}
746 
747 	/*
748 	 * we allow up to three times the time running backwards.
749 	 * CLOCK_REALTIME is affected by adjtime and NTP operations. Thus,
750 	 * if such an operation just happens to interfere with our test, it
751 	 * should not fail. The value of 3 should cover the NTP case being
752 	 * performed during our test run.
753 	 */
754 	if (time_backwards > 3)
755 		return JENT_ENOMONOTONIC;
756 
757 	/*
758 	 * Variations of deltas of time must on average be larger
759 	 * than 1 to ensure the entropy estimation
760 	 * implied with 1 is preserved
761 	 */
762 	if ((delta_sum) <= 1)
763 		return JENT_EVARVAR;
764 
765 	/*
766 	 * Ensure that we have variations in the time stamp below 10 for at
767 	 * least 10% of all checks -- on some platforms, the counter increments
768 	 * in multiples of 100, but not always
769 	 */
770 	if ((TESTLOOPCOUNT/10 * 9) < count_mod)
771 		return JENT_ECOARSETIME;
772 
773 	/*
774 	 * If we have more than 90% stuck results, then this Jitter RNG is
775 	 * likely to not work well.
776 	 */
777 	if ((TESTLOOPCOUNT/10 * 9) < count_stuck)
778 		return JENT_ESTUCK;
779 
780 	return 0;
781 }
782