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.
37 #include <sys/processor.h>
38 #include <sys/zfs_context.h>
39 #include <sys/rrwlock.h>
41 #include <sys/utsname.h>
42 #include <sys/systeminfo.h>
45 * Emulation of kernel services in userland.
52 vnode_t *rootdir = (vnode_t *)0xabcd1234;
53 char hw_serial[HW_HOSTID_LEN];
58 /* If set, all blocks read will be copied to the specified directory. */
59 char *vn_dumpdir = NULL;
61 struct utsname utsname = {
62 "userland", "libzpool", "1", "1", "na"
65 /* this only exists to have its address taken */
69 * =========================================================================
71 * =========================================================================
75 zk_thread_create(void (*func)(), void *arg)
79 VERIFY(thr_create(0, 0, (void *(*)(void *))func, arg, THR_DETACHED,
82 return ((void *)(uintptr_t)tid);
86 * =========================================================================
88 * =========================================================================
92 kstat_create(char *module, int instance, char *name, char *class,
93 uchar_t type, ulong_t ndata, uchar_t ks_flag)
100 kstat_install(kstat_t *ksp)
105 kstat_delete(kstat_t *ksp)
109 * =========================================================================
111 * =========================================================================
114 zmutex_init(kmutex_t *mp)
117 mp->initialized = B_TRUE;
118 (void) _mutex_init(&mp->m_lock, USYNC_THREAD, NULL);
122 zmutex_destroy(kmutex_t *mp)
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;
132 zmutex_owned(kmutex_t *mp)
134 ASSERT(mp->initialized == B_TRUE);
136 return (mp->m_owner == curthread);
140 mutex_enter(kmutex_t *mp)
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;
151 mutex_tryenter(kmutex_t *mp)
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;
165 mutex_exit(kmutex_t *mp)
167 ASSERT(mp->initialized == B_TRUE);
168 ASSERT(mutex_owner(mp) == curthread);
170 VERIFY(mutex_unlock(&mp->m_lock) == 0);
174 mutex_owner(kmutex_t *mp)
176 ASSERT(mp->initialized == B_TRUE);
177 return (mp->m_owner);
181 * =========================================================================
183 * =========================================================================
187 rw_init(krwlock_t *rwlp, char *name, int type, void *arg)
189 rwlock_init(&rwlp->rw_lock, USYNC_THREAD, NULL);
190 rwlp->rw_owner = NULL;
191 rwlp->initialized = B_TRUE;
196 rw_destroy(krwlock_t *rwlp)
198 ASSERT(rwlp->rw_count == 0);
199 rwlock_destroy(&rwlp->rw_lock);
200 rwlp->rw_owner = (void *)-1UL;
201 rwlp->initialized = B_FALSE;
205 rw_enter(krwlock_t *rwlp, krw_t rw)
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);
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);
217 VERIFY(rw_wrlock(&rwlp->rw_lock) == 0);
218 ASSERT(rwlp->rw_count == 0);
220 rwlp->rw_owner = curthread;
225 rw_exit(krwlock_t *rwlp)
227 ASSERT(rwlp->initialized == B_TRUE);
228 ASSERT(rwlp->rw_owner != (void *)-1UL);
230 if (rwlp->rw_owner == curthread) {
232 ASSERT(rwlp->rw_count == -1);
234 rwlp->rw_owner = NULL;
237 ASSERT(rwlp->rw_count > 0);
238 atomic_add_int(&rwlp->rw_count, -1);
240 VERIFY(rw_unlock(&rwlp->rw_lock) == 0);
244 rw_tryenter(krwlock_t *rwlp, krw_t rw)
248 ASSERT(rwlp->initialized == B_TRUE);
249 ASSERT(rwlp->rw_owner != (void *)-1UL);
250 ASSERT(rwlp->rw_owner != curthread);
253 rv = rw_tryrdlock(&rwlp->rw_lock);
255 rv = rw_trywrlock(&rwlp->rw_lock);
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);
263 ASSERT(rwlp->rw_count == 0);
265 rwlp->rw_owner = curthread;
275 rw_tryupgrade(krwlock_t *rwlp)
277 ASSERT(rwlp->initialized == B_TRUE);
278 ASSERT(rwlp->rw_owner != (void *)-1UL);
284 rw_lock_held(krwlock_t *rwlp)
287 return (rwlp->rw_count != 0);
291 * =========================================================================
292 * condition variables
293 * =========================================================================
297 cv_init(kcondvar_t *cv, char *name, int type, void *arg)
299 VERIFY(cond_init(cv, name, NULL) == 0);
303 cv_destroy(kcondvar_t *cv)
305 VERIFY(cond_destroy(cv) == 0);
309 cv_wait(kcondvar_t *cv, kmutex_t *mp)
311 ASSERT(mutex_owner(mp) == curthread);
313 int ret = cond_wait(cv, &mp->m_lock);
314 VERIFY(ret == 0 || ret == EINTR);
315 mp->m_owner = curthread;
319 cv_timedwait(kcondvar_t *cv, kmutex_t *mp, clock_t abstime)
326 abstime += ddi_get_lbolt();
328 delta = abstime - ddi_get_lbolt();
332 if (gettimeofday(&tv, NULL) != 0)
333 assert(!"gettimeofday() failed");
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);
339 if (ts.tv_nsec >= NANOSEC) {
341 ts.tv_nsec -= NANOSEC;
344 ASSERT(mutex_owner(mp) == curthread);
346 error = pthread_cond_timedwait(cv, &mp->m_lock, &ts);
347 mp->m_owner = curthread;
352 if (error == ETIMEDOUT)
362 cv_timedwait_hires(kcondvar_t *cv, kmutex_t *mp, hrtime_t tim, hrtime_t res,
369 ASSERT(flag == 0 || flag == CALLOUT_FLAG_ABSOLUTE);
373 if (flag & CALLOUT_FLAG_ABSOLUTE)
374 delta -= gethrtime();
379 clock_gettime(CLOCK_REALTIME, &ts);
380 ts.tv_sec += delta / NANOSEC;
381 ts.tv_nsec += delta % NANOSEC;
382 if (ts.tv_nsec >= NANOSEC) {
384 ts.tv_nsec -= NANOSEC;
387 ASSERT(mutex_owner(mp) == curthread);
389 error = pthread_cond_timedwait(cv, &mp->m_lock, &ts);
390 mp->m_owner = curthread;
392 if (error == ETIMEDOUT)
404 cv_signal(kcondvar_t *cv)
406 VERIFY(cond_signal(cv) == 0);
410 cv_broadcast(kcondvar_t *cv)
412 VERIFY(cond_broadcast(cv) == 0);
416 * =========================================================================
418 * =========================================================================
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.
429 vn_open(char *path, int x1, int flags, int mode, vnode_t **vpp, int x2, int x3)
435 char realpath[MAXPATHLEN];
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().
448 if (strncmp(path, "/dev/", 5) == 0) {
450 fd = open64(path, O_RDONLY);
453 if (fstat64(fd, &st) == -1) {
458 (void) sprintf(realpath, "%s", path);
459 dsk = strstr(path, "/dsk/");
461 (void) sprintf(realpath + (dsk - path) + 1, "r%s",
464 (void) sprintf(realpath, "%s", path);
465 if (!(flags & FCREAT) && stat64(realpath, &st) == -1)
470 old_umask = umask(0);
473 * The construct 'flags - FREAD' conveniently maps combinations of
474 * FREAD and FWRITE to the corresponding O_RDONLY, O_WRONLY, and O_RDWR.
476 fd = open64(realpath, flags - FREAD, mode);
479 (void) umask(old_umask);
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);
495 if (fstat64(fd, &st) == -1) {
500 (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
502 *vpp = vp = umem_zalloc(sizeof (vnode_t), UMEM_NOFAIL);
505 vp->v_size = st.st_size;
506 vp->v_path = spa_strdup(path);
507 vp->v_dump_fd = dump_fd;
514 vn_openat(char *path, int x1, int flags, int mode, vnode_t **vpp, int x2,
515 int x3, vnode_t *startvp, int fd)
517 char *realpath = umem_alloc(strlen(path) + 2, UMEM_NOFAIL);
520 ASSERT(startvp == rootdir);
521 (void) sprintf(realpath, "/%s", path);
523 /* fd ignored for now, need if want to simulate nbmand support */
524 ret = vn_open(realpath, x1, flags, mode, vpp, x2, x3);
526 umem_free(realpath, strlen(path) + 2);
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)
536 ssize_t iolen, split;
538 if (uio == UIO_READ) {
539 iolen = pread64(vp->v_fd, addr, len, offset);
540 if (vp->v_dump_fd != -1) {
542 pwrite64(vp->v_dump_fd, addr, iolen, offset);
543 ASSERT(status != -1);
547 * To simulate partial disk writes, we split writes into two
548 * system calls so that the process can be killed in between.
550 int sectors = len >> SPA_MINBLOCKSHIFT;
551 split = (sectors > 0 ? rand() % sectors : 0) <<
553 iolen = pwrite64(vp->v_fd, addr, split, offset);
554 iolen += pwrite64(vp->v_fd, (char *)addr + split,
555 len - split, offset + split);
561 *residp = len - iolen;
562 else if (iolen != len)
568 vn_close(vnode_t *vp, int openflag, cred_t *cr, kthread_t *td)
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));
578 * At a minimum we need to update the size since vdev_reopen()
579 * will no longer call vn_openat().
582 fop_getattr(vnode_t *vp, vattr_t *vap)
586 if (fstat64(vp->v_fd, &st) == -1) {
591 vap->va_size = st.st_size;
598 * =========================================================================
599 * Figure out which debugging statements to print
600 * =========================================================================
603 static char *dprintf_string;
604 static int dprintf_print_all;
607 dprintf_find_string(const char *string)
609 char *tmp_str = dprintf_string;
610 int len = strlen(string);
613 * Find out if this is a string we want to print.
614 * String format: file1.c,function_name1,file2.c,file3.c
617 while (tmp_str != NULL) {
618 if (strncmp(tmp_str, string, len) == 0 &&
619 (tmp_str[len] == ',' || tmp_str[len] == '\0'))
621 tmp_str = strchr(tmp_str, ',');
623 tmp_str++; /* Get rid of , */
629 dprintf_setup(int *argc, char **argv)
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.
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++)
653 if (dprintf_string == NULL) {
654 /* Look for ZFS_DEBUG environment variable */
655 dprintf_string = getenv("ZFS_DEBUG");
659 * Are we just turning on all debugging?
661 if (dprintf_find_string("on"))
662 dprintf_print_all = 1;
666 sysctl_handle_64(SYSCTL_HANDLER_ARGS)
672 * =========================================================================
674 * =========================================================================
677 __dprintf(const char *file, const char *func, int line, const char *fmt, ...)
683 * Get rid of annoying "../common/" prefix to filename.
685 newfile = strrchr(file, '/');
686 if (newfile != NULL) {
687 newfile = newfile + 1; /* Get rid of leading / */
692 if (dprintf_print_all ||
693 dprintf_find_string(newfile) ||
694 dprintf_find_string(func)) {
695 /* Print out just the function name if requested */
697 if (dprintf_find_string("pid"))
698 (void) printf("%d ", getpid());
699 if (dprintf_find_string("tid"))
700 (void) printf("%ul ", thr_self());
702 if (dprintf_find_string("cpu"))
703 (void) printf("%u ", getcpuid());
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);
711 (void) vprintf(fmt, adx);
717 #endif /* ZFS_DEBUG */
720 * =========================================================================
721 * cmn_err() and panic()
722 * =========================================================================
724 static char ce_prefix[CE_IGNORE][10] = { "", "NOTICE: ", "WARNING: ", "" };
725 static char ce_suffix[CE_IGNORE][2] = { "", "\n", "\n", "" };
728 vpanic(const char *fmt, va_list adx)
730 (void) fprintf(stderr, "error: ");
731 (void) vfprintf(stderr, fmt, adx);
732 (void) fprintf(stderr, "\n");
734 abort(); /* think of it as a "user-level crash dump" */
738 panic(const char *fmt, ...)
748 vcmn_err(int ce, const char *fmt, va_list 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]);
761 cmn_err(int ce, const char *fmt, ...)
766 vcmn_err(ce, fmt, adx);
771 * =========================================================================
773 * =========================================================================
776 kobj_open_file(char *name)
781 /* set vp as the _fd field of the file */
782 if (vn_openat(name, UIO_SYSSPACE, FREAD, 0, &vp, 0, 0, rootdir,
784 return ((void *)-1UL);
786 file = umem_zalloc(sizeof (struct _buf), UMEM_NOFAIL);
787 file->_fd = (intptr_t)vp;
792 kobj_read_file(struct _buf *file, char *buf, unsigned size, unsigned off)
796 vn_rdwr(UIO_READ, (vnode_t *)file->_fd, buf, size, (offset_t)off,
797 UIO_SYSSPACE, 0, 0, 0, &resid);
799 return (size - resid);
803 kobj_close_file(struct _buf *file)
805 vn_close((vnode_t *)file->_fd, 0, NULL, NULL);
806 umem_free(file, sizeof (struct _buf));
810 kobj_get_filesize(struct _buf *file, uint64_t *size)
813 vnode_t *vp = (vnode_t *)file->_fd;
815 if (fstat64(vp->v_fd, &st) == -1) {
816 vn_close(vp, 0, NULL, NULL);
824 * =========================================================================
826 * =========================================================================
832 poll(0, 0, ticks * (1000 / hz));
837 * Find highest one bit set.
838 * Returns bit number + 1 of highest bit that is set, otherwise returns 0.
841 highbit64(uint64_t i)
847 if (i & 0xffffffff00000000ULL) {
850 if (i & 0xffff0000) {
869 static int random_fd = -1, urandom_fd = -1;
872 random_get_bytes_common(uint8_t *ptr, size_t len, int fd)
880 bytes = read(fd, ptr, resid);
881 ASSERT3S(bytes, >=, 0);
890 random_get_bytes(uint8_t *ptr, size_t len)
892 return (random_get_bytes_common(ptr, len, random_fd));
896 random_get_pseudo_bytes(uint8_t *ptr, size_t len)
898 return (random_get_bytes_common(ptr, len, urandom_fd));
902 ddi_strtoul(const char *hw_serial, char **nptr, int base, unsigned long *result)
906 *result = strtoul(hw_serial, &end, base);
913 ddi_strtoull(const char *str, char **nptr, int base, u_longlong_t *result)
917 *result = strtoull(str, &end, base);
926 cyclic_add(cyc_handler_t *hdlr, cyc_time_t *when)
933 cyclic_remove(cyclic_id_t id)
939 cyclic_reprogram(cyclic_id_t id, hrtime_t expiration)
946 * =========================================================================
947 * kernel emulation setup & teardown
948 * =========================================================================
951 umem_out_of_memory(void)
953 char errmsg[] = "out of memory -- generating core dump\n";
955 write(fileno(stderr), errmsg, sizeof (errmsg));
961 kernel_init(int mode)
963 extern uint_t rrw_tsd_key;
965 umem_nofail_callback(umem_out_of_memory);
967 physmem = sysconf(_SC_PHYS_PAGES);
969 dprintf("physmem = %llu pages (%.2f GB)\n", physmem,
970 (double)physmem * sysconf(_SC_PAGE_SIZE) / (1ULL << 30));
972 (void) snprintf(hw_serial, sizeof (hw_serial), "%lu",
973 (mode & FWRITE) ? (unsigned long)gethostid() : 0);
975 VERIFY((random_fd = open("/dev/random", O_RDONLY)) != -1);
976 VERIFY((urandom_fd = open("/dev/urandom", O_RDONLY)) != -1);
981 mutex_init(&cpu_lock, NULL, MUTEX_DEFAULT, NULL);
986 tsd_create(&rrw_tsd_key, rrw_tsd_destroy);
1004 z_uncompress(void *dst, size_t *dstlen, const void *src, size_t srclen)
1007 uLongf len = *dstlen;
1009 if ((ret = uncompress(dst, &len, src, srclen)) == Z_OK)
1010 *dstlen = (size_t)len;
1016 z_compress_level(void *dst, size_t *dstlen, const void *src, size_t srclen,
1020 uLongf len = *dstlen;
1022 if ((ret = compress2(dst, &len, src, srclen, level)) == Z_OK)
1023 *dstlen = (size_t)len;
1029 crgetuid(cred_t *cr)
1035 crgetruid(cred_t *cr)
1041 crgetgid(cred_t *cr)
1047 crgetngroups(cred_t *cr)
1053 crgetgroups(cred_t *cr)
1059 zfs_secpolicy_snapshot_perms(const char *name, cred_t *cr)
1065 zfs_secpolicy_rename_perms(const char *from, const char *to, cred_t *cr)
1071 zfs_secpolicy_destroy_perms(const char *name, cred_t *cr)
1077 ksid_lookupdomain(const char *dom)
1081 kd = umem_zalloc(sizeof (ksiddomain_t), UMEM_NOFAIL);
1082 kd->kd_name = spa_strdup(dom);
1087 ksiddomain_rele(ksiddomain_t *ksid)
1089 spa_strfree(ksid->kd_name);
1090 umem_free(ksid, sizeof (ksiddomain_t));
1094 * Do not change the length of the returned string; it must be freed
1098 kmem_asprintf(const char *fmt, ...)
1105 size = vsnprintf(NULL, 0, fmt, adx) + 1;
1108 buf = kmem_alloc(size, KM_SLEEP);
1111 size = vsnprintf(buf, size, fmt, adx);
1119 zfs_onexit_fd_hold(int fd, minor_t *minorp)
1127 zfs_onexit_fd_rele(int fd)
1133 zfs_onexit_add_cb(minor_t minor, void (*func)(void *), void *data,
1134 uint64_t *action_handle)
1141 zfs_onexit_del_cb(minor_t minor, uint64_t action_handle, boolean_t fire)
1148 zfs_onexit_cb_data(minor_t minor, uint64_t action_handle, void **data)
1156 zvol_create_minors(const char *name)
1166 bzero(bp, sizeof (buf_t));
1172 if (bp->b_iodone != NULL) {
1173 (*(bp->b_iodone))(bp);
1176 ASSERT((bp->b_flags & B_DONE) == 0);
1177 bp->b_flags |= B_DONE;
1181 bioerror(buf_t *bp, int error)
1187 bp->b_flags |= B_ERROR;
1189 bp->b_flags &= ~B_ERROR;
1191 bp->b_error = error;
1196 geterror(struct buf *bp)
1200 if (bp->b_flags & B_ERROR) {
1201 error = bp->b_error;