random.c 69 KB

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