random.c 61 KB

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