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