]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/contrib/openzfs/module/os/linux/spl/spl-generic.c
Update OpenZFS to 2.0.0-rc3-gfc5966
[FreeBSD/FreeBSD.git] / sys / contrib / openzfs / module / os / linux / spl / spl-generic.c
1 /*
2  *  Copyright (C) 2007-2010 Lawrence Livermore National Security, LLC.
3  *  Copyright (C) 2007 The Regents of the University of California.
4  *  Produced at Lawrence Livermore National Laboratory (cf, DISCLAIMER).
5  *  Written by Brian Behlendorf <behlendorf1@llnl.gov>.
6  *  UCRL-CODE-235197
7  *
8  *  This file is part of the SPL, Solaris Porting Layer.
9  *
10  *  The SPL is free software; you can redistribute it and/or modify it
11  *  under the terms of the GNU General Public License as published by the
12  *  Free Software Foundation; either version 2 of the License, or (at your
13  *  option) any later version.
14  *
15  *  The SPL is distributed in the hope that it will be useful, but WITHOUT
16  *  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
17  *  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
18  *  for more details.
19  *
20  *  You should have received a copy of the GNU General Public License along
21  *  with the SPL.  If not, see <http://www.gnu.org/licenses/>.
22  *
23  *  Solaris Porting Layer (SPL) Generic Implementation.
24  */
25
26 #include <sys/sysmacros.h>
27 #include <sys/systeminfo.h>
28 #include <sys/vmsystm.h>
29 #include <sys/kmem.h>
30 #include <sys/kmem_cache.h>
31 #include <sys/vmem.h>
32 #include <sys/mutex.h>
33 #include <sys/rwlock.h>
34 #include <sys/taskq.h>
35 #include <sys/tsd.h>
36 #include <sys/zmod.h>
37 #include <sys/debug.h>
38 #include <sys/proc.h>
39 #include <sys/kstat.h>
40 #include <sys/file.h>
41 #include <sys/sunddi.h>
42 #include <linux/ctype.h>
43 #include <sys/disp.h>
44 #include <sys/random.h>
45 #include <sys/strings.h>
46 #include <linux/kmod.h>
47 #include "zfs_gitrev.h"
48 #include <linux/mod_compat.h>
49 #include <sys/cred.h>
50 #include <sys/vnode.h>
51
52 char spl_gitrev[64] = ZFS_META_GITREV;
53
54 /* BEGIN CSTYLED */
55 unsigned long spl_hostid = 0;
56 EXPORT_SYMBOL(spl_hostid);
57 /* BEGIN CSTYLED */
58 module_param(spl_hostid, ulong, 0644);
59 MODULE_PARM_DESC(spl_hostid, "The system hostid.");
60 /* END CSTYLED */
61
62 proc_t p0;
63 EXPORT_SYMBOL(p0);
64
65 /*
66  * Xorshift Pseudo Random Number Generator based on work by Sebastiano Vigna
67  *
68  * "Further scramblings of Marsaglia's xorshift generators"
69  * http://vigna.di.unimi.it/ftp/papers/xorshiftplus.pdf
70  *
71  * random_get_pseudo_bytes() is an API function on Illumos whose sole purpose
72  * is to provide bytes containing random numbers. It is mapped to /dev/urandom
73  * on Illumos, which uses a "FIPS 186-2 algorithm". No user of the SPL's
74  * random_get_pseudo_bytes() needs bytes that are of cryptographic quality, so
75  * we can implement it using a fast PRNG that we seed using Linux' actual
76  * equivalent to random_get_pseudo_bytes(). We do this by providing each CPU
77  * with an independent seed so that all calls to random_get_pseudo_bytes() are
78  * free of atomic instructions.
79  *
80  * A consequence of using a fast PRNG is that using random_get_pseudo_bytes()
81  * to generate words larger than 128 bits will paradoxically be limited to
82  * `2^128 - 1` possibilities. This is because we have a sequence of `2^128 - 1`
83  * 128-bit words and selecting the first will implicitly select the second. If
84  * a caller finds this behavior undesirable, random_get_bytes() should be used
85  * instead.
86  *
87  * XXX: Linux interrupt handlers that trigger within the critical section
88  * formed by `s[1] = xp[1];` and `xp[0] = s[0];` and call this function will
89  * see the same numbers. Nothing in the code currently calls this in an
90  * interrupt handler, so this is considered to be okay. If that becomes a
91  * problem, we could create a set of per-cpu variables for interrupt handlers
92  * and use them when in_interrupt() from linux/preempt_mask.h evaluates to
93  * true.
94  */
95 void __percpu *spl_pseudo_entropy;
96
97 /*
98  * spl_rand_next()/spl_rand_jump() are copied from the following CC-0 licensed
99  * file:
100  *
101  * http://xorshift.di.unimi.it/xorshift128plus.c
102  */
103
104 static inline uint64_t
105 spl_rand_next(uint64_t *s)
106 {
107         uint64_t s1 = s[0];
108         const uint64_t s0 = s[1];
109         s[0] = s0;
110         s1 ^= s1 << 23; // a
111         s[1] = s1 ^ s0 ^ (s1 >> 18) ^ (s0 >> 5); // b, c
112         return (s[1] + s0);
113 }
114
115 static inline void
116 spl_rand_jump(uint64_t *s)
117 {
118         static const uint64_t JUMP[] =
119             { 0x8a5cd789635d2dff, 0x121fd2155c472f96 };
120
121         uint64_t s0 = 0;
122         uint64_t s1 = 0;
123         int i, b;
124         for (i = 0; i < sizeof (JUMP) / sizeof (*JUMP); i++)
125                 for (b = 0; b < 64; b++) {
126                         if (JUMP[i] & 1ULL << b) {
127                                 s0 ^= s[0];
128                                 s1 ^= s[1];
129                         }
130                         (void) spl_rand_next(s);
131                 }
132
133         s[0] = s0;
134         s[1] = s1;
135 }
136
137 int
138 random_get_pseudo_bytes(uint8_t *ptr, size_t len)
139 {
140         uint64_t *xp, s[2];
141
142         ASSERT(ptr);
143
144         xp = get_cpu_ptr(spl_pseudo_entropy);
145
146         s[0] = xp[0];
147         s[1] = xp[1];
148
149         while (len) {
150                 union {
151                         uint64_t ui64;
152                         uint8_t byte[sizeof (uint64_t)];
153                 }entropy;
154                 int i = MIN(len, sizeof (uint64_t));
155
156                 len -= i;
157                 entropy.ui64 = spl_rand_next(s);
158
159                 while (i--)
160                         *ptr++ = entropy.byte[i];
161         }
162
163         xp[0] = s[0];
164         xp[1] = s[1];
165
166         put_cpu_ptr(spl_pseudo_entropy);
167
168         return (0);
169 }
170
171
172 EXPORT_SYMBOL(random_get_pseudo_bytes);
173
174 #if BITS_PER_LONG == 32
175
176 /*
177  * Support 64/64 => 64 division on a 32-bit platform.  While the kernel
178  * provides a div64_u64() function for this we do not use it because the
179  * implementation is flawed.  There are cases which return incorrect
180  * results as late as linux-2.6.35.  Until this is fixed upstream the
181  * spl must provide its own implementation.
182  *
183  * This implementation is a slightly modified version of the algorithm
184  * proposed by the book 'Hacker's Delight'.  The original source can be
185  * found here and is available for use without restriction.
186  *
187  * http://www.hackersdelight.org/HDcode/newCode/divDouble.c
188  */
189
190 /*
191  * Calculate number of leading of zeros for a 64-bit value.
192  */
193 static int
194 nlz64(uint64_t x)
195 {
196         register int n = 0;
197
198         if (x == 0)
199                 return (64);
200
201         if (x <= 0x00000000FFFFFFFFULL) { n = n + 32; x = x << 32; }
202         if (x <= 0x0000FFFFFFFFFFFFULL) { n = n + 16; x = x << 16; }
203         if (x <= 0x00FFFFFFFFFFFFFFULL) { n = n +  8; x = x <<  8; }
204         if (x <= 0x0FFFFFFFFFFFFFFFULL) { n = n +  4; x = x <<  4; }
205         if (x <= 0x3FFFFFFFFFFFFFFFULL) { n = n +  2; x = x <<  2; }
206         if (x <= 0x7FFFFFFFFFFFFFFFULL) { n = n +  1; }
207
208         return (n);
209 }
210
211 /*
212  * Newer kernels have a div_u64() function but we define our own
213  * to simplify portability between kernel versions.
214  */
215 static inline uint64_t
216 __div_u64(uint64_t u, uint32_t v)
217 {
218         (void) do_div(u, v);
219         return (u);
220 }
221
222 /*
223  * Turn off missing prototypes warning for these functions. They are
224  * replacements for libgcc-provided functions and will never be called
225  * directly.
226  */
227 #pragma GCC diagnostic push
228 #pragma GCC diagnostic ignored "-Wmissing-prototypes"
229
230 /*
231  * Implementation of 64-bit unsigned division for 32-bit machines.
232  *
233  * First the procedure takes care of the case in which the divisor is a
234  * 32-bit quantity. There are two subcases: (1) If the left half of the
235  * dividend is less than the divisor, one execution of do_div() is all that
236  * is required (overflow is not possible). (2) Otherwise it does two
237  * divisions, using the grade school method.
238  */
239 uint64_t
240 __udivdi3(uint64_t u, uint64_t v)
241 {
242         uint64_t u0, u1, v1, q0, q1, k;
243         int n;
244
245         if (v >> 32 == 0) {                     // If v < 2**32:
246                 if (u >> 32 < v) {              // If u/v cannot overflow,
247                         return (__div_u64(u, v)); // just do one division.
248                 } else {                        // If u/v would overflow:
249                         u1 = u >> 32;           // Break u into two halves.
250                         u0 = u & 0xFFFFFFFF;
251                         q1 = __div_u64(u1, v);  // First quotient digit.
252                         k  = u1 - q1 * v;       // First remainder, < v.
253                         u0 += (k << 32);
254                         q0 = __div_u64(u0, v);  // Seconds quotient digit.
255                         return ((q1 << 32) + q0);
256                 }
257         } else {                                // If v >= 2**32:
258                 n = nlz64(v);                   // 0 <= n <= 31.
259                 v1 = (v << n) >> 32;            // Normalize divisor, MSB is 1.
260                 u1 = u >> 1;                    // To ensure no overflow.
261                 q1 = __div_u64(u1, v1);         // Get quotient from
262                 q0 = (q1 << n) >> 31;           // Undo normalization and
263                                                 // division of u by 2.
264                 if (q0 != 0)                    // Make q0 correct or
265                         q0 = q0 - 1;            // too small by 1.
266                 if ((u - q0 * v) >= v)
267                         q0 = q0 + 1;            // Now q0 is correct.
268
269                 return (q0);
270         }
271 }
272 EXPORT_SYMBOL(__udivdi3);
273
274 /* BEGIN CSTYLED */
275 #ifndef abs64
276 #define abs64(x)        ({ uint64_t t = (x) >> 63; ((x) ^ t) - t; })
277 #endif
278 /* END CSTYLED */
279
280 /*
281  * Implementation of 64-bit signed division for 32-bit machines.
282  */
283 int64_t
284 __divdi3(int64_t u, int64_t v)
285 {
286         int64_t q, t;
287         // cppcheck-suppress shiftTooManyBitsSigned
288         q = __udivdi3(abs64(u), abs64(v));
289         // cppcheck-suppress shiftTooManyBitsSigned
290         t = (u ^ v) >> 63;      // If u, v have different
291         return ((q ^ t) - t);   // signs, negate q.
292 }
293 EXPORT_SYMBOL(__divdi3);
294
295 /*
296  * Implementation of 64-bit unsigned modulo for 32-bit machines.
297  */
298 uint64_t
299 __umoddi3(uint64_t dividend, uint64_t divisor)
300 {
301         return (dividend - (divisor * __udivdi3(dividend, divisor)));
302 }
303 EXPORT_SYMBOL(__umoddi3);
304
305 /* 64-bit signed modulo for 32-bit machines. */
306 int64_t
307 __moddi3(int64_t n, int64_t d)
308 {
309         int64_t q;
310         boolean_t nn = B_FALSE;
311
312         if (n < 0) {
313                 nn = B_TRUE;
314                 n = -n;
315         }
316         if (d < 0)
317                 d = -d;
318
319         q = __umoddi3(n, d);
320
321         return (nn ? -q : q);
322 }
323 EXPORT_SYMBOL(__moddi3);
324
325 /*
326  * Implementation of 64-bit unsigned division/modulo for 32-bit machines.
327  */
328 uint64_t
329 __udivmoddi4(uint64_t n, uint64_t d, uint64_t *r)
330 {
331         uint64_t q = __udivdi3(n, d);
332         if (r)
333                 *r = n - d * q;
334         return (q);
335 }
336 EXPORT_SYMBOL(__udivmoddi4);
337
338 /*
339  * Implementation of 64-bit signed division/modulo for 32-bit machines.
340  */
341 int64_t
342 __divmoddi4(int64_t n, int64_t d, int64_t *r)
343 {
344         int64_t q, rr;
345         boolean_t nn = B_FALSE;
346         boolean_t nd = B_FALSE;
347         if (n < 0) {
348                 nn = B_TRUE;
349                 n = -n;
350         }
351         if (d < 0) {
352                 nd = B_TRUE;
353                 d = -d;
354         }
355
356         q = __udivmoddi4(n, d, (uint64_t *)&rr);
357
358         if (nn != nd)
359                 q = -q;
360         if (nn)
361                 rr = -rr;
362         if (r)
363                 *r = rr;
364         return (q);
365 }
366 EXPORT_SYMBOL(__divmoddi4);
367
368 #if defined(__arm) || defined(__arm__)
369 /*
370  * Implementation of 64-bit (un)signed division for 32-bit arm machines.
371  *
372  * Run-time ABI for the ARM Architecture (page 20).  A pair of (unsigned)
373  * long longs is returned in {{r0, r1}, {r2,r3}}, the quotient in {r0, r1},
374  * and the remainder in {r2, r3}.  The return type is specifically left
375  * set to 'void' to ensure the compiler does not overwrite these registers
376  * during the return.  All results are in registers as per ABI
377  */
378 void
379 __aeabi_uldivmod(uint64_t u, uint64_t v)
380 {
381         uint64_t res;
382         uint64_t mod;
383
384         res = __udivdi3(u, v);
385         mod = __umoddi3(u, v);
386         {
387                 register uint32_t r0 asm("r0") = (res & 0xFFFFFFFF);
388                 register uint32_t r1 asm("r1") = (res >> 32);
389                 register uint32_t r2 asm("r2") = (mod & 0xFFFFFFFF);
390                 register uint32_t r3 asm("r3") = (mod >> 32);
391
392                 /* BEGIN CSTYLED */
393                 asm volatile(""
394                     : "+r"(r0), "+r"(r1), "+r"(r2),"+r"(r3)  /* output */
395                     : "r"(r0), "r"(r1), "r"(r2), "r"(r3));   /* input */
396                 /* END CSTYLED */
397
398                 return; /* r0; */
399         }
400 }
401 EXPORT_SYMBOL(__aeabi_uldivmod);
402
403 void
404 __aeabi_ldivmod(int64_t u, int64_t v)
405 {
406         int64_t res;
407         uint64_t mod;
408
409         res =  __divdi3(u, v);
410         mod = __umoddi3(u, v);
411         {
412                 register uint32_t r0 asm("r0") = (res & 0xFFFFFFFF);
413                 register uint32_t r1 asm("r1") = (res >> 32);
414                 register uint32_t r2 asm("r2") = (mod & 0xFFFFFFFF);
415                 register uint32_t r3 asm("r3") = (mod >> 32);
416
417                 /* BEGIN CSTYLED */
418                 asm volatile(""
419                     : "+r"(r0), "+r"(r1), "+r"(r2),"+r"(r3)  /* output */
420                     : "r"(r0), "r"(r1), "r"(r2), "r"(r3));   /* input */
421                 /* END CSTYLED */
422
423                 return; /* r0; */
424         }
425 }
426 EXPORT_SYMBOL(__aeabi_ldivmod);
427 #endif /* __arm || __arm__ */
428
429 #pragma GCC diagnostic pop
430
431 #endif /* BITS_PER_LONG */
432
433 /*
434  * NOTE: The strtoxx behavior is solely based on my reading of the Solaris
435  * ddi_strtol(9F) man page.  I have not verified the behavior of these
436  * functions against their Solaris counterparts.  It is possible that I
437  * may have misinterpreted the man page or the man page is incorrect.
438  */
439 int ddi_strtoul(const char *, char **, int, unsigned long *);
440 int ddi_strtol(const char *, char **, int, long *);
441 int ddi_strtoull(const char *, char **, int, unsigned long long *);
442 int ddi_strtoll(const char *, char **, int, long long *);
443
444 #define define_ddi_strtoux(type, valtype)                               \
445 int ddi_strtou##type(const char *str, char **endptr,                    \
446     int base, valtype *result)                                          \
447 {                                                                       \
448         valtype last_value, value = 0;                                  \
449         char *ptr = (char *)str;                                        \
450         int flag = 1, digit;                                            \
451                                                                         \
452         if (strlen(ptr) == 0)                                           \
453                 return (EINVAL);                                        \
454                                                                         \
455         /* Auto-detect base based on prefix */                          \
456         if (!base) {                                                    \
457                 if (str[0] == '0') {                                    \
458                         if (tolower(str[1]) == 'x' && isxdigit(str[2])) { \
459                                 base = 16; /* hex */                    \
460                                 ptr += 2;                               \
461                         } else if (str[1] >= '0' && str[1] < 8) {       \
462                                 base = 8; /* octal */                   \
463                                 ptr += 1;                               \
464                         } else {                                        \
465                                 return (EINVAL);                        \
466                         }                                               \
467                 } else {                                                \
468                         base = 10; /* decimal */                        \
469                 }                                                       \
470         }                                                               \
471                                                                         \
472         while (1) {                                                     \
473                 if (isdigit(*ptr))                                      \
474                         digit = *ptr - '0';                             \
475                 else if (isalpha(*ptr))                                 \
476                         digit = tolower(*ptr) - 'a' + 10;               \
477                 else                                                    \
478                         break;                                          \
479                                                                         \
480                 if (digit >= base)                                      \
481                         break;                                          \
482                                                                         \
483                 last_value = value;                                     \
484                 value = value * base + digit;                           \
485                 if (last_value > value) /* Overflow */                  \
486                         return (ERANGE);                                \
487                                                                         \
488                 flag = 1;                                               \
489                 ptr++;                                                  \
490         }                                                               \
491                                                                         \
492         if (flag)                                                       \
493                 *result = value;                                        \
494                                                                         \
495         if (endptr)                                                     \
496                 *endptr = (char *)(flag ? ptr : str);                   \
497                                                                         \
498         return (0);                                                     \
499 }                                                                       \
500
501 #define define_ddi_strtox(type, valtype)                                \
502 int ddi_strto##type(const char *str, char **endptr,                     \
503     int base, valtype *result)                                          \
504 {                                                                       \
505         int rc;                                                         \
506                                                                         \
507         if (*str == '-') {                                              \
508                 rc = ddi_strtou##type(str + 1, endptr, base, result);   \
509                 if (!rc) {                                              \
510                         if (*endptr == str + 1)                         \
511                                 *endptr = (char *)str;                  \
512                         else                                            \
513                                 *result = -*result;                     \
514                 }                                                       \
515         } else {                                                        \
516                 rc = ddi_strtou##type(str, endptr, base, result);       \
517         }                                                               \
518                                                                         \
519         return (rc);                                                    \
520 }
521
522 define_ddi_strtoux(l, unsigned long)
523 define_ddi_strtox(l, long)
524 define_ddi_strtoux(ll, unsigned long long)
525 define_ddi_strtox(ll, long long)
526
527 EXPORT_SYMBOL(ddi_strtoul);
528 EXPORT_SYMBOL(ddi_strtol);
529 EXPORT_SYMBOL(ddi_strtoll);
530 EXPORT_SYMBOL(ddi_strtoull);
531
532 int
533 ddi_copyin(const void *from, void *to, size_t len, int flags)
534 {
535         /* Fake ioctl() issued by kernel, 'from' is a kernel address */
536         if (flags & FKIOCTL) {
537                 memcpy(to, from, len);
538                 return (0);
539         }
540
541         return (copyin(from, to, len));
542 }
543 EXPORT_SYMBOL(ddi_copyin);
544
545 int
546 ddi_copyout(const void *from, void *to, size_t len, int flags)
547 {
548         /* Fake ioctl() issued by kernel, 'from' is a kernel address */
549         if (flags & FKIOCTL) {
550                 memcpy(to, from, len);
551                 return (0);
552         }
553
554         return (copyout(from, to, len));
555 }
556 EXPORT_SYMBOL(ddi_copyout);
557
558 static ssize_t
559 spl_kernel_read(struct file *file, void *buf, size_t count, loff_t *pos)
560 {
561 #if defined(HAVE_KERNEL_READ_PPOS)
562         return (kernel_read(file, buf, count, pos));
563 #else
564         mm_segment_t saved_fs;
565         ssize_t ret;
566
567         saved_fs = get_fs();
568         set_fs(KERNEL_DS);
569
570         ret = vfs_read(file, (void __user *)buf, count, pos);
571
572         set_fs(saved_fs);
573
574         return (ret);
575 #endif
576 }
577
578 static int
579 spl_getattr(struct file *filp, struct kstat *stat)
580 {
581         int rc;
582
583         ASSERT(filp);
584         ASSERT(stat);
585
586 #if defined(HAVE_4ARGS_VFS_GETATTR)
587         rc = vfs_getattr(&filp->f_path, stat, STATX_BASIC_STATS,
588             AT_STATX_SYNC_AS_STAT);
589 #elif defined(HAVE_2ARGS_VFS_GETATTR)
590         rc = vfs_getattr(&filp->f_path, stat);
591 #else
592         rc = vfs_getattr(filp->f_path.mnt, filp->f_dentry, stat);
593 #endif
594         if (rc)
595                 return (-rc);
596
597         return (0);
598 }
599
600 /*
601  * Read the unique system identifier from the /etc/hostid file.
602  *
603  * The behavior of /usr/bin/hostid on Linux systems with the
604  * regular eglibc and coreutils is:
605  *
606  *   1. Generate the value if the /etc/hostid file does not exist
607  *      or if the /etc/hostid file is less than four bytes in size.
608  *
609  *   2. If the /etc/hostid file is at least 4 bytes, then return
610  *      the first four bytes [0..3] in native endian order.
611  *
612  *   3. Always ignore bytes [4..] if they exist in the file.
613  *
614  * Only the first four bytes are significant, even on systems that
615  * have a 64-bit word size.
616  *
617  * See:
618  *
619  *   eglibc: sysdeps/unix/sysv/linux/gethostid.c
620  *   coreutils: src/hostid.c
621  *
622  * Notes:
623  *
624  * The /etc/hostid file on Solaris is a text file that often reads:
625  *
626  *   # DO NOT EDIT
627  *   "0123456789"
628  *
629  * Directly copying this file to Linux results in a constant
630  * hostid of 4f442023 because the default comment constitutes
631  * the first four bytes of the file.
632  *
633  */
634
635 char *spl_hostid_path = HW_HOSTID_PATH;
636 module_param(spl_hostid_path, charp, 0444);
637 MODULE_PARM_DESC(spl_hostid_path, "The system hostid file (/etc/hostid)");
638
639 static int
640 hostid_read(uint32_t *hostid)
641 {
642         uint64_t size;
643         uint32_t value = 0;
644         int error;
645         loff_t off;
646         struct file *filp;
647         struct kstat stat;
648
649         filp = filp_open(spl_hostid_path, 0, 0);
650
651         if (IS_ERR(filp))
652                 return (ENOENT);
653
654         error = spl_getattr(filp, &stat);
655         if (error) {
656                 filp_close(filp, 0);
657                 return (error);
658         }
659         size = stat.size;
660         if (size < sizeof (HW_HOSTID_MASK)) {
661                 filp_close(filp, 0);
662                 return (EINVAL);
663         }
664
665         off = 0;
666         /*
667          * Read directly into the variable like eglibc does.
668          * Short reads are okay; native behavior is preserved.
669          */
670         error = spl_kernel_read(filp, &value, sizeof (value), &off);
671         if (error < 0) {
672                 filp_close(filp, 0);
673                 return (EIO);
674         }
675
676         /* Mask down to 32 bits like coreutils does. */
677         *hostid = (value & HW_HOSTID_MASK);
678         filp_close(filp, 0);
679
680         return (0);
681 }
682
683 /*
684  * Return the system hostid.  Preferentially use the spl_hostid module option
685  * when set, otherwise use the value in the /etc/hostid file.
686  */
687 uint32_t
688 zone_get_hostid(void *zone)
689 {
690         uint32_t hostid;
691
692         ASSERT3P(zone, ==, NULL);
693
694         if (spl_hostid != 0)
695                 return ((uint32_t)(spl_hostid & HW_HOSTID_MASK));
696
697         if (hostid_read(&hostid) == 0)
698                 return (hostid);
699
700         return (0);
701 }
702 EXPORT_SYMBOL(zone_get_hostid);
703
704 static int
705 spl_kvmem_init(void)
706 {
707         int rc = 0;
708
709         rc = spl_kmem_init();
710         if (rc)
711                 return (rc);
712
713         rc = spl_vmem_init();
714         if (rc) {
715                 spl_kmem_fini();
716                 return (rc);
717         }
718
719         return (rc);
720 }
721
722 /*
723  * We initialize the random number generator with 128 bits of entropy from the
724  * system random number generator. In the improbable case that we have a zero
725  * seed, we fallback to the system jiffies, unless it is also zero, in which
726  * situation we use a preprogrammed seed. We step forward by 2^64 iterations to
727  * initialize each of the per-cpu seeds so that the sequences generated on each
728  * CPU are guaranteed to never overlap in practice.
729  */
730 static void __init
731 spl_random_init(void)
732 {
733         uint64_t s[2];
734         int i = 0;
735
736         spl_pseudo_entropy = __alloc_percpu(2 * sizeof (uint64_t),
737             sizeof (uint64_t));
738
739         get_random_bytes(s, sizeof (s));
740
741         if (s[0] == 0 && s[1] == 0) {
742                 if (jiffies != 0) {
743                         s[0] = jiffies;
744                         s[1] = ~0 - jiffies;
745                 } else {
746                         (void) memcpy(s, "improbable seed", sizeof (s));
747                 }
748                 printk("SPL: get_random_bytes() returned 0 "
749                     "when generating random seed. Setting initial seed to "
750                     "0x%016llx%016llx.\n", cpu_to_be64(s[0]),
751                     cpu_to_be64(s[1]));
752         }
753
754         for_each_possible_cpu(i) {
755                 uint64_t *wordp = per_cpu_ptr(spl_pseudo_entropy, i);
756
757                 spl_rand_jump(s);
758
759                 wordp[0] = s[0];
760                 wordp[1] = s[1];
761         }
762 }
763
764 static void
765 spl_random_fini(void)
766 {
767         free_percpu(spl_pseudo_entropy);
768 }
769
770 static void
771 spl_kvmem_fini(void)
772 {
773         spl_vmem_fini();
774         spl_kmem_fini();
775 }
776
777 static int __init
778 spl_init(void)
779 {
780         int rc = 0;
781
782         bzero(&p0, sizeof (proc_t));
783         spl_random_init();
784
785         if ((rc = spl_kvmem_init()))
786                 goto out1;
787
788         if ((rc = spl_tsd_init()))
789                 goto out2;
790
791         if ((rc = spl_taskq_init()))
792                 goto out3;
793
794         if ((rc = spl_kmem_cache_init()))
795                 goto out4;
796
797         if ((rc = spl_proc_init()))
798                 goto out5;
799
800         if ((rc = spl_kstat_init()))
801                 goto out6;
802
803         if ((rc = spl_zlib_init()))
804                 goto out7;
805
806         return (rc);
807
808 out7:
809         spl_kstat_fini();
810 out6:
811         spl_proc_fini();
812 out5:
813         spl_kmem_cache_fini();
814 out4:
815         spl_taskq_fini();
816 out3:
817         spl_tsd_fini();
818 out2:
819         spl_kvmem_fini();
820 out1:
821         return (rc);
822 }
823
824 static void __exit
825 spl_fini(void)
826 {
827         spl_zlib_fini();
828         spl_kstat_fini();
829         spl_proc_fini();
830         spl_kmem_cache_fini();
831         spl_taskq_fini();
832         spl_tsd_fini();
833         spl_kvmem_fini();
834         spl_random_fini();
835 }
836
837 module_init(spl_init);
838 module_exit(spl_fini);
839
840 ZFS_MODULE_DESCRIPTION("Solaris Porting Layer");
841 ZFS_MODULE_AUTHOR(ZFS_META_AUTHOR);
842 ZFS_MODULE_LICENSE("GPL");
843 ZFS_MODULE_VERSION(ZFS_META_VERSION "-" ZFS_META_RELEASE);