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/string.h>
46 #include <linux/kmod.h>
47 #include <linux/mod_compat.h>
48 #include <sys/cred.h>
49 #include <sys/vnode.h>
50 #include <sys/misc.h>
51 
52 unsigned long spl_hostid = 0;
53 EXPORT_SYMBOL(spl_hostid);
54 
55 /* CSTYLED */
56 module_param(spl_hostid, ulong, 0644);
57 MODULE_PARM_DESC(spl_hostid, "The system hostid.");
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 #ifndef abs64
272 /* CSTYLED */
273 #define	abs64(x)	({ uint64_t t = (x) >> 63; ((x) ^ t) - t; })
274 #endif
275 
276 /*
277  * Implementation of 64-bit signed division for 32-bit machines.
278  */
279 int64_t
280 __divdi3(int64_t u, int64_t v)
281 {
282 	int64_t q, t;
283 	q = __udivdi3(abs64(u), abs64(v));
284 	t = (u ^ v) >> 63;	// If u, v have different
285 	return ((q ^ t) - t);	// signs, negate q.
286 }
287 EXPORT_SYMBOL(__divdi3);
288 
289 /*
290  * Implementation of 64-bit unsigned modulo for 32-bit machines.
291  */
292 uint64_t
293 __umoddi3(uint64_t dividend, uint64_t divisor)
294 {
295 	return (dividend - (divisor * __udivdi3(dividend, divisor)));
296 }
297 EXPORT_SYMBOL(__umoddi3);
298 
299 /* 64-bit signed modulo for 32-bit machines. */
300 int64_t
301 __moddi3(int64_t n, int64_t d)
302 {
303 	int64_t q;
304 	boolean_t nn = B_FALSE;
305 
306 	if (n < 0) {
307 		nn = B_TRUE;
308 		n = -n;
309 	}
310 	if (d < 0)
311 		d = -d;
312 
313 	q = __umoddi3(n, d);
314 
315 	return (nn ? -q : q);
316 }
317 EXPORT_SYMBOL(__moddi3);
318 
319 /*
320  * Implementation of 64-bit unsigned division/modulo for 32-bit machines.
321  */
322 uint64_t
323 __udivmoddi4(uint64_t n, uint64_t d, uint64_t *r)
324 {
325 	uint64_t q = __udivdi3(n, d);
326 	if (r)
327 		*r = n - d * q;
328 	return (q);
329 }
330 EXPORT_SYMBOL(__udivmoddi4);
331 
332 /*
333  * Implementation of 64-bit signed division/modulo for 32-bit machines.
334  */
335 int64_t
336 __divmoddi4(int64_t n, int64_t d, int64_t *r)
337 {
338 	int64_t q, rr;
339 	boolean_t nn = B_FALSE;
340 	boolean_t nd = B_FALSE;
341 	if (n < 0) {
342 		nn = B_TRUE;
343 		n = -n;
344 	}
345 	if (d < 0) {
346 		nd = B_TRUE;
347 		d = -d;
348 	}
349 
350 	q = __udivmoddi4(n, d, (uint64_t *)&rr);
351 
352 	if (nn != nd)
353 		q = -q;
354 	if (nn)
355 		rr = -rr;
356 	if (r)
357 		*r = rr;
358 	return (q);
359 }
360 EXPORT_SYMBOL(__divmoddi4);
361 
362 #if defined(__arm) || defined(__arm__)
363 /*
364  * Implementation of 64-bit (un)signed division for 32-bit arm machines.
365  *
366  * Run-time ABI for the ARM Architecture (page 20).  A pair of (unsigned)
367  * long longs is returned in {{r0, r1}, {r2,r3}}, the quotient in {r0, r1},
368  * and the remainder in {r2, r3}.  The return type is specifically left
369  * set to 'void' to ensure the compiler does not overwrite these registers
370  * during the return.  All results are in registers as per ABI
371  */
372 void
373 __aeabi_uldivmod(uint64_t u, uint64_t v)
374 {
375 	uint64_t res;
376 	uint64_t mod;
377 
378 	res = __udivdi3(u, v);
379 	mod = __umoddi3(u, v);
380 	{
381 		register uint32_t r0 asm("r0") = (res & 0xFFFFFFFF);
382 		register uint32_t r1 asm("r1") = (res >> 32);
383 		register uint32_t r2 asm("r2") = (mod & 0xFFFFFFFF);
384 		register uint32_t r3 asm("r3") = (mod >> 32);
385 
386 		asm volatile(""
387 		    : "+r"(r0), "+r"(r1), "+r"(r2), "+r"(r3)  /* output */
388 		    : "r"(r0), "r"(r1), "r"(r2), "r"(r3));    /* input */
389 
390 		return; /* r0; */
391 	}
392 }
393 EXPORT_SYMBOL(__aeabi_uldivmod);
394 
395 void
396 __aeabi_ldivmod(int64_t u, int64_t v)
397 {
398 	int64_t res;
399 	uint64_t mod;
400 
401 	res =  __divdi3(u, v);
402 	mod = __umoddi3(u, v);
403 	{
404 		register uint32_t r0 asm("r0") = (res & 0xFFFFFFFF);
405 		register uint32_t r1 asm("r1") = (res >> 32);
406 		register uint32_t r2 asm("r2") = (mod & 0xFFFFFFFF);
407 		register uint32_t r3 asm("r3") = (mod >> 32);
408 
409 		asm volatile(""
410 		    : "+r"(r0), "+r"(r1), "+r"(r2), "+r"(r3)  /* output */
411 		    : "r"(r0), "r"(r1), "r"(r2), "r"(r3));    /* input */
412 
413 		return; /* r0; */
414 	}
415 }
416 EXPORT_SYMBOL(__aeabi_ldivmod);
417 #endif /* __arm || __arm__ */
418 
419 #pragma GCC diagnostic pop
420 
421 #endif /* BITS_PER_LONG */
422 
423 /*
424  * NOTE: The strtoxx behavior is solely based on my reading of the Solaris
425  * ddi_strtol(9F) man page.  I have not verified the behavior of these
426  * functions against their Solaris counterparts.  It is possible that I
427  * may have misinterpreted the man page or the man page is incorrect.
428  */
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_strtox(type, valtype)				\
434 int ddi_strto##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 digit, minus = 0;						\
440 									\
441 	while (strchr(" \t\n\r\f", *ptr))				\
442 		++ptr;							\
443 									\
444 	if (strlen(ptr) == 0)						\
445 		return (EINVAL);					\
446 									\
447 	switch (*ptr) {							\
448 	case '-':							\
449 		minus = 1;						\
450 		zfs_fallthrough;					\
451 	case '+':							\
452 		++ptr;							\
453 		break;							\
454 	}								\
455 									\
456 	/* Auto-detect base based on prefix */				\
457 	if (!base) {							\
458 		if (str[0] == '0') {					\
459 			if (tolower(str[1]) == 'x' && isxdigit(str[2])) { \
460 				base = 16; /* hex */			\
461 				ptr += 2;				\
462 			} else if (str[1] >= '0' && str[1] < 8) {	\
463 				base = 8; /* octal */			\
464 				ptr += 1;				\
465 			} else {					\
466 				return (EINVAL);			\
467 			}						\
468 		} else {						\
469 			base = 10; /* decimal */			\
470 		}							\
471 	}								\
472 									\
473 	while (1) {							\
474 		if (isdigit(*ptr))					\
475 			digit = *ptr - '0';				\
476 		else if (isalpha(*ptr))					\
477 			digit = tolower(*ptr) - 'a' + 10;		\
478 		else							\
479 			break;						\
480 									\
481 		if (digit >= base)					\
482 			break;						\
483 									\
484 		last_value = value;					\
485 		value = value * base + digit;				\
486 		if (last_value > value) /* Overflow */			\
487 			return (ERANGE);				\
488 									\
489 		ptr++;							\
490 	}								\
491 									\
492 	*result = minus ? -value : value;				\
493 									\
494 	if (endptr)							\
495 		*endptr = ptr;						\
496 									\
497 	return (0);							\
498 }									\
499 
500 define_ddi_strtox(l, long)
501 define_ddi_strtox(ull, unsigned long long)
502 define_ddi_strtox(ll, long long)
503 
504 EXPORT_SYMBOL(ddi_strtol);
505 EXPORT_SYMBOL(ddi_strtoll);
506 EXPORT_SYMBOL(ddi_strtoull);
507 
508 int
509 ddi_copyin(const void *from, void *to, size_t len, int flags)
510 {
511 	/* Fake ioctl() issued by kernel, 'from' is a kernel address */
512 	if (flags & FKIOCTL) {
513 		memcpy(to, from, len);
514 		return (0);
515 	}
516 
517 	return (copyin(from, to, len));
518 }
519 EXPORT_SYMBOL(ddi_copyin);
520 
521 /*
522  * Post a uevent to userspace whenever a new vdev adds to the pool. It is
523  * necessary to sync blkid information with udev, which zed daemon uses
524  * during device hotplug to identify the vdev.
525  */
526 void
527 spl_signal_kobj_evt(struct block_device *bdev)
528 {
529 #if defined(HAVE_BDEV_KOBJ) || defined(HAVE_PART_TO_DEV)
530 #ifdef HAVE_BDEV_KOBJ
531 	struct kobject *disk_kobj = bdev_kobj(bdev);
532 #else
533 	struct kobject *disk_kobj = &part_to_dev(bdev->bd_part)->kobj;
534 #endif
535 	if (disk_kobj) {
536 		int ret = kobject_uevent(disk_kobj, KOBJ_CHANGE);
537 		if (ret) {
538 			pr_warn("ZFS: Sending event '%d' to kobject: '%s'"
539 			    " (%p): failed(ret:%d)\n", KOBJ_CHANGE,
540 			    kobject_name(disk_kobj), disk_kobj, ret);
541 		}
542 	}
543 #else
544 /*
545  * This is encountered if neither bdev_kobj() nor part_to_dev() is available
546  * in the kernel - likely due to an API change that needs to be chased down.
547  */
548 #error "Unsupported kernel: unable to get struct kobj from bdev"
549 #endif
550 }
551 EXPORT_SYMBOL(spl_signal_kobj_evt);
552 
553 int
554 ddi_copyout(const void *from, void *to, size_t len, int flags)
555 {
556 	/* Fake ioctl() issued by kernel, 'from' is a kernel address */
557 	if (flags & FKIOCTL) {
558 		memcpy(to, from, len);
559 		return (0);
560 	}
561 
562 	return (copyout(from, to, len));
563 }
564 EXPORT_SYMBOL(ddi_copyout);
565 
566 static ssize_t
567 spl_kernel_read(struct file *file, void *buf, size_t count, loff_t *pos)
568 {
569 #if defined(HAVE_KERNEL_READ_PPOS)
570 	return (kernel_read(file, buf, count, pos));
571 #else
572 	mm_segment_t saved_fs;
573 	ssize_t ret;
574 
575 	saved_fs = get_fs();
576 	set_fs(KERNEL_DS);
577 
578 	ret = vfs_read(file, (void __user *)buf, count, pos);
579 
580 	set_fs(saved_fs);
581 
582 	return (ret);
583 #endif
584 }
585 
586 static int
587 spl_getattr(struct file *filp, struct kstat *stat)
588 {
589 	int rc;
590 
591 	ASSERT(filp);
592 	ASSERT(stat);
593 
594 #if defined(HAVE_4ARGS_VFS_GETATTR)
595 	rc = vfs_getattr(&filp->f_path, stat, STATX_BASIC_STATS,
596 	    AT_STATX_SYNC_AS_STAT);
597 #elif defined(HAVE_2ARGS_VFS_GETATTR)
598 	rc = vfs_getattr(&filp->f_path, stat);
599 #elif defined(HAVE_3ARGS_VFS_GETATTR)
600 	rc = vfs_getattr(filp->f_path.mnt, filp->f_dentry, stat);
601 #else
602 #error "No available vfs_getattr()"
603 #endif
604 	if (rc)
605 		return (-rc);
606 
607 	return (0);
608 }
609 
610 /*
611  * Read the unique system identifier from the /etc/hostid file.
612  *
613  * The behavior of /usr/bin/hostid on Linux systems with the
614  * regular eglibc and coreutils is:
615  *
616  *   1. Generate the value if the /etc/hostid file does not exist
617  *      or if the /etc/hostid file is less than four bytes in size.
618  *
619  *   2. If the /etc/hostid file is at least 4 bytes, then return
620  *      the first four bytes [0..3] in native endian order.
621  *
622  *   3. Always ignore bytes [4..] if they exist in the file.
623  *
624  * Only the first four bytes are significant, even on systems that
625  * have a 64-bit word size.
626  *
627  * See:
628  *
629  *   eglibc: sysdeps/unix/sysv/linux/gethostid.c
630  *   coreutils: src/hostid.c
631  *
632  * Notes:
633  *
634  * The /etc/hostid file on Solaris is a text file that often reads:
635  *
636  *   # DO NOT EDIT
637  *   "0123456789"
638  *
639  * Directly copying this file to Linux results in a constant
640  * hostid of 4f442023 because the default comment constitutes
641  * the first four bytes of the file.
642  *
643  */
644 
645 static char *spl_hostid_path = HW_HOSTID_PATH;
646 module_param(spl_hostid_path, charp, 0444);
647 MODULE_PARM_DESC(spl_hostid_path, "The system hostid file (/etc/hostid)");
648 
649 static int
650 hostid_read(uint32_t *hostid)
651 {
652 	uint64_t size;
653 	uint32_t value = 0;
654 	int error;
655 	loff_t off;
656 	struct file *filp;
657 	struct kstat stat;
658 
659 	filp = filp_open(spl_hostid_path, 0, 0);
660 
661 	if (IS_ERR(filp))
662 		return (ENOENT);
663 
664 	error = spl_getattr(filp, &stat);
665 	if (error) {
666 		filp_close(filp, 0);
667 		return (error);
668 	}
669 	size = stat.size;
670 	// cppcheck-suppress sizeofwithnumericparameter
671 	if (size < sizeof (HW_HOSTID_MASK)) {
672 		filp_close(filp, 0);
673 		return (EINVAL);
674 	}
675 
676 	off = 0;
677 	/*
678 	 * Read directly into the variable like eglibc does.
679 	 * Short reads are okay; native behavior is preserved.
680 	 */
681 	error = spl_kernel_read(filp, &value, sizeof (value), &off);
682 	if (error < 0) {
683 		filp_close(filp, 0);
684 		return (EIO);
685 	}
686 
687 	/* Mask down to 32 bits like coreutils does. */
688 	*hostid = (value & HW_HOSTID_MASK);
689 	filp_close(filp, 0);
690 
691 	return (0);
692 }
693 
694 /*
695  * Return the system hostid.  Preferentially use the spl_hostid module option
696  * when set, otherwise use the value in the /etc/hostid file.
697  */
698 uint32_t
699 zone_get_hostid(void *zone)
700 {
701 	uint32_t hostid;
702 
703 	ASSERT3P(zone, ==, NULL);
704 
705 	if (spl_hostid != 0)
706 		return ((uint32_t)(spl_hostid & HW_HOSTID_MASK));
707 
708 	if (hostid_read(&hostid) == 0)
709 		return (hostid);
710 
711 	return (0);
712 }
713 EXPORT_SYMBOL(zone_get_hostid);
714 
715 static int
716 spl_kvmem_init(void)
717 {
718 	int rc = 0;
719 
720 	rc = spl_kmem_init();
721 	if (rc)
722 		return (rc);
723 
724 	rc = spl_vmem_init();
725 	if (rc) {
726 		spl_kmem_fini();
727 		return (rc);
728 	}
729 
730 	return (rc);
731 }
732 
733 /*
734  * We initialize the random number generator with 128 bits of entropy from the
735  * system random number generator. In the improbable case that we have a zero
736  * seed, we fallback to the system jiffies, unless it is also zero, in which
737  * situation we use a preprogrammed seed. We step forward by 2^64 iterations to
738  * initialize each of the per-cpu seeds so that the sequences generated on each
739  * CPU are guaranteed to never overlap in practice.
740  */
741 static int __init
742 spl_random_init(void)
743 {
744 	uint64_t s[2];
745 	int i = 0;
746 
747 	spl_pseudo_entropy = __alloc_percpu(2 * sizeof (uint64_t),
748 	    sizeof (uint64_t));
749 
750 	if (!spl_pseudo_entropy)
751 		return (-ENOMEM);
752 
753 	get_random_bytes(s, sizeof (s));
754 
755 	if (s[0] == 0 && s[1] == 0) {
756 		if (jiffies != 0) {
757 			s[0] = jiffies;
758 			s[1] = ~0 - jiffies;
759 		} else {
760 			(void) memcpy(s, "improbable seed", sizeof (s));
761 		}
762 		printk("SPL: get_random_bytes() returned 0 "
763 		    "when generating random seed. Setting initial seed to "
764 		    "0x%016llx%016llx.\n", cpu_to_be64(s[0]),
765 		    cpu_to_be64(s[1]));
766 	}
767 
768 	for_each_possible_cpu(i) {
769 		uint64_t *wordp = per_cpu_ptr(spl_pseudo_entropy, i);
770 
771 		spl_rand_jump(s);
772 
773 		wordp[0] = s[0];
774 		wordp[1] = s[1];
775 	}
776 
777 	return (0);
778 }
779 
780 static void
781 spl_random_fini(void)
782 {
783 	free_percpu(spl_pseudo_entropy);
784 }
785 
786 static void
787 spl_kvmem_fini(void)
788 {
789 	spl_vmem_fini();
790 	spl_kmem_fini();
791 }
792 
793 static int __init
794 spl_init(void)
795 {
796 	int rc = 0;
797 
798 	if ((rc = spl_random_init()))
799 		goto out0;
800 
801 	if ((rc = spl_kvmem_init()))
802 		goto out1;
803 
804 	if ((rc = spl_tsd_init()))
805 		goto out2;
806 
807 	if ((rc = spl_taskq_init()))
808 		goto out3;
809 
810 	if ((rc = spl_kmem_cache_init()))
811 		goto out4;
812 
813 	if ((rc = spl_proc_init()))
814 		goto out5;
815 
816 	if ((rc = spl_kstat_init()))
817 		goto out6;
818 
819 	if ((rc = spl_zlib_init()))
820 		goto out7;
821 
822 	if ((rc = spl_zone_init()))
823 		goto out8;
824 
825 	return (rc);
826 
827 out8:
828 	spl_zlib_fini();
829 out7:
830 	spl_kstat_fini();
831 out6:
832 	spl_proc_fini();
833 out5:
834 	spl_kmem_cache_fini();
835 out4:
836 	spl_taskq_fini();
837 out3:
838 	spl_tsd_fini();
839 out2:
840 	spl_kvmem_fini();
841 out1:
842 	spl_random_fini();
843 out0:
844 	return (rc);
845 }
846 
847 static void __exit
848 spl_fini(void)
849 {
850 	spl_zone_fini();
851 	spl_zlib_fini();
852 	spl_kstat_fini();
853 	spl_proc_fini();
854 	spl_kmem_cache_fini();
855 	spl_taskq_fini();
856 	spl_tsd_fini();
857 	spl_kvmem_fini();
858 	spl_random_fini();
859 }
860 
861 module_init(spl_init);
862 module_exit(spl_fini);
863 
864 MODULE_DESCRIPTION("Solaris Porting Layer");
865 MODULE_AUTHOR(ZFS_META_AUTHOR);
866 MODULE_LICENSE("GPL");
867 MODULE_VERSION(ZFS_META_VERSION "-" ZFS_META_RELEASE);
868