xref: /titanic_44/usr/src/lib/libzpool/common/kernel.c (revision a05fd0c9b9aa46cf66ddea7617e56facdf1f4aaf)
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, 2014 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 mutex_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 mutex_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 	(void) fprintf(stderr, "error: ");
695 	(void) vfprintf(stderr, fmt, adx);
696 	(void) fprintf(stderr, "\n");
697 
698 	abort();	/* think of it as a "user-level crash dump" */
699 }
700 
701 void
702 panic(const char *fmt, ...)
703 {
704 	va_list adx;
705 
706 	va_start(adx, fmt);
707 	vpanic(fmt, adx);
708 	va_end(adx);
709 }
710 
711 void
712 vcmn_err(int ce, const char *fmt, va_list adx)
713 {
714 	if (ce == CE_PANIC)
715 		vpanic(fmt, adx);
716 	if (ce != CE_NOTE) {	/* suppress noise in userland stress testing */
717 		(void) fprintf(stderr, "%s", ce_prefix[ce]);
718 		(void) vfprintf(stderr, fmt, adx);
719 		(void) fprintf(stderr, "%s", ce_suffix[ce]);
720 	}
721 }
722 
723 /*PRINTFLIKE2*/
724 void
725 cmn_err(int ce, const char *fmt, ...)
726 {
727 	va_list adx;
728 
729 	va_start(adx, fmt);
730 	vcmn_err(ce, fmt, adx);
731 	va_end(adx);
732 }
733 
734 /*
735  * =========================================================================
736  * kobj interfaces
737  * =========================================================================
738  */
739 struct _buf *
740 kobj_open_file(char *name)
741 {
742 	struct _buf *file;
743 	vnode_t *vp;
744 
745 	/* set vp as the _fd field of the file */
746 	if (vn_openat(name, UIO_SYSSPACE, FREAD, 0, &vp, 0, 0, rootdir,
747 	    -1) != 0)
748 		return ((void *)-1UL);
749 
750 	file = umem_zalloc(sizeof (struct _buf), UMEM_NOFAIL);
751 	file->_fd = (intptr_t)vp;
752 	return (file);
753 }
754 
755 int
756 kobj_read_file(struct _buf *file, char *buf, unsigned size, unsigned off)
757 {
758 	ssize_t resid;
759 
760 	vn_rdwr(UIO_READ, (vnode_t *)file->_fd, buf, size, (offset_t)off,
761 	    UIO_SYSSPACE, 0, 0, 0, &resid);
762 
763 	return (size - resid);
764 }
765 
766 void
767 kobj_close_file(struct _buf *file)
768 {
769 	vn_close((vnode_t *)file->_fd);
770 	umem_free(file, sizeof (struct _buf));
771 }
772 
773 int
774 kobj_get_filesize(struct _buf *file, uint64_t *size)
775 {
776 	struct stat64 st;
777 	vnode_t *vp = (vnode_t *)file->_fd;
778 
779 	if (fstat64(vp->v_fd, &st) == -1) {
780 		vn_close(vp);
781 		return (errno);
782 	}
783 	*size = st.st_size;
784 	return (0);
785 }
786 
787 /*
788  * =========================================================================
789  * misc routines
790  * =========================================================================
791  */
792 
793 void
794 delay(clock_t ticks)
795 {
796 	poll(0, 0, ticks * (1000 / hz));
797 }
798 
799 /*
800  * Find highest one bit set.
801  *	Returns bit number + 1 of highest bit that is set, otherwise returns 0.
802  */
803 int
804 highbit64(uint64_t i)
805 {
806 	int h = 1;
807 
808 	if (i == 0)
809 		return (0);
810 	if (i & 0xffffffff00000000ULL) {
811 		h += 32; i >>= 32;
812 	}
813 	if (i & 0xffff0000) {
814 		h += 16; i >>= 16;
815 	}
816 	if (i & 0xff00) {
817 		h += 8; i >>= 8;
818 	}
819 	if (i & 0xf0) {
820 		h += 4; i >>= 4;
821 	}
822 	if (i & 0xc) {
823 		h += 2; i >>= 2;
824 	}
825 	if (i & 0x2) {
826 		h += 1;
827 	}
828 	return (h);
829 }
830 
831 static int random_fd = -1, urandom_fd = -1;
832 
833 static int
834 random_get_bytes_common(uint8_t *ptr, size_t len, int fd)
835 {
836 	size_t resid = len;
837 	ssize_t bytes;
838 
839 	ASSERT(fd != -1);
840 
841 	while (resid != 0) {
842 		bytes = read(fd, ptr, resid);
843 		ASSERT3S(bytes, >=, 0);
844 		ptr += bytes;
845 		resid -= bytes;
846 	}
847 
848 	return (0);
849 }
850 
851 int
852 random_get_bytes(uint8_t *ptr, size_t len)
853 {
854 	return (random_get_bytes_common(ptr, len, random_fd));
855 }
856 
857 int
858 random_get_pseudo_bytes(uint8_t *ptr, size_t len)
859 {
860 	return (random_get_bytes_common(ptr, len, urandom_fd));
861 }
862 
863 int
864 ddi_strtoul(const char *hw_serial, char **nptr, int base, unsigned long *result)
865 {
866 	char *end;
867 
868 	*result = strtoul(hw_serial, &end, base);
869 	if (*result == 0)
870 		return (errno);
871 	return (0);
872 }
873 
874 int
875 ddi_strtoull(const char *str, char **nptr, int base, u_longlong_t *result)
876 {
877 	char *end;
878 
879 	*result = strtoull(str, &end, base);
880 	if (*result == 0)
881 		return (errno);
882 	return (0);
883 }
884 
885 /* ARGSUSED */
886 cyclic_id_t
887 cyclic_add(cyc_handler_t *hdlr, cyc_time_t *when)
888 {
889 	return (1);
890 }
891 
892 /* ARGSUSED */
893 void
894 cyclic_remove(cyclic_id_t id)
895 {
896 }
897 
898 /* ARGSUSED */
899 int
900 cyclic_reprogram(cyclic_id_t id, hrtime_t expiration)
901 {
902 	return (1);
903 }
904 
905 /*
906  * =========================================================================
907  * kernel emulation setup & teardown
908  * =========================================================================
909  */
910 static int
911 umem_out_of_memory(void)
912 {
913 	char errmsg[] = "out of memory -- generating core dump\n";
914 
915 	write(fileno(stderr), errmsg, sizeof (errmsg));
916 	abort();
917 	return (0);
918 }
919 
920 void
921 kernel_init(int mode)
922 {
923 	extern uint_t rrw_tsd_key;
924 
925 	umem_nofail_callback(umem_out_of_memory);
926 
927 	physmem = sysconf(_SC_PHYS_PAGES);
928 
929 	dprintf("physmem = %llu pages (%.2f GB)\n", physmem,
930 	    (double)physmem * sysconf(_SC_PAGE_SIZE) / (1ULL << 30));
931 
932 	(void) snprintf(hw_serial, sizeof (hw_serial), "%ld",
933 	    (mode & FWRITE) ? gethostid() : 0);
934 
935 	VERIFY((random_fd = open("/dev/random", O_RDONLY)) != -1);
936 	VERIFY((urandom_fd = open("/dev/urandom", O_RDONLY)) != -1);
937 
938 	system_taskq_init();
939 
940 	mutex_init(&cpu_lock, NULL, MUTEX_DEFAULT, NULL);
941 
942 	spa_init(mode);
943 
944 	tsd_create(&rrw_tsd_key, rrw_tsd_destroy);
945 }
946 
947 void
948 kernel_fini(void)
949 {
950 	spa_fini();
951 
952 	system_taskq_fini();
953 
954 	close(random_fd);
955 	close(urandom_fd);
956 
957 	random_fd = -1;
958 	urandom_fd = -1;
959 }
960 
961 int
962 z_uncompress(void *dst, size_t *dstlen, const void *src, size_t srclen)
963 {
964 	int ret;
965 	uLongf len = *dstlen;
966 
967 	if ((ret = uncompress(dst, &len, src, srclen)) == Z_OK)
968 		*dstlen = (size_t)len;
969 
970 	return (ret);
971 }
972 
973 int
974 z_compress_level(void *dst, size_t *dstlen, const void *src, size_t srclen,
975     int level)
976 {
977 	int ret;
978 	uLongf len = *dstlen;
979 
980 	if ((ret = compress2(dst, &len, src, srclen, level)) == Z_OK)
981 		*dstlen = (size_t)len;
982 
983 	return (ret);
984 }
985 
986 uid_t
987 crgetuid(cred_t *cr)
988 {
989 	return (0);
990 }
991 
992 uid_t
993 crgetruid(cred_t *cr)
994 {
995 	return (0);
996 }
997 
998 gid_t
999 crgetgid(cred_t *cr)
1000 {
1001 	return (0);
1002 }
1003 
1004 int
1005 crgetngroups(cred_t *cr)
1006 {
1007 	return (0);
1008 }
1009 
1010 gid_t *
1011 crgetgroups(cred_t *cr)
1012 {
1013 	return (NULL);
1014 }
1015 
1016 int
1017 zfs_secpolicy_snapshot_perms(const char *name, cred_t *cr)
1018 {
1019 	return (0);
1020 }
1021 
1022 int
1023 zfs_secpolicy_rename_perms(const char *from, const char *to, cred_t *cr)
1024 {
1025 	return (0);
1026 }
1027 
1028 int
1029 zfs_secpolicy_destroy_perms(const char *name, cred_t *cr)
1030 {
1031 	return (0);
1032 }
1033 
1034 ksiddomain_t *
1035 ksid_lookupdomain(const char *dom)
1036 {
1037 	ksiddomain_t *kd;
1038 
1039 	kd = umem_zalloc(sizeof (ksiddomain_t), UMEM_NOFAIL);
1040 	kd->kd_name = spa_strdup(dom);
1041 	return (kd);
1042 }
1043 
1044 void
1045 ksiddomain_rele(ksiddomain_t *ksid)
1046 {
1047 	spa_strfree(ksid->kd_name);
1048 	umem_free(ksid, sizeof (ksiddomain_t));
1049 }
1050 
1051 /*
1052  * Do not change the length of the returned string; it must be freed
1053  * with strfree().
1054  */
1055 char *
1056 kmem_asprintf(const char *fmt, ...)
1057 {
1058 	int size;
1059 	va_list adx;
1060 	char *buf;
1061 
1062 	va_start(adx, fmt);
1063 	size = vsnprintf(NULL, 0, fmt, adx) + 1;
1064 	va_end(adx);
1065 
1066 	buf = kmem_alloc(size, KM_SLEEP);
1067 
1068 	va_start(adx, fmt);
1069 	size = vsnprintf(buf, size, fmt, adx);
1070 	va_end(adx);
1071 
1072 	return (buf);
1073 }
1074 
1075 /* ARGSUSED */
1076 int
1077 zfs_onexit_fd_hold(int fd, minor_t *minorp)
1078 {
1079 	*minorp = 0;
1080 	return (0);
1081 }
1082 
1083 /* ARGSUSED */
1084 void
1085 zfs_onexit_fd_rele(int fd)
1086 {
1087 }
1088 
1089 /* ARGSUSED */
1090 int
1091 zfs_onexit_add_cb(minor_t minor, void (*func)(void *), void *data,
1092     uint64_t *action_handle)
1093 {
1094 	return (0);
1095 }
1096 
1097 /* ARGSUSED */
1098 int
1099 zfs_onexit_del_cb(minor_t minor, uint64_t action_handle, boolean_t fire)
1100 {
1101 	return (0);
1102 }
1103 
1104 /* ARGSUSED */
1105 int
1106 zfs_onexit_cb_data(minor_t minor, uint64_t action_handle, void **data)
1107 {
1108 	return (0);
1109 }
1110 
1111 void
1112 bioinit(buf_t *bp)
1113 {
1114 	bzero(bp, sizeof (buf_t));
1115 }
1116 
1117 void
1118 biodone(buf_t *bp)
1119 {
1120 	if (bp->b_iodone != NULL) {
1121 		(*(bp->b_iodone))(bp);
1122 		return;
1123 	}
1124 	ASSERT((bp->b_flags & B_DONE) == 0);
1125 	bp->b_flags |= B_DONE;
1126 }
1127 
1128 void
1129 bioerror(buf_t *bp, int error)
1130 {
1131 	ASSERT(bp != NULL);
1132 	ASSERT(error >= 0);
1133 
1134 	if (error != 0) {
1135 		bp->b_flags |= B_ERROR;
1136 	} else {
1137 		bp->b_flags &= ~B_ERROR;
1138 	}
1139 	bp->b_error = error;
1140 }
1141 
1142 
1143 int
1144 geterror(struct buf *bp)
1145 {
1146 	int error = 0;
1147 
1148 	if (bp->b_flags & B_ERROR) {
1149 		error = bp->b_error;
1150 		if (!error)
1151 			error = EIO;
1152 	}
1153 	return (error);
1154 }
1155