random.c 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161
  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 <asm/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. * The minimum number of seconds between urandom pool reseeding. We
  305. * do this to limit the amount of entropy that can be drained from the
  306. * input pool even if there are heavy demands on /dev/urandom.
  307. */
  308. static int random_min_urandom_seed = 60;
  309. /*
  310. * Originally, we used a primitive polynomial of degree .poolwords
  311. * over GF(2). The taps for various sizes are defined below. They
  312. * were chosen to be evenly spaced except for the last tap, which is 1
  313. * to get the twisting happening as fast as possible.
  314. *
  315. * For the purposes of better mixing, we use the CRC-32 polynomial as
  316. * well to make a (modified) twisted Generalized Feedback Shift
  317. * Register. (See M. Matsumoto & Y. Kurita, 1992. Twisted GFSR
  318. * generators. ACM Transactions on Modeling and Computer Simulation
  319. * 2(3):179-194. Also see M. Matsumoto & Y. Kurita, 1994. Twisted
  320. * GFSR generators II. ACM Transactions on Modeling and Computer
  321. * Simulation 4:254-266)
  322. *
  323. * Thanks to Colin Plumb for suggesting this.
  324. *
  325. * The mixing operation is much less sensitive than the output hash,
  326. * where we use SHA-1. All that we want of mixing operation is that
  327. * it be a good non-cryptographic hash; i.e. it not produce collisions
  328. * when fed "random" data of the sort we expect to see. As long as
  329. * the pool state differs for different inputs, we have preserved the
  330. * input entropy and done a good job. The fact that an intelligent
  331. * attacker can construct inputs that will produce controlled
  332. * alterations to the pool's state is not important because we don't
  333. * consider such inputs to contribute any randomness. The only
  334. * property we need with respect to them is that the attacker can't
  335. * increase his/her knowledge of the pool's state. Since all
  336. * additions are reversible (knowing the final state and the input,
  337. * you can reconstruct the initial state), if an attacker has any
  338. * uncertainty about the initial state, he/she can only shuffle that
  339. * uncertainty about, but never cause any collisions (which would
  340. * decrease the uncertainty).
  341. *
  342. * Our mixing functions were analyzed by Lacharme, Roeck, Strubel, and
  343. * Videau in their paper, "The Linux Pseudorandom Number Generator
  344. * Revisited" (see: http://eprint.iacr.org/2012/251.pdf). In their
  345. * paper, they point out that we are not using a true Twisted GFSR,
  346. * since Matsumoto & Kurita used a trinomial feedback polynomial (that
  347. * is, with only three taps, instead of the six that we are using).
  348. * As a result, the resulting polynomial is neither primitive nor
  349. * irreducible, and hence does not have a maximal period over
  350. * GF(2**32). They suggest a slight change to the generator
  351. * polynomial which improves the resulting TGFSR polynomial to be
  352. * irreducible, which we have made here.
  353. */
  354. static struct poolinfo {
  355. int poolbitshift, poolwords, poolbytes, poolbits, poolfracbits;
  356. #define S(x) ilog2(x)+5, (x), (x)*4, (x)*32, (x) << (ENTROPY_SHIFT+5)
  357. int tap1, tap2, tap3, tap4, tap5;
  358. } poolinfo_table[] = {
  359. /* was: x^128 + x^103 + x^76 + x^51 +x^25 + x + 1 */
  360. /* x^128 + x^104 + x^76 + x^51 +x^25 + x + 1 */
  361. { S(128), 104, 76, 51, 25, 1 },
  362. /* was: x^32 + x^26 + x^20 + x^14 + x^7 + x + 1 */
  363. /* x^32 + x^26 + x^19 + x^14 + x^7 + x + 1 */
  364. { S(32), 26, 19, 14, 7, 1 },
  365. #if 0
  366. /* x^2048 + x^1638 + x^1231 + x^819 + x^411 + x + 1 -- 115 */
  367. { S(2048), 1638, 1231, 819, 411, 1 },
  368. /* x^1024 + x^817 + x^615 + x^412 + x^204 + x + 1 -- 290 */
  369. { S(1024), 817, 615, 412, 204, 1 },
  370. /* x^1024 + x^819 + x^616 + x^410 + x^207 + x^2 + 1 -- 115 */
  371. { S(1024), 819, 616, 410, 207, 2 },
  372. /* x^512 + x^411 + x^308 + x^208 + x^104 + x + 1 -- 225 */
  373. { S(512), 411, 308, 208, 104, 1 },
  374. /* x^512 + x^409 + x^307 + x^206 + x^102 + x^2 + 1 -- 95 */
  375. { S(512), 409, 307, 206, 102, 2 },
  376. /* x^512 + x^409 + x^309 + x^205 + x^103 + x^2 + 1 -- 95 */
  377. { S(512), 409, 309, 205, 103, 2 },
  378. /* x^256 + x^205 + x^155 + x^101 + x^52 + x + 1 -- 125 */
  379. { S(256), 205, 155, 101, 52, 1 },
  380. /* x^128 + x^103 + x^78 + x^51 + x^27 + x^2 + 1 -- 70 */
  381. { S(128), 103, 78, 51, 27, 2 },
  382. /* x^64 + x^52 + x^39 + x^26 + x^14 + x + 1 -- 15 */
  383. { S(64), 52, 39, 26, 14, 1 },
  384. #endif
  385. };
  386. /*
  387. * Static global variables
  388. */
  389. static DECLARE_WAIT_QUEUE_HEAD(random_read_wait);
  390. static DECLARE_WAIT_QUEUE_HEAD(random_write_wait);
  391. static DECLARE_WAIT_QUEUE_HEAD(urandom_init_wait);
  392. static struct fasync_struct *fasync;
  393. static DEFINE_SPINLOCK(random_ready_list_lock);
  394. static LIST_HEAD(random_ready_list);
  395. struct crng_state {
  396. __u32 state[16];
  397. unsigned long init_time;
  398. spinlock_t lock;
  399. };
  400. struct crng_state primary_crng = {
  401. .lock = __SPIN_LOCK_UNLOCKED(primary_crng.lock),
  402. };
  403. /*
  404. * crng_init = 0 --> Uninitialized
  405. * 1 --> Initialized
  406. * 2 --> Initialized from input_pool
  407. *
  408. * crng_init is protected by primary_crng->lock, and only increases
  409. * its value (from 0->1->2).
  410. */
  411. static int crng_init = 0;
  412. #define crng_ready() (likely(crng_init > 0))
  413. static int crng_init_cnt = 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. /**********************************************************************
  421. *
  422. * OS independent entropy store. Here are the functions which handle
  423. * storing entropy in an entropy pool.
  424. *
  425. **********************************************************************/
  426. struct entropy_store;
  427. struct entropy_store {
  428. /* read-only data: */
  429. const struct poolinfo *poolinfo;
  430. __u32 *pool;
  431. const char *name;
  432. struct entropy_store *pull;
  433. struct work_struct push_work;
  434. /* read-write data: */
  435. unsigned long last_pulled;
  436. spinlock_t lock;
  437. unsigned short add_ptr;
  438. unsigned short input_rotate;
  439. int entropy_count;
  440. int entropy_total;
  441. unsigned int initialized:1;
  442. unsigned int limit:1;
  443. unsigned int last_data_init:1;
  444. __u8 last_data[EXTRACT_SIZE];
  445. };
  446. static ssize_t extract_entropy(struct entropy_store *r, void *buf,
  447. size_t nbytes, int min, int rsvd);
  448. static ssize_t _extract_entropy(struct entropy_store *r, void *buf,
  449. size_t nbytes, int fips);
  450. static void crng_reseed(struct crng_state *crng, struct entropy_store *r);
  451. static void push_to_pool(struct work_struct *work);
  452. static __u32 input_pool_data[INPUT_POOL_WORDS] __latent_entropy;
  453. static __u32 blocking_pool_data[OUTPUT_POOL_WORDS] __latent_entropy;
  454. static struct entropy_store input_pool = {
  455. .poolinfo = &poolinfo_table[0],
  456. .name = "input",
  457. .limit = 1,
  458. .lock = __SPIN_LOCK_UNLOCKED(input_pool.lock),
  459. .pool = input_pool_data
  460. };
  461. static struct entropy_store blocking_pool = {
  462. .poolinfo = &poolinfo_table[1],
  463. .name = "blocking",
  464. .limit = 1,
  465. .pull = &input_pool,
  466. .lock = __SPIN_LOCK_UNLOCKED(blocking_pool.lock),
  467. .pool = blocking_pool_data,
  468. .push_work = __WORK_INITIALIZER(blocking_pool.push_work,
  469. push_to_pool),
  470. };
  471. static __u32 const twist_table[8] = {
  472. 0x00000000, 0x3b6e20c8, 0x76dc4190, 0x4db26158,
  473. 0xedb88320, 0xd6d6a3e8, 0x9b64c2b0, 0xa00ae278 };
  474. /*
  475. * This function adds bytes into the entropy "pool". It does not
  476. * update the entropy estimate. The caller should call
  477. * credit_entropy_bits if this is appropriate.
  478. *
  479. * The pool is stirred with a primitive polynomial of the appropriate
  480. * degree, and then twisted. We twist by three bits at a time because
  481. * it's cheap to do so and helps slightly in the expected case where
  482. * the entropy is concentrated in the low-order bits.
  483. */
  484. static void _mix_pool_bytes(struct entropy_store *r, const void *in,
  485. int nbytes)
  486. {
  487. unsigned long i, tap1, tap2, tap3, tap4, tap5;
  488. int input_rotate;
  489. int wordmask = r->poolinfo->poolwords - 1;
  490. const char *bytes = in;
  491. __u32 w;
  492. tap1 = r->poolinfo->tap1;
  493. tap2 = r->poolinfo->tap2;
  494. tap3 = r->poolinfo->tap3;
  495. tap4 = r->poolinfo->tap4;
  496. tap5 = r->poolinfo->tap5;
  497. input_rotate = r->input_rotate;
  498. i = r->add_ptr;
  499. /* mix one byte at a time to simplify size handling and churn faster */
  500. while (nbytes--) {
  501. w = rol32(*bytes++, input_rotate);
  502. i = (i - 1) & wordmask;
  503. /* XOR in the various taps */
  504. w ^= r->pool[i];
  505. w ^= r->pool[(i + tap1) & wordmask];
  506. w ^= r->pool[(i + tap2) & wordmask];
  507. w ^= r->pool[(i + tap3) & wordmask];
  508. w ^= r->pool[(i + tap4) & wordmask];
  509. w ^= r->pool[(i + tap5) & wordmask];
  510. /* Mix the result back in with a twist */
  511. r->pool[i] = (w >> 3) ^ twist_table[w & 7];
  512. /*
  513. * Normally, we add 7 bits of rotation to the pool.
  514. * At the beginning of the pool, add an extra 7 bits
  515. * rotation, so that successive passes spread the
  516. * input bits across the pool evenly.
  517. */
  518. input_rotate = (input_rotate + (i ? 7 : 14)) & 31;
  519. }
  520. r->input_rotate = input_rotate;
  521. r->add_ptr = i;
  522. }
  523. static void __mix_pool_bytes(struct entropy_store *r, const void *in,
  524. int nbytes)
  525. {
  526. trace_mix_pool_bytes_nolock(r->name, nbytes, _RET_IP_);
  527. _mix_pool_bytes(r, in, nbytes);
  528. }
  529. static void mix_pool_bytes(struct entropy_store *r, const void *in,
  530. int nbytes)
  531. {
  532. unsigned long flags;
  533. trace_mix_pool_bytes(r->name, nbytes, _RET_IP_);
  534. spin_lock_irqsave(&r->lock, flags);
  535. _mix_pool_bytes(r, in, nbytes);
  536. spin_unlock_irqrestore(&r->lock, flags);
  537. }
  538. struct fast_pool {
  539. __u32 pool[4];
  540. unsigned long last;
  541. unsigned short reg_idx;
  542. unsigned char count;
  543. };
  544. /*
  545. * This is a fast mixing routine used by the interrupt randomness
  546. * collector. It's hardcoded for an 128 bit pool and assumes that any
  547. * locks that might be needed are taken by the caller.
  548. */
  549. static void fast_mix(struct fast_pool *f)
  550. {
  551. __u32 a = f->pool[0], b = f->pool[1];
  552. __u32 c = f->pool[2], d = f->pool[3];
  553. a += b; c += d;
  554. b = rol32(b, 6); d = rol32(d, 27);
  555. d ^= a; b ^= c;
  556. a += b; c += d;
  557. b = rol32(b, 16); d = rol32(d, 14);
  558. d ^= a; b ^= c;
  559. a += b; c += d;
  560. b = rol32(b, 6); d = rol32(d, 27);
  561. d ^= a; b ^= c;
  562. a += b; c += d;
  563. b = rol32(b, 16); d = rol32(d, 14);
  564. d ^= a; b ^= c;
  565. f->pool[0] = a; f->pool[1] = b;
  566. f->pool[2] = c; f->pool[3] = d;
  567. f->count++;
  568. }
  569. static void process_random_ready_list(void)
  570. {
  571. unsigned long flags;
  572. struct random_ready_callback *rdy, *tmp;
  573. spin_lock_irqsave(&random_ready_list_lock, flags);
  574. list_for_each_entry_safe(rdy, tmp, &random_ready_list, list) {
  575. struct module *owner = rdy->owner;
  576. list_del_init(&rdy->list);
  577. rdy->func(rdy);
  578. module_put(owner);
  579. }
  580. spin_unlock_irqrestore(&random_ready_list_lock, flags);
  581. }
  582. /*
  583. * Credit (or debit) the entropy store with n bits of entropy.
  584. * Use credit_entropy_bits_safe() if the value comes from userspace
  585. * or otherwise should be checked for extreme values.
  586. */
  587. static void credit_entropy_bits(struct entropy_store *r, int nbits)
  588. {
  589. int entropy_count, orig;
  590. const int pool_size = r->poolinfo->poolfracbits;
  591. int nfrac = nbits << ENTROPY_SHIFT;
  592. if (!nbits)
  593. return;
  594. retry:
  595. entropy_count = orig = ACCESS_ONCE(r->entropy_count);
  596. if (nfrac < 0) {
  597. /* Debit */
  598. entropy_count += nfrac;
  599. } else {
  600. /*
  601. * Credit: we have to account for the possibility of
  602. * overwriting already present entropy. Even in the
  603. * ideal case of pure Shannon entropy, new contributions
  604. * approach the full value asymptotically:
  605. *
  606. * entropy <- entropy + (pool_size - entropy) *
  607. * (1 - exp(-add_entropy/pool_size))
  608. *
  609. * For add_entropy <= pool_size/2 then
  610. * (1 - exp(-add_entropy/pool_size)) >=
  611. * (add_entropy/pool_size)*0.7869...
  612. * so we can approximate the exponential with
  613. * 3/4*add_entropy/pool_size and still be on the
  614. * safe side by adding at most pool_size/2 at a time.
  615. *
  616. * The use of pool_size-2 in the while statement is to
  617. * prevent rounding artifacts from making the loop
  618. * arbitrarily long; this limits the loop to log2(pool_size)*2
  619. * turns no matter how large nbits is.
  620. */
  621. int pnfrac = nfrac;
  622. const int s = r->poolinfo->poolbitshift + ENTROPY_SHIFT + 2;
  623. /* The +2 corresponds to the /4 in the denominator */
  624. do {
  625. unsigned int anfrac = min(pnfrac, pool_size/2);
  626. unsigned int add =
  627. ((pool_size - entropy_count)*anfrac*3) >> s;
  628. entropy_count += add;
  629. pnfrac -= anfrac;
  630. } while (unlikely(entropy_count < pool_size-2 && pnfrac));
  631. }
  632. if (unlikely(entropy_count < 0)) {
  633. pr_warn("random: negative entropy/overflow: pool %s count %d\n",
  634. r->name, entropy_count);
  635. WARN_ON(1);
  636. entropy_count = 0;
  637. } else if (entropy_count > pool_size)
  638. entropy_count = pool_size;
  639. if (cmpxchg(&r->entropy_count, orig, entropy_count) != orig)
  640. goto retry;
  641. r->entropy_total += nbits;
  642. if (!r->initialized && r->entropy_total > 128) {
  643. r->initialized = 1;
  644. r->entropy_total = 0;
  645. }
  646. trace_credit_entropy_bits(r->name, nbits,
  647. entropy_count >> ENTROPY_SHIFT,
  648. r->entropy_total, _RET_IP_);
  649. if (r == &input_pool) {
  650. int entropy_bits = entropy_count >> ENTROPY_SHIFT;
  651. if (crng_init < 2 && entropy_bits >= 128) {
  652. crng_reseed(&primary_crng, r);
  653. entropy_bits = r->entropy_count >> ENTROPY_SHIFT;
  654. }
  655. /* should we wake readers? */
  656. if (entropy_bits >= random_read_wakeup_bits) {
  657. wake_up_interruptible(&random_read_wait);
  658. kill_fasync(&fasync, SIGIO, POLL_IN);
  659. }
  660. /* If the input pool is getting full, send some
  661. * entropy to the blocking pool until it is 75% full.
  662. */
  663. if (entropy_bits > random_write_wakeup_bits &&
  664. r->initialized &&
  665. r->entropy_total >= 2*random_read_wakeup_bits) {
  666. struct entropy_store *other = &blocking_pool;
  667. if (other->entropy_count <=
  668. 3 * other->poolinfo->poolfracbits / 4) {
  669. schedule_work(&other->push_work);
  670. r->entropy_total = 0;
  671. }
  672. }
  673. }
  674. }
  675. static int credit_entropy_bits_safe(struct entropy_store *r, int nbits)
  676. {
  677. const int nbits_max = (int)(~0U >> (ENTROPY_SHIFT + 1));
  678. if (nbits < 0)
  679. return -EINVAL;
  680. /* Cap the value to avoid overflows */
  681. nbits = min(nbits, nbits_max);
  682. credit_entropy_bits(r, nbits);
  683. return 0;
  684. }
  685. /*********************************************************************
  686. *
  687. * CRNG using CHACHA20
  688. *
  689. *********************************************************************/
  690. #define CRNG_RESEED_INTERVAL (300*HZ)
  691. static DECLARE_WAIT_QUEUE_HEAD(crng_init_wait);
  692. #ifdef CONFIG_NUMA
  693. /*
  694. * Hack to deal with crazy userspace progams when they are all trying
  695. * to access /dev/urandom in parallel. The programs are almost
  696. * certainly doing something terribly wrong, but we'll work around
  697. * their brain damage.
  698. */
  699. static struct crng_state **crng_node_pool __read_mostly;
  700. #endif
  701. static void crng_initialize(struct crng_state *crng)
  702. {
  703. int i;
  704. unsigned long rv;
  705. memcpy(&crng->state[0], "expand 32-byte k", 16);
  706. if (crng == &primary_crng)
  707. _extract_entropy(&input_pool, &crng->state[4],
  708. sizeof(__u32) * 12, 0);
  709. else
  710. get_random_bytes(&crng->state[4], sizeof(__u32) * 12);
  711. for (i = 4; i < 16; i++) {
  712. if (!arch_get_random_seed_long(&rv) &&
  713. !arch_get_random_long(&rv))
  714. rv = random_get_entropy();
  715. crng->state[i] ^= rv;
  716. }
  717. crng->init_time = jiffies - CRNG_RESEED_INTERVAL - 1;
  718. }
  719. static int crng_fast_load(const char *cp, size_t len)
  720. {
  721. unsigned long flags;
  722. char *p;
  723. if (!spin_trylock_irqsave(&primary_crng.lock, flags))
  724. return 0;
  725. if (crng_ready()) {
  726. spin_unlock_irqrestore(&primary_crng.lock, flags);
  727. return 0;
  728. }
  729. p = (unsigned char *) &primary_crng.state[4];
  730. while (len > 0 && crng_init_cnt < CRNG_INIT_CNT_THRESH) {
  731. p[crng_init_cnt % CHACHA20_KEY_SIZE] ^= *cp;
  732. cp++; crng_init_cnt++; len--;
  733. }
  734. if (crng_init_cnt >= CRNG_INIT_CNT_THRESH) {
  735. crng_init = 1;
  736. wake_up_interruptible(&crng_init_wait);
  737. pr_notice("random: fast init done\n");
  738. }
  739. spin_unlock_irqrestore(&primary_crng.lock, flags);
  740. return 1;
  741. }
  742. static void crng_reseed(struct crng_state *crng, struct entropy_store *r)
  743. {
  744. unsigned long flags;
  745. int i, num;
  746. union {
  747. __u8 block[CHACHA20_BLOCK_SIZE];
  748. __u32 key[8];
  749. } buf;
  750. if (r) {
  751. num = extract_entropy(r, &buf, 32, 16, 0);
  752. if (num == 0)
  753. return;
  754. } else {
  755. _extract_crng(&primary_crng, buf.block);
  756. _crng_backtrack_protect(&primary_crng, buf.block,
  757. CHACHA20_KEY_SIZE);
  758. }
  759. spin_lock_irqsave(&primary_crng.lock, flags);
  760. for (i = 0; i < 8; i++) {
  761. unsigned long rv;
  762. if (!arch_get_random_seed_long(&rv) &&
  763. !arch_get_random_long(&rv))
  764. rv = random_get_entropy();
  765. crng->state[i+4] ^= buf.key[i] ^ rv;
  766. }
  767. memzero_explicit(&buf, sizeof(buf));
  768. crng->init_time = jiffies;
  769. if (crng == &primary_crng && crng_init < 2) {
  770. crng_init = 2;
  771. process_random_ready_list();
  772. wake_up_interruptible(&crng_init_wait);
  773. pr_notice("random: crng init done\n");
  774. }
  775. spin_unlock_irqrestore(&primary_crng.lock, flags);
  776. }
  777. static inline void maybe_reseed_primary_crng(void)
  778. {
  779. if (crng_init > 2 &&
  780. time_after(jiffies, primary_crng.init_time + CRNG_RESEED_INTERVAL))
  781. crng_reseed(&primary_crng, &input_pool);
  782. }
  783. static inline void crng_wait_ready(void)
  784. {
  785. wait_event_interruptible(crng_init_wait, crng_ready());
  786. }
  787. static void _extract_crng(struct crng_state *crng,
  788. __u8 out[CHACHA20_BLOCK_SIZE])
  789. {
  790. unsigned long v, flags;
  791. if (crng_init > 1 &&
  792. time_after(jiffies, crng->init_time + CRNG_RESEED_INTERVAL))
  793. crng_reseed(crng, crng == &primary_crng ? &input_pool : NULL);
  794. spin_lock_irqsave(&crng->lock, flags);
  795. if (arch_get_random_long(&v))
  796. crng->state[14] ^= v;
  797. chacha20_block(&crng->state[0], out);
  798. if (crng->state[12] == 0)
  799. crng->state[13]++;
  800. spin_unlock_irqrestore(&crng->lock, flags);
  801. }
  802. static void extract_crng(__u8 out[CHACHA20_BLOCK_SIZE])
  803. {
  804. struct crng_state *crng = NULL;
  805. #ifdef CONFIG_NUMA
  806. if (crng_node_pool)
  807. crng = crng_node_pool[numa_node_id()];
  808. if (crng == NULL)
  809. #endif
  810. crng = &primary_crng;
  811. _extract_crng(crng, out);
  812. }
  813. /*
  814. * Use the leftover bytes from the CRNG block output (if there is
  815. * enough) to mutate the CRNG key to provide backtracking protection.
  816. */
  817. static void _crng_backtrack_protect(struct crng_state *crng,
  818. __u8 tmp[CHACHA20_BLOCK_SIZE], int used)
  819. {
  820. unsigned long flags;
  821. __u32 *s, *d;
  822. int i;
  823. used = round_up(used, sizeof(__u32));
  824. if (used + CHACHA20_KEY_SIZE > CHACHA20_BLOCK_SIZE) {
  825. extract_crng(tmp);
  826. used = 0;
  827. }
  828. spin_lock_irqsave(&crng->lock, flags);
  829. s = (__u32 *) &tmp[used];
  830. d = &crng->state[4];
  831. for (i=0; i < 8; i++)
  832. *d++ ^= *s++;
  833. spin_unlock_irqrestore(&crng->lock, flags);
  834. }
  835. static void crng_backtrack_protect(__u8 tmp[CHACHA20_BLOCK_SIZE], int used)
  836. {
  837. struct crng_state *crng = NULL;
  838. #ifdef CONFIG_NUMA
  839. if (crng_node_pool)
  840. crng = crng_node_pool[numa_node_id()];
  841. if (crng == NULL)
  842. #endif
  843. crng = &primary_crng;
  844. _crng_backtrack_protect(crng, tmp, used);
  845. }
  846. static ssize_t extract_crng_user(void __user *buf, size_t nbytes)
  847. {
  848. ssize_t ret = 0, i = CHACHA20_BLOCK_SIZE;
  849. __u8 tmp[CHACHA20_BLOCK_SIZE];
  850. int large_request = (nbytes > 256);
  851. while (nbytes) {
  852. if (large_request && need_resched()) {
  853. if (signal_pending(current)) {
  854. if (ret == 0)
  855. ret = -ERESTARTSYS;
  856. break;
  857. }
  858. schedule();
  859. }
  860. extract_crng(tmp);
  861. i = min_t(int, nbytes, CHACHA20_BLOCK_SIZE);
  862. if (copy_to_user(buf, tmp, i)) {
  863. ret = -EFAULT;
  864. break;
  865. }
  866. nbytes -= i;
  867. buf += i;
  868. ret += i;
  869. }
  870. crng_backtrack_protect(tmp, i);
  871. /* Wipe data just written to memory */
  872. memzero_explicit(tmp, sizeof(tmp));
  873. return ret;
  874. }
  875. /*********************************************************************
  876. *
  877. * Entropy input management
  878. *
  879. *********************************************************************/
  880. /* There is one of these per entropy source */
  881. struct timer_rand_state {
  882. cycles_t last_time;
  883. long last_delta, last_delta2;
  884. unsigned dont_count_entropy:1;
  885. };
  886. #define INIT_TIMER_RAND_STATE { INITIAL_JIFFIES, };
  887. /*
  888. * Add device- or boot-specific data to the input pool to help
  889. * initialize it.
  890. *
  891. * None of this adds any entropy; it is meant to avoid the problem of
  892. * the entropy pool having similar initial state across largely
  893. * identical devices.
  894. */
  895. void add_device_randomness(const void *buf, unsigned int size)
  896. {
  897. unsigned long time = random_get_entropy() ^ jiffies;
  898. unsigned long flags;
  899. trace_add_device_randomness(size, _RET_IP_);
  900. spin_lock_irqsave(&input_pool.lock, flags);
  901. _mix_pool_bytes(&input_pool, buf, size);
  902. _mix_pool_bytes(&input_pool, &time, sizeof(time));
  903. spin_unlock_irqrestore(&input_pool.lock, flags);
  904. }
  905. EXPORT_SYMBOL(add_device_randomness);
  906. static struct timer_rand_state input_timer_state = INIT_TIMER_RAND_STATE;
  907. /*
  908. * This function adds entropy to the entropy "pool" by using timing
  909. * delays. It uses the timer_rand_state structure to make an estimate
  910. * of how many bits of entropy this call has added to the pool.
  911. *
  912. * The number "num" is also added to the pool - it should somehow describe
  913. * the type of event which just happened. This is currently 0-255 for
  914. * keyboard scan codes, and 256 upwards for interrupts.
  915. *
  916. */
  917. static void add_timer_randomness(struct timer_rand_state *state, unsigned num)
  918. {
  919. struct entropy_store *r;
  920. struct {
  921. long jiffies;
  922. unsigned cycles;
  923. unsigned num;
  924. } sample;
  925. long delta, delta2, delta3;
  926. preempt_disable();
  927. sample.jiffies = jiffies;
  928. sample.cycles = random_get_entropy();
  929. sample.num = num;
  930. r = &input_pool;
  931. mix_pool_bytes(r, &sample, sizeof(sample));
  932. /*
  933. * Calculate number of bits of randomness we probably added.
  934. * We take into account the first, second and third-order deltas
  935. * in order to make our estimate.
  936. */
  937. if (!state->dont_count_entropy) {
  938. delta = sample.jiffies - state->last_time;
  939. state->last_time = sample.jiffies;
  940. delta2 = delta - state->last_delta;
  941. state->last_delta = delta;
  942. delta3 = delta2 - state->last_delta2;
  943. state->last_delta2 = delta2;
  944. if (delta < 0)
  945. delta = -delta;
  946. if (delta2 < 0)
  947. delta2 = -delta2;
  948. if (delta3 < 0)
  949. delta3 = -delta3;
  950. if (delta > delta2)
  951. delta = delta2;
  952. if (delta > delta3)
  953. delta = delta3;
  954. /*
  955. * delta is now minimum absolute delta.
  956. * Round down by 1 bit on general principles,
  957. * and limit entropy entimate to 12 bits.
  958. */
  959. credit_entropy_bits(r, min_t(int, fls(delta>>1), 11));
  960. }
  961. preempt_enable();
  962. }
  963. void add_input_randomness(unsigned int type, unsigned int code,
  964. unsigned int value)
  965. {
  966. static unsigned char last_value;
  967. /* ignore autorepeat and the like */
  968. if (value == last_value)
  969. return;
  970. last_value = value;
  971. add_timer_randomness(&input_timer_state,
  972. (type << 4) ^ code ^ (code >> 4) ^ value);
  973. trace_add_input_randomness(ENTROPY_BITS(&input_pool));
  974. }
  975. EXPORT_SYMBOL_GPL(add_input_randomness);
  976. static DEFINE_PER_CPU(struct fast_pool, irq_randomness);
  977. #ifdef ADD_INTERRUPT_BENCH
  978. static unsigned long avg_cycles, avg_deviation;
  979. #define AVG_SHIFT 8 /* Exponential average factor k=1/256 */
  980. #define FIXED_1_2 (1 << (AVG_SHIFT-1))
  981. static void add_interrupt_bench(cycles_t start)
  982. {
  983. long delta = random_get_entropy() - start;
  984. /* Use a weighted moving average */
  985. delta = delta - ((avg_cycles + FIXED_1_2) >> AVG_SHIFT);
  986. avg_cycles += delta;
  987. /* And average deviation */
  988. delta = abs(delta) - ((avg_deviation + FIXED_1_2) >> AVG_SHIFT);
  989. avg_deviation += delta;
  990. }
  991. #else
  992. #define add_interrupt_bench(x)
  993. #endif
  994. static __u32 get_reg(struct fast_pool *f, struct pt_regs *regs)
  995. {
  996. __u32 *ptr = (__u32 *) regs;
  997. if (regs == NULL)
  998. return 0;
  999. if (f->reg_idx >= sizeof(struct pt_regs) / sizeof(__u32))
  1000. f->reg_idx = 0;
  1001. return *(ptr + f->reg_idx++);
  1002. }
  1003. void add_interrupt_randomness(int irq, int irq_flags)
  1004. {
  1005. struct entropy_store *r;
  1006. struct fast_pool *fast_pool = this_cpu_ptr(&irq_randomness);
  1007. struct pt_regs *regs = get_irq_regs();
  1008. unsigned long now = jiffies;
  1009. cycles_t cycles = random_get_entropy();
  1010. __u32 c_high, j_high;
  1011. __u64 ip;
  1012. unsigned long seed;
  1013. int credit = 0;
  1014. if (cycles == 0)
  1015. cycles = get_reg(fast_pool, regs);
  1016. c_high = (sizeof(cycles) > 4) ? cycles >> 32 : 0;
  1017. j_high = (sizeof(now) > 4) ? now >> 32 : 0;
  1018. fast_pool->pool[0] ^= cycles ^ j_high ^ irq;
  1019. fast_pool->pool[1] ^= now ^ c_high;
  1020. ip = regs ? instruction_pointer(regs) : _RET_IP_;
  1021. fast_pool->pool[2] ^= ip;
  1022. fast_pool->pool[3] ^= (sizeof(ip) > 4) ? ip >> 32 :
  1023. get_reg(fast_pool, regs);
  1024. fast_mix(fast_pool);
  1025. add_interrupt_bench(cycles);
  1026. if (!crng_ready()) {
  1027. if ((fast_pool->count >= 64) &&
  1028. crng_fast_load((char *) fast_pool->pool,
  1029. sizeof(fast_pool->pool))) {
  1030. fast_pool->count = 0;
  1031. fast_pool->last = now;
  1032. }
  1033. return;
  1034. }
  1035. if ((fast_pool->count < 64) &&
  1036. !time_after(now, fast_pool->last + HZ))
  1037. return;
  1038. r = &input_pool;
  1039. if (!spin_trylock(&r->lock))
  1040. return;
  1041. fast_pool->last = now;
  1042. __mix_pool_bytes(r, &fast_pool->pool, sizeof(fast_pool->pool));
  1043. /*
  1044. * If we have architectural seed generator, produce a seed and
  1045. * add it to the pool. For the sake of paranoia don't let the
  1046. * architectural seed generator dominate the input from the
  1047. * interrupt noise.
  1048. */
  1049. if (arch_get_random_seed_long(&seed)) {
  1050. __mix_pool_bytes(r, &seed, sizeof(seed));
  1051. credit = 1;
  1052. }
  1053. spin_unlock(&r->lock);
  1054. fast_pool->count = 0;
  1055. /* award one bit for the contents of the fast pool */
  1056. credit_entropy_bits(r, credit + 1);
  1057. }
  1058. EXPORT_SYMBOL_GPL(add_interrupt_randomness);
  1059. #ifdef CONFIG_BLOCK
  1060. void add_disk_randomness(struct gendisk *disk)
  1061. {
  1062. if (!disk || !disk->random)
  1063. return;
  1064. /* first major is 1, so we get >= 0x200 here */
  1065. add_timer_randomness(disk->random, 0x100 + disk_devt(disk));
  1066. trace_add_disk_randomness(disk_devt(disk), ENTROPY_BITS(&input_pool));
  1067. }
  1068. EXPORT_SYMBOL_GPL(add_disk_randomness);
  1069. #endif
  1070. /*********************************************************************
  1071. *
  1072. * Entropy extraction routines
  1073. *
  1074. *********************************************************************/
  1075. /*
  1076. * This utility inline function is responsible for transferring entropy
  1077. * from the primary pool to the secondary extraction pool. We make
  1078. * sure we pull enough for a 'catastrophic reseed'.
  1079. */
  1080. static void _xfer_secondary_pool(struct entropy_store *r, size_t nbytes);
  1081. static void xfer_secondary_pool(struct entropy_store *r, size_t nbytes)
  1082. {
  1083. if (!r->pull ||
  1084. r->entropy_count >= (nbytes << (ENTROPY_SHIFT + 3)) ||
  1085. r->entropy_count > r->poolinfo->poolfracbits)
  1086. return;
  1087. if (r->limit == 0 && random_min_urandom_seed) {
  1088. unsigned long now = jiffies;
  1089. if (time_before(now,
  1090. r->last_pulled + random_min_urandom_seed * HZ))
  1091. return;
  1092. r->last_pulled = now;
  1093. }
  1094. _xfer_secondary_pool(r, nbytes);
  1095. }
  1096. static void _xfer_secondary_pool(struct entropy_store *r, size_t nbytes)
  1097. {
  1098. __u32 tmp[OUTPUT_POOL_WORDS];
  1099. /* For /dev/random's pool, always leave two wakeups' worth */
  1100. int rsvd_bytes = r->limit ? 0 : random_read_wakeup_bits / 4;
  1101. int bytes = nbytes;
  1102. /* pull at least as much as a wakeup */
  1103. bytes = max_t(int, bytes, random_read_wakeup_bits / 8);
  1104. /* but never more than the buffer size */
  1105. bytes = min_t(int, bytes, sizeof(tmp));
  1106. trace_xfer_secondary_pool(r->name, bytes * 8, nbytes * 8,
  1107. ENTROPY_BITS(r), ENTROPY_BITS(r->pull));
  1108. bytes = extract_entropy(r->pull, tmp, bytes,
  1109. random_read_wakeup_bits / 8, rsvd_bytes);
  1110. mix_pool_bytes(r, tmp, bytes);
  1111. credit_entropy_bits(r, bytes*8);
  1112. }
  1113. /*
  1114. * Used as a workqueue function so that when the input pool is getting
  1115. * full, we can "spill over" some entropy to the output pools. That
  1116. * way the output pools can store some of the excess entropy instead
  1117. * of letting it go to waste.
  1118. */
  1119. static void push_to_pool(struct work_struct *work)
  1120. {
  1121. struct entropy_store *r = container_of(work, struct entropy_store,
  1122. push_work);
  1123. BUG_ON(!r);
  1124. _xfer_secondary_pool(r, random_read_wakeup_bits/8);
  1125. trace_push_to_pool(r->name, r->entropy_count >> ENTROPY_SHIFT,
  1126. r->pull->entropy_count >> ENTROPY_SHIFT);
  1127. }
  1128. /*
  1129. * This function decides how many bytes to actually take from the
  1130. * given pool, and also debits the entropy count accordingly.
  1131. */
  1132. static size_t account(struct entropy_store *r, size_t nbytes, int min,
  1133. int reserved)
  1134. {
  1135. int entropy_count, orig;
  1136. size_t ibytes, nfrac;
  1137. BUG_ON(r->entropy_count > r->poolinfo->poolfracbits);
  1138. /* Can we pull enough? */
  1139. retry:
  1140. entropy_count = orig = ACCESS_ONCE(r->entropy_count);
  1141. ibytes = nbytes;
  1142. /* If limited, never pull more than available */
  1143. if (r->limit) {
  1144. int have_bytes = entropy_count >> (ENTROPY_SHIFT + 3);
  1145. if ((have_bytes -= reserved) < 0)
  1146. have_bytes = 0;
  1147. ibytes = min_t(size_t, ibytes, have_bytes);
  1148. }
  1149. if (ibytes < min)
  1150. ibytes = 0;
  1151. if (unlikely(entropy_count < 0)) {
  1152. pr_warn("random: negative entropy count: pool %s count %d\n",
  1153. r->name, entropy_count);
  1154. WARN_ON(1);
  1155. entropy_count = 0;
  1156. }
  1157. nfrac = ibytes << (ENTROPY_SHIFT + 3);
  1158. if ((size_t) entropy_count > nfrac)
  1159. entropy_count -= nfrac;
  1160. else
  1161. entropy_count = 0;
  1162. if (cmpxchg(&r->entropy_count, orig, entropy_count) != orig)
  1163. goto retry;
  1164. trace_debit_entropy(r->name, 8 * ibytes);
  1165. if (ibytes &&
  1166. (r->entropy_count >> ENTROPY_SHIFT) < random_write_wakeup_bits) {
  1167. wake_up_interruptible(&random_write_wait);
  1168. kill_fasync(&fasync, SIGIO, POLL_OUT);
  1169. }
  1170. return ibytes;
  1171. }
  1172. /*
  1173. * This function does the actual extraction for extract_entropy and
  1174. * extract_entropy_user.
  1175. *
  1176. * Note: we assume that .poolwords is a multiple of 16 words.
  1177. */
  1178. static void extract_buf(struct entropy_store *r, __u8 *out)
  1179. {
  1180. int i;
  1181. union {
  1182. __u32 w[5];
  1183. unsigned long l[LONGS(20)];
  1184. } hash;
  1185. __u32 workspace[SHA_WORKSPACE_WORDS];
  1186. unsigned long flags;
  1187. /*
  1188. * If we have an architectural hardware random number
  1189. * generator, use it for SHA's initial vector
  1190. */
  1191. sha_init(hash.w);
  1192. for (i = 0; i < LONGS(20); i++) {
  1193. unsigned long v;
  1194. if (!arch_get_random_long(&v))
  1195. break;
  1196. hash.l[i] = v;
  1197. }
  1198. /* Generate a hash across the pool, 16 words (512 bits) at a time */
  1199. spin_lock_irqsave(&r->lock, flags);
  1200. for (i = 0; i < r->poolinfo->poolwords; i += 16)
  1201. sha_transform(hash.w, (__u8 *)(r->pool + i), workspace);
  1202. /*
  1203. * We mix the hash back into the pool to prevent backtracking
  1204. * attacks (where the attacker knows the state of the pool
  1205. * plus the current outputs, and attempts to find previous
  1206. * ouputs), unless the hash function can be inverted. By
  1207. * mixing at least a SHA1 worth of hash data back, we make
  1208. * brute-forcing the feedback as hard as brute-forcing the
  1209. * hash.
  1210. */
  1211. __mix_pool_bytes(r, hash.w, sizeof(hash.w));
  1212. spin_unlock_irqrestore(&r->lock, flags);
  1213. memzero_explicit(workspace, sizeof(workspace));
  1214. /*
  1215. * In case the hash function has some recognizable output
  1216. * pattern, we fold it in half. Thus, we always feed back
  1217. * twice as much data as we output.
  1218. */
  1219. hash.w[0] ^= hash.w[3];
  1220. hash.w[1] ^= hash.w[4];
  1221. hash.w[2] ^= rol32(hash.w[2], 16);
  1222. memcpy(out, &hash, EXTRACT_SIZE);
  1223. memzero_explicit(&hash, sizeof(hash));
  1224. }
  1225. static ssize_t _extract_entropy(struct entropy_store *r, void *buf,
  1226. size_t nbytes, int fips)
  1227. {
  1228. ssize_t ret = 0, i;
  1229. __u8 tmp[EXTRACT_SIZE];
  1230. unsigned long flags;
  1231. while (nbytes) {
  1232. extract_buf(r, tmp);
  1233. if (fips) {
  1234. spin_lock_irqsave(&r->lock, flags);
  1235. if (!memcmp(tmp, r->last_data, EXTRACT_SIZE))
  1236. panic("Hardware RNG duplicated output!\n");
  1237. memcpy(r->last_data, tmp, EXTRACT_SIZE);
  1238. spin_unlock_irqrestore(&r->lock, flags);
  1239. }
  1240. i = min_t(int, nbytes, EXTRACT_SIZE);
  1241. memcpy(buf, tmp, i);
  1242. nbytes -= i;
  1243. buf += i;
  1244. ret += i;
  1245. }
  1246. /* Wipe data just returned from memory */
  1247. memzero_explicit(tmp, sizeof(tmp));
  1248. return ret;
  1249. }
  1250. /*
  1251. * This function extracts randomness from the "entropy pool", and
  1252. * returns it in a buffer.
  1253. *
  1254. * The min parameter specifies the minimum amount we can pull before
  1255. * failing to avoid races that defeat catastrophic reseeding while the
  1256. * reserved parameter indicates how much entropy we must leave in the
  1257. * pool after each pull to avoid starving other readers.
  1258. */
  1259. static ssize_t extract_entropy(struct entropy_store *r, void *buf,
  1260. size_t nbytes, int min, int reserved)
  1261. {
  1262. __u8 tmp[EXTRACT_SIZE];
  1263. unsigned long flags;
  1264. /* if last_data isn't primed, we need EXTRACT_SIZE extra bytes */
  1265. if (fips_enabled) {
  1266. spin_lock_irqsave(&r->lock, flags);
  1267. if (!r->last_data_init) {
  1268. r->last_data_init = 1;
  1269. spin_unlock_irqrestore(&r->lock, flags);
  1270. trace_extract_entropy(r->name, EXTRACT_SIZE,
  1271. ENTROPY_BITS(r), _RET_IP_);
  1272. xfer_secondary_pool(r, EXTRACT_SIZE);
  1273. extract_buf(r, tmp);
  1274. spin_lock_irqsave(&r->lock, flags);
  1275. memcpy(r->last_data, tmp, EXTRACT_SIZE);
  1276. }
  1277. spin_unlock_irqrestore(&r->lock, flags);
  1278. }
  1279. trace_extract_entropy(r->name, nbytes, ENTROPY_BITS(r), _RET_IP_);
  1280. xfer_secondary_pool(r, nbytes);
  1281. nbytes = account(r, nbytes, min, reserved);
  1282. return _extract_entropy(r, buf, nbytes, fips_enabled);
  1283. }
  1284. /*
  1285. * This function extracts randomness from the "entropy pool", and
  1286. * returns it in a userspace buffer.
  1287. */
  1288. static ssize_t extract_entropy_user(struct entropy_store *r, void __user *buf,
  1289. size_t nbytes)
  1290. {
  1291. ssize_t ret = 0, i;
  1292. __u8 tmp[EXTRACT_SIZE];
  1293. int large_request = (nbytes > 256);
  1294. trace_extract_entropy_user(r->name, nbytes, ENTROPY_BITS(r), _RET_IP_);
  1295. xfer_secondary_pool(r, nbytes);
  1296. nbytes = account(r, nbytes, 0, 0);
  1297. while (nbytes) {
  1298. if (large_request && need_resched()) {
  1299. if (signal_pending(current)) {
  1300. if (ret == 0)
  1301. ret = -ERESTARTSYS;
  1302. break;
  1303. }
  1304. schedule();
  1305. }
  1306. extract_buf(r, tmp);
  1307. i = min_t(int, nbytes, EXTRACT_SIZE);
  1308. if (copy_to_user(buf, tmp, i)) {
  1309. ret = -EFAULT;
  1310. break;
  1311. }
  1312. nbytes -= i;
  1313. buf += i;
  1314. ret += i;
  1315. }
  1316. /* Wipe data just returned from memory */
  1317. memzero_explicit(tmp, sizeof(tmp));
  1318. return ret;
  1319. }
  1320. /*
  1321. * This function is the exported kernel interface. It returns some
  1322. * number of good random numbers, suitable for key generation, seeding
  1323. * TCP sequence numbers, etc. It does not rely on the hardware random
  1324. * number generator. For random bytes direct from the hardware RNG
  1325. * (when available), use get_random_bytes_arch().
  1326. */
  1327. void get_random_bytes(void *buf, int nbytes)
  1328. {
  1329. __u8 tmp[CHACHA20_BLOCK_SIZE];
  1330. #if DEBUG_RANDOM_BOOT > 0
  1331. if (!crng_ready())
  1332. printk(KERN_NOTICE "random: %pF get_random_bytes called "
  1333. "with crng_init = %d\n", (void *) _RET_IP_, crng_init);
  1334. #endif
  1335. trace_get_random_bytes(nbytes, _RET_IP_);
  1336. while (nbytes >= CHACHA20_BLOCK_SIZE) {
  1337. extract_crng(buf);
  1338. buf += CHACHA20_BLOCK_SIZE;
  1339. nbytes -= CHACHA20_BLOCK_SIZE;
  1340. }
  1341. if (nbytes > 0) {
  1342. extract_crng(tmp);
  1343. memcpy(buf, tmp, nbytes);
  1344. crng_backtrack_protect(tmp, nbytes);
  1345. } else
  1346. crng_backtrack_protect(tmp, CHACHA20_BLOCK_SIZE);
  1347. memzero_explicit(tmp, sizeof(tmp));
  1348. }
  1349. EXPORT_SYMBOL(get_random_bytes);
  1350. /*
  1351. * Add a callback function that will be invoked when the nonblocking
  1352. * pool is initialised.
  1353. *
  1354. * returns: 0 if callback is successfully added
  1355. * -EALREADY if pool is already initialised (callback not called)
  1356. * -ENOENT if module for callback is not alive
  1357. */
  1358. int add_random_ready_callback(struct random_ready_callback *rdy)
  1359. {
  1360. struct module *owner;
  1361. unsigned long flags;
  1362. int err = -EALREADY;
  1363. if (crng_ready())
  1364. return err;
  1365. owner = rdy->owner;
  1366. if (!try_module_get(owner))
  1367. return -ENOENT;
  1368. spin_lock_irqsave(&random_ready_list_lock, flags);
  1369. if (crng_ready())
  1370. goto out;
  1371. owner = NULL;
  1372. list_add(&rdy->list, &random_ready_list);
  1373. err = 0;
  1374. out:
  1375. spin_unlock_irqrestore(&random_ready_list_lock, flags);
  1376. module_put(owner);
  1377. return err;
  1378. }
  1379. EXPORT_SYMBOL(add_random_ready_callback);
  1380. /*
  1381. * Delete a previously registered readiness callback function.
  1382. */
  1383. void del_random_ready_callback(struct random_ready_callback *rdy)
  1384. {
  1385. unsigned long flags;
  1386. struct module *owner = NULL;
  1387. spin_lock_irqsave(&random_ready_list_lock, flags);
  1388. if (!list_empty(&rdy->list)) {
  1389. list_del_init(&rdy->list);
  1390. owner = rdy->owner;
  1391. }
  1392. spin_unlock_irqrestore(&random_ready_list_lock, flags);
  1393. module_put(owner);
  1394. }
  1395. EXPORT_SYMBOL(del_random_ready_callback);
  1396. /*
  1397. * This function will use the architecture-specific hardware random
  1398. * number generator if it is available. The arch-specific hw RNG will
  1399. * almost certainly be faster than what we can do in software, but it
  1400. * is impossible to verify that it is implemented securely (as
  1401. * opposed, to, say, the AES encryption of a sequence number using a
  1402. * key known by the NSA). So it's useful if we need the speed, but
  1403. * only if we're willing to trust the hardware manufacturer not to
  1404. * have put in a back door.
  1405. */
  1406. void get_random_bytes_arch(void *buf, int nbytes)
  1407. {
  1408. char *p = buf;
  1409. trace_get_random_bytes_arch(nbytes, _RET_IP_);
  1410. while (nbytes) {
  1411. unsigned long v;
  1412. int chunk = min(nbytes, (int)sizeof(unsigned long));
  1413. if (!arch_get_random_long(&v))
  1414. break;
  1415. memcpy(p, &v, chunk);
  1416. p += chunk;
  1417. nbytes -= chunk;
  1418. }
  1419. if (nbytes)
  1420. get_random_bytes(p, nbytes);
  1421. }
  1422. EXPORT_SYMBOL(get_random_bytes_arch);
  1423. /*
  1424. * init_std_data - initialize pool with system data
  1425. *
  1426. * @r: pool to initialize
  1427. *
  1428. * This function clears the pool's entropy count and mixes some system
  1429. * data into the pool to prepare it for use. The pool is not cleared
  1430. * as that can only decrease the entropy in the pool.
  1431. */
  1432. static void init_std_data(struct entropy_store *r)
  1433. {
  1434. int i;
  1435. ktime_t now = ktime_get_real();
  1436. unsigned long rv;
  1437. r->last_pulled = jiffies;
  1438. mix_pool_bytes(r, &now, sizeof(now));
  1439. for (i = r->poolinfo->poolbytes; i > 0; i -= sizeof(rv)) {
  1440. if (!arch_get_random_seed_long(&rv) &&
  1441. !arch_get_random_long(&rv))
  1442. rv = random_get_entropy();
  1443. mix_pool_bytes(r, &rv, sizeof(rv));
  1444. }
  1445. mix_pool_bytes(r, utsname(), sizeof(*(utsname())));
  1446. }
  1447. /*
  1448. * Note that setup_arch() may call add_device_randomness()
  1449. * long before we get here. This allows seeding of the pools
  1450. * with some platform dependent data very early in the boot
  1451. * process. But it limits our options here. We must use
  1452. * statically allocated structures that already have all
  1453. * initializations complete at compile time. We should also
  1454. * take care not to overwrite the precious per platform data
  1455. * we were given.
  1456. */
  1457. static int rand_initialize(void)
  1458. {
  1459. #ifdef CONFIG_NUMA
  1460. int i;
  1461. struct crng_state *crng;
  1462. struct crng_state **pool;
  1463. #endif
  1464. init_std_data(&input_pool);
  1465. init_std_data(&blocking_pool);
  1466. crng_initialize(&primary_crng);
  1467. #ifdef CONFIG_NUMA
  1468. pool = kcalloc(nr_node_ids, sizeof(*pool), GFP_KERNEL|__GFP_NOFAIL);
  1469. for_each_online_node(i) {
  1470. crng = kmalloc_node(sizeof(struct crng_state),
  1471. GFP_KERNEL | __GFP_NOFAIL, i);
  1472. spin_lock_init(&crng->lock);
  1473. crng_initialize(crng);
  1474. pool[i] = crng;
  1475. }
  1476. mb();
  1477. crng_node_pool = pool;
  1478. #endif
  1479. return 0;
  1480. }
  1481. early_initcall(rand_initialize);
  1482. #ifdef CONFIG_BLOCK
  1483. void rand_initialize_disk(struct gendisk *disk)
  1484. {
  1485. struct timer_rand_state *state;
  1486. /*
  1487. * If kzalloc returns null, we just won't use that entropy
  1488. * source.
  1489. */
  1490. state = kzalloc(sizeof(struct timer_rand_state), GFP_KERNEL);
  1491. if (state) {
  1492. state->last_time = INITIAL_JIFFIES;
  1493. disk->random = state;
  1494. }
  1495. }
  1496. #endif
  1497. static ssize_t
  1498. _random_read(int nonblock, char __user *buf, size_t nbytes)
  1499. {
  1500. ssize_t n;
  1501. if (nbytes == 0)
  1502. return 0;
  1503. nbytes = min_t(size_t, nbytes, SEC_XFER_SIZE);
  1504. while (1) {
  1505. n = extract_entropy_user(&blocking_pool, buf, nbytes);
  1506. if (n < 0)
  1507. return n;
  1508. trace_random_read(n*8, (nbytes-n)*8,
  1509. ENTROPY_BITS(&blocking_pool),
  1510. ENTROPY_BITS(&input_pool));
  1511. if (n > 0)
  1512. return n;
  1513. /* Pool is (near) empty. Maybe wait and retry. */
  1514. if (nonblock)
  1515. return -EAGAIN;
  1516. wait_event_interruptible(random_read_wait,
  1517. ENTROPY_BITS(&input_pool) >=
  1518. random_read_wakeup_bits);
  1519. if (signal_pending(current))
  1520. return -ERESTARTSYS;
  1521. }
  1522. }
  1523. static ssize_t
  1524. random_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
  1525. {
  1526. return _random_read(file->f_flags & O_NONBLOCK, buf, nbytes);
  1527. }
  1528. static ssize_t
  1529. urandom_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
  1530. {
  1531. unsigned long flags;
  1532. static int maxwarn = 10;
  1533. int ret;
  1534. if (!crng_ready() && maxwarn > 0) {
  1535. maxwarn--;
  1536. printk(KERN_NOTICE "random: %s: uninitialized urandom read "
  1537. "(%zd bytes read)\n",
  1538. current->comm, nbytes);
  1539. spin_lock_irqsave(&primary_crng.lock, flags);
  1540. crng_init_cnt = 0;
  1541. spin_unlock_irqrestore(&primary_crng.lock, flags);
  1542. }
  1543. nbytes = min_t(size_t, nbytes, INT_MAX >> (ENTROPY_SHIFT + 3));
  1544. ret = extract_crng_user(buf, nbytes);
  1545. trace_urandom_read(8 * nbytes, 0, ENTROPY_BITS(&input_pool));
  1546. return ret;
  1547. }
  1548. static unsigned int
  1549. random_poll(struct file *file, poll_table * wait)
  1550. {
  1551. unsigned int mask;
  1552. poll_wait(file, &random_read_wait, wait);
  1553. poll_wait(file, &random_write_wait, wait);
  1554. mask = 0;
  1555. if (ENTROPY_BITS(&input_pool) >= random_read_wakeup_bits)
  1556. mask |= POLLIN | POLLRDNORM;
  1557. if (ENTROPY_BITS(&input_pool) < random_write_wakeup_bits)
  1558. mask |= POLLOUT | POLLWRNORM;
  1559. return mask;
  1560. }
  1561. static int
  1562. write_pool(struct entropy_store *r, const char __user *buffer, size_t count)
  1563. {
  1564. size_t bytes;
  1565. __u32 buf[16];
  1566. const char __user *p = buffer;
  1567. while (count > 0) {
  1568. bytes = min(count, sizeof(buf));
  1569. if (copy_from_user(&buf, p, bytes))
  1570. return -EFAULT;
  1571. count -= bytes;
  1572. p += bytes;
  1573. mix_pool_bytes(r, buf, bytes);
  1574. cond_resched();
  1575. }
  1576. return 0;
  1577. }
  1578. static ssize_t random_write(struct file *file, const char __user *buffer,
  1579. size_t count, loff_t *ppos)
  1580. {
  1581. size_t ret;
  1582. ret = write_pool(&input_pool, buffer, count);
  1583. if (ret)
  1584. return ret;
  1585. return (ssize_t)count;
  1586. }
  1587. static long random_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
  1588. {
  1589. int size, ent_count;
  1590. int __user *p = (int __user *)arg;
  1591. int retval;
  1592. switch (cmd) {
  1593. case RNDGETENTCNT:
  1594. /* inherently racy, no point locking */
  1595. ent_count = ENTROPY_BITS(&input_pool);
  1596. if (put_user(ent_count, p))
  1597. return -EFAULT;
  1598. return 0;
  1599. case RNDADDTOENTCNT:
  1600. if (!capable(CAP_SYS_ADMIN))
  1601. return -EPERM;
  1602. if (get_user(ent_count, p))
  1603. return -EFAULT;
  1604. return credit_entropy_bits_safe(&input_pool, ent_count);
  1605. case RNDADDENTROPY:
  1606. if (!capable(CAP_SYS_ADMIN))
  1607. return -EPERM;
  1608. if (get_user(ent_count, p++))
  1609. return -EFAULT;
  1610. if (ent_count < 0)
  1611. return -EINVAL;
  1612. if (get_user(size, p++))
  1613. return -EFAULT;
  1614. retval = write_pool(&input_pool, (const char __user *)p,
  1615. size);
  1616. if (retval < 0)
  1617. return retval;
  1618. return credit_entropy_bits_safe(&input_pool, ent_count);
  1619. case RNDZAPENTCNT:
  1620. case RNDCLEARPOOL:
  1621. /*
  1622. * Clear the entropy pool counters. We no longer clear
  1623. * the entropy pool, as that's silly.
  1624. */
  1625. if (!capable(CAP_SYS_ADMIN))
  1626. return -EPERM;
  1627. input_pool.entropy_count = 0;
  1628. blocking_pool.entropy_count = 0;
  1629. return 0;
  1630. default:
  1631. return -EINVAL;
  1632. }
  1633. }
  1634. static int random_fasync(int fd, struct file *filp, int on)
  1635. {
  1636. return fasync_helper(fd, filp, on, &fasync);
  1637. }
  1638. const struct file_operations random_fops = {
  1639. .read = random_read,
  1640. .write = random_write,
  1641. .poll = random_poll,
  1642. .unlocked_ioctl = random_ioctl,
  1643. .fasync = random_fasync,
  1644. .llseek = noop_llseek,
  1645. };
  1646. const struct file_operations urandom_fops = {
  1647. .read = urandom_read,
  1648. .write = random_write,
  1649. .unlocked_ioctl = random_ioctl,
  1650. .fasync = random_fasync,
  1651. .llseek = noop_llseek,
  1652. };
  1653. SYSCALL_DEFINE3(getrandom, char __user *, buf, size_t, count,
  1654. unsigned int, flags)
  1655. {
  1656. if (flags & ~(GRND_NONBLOCK|GRND_RANDOM))
  1657. return -EINVAL;
  1658. if (count > INT_MAX)
  1659. count = INT_MAX;
  1660. if (flags & GRND_RANDOM)
  1661. return _random_read(flags & GRND_NONBLOCK, buf, count);
  1662. if (!crng_ready()) {
  1663. if (flags & GRND_NONBLOCK)
  1664. return -EAGAIN;
  1665. crng_wait_ready();
  1666. if (signal_pending(current))
  1667. return -ERESTARTSYS;
  1668. }
  1669. return urandom_read(NULL, buf, count, NULL);
  1670. }
  1671. /********************************************************************
  1672. *
  1673. * Sysctl interface
  1674. *
  1675. ********************************************************************/
  1676. #ifdef CONFIG_SYSCTL
  1677. #include <linux/sysctl.h>
  1678. static int min_read_thresh = 8, min_write_thresh;
  1679. static int max_read_thresh = OUTPUT_POOL_WORDS * 32;
  1680. static int max_write_thresh = INPUT_POOL_WORDS * 32;
  1681. static char sysctl_bootid[16];
  1682. /*
  1683. * This function is used to return both the bootid UUID, and random
  1684. * UUID. The difference is in whether table->data is NULL; if it is,
  1685. * then a new UUID is generated and returned to the user.
  1686. *
  1687. * If the user accesses this via the proc interface, the UUID will be
  1688. * returned as an ASCII string in the standard UUID format; if via the
  1689. * sysctl system call, as 16 bytes of binary data.
  1690. */
  1691. static int proc_do_uuid(struct ctl_table *table, int write,
  1692. void __user *buffer, size_t *lenp, loff_t *ppos)
  1693. {
  1694. struct ctl_table fake_table;
  1695. unsigned char buf[64], tmp_uuid[16], *uuid;
  1696. uuid = table->data;
  1697. if (!uuid) {
  1698. uuid = tmp_uuid;
  1699. generate_random_uuid(uuid);
  1700. } else {
  1701. static DEFINE_SPINLOCK(bootid_spinlock);
  1702. spin_lock(&bootid_spinlock);
  1703. if (!uuid[8])
  1704. generate_random_uuid(uuid);
  1705. spin_unlock(&bootid_spinlock);
  1706. }
  1707. sprintf(buf, "%pU", uuid);
  1708. fake_table.data = buf;
  1709. fake_table.maxlen = sizeof(buf);
  1710. return proc_dostring(&fake_table, write, buffer, lenp, ppos);
  1711. }
  1712. /*
  1713. * Return entropy available scaled to integral bits
  1714. */
  1715. static int proc_do_entropy(struct ctl_table *table, int write,
  1716. void __user *buffer, size_t *lenp, loff_t *ppos)
  1717. {
  1718. struct ctl_table fake_table;
  1719. int entropy_count;
  1720. entropy_count = *(int *)table->data >> ENTROPY_SHIFT;
  1721. fake_table.data = &entropy_count;
  1722. fake_table.maxlen = sizeof(entropy_count);
  1723. return proc_dointvec(&fake_table, write, buffer, lenp, ppos);
  1724. }
  1725. static int sysctl_poolsize = INPUT_POOL_WORDS * 32;
  1726. extern struct ctl_table random_table[];
  1727. struct ctl_table random_table[] = {
  1728. {
  1729. .procname = "poolsize",
  1730. .data = &sysctl_poolsize,
  1731. .maxlen = sizeof(int),
  1732. .mode = 0444,
  1733. .proc_handler = proc_dointvec,
  1734. },
  1735. {
  1736. .procname = "entropy_avail",
  1737. .maxlen = sizeof(int),
  1738. .mode = 0444,
  1739. .proc_handler = proc_do_entropy,
  1740. .data = &input_pool.entropy_count,
  1741. },
  1742. {
  1743. .procname = "read_wakeup_threshold",
  1744. .data = &random_read_wakeup_bits,
  1745. .maxlen = sizeof(int),
  1746. .mode = 0644,
  1747. .proc_handler = proc_dointvec_minmax,
  1748. .extra1 = &min_read_thresh,
  1749. .extra2 = &max_read_thresh,
  1750. },
  1751. {
  1752. .procname = "write_wakeup_threshold",
  1753. .data = &random_write_wakeup_bits,
  1754. .maxlen = sizeof(int),
  1755. .mode = 0644,
  1756. .proc_handler = proc_dointvec_minmax,
  1757. .extra1 = &min_write_thresh,
  1758. .extra2 = &max_write_thresh,
  1759. },
  1760. {
  1761. .procname = "urandom_min_reseed_secs",
  1762. .data = &random_min_urandom_seed,
  1763. .maxlen = sizeof(int),
  1764. .mode = 0644,
  1765. .proc_handler = proc_dointvec,
  1766. },
  1767. {
  1768. .procname = "boot_id",
  1769. .data = &sysctl_bootid,
  1770. .maxlen = 16,
  1771. .mode = 0444,
  1772. .proc_handler = proc_do_uuid,
  1773. },
  1774. {
  1775. .procname = "uuid",
  1776. .maxlen = 16,
  1777. .mode = 0444,
  1778. .proc_handler = proc_do_uuid,
  1779. },
  1780. #ifdef ADD_INTERRUPT_BENCH
  1781. {
  1782. .procname = "add_interrupt_avg_cycles",
  1783. .data = &avg_cycles,
  1784. .maxlen = sizeof(avg_cycles),
  1785. .mode = 0444,
  1786. .proc_handler = proc_doulongvec_minmax,
  1787. },
  1788. {
  1789. .procname = "add_interrupt_avg_deviation",
  1790. .data = &avg_deviation,
  1791. .maxlen = sizeof(avg_deviation),
  1792. .mode = 0444,
  1793. .proc_handler = proc_doulongvec_minmax,
  1794. },
  1795. #endif
  1796. { }
  1797. };
  1798. #endif /* CONFIG_SYSCTL */
  1799. struct batched_entropy {
  1800. union {
  1801. unsigned long entropy_long[CHACHA20_BLOCK_SIZE / sizeof(unsigned long)];
  1802. unsigned int entropy_int[CHACHA20_BLOCK_SIZE / sizeof(unsigned int)];
  1803. };
  1804. unsigned int position;
  1805. };
  1806. /*
  1807. * Get a random word for internal kernel use only. The quality of the random
  1808. * number is either as good as RDRAND or as good as /dev/urandom, with the
  1809. * goal of being quite fast and not depleting entropy.
  1810. */
  1811. static DEFINE_PER_CPU(struct batched_entropy, batched_entropy_long);
  1812. unsigned long get_random_long(void)
  1813. {
  1814. unsigned long ret;
  1815. struct batched_entropy *batch;
  1816. if (arch_get_random_long(&ret))
  1817. return ret;
  1818. batch = &get_cpu_var(batched_entropy_long);
  1819. if (batch->position % ARRAY_SIZE(batch->entropy_long) == 0) {
  1820. extract_crng((u8 *)batch->entropy_long);
  1821. batch->position = 0;
  1822. }
  1823. ret = batch->entropy_long[batch->position++];
  1824. put_cpu_var(batched_entropy_long);
  1825. return ret;
  1826. }
  1827. EXPORT_SYMBOL(get_random_long);
  1828. #if BITS_PER_LONG == 32
  1829. unsigned int get_random_int(void)
  1830. {
  1831. return get_random_long();
  1832. }
  1833. #else
  1834. static DEFINE_PER_CPU(struct batched_entropy, batched_entropy_int);
  1835. unsigned int get_random_int(void)
  1836. {
  1837. unsigned int ret;
  1838. struct batched_entropy *batch;
  1839. if (arch_get_random_int(&ret))
  1840. return ret;
  1841. batch = &get_cpu_var(batched_entropy_int);
  1842. if (batch->position % ARRAY_SIZE(batch->entropy_int) == 0) {
  1843. extract_crng((u8 *)batch->entropy_int);
  1844. batch->position = 0;
  1845. }
  1846. ret = batch->entropy_int[batch->position++];
  1847. put_cpu_var(batched_entropy_int);
  1848. return ret;
  1849. }
  1850. #endif
  1851. EXPORT_SYMBOL(get_random_int);
  1852. /**
  1853. * randomize_page - Generate a random, page aligned address
  1854. * @start: The smallest acceptable address the caller will take.
  1855. * @range: The size of the area, starting at @start, within which the
  1856. * random address must fall.
  1857. *
  1858. * If @start + @range would overflow, @range is capped.
  1859. *
  1860. * NOTE: Historical use of randomize_range, which this replaces, presumed that
  1861. * @start was already page aligned. We now align it regardless.
  1862. *
  1863. * Return: A page aligned address within [start, start + range). On error,
  1864. * @start is returned.
  1865. */
  1866. unsigned long
  1867. randomize_page(unsigned long start, unsigned long range)
  1868. {
  1869. if (!PAGE_ALIGNED(start)) {
  1870. range -= PAGE_ALIGN(start) - start;
  1871. start = PAGE_ALIGN(start);
  1872. }
  1873. if (start > ULONG_MAX - range)
  1874. range = ULONG_MAX - start;
  1875. range >>= PAGE_SHIFT;
  1876. if (range == 0)
  1877. return start;
  1878. return start + (get_random_long() % range << PAGE_SHIFT);
  1879. }
  1880. /* Interface for in-kernel drivers of true hardware RNGs.
  1881. * Those devices may produce endless random bits and will be throttled
  1882. * when our pool is full.
  1883. */
  1884. void add_hwgenerator_randomness(const char *buffer, size_t count,
  1885. size_t entropy)
  1886. {
  1887. struct entropy_store *poolp = &input_pool;
  1888. if (!crng_ready()) {
  1889. crng_fast_load(buffer, count);
  1890. return;
  1891. }
  1892. /* Suspend writing if we're above the trickle threshold.
  1893. * We'll be woken up again once below random_write_wakeup_thresh,
  1894. * or when the calling thread is about to terminate.
  1895. */
  1896. wait_event_interruptible(random_write_wait, kthread_should_stop() ||
  1897. ENTROPY_BITS(&input_pool) <= random_write_wakeup_bits);
  1898. mix_pool_bytes(poolp, buffer, count);
  1899. credit_entropy_bits(poolp, entropy);
  1900. }
  1901. EXPORT_SYMBOL_GPL(add_hwgenerator_randomness);