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