xref: /titanic_52/usr/src/lib/libzpool/common/kernel.c (revision 28f2c52052034474a5881e13013564f72ffa345f)
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 by Delphix. All rights reserved.
24  */
25 
26 #include <assert.h>
27 #include <fcntl.h>
28 #include <poll.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <zlib.h>
33 #include <sys/spa.h>
34 #include <sys/stat.h>
35 #include <sys/processor.h>
36 #include <sys/zfs_context.h>
37 #include <sys/zmod.h>
38 #include <sys/utsname.h>
39 #include <sys/systeminfo.h>
40 
41 /*
42  * Emulation of kernel services in userland.
43  */
44 
45 int aok;
46 uint64_t physmem;
47 vnode_t *rootdir = (vnode_t *)0xabcd1234;
48 char hw_serial[HW_HOSTID_LEN];
49 kmutex_t cpu_lock;
50 vmem_t *zio_arena = NULL;
51 
52 struct utsname utsname = {
53 	"userland", "libzpool", "1", "1", "na"
54 };
55 
56 /* this only exists to have its address taken */
57 struct proc p0;
58 
59 /*
60  * =========================================================================
61  * threads
62  * =========================================================================
63  */
64 /*ARGSUSED*/
65 kthread_t *
66 zk_thread_create(void (*func)(), void *arg)
67 {
68 	thread_t tid;
69 
70 	VERIFY(thr_create(0, 0, (void *(*)(void *))func, arg, THR_DETACHED,
71 	    &tid) == 0);
72 
73 	return ((void *)(uintptr_t)tid);
74 }
75 
76 /*
77  * =========================================================================
78  * kstats
79  * =========================================================================
80  */
81 /*ARGSUSED*/
82 kstat_t *
83 kstat_create(const char *module, int instance, const char *name,
84     const char *class, uchar_t type, ulong_t ndata, uchar_t ks_flag)
85 {
86 	return (NULL);
87 }
88 
89 /*ARGSUSED*/
90 void
91 kstat_install(kstat_t *ksp)
92 {}
93 
94 /*ARGSUSED*/
95 void
96 kstat_delete(kstat_t *ksp)
97 {}
98 
99 /*ARGSUSED*/
100 void
101 kstat_waitq_enter(kstat_io_t *kiop)
102 {}
103 
104 /*ARGSUSED*/
105 void
106 kstat_waitq_exit(kstat_io_t *kiop)
107 {}
108 
109 /*ARGSUSED*/
110 void
111 kstat_runq_enter(kstat_io_t *kiop)
112 {}
113 
114 /*ARGSUSED*/
115 void
116 kstat_runq_exit(kstat_io_t *kiop)
117 {}
118 
119 /*ARGSUSED*/
120 void
121 kstat_waitq_to_runq(kstat_io_t *kiop)
122 {}
123 
124 /*ARGSUSED*/
125 void
126 kstat_runq_back_to_waitq(kstat_io_t *kiop)
127 {}
128 
129 /*
130  * =========================================================================
131  * mutexes
132  * =========================================================================
133  */
134 void
135 zmutex_init(kmutex_t *mp)
136 {
137 	mp->m_owner = NULL;
138 	mp->initialized = B_TRUE;
139 	(void) _mutex_init(&mp->m_lock, USYNC_THREAD, NULL);
140 }
141 
142 void
143 zmutex_destroy(kmutex_t *mp)
144 {
145 	ASSERT(mp->initialized == B_TRUE);
146 	ASSERT(mp->m_owner == NULL);
147 	(void) _mutex_destroy(&(mp)->m_lock);
148 	mp->m_owner = (void *)-1UL;
149 	mp->initialized = B_FALSE;
150 }
151 
152 void
153 mutex_enter(kmutex_t *mp)
154 {
155 	ASSERT(mp->initialized == B_TRUE);
156 	ASSERT(mp->m_owner != (void *)-1UL);
157 	ASSERT(mp->m_owner != curthread);
158 	VERIFY(mutex_lock(&mp->m_lock) == 0);
159 	ASSERT(mp->m_owner == NULL);
160 	mp->m_owner = curthread;
161 }
162 
163 int
164 mutex_tryenter(kmutex_t *mp)
165 {
166 	ASSERT(mp->initialized == B_TRUE);
167 	ASSERT(mp->m_owner != (void *)-1UL);
168 	if (0 == mutex_trylock(&mp->m_lock)) {
169 		ASSERT(mp->m_owner == NULL);
170 		mp->m_owner = curthread;
171 		return (1);
172 	} else {
173 		return (0);
174 	}
175 }
176 
177 void
178 mutex_exit(kmutex_t *mp)
179 {
180 	ASSERT(mp->initialized == B_TRUE);
181 	ASSERT(mutex_owner(mp) == curthread);
182 	mp->m_owner = NULL;
183 	VERIFY(mutex_unlock(&mp->m_lock) == 0);
184 }
185 
186 void *
187 mutex_owner(kmutex_t *mp)
188 {
189 	ASSERT(mp->initialized == B_TRUE);
190 	return (mp->m_owner);
191 }
192 
193 /*
194  * =========================================================================
195  * rwlocks
196  * =========================================================================
197  */
198 /*ARGSUSED*/
199 void
200 rw_init(krwlock_t *rwlp, char *name, int type, void *arg)
201 {
202 	rwlock_init(&rwlp->rw_lock, USYNC_THREAD, NULL);
203 	rwlp->rw_owner = NULL;
204 	rwlp->initialized = B_TRUE;
205 }
206 
207 void
208 rw_destroy(krwlock_t *rwlp)
209 {
210 	rwlock_destroy(&rwlp->rw_lock);
211 	rwlp->rw_owner = (void *)-1UL;
212 	rwlp->initialized = B_FALSE;
213 }
214 
215 void
216 rw_enter(krwlock_t *rwlp, krw_t rw)
217 {
218 	ASSERT(!RW_LOCK_HELD(rwlp));
219 	ASSERT(rwlp->initialized == B_TRUE);
220 	ASSERT(rwlp->rw_owner != (void *)-1UL);
221 	ASSERT(rwlp->rw_owner != curthread);
222 
223 	if (rw == RW_READER)
224 		VERIFY(rw_rdlock(&rwlp->rw_lock) == 0);
225 	else
226 		VERIFY(rw_wrlock(&rwlp->rw_lock) == 0);
227 
228 	rwlp->rw_owner = curthread;
229 }
230 
231 void
232 rw_exit(krwlock_t *rwlp)
233 {
234 	ASSERT(rwlp->initialized == B_TRUE);
235 	ASSERT(rwlp->rw_owner != (void *)-1UL);
236 
237 	rwlp->rw_owner = NULL;
238 	VERIFY(rw_unlock(&rwlp->rw_lock) == 0);
239 }
240 
241 int
242 rw_tryenter(krwlock_t *rwlp, krw_t rw)
243 {
244 	int rv;
245 
246 	ASSERT(rwlp->initialized == B_TRUE);
247 	ASSERT(rwlp->rw_owner != (void *)-1UL);
248 
249 	if (rw == RW_READER)
250 		rv = rw_tryrdlock(&rwlp->rw_lock);
251 	else
252 		rv = rw_trywrlock(&rwlp->rw_lock);
253 
254 	if (rv == 0) {
255 		rwlp->rw_owner = curthread;
256 		return (1);
257 	}
258 
259 	return (0);
260 }
261 
262 /*ARGSUSED*/
263 int
264 rw_tryupgrade(krwlock_t *rwlp)
265 {
266 	ASSERT(rwlp->initialized == B_TRUE);
267 	ASSERT(rwlp->rw_owner != (void *)-1UL);
268 
269 	return (0);
270 }
271 
272 /*
273  * =========================================================================
274  * condition variables
275  * =========================================================================
276  */
277 /*ARGSUSED*/
278 void
279 cv_init(kcondvar_t *cv, char *name, int type, void *arg)
280 {
281 	VERIFY(cond_init(cv, type, NULL) == 0);
282 }
283 
284 void
285 cv_destroy(kcondvar_t *cv)
286 {
287 	VERIFY(cond_destroy(cv) == 0);
288 }
289 
290 void
291 cv_wait(kcondvar_t *cv, kmutex_t *mp)
292 {
293 	ASSERT(mutex_owner(mp) == curthread);
294 	mp->m_owner = NULL;
295 	int ret = cond_wait(cv, &mp->m_lock);
296 	VERIFY(ret == 0 || ret == EINTR);
297 	mp->m_owner = curthread;
298 }
299 
300 clock_t
301 cv_timedwait(kcondvar_t *cv, kmutex_t *mp, clock_t abstime)
302 {
303 	int error;
304 	timestruc_t ts;
305 	clock_t delta;
306 
307 top:
308 	delta = abstime - ddi_get_lbolt();
309 	if (delta <= 0)
310 		return (-1);
311 
312 	ts.tv_sec = delta / hz;
313 	ts.tv_nsec = (delta % hz) * (NANOSEC / hz);
314 
315 	ASSERT(mutex_owner(mp) == curthread);
316 	mp->m_owner = NULL;
317 	error = cond_reltimedwait(cv, &mp->m_lock, &ts);
318 	mp->m_owner = curthread;
319 
320 	if (error == ETIME)
321 		return (-1);
322 
323 	if (error == EINTR)
324 		goto top;
325 
326 	ASSERT(error == 0);
327 
328 	return (1);
329 }
330 
331 void
332 cv_signal(kcondvar_t *cv)
333 {
334 	VERIFY(cond_signal(cv) == 0);
335 }
336 
337 void
338 cv_broadcast(kcondvar_t *cv)
339 {
340 	VERIFY(cond_broadcast(cv) == 0);
341 }
342 
343 /*
344  * =========================================================================
345  * vnode operations
346  * =========================================================================
347  */
348 /*
349  * Note: for the xxxat() versions of these functions, we assume that the
350  * starting vp is always rootdir (which is true for spa_directory.c, the only
351  * ZFS consumer of these interfaces).  We assert this is true, and then emulate
352  * them by adding '/' in front of the path.
353  */
354 
355 /*ARGSUSED*/
356 int
357 vn_open(char *path, int x1, int flags, int mode, vnode_t **vpp, int x2, int x3)
358 {
359 	int fd;
360 	vnode_t *vp;
361 	int old_umask;
362 	char realpath[MAXPATHLEN];
363 	struct stat64 st;
364 
365 	/*
366 	 * If we're accessing a real disk from userland, we need to use
367 	 * the character interface to avoid caching.  This is particularly
368 	 * important if we're trying to look at a real in-kernel storage
369 	 * pool from userland, e.g. via zdb, because otherwise we won't
370 	 * see the changes occurring under the segmap cache.
371 	 * On the other hand, the stupid character device returns zero
372 	 * for its size.  So -- gag -- we open the block device to get
373 	 * its size, and remember it for subsequent VOP_GETATTR().
374 	 */
375 	if (strncmp(path, "/dev/", 5) == 0) {
376 		char *dsk;
377 		fd = open64(path, O_RDONLY);
378 		if (fd == -1)
379 			return (errno);
380 		if (fstat64(fd, &st) == -1) {
381 			close(fd);
382 			return (errno);
383 		}
384 		close(fd);
385 		(void) sprintf(realpath, "%s", path);
386 		dsk = strstr(path, "/dsk/");
387 		if (dsk != NULL)
388 			(void) sprintf(realpath + (dsk - path) + 1, "r%s",
389 			    dsk + 1);
390 	} else {
391 		(void) sprintf(realpath, "%s", path);
392 		if (!(flags & FCREAT) && stat64(realpath, &st) == -1)
393 			return (errno);
394 	}
395 
396 	if (flags & FCREAT)
397 		old_umask = umask(0);
398 
399 	/*
400 	 * The construct 'flags - FREAD' conveniently maps combinations of
401 	 * FREAD and FWRITE to the corresponding O_RDONLY, O_WRONLY, and O_RDWR.
402 	 */
403 	fd = open64(realpath, flags - FREAD, mode);
404 
405 	if (flags & FCREAT)
406 		(void) umask(old_umask);
407 
408 	if (fd == -1)
409 		return (errno);
410 
411 	if (fstat64(fd, &st) == -1) {
412 		close(fd);
413 		return (errno);
414 	}
415 
416 	(void) fcntl(fd, F_SETFD, FD_CLOEXEC);
417 
418 	*vpp = vp = umem_zalloc(sizeof (vnode_t), UMEM_NOFAIL);
419 
420 	vp->v_fd = fd;
421 	vp->v_size = st.st_size;
422 	vp->v_path = spa_strdup(path);
423 
424 	return (0);
425 }
426 
427 /*ARGSUSED*/
428 int
429 vn_openat(char *path, int x1, int flags, int mode, vnode_t **vpp, int x2,
430     int x3, vnode_t *startvp, int fd)
431 {
432 	char *realpath = umem_alloc(strlen(path) + 2, UMEM_NOFAIL);
433 	int ret;
434 
435 	ASSERT(startvp == rootdir);
436 	(void) sprintf(realpath, "/%s", path);
437 
438 	/* fd ignored for now, need if want to simulate nbmand support */
439 	ret = vn_open(realpath, x1, flags, mode, vpp, x2, x3);
440 
441 	umem_free(realpath, strlen(path) + 2);
442 
443 	return (ret);
444 }
445 
446 /*ARGSUSED*/
447 int
448 vn_rdwr(int uio, vnode_t *vp, void *addr, ssize_t len, offset_t offset,
449 	int x1, int x2, rlim64_t x3, void *x4, ssize_t *residp)
450 {
451 	ssize_t iolen, split;
452 
453 	if (uio == UIO_READ) {
454 		iolen = pread64(vp->v_fd, addr, len, offset);
455 	} else {
456 		/*
457 		 * To simulate partial disk writes, we split writes into two
458 		 * system calls so that the process can be killed in between.
459 		 */
460 		int sectors = len >> SPA_MINBLOCKSHIFT;
461 		split = (sectors > 0 ? rand() % sectors : 0) <<
462 		    SPA_MINBLOCKSHIFT;
463 		iolen = pwrite64(vp->v_fd, addr, split, offset);
464 		iolen += pwrite64(vp->v_fd, (char *)addr + split,
465 		    len - split, offset + split);
466 	}
467 
468 	if (iolen == -1)
469 		return (errno);
470 	if (residp)
471 		*residp = len - iolen;
472 	else if (iolen != len)
473 		return (EIO);
474 	return (0);
475 }
476 
477 void
478 vn_close(vnode_t *vp)
479 {
480 	close(vp->v_fd);
481 	spa_strfree(vp->v_path);
482 	umem_free(vp, sizeof (vnode_t));
483 }
484 
485 /*
486  * At a minimum we need to update the size since vdev_reopen()
487  * will no longer call vn_openat().
488  */
489 int
490 fop_getattr(vnode_t *vp, vattr_t *vap)
491 {
492 	struct stat64 st;
493 
494 	if (fstat64(vp->v_fd, &st) == -1) {
495 		close(vp->v_fd);
496 		return (errno);
497 	}
498 
499 	vap->va_size = st.st_size;
500 	return (0);
501 }
502 
503 #ifdef ZFS_DEBUG
504 
505 /*
506  * =========================================================================
507  * Figure out which debugging statements to print
508  * =========================================================================
509  */
510 
511 static char *dprintf_string;
512 static int dprintf_print_all;
513 
514 int
515 dprintf_find_string(const char *string)
516 {
517 	char *tmp_str = dprintf_string;
518 	int len = strlen(string);
519 
520 	/*
521 	 * Find out if this is a string we want to print.
522 	 * String format: file1.c,function_name1,file2.c,file3.c
523 	 */
524 
525 	while (tmp_str != NULL) {
526 		if (strncmp(tmp_str, string, len) == 0 &&
527 		    (tmp_str[len] == ',' || tmp_str[len] == '\0'))
528 			return (1);
529 		tmp_str = strchr(tmp_str, ',');
530 		if (tmp_str != NULL)
531 			tmp_str++; /* Get rid of , */
532 	}
533 	return (0);
534 }
535 
536 void
537 dprintf_setup(int *argc, char **argv)
538 {
539 	int i, j;
540 
541 	/*
542 	 * Debugging can be specified two ways: by setting the
543 	 * environment variable ZFS_DEBUG, or by including a
544 	 * "debug=..."  argument on the command line.  The command
545 	 * line setting overrides the environment variable.
546 	 */
547 
548 	for (i = 1; i < *argc; i++) {
549 		int len = strlen("debug=");
550 		/* First look for a command line argument */
551 		if (strncmp("debug=", argv[i], len) == 0) {
552 			dprintf_string = argv[i] + len;
553 			/* Remove from args */
554 			for (j = i; j < *argc; j++)
555 				argv[j] = argv[j+1];
556 			argv[j] = NULL;
557 			(*argc)--;
558 		}
559 	}
560 
561 	if (dprintf_string == NULL) {
562 		/* Look for ZFS_DEBUG environment variable */
563 		dprintf_string = getenv("ZFS_DEBUG");
564 	}
565 
566 	/*
567 	 * Are we just turning on all debugging?
568 	 */
569 	if (dprintf_find_string("on"))
570 		dprintf_print_all = 1;
571 }
572 
573 /*
574  * =========================================================================
575  * debug printfs
576  * =========================================================================
577  */
578 void
579 __dprintf(const char *file, const char *func, int line, const char *fmt, ...)
580 {
581 	const char *newfile;
582 	va_list adx;
583 
584 	/*
585 	 * Get rid of annoying "../common/" prefix to filename.
586 	 */
587 	newfile = strrchr(file, '/');
588 	if (newfile != NULL) {
589 		newfile = newfile + 1; /* Get rid of leading / */
590 	} else {
591 		newfile = file;
592 	}
593 
594 	if (dprintf_print_all ||
595 	    dprintf_find_string(newfile) ||
596 	    dprintf_find_string(func)) {
597 		/* Print out just the function name if requested */
598 		flockfile(stdout);
599 		if (dprintf_find_string("pid"))
600 			(void) printf("%d ", getpid());
601 		if (dprintf_find_string("tid"))
602 			(void) printf("%u ", thr_self());
603 		if (dprintf_find_string("cpu"))
604 			(void) printf("%u ", getcpuid());
605 		if (dprintf_find_string("time"))
606 			(void) printf("%llu ", gethrtime());
607 		if (dprintf_find_string("long"))
608 			(void) printf("%s, line %d: ", newfile, line);
609 		(void) printf("%s: ", func);
610 		va_start(adx, fmt);
611 		(void) vprintf(fmt, adx);
612 		va_end(adx);
613 		funlockfile(stdout);
614 	}
615 }
616 
617 #endif /* ZFS_DEBUG */
618 
619 /*
620  * =========================================================================
621  * cmn_err() and panic()
622  * =========================================================================
623  */
624 static char ce_prefix[CE_IGNORE][10] = { "", "NOTICE: ", "WARNING: ", "" };
625 static char ce_suffix[CE_IGNORE][2] = { "", "\n", "\n", "" };
626 
627 void
628 vpanic(const char *fmt, va_list adx)
629 {
630 	(void) fprintf(stderr, "error: ");
631 	(void) vfprintf(stderr, fmt, adx);
632 	(void) fprintf(stderr, "\n");
633 
634 	abort();	/* think of it as a "user-level crash dump" */
635 }
636 
637 void
638 panic(const char *fmt, ...)
639 {
640 	va_list adx;
641 
642 	va_start(adx, fmt);
643 	vpanic(fmt, adx);
644 	va_end(adx);
645 }
646 
647 void
648 vcmn_err(int ce, const char *fmt, va_list adx)
649 {
650 	if (ce == CE_PANIC)
651 		vpanic(fmt, adx);
652 	if (ce != CE_NOTE) {	/* suppress noise in userland stress testing */
653 		(void) fprintf(stderr, "%s", ce_prefix[ce]);
654 		(void) vfprintf(stderr, fmt, adx);
655 		(void) fprintf(stderr, "%s", ce_suffix[ce]);
656 	}
657 }
658 
659 /*PRINTFLIKE2*/
660 void
661 cmn_err(int ce, const char *fmt, ...)
662 {
663 	va_list adx;
664 
665 	va_start(adx, fmt);
666 	vcmn_err(ce, fmt, adx);
667 	va_end(adx);
668 }
669 
670 /*
671  * =========================================================================
672  * kobj interfaces
673  * =========================================================================
674  */
675 struct _buf *
676 kobj_open_file(char *name)
677 {
678 	struct _buf *file;
679 	vnode_t *vp;
680 
681 	/* set vp as the _fd field of the file */
682 	if (vn_openat(name, UIO_SYSSPACE, FREAD, 0, &vp, 0, 0, rootdir,
683 	    -1) != 0)
684 		return ((void *)-1UL);
685 
686 	file = umem_zalloc(sizeof (struct _buf), UMEM_NOFAIL);
687 	file->_fd = (intptr_t)vp;
688 	return (file);
689 }
690 
691 int
692 kobj_read_file(struct _buf *file, char *buf, unsigned size, unsigned off)
693 {
694 	ssize_t resid;
695 
696 	vn_rdwr(UIO_READ, (vnode_t *)file->_fd, buf, size, (offset_t)off,
697 	    UIO_SYSSPACE, 0, 0, 0, &resid);
698 
699 	return (size - resid);
700 }
701 
702 void
703 kobj_close_file(struct _buf *file)
704 {
705 	vn_close((vnode_t *)file->_fd);
706 	umem_free(file, sizeof (struct _buf));
707 }
708 
709 int
710 kobj_get_filesize(struct _buf *file, uint64_t *size)
711 {
712 	struct stat64 st;
713 	vnode_t *vp = (vnode_t *)file->_fd;
714 
715 	if (fstat64(vp->v_fd, &st) == -1) {
716 		vn_close(vp);
717 		return (errno);
718 	}
719 	*size = st.st_size;
720 	return (0);
721 }
722 
723 /*
724  * =========================================================================
725  * misc routines
726  * =========================================================================
727  */
728 
729 void
730 delay(clock_t ticks)
731 {
732 	poll(0, 0, ticks * (1000 / hz));
733 }
734 
735 /*
736  * Find highest one bit set.
737  *	Returns bit number + 1 of highest bit that is set, otherwise returns 0.
738  * High order bit is 31 (or 63 in _LP64 kernel).
739  */
740 int
741 highbit(ulong_t i)
742 {
743 	register int h = 1;
744 
745 	if (i == 0)
746 		return (0);
747 #ifdef _LP64
748 	if (i & 0xffffffff00000000ul) {
749 		h += 32; i >>= 32;
750 	}
751 #endif
752 	if (i & 0xffff0000) {
753 		h += 16; i >>= 16;
754 	}
755 	if (i & 0xff00) {
756 		h += 8; i >>= 8;
757 	}
758 	if (i & 0xf0) {
759 		h += 4; i >>= 4;
760 	}
761 	if (i & 0xc) {
762 		h += 2; i >>= 2;
763 	}
764 	if (i & 0x2) {
765 		h += 1;
766 	}
767 	return (h);
768 }
769 
770 static int random_fd = -1, urandom_fd = -1;
771 
772 static int
773 random_get_bytes_common(uint8_t *ptr, size_t len, int fd)
774 {
775 	size_t resid = len;
776 	ssize_t bytes;
777 
778 	ASSERT(fd != -1);
779 
780 	while (resid != 0) {
781 		bytes = read(fd, ptr, resid);
782 		ASSERT3S(bytes, >=, 0);
783 		ptr += bytes;
784 		resid -= bytes;
785 	}
786 
787 	return (0);
788 }
789 
790 int
791 random_get_bytes(uint8_t *ptr, size_t len)
792 {
793 	return (random_get_bytes_common(ptr, len, random_fd));
794 }
795 
796 int
797 random_get_pseudo_bytes(uint8_t *ptr, size_t len)
798 {
799 	return (random_get_bytes_common(ptr, len, urandom_fd));
800 }
801 
802 int
803 ddi_strtoul(const char *hw_serial, char **nptr, int base, unsigned long *result)
804 {
805 	char *end;
806 
807 	*result = strtoul(hw_serial, &end, base);
808 	if (*result == 0)
809 		return (errno);
810 	return (0);
811 }
812 
813 int
814 ddi_strtoull(const char *str, char **nptr, int base, u_longlong_t *result)
815 {
816 	char *end;
817 
818 	*result = strtoull(str, &end, base);
819 	if (*result == 0)
820 		return (errno);
821 	return (0);
822 }
823 
824 /* ARGSUSED */
825 cyclic_id_t
826 cyclic_add(cyc_handler_t *hdlr, cyc_time_t *when)
827 {
828 	return (1);
829 }
830 
831 /* ARGSUSED */
832 void
833 cyclic_remove(cyclic_id_t id)
834 {
835 }
836 
837 /* ARGSUSED */
838 int
839 cyclic_reprogram(cyclic_id_t id, hrtime_t expiration)
840 {
841 	return (1);
842 }
843 
844 /*
845  * =========================================================================
846  * kernel emulation setup & teardown
847  * =========================================================================
848  */
849 static int
850 umem_out_of_memory(void)
851 {
852 	char errmsg[] = "out of memory -- generating core dump\n";
853 
854 	write(fileno(stderr), errmsg, sizeof (errmsg));
855 	abort();
856 	return (0);
857 }
858 
859 void
860 kernel_init(int mode)
861 {
862 	umem_nofail_callback(umem_out_of_memory);
863 
864 	physmem = sysconf(_SC_PHYS_PAGES);
865 
866 	dprintf("physmem = %llu pages (%.2f GB)\n", physmem,
867 	    (double)physmem * sysconf(_SC_PAGE_SIZE) / (1ULL << 30));
868 
869 	(void) snprintf(hw_serial, sizeof (hw_serial), "%ld",
870 	    (mode & FWRITE) ? gethostid() : 0);
871 
872 	VERIFY((random_fd = open("/dev/random", O_RDONLY)) != -1);
873 	VERIFY((urandom_fd = open("/dev/urandom", O_RDONLY)) != -1);
874 
875 	system_taskq_init();
876 
877 	mutex_init(&cpu_lock, NULL, MUTEX_DEFAULT, NULL);
878 
879 	spa_init(mode);
880 }
881 
882 void
883 kernel_fini(void)
884 {
885 	spa_fini();
886 
887 	system_taskq_fini();
888 
889 	close(random_fd);
890 	close(urandom_fd);
891 
892 	random_fd = -1;
893 	urandom_fd = -1;
894 }
895 
896 int
897 z_uncompress(void *dst, size_t *dstlen, const void *src, size_t srclen)
898 {
899 	int ret;
900 	uLongf len = *dstlen;
901 
902 	if ((ret = uncompress(dst, &len, src, srclen)) == Z_OK)
903 		*dstlen = (size_t)len;
904 
905 	return (ret);
906 }
907 
908 int
909 z_compress_level(void *dst, size_t *dstlen, const void *src, size_t srclen,
910     int level)
911 {
912 	int ret;
913 	uLongf len = *dstlen;
914 
915 	if ((ret = compress2(dst, &len, src, srclen, level)) == Z_OK)
916 		*dstlen = (size_t)len;
917 
918 	return (ret);
919 }
920 
921 uid_t
922 crgetuid(cred_t *cr)
923 {
924 	return (0);
925 }
926 
927 uid_t
928 crgetruid(cred_t *cr)
929 {
930 	return (0);
931 }
932 
933 gid_t
934 crgetgid(cred_t *cr)
935 {
936 	return (0);
937 }
938 
939 int
940 crgetngroups(cred_t *cr)
941 {
942 	return (0);
943 }
944 
945 gid_t *
946 crgetgroups(cred_t *cr)
947 {
948 	return (NULL);
949 }
950 
951 int
952 zfs_secpolicy_snapshot_perms(const char *name, cred_t *cr)
953 {
954 	return (0);
955 }
956 
957 int
958 zfs_secpolicy_rename_perms(const char *from, const char *to, cred_t *cr)
959 {
960 	return (0);
961 }
962 
963 int
964 zfs_secpolicy_destroy_perms(const char *name, cred_t *cr)
965 {
966 	return (0);
967 }
968 
969 ksiddomain_t *
970 ksid_lookupdomain(const char *dom)
971 {
972 	ksiddomain_t *kd;
973 
974 	kd = umem_zalloc(sizeof (ksiddomain_t), UMEM_NOFAIL);
975 	kd->kd_name = spa_strdup(dom);
976 	return (kd);
977 }
978 
979 void
980 ksiddomain_rele(ksiddomain_t *ksid)
981 {
982 	spa_strfree(ksid->kd_name);
983 	umem_free(ksid, sizeof (ksiddomain_t));
984 }
985 
986 /*
987  * Do not change the length of the returned string; it must be freed
988  * with strfree().
989  */
990 char *
991 kmem_asprintf(const char *fmt, ...)
992 {
993 	int size;
994 	va_list adx;
995 	char *buf;
996 
997 	va_start(adx, fmt);
998 	size = vsnprintf(NULL, 0, fmt, adx) + 1;
999 	va_end(adx);
1000 
1001 	buf = kmem_alloc(size, KM_SLEEP);
1002 
1003 	va_start(adx, fmt);
1004 	size = vsnprintf(buf, size, fmt, adx);
1005 	va_end(adx);
1006 
1007 	return (buf);
1008 }
1009 
1010 /* ARGSUSED */
1011 int
1012 zfs_onexit_fd_hold(int fd, minor_t *minorp)
1013 {
1014 	*minorp = 0;
1015 	return (0);
1016 }
1017 
1018 /* ARGSUSED */
1019 void
1020 zfs_onexit_fd_rele(int fd)
1021 {
1022 }
1023 
1024 /* ARGSUSED */
1025 int
1026 zfs_onexit_add_cb(minor_t minor, void (*func)(void *), void *data,
1027     uint64_t *action_handle)
1028 {
1029 	return (0);
1030 }
1031 
1032 /* ARGSUSED */
1033 int
1034 zfs_onexit_del_cb(minor_t minor, uint64_t action_handle, boolean_t fire)
1035 {
1036 	return (0);
1037 }
1038 
1039 /* ARGSUSED */
1040 int
1041 zfs_onexit_cb_data(minor_t minor, uint64_t action_handle, void **data)
1042 {
1043 	return (0);
1044 }
1045 
1046 void
1047 bioinit(buf_t *bp)
1048 {
1049 	bzero(bp, sizeof (buf_t));
1050 }
1051 
1052 void
1053 biodone(buf_t *bp)
1054 {
1055 	if (bp->b_iodone != NULL) {
1056 		(*(bp->b_iodone))(bp);
1057 		return;
1058 	}
1059 	ASSERT((bp->b_flags & B_DONE) == 0);
1060 	bp->b_flags |= B_DONE;
1061 }
1062 
1063 void
1064 bioerror(buf_t *bp, int error)
1065 {
1066 	ASSERT(bp != NULL);
1067 	ASSERT(error >= 0);
1068 
1069 	if (error != 0) {
1070 		bp->b_flags |= B_ERROR;
1071 	} else {
1072 		bp->b_flags &= ~B_ERROR;
1073 	}
1074 	bp->b_error = error;
1075 }
1076 
1077 
1078 int
1079 geterror(struct buf *bp)
1080 {
1081 	int error = 0;
1082 
1083 	if (bp->b_flags & B_ERROR) {
1084 		error = bp->b_error;
1085 		if (!error)
1086 			error = EIO;
1087 	}
1088 	return (error);
1089 }
1090