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