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.
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.
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]
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.
35 #include <sys/assfail.h>
38 #include <sys/processor.h>
39 #include <sys/zfs_context.h>
40 #include <sys/rrwlock.h>
42 #include <sys/utsname.h>
43 #include <sys/systeminfo.h>
47 * Emulation of kernel services in userland.
54 vnode_t *rootdir = (vnode_t *)0xabcd1234;
55 char hw_serial[HW_HOSTID_LEN];
60 /* If set, all blocks read will be copied to the specified directory. */
61 char *vn_dumpdir = NULL;
63 struct utsname utsname = {
64 "userland", "libzpool", "1", "1", "na"
67 /* this only exists to have its address taken */
71 * =========================================================================
73 * =========================================================================
77 zk_thread_create(void (*func)(), void *arg)
81 VERIFY(thr_create(0, 0, (void *(*)(void *))func, arg, THR_DETACHED,
84 return ((void *)(uintptr_t)tid);
88 * =========================================================================
90 * =========================================================================
94 kstat_create(char *module, int instance, char *name, char *class,
95 uchar_t type, ulong_t ndata, uchar_t ks_flag)
102 kstat_named_init(kstat_named_t *knp, const char *name, uchar_t type)
107 kstat_install(kstat_t *ksp)
112 kstat_delete(kstat_t *ksp)
116 * =========================================================================
118 * =========================================================================
121 zmutex_init(kmutex_t *mp)
124 mp->initialized = B_TRUE;
125 (void) _mutex_init(&mp->m_lock, USYNC_THREAD, NULL);
129 zmutex_destroy(kmutex_t *mp)
131 ASSERT(mp->initialized == B_TRUE);
132 ASSERT(mp->m_owner == NULL);
133 (void) _mutex_destroy(&(mp)->m_lock);
134 mp->m_owner = (void *)-1UL;
135 mp->initialized = B_FALSE;
139 zmutex_owned(kmutex_t *mp)
141 ASSERT(mp->initialized == B_TRUE);
143 return (mp->m_owner == curthread);
147 mutex_enter(kmutex_t *mp)
149 ASSERT(mp->initialized == B_TRUE);
150 ASSERT(mp->m_owner != (void *)-1UL);
151 ASSERT(mp->m_owner != curthread);
152 VERIFY(mutex_lock(&mp->m_lock) == 0);
153 ASSERT(mp->m_owner == NULL);
154 mp->m_owner = curthread;
158 mutex_tryenter(kmutex_t *mp)
160 ASSERT(mp->initialized == B_TRUE);
161 ASSERT(mp->m_owner != (void *)-1UL);
162 if (0 == mutex_trylock(&mp->m_lock)) {
163 ASSERT(mp->m_owner == NULL);
164 mp->m_owner = curthread;
172 mutex_exit(kmutex_t *mp)
174 ASSERT(mp->initialized == B_TRUE);
175 ASSERT(mutex_owner(mp) == curthread);
177 VERIFY(mutex_unlock(&mp->m_lock) == 0);
181 mutex_owner(kmutex_t *mp)
183 ASSERT(mp->initialized == B_TRUE);
184 return (mp->m_owner);
188 * =========================================================================
190 * =========================================================================
194 rw_init(krwlock_t *rwlp, char *name, int type, void *arg)
196 rwlock_init(&rwlp->rw_lock, USYNC_THREAD, NULL);
197 rwlp->rw_owner = NULL;
198 rwlp->initialized = B_TRUE;
203 rw_destroy(krwlock_t *rwlp)
205 ASSERT(rwlp->rw_count == 0);
206 rwlock_destroy(&rwlp->rw_lock);
207 rwlp->rw_owner = (void *)-1UL;
208 rwlp->initialized = B_FALSE;
212 rw_enter(krwlock_t *rwlp, krw_t rw)
214 //ASSERT(!RW_LOCK_HELD(rwlp));
215 ASSERT(rwlp->initialized == B_TRUE);
216 ASSERT(rwlp->rw_owner != (void *)-1UL);
217 ASSERT(rwlp->rw_owner != curthread);
219 if (rw == RW_READER) {
220 VERIFY(rw_rdlock(&rwlp->rw_lock) == 0);
221 ASSERT(rwlp->rw_count >= 0);
222 atomic_add_int(&rwlp->rw_count, 1);
224 VERIFY(rw_wrlock(&rwlp->rw_lock) == 0);
225 ASSERT(rwlp->rw_count == 0);
227 rwlp->rw_owner = curthread;
232 rw_exit(krwlock_t *rwlp)
234 ASSERT(rwlp->initialized == B_TRUE);
235 ASSERT(rwlp->rw_owner != (void *)-1UL);
237 if (rwlp->rw_owner == curthread) {
239 ASSERT(rwlp->rw_count == -1);
241 rwlp->rw_owner = NULL;
244 ASSERT(rwlp->rw_count > 0);
245 atomic_add_int(&rwlp->rw_count, -1);
247 VERIFY(rw_unlock(&rwlp->rw_lock) == 0);
251 rw_tryenter(krwlock_t *rwlp, krw_t rw)
255 ASSERT(rwlp->initialized == B_TRUE);
256 ASSERT(rwlp->rw_owner != (void *)-1UL);
257 ASSERT(rwlp->rw_owner != curthread);
260 rv = rw_tryrdlock(&rwlp->rw_lock);
262 rv = rw_trywrlock(&rwlp->rw_lock);
265 ASSERT(rwlp->rw_owner == NULL);
266 if (rw == RW_READER) {
267 ASSERT(rwlp->rw_count >= 0);
268 atomic_add_int(&rwlp->rw_count, 1);
270 ASSERT(rwlp->rw_count == 0);
272 rwlp->rw_owner = curthread;
282 rw_tryupgrade(krwlock_t *rwlp)
284 ASSERT(rwlp->initialized == B_TRUE);
285 ASSERT(rwlp->rw_owner != (void *)-1UL);
291 rw_lock_held(krwlock_t *rwlp)
294 return (rwlp->rw_count != 0);
298 * =========================================================================
299 * condition variables
300 * =========================================================================
304 cv_init(kcondvar_t *cv, char *name, int type, void *arg)
306 VERIFY(cond_init(cv, name, NULL) == 0);
310 cv_destroy(kcondvar_t *cv)
312 VERIFY(cond_destroy(cv) == 0);
316 cv_wait(kcondvar_t *cv, kmutex_t *mp)
318 ASSERT(mutex_owner(mp) == curthread);
320 int ret = cond_wait(cv, &mp->m_lock);
321 VERIFY(ret == 0 || ret == EINTR);
322 mp->m_owner = curthread;
326 * NB: this emulates FreeBSD cv_wait_sig(9), not the illumos one.
327 * Meanings of the return code are different.
328 * NB: this does not actually catch any signals.
331 cv_wait_sig(kcondvar_t *cv, kmutex_t *mp)
338 cv_timedwait(kcondvar_t *cv, kmutex_t *mp, clock_t abstime)
345 abstime += ddi_get_lbolt();
347 delta = abstime - ddi_get_lbolt();
351 if (gettimeofday(&tv, NULL) != 0)
352 assert(!"gettimeofday() failed");
354 ts.tv_sec = tv.tv_sec + delta / hz;
355 ts.tv_nsec = tv.tv_usec * 1000 + (delta % hz) * (NANOSEC / hz);
356 ASSERT(ts.tv_nsec >= 0);
358 if (ts.tv_nsec >= NANOSEC) {
360 ts.tv_nsec -= NANOSEC;
363 ASSERT(mutex_owner(mp) == curthread);
365 error = pthread_cond_timedwait(cv, &mp->m_lock, &ts);
366 mp->m_owner = curthread;
371 if (error == ETIMEDOUT)
381 cv_timedwait_hires(kcondvar_t *cv, kmutex_t *mp, hrtime_t tim, hrtime_t res,
388 ASSERT(flag == 0 || flag == CALLOUT_FLAG_ABSOLUTE);
392 if (flag & CALLOUT_FLAG_ABSOLUTE)
393 delta -= gethrtime();
398 clock_gettime(CLOCK_REALTIME, &ts);
399 ts.tv_sec += delta / NANOSEC;
400 ts.tv_nsec += delta % NANOSEC;
401 if (ts.tv_nsec >= NANOSEC) {
403 ts.tv_nsec -= NANOSEC;
406 ASSERT(mutex_owner(mp) == curthread);
408 error = pthread_cond_timedwait(cv, &mp->m_lock, &ts);
409 mp->m_owner = curthread;
411 if (error == ETIMEDOUT)
423 cv_signal(kcondvar_t *cv)
425 VERIFY(cond_signal(cv) == 0);
429 cv_broadcast(kcondvar_t *cv)
431 VERIFY(cond_broadcast(cv) == 0);
435 * =========================================================================
437 * =========================================================================
440 * Note: for the xxxat() versions of these functions, we assume that the
441 * starting vp is always rootdir (which is true for spa_directory.c, the only
442 * ZFS consumer of these interfaces). We assert this is true, and then emulate
443 * them by adding '/' in front of the path.
448 vn_open(char *path, int x1, int flags, int mode, vnode_t **vpp, int x2, int x3)
454 char realpath[MAXPATHLEN];
458 * If we're accessing a real disk from userland, we need to use
459 * the character interface to avoid caching. This is particularly
460 * important if we're trying to look at a real in-kernel storage
461 * pool from userland, e.g. via zdb, because otherwise we won't
462 * see the changes occurring under the segmap cache.
463 * On the other hand, the stupid character device returns zero
464 * for its size. So -- gag -- we open the block device to get
465 * its size, and remember it for subsequent VOP_GETATTR().
467 if (strncmp(path, "/dev/", 5) == 0) {
469 fd = open64(path, O_RDONLY);
472 if (fstat64(fd, &st) == -1) {
477 (void) sprintf(realpath, "%s", path);
478 dsk = strstr(path, "/dsk/");
480 (void) sprintf(realpath + (dsk - path) + 1, "r%s",
483 (void) sprintf(realpath, "%s", path);
484 if (!(flags & FCREAT) && stat64(realpath, &st) == -1)
489 old_umask = umask(0);
492 * The construct 'flags - FREAD' conveniently maps combinations of
493 * FREAD and FWRITE to the corresponding O_RDONLY, O_WRONLY, and O_RDWR.
495 fd = open64(realpath, flags - FREAD, mode);
498 (void) umask(old_umask);
500 if (vn_dumpdir != NULL) {
501 char dumppath[MAXPATHLEN];
502 (void) snprintf(dumppath, sizeof (dumppath),
503 "%s/%s", vn_dumpdir, basename(realpath));
504 dump_fd = open64(dumppath, O_CREAT | O_WRONLY, 0666);
514 if (fstat64(fd, &st) == -1) {
519 (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
521 *vpp = vp = umem_zalloc(sizeof (vnode_t), UMEM_NOFAIL);
524 vp->v_size = st.st_size;
525 vp->v_path = spa_strdup(path);
526 vp->v_dump_fd = dump_fd;
533 vn_openat(char *path, int x1, int flags, int mode, vnode_t **vpp, int x2,
534 int x3, vnode_t *startvp, int fd)
536 char *realpath = umem_alloc(strlen(path) + 2, UMEM_NOFAIL);
539 ASSERT(startvp == rootdir);
540 (void) sprintf(realpath, "/%s", path);
542 /* fd ignored for now, need if want to simulate nbmand support */
543 ret = vn_open(realpath, x1, flags, mode, vpp, x2, x3);
545 umem_free(realpath, strlen(path) + 2);
552 vn_rdwr(int uio, vnode_t *vp, void *addr, ssize_t len, offset_t offset,
553 int x1, int x2, rlim64_t x3, void *x4, ssize_t *residp)
555 ssize_t iolen, split;
557 if (uio == UIO_READ) {
558 iolen = pread64(vp->v_fd, addr, len, offset);
559 if (vp->v_dump_fd != -1) {
561 pwrite64(vp->v_dump_fd, addr, iolen, offset);
562 ASSERT(status != -1);
566 * To simulate partial disk writes, we split writes into two
567 * system calls so that the process can be killed in between.
569 int sectors = len >> SPA_MINBLOCKSHIFT;
570 split = (sectors > 0 ? rand() % sectors : 0) <<
572 iolen = pwrite64(vp->v_fd, addr, split, offset);
573 iolen += pwrite64(vp->v_fd, (char *)addr + split,
574 len - split, offset + split);
580 *residp = len - iolen;
581 else if (iolen != len)
587 vn_close(vnode_t *vp, int openflag, cred_t *cr, kthread_t *td)
590 if (vp->v_dump_fd != -1)
591 close(vp->v_dump_fd);
592 spa_strfree(vp->v_path);
593 umem_free(vp, sizeof (vnode_t));
597 * At a minimum we need to update the size since vdev_reopen()
598 * will no longer call vn_openat().
601 fop_getattr(vnode_t *vp, vattr_t *vap)
605 if (fstat64(vp->v_fd, &st) == -1) {
610 vap->va_size = st.st_size;
617 * =========================================================================
618 * Figure out which debugging statements to print
619 * =========================================================================
622 static char *dprintf_string;
623 static int dprintf_print_all;
626 dprintf_find_string(const char *string)
628 char *tmp_str = dprintf_string;
629 int len = strlen(string);
632 * Find out if this is a string we want to print.
633 * String format: file1.c,function_name1,file2.c,file3.c
636 while (tmp_str != NULL) {
637 if (strncmp(tmp_str, string, len) == 0 &&
638 (tmp_str[len] == ',' || tmp_str[len] == '\0'))
640 tmp_str = strchr(tmp_str, ',');
642 tmp_str++; /* Get rid of , */
648 dprintf_setup(int *argc, char **argv)
653 * Debugging can be specified two ways: by setting the
654 * environment variable ZFS_DEBUG, or by including a
655 * "debug=..." argument on the command line. The command
656 * line setting overrides the environment variable.
659 for (i = 1; i < *argc; i++) {
660 int len = strlen("debug=");
661 /* First look for a command line argument */
662 if (strncmp("debug=", argv[i], len) == 0) {
663 dprintf_string = argv[i] + len;
664 /* Remove from args */
665 for (j = i; j < *argc; j++)
672 if (dprintf_string == NULL) {
673 /* Look for ZFS_DEBUG environment variable */
674 dprintf_string = getenv("ZFS_DEBUG");
678 * Are we just turning on all debugging?
680 if (dprintf_find_string("on"))
681 dprintf_print_all = 1;
683 if (dprintf_string != NULL)
684 zfs_flags |= ZFS_DEBUG_DPRINTF;
688 sysctl_handle_64(SYSCTL_HANDLER_ARGS)
694 * =========================================================================
696 * =========================================================================
699 __dprintf(const char *file, const char *func, int line, const char *fmt, ...)
705 * Get rid of annoying "../common/" prefix to filename.
707 newfile = strrchr(file, '/');
708 if (newfile != NULL) {
709 newfile = newfile + 1; /* Get rid of leading / */
714 if (dprintf_print_all ||
715 dprintf_find_string(newfile) ||
716 dprintf_find_string(func)) {
717 /* Print out just the function name if requested */
719 if (dprintf_find_string("pid"))
720 (void) printf("%d ", getpid());
721 if (dprintf_find_string("tid"))
722 (void) printf("%lu ", thr_self());
724 if (dprintf_find_string("cpu"))
725 (void) printf("%u ", getcpuid());
727 if (dprintf_find_string("time"))
728 (void) printf("%llu ", gethrtime());
729 if (dprintf_find_string("long"))
730 (void) printf("%s, line %d: ", newfile, line);
731 (void) printf("%s: ", func);
733 (void) vprintf(fmt, adx);
739 #endif /* ZFS_DEBUG */
742 * =========================================================================
743 * cmn_err() and panic()
744 * =========================================================================
746 static char ce_prefix[CE_IGNORE][10] = { "", "NOTICE: ", "WARNING: ", "" };
747 static char ce_suffix[CE_IGNORE][2] = { "", "\n", "\n", "" };
750 vpanic(const char *fmt, va_list adx)
753 (void) vsnprintf(buf, 512, fmt, adx);
754 assfail(buf, NULL, 0);
755 abort(); /* necessary to make vpanic meet noreturn requirements */
759 panic(const char *fmt, ...)
769 vcmn_err(int ce, const char *fmt, va_list adx)
773 if (ce != CE_NOTE) { /* suppress noise in userland stress testing */
774 (void) fprintf(stderr, "%s", ce_prefix[ce]);
775 (void) vfprintf(stderr, fmt, adx);
776 (void) fprintf(stderr, "%s", ce_suffix[ce]);
782 cmn_err(int ce, const char *fmt, ...)
787 vcmn_err(ce, fmt, adx);
792 * =========================================================================
794 * =========================================================================
797 kobj_open_file(char *name)
802 /* set vp as the _fd field of the file */
803 if (vn_openat(name, UIO_SYSSPACE, FREAD, 0, &vp, 0, 0, rootdir,
805 return ((void *)-1UL);
807 file = umem_zalloc(sizeof (struct _buf), UMEM_NOFAIL);
808 file->_fd = (intptr_t)vp;
813 kobj_read_file(struct _buf *file, char *buf, unsigned size, unsigned off)
817 vn_rdwr(UIO_READ, (vnode_t *)file->_fd, buf, size, (offset_t)off,
818 UIO_SYSSPACE, 0, 0, 0, &resid);
820 return (size - resid);
824 kobj_close_file(struct _buf *file)
826 vn_close((vnode_t *)file->_fd, 0, NULL, NULL);
827 umem_free(file, sizeof (struct _buf));
831 kobj_get_filesize(struct _buf *file, uint64_t *size)
834 vnode_t *vp = (vnode_t *)file->_fd;
836 if (fstat64(vp->v_fd, &st) == -1) {
837 vn_close(vp, 0, NULL, NULL);
845 * =========================================================================
847 * =========================================================================
853 poll(0, 0, ticks * (1000 / hz));
858 * Find highest one bit set.
859 * Returns bit number + 1 of highest bit that is set, otherwise returns 0.
862 highbit64(uint64_t i)
868 if (i & 0xffffffff00000000ULL) {
871 if (i & 0xffff0000) {
890 static int random_fd = -1, urandom_fd = -1;
893 random_get_bytes_common(uint8_t *ptr, size_t len, int fd)
901 bytes = read(fd, ptr, resid);
902 ASSERT3S(bytes, >=, 0);
911 random_get_bytes(uint8_t *ptr, size_t len)
913 return (random_get_bytes_common(ptr, len, random_fd));
917 random_get_pseudo_bytes(uint8_t *ptr, size_t len)
919 return (random_get_bytes_common(ptr, len, urandom_fd));
923 ddi_strtoul(const char *hw_serial, char **nptr, int base, unsigned long *result)
927 *result = strtoul(hw_serial, &end, base);
934 ddi_strtoull(const char *str, char **nptr, int base, u_longlong_t *result)
938 *result = strtoull(str, &end, base);
947 cyclic_add(cyc_handler_t *hdlr, cyc_time_t *when)
954 cyclic_remove(cyclic_id_t id)
960 cyclic_reprogram(cyclic_id_t id, hrtime_t expiration)
967 * =========================================================================
968 * kernel emulation setup & teardown
969 * =========================================================================
972 umem_out_of_memory(void)
974 char errmsg[] = "out of memory -- generating core dump\n";
976 write(fileno(stderr), errmsg, sizeof (errmsg));
982 kernel_init(int mode)
984 extern uint_t rrw_tsd_key;
986 umem_nofail_callback(umem_out_of_memory);
988 physmem = sysconf(_SC_PHYS_PAGES);
990 dprintf("physmem = %llu pages (%.2f GB)\n", physmem,
991 (double)physmem * sysconf(_SC_PAGE_SIZE) / (1ULL << 30));
993 (void) snprintf(hw_serial, sizeof (hw_serial), "%ld",
994 (mode & FWRITE) ? get_system_hostid() : 0);
996 VERIFY((random_fd = open("/dev/random", O_RDONLY)) != -1);
997 VERIFY((urandom_fd = open("/dev/urandom", O_RDONLY)) != -1);
1002 mutex_init(&cpu_lock, NULL, MUTEX_DEFAULT, NULL);
1007 tsd_create(&rrw_tsd_key, rrw_tsd_destroy);
1015 system_taskq_fini();
1026 zone_get_hostid(void *zonep)
1029 * We're emulating the system's hostid in userland.
1031 return (strtoul(hw_serial, NULL, 10));
1035 z_uncompress(void *dst, size_t *dstlen, const void *src, size_t srclen)
1038 uLongf len = *dstlen;
1040 if ((ret = uncompress(dst, &len, src, srclen)) == Z_OK)
1041 *dstlen = (size_t)len;
1047 z_compress_level(void *dst, size_t *dstlen, const void *src, size_t srclen,
1051 uLongf len = *dstlen;
1053 if ((ret = compress2(dst, &len, src, srclen, level)) == Z_OK)
1054 *dstlen = (size_t)len;
1060 crgetuid(cred_t *cr)
1066 crgetruid(cred_t *cr)
1072 crgetgid(cred_t *cr)
1078 crgetngroups(cred_t *cr)
1084 crgetgroups(cred_t *cr)
1090 zfs_secpolicy_snapshot_perms(const char *name, cred_t *cr)
1096 zfs_secpolicy_rename_perms(const char *from, const char *to, cred_t *cr)
1102 zfs_secpolicy_destroy_perms(const char *name, cred_t *cr)
1108 ksid_lookupdomain(const char *dom)
1112 kd = umem_zalloc(sizeof (ksiddomain_t), UMEM_NOFAIL);
1113 kd->kd_name = spa_strdup(dom);
1118 ksiddomain_rele(ksiddomain_t *ksid)
1120 spa_strfree(ksid->kd_name);
1121 umem_free(ksid, sizeof (ksiddomain_t));
1125 * Do not change the length of the returned string; it must be freed
1129 kmem_asprintf(const char *fmt, ...)
1136 size = vsnprintf(NULL, 0, fmt, adx) + 1;
1139 buf = kmem_alloc(size, KM_SLEEP);
1142 size = vsnprintf(buf, size, fmt, adx);
1150 zfs_onexit_fd_hold(int fd, minor_t *minorp)
1158 zfs_onexit_fd_rele(int fd)
1164 zfs_onexit_add_cb(minor_t minor, void (*func)(void *), void *data,
1165 uint64_t *action_handle)
1172 zfs_onexit_del_cb(minor_t minor, uint64_t action_handle, boolean_t fire)
1179 zfs_onexit_cb_data(minor_t minor, uint64_t action_handle, void **data)
1187 zvol_create_minors(const char *name)
1197 bzero(bp, sizeof (buf_t));
1203 if (bp->b_iodone != NULL) {
1204 (*(bp->b_iodone))(bp);
1207 ASSERT((bp->b_flags & B_DONE) == 0);
1208 bp->b_flags |= B_DONE;
1212 bioerror(buf_t *bp, int error)
1218 bp->b_flags |= B_ERROR;
1220 bp->b_flags &= ~B_ERROR;
1222 bp->b_error = error;
1227 geterror(struct buf *bp)
1231 if (bp->b_flags & B_ERROR) {
1232 error = bp->b_error;