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