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