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