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