random.c 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724
  1. // SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause)
  2. /*
  3. * Copyright (C) 2017-2024 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
  4. * Copyright Matt Mackall <mpm@selenic.com>, 2003, 2004, 2005
  5. * Copyright Theodore Ts'o, 1994, 1995, 1996, 1997, 1998, 1999. All rights reserved.
  6. *
  7. * This driver produces cryptographically secure pseudorandom data. It is divided
  8. * into roughly six sections, each with a section header:
  9. *
  10. * - Initialization and readiness waiting.
  11. * - Fast key erasure RNG, the "crng".
  12. * - Entropy accumulation and extraction routines.
  13. * - Entropy collection routines.
  14. * - Userspace reader/writer interfaces.
  15. * - Sysctl interface.
  16. *
  17. * The high level overview is that there is one input pool, into which
  18. * various pieces of data are hashed. Prior to initialization, some of that
  19. * data is then "credited" as having a certain number of bits of entropy.
  20. * When enough bits of entropy are available, the hash is finalized and
  21. * handed as a key to a stream cipher that expands it indefinitely for
  22. * various consumers. This key is periodically refreshed as the various
  23. * entropy collectors, described below, add data to the input pool.
  24. */
  25. #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
  26. #include <linux/utsname.h>
  27. #include <linux/module.h>
  28. #include <linux/kernel.h>
  29. #include <linux/major.h>
  30. #include <linux/string.h>
  31. #include <linux/fcntl.h>
  32. #include <linux/slab.h>
  33. #include <linux/random.h>
  34. #include <linux/poll.h>
  35. #include <linux/init.h>
  36. #include <linux/fs.h>
  37. #include <linux/blkdev.h>
  38. #include <linux/interrupt.h>
  39. #include <linux/mm.h>
  40. #include <linux/nodemask.h>
  41. #include <linux/spinlock.h>
  42. #include <linux/kthread.h>
  43. #include <linux/percpu.h>
  44. #include <linux/ptrace.h>
  45. #include <linux/workqueue.h>
  46. #include <linux/irq.h>
  47. #include <linux/ratelimit.h>
  48. #include <linux/syscalls.h>
  49. #include <linux/completion.h>
  50. #include <linux/uuid.h>
  51. #include <linux/uaccess.h>
  52. #include <linux/suspend.h>
  53. #include <linux/siphash.h>
  54. #include <linux/sched/isolation.h>
  55. #include <crypto/chacha.h>
  56. #include <crypto/blake2s.h>
  57. #ifdef CONFIG_VDSO_GETRANDOM
  58. #include <vdso/getrandom.h>
  59. #include <vdso/datapage.h>
  60. #include <vdso/vsyscall.h>
  61. #endif
  62. #include <asm/archrandom.h>
  63. #include <asm/processor.h>
  64. #include <asm/irq.h>
  65. #include <asm/irq_regs.h>
  66. #include <asm/io.h>
  67. /*********************************************************************
  68. *
  69. * Initialization and readiness waiting.
  70. *
  71. * Much of the RNG infrastructure is devoted to various dependencies
  72. * being able to wait until the RNG has collected enough entropy and
  73. * is ready for safe consumption.
  74. *
  75. *********************************************************************/
  76. /*
  77. * crng_init is protected by base_crng->lock, and only increases
  78. * its value (from empty->early->ready).
  79. */
  80. static enum {
  81. CRNG_EMPTY = 0, /* Little to no entropy collected */
  82. CRNG_EARLY = 1, /* At least POOL_EARLY_BITS collected */
  83. CRNG_READY = 2 /* Fully initialized with POOL_READY_BITS collected */
  84. } crng_init __read_mostly = CRNG_EMPTY;
  85. static DEFINE_STATIC_KEY_FALSE(crng_is_ready);
  86. #ifdef CONFIG_ARCH_ARKMICRO
  87. #define crng_ready() (likely(crng_init > CRNG_EMPTY))
  88. #else
  89. #define crng_ready() (static_branch_likely(&crng_is_ready) || crng_init >= CRNG_READY)
  90. #endif
  91. /* Various types of waiters for crng_init->CRNG_READY transition. */
  92. static DECLARE_WAIT_QUEUE_HEAD(crng_init_wait);
  93. static struct fasync_struct *fasync;
  94. static ATOMIC_NOTIFIER_HEAD(random_ready_notifier);
  95. /* Control how we warn userspace. */
  96. static struct ratelimit_state urandom_warning =
  97. RATELIMIT_STATE_INIT_FLAGS("urandom_warning", HZ, 3, RATELIMIT_MSG_ON_RELEASE);
  98. static int ratelimit_disable __read_mostly =
  99. IS_ENABLED(CONFIG_WARN_ALL_UNSEEDED_RANDOM);
  100. module_param_named(ratelimit_disable, ratelimit_disable, int, 0644);
  101. MODULE_PARM_DESC(ratelimit_disable, "Disable random ratelimit suppression");
  102. /*
  103. * Returns whether or not the input pool has been seeded and thus guaranteed
  104. * to supply cryptographically secure random numbers. This applies to: the
  105. * /dev/urandom device, the get_random_bytes function, and the get_random_{u8,
  106. * u16,u32,u64,long} family of functions.
  107. *
  108. * Returns: true if the input pool has been seeded.
  109. * false if the input pool has not been seeded.
  110. */
  111. bool rng_is_initialized(void)
  112. {
  113. return crng_ready();
  114. }
  115. EXPORT_SYMBOL(rng_is_initialized);
  116. static void __cold crng_set_ready(struct work_struct *work)
  117. {
  118. static_branch_enable(&crng_is_ready);
  119. }
  120. /* Used by wait_for_random_bytes(), and considered an entropy collector, below. */
  121. static void try_to_generate_entropy(void);
  122. /*
  123. * Wait for the input pool to be seeded and thus guaranteed to supply
  124. * cryptographically secure random numbers. This applies to: the /dev/urandom
  125. * device, the get_random_bytes function, and the get_random_{u8,u16,u32,u64,
  126. * long} family of functions. Using any of these functions without first
  127. * calling this function forfeits the guarantee of security.
  128. *
  129. * Returns: 0 if the input pool has been seeded.
  130. * -ERESTARTSYS if the function was interrupted by a signal.
  131. */
  132. int wait_for_random_bytes(void)
  133. {
  134. while (!crng_ready()) {
  135. int ret;
  136. try_to_generate_entropy();
  137. ret = wait_event_interruptible_timeout(crng_init_wait, crng_ready(), HZ);
  138. if (ret)
  139. return ret > 0 ? 0 : ret;
  140. }
  141. return 0;
  142. }
  143. EXPORT_SYMBOL(wait_for_random_bytes);
  144. /*
  145. * Add a callback function that will be invoked when the crng is initialised,
  146. * or immediately if it already has been. Only use this is you are absolutely
  147. * sure it is required. Most users should instead be able to test
  148. * `rng_is_initialized()` on demand, or make use of `get_random_bytes_wait()`.
  149. */
  150. int __cold execute_with_initialized_rng(struct notifier_block *nb)
  151. {
  152. unsigned long flags;
  153. int ret = 0;
  154. spin_lock_irqsave(&random_ready_notifier.lock, flags);
  155. if (crng_ready())
  156. nb->notifier_call(nb, 0, NULL);
  157. else
  158. ret = raw_notifier_chain_register((struct raw_notifier_head *)&random_ready_notifier.head, nb);
  159. spin_unlock_irqrestore(&random_ready_notifier.lock, flags);
  160. return ret;
  161. }
  162. #define warn_unseeded_randomness() \
  163. if (IS_ENABLED(CONFIG_WARN_ALL_UNSEEDED_RANDOM) && !crng_ready()) \
  164. printk_deferred(KERN_NOTICE "random: %s called from %pS with crng_init=%d\n", \
  165. __func__, (void *)_RET_IP_, crng_init)
  166. /*********************************************************************
  167. *
  168. * Fast key erasure RNG, the "crng".
  169. *
  170. * These functions expand entropy from the entropy extractor into
  171. * long streams for external consumption using the "fast key erasure"
  172. * RNG described at <https://blog.cr.yp.to/20170723-random.html>.
  173. *
  174. * There are a few exported interfaces for use by other drivers:
  175. *
  176. * void get_random_bytes(void *buf, size_t len)
  177. * u8 get_random_u8()
  178. * u16 get_random_u16()
  179. * u32 get_random_u32()
  180. * u32 get_random_u32_below(u32 ceil)
  181. * u32 get_random_u32_above(u32 floor)
  182. * u32 get_random_u32_inclusive(u32 floor, u32 ceil)
  183. * u64 get_random_u64()
  184. * unsigned long get_random_long()
  185. *
  186. * These interfaces will return the requested number of random bytes
  187. * into the given buffer or as a return value. This is equivalent to
  188. * a read from /dev/urandom. The u8, u16, u32, u64, long family of
  189. * functions may be higher performance for one-off random integers,
  190. * because they do a bit of buffering and do not invoke reseeding
  191. * until the buffer is emptied.
  192. *
  193. *********************************************************************/
  194. enum {
  195. CRNG_RESEED_START_INTERVAL = HZ,
  196. CRNG_RESEED_INTERVAL = 60 * HZ
  197. };
  198. static struct {
  199. u8 key[CHACHA_KEY_SIZE] __aligned(__alignof__(long));
  200. unsigned long generation;
  201. spinlock_t lock;
  202. } base_crng = {
  203. .lock = __SPIN_LOCK_UNLOCKED(base_crng.lock)
  204. };
  205. struct crng {
  206. u8 key[CHACHA_KEY_SIZE];
  207. unsigned long generation;
  208. local_lock_t lock;
  209. };
  210. static DEFINE_PER_CPU(struct crng, crngs) = {
  211. .generation = ULONG_MAX,
  212. .lock = INIT_LOCAL_LOCK(crngs.lock),
  213. };
  214. /*
  215. * Return the interval until the next reseeding, which is normally
  216. * CRNG_RESEED_INTERVAL, but during early boot, it is at an interval
  217. * proportional to the uptime.
  218. */
  219. static unsigned int crng_reseed_interval(void)
  220. {
  221. static bool early_boot = true;
  222. if (unlikely(READ_ONCE(early_boot))) {
  223. time64_t uptime = ktime_get_seconds();
  224. if (uptime >= CRNG_RESEED_INTERVAL / HZ * 2)
  225. WRITE_ONCE(early_boot, false);
  226. else
  227. return max_t(unsigned int, CRNG_RESEED_START_INTERVAL,
  228. (unsigned int)uptime / 2 * HZ);
  229. }
  230. return CRNG_RESEED_INTERVAL;
  231. }
  232. /* Used by crng_reseed() and crng_make_state() to extract a new seed from the input pool. */
  233. static void extract_entropy(void *buf, size_t len);
  234. /* This extracts a new crng key from the input pool. */
  235. static void crng_reseed(struct work_struct *work)
  236. {
  237. static DECLARE_DELAYED_WORK(next_reseed, crng_reseed);
  238. unsigned long flags;
  239. unsigned long next_gen;
  240. u8 key[CHACHA_KEY_SIZE];
  241. /* Immediately schedule the next reseeding, so that it fires sooner rather than later. */
  242. if (likely(system_unbound_wq))
  243. queue_delayed_work(system_unbound_wq, &next_reseed, crng_reseed_interval());
  244. extract_entropy(key, sizeof(key));
  245. /*
  246. * We copy the new key into the base_crng, overwriting the old one,
  247. * and update the generation counter. We avoid hitting ULONG_MAX,
  248. * because the per-cpu crngs are initialized to ULONG_MAX, so this
  249. * forces new CPUs that come online to always initialize.
  250. */
  251. spin_lock_irqsave(&base_crng.lock, flags);
  252. memcpy(base_crng.key, key, sizeof(base_crng.key));
  253. next_gen = base_crng.generation + 1;
  254. if (next_gen == ULONG_MAX)
  255. ++next_gen;
  256. WRITE_ONCE(base_crng.generation, next_gen);
  257. #ifdef CONFIG_VDSO_GETRANDOM
  258. /* base_crng.generation's invalid value is ULONG_MAX, while
  259. * _vdso_rng_data.generation's invalid value is 0, so add one to the
  260. * former to arrive at the latter. Use smp_store_release so that this
  261. * is ordered with the write above to base_crng.generation. Pairs with
  262. * the smp_rmb() before the syscall in the vDSO code.
  263. *
  264. * Cast to unsigned long for 32-bit architectures, since atomic 64-bit
  265. * operations are not supported on those architectures. This is safe
  266. * because base_crng.generation is a 32-bit value. On big-endian
  267. * architectures it will be stored in the upper 32 bits, but that's okay
  268. * because the vDSO side only checks whether the value changed, without
  269. * actually using or interpreting the value.
  270. */
  271. smp_store_release((unsigned long *)&__arch_get_k_vdso_rng_data()->generation, next_gen + 1);
  272. #endif
  273. if (!static_branch_likely(&crng_is_ready))
  274. crng_init = CRNG_READY;
  275. spin_unlock_irqrestore(&base_crng.lock, flags);
  276. memzero_explicit(key, sizeof(key));
  277. }
  278. /*
  279. * This generates a ChaCha block using the provided key, and then
  280. * immediately overwrites that key with half the block. It returns
  281. * the resultant ChaCha state to the user, along with the second
  282. * half of the block containing 32 bytes of random data that may
  283. * be used; random_data_len may not be greater than 32.
  284. *
  285. * The returned ChaCha state contains within it a copy of the old
  286. * key value, at index 4, so the state should always be zeroed out
  287. * immediately after using in order to maintain forward secrecy.
  288. * If the state cannot be erased in a timely manner, then it is
  289. * safer to set the random_data parameter to &chacha_state[4] so
  290. * that this function overwrites it before returning.
  291. */
  292. static void crng_fast_key_erasure(u8 key[CHACHA_KEY_SIZE],
  293. u32 chacha_state[CHACHA_STATE_WORDS],
  294. u8 *random_data, size_t random_data_len)
  295. {
  296. u8 first_block[CHACHA_BLOCK_SIZE];
  297. BUG_ON(random_data_len > 32);
  298. chacha_init_consts(chacha_state);
  299. memcpy(&chacha_state[4], key, CHACHA_KEY_SIZE);
  300. memset(&chacha_state[12], 0, sizeof(u32) * 4);
  301. chacha20_block(chacha_state, first_block);
  302. memcpy(key, first_block, CHACHA_KEY_SIZE);
  303. memcpy(random_data, first_block + CHACHA_KEY_SIZE, random_data_len);
  304. memzero_explicit(first_block, sizeof(first_block));
  305. }
  306. /*
  307. * This function returns a ChaCha state that you may use for generating
  308. * random data. It also returns up to 32 bytes on its own of random data
  309. * that may be used; random_data_len may not be greater than 32.
  310. */
  311. static void crng_make_state(u32 chacha_state[CHACHA_STATE_WORDS],
  312. u8 *random_data, size_t random_data_len)
  313. {
  314. unsigned long flags;
  315. struct crng *crng;
  316. BUG_ON(random_data_len > 32);
  317. /*
  318. * For the fast path, we check whether we're ready, unlocked first, and
  319. * then re-check once locked later. In the case where we're really not
  320. * ready, we do fast key erasure with the base_crng directly, extracting
  321. * when crng_init is CRNG_EMPTY.
  322. */
  323. if (!crng_ready()) {
  324. bool ready;
  325. spin_lock_irqsave(&base_crng.lock, flags);
  326. ready = crng_ready();
  327. if (!ready) {
  328. if (crng_init == CRNG_EMPTY)
  329. extract_entropy(base_crng.key, sizeof(base_crng.key));
  330. crng_fast_key_erasure(base_crng.key, chacha_state,
  331. random_data, random_data_len);
  332. }
  333. spin_unlock_irqrestore(&base_crng.lock, flags);
  334. if (!ready)
  335. return;
  336. }
  337. local_lock_irqsave(&crngs.lock, flags);
  338. crng = raw_cpu_ptr(&crngs);
  339. /*
  340. * If our per-cpu crng is older than the base_crng, then it means
  341. * somebody reseeded the base_crng. In that case, we do fast key
  342. * erasure on the base_crng, and use its output as the new key
  343. * for our per-cpu crng. This brings us up to date with base_crng.
  344. */
  345. if (unlikely(crng->generation != READ_ONCE(base_crng.generation))) {
  346. spin_lock(&base_crng.lock);
  347. crng_fast_key_erasure(base_crng.key, chacha_state,
  348. crng->key, sizeof(crng->key));
  349. crng->generation = base_crng.generation;
  350. spin_unlock(&base_crng.lock);
  351. }
  352. /*
  353. * Finally, when we've made it this far, our per-cpu crng has an up
  354. * to date key, and we can do fast key erasure with it to produce
  355. * some random data and a ChaCha state for the caller. All other
  356. * branches of this function are "unlikely", so most of the time we
  357. * should wind up here immediately.
  358. */
  359. crng_fast_key_erasure(crng->key, chacha_state, random_data, random_data_len);
  360. local_unlock_irqrestore(&crngs.lock, flags);
  361. }
  362. static void _get_random_bytes(void *buf, size_t len)
  363. {
  364. u32 chacha_state[CHACHA_STATE_WORDS];
  365. u8 tmp[CHACHA_BLOCK_SIZE];
  366. size_t first_block_len;
  367. if (!len)
  368. return;
  369. first_block_len = min_t(size_t, 32, len);
  370. crng_make_state(chacha_state, buf, first_block_len);
  371. len -= first_block_len;
  372. buf += first_block_len;
  373. while (len) {
  374. if (len < CHACHA_BLOCK_SIZE) {
  375. chacha20_block(chacha_state, tmp);
  376. memcpy(buf, tmp, len);
  377. memzero_explicit(tmp, sizeof(tmp));
  378. break;
  379. }
  380. chacha20_block(chacha_state, buf);
  381. if (unlikely(chacha_state[12] == 0))
  382. ++chacha_state[13];
  383. len -= CHACHA_BLOCK_SIZE;
  384. buf += CHACHA_BLOCK_SIZE;
  385. }
  386. memzero_explicit(chacha_state, sizeof(chacha_state));
  387. }
  388. /*
  389. * This returns random bytes in arbitrary quantities. The quality of the
  390. * random bytes is good as /dev/urandom. In order to ensure that the
  391. * randomness provided by this function is okay, the function
  392. * wait_for_random_bytes() should be called and return 0 at least once
  393. * at any point prior.
  394. */
  395. void get_random_bytes(void *buf, size_t len)
  396. {
  397. warn_unseeded_randomness();
  398. _get_random_bytes(buf, len);
  399. }
  400. EXPORT_SYMBOL(get_random_bytes);
  401. static ssize_t get_random_bytes_user(struct iov_iter *iter)
  402. {
  403. u32 chacha_state[CHACHA_STATE_WORDS];
  404. u8 block[CHACHA_BLOCK_SIZE];
  405. size_t ret = 0, copied;
  406. if (unlikely(!iov_iter_count(iter)))
  407. return 0;
  408. /*
  409. * Immediately overwrite the ChaCha key at index 4 with random
  410. * bytes, in case userspace causes copy_to_iter() below to sleep
  411. * forever, so that we still retain forward secrecy in that case.
  412. */
  413. crng_make_state(chacha_state, (u8 *)&chacha_state[4], CHACHA_KEY_SIZE);
  414. /*
  415. * However, if we're doing a read of len <= 32, we don't need to
  416. * use chacha_state after, so we can simply return those bytes to
  417. * the user directly.
  418. */
  419. if (iov_iter_count(iter) <= CHACHA_KEY_SIZE) {
  420. ret = copy_to_iter(&chacha_state[4], CHACHA_KEY_SIZE, iter);
  421. goto out_zero_chacha;
  422. }
  423. for (;;) {
  424. chacha20_block(chacha_state, block);
  425. if (unlikely(chacha_state[12] == 0))
  426. ++chacha_state[13];
  427. copied = copy_to_iter(block, sizeof(block), iter);
  428. ret += copied;
  429. if (!iov_iter_count(iter) || copied != sizeof(block))
  430. break;
  431. BUILD_BUG_ON(PAGE_SIZE % sizeof(block) != 0);
  432. if (ret % PAGE_SIZE == 0) {
  433. if (signal_pending(current))
  434. break;
  435. cond_resched();
  436. }
  437. }
  438. memzero_explicit(block, sizeof(block));
  439. out_zero_chacha:
  440. memzero_explicit(chacha_state, sizeof(chacha_state));
  441. return ret ? ret : -EFAULT;
  442. }
  443. /*
  444. * Batched entropy returns random integers. The quality of the random
  445. * number is good as /dev/urandom. In order to ensure that the randomness
  446. * provided by this function is okay, the function wait_for_random_bytes()
  447. * should be called and return 0 at least once at any point prior.
  448. */
  449. #define DEFINE_BATCHED_ENTROPY(type) \
  450. struct batch_ ##type { \
  451. /* \
  452. * We make this 1.5x a ChaCha block, so that we get the \
  453. * remaining 32 bytes from fast key erasure, plus one full \
  454. * block from the detached ChaCha state. We can increase \
  455. * the size of this later if needed so long as we keep the \
  456. * formula of (integer_blocks + 0.5) * CHACHA_BLOCK_SIZE. \
  457. */ \
  458. type entropy[CHACHA_BLOCK_SIZE * 3 / (2 * sizeof(type))]; \
  459. local_lock_t lock; \
  460. unsigned long generation; \
  461. unsigned int position; \
  462. }; \
  463. \
  464. static DEFINE_PER_CPU(struct batch_ ##type, batched_entropy_ ##type) = { \
  465. .lock = INIT_LOCAL_LOCK(batched_entropy_ ##type.lock), \
  466. .position = UINT_MAX \
  467. }; \
  468. \
  469. type get_random_ ##type(void) \
  470. { \
  471. type ret; \
  472. unsigned long flags; \
  473. struct batch_ ##type *batch; \
  474. unsigned long next_gen; \
  475. \
  476. warn_unseeded_randomness(); \
  477. \
  478. if (!crng_ready()) { \
  479. _get_random_bytes(&ret, sizeof(ret)); \
  480. return ret; \
  481. } \
  482. \
  483. local_lock_irqsave(&batched_entropy_ ##type.lock, flags); \
  484. batch = raw_cpu_ptr(&batched_entropy_##type); \
  485. \
  486. next_gen = READ_ONCE(base_crng.generation); \
  487. if (batch->position >= ARRAY_SIZE(batch->entropy) || \
  488. next_gen != batch->generation) { \
  489. _get_random_bytes(batch->entropy, sizeof(batch->entropy)); \
  490. batch->position = 0; \
  491. batch->generation = next_gen; \
  492. } \
  493. \
  494. ret = batch->entropy[batch->position]; \
  495. batch->entropy[batch->position] = 0; \
  496. ++batch->position; \
  497. local_unlock_irqrestore(&batched_entropy_ ##type.lock, flags); \
  498. return ret; \
  499. } \
  500. EXPORT_SYMBOL(get_random_ ##type);
  501. DEFINE_BATCHED_ENTROPY(u8)
  502. DEFINE_BATCHED_ENTROPY(u16)
  503. DEFINE_BATCHED_ENTROPY(u32)
  504. DEFINE_BATCHED_ENTROPY(u64)
  505. u32 __get_random_u32_below(u32 ceil)
  506. {
  507. /*
  508. * This is the slow path for variable ceil. It is still fast, most of
  509. * the time, by doing traditional reciprocal multiplication and
  510. * opportunistically comparing the lower half to ceil itself, before
  511. * falling back to computing a larger bound, and then rejecting samples
  512. * whose lower half would indicate a range indivisible by ceil. The use
  513. * of `-ceil % ceil` is analogous to `2^32 % ceil`, but is computable
  514. * in 32-bits.
  515. */
  516. u32 rand = get_random_u32();
  517. u64 mult;
  518. /*
  519. * This function is technically undefined for ceil == 0, and in fact
  520. * for the non-underscored constant version in the header, we build bug
  521. * on that. But for the non-constant case, it's convenient to have that
  522. * evaluate to being a straight call to get_random_u32(), so that
  523. * get_random_u32_inclusive() can work over its whole range without
  524. * undefined behavior.
  525. */
  526. if (unlikely(!ceil))
  527. return rand;
  528. mult = (u64)ceil * rand;
  529. if (unlikely((u32)mult < ceil)) {
  530. u32 bound = -ceil % ceil;
  531. while (unlikely((u32)mult < bound))
  532. mult = (u64)ceil * get_random_u32();
  533. }
  534. return mult >> 32;
  535. }
  536. EXPORT_SYMBOL(__get_random_u32_below);
  537. #ifdef CONFIG_SMP
  538. /*
  539. * This function is called when the CPU is coming up, with entry
  540. * CPUHP_RANDOM_PREPARE, which comes before CPUHP_WORKQUEUE_PREP.
  541. */
  542. int __cold random_prepare_cpu(unsigned int cpu)
  543. {
  544. /*
  545. * When the cpu comes back online, immediately invalidate both
  546. * the per-cpu crng and all batches, so that we serve fresh
  547. * randomness.
  548. */
  549. per_cpu_ptr(&crngs, cpu)->generation = ULONG_MAX;
  550. per_cpu_ptr(&batched_entropy_u8, cpu)->position = UINT_MAX;
  551. per_cpu_ptr(&batched_entropy_u16, cpu)->position = UINT_MAX;
  552. per_cpu_ptr(&batched_entropy_u32, cpu)->position = UINT_MAX;
  553. per_cpu_ptr(&batched_entropy_u64, cpu)->position = UINT_MAX;
  554. return 0;
  555. }
  556. #endif
  557. /**********************************************************************
  558. *
  559. * Entropy accumulation and extraction routines.
  560. *
  561. * Callers may add entropy via:
  562. *
  563. * static void mix_pool_bytes(const void *buf, size_t len)
  564. *
  565. * After which, if added entropy should be credited:
  566. *
  567. * static void credit_init_bits(size_t bits)
  568. *
  569. * Finally, extract entropy via:
  570. *
  571. * static void extract_entropy(void *buf, size_t len)
  572. *
  573. **********************************************************************/
  574. enum {
  575. POOL_BITS = BLAKE2S_HASH_SIZE * 8,
  576. POOL_READY_BITS = POOL_BITS, /* When crng_init->CRNG_READY */
  577. POOL_EARLY_BITS = POOL_READY_BITS / 2 /* When crng_init->CRNG_EARLY */
  578. };
  579. static struct {
  580. struct blake2s_state hash;
  581. spinlock_t lock;
  582. unsigned int init_bits;
  583. } input_pool = {
  584. .hash.h = { BLAKE2S_IV0 ^ (0x01010000 | BLAKE2S_HASH_SIZE),
  585. BLAKE2S_IV1, BLAKE2S_IV2, BLAKE2S_IV3, BLAKE2S_IV4,
  586. BLAKE2S_IV5, BLAKE2S_IV6, BLAKE2S_IV7 },
  587. .hash.outlen = BLAKE2S_HASH_SIZE,
  588. .lock = __SPIN_LOCK_UNLOCKED(input_pool.lock),
  589. };
  590. static void _mix_pool_bytes(const void *buf, size_t len)
  591. {
  592. blake2s_update(&input_pool.hash, buf, len);
  593. }
  594. /*
  595. * This function adds bytes into the input pool. It does not
  596. * update the initialization bit counter; the caller should call
  597. * credit_init_bits if this is appropriate.
  598. */
  599. static void mix_pool_bytes(const void *buf, size_t len)
  600. {
  601. unsigned long flags;
  602. spin_lock_irqsave(&input_pool.lock, flags);
  603. _mix_pool_bytes(buf, len);
  604. spin_unlock_irqrestore(&input_pool.lock, flags);
  605. }
  606. /*
  607. * This is an HKDF-like construction for using the hashed collected entropy
  608. * as a PRF key, that's then expanded block-by-block.
  609. */
  610. static void extract_entropy(void *buf, size_t len)
  611. {
  612. unsigned long flags;
  613. u8 seed[BLAKE2S_HASH_SIZE], next_key[BLAKE2S_HASH_SIZE];
  614. struct {
  615. unsigned long rdseed[32 / sizeof(long)];
  616. size_t counter;
  617. } block;
  618. size_t i, longs;
  619. for (i = 0; i < ARRAY_SIZE(block.rdseed);) {
  620. longs = arch_get_random_seed_longs(&block.rdseed[i], ARRAY_SIZE(block.rdseed) - i);
  621. if (longs) {
  622. i += longs;
  623. continue;
  624. }
  625. longs = arch_get_random_longs(&block.rdseed[i], ARRAY_SIZE(block.rdseed) - i);
  626. if (longs) {
  627. i += longs;
  628. continue;
  629. }
  630. block.rdseed[i++] = random_get_entropy();
  631. }
  632. spin_lock_irqsave(&input_pool.lock, flags);
  633. /* seed = HASHPRF(last_key, entropy_input) */
  634. blake2s_final(&input_pool.hash, seed);
  635. /* next_key = HASHPRF(seed, RDSEED || 0) */
  636. block.counter = 0;
  637. blake2s(next_key, (u8 *)&block, seed, sizeof(next_key), sizeof(block), sizeof(seed));
  638. blake2s_init_key(&input_pool.hash, BLAKE2S_HASH_SIZE, next_key, sizeof(next_key));
  639. spin_unlock_irqrestore(&input_pool.lock, flags);
  640. memzero_explicit(next_key, sizeof(next_key));
  641. while (len) {
  642. i = min_t(size_t, len, BLAKE2S_HASH_SIZE);
  643. /* output = HASHPRF(seed, RDSEED || ++counter) */
  644. ++block.counter;
  645. blake2s(buf, (u8 *)&block, seed, i, sizeof(block), sizeof(seed));
  646. len -= i;
  647. buf += i;
  648. }
  649. memzero_explicit(seed, sizeof(seed));
  650. memzero_explicit(&block, sizeof(block));
  651. }
  652. #define credit_init_bits(bits) if (!crng_ready()) _credit_init_bits(bits)
  653. static void __cold _credit_init_bits(size_t bits)
  654. {
  655. static DECLARE_WORK(set_ready, crng_set_ready);
  656. unsigned int new, orig, add;
  657. unsigned long flags;
  658. if (!bits)
  659. return;
  660. add = min_t(size_t, bits, POOL_BITS);
  661. orig = READ_ONCE(input_pool.init_bits);
  662. do {
  663. new = min_t(unsigned int, POOL_BITS, orig + add);
  664. } while (!try_cmpxchg(&input_pool.init_bits, &orig, new));
  665. if (orig < POOL_READY_BITS && new >= POOL_READY_BITS) {
  666. crng_reseed(NULL); /* Sets crng_init to CRNG_READY under base_crng.lock. */
  667. if (static_key_initialized && system_unbound_wq)
  668. queue_work(system_unbound_wq, &set_ready);
  669. atomic_notifier_call_chain(&random_ready_notifier, 0, NULL);
  670. #ifdef CONFIG_VDSO_GETRANDOM
  671. WRITE_ONCE(__arch_get_k_vdso_rng_data()->is_ready, true);
  672. #endif
  673. wake_up_interruptible(&crng_init_wait);
  674. kill_fasync(&fasync, SIGIO, POLL_IN);
  675. pr_notice("crng init done\n");
  676. if (urandom_warning.missed)
  677. pr_notice("%d urandom warning(s) missed due to ratelimiting\n",
  678. urandom_warning.missed);
  679. } else if (orig < POOL_EARLY_BITS && new >= POOL_EARLY_BITS) {
  680. spin_lock_irqsave(&base_crng.lock, flags);
  681. /* Check if crng_init is CRNG_EMPTY, to avoid race with crng_reseed(). */
  682. if (crng_init == CRNG_EMPTY) {
  683. extract_entropy(base_crng.key, sizeof(base_crng.key));
  684. crng_init = CRNG_EARLY;
  685. }
  686. spin_unlock_irqrestore(&base_crng.lock, flags);
  687. }
  688. }
  689. /**********************************************************************
  690. *
  691. * Entropy collection routines.
  692. *
  693. * The following exported functions are used for pushing entropy into
  694. * the above entropy accumulation routines:
  695. *
  696. * void add_device_randomness(const void *buf, size_t len);
  697. * void add_hwgenerator_randomness(const void *buf, size_t len, size_t entropy, bool sleep_after);
  698. * void add_bootloader_randomness(const void *buf, size_t len);
  699. * void add_vmfork_randomness(const void *unique_vm_id, size_t len);
  700. * void add_interrupt_randomness(int irq);
  701. * void add_input_randomness(unsigned int type, unsigned int code, unsigned int value);
  702. * void add_disk_randomness(struct gendisk *disk);
  703. *
  704. * add_device_randomness() adds data to the input pool that
  705. * is likely to differ between two devices (or possibly even per boot).
  706. * This would be things like MAC addresses or serial numbers, or the
  707. * read-out of the RTC. This does *not* credit any actual entropy to
  708. * the pool, but it initializes the pool to different values for devices
  709. * that might otherwise be identical and have very little entropy
  710. * available to them (particularly common in the embedded world).
  711. *
  712. * add_hwgenerator_randomness() is for true hardware RNGs, and will credit
  713. * entropy as specified by the caller. If the entropy pool is full it will
  714. * block until more entropy is needed.
  715. *
  716. * add_bootloader_randomness() is called by bootloader drivers, such as EFI
  717. * and device tree, and credits its input depending on whether or not the
  718. * command line option 'random.trust_bootloader'.
  719. *
  720. * add_vmfork_randomness() adds a unique (but not necessarily secret) ID
  721. * representing the current instance of a VM to the pool, without crediting,
  722. * and then force-reseeds the crng so that it takes effect immediately.
  723. *
  724. * add_interrupt_randomness() uses the interrupt timing as random
  725. * inputs to the entropy pool. Using the cycle counters and the irq source
  726. * as inputs, it feeds the input pool roughly once a second or after 64
  727. * interrupts, crediting 1 bit of entropy for whichever comes first.
  728. *
  729. * add_input_randomness() uses the input layer interrupt timing, as well
  730. * as the event type information from the hardware.
  731. *
  732. * add_disk_randomness() uses what amounts to the seek time of block
  733. * layer request events, on a per-disk_devt basis, as input to the
  734. * entropy pool. Note that high-speed solid state drives with very low
  735. * seek times do not make for good sources of entropy, as their seek
  736. * times are usually fairly consistent.
  737. *
  738. * The last two routines try to estimate how many bits of entropy
  739. * to credit. They do this by keeping track of the first and second
  740. * order deltas of the event timings.
  741. *
  742. **********************************************************************/
  743. static bool trust_cpu __initdata = true;
  744. static bool trust_bootloader __initdata = true;
  745. static int __init parse_trust_cpu(char *arg)
  746. {
  747. return kstrtobool(arg, &trust_cpu);
  748. }
  749. static int __init parse_trust_bootloader(char *arg)
  750. {
  751. return kstrtobool(arg, &trust_bootloader);
  752. }
  753. early_param("random.trust_cpu", parse_trust_cpu);
  754. early_param("random.trust_bootloader", parse_trust_bootloader);
  755. static int random_pm_notification(struct notifier_block *nb, unsigned long action, void *data)
  756. {
  757. unsigned long flags, entropy = random_get_entropy();
  758. /*
  759. * Encode a representation of how long the system has been suspended,
  760. * in a way that is distinct from prior system suspends.
  761. */
  762. ktime_t stamps[] = { ktime_get(), ktime_get_boottime(), ktime_get_real() };
  763. spin_lock_irqsave(&input_pool.lock, flags);
  764. _mix_pool_bytes(&action, sizeof(action));
  765. _mix_pool_bytes(stamps, sizeof(stamps));
  766. _mix_pool_bytes(&entropy, sizeof(entropy));
  767. spin_unlock_irqrestore(&input_pool.lock, flags);
  768. if (crng_ready() && (action == PM_RESTORE_PREPARE ||
  769. (action == PM_POST_SUSPEND && !IS_ENABLED(CONFIG_PM_AUTOSLEEP) &&
  770. !IS_ENABLED(CONFIG_PM_USERSPACE_AUTOSLEEP)))) {
  771. crng_reseed(NULL);
  772. pr_notice("crng reseeded on system resumption\n");
  773. }
  774. return 0;
  775. }
  776. static struct notifier_block pm_notifier = { .notifier_call = random_pm_notification };
  777. /*
  778. * This is called extremely early, before time keeping functionality is
  779. * available, but arch randomness is. Interrupts are not yet enabled.
  780. */
  781. void __init random_init_early(const char *command_line)
  782. {
  783. unsigned long entropy[BLAKE2S_BLOCK_SIZE / sizeof(long)];
  784. size_t i, longs, arch_bits;
  785. #if defined(LATENT_ENTROPY_PLUGIN)
  786. static const u8 compiletime_seed[BLAKE2S_BLOCK_SIZE] __initconst __latent_entropy;
  787. _mix_pool_bytes(compiletime_seed, sizeof(compiletime_seed));
  788. #endif
  789. for (i = 0, arch_bits = sizeof(entropy) * 8; i < ARRAY_SIZE(entropy);) {
  790. longs = arch_get_random_seed_longs(entropy, ARRAY_SIZE(entropy) - i);
  791. if (longs) {
  792. _mix_pool_bytes(entropy, sizeof(*entropy) * longs);
  793. i += longs;
  794. continue;
  795. }
  796. longs = arch_get_random_longs(entropy, ARRAY_SIZE(entropy) - i);
  797. if (longs) {
  798. _mix_pool_bytes(entropy, sizeof(*entropy) * longs);
  799. i += longs;
  800. continue;
  801. }
  802. arch_bits -= sizeof(*entropy) * 8;
  803. ++i;
  804. }
  805. _mix_pool_bytes(init_utsname(), sizeof(*(init_utsname())));
  806. _mix_pool_bytes(command_line, strlen(command_line));
  807. /* Reseed if already seeded by earlier phases. */
  808. if (crng_ready())
  809. crng_reseed(NULL);
  810. else if (trust_cpu)
  811. _credit_init_bits(arch_bits);
  812. }
  813. /*
  814. * This is called a little bit after the prior function, and now there is
  815. * access to timestamps counters. Interrupts are not yet enabled.
  816. */
  817. void __init random_init(void)
  818. {
  819. unsigned long entropy = random_get_entropy();
  820. ktime_t now = ktime_get_real();
  821. _mix_pool_bytes(&now, sizeof(now));
  822. _mix_pool_bytes(&entropy, sizeof(entropy));
  823. add_latent_entropy();
  824. /*
  825. * If we were initialized by the cpu or bootloader before jump labels
  826. * or workqueues are initialized, then we should enable the static
  827. * branch here, where it's guaranteed that these have been initialized.
  828. */
  829. if (!static_branch_likely(&crng_is_ready) && crng_init >= CRNG_READY)
  830. crng_set_ready(NULL);
  831. /* Reseed if already seeded by earlier phases. */
  832. if (crng_ready())
  833. crng_reseed(NULL);
  834. WARN_ON(register_pm_notifier(&pm_notifier));
  835. WARN(!entropy, "Missing cycle counter and fallback timer; RNG "
  836. "entropy collection will consequently suffer.");
  837. }
  838. /*
  839. * Add device- or boot-specific data to the input pool to help
  840. * initialize it.
  841. *
  842. * None of this adds any entropy; it is meant to avoid the problem of
  843. * the entropy pool having similar initial state across largely
  844. * identical devices.
  845. */
  846. void add_device_randomness(const void *buf, size_t len)
  847. {
  848. unsigned long entropy = random_get_entropy();
  849. unsigned long flags;
  850. spin_lock_irqsave(&input_pool.lock, flags);
  851. _mix_pool_bytes(&entropy, sizeof(entropy));
  852. _mix_pool_bytes(buf, len);
  853. spin_unlock_irqrestore(&input_pool.lock, flags);
  854. }
  855. EXPORT_SYMBOL(add_device_randomness);
  856. /*
  857. * Interface for in-kernel drivers of true hardware RNGs. Those devices
  858. * may produce endless random bits, so this function will sleep for
  859. * some amount of time after, if the sleep_after parameter is true.
  860. */
  861. void add_hwgenerator_randomness(const void *buf, size_t len, size_t entropy, bool sleep_after)
  862. {
  863. mix_pool_bytes(buf, len);
  864. credit_init_bits(entropy);
  865. /*
  866. * Throttle writing to once every reseed interval, unless we're not yet
  867. * initialized or no entropy is credited.
  868. */
  869. if (sleep_after && !kthread_should_stop() && (crng_ready() || !entropy))
  870. schedule_timeout_interruptible(crng_reseed_interval());
  871. }
  872. EXPORT_SYMBOL_GPL(add_hwgenerator_randomness);
  873. /*
  874. * Handle random seed passed by bootloader, and credit it depending
  875. * on the command line option 'random.trust_bootloader'.
  876. */
  877. void __init add_bootloader_randomness(const void *buf, size_t len)
  878. {
  879. mix_pool_bytes(buf, len);
  880. if (trust_bootloader)
  881. credit_init_bits(len * 8);
  882. }
  883. #if IS_ENABLED(CONFIG_VMGENID)
  884. static BLOCKING_NOTIFIER_HEAD(vmfork_chain);
  885. /*
  886. * Handle a new unique VM ID, which is unique, not secret, so we
  887. * don't credit it, but we do immediately force a reseed after so
  888. * that it's used by the crng posthaste.
  889. */
  890. void __cold add_vmfork_randomness(const void *unique_vm_id, size_t len)
  891. {
  892. add_device_randomness(unique_vm_id, len);
  893. if (crng_ready()) {
  894. crng_reseed(NULL);
  895. pr_notice("crng reseeded due to virtual machine fork\n");
  896. }
  897. blocking_notifier_call_chain(&vmfork_chain, 0, NULL);
  898. }
  899. #if IS_MODULE(CONFIG_VMGENID)
  900. EXPORT_SYMBOL_GPL(add_vmfork_randomness);
  901. #endif
  902. int __cold register_random_vmfork_notifier(struct notifier_block *nb)
  903. {
  904. return blocking_notifier_chain_register(&vmfork_chain, nb);
  905. }
  906. EXPORT_SYMBOL_GPL(register_random_vmfork_notifier);
  907. int __cold unregister_random_vmfork_notifier(struct notifier_block *nb)
  908. {
  909. return blocking_notifier_chain_unregister(&vmfork_chain, nb);
  910. }
  911. EXPORT_SYMBOL_GPL(unregister_random_vmfork_notifier);
  912. #endif
  913. struct fast_pool {
  914. unsigned long pool[4];
  915. unsigned long last;
  916. unsigned int count;
  917. struct timer_list mix;
  918. };
  919. static void mix_interrupt_randomness(struct timer_list *work);
  920. static DEFINE_PER_CPU(struct fast_pool, irq_randomness) = {
  921. #ifdef CONFIG_64BIT
  922. #define FASTMIX_PERM SIPHASH_PERMUTATION
  923. .pool = { SIPHASH_CONST_0, SIPHASH_CONST_1, SIPHASH_CONST_2, SIPHASH_CONST_3 },
  924. #else
  925. #define FASTMIX_PERM HSIPHASH_PERMUTATION
  926. .pool = { HSIPHASH_CONST_0, HSIPHASH_CONST_1, HSIPHASH_CONST_2, HSIPHASH_CONST_3 },
  927. #endif
  928. .mix = __TIMER_INITIALIZER(mix_interrupt_randomness, 0)
  929. };
  930. /*
  931. * This is [Half]SipHash-1-x, starting from an empty key. Because
  932. * the key is fixed, it assumes that its inputs are non-malicious,
  933. * and therefore this has no security on its own. s represents the
  934. * four-word SipHash state, while v represents a two-word input.
  935. */
  936. static void fast_mix(unsigned long s[4], unsigned long v1, unsigned long v2)
  937. {
  938. s[3] ^= v1;
  939. FASTMIX_PERM(s[0], s[1], s[2], s[3]);
  940. s[0] ^= v1;
  941. s[3] ^= v2;
  942. FASTMIX_PERM(s[0], s[1], s[2], s[3]);
  943. s[0] ^= v2;
  944. }
  945. #ifdef CONFIG_SMP
  946. /*
  947. * This function is called when the CPU has just come online, with
  948. * entry CPUHP_AP_RANDOM_ONLINE, just after CPUHP_AP_WORKQUEUE_ONLINE.
  949. */
  950. int __cold random_online_cpu(unsigned int cpu)
  951. {
  952. /*
  953. * During CPU shutdown and before CPU onlining, add_interrupt_
  954. * randomness() may schedule mix_interrupt_randomness(), and
  955. * set the MIX_INFLIGHT flag. However, because the worker can
  956. * be scheduled on a different CPU during this period, that
  957. * flag will never be cleared. For that reason, we zero out
  958. * the flag here, which runs just after workqueues are onlined
  959. * for the CPU again. This also has the effect of setting the
  960. * irq randomness count to zero so that new accumulated irqs
  961. * are fresh.
  962. */
  963. per_cpu_ptr(&irq_randomness, cpu)->count = 0;
  964. return 0;
  965. }
  966. #endif
  967. static void mix_interrupt_randomness(struct timer_list *work)
  968. {
  969. struct fast_pool *fast_pool = container_of(work, struct fast_pool, mix);
  970. /*
  971. * The size of the copied stack pool is explicitly 2 longs so that we
  972. * only ever ingest half of the siphash output each time, retaining
  973. * the other half as the next "key" that carries over. The entropy is
  974. * supposed to be sufficiently dispersed between bits so on average
  975. * we don't wind up "losing" some.
  976. */
  977. unsigned long pool[2];
  978. unsigned int count;
  979. /* Check to see if we're running on the wrong CPU due to hotplug. */
  980. local_irq_disable();
  981. if (fast_pool != this_cpu_ptr(&irq_randomness)) {
  982. local_irq_enable();
  983. return;
  984. }
  985. /*
  986. * Copy the pool to the stack so that the mixer always has a
  987. * consistent view, before we reenable irqs again.
  988. */
  989. memcpy(pool, fast_pool->pool, sizeof(pool));
  990. count = fast_pool->count;
  991. fast_pool->count = 0;
  992. fast_pool->last = jiffies;
  993. local_irq_enable();
  994. mix_pool_bytes(pool, sizeof(pool));
  995. credit_init_bits(clamp_t(unsigned int, (count & U16_MAX) / 64, 1, sizeof(pool) * 8));
  996. memzero_explicit(pool, sizeof(pool));
  997. }
  998. void add_interrupt_randomness(int irq)
  999. {
  1000. enum { MIX_INFLIGHT = 1U << 31 };
  1001. unsigned long entropy = random_get_entropy();
  1002. struct fast_pool *fast_pool = this_cpu_ptr(&irq_randomness);
  1003. struct pt_regs *regs = get_irq_regs();
  1004. unsigned int new_count;
  1005. fast_mix(fast_pool->pool, entropy,
  1006. (regs ? instruction_pointer(regs) : _RET_IP_) ^ swab(irq));
  1007. new_count = ++fast_pool->count;
  1008. if (new_count & MIX_INFLIGHT)
  1009. return;
  1010. if (new_count < 1024 && !time_is_before_jiffies(fast_pool->last + HZ))
  1011. return;
  1012. fast_pool->count |= MIX_INFLIGHT;
  1013. if (!timer_pending(&fast_pool->mix)) {
  1014. fast_pool->mix.expires = jiffies;
  1015. add_timer_on(&fast_pool->mix, raw_smp_processor_id());
  1016. }
  1017. }
  1018. EXPORT_SYMBOL_GPL(add_interrupt_randomness);
  1019. /* There is one of these per entropy source */
  1020. struct timer_rand_state {
  1021. unsigned long last_time;
  1022. long last_delta, last_delta2;
  1023. };
  1024. /*
  1025. * This function adds entropy to the entropy "pool" by using timing
  1026. * delays. It uses the timer_rand_state structure to make an estimate
  1027. * of how many bits of entropy this call has added to the pool. The
  1028. * value "num" is also added to the pool; it should somehow describe
  1029. * the type of event that just happened.
  1030. */
  1031. static void add_timer_randomness(struct timer_rand_state *state, unsigned int num)
  1032. {
  1033. unsigned long entropy = random_get_entropy(), now = jiffies, flags;
  1034. long delta, delta2, delta3;
  1035. unsigned int bits;
  1036. /*
  1037. * If we're in a hard IRQ, add_interrupt_randomness() will be called
  1038. * sometime after, so mix into the fast pool.
  1039. */
  1040. if (in_hardirq()) {
  1041. fast_mix(this_cpu_ptr(&irq_randomness)->pool, entropy, num);
  1042. } else {
  1043. spin_lock_irqsave(&input_pool.lock, flags);
  1044. _mix_pool_bytes(&entropy, sizeof(entropy));
  1045. _mix_pool_bytes(&num, sizeof(num));
  1046. spin_unlock_irqrestore(&input_pool.lock, flags);
  1047. }
  1048. if (crng_ready())
  1049. return;
  1050. /*
  1051. * Calculate number of bits of randomness we probably added.
  1052. * We take into account the first, second and third-order deltas
  1053. * in order to make our estimate.
  1054. */
  1055. delta = now - READ_ONCE(state->last_time);
  1056. WRITE_ONCE(state->last_time, now);
  1057. delta2 = delta - READ_ONCE(state->last_delta);
  1058. WRITE_ONCE(state->last_delta, delta);
  1059. delta3 = delta2 - READ_ONCE(state->last_delta2);
  1060. WRITE_ONCE(state->last_delta2, delta2);
  1061. if (delta < 0)
  1062. delta = -delta;
  1063. if (delta2 < 0)
  1064. delta2 = -delta2;
  1065. if (delta3 < 0)
  1066. delta3 = -delta3;
  1067. if (delta > delta2)
  1068. delta = delta2;
  1069. if (delta > delta3)
  1070. delta = delta3;
  1071. /*
  1072. * delta is now minimum absolute delta. Round down by 1 bit
  1073. * on general principles, and limit entropy estimate to 11 bits.
  1074. */
  1075. bits = min(fls(delta >> 1), 11);
  1076. /*
  1077. * As mentioned above, if we're in a hard IRQ, add_interrupt_randomness()
  1078. * will run after this, which uses a different crediting scheme of 1 bit
  1079. * per every 64 interrupts. In order to let that function do accounting
  1080. * close to the one in this function, we credit a full 64/64 bit per bit,
  1081. * and then subtract one to account for the extra one added.
  1082. */
  1083. if (in_hardirq())
  1084. this_cpu_ptr(&irq_randomness)->count += max(1u, bits * 64) - 1;
  1085. else
  1086. _credit_init_bits(bits);
  1087. }
  1088. void add_input_randomness(unsigned int type, unsigned int code, unsigned int value)
  1089. {
  1090. static unsigned char last_value;
  1091. static struct timer_rand_state input_timer_state = { INITIAL_JIFFIES };
  1092. /* Ignore autorepeat and the like. */
  1093. if (value == last_value)
  1094. return;
  1095. last_value = value;
  1096. add_timer_randomness(&input_timer_state,
  1097. (type << 4) ^ code ^ (code >> 4) ^ value);
  1098. }
  1099. EXPORT_SYMBOL_GPL(add_input_randomness);
  1100. #ifdef CONFIG_BLOCK
  1101. void add_disk_randomness(struct gendisk *disk)
  1102. {
  1103. if (!disk || !disk->random)
  1104. return;
  1105. /* First major is 1, so we get >= 0x200 here. */
  1106. add_timer_randomness(disk->random, 0x100 + disk_devt(disk));
  1107. }
  1108. EXPORT_SYMBOL_GPL(add_disk_randomness);
  1109. void __cold rand_initialize_disk(struct gendisk *disk)
  1110. {
  1111. struct timer_rand_state *state;
  1112. /*
  1113. * If kzalloc returns null, we just won't use that entropy
  1114. * source.
  1115. */
  1116. state = kzalloc(sizeof(struct timer_rand_state), GFP_KERNEL);
  1117. if (state) {
  1118. state->last_time = INITIAL_JIFFIES;
  1119. disk->random = state;
  1120. }
  1121. }
  1122. #endif
  1123. struct entropy_timer_state {
  1124. unsigned long entropy;
  1125. struct timer_list timer;
  1126. atomic_t samples;
  1127. unsigned int samples_per_bit;
  1128. };
  1129. /*
  1130. * Each time the timer fires, we expect that we got an unpredictable jump in
  1131. * the cycle counter. Even if the timer is running on another CPU, the timer
  1132. * activity will be touching the stack of the CPU that is generating entropy.
  1133. *
  1134. * Note that we don't re-arm the timer in the timer itself - we are happy to be
  1135. * scheduled away, since that just makes the load more complex, but we do not
  1136. * want the timer to keep ticking unless the entropy loop is running.
  1137. *
  1138. * So the re-arming always happens in the entropy loop itself.
  1139. */
  1140. static void __cold entropy_timer(struct timer_list *timer)
  1141. {
  1142. struct entropy_timer_state *state = container_of(timer, struct entropy_timer_state, timer);
  1143. unsigned long entropy = random_get_entropy();
  1144. mix_pool_bytes(&entropy, sizeof(entropy));
  1145. if (atomic_inc_return(&state->samples) % state->samples_per_bit == 0)
  1146. credit_init_bits(1);
  1147. }
  1148. /*
  1149. * If we have an actual cycle counter, see if we can generate enough entropy
  1150. * with timing noise.
  1151. */
  1152. static void __cold try_to_generate_entropy(void)
  1153. {
  1154. enum { NUM_TRIAL_SAMPLES = 8192, MAX_SAMPLES_PER_BIT = HZ / 15 };
  1155. u8 stack_bytes[sizeof(struct entropy_timer_state) + SMP_CACHE_BYTES - 1];
  1156. struct entropy_timer_state *stack = PTR_ALIGN((void *)stack_bytes, SMP_CACHE_BYTES);
  1157. unsigned int i, num_different = 0;
  1158. unsigned long last = random_get_entropy();
  1159. int cpu = -1;
  1160. for (i = 0; i < NUM_TRIAL_SAMPLES - 1; ++i) {
  1161. stack->entropy = random_get_entropy();
  1162. if (stack->entropy != last)
  1163. ++num_different;
  1164. last = stack->entropy;
  1165. }
  1166. stack->samples_per_bit = DIV_ROUND_UP(NUM_TRIAL_SAMPLES, num_different + 1);
  1167. if (stack->samples_per_bit > MAX_SAMPLES_PER_BIT)
  1168. return;
  1169. atomic_set(&stack->samples, 0);
  1170. timer_setup_on_stack(&stack->timer, entropy_timer, 0);
  1171. while (!crng_ready() && !signal_pending(current)) {
  1172. /*
  1173. * Check !timer_pending() and then ensure that any previous callback has finished
  1174. * executing by checking try_to_del_timer_sync(), before queueing the next one.
  1175. */
  1176. if (!timer_pending(&stack->timer) && try_to_del_timer_sync(&stack->timer) >= 0) {
  1177. struct cpumask timer_cpus;
  1178. unsigned int num_cpus;
  1179. /*
  1180. * Preemption must be disabled here, both to read the current CPU number
  1181. * and to avoid scheduling a timer on a dead CPU.
  1182. */
  1183. preempt_disable();
  1184. /* Only schedule callbacks on timer CPUs that are online. */
  1185. cpumask_and(&timer_cpus, housekeeping_cpumask(HK_TYPE_TIMER), cpu_online_mask);
  1186. num_cpus = cpumask_weight(&timer_cpus);
  1187. /* In very bizarre case of misconfiguration, fallback to all online. */
  1188. if (unlikely(num_cpus == 0)) {
  1189. timer_cpus = *cpu_online_mask;
  1190. num_cpus = cpumask_weight(&timer_cpus);
  1191. }
  1192. /* Basic CPU round-robin, which avoids the current CPU. */
  1193. do {
  1194. cpu = cpumask_next(cpu, &timer_cpus);
  1195. if (cpu >= nr_cpu_ids)
  1196. cpu = cpumask_first(&timer_cpus);
  1197. } while (cpu == smp_processor_id() && num_cpus > 1);
  1198. /* Expiring the timer at `jiffies` means it's the next tick. */
  1199. stack->timer.expires = jiffies;
  1200. add_timer_on(&stack->timer, cpu);
  1201. preempt_enable();
  1202. }
  1203. mix_pool_bytes(&stack->entropy, sizeof(stack->entropy));
  1204. schedule();
  1205. stack->entropy = random_get_entropy();
  1206. }
  1207. mix_pool_bytes(&stack->entropy, sizeof(stack->entropy));
  1208. del_timer_sync(&stack->timer);
  1209. destroy_timer_on_stack(&stack->timer);
  1210. }
  1211. /**********************************************************************
  1212. *
  1213. * Userspace reader/writer interfaces.
  1214. *
  1215. * getrandom(2) is the primary modern interface into the RNG and should
  1216. * be used in preference to anything else.
  1217. *
  1218. * Reading from /dev/random has the same functionality as calling
  1219. * getrandom(2) with flags=0. In earlier versions, however, it had
  1220. * vastly different semantics and should therefore be avoided, to
  1221. * prevent backwards compatibility issues.
  1222. *
  1223. * Reading from /dev/urandom has the same functionality as calling
  1224. * getrandom(2) with flags=GRND_INSECURE. Because it does not block
  1225. * waiting for the RNG to be ready, it should not be used.
  1226. *
  1227. * Writing to either /dev/random or /dev/urandom adds entropy to
  1228. * the input pool but does not credit it.
  1229. *
  1230. * Polling on /dev/random indicates when the RNG is initialized, on
  1231. * the read side, and when it wants new entropy, on the write side.
  1232. *
  1233. * Both /dev/random and /dev/urandom have the same set of ioctls for
  1234. * adding entropy, getting the entropy count, zeroing the count, and
  1235. * reseeding the crng.
  1236. *
  1237. **********************************************************************/
  1238. SYSCALL_DEFINE3(getrandom, char __user *, ubuf, size_t, len, unsigned int, flags)
  1239. {
  1240. struct iov_iter iter;
  1241. int ret;
  1242. if (flags & ~(GRND_NONBLOCK | GRND_RANDOM | GRND_INSECURE))
  1243. return -EINVAL;
  1244. /*
  1245. * Requesting insecure and blocking randomness at the same time makes
  1246. * no sense.
  1247. */
  1248. if ((flags & (GRND_INSECURE | GRND_RANDOM)) == (GRND_INSECURE | GRND_RANDOM))
  1249. return -EINVAL;
  1250. if (!crng_ready() && !(flags & GRND_INSECURE)) {
  1251. if (flags & GRND_NONBLOCK)
  1252. return -EAGAIN;
  1253. ret = wait_for_random_bytes();
  1254. if (unlikely(ret))
  1255. return ret;
  1256. }
  1257. ret = import_ubuf(ITER_DEST, ubuf, len, &iter);
  1258. if (unlikely(ret))
  1259. return ret;
  1260. return get_random_bytes_user(&iter);
  1261. }
  1262. static __poll_t random_poll(struct file *file, poll_table *wait)
  1263. {
  1264. poll_wait(file, &crng_init_wait, wait);
  1265. return crng_ready() ? EPOLLIN | EPOLLRDNORM : EPOLLOUT | EPOLLWRNORM;
  1266. }
  1267. static ssize_t write_pool_user(struct iov_iter *iter)
  1268. {
  1269. u8 block[BLAKE2S_BLOCK_SIZE];
  1270. ssize_t ret = 0;
  1271. size_t copied;
  1272. if (unlikely(!iov_iter_count(iter)))
  1273. return 0;
  1274. for (;;) {
  1275. copied = copy_from_iter(block, sizeof(block), iter);
  1276. ret += copied;
  1277. mix_pool_bytes(block, copied);
  1278. if (!iov_iter_count(iter) || copied != sizeof(block))
  1279. break;
  1280. BUILD_BUG_ON(PAGE_SIZE % sizeof(block) != 0);
  1281. if (ret % PAGE_SIZE == 0) {
  1282. if (signal_pending(current))
  1283. break;
  1284. cond_resched();
  1285. }
  1286. }
  1287. memzero_explicit(block, sizeof(block));
  1288. return ret ? ret : -EFAULT;
  1289. }
  1290. static ssize_t random_write_iter(struct kiocb *kiocb, struct iov_iter *iter)
  1291. {
  1292. return write_pool_user(iter);
  1293. }
  1294. static ssize_t urandom_read_iter(struct kiocb *kiocb, struct iov_iter *iter)
  1295. {
  1296. static int maxwarn = 10;
  1297. /*
  1298. * Opportunistically attempt to initialize the RNG on platforms that
  1299. * have fast cycle counters, but don't (for now) require it to succeed.
  1300. */
  1301. if (!crng_ready())
  1302. try_to_generate_entropy();
  1303. if (!crng_ready()) {
  1304. if (!ratelimit_disable && maxwarn <= 0)
  1305. ++urandom_warning.missed;
  1306. else if (ratelimit_disable || __ratelimit(&urandom_warning)) {
  1307. --maxwarn;
  1308. pr_notice("%s: uninitialized urandom read (%zu bytes read)\n",
  1309. current->comm, iov_iter_count(iter));
  1310. }
  1311. }
  1312. return get_random_bytes_user(iter);
  1313. }
  1314. static ssize_t random_read_iter(struct kiocb *kiocb, struct iov_iter *iter)
  1315. {
  1316. int ret;
  1317. if (!crng_ready() &&
  1318. ((kiocb->ki_flags & (IOCB_NOWAIT | IOCB_NOIO)) ||
  1319. (kiocb->ki_filp->f_flags & O_NONBLOCK)))
  1320. return -EAGAIN;
  1321. ret = wait_for_random_bytes();
  1322. if (ret != 0)
  1323. return ret;
  1324. return get_random_bytes_user(iter);
  1325. }
  1326. static long random_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
  1327. {
  1328. int __user *p = (int __user *)arg;
  1329. int ent_count;
  1330. switch (cmd) {
  1331. case RNDGETENTCNT:
  1332. /* Inherently racy, no point locking. */
  1333. if (put_user(input_pool.init_bits, p))
  1334. return -EFAULT;
  1335. return 0;
  1336. case RNDADDTOENTCNT:
  1337. if (!capable(CAP_SYS_ADMIN))
  1338. return -EPERM;
  1339. if (get_user(ent_count, p))
  1340. return -EFAULT;
  1341. if (ent_count < 0)
  1342. return -EINVAL;
  1343. credit_init_bits(ent_count);
  1344. return 0;
  1345. case RNDADDENTROPY: {
  1346. struct iov_iter iter;
  1347. ssize_t ret;
  1348. int len;
  1349. if (!capable(CAP_SYS_ADMIN))
  1350. return -EPERM;
  1351. if (get_user(ent_count, p++))
  1352. return -EFAULT;
  1353. if (ent_count < 0)
  1354. return -EINVAL;
  1355. if (get_user(len, p++))
  1356. return -EFAULT;
  1357. ret = import_ubuf(ITER_SOURCE, p, len, &iter);
  1358. if (unlikely(ret))
  1359. return ret;
  1360. ret = write_pool_user(&iter);
  1361. if (unlikely(ret < 0))
  1362. return ret;
  1363. /* Since we're crediting, enforce that it was all written into the pool. */
  1364. if (unlikely(ret != len))
  1365. return -EFAULT;
  1366. credit_init_bits(ent_count);
  1367. return 0;
  1368. }
  1369. case RNDZAPENTCNT:
  1370. case RNDCLEARPOOL:
  1371. /* No longer has any effect. */
  1372. if (!capable(CAP_SYS_ADMIN))
  1373. return -EPERM;
  1374. return 0;
  1375. case RNDRESEEDCRNG:
  1376. if (!capable(CAP_SYS_ADMIN))
  1377. return -EPERM;
  1378. if (!crng_ready())
  1379. return -ENODATA;
  1380. crng_reseed(NULL);
  1381. return 0;
  1382. default:
  1383. return -EINVAL;
  1384. }
  1385. }
  1386. static int random_fasync(int fd, struct file *filp, int on)
  1387. {
  1388. return fasync_helper(fd, filp, on, &fasync);
  1389. }
  1390. const struct file_operations random_fops = {
  1391. .read_iter = random_read_iter,
  1392. .write_iter = random_write_iter,
  1393. .poll = random_poll,
  1394. .unlocked_ioctl = random_ioctl,
  1395. .compat_ioctl = compat_ptr_ioctl,
  1396. .fasync = random_fasync,
  1397. .llseek = noop_llseek,
  1398. .splice_read = copy_splice_read,
  1399. .splice_write = iter_file_splice_write,
  1400. };
  1401. const struct file_operations urandom_fops = {
  1402. .read_iter = urandom_read_iter,
  1403. .write_iter = random_write_iter,
  1404. .unlocked_ioctl = random_ioctl,
  1405. .compat_ioctl = compat_ptr_ioctl,
  1406. .fasync = random_fasync,
  1407. .llseek = noop_llseek,
  1408. .splice_read = copy_splice_read,
  1409. .splice_write = iter_file_splice_write,
  1410. };
  1411. /********************************************************************
  1412. *
  1413. * Sysctl interface.
  1414. *
  1415. * These are partly unused legacy knobs with dummy values to not break
  1416. * userspace and partly still useful things. They are usually accessible
  1417. * in /proc/sys/kernel/random/ and are as follows:
  1418. *
  1419. * - boot_id - a UUID representing the current boot.
  1420. *
  1421. * - uuid - a random UUID, different each time the file is read.
  1422. *
  1423. * - poolsize - the number of bits of entropy that the input pool can
  1424. * hold, tied to the POOL_BITS constant.
  1425. *
  1426. * - entropy_avail - the number of bits of entropy currently in the
  1427. * input pool. Always <= poolsize.
  1428. *
  1429. * - write_wakeup_threshold - the amount of entropy in the input pool
  1430. * below which write polls to /dev/random will unblock, requesting
  1431. * more entropy, tied to the POOL_READY_BITS constant. It is writable
  1432. * to avoid breaking old userspaces, but writing to it does not
  1433. * change any behavior of the RNG.
  1434. *
  1435. * - urandom_min_reseed_secs - fixed to the value CRNG_RESEED_INTERVAL.
  1436. * It is writable to avoid breaking old userspaces, but writing
  1437. * to it does not change any behavior of the RNG.
  1438. *
  1439. ********************************************************************/
  1440. #ifdef CONFIG_SYSCTL
  1441. #include <linux/sysctl.h>
  1442. static int sysctl_random_min_urandom_seed = CRNG_RESEED_INTERVAL / HZ;
  1443. static int sysctl_random_write_wakeup_bits = POOL_READY_BITS;
  1444. static int sysctl_poolsize = POOL_BITS;
  1445. static u8 sysctl_bootid[UUID_SIZE];
  1446. /*
  1447. * This function is used to return both the bootid UUID, and random
  1448. * UUID. The difference is in whether table->data is NULL; if it is,
  1449. * then a new UUID is generated and returned to the user.
  1450. */
  1451. static int proc_do_uuid(const struct ctl_table *table, int write, void *buf,
  1452. size_t *lenp, loff_t *ppos)
  1453. {
  1454. u8 tmp_uuid[UUID_SIZE], *uuid;
  1455. char uuid_string[UUID_STRING_LEN + 1];
  1456. struct ctl_table fake_table = {
  1457. .data = uuid_string,
  1458. .maxlen = UUID_STRING_LEN
  1459. };
  1460. if (write)
  1461. return -EPERM;
  1462. uuid = table->data;
  1463. if (!uuid) {
  1464. uuid = tmp_uuid;
  1465. generate_random_uuid(uuid);
  1466. } else {
  1467. static DEFINE_SPINLOCK(bootid_spinlock);
  1468. spin_lock(&bootid_spinlock);
  1469. if (!uuid[8])
  1470. generate_random_uuid(uuid);
  1471. spin_unlock(&bootid_spinlock);
  1472. }
  1473. snprintf(uuid_string, sizeof(uuid_string), "%pU", uuid);
  1474. return proc_dostring(&fake_table, 0, buf, lenp, ppos);
  1475. }
  1476. /* The same as proc_dointvec, but writes don't change anything. */
  1477. static int proc_do_rointvec(const struct ctl_table *table, int write, void *buf,
  1478. size_t *lenp, loff_t *ppos)
  1479. {
  1480. return write ? 0 : proc_dointvec(table, 0, buf, lenp, ppos);
  1481. }
  1482. static struct ctl_table random_table[] = {
  1483. {
  1484. .procname = "poolsize",
  1485. .data = &sysctl_poolsize,
  1486. .maxlen = sizeof(int),
  1487. .mode = 0444,
  1488. .proc_handler = proc_dointvec,
  1489. },
  1490. {
  1491. .procname = "entropy_avail",
  1492. .data = &input_pool.init_bits,
  1493. .maxlen = sizeof(int),
  1494. .mode = 0444,
  1495. .proc_handler = proc_dointvec,
  1496. },
  1497. {
  1498. .procname = "write_wakeup_threshold",
  1499. .data = &sysctl_random_write_wakeup_bits,
  1500. .maxlen = sizeof(int),
  1501. .mode = 0644,
  1502. .proc_handler = proc_do_rointvec,
  1503. },
  1504. {
  1505. .procname = "urandom_min_reseed_secs",
  1506. .data = &sysctl_random_min_urandom_seed,
  1507. .maxlen = sizeof(int),
  1508. .mode = 0644,
  1509. .proc_handler = proc_do_rointvec,
  1510. },
  1511. {
  1512. .procname = "boot_id",
  1513. .data = &sysctl_bootid,
  1514. .mode = 0444,
  1515. .proc_handler = proc_do_uuid,
  1516. },
  1517. {
  1518. .procname = "uuid",
  1519. .mode = 0444,
  1520. .proc_handler = proc_do_uuid,
  1521. },
  1522. };
  1523. /*
  1524. * random_init() is called before sysctl_init(),
  1525. * so we cannot call register_sysctl_init() in random_init()
  1526. */
  1527. static int __init random_sysctls_init(void)
  1528. {
  1529. register_sysctl_init("kernel/random", random_table);
  1530. return 0;
  1531. }
  1532. device_initcall(random_sysctls_init);
  1533. #endif