xref: /freebsd/sys/contrib/openzfs/lib/libzpool/kernel.c (revision eda14cbc264d6969b02f2b1994cef11148e914f1)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright (c) 2012, 2018 by Delphix. All rights reserved.
24  * Copyright (c) 2016 Actifio, Inc. All rights reserved.
25  */
26 
27 #include <assert.h>
28 #include <fcntl.h>
29 #include <libgen.h>
30 #include <poll.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <sys/crypto/icp.h>
35 #include <sys/processor.h>
36 #include <sys/rrwlock.h>
37 #include <sys/spa.h>
38 #include <sys/stat.h>
39 #include <sys/systeminfo.h>
40 #include <sys/time.h>
41 #include <sys/utsname.h>
42 #include <sys/zfs_context.h>
43 #include <sys/zfs_onexit.h>
44 #include <sys/zstd/zstd.h>
45 #include <sys/zvol.h>
46 #include <zfs_fletcher.h>
47 #include <zlib.h>
48 
49 /*
50  * Emulation of kernel services in userland.
51  */
52 
53 uint64_t physmem;
54 char hw_serial[HW_HOSTID_LEN];
55 struct utsname hw_utsname;
56 
57 /* If set, all blocks read will be copied to the specified directory. */
58 char *vn_dumpdir = NULL;
59 
60 /* this only exists to have its address taken */
61 struct proc p0;
62 
63 /*
64  * =========================================================================
65  * threads
66  * =========================================================================
67  *
68  * TS_STACK_MIN is dictated by the minimum allowed pthread stack size.  While
69  * TS_STACK_MAX is somewhat arbitrary, it was selected to be large enough for
70  * the expected stack depth while small enough to avoid exhausting address
71  * space with high thread counts.
72  */
73 #define	TS_STACK_MIN	MAX(PTHREAD_STACK_MIN, 32768)
74 #define	TS_STACK_MAX	(256 * 1024)
75 
76 /*ARGSUSED*/
77 kthread_t *
78 zk_thread_create(void (*func)(void *), void *arg, size_t stksize, int state)
79 {
80 	pthread_attr_t attr;
81 	pthread_t tid;
82 	char *stkstr;
83 	int detachstate = PTHREAD_CREATE_DETACHED;
84 
85 	VERIFY0(pthread_attr_init(&attr));
86 
87 	if (state & TS_JOINABLE)
88 		detachstate = PTHREAD_CREATE_JOINABLE;
89 
90 	VERIFY0(pthread_attr_setdetachstate(&attr, detachstate));
91 
92 	/*
93 	 * We allow the default stack size in user space to be specified by
94 	 * setting the ZFS_STACK_SIZE environment variable.  This allows us
95 	 * the convenience of observing and debugging stack overruns in
96 	 * user space.  Explicitly specified stack sizes will be honored.
97 	 * The usage of ZFS_STACK_SIZE is discussed further in the
98 	 * ENVIRONMENT VARIABLES sections of the ztest(1) man page.
99 	 */
100 	if (stksize == 0) {
101 		stkstr = getenv("ZFS_STACK_SIZE");
102 
103 		if (stkstr == NULL)
104 			stksize = TS_STACK_MAX;
105 		else
106 			stksize = MAX(atoi(stkstr), TS_STACK_MIN);
107 	}
108 
109 	VERIFY3S(stksize, >, 0);
110 	stksize = P2ROUNDUP(MAX(stksize, TS_STACK_MIN), PAGESIZE);
111 
112 	/*
113 	 * If this ever fails, it may be because the stack size is not a
114 	 * multiple of system page size.
115 	 */
116 	VERIFY0(pthread_attr_setstacksize(&attr, stksize));
117 	VERIFY0(pthread_attr_setguardsize(&attr, PAGESIZE));
118 
119 	VERIFY0(pthread_create(&tid, &attr, (void *(*)(void *))func, arg));
120 	VERIFY0(pthread_attr_destroy(&attr));
121 
122 	return ((void *)(uintptr_t)tid);
123 }
124 
125 /*
126  * =========================================================================
127  * kstats
128  * =========================================================================
129  */
130 /*ARGSUSED*/
131 kstat_t *
132 kstat_create(const char *module, int instance, const char *name,
133     const char *class, uchar_t type, ulong_t ndata, uchar_t ks_flag)
134 {
135 	return (NULL);
136 }
137 
138 /*ARGSUSED*/
139 void
140 kstat_install(kstat_t *ksp)
141 {}
142 
143 /*ARGSUSED*/
144 void
145 kstat_delete(kstat_t *ksp)
146 {}
147 
148 /*ARGSUSED*/
149 void
150 kstat_waitq_enter(kstat_io_t *kiop)
151 {}
152 
153 /*ARGSUSED*/
154 void
155 kstat_waitq_exit(kstat_io_t *kiop)
156 {}
157 
158 /*ARGSUSED*/
159 void
160 kstat_runq_enter(kstat_io_t *kiop)
161 {}
162 
163 /*ARGSUSED*/
164 void
165 kstat_runq_exit(kstat_io_t *kiop)
166 {}
167 
168 /*ARGSUSED*/
169 void
170 kstat_waitq_to_runq(kstat_io_t *kiop)
171 {}
172 
173 /*ARGSUSED*/
174 void
175 kstat_runq_back_to_waitq(kstat_io_t *kiop)
176 {}
177 
178 void
179 kstat_set_raw_ops(kstat_t *ksp,
180     int (*headers)(char *buf, size_t size),
181     int (*data)(char *buf, size_t size, void *data),
182     void *(*addr)(kstat_t *ksp, loff_t index))
183 {}
184 
185 /*
186  * =========================================================================
187  * mutexes
188  * =========================================================================
189  */
190 
191 void
192 mutex_init(kmutex_t *mp, char *name, int type, void *cookie)
193 {
194 	VERIFY0(pthread_mutex_init(&mp->m_lock, NULL));
195 	memset(&mp->m_owner, 0, sizeof (pthread_t));
196 }
197 
198 void
199 mutex_destroy(kmutex_t *mp)
200 {
201 	VERIFY0(pthread_mutex_destroy(&mp->m_lock));
202 }
203 
204 void
205 mutex_enter(kmutex_t *mp)
206 {
207 	VERIFY0(pthread_mutex_lock(&mp->m_lock));
208 	mp->m_owner = pthread_self();
209 }
210 
211 int
212 mutex_tryenter(kmutex_t *mp)
213 {
214 	int error;
215 
216 	error = pthread_mutex_trylock(&mp->m_lock);
217 	if (error == 0) {
218 		mp->m_owner = pthread_self();
219 		return (1);
220 	} else {
221 		VERIFY3S(error, ==, EBUSY);
222 		return (0);
223 	}
224 }
225 
226 void
227 mutex_exit(kmutex_t *mp)
228 {
229 	memset(&mp->m_owner, 0, sizeof (pthread_t));
230 	VERIFY0(pthread_mutex_unlock(&mp->m_lock));
231 }
232 
233 /*
234  * =========================================================================
235  * rwlocks
236  * =========================================================================
237  */
238 
239 void
240 rw_init(krwlock_t *rwlp, char *name, int type, void *arg)
241 {
242 	VERIFY0(pthread_rwlock_init(&rwlp->rw_lock, NULL));
243 	rwlp->rw_readers = 0;
244 	rwlp->rw_owner = 0;
245 }
246 
247 void
248 rw_destroy(krwlock_t *rwlp)
249 {
250 	VERIFY0(pthread_rwlock_destroy(&rwlp->rw_lock));
251 }
252 
253 void
254 rw_enter(krwlock_t *rwlp, krw_t rw)
255 {
256 	if (rw == RW_READER) {
257 		VERIFY0(pthread_rwlock_rdlock(&rwlp->rw_lock));
258 		atomic_inc_uint(&rwlp->rw_readers);
259 	} else {
260 		VERIFY0(pthread_rwlock_wrlock(&rwlp->rw_lock));
261 		rwlp->rw_owner = pthread_self();
262 	}
263 }
264 
265 void
266 rw_exit(krwlock_t *rwlp)
267 {
268 	if (RW_READ_HELD(rwlp))
269 		atomic_dec_uint(&rwlp->rw_readers);
270 	else
271 		rwlp->rw_owner = 0;
272 
273 	VERIFY0(pthread_rwlock_unlock(&rwlp->rw_lock));
274 }
275 
276 int
277 rw_tryenter(krwlock_t *rwlp, krw_t rw)
278 {
279 	int error;
280 
281 	if (rw == RW_READER)
282 		error = pthread_rwlock_tryrdlock(&rwlp->rw_lock);
283 	else
284 		error = pthread_rwlock_trywrlock(&rwlp->rw_lock);
285 
286 	if (error == 0) {
287 		if (rw == RW_READER)
288 			atomic_inc_uint(&rwlp->rw_readers);
289 		else
290 			rwlp->rw_owner = pthread_self();
291 
292 		return (1);
293 	}
294 
295 	VERIFY3S(error, ==, EBUSY);
296 
297 	return (0);
298 }
299 
300 /* ARGSUSED */
301 uint32_t
302 zone_get_hostid(void *zonep)
303 {
304 	/*
305 	 * We're emulating the system's hostid in userland.
306 	 */
307 	return (strtoul(hw_serial, NULL, 10));
308 }
309 
310 int
311 rw_tryupgrade(krwlock_t *rwlp)
312 {
313 	return (0);
314 }
315 
316 /*
317  * =========================================================================
318  * condition variables
319  * =========================================================================
320  */
321 
322 void
323 cv_init(kcondvar_t *cv, char *name, int type, void *arg)
324 {
325 	VERIFY0(pthread_cond_init(cv, NULL));
326 }
327 
328 void
329 cv_destroy(kcondvar_t *cv)
330 {
331 	VERIFY0(pthread_cond_destroy(cv));
332 }
333 
334 void
335 cv_wait(kcondvar_t *cv, kmutex_t *mp)
336 {
337 	memset(&mp->m_owner, 0, sizeof (pthread_t));
338 	VERIFY0(pthread_cond_wait(cv, &mp->m_lock));
339 	mp->m_owner = pthread_self();
340 }
341 
342 int
343 cv_wait_sig(kcondvar_t *cv, kmutex_t *mp)
344 {
345 	cv_wait(cv, mp);
346 	return (1);
347 }
348 
349 int
350 cv_timedwait(kcondvar_t *cv, kmutex_t *mp, clock_t abstime)
351 {
352 	int error;
353 	struct timeval tv;
354 	struct timespec ts;
355 	clock_t delta;
356 
357 	delta = abstime - ddi_get_lbolt();
358 	if (delta <= 0)
359 		return (-1);
360 
361 	VERIFY(gettimeofday(&tv, NULL) == 0);
362 
363 	ts.tv_sec = tv.tv_sec + delta / hz;
364 	ts.tv_nsec = tv.tv_usec * NSEC_PER_USEC + (delta % hz) * (NANOSEC / hz);
365 	if (ts.tv_nsec >= NANOSEC) {
366 		ts.tv_sec++;
367 		ts.tv_nsec -= NANOSEC;
368 	}
369 
370 	memset(&mp->m_owner, 0, sizeof (pthread_t));
371 	error = pthread_cond_timedwait(cv, &mp->m_lock, &ts);
372 	mp->m_owner = pthread_self();
373 
374 	if (error == ETIMEDOUT)
375 		return (-1);
376 
377 	VERIFY0(error);
378 
379 	return (1);
380 }
381 
382 /*ARGSUSED*/
383 int
384 cv_timedwait_hires(kcondvar_t *cv, kmutex_t *mp, hrtime_t tim, hrtime_t res,
385     int flag)
386 {
387 	int error;
388 	struct timeval tv;
389 	struct timespec ts;
390 	hrtime_t delta;
391 
392 	ASSERT(flag == 0 || flag == CALLOUT_FLAG_ABSOLUTE);
393 
394 	delta = tim;
395 	if (flag & CALLOUT_FLAG_ABSOLUTE)
396 		delta -= gethrtime();
397 
398 	if (delta <= 0)
399 		return (-1);
400 
401 	VERIFY0(gettimeofday(&tv, NULL));
402 
403 	ts.tv_sec = tv.tv_sec + delta / NANOSEC;
404 	ts.tv_nsec = tv.tv_usec * NSEC_PER_USEC + (delta % NANOSEC);
405 	if (ts.tv_nsec >= NANOSEC) {
406 		ts.tv_sec++;
407 		ts.tv_nsec -= NANOSEC;
408 	}
409 
410 	memset(&mp->m_owner, 0, sizeof (pthread_t));
411 	error = pthread_cond_timedwait(cv, &mp->m_lock, &ts);
412 	mp->m_owner = pthread_self();
413 
414 	if (error == ETIMEDOUT)
415 		return (-1);
416 
417 	VERIFY0(error);
418 
419 	return (1);
420 }
421 
422 void
423 cv_signal(kcondvar_t *cv)
424 {
425 	VERIFY0(pthread_cond_signal(cv));
426 }
427 
428 void
429 cv_broadcast(kcondvar_t *cv)
430 {
431 	VERIFY0(pthread_cond_broadcast(cv));
432 }
433 
434 /*
435  * =========================================================================
436  * procfs list
437  * =========================================================================
438  */
439 
440 void
441 seq_printf(struct seq_file *m, const char *fmt, ...)
442 {}
443 
444 void
445 procfs_list_install(const char *module,
446     const char *name,
447     mode_t mode,
448     procfs_list_t *procfs_list,
449     int (*show)(struct seq_file *f, void *p),
450     int (*show_header)(struct seq_file *f),
451     int (*clear)(procfs_list_t *procfs_list),
452     size_t procfs_list_node_off)
453 {
454 	mutex_init(&procfs_list->pl_lock, NULL, MUTEX_DEFAULT, NULL);
455 	list_create(&procfs_list->pl_list,
456 	    procfs_list_node_off + sizeof (procfs_list_node_t),
457 	    procfs_list_node_off + offsetof(procfs_list_node_t, pln_link));
458 	procfs_list->pl_next_id = 1;
459 	procfs_list->pl_node_offset = procfs_list_node_off;
460 }
461 
462 void
463 procfs_list_uninstall(procfs_list_t *procfs_list)
464 {}
465 
466 void
467 procfs_list_destroy(procfs_list_t *procfs_list)
468 {
469 	ASSERT(list_is_empty(&procfs_list->pl_list));
470 	list_destroy(&procfs_list->pl_list);
471 	mutex_destroy(&procfs_list->pl_lock);
472 }
473 
474 #define	NODE_ID(procfs_list, obj) \
475 		(((procfs_list_node_t *)(((char *)obj) + \
476 		(procfs_list)->pl_node_offset))->pln_id)
477 
478 void
479 procfs_list_add(procfs_list_t *procfs_list, void *p)
480 {
481 	ASSERT(MUTEX_HELD(&procfs_list->pl_lock));
482 	NODE_ID(procfs_list, p) = procfs_list->pl_next_id++;
483 	list_insert_tail(&procfs_list->pl_list, p);
484 }
485 
486 /*
487  * =========================================================================
488  * vnode operations
489  * =========================================================================
490  */
491 
492 /*
493  * =========================================================================
494  * Figure out which debugging statements to print
495  * =========================================================================
496  */
497 
498 static char *dprintf_string;
499 static int dprintf_print_all;
500 
501 int
502 dprintf_find_string(const char *string)
503 {
504 	char *tmp_str = dprintf_string;
505 	int len = strlen(string);
506 
507 	/*
508 	 * Find out if this is a string we want to print.
509 	 * String format: file1.c,function_name1,file2.c,file3.c
510 	 */
511 
512 	while (tmp_str != NULL) {
513 		if (strncmp(tmp_str, string, len) == 0 &&
514 		    (tmp_str[len] == ',' || tmp_str[len] == '\0'))
515 			return (1);
516 		tmp_str = strchr(tmp_str, ',');
517 		if (tmp_str != NULL)
518 			tmp_str++; /* Get rid of , */
519 	}
520 	return (0);
521 }
522 
523 void
524 dprintf_setup(int *argc, char **argv)
525 {
526 	int i, j;
527 
528 	/*
529 	 * Debugging can be specified two ways: by setting the
530 	 * environment variable ZFS_DEBUG, or by including a
531 	 * "debug=..."  argument on the command line.  The command
532 	 * line setting overrides the environment variable.
533 	 */
534 
535 	for (i = 1; i < *argc; i++) {
536 		int len = strlen("debug=");
537 		/* First look for a command line argument */
538 		if (strncmp("debug=", argv[i], len) == 0) {
539 			dprintf_string = argv[i] + len;
540 			/* Remove from args */
541 			for (j = i; j < *argc; j++)
542 				argv[j] = argv[j+1];
543 			argv[j] = NULL;
544 			(*argc)--;
545 		}
546 	}
547 
548 	if (dprintf_string == NULL) {
549 		/* Look for ZFS_DEBUG environment variable */
550 		dprintf_string = getenv("ZFS_DEBUG");
551 	}
552 
553 	/*
554 	 * Are we just turning on all debugging?
555 	 */
556 	if (dprintf_find_string("on"))
557 		dprintf_print_all = 1;
558 
559 	if (dprintf_string != NULL)
560 		zfs_flags |= ZFS_DEBUG_DPRINTF;
561 }
562 
563 /*
564  * =========================================================================
565  * debug printfs
566  * =========================================================================
567  */
568 void
569 __dprintf(boolean_t dprint, const char *file, const char *func,
570     int line, const char *fmt, ...)
571 {
572 	const char *newfile;
573 	va_list adx;
574 
575 	/*
576 	 * Get rid of annoying "../common/" prefix to filename.
577 	 */
578 	newfile = strrchr(file, '/');
579 	if (newfile != NULL) {
580 		newfile = newfile + 1; /* Get rid of leading / */
581 	} else {
582 		newfile = file;
583 	}
584 
585 	if (dprint) {
586 		/* dprintf messages are printed immediately */
587 
588 		if (!dprintf_print_all &&
589 		    !dprintf_find_string(newfile) &&
590 		    !dprintf_find_string(func))
591 			return;
592 
593 		/* Print out just the function name if requested */
594 		flockfile(stdout);
595 		if (dprintf_find_string("pid"))
596 			(void) printf("%d ", getpid());
597 		if (dprintf_find_string("tid"))
598 			(void) printf("%ju ",
599 			    (uintmax_t)(uintptr_t)pthread_self());
600 		if (dprintf_find_string("cpu"))
601 			(void) printf("%u ", getcpuid());
602 		if (dprintf_find_string("time"))
603 			(void) printf("%llu ", gethrtime());
604 		if (dprintf_find_string("long"))
605 			(void) printf("%s, line %d: ", newfile, line);
606 		(void) printf("dprintf: %s: ", func);
607 		va_start(adx, fmt);
608 		(void) vprintf(fmt, adx);
609 		va_end(adx);
610 		funlockfile(stdout);
611 	} else {
612 		/* zfs_dbgmsg is logged for dumping later */
613 		size_t size;
614 		char *buf;
615 		int i;
616 
617 		size = 1024;
618 		buf = umem_alloc(size, UMEM_NOFAIL);
619 		i = snprintf(buf, size, "%s:%d:%s(): ", newfile, line, func);
620 
621 		if (i < size) {
622 			va_start(adx, fmt);
623 			(void) vsnprintf(buf + i, size - i, fmt, adx);
624 			va_end(adx);
625 		}
626 
627 		__zfs_dbgmsg(buf);
628 
629 		umem_free(buf, size);
630 	}
631 }
632 
633 /*
634  * =========================================================================
635  * cmn_err() and panic()
636  * =========================================================================
637  */
638 static char ce_prefix[CE_IGNORE][10] = { "", "NOTICE: ", "WARNING: ", "" };
639 static char ce_suffix[CE_IGNORE][2] = { "", "\n", "\n", "" };
640 
641 void
642 vpanic(const char *fmt, va_list adx)
643 {
644 	(void) fprintf(stderr, "error: ");
645 	(void) vfprintf(stderr, fmt, adx);
646 	(void) fprintf(stderr, "\n");
647 
648 	abort();	/* think of it as a "user-level crash dump" */
649 }
650 
651 void
652 panic(const char *fmt, ...)
653 {
654 	va_list adx;
655 
656 	va_start(adx, fmt);
657 	vpanic(fmt, adx);
658 	va_end(adx);
659 }
660 
661 void
662 vcmn_err(int ce, const char *fmt, va_list adx)
663 {
664 	if (ce == CE_PANIC)
665 		vpanic(fmt, adx);
666 	if (ce != CE_NOTE) {	/* suppress noise in userland stress testing */
667 		(void) fprintf(stderr, "%s", ce_prefix[ce]);
668 		(void) vfprintf(stderr, fmt, adx);
669 		(void) fprintf(stderr, "%s", ce_suffix[ce]);
670 	}
671 }
672 
673 /*PRINTFLIKE2*/
674 void
675 cmn_err(int ce, const char *fmt, ...)
676 {
677 	va_list adx;
678 
679 	va_start(adx, fmt);
680 	vcmn_err(ce, fmt, adx);
681 	va_end(adx);
682 }
683 
684 /*
685  * =========================================================================
686  * misc routines
687  * =========================================================================
688  */
689 
690 void
691 delay(clock_t ticks)
692 {
693 	(void) poll(0, 0, ticks * (1000 / hz));
694 }
695 
696 /*
697  * Find highest one bit set.
698  * Returns bit number + 1 of highest bit that is set, otherwise returns 0.
699  * The __builtin_clzll() function is supported by both GCC and Clang.
700  */
701 int
702 highbit64(uint64_t i)
703 {
704 	if (i == 0)
705 	return (0);
706 
707 	return (NBBY * sizeof (uint64_t) - __builtin_clzll(i));
708 }
709 
710 /*
711  * Find lowest one bit set.
712  * Returns bit number + 1 of lowest bit that is set, otherwise returns 0.
713  * The __builtin_ffsll() function is supported by both GCC and Clang.
714  */
715 int
716 lowbit64(uint64_t i)
717 {
718 	if (i == 0)
719 		return (0);
720 
721 	return (__builtin_ffsll(i));
722 }
723 
724 char *random_path = "/dev/random";
725 char *urandom_path = "/dev/urandom";
726 static int random_fd = -1, urandom_fd = -1;
727 
728 void
729 random_init(void)
730 {
731 	VERIFY((random_fd = open(random_path, O_RDONLY)) != -1);
732 	VERIFY((urandom_fd = open(urandom_path, O_RDONLY)) != -1);
733 }
734 
735 void
736 random_fini(void)
737 {
738 	close(random_fd);
739 	close(urandom_fd);
740 
741 	random_fd = -1;
742 	urandom_fd = -1;
743 }
744 
745 static int
746 random_get_bytes_common(uint8_t *ptr, size_t len, int fd)
747 {
748 	size_t resid = len;
749 	ssize_t bytes;
750 
751 	ASSERT(fd != -1);
752 
753 	while (resid != 0) {
754 		bytes = read(fd, ptr, resid);
755 		ASSERT3S(bytes, >=, 0);
756 		ptr += bytes;
757 		resid -= bytes;
758 	}
759 
760 	return (0);
761 }
762 
763 int
764 random_get_bytes(uint8_t *ptr, size_t len)
765 {
766 	return (random_get_bytes_common(ptr, len, random_fd));
767 }
768 
769 int
770 random_get_pseudo_bytes(uint8_t *ptr, size_t len)
771 {
772 	return (random_get_bytes_common(ptr, len, urandom_fd));
773 }
774 
775 int
776 ddi_strtoul(const char *hw_serial, char **nptr, int base, unsigned long *result)
777 {
778 	char *end;
779 
780 	*result = strtoul(hw_serial, &end, base);
781 	if (*result == 0)
782 		return (errno);
783 	return (0);
784 }
785 
786 int
787 ddi_strtoull(const char *str, char **nptr, int base, u_longlong_t *result)
788 {
789 	char *end;
790 
791 	*result = strtoull(str, &end, base);
792 	if (*result == 0)
793 		return (errno);
794 	return (0);
795 }
796 
797 utsname_t *
798 utsname(void)
799 {
800 	return (&hw_utsname);
801 }
802 
803 /*
804  * =========================================================================
805  * kernel emulation setup & teardown
806  * =========================================================================
807  */
808 static int
809 umem_out_of_memory(void)
810 {
811 	char errmsg[] = "out of memory -- generating core dump\n";
812 
813 	(void) fprintf(stderr, "%s", errmsg);
814 	abort();
815 	return (0);
816 }
817 
818 void
819 kernel_init(int mode)
820 {
821 	extern uint_t rrw_tsd_key;
822 
823 	umem_nofail_callback(umem_out_of_memory);
824 
825 	physmem = sysconf(_SC_PHYS_PAGES);
826 
827 	dprintf("physmem = %llu pages (%.2f GB)\n", physmem,
828 	    (double)physmem * sysconf(_SC_PAGE_SIZE) / (1ULL << 30));
829 
830 	(void) snprintf(hw_serial, sizeof (hw_serial), "%ld",
831 	    (mode & SPA_MODE_WRITE) ? get_system_hostid() : 0);
832 
833 	random_init();
834 
835 	VERIFY0(uname(&hw_utsname));
836 
837 	system_taskq_init();
838 	icp_init();
839 
840 	zstd_init();
841 
842 	spa_init((spa_mode_t)mode);
843 
844 	fletcher_4_init();
845 
846 	tsd_create(&rrw_tsd_key, rrw_tsd_destroy);
847 }
848 
849 void
850 kernel_fini(void)
851 {
852 	fletcher_4_fini();
853 	spa_fini();
854 
855 	zstd_fini();
856 
857 	icp_fini();
858 	system_taskq_fini();
859 
860 	random_fini();
861 }
862 
863 uid_t
864 crgetuid(cred_t *cr)
865 {
866 	return (0);
867 }
868 
869 uid_t
870 crgetruid(cred_t *cr)
871 {
872 	return (0);
873 }
874 
875 gid_t
876 crgetgid(cred_t *cr)
877 {
878 	return (0);
879 }
880 
881 int
882 crgetngroups(cred_t *cr)
883 {
884 	return (0);
885 }
886 
887 gid_t *
888 crgetgroups(cred_t *cr)
889 {
890 	return (NULL);
891 }
892 
893 int
894 zfs_secpolicy_snapshot_perms(const char *name, cred_t *cr)
895 {
896 	return (0);
897 }
898 
899 int
900 zfs_secpolicy_rename_perms(const char *from, const char *to, cred_t *cr)
901 {
902 	return (0);
903 }
904 
905 int
906 zfs_secpolicy_destroy_perms(const char *name, cred_t *cr)
907 {
908 	return (0);
909 }
910 
911 int
912 secpolicy_zfs(const cred_t *cr)
913 {
914 	return (0);
915 }
916 
917 int
918 secpolicy_zfs_proc(const cred_t *cr, proc_t *proc)
919 {
920 	return (0);
921 }
922 
923 ksiddomain_t *
924 ksid_lookupdomain(const char *dom)
925 {
926 	ksiddomain_t *kd;
927 
928 	kd = umem_zalloc(sizeof (ksiddomain_t), UMEM_NOFAIL);
929 	kd->kd_name = spa_strdup(dom);
930 	return (kd);
931 }
932 
933 void
934 ksiddomain_rele(ksiddomain_t *ksid)
935 {
936 	spa_strfree(ksid->kd_name);
937 	umem_free(ksid, sizeof (ksiddomain_t));
938 }
939 
940 char *
941 kmem_vasprintf(const char *fmt, va_list adx)
942 {
943 	char *buf = NULL;
944 	va_list adx_copy;
945 
946 	va_copy(adx_copy, adx);
947 	VERIFY(vasprintf(&buf, fmt, adx_copy) != -1);
948 	va_end(adx_copy);
949 
950 	return (buf);
951 }
952 
953 char *
954 kmem_asprintf(const char *fmt, ...)
955 {
956 	char *buf = NULL;
957 	va_list adx;
958 
959 	va_start(adx, fmt);
960 	VERIFY(vasprintf(&buf, fmt, adx) != -1);
961 	va_end(adx);
962 
963 	return (buf);
964 }
965 
966 /* ARGSUSED */
967 int
968 zfs_onexit_fd_hold(int fd, minor_t *minorp)
969 {
970 	*minorp = 0;
971 	return (0);
972 }
973 
974 /* ARGSUSED */
975 void
976 zfs_onexit_fd_rele(int fd)
977 {
978 }
979 
980 /* ARGSUSED */
981 int
982 zfs_onexit_add_cb(minor_t minor, void (*func)(void *), void *data,
983     uint64_t *action_handle)
984 {
985 	return (0);
986 }
987 
988 fstrans_cookie_t
989 spl_fstrans_mark(void)
990 {
991 	return ((fstrans_cookie_t)0);
992 }
993 
994 void
995 spl_fstrans_unmark(fstrans_cookie_t cookie)
996 {
997 }
998 
999 int
1000 __spl_pf_fstrans_check(void)
1001 {
1002 	return (0);
1003 }
1004 
1005 int
1006 kmem_cache_reap_active(void)
1007 {
1008 	return (0);
1009 }
1010 
1011 void *zvol_tag = "zvol_tag";
1012 
1013 void
1014 zvol_create_minor(const char *name)
1015 {
1016 }
1017 
1018 void
1019 zvol_create_minors_recursive(const char *name)
1020 {
1021 }
1022 
1023 void
1024 zvol_remove_minors(spa_t *spa, const char *name, boolean_t async)
1025 {
1026 }
1027 
1028 void
1029 zvol_rename_minors(spa_t *spa, const char *oldname, const char *newname,
1030     boolean_t async)
1031 {
1032 }
1033 
1034 /*
1035  * Open file
1036  *
1037  * path - fully qualified path to file
1038  * flags - file attributes O_READ / O_WRITE / O_EXCL
1039  * fpp - pointer to return file pointer
1040  *
1041  * Returns 0 on success underlying error on failure.
1042  */
1043 int
1044 zfs_file_open(const char *path, int flags, int mode, zfs_file_t **fpp)
1045 {
1046 	int fd = -1;
1047 	int dump_fd = -1;
1048 	int err;
1049 	int old_umask = 0;
1050 	zfs_file_t *fp;
1051 	struct stat64 st;
1052 
1053 	if (!(flags & O_CREAT) && stat64(path, &st) == -1)
1054 		return (errno);
1055 
1056 	if (!(flags & O_CREAT) && S_ISBLK(st.st_mode))
1057 		flags |= O_DIRECT;
1058 
1059 	if (flags & O_CREAT)
1060 		old_umask = umask(0);
1061 
1062 	fd = open64(path, flags, mode);
1063 	if (fd == -1)
1064 		return (errno);
1065 
1066 	if (flags & O_CREAT)
1067 		(void) umask(old_umask);
1068 
1069 	if (vn_dumpdir != NULL) {
1070 		char *dumppath = umem_zalloc(MAXPATHLEN, UMEM_NOFAIL);
1071 		char *inpath = basename((char *)(uintptr_t)path);
1072 
1073 		(void) snprintf(dumppath, MAXPATHLEN,
1074 		    "%s/%s", vn_dumpdir, inpath);
1075 		dump_fd = open64(dumppath, O_CREAT | O_WRONLY, 0666);
1076 		umem_free(dumppath, MAXPATHLEN);
1077 		if (dump_fd == -1) {
1078 			err = errno;
1079 			close(fd);
1080 			return (err);
1081 		}
1082 	} else {
1083 		dump_fd = -1;
1084 	}
1085 
1086 	(void) fcntl(fd, F_SETFD, FD_CLOEXEC);
1087 
1088 	fp = umem_zalloc(sizeof (zfs_file_t), UMEM_NOFAIL);
1089 	fp->f_fd = fd;
1090 	fp->f_dump_fd = dump_fd;
1091 	*fpp = fp;
1092 
1093 	return (0);
1094 }
1095 
1096 void
1097 zfs_file_close(zfs_file_t *fp)
1098 {
1099 	close(fp->f_fd);
1100 	if (fp->f_dump_fd != -1)
1101 		close(fp->f_dump_fd);
1102 
1103 	umem_free(fp, sizeof (zfs_file_t));
1104 }
1105 
1106 /*
1107  * Stateful write - use os internal file pointer to determine where to
1108  * write and update on successful completion.
1109  *
1110  * fp -  pointer to file (pipe, socket, etc) to write to
1111  * buf - buffer to write
1112  * count - # of bytes to write
1113  * resid -  pointer to count of unwritten bytes  (if short write)
1114  *
1115  * Returns 0 on success errno on failure.
1116  */
1117 int
1118 zfs_file_write(zfs_file_t *fp, const void *buf, size_t count, ssize_t *resid)
1119 {
1120 	ssize_t rc;
1121 
1122 	rc = write(fp->f_fd, buf, count);
1123 	if (rc < 0)
1124 		return (errno);
1125 
1126 	if (resid) {
1127 		*resid = count - rc;
1128 	} else if (rc != count) {
1129 		return (EIO);
1130 	}
1131 
1132 	return (0);
1133 }
1134 
1135 /*
1136  * Stateless write - os internal file pointer is not updated.
1137  *
1138  * fp -  pointer to file (pipe, socket, etc) to write to
1139  * buf - buffer to write
1140  * count - # of bytes to write
1141  * off - file offset to write to (only valid for seekable types)
1142  * resid -  pointer to count of unwritten bytes
1143  *
1144  * Returns 0 on success errno on failure.
1145  */
1146 int
1147 zfs_file_pwrite(zfs_file_t *fp, const void *buf,
1148     size_t count, loff_t pos, ssize_t *resid)
1149 {
1150 	ssize_t rc, split, done;
1151 	int sectors;
1152 
1153 	/*
1154 	 * To simulate partial disk writes, we split writes into two
1155 	 * system calls so that the process can be killed in between.
1156 	 * This is used by ztest to simulate realistic failure modes.
1157 	 */
1158 	sectors = count >> SPA_MINBLOCKSHIFT;
1159 	split = (sectors > 0 ? rand() % sectors : 0) << SPA_MINBLOCKSHIFT;
1160 	rc = pwrite64(fp->f_fd, buf, split, pos);
1161 	if (rc != -1) {
1162 		done = rc;
1163 		rc = pwrite64(fp->f_fd, (char *)buf + split,
1164 		    count - split, pos + split);
1165 	}
1166 #ifdef __linux__
1167 	if (rc == -1 && errno == EINVAL) {
1168 		/*
1169 		 * Under Linux, this most likely means an alignment issue
1170 		 * (memory or disk) due to O_DIRECT, so we abort() in order
1171 		 * to catch the offender.
1172 		 */
1173 		abort();
1174 	}
1175 #endif
1176 
1177 	if (rc < 0)
1178 		return (errno);
1179 
1180 	done += rc;
1181 
1182 	if (resid) {
1183 		*resid = count - done;
1184 	} else if (done != count) {
1185 		return (EIO);
1186 	}
1187 
1188 	return (0);
1189 }
1190 
1191 /*
1192  * Stateful read - use os internal file pointer to determine where to
1193  * read and update on successful completion.
1194  *
1195  * fp -  pointer to file (pipe, socket, etc) to read from
1196  * buf - buffer to write
1197  * count - # of bytes to read
1198  * resid -  pointer to count of unread bytes (if short read)
1199  *
1200  * Returns 0 on success errno on failure.
1201  */
1202 int
1203 zfs_file_read(zfs_file_t *fp, void *buf, size_t count, ssize_t *resid)
1204 {
1205 	int rc;
1206 
1207 	rc = read(fp->f_fd, buf, count);
1208 	if (rc < 0)
1209 		return (errno);
1210 
1211 	if (resid) {
1212 		*resid = count - rc;
1213 	} else if (rc != count) {
1214 		return (EIO);
1215 	}
1216 
1217 	return (0);
1218 }
1219 
1220 /*
1221  * Stateless read - os internal file pointer is not updated.
1222  *
1223  * fp -  pointer to file (pipe, socket, etc) to read from
1224  * buf - buffer to write
1225  * count - # of bytes to write
1226  * off - file offset to read from (only valid for seekable types)
1227  * resid -  pointer to count of unwritten bytes (if short write)
1228  *
1229  * Returns 0 on success errno on failure.
1230  */
1231 int
1232 zfs_file_pread(zfs_file_t *fp, void *buf, size_t count, loff_t off,
1233     ssize_t *resid)
1234 {
1235 	ssize_t rc;
1236 
1237 	rc = pread64(fp->f_fd, buf, count, off);
1238 	if (rc < 0) {
1239 #ifdef __linux__
1240 		/*
1241 		 * Under Linux, this most likely means an alignment issue
1242 		 * (memory or disk) due to O_DIRECT, so we abort() in order to
1243 		 * catch the offender.
1244 		 */
1245 		if (errno == EINVAL)
1246 			abort();
1247 #endif
1248 		return (errno);
1249 	}
1250 
1251 	if (fp->f_dump_fd != -1) {
1252 		int status;
1253 
1254 		status = pwrite64(fp->f_dump_fd, buf, rc, off);
1255 		ASSERT(status != -1);
1256 	}
1257 
1258 	if (resid) {
1259 		*resid = count - rc;
1260 	} else if (rc != count) {
1261 		return (EIO);
1262 	}
1263 
1264 	return (0);
1265 }
1266 
1267 /*
1268  * lseek - set / get file pointer
1269  *
1270  * fp -  pointer to file (pipe, socket, etc) to read from
1271  * offp - value to seek to, returns current value plus passed offset
1272  * whence - see man pages for standard lseek whence values
1273  *
1274  * Returns 0 on success errno on failure (ESPIPE for non seekable types)
1275  */
1276 int
1277 zfs_file_seek(zfs_file_t *fp, loff_t *offp, int whence)
1278 {
1279 	loff_t rc;
1280 
1281 	rc = lseek(fp->f_fd, *offp, whence);
1282 	if (rc < 0)
1283 		return (errno);
1284 
1285 	*offp = rc;
1286 
1287 	return (0);
1288 }
1289 
1290 /*
1291  * Get file attributes
1292  *
1293  * filp - file pointer
1294  * zfattr - pointer to file attr structure
1295  *
1296  * Currently only used for fetching size and file mode
1297  *
1298  * Returns 0 on success or error code of underlying getattr call on failure.
1299  */
1300 int
1301 zfs_file_getattr(zfs_file_t *fp, zfs_file_attr_t *zfattr)
1302 {
1303 	struct stat64 st;
1304 
1305 	if (fstat64_blk(fp->f_fd, &st) == -1)
1306 		return (errno);
1307 
1308 	zfattr->zfa_size = st.st_size;
1309 	zfattr->zfa_mode = st.st_mode;
1310 
1311 	return (0);
1312 }
1313 
1314 /*
1315  * Sync file to disk
1316  *
1317  * filp - file pointer
1318  * flags - O_SYNC and or O_DSYNC
1319  *
1320  * Returns 0 on success or error code of underlying sync call on failure.
1321  */
1322 int
1323 zfs_file_fsync(zfs_file_t *fp, int flags)
1324 {
1325 	int rc;
1326 
1327 	rc = fsync(fp->f_fd);
1328 	if (rc < 0)
1329 		return (errno);
1330 
1331 	return (0);
1332 }
1333 
1334 /*
1335  * fallocate - allocate or free space on disk
1336  *
1337  * fp - file pointer
1338  * mode (non-standard options for hole punching etc)
1339  * offset - offset to start allocating or freeing from
1340  * len - length to free / allocate
1341  *
1342  * OPTIONAL
1343  */
1344 int
1345 zfs_file_fallocate(zfs_file_t *fp, int mode, loff_t offset, loff_t len)
1346 {
1347 #ifdef __linux__
1348 	return (fallocate(fp->f_fd, mode, offset, len));
1349 #else
1350 	return (EOPNOTSUPP);
1351 #endif
1352 }
1353 
1354 /*
1355  * Request current file pointer offset
1356  *
1357  * fp - pointer to file
1358  *
1359  * Returns current file offset.
1360  */
1361 loff_t
1362 zfs_file_off(zfs_file_t *fp)
1363 {
1364 	return (lseek(fp->f_fd, SEEK_CUR, 0));
1365 }
1366 
1367 /*
1368  * unlink file
1369  *
1370  * path - fully qualified file path
1371  *
1372  * Returns 0 on success.
1373  *
1374  * OPTIONAL
1375  */
1376 int
1377 zfs_file_unlink(const char *path)
1378 {
1379 	return (remove(path));
1380 }
1381 
1382 /*
1383  * Get reference to file pointer
1384  *
1385  * fd - input file descriptor
1386  * fpp - pointer to file pointer
1387  *
1388  * Returns 0 on success EBADF on failure.
1389  * Unsupported in user space.
1390  */
1391 int
1392 zfs_file_get(int fd, zfs_file_t **fpp)
1393 {
1394 	abort();
1395 
1396 	return (EOPNOTSUPP);
1397 }
1398 
1399 /*
1400  * Drop reference to file pointer
1401  *
1402  * fd - input file descriptor
1403  *
1404  * Unsupported in user space.
1405  */
1406 void
1407 zfs_file_put(int fd)
1408 {
1409 	abort();
1410 }
1411