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, 2014 by Delphix. All rights reserved.
24 * Copyright (c) 2013, Joyent, Inc. All rights reserved.
36 #include <sys/processor.h>
37 #include <sys/zfs_context.h>
38 #include <sys/rrwlock.h>
40 #include <sys/utsname.h>
41 #include <sys/systeminfo.h>
44 * Emulation of kernel services in userland.
49 vnode_t *rootdir = (vnode_t *)0xabcd1234;
50 char hw_serial[HW_HOSTID_LEN];
55 struct utsname utsname = {
56 "userland", "libzpool", "1", "1", "na"
59 /* this only exists to have its address taken */
63 * =========================================================================
65 * =========================================================================
69 zk_thread_create(void (*func)(), void *arg)
73 VERIFY(thr_create(0, 0, (void *(*)(void *))func, arg, THR_DETACHED,
76 return ((void *)(uintptr_t)tid);
80 * =========================================================================
82 * =========================================================================
86 kstat_create(char *module, int instance, char *name, char *class,
87 uchar_t type, ulong_t ndata, uchar_t ks_flag)
94 kstat_install(kstat_t *ksp)
99 kstat_delete(kstat_t *ksp)
103 * =========================================================================
105 * =========================================================================
108 zmutex_init(kmutex_t *mp)
111 mp->initialized = B_TRUE;
112 (void) _mutex_init(&mp->m_lock, USYNC_THREAD, NULL);
116 zmutex_destroy(kmutex_t *mp)
118 ASSERT(mp->initialized == B_TRUE);
119 ASSERT(mp->m_owner == NULL);
120 (void) _mutex_destroy(&(mp)->m_lock);
121 mp->m_owner = (void *)-1UL;
122 mp->initialized = B_FALSE;
126 zmutex_owned(kmutex_t *mp)
128 ASSERT(mp->initialized == B_TRUE);
130 return (mp->m_owner == curthread);
134 mutex_enter(kmutex_t *mp)
136 ASSERT(mp->initialized == B_TRUE);
137 ASSERT(mp->m_owner != (void *)-1UL);
138 ASSERT(mp->m_owner != curthread);
139 VERIFY(mutex_lock(&mp->m_lock) == 0);
140 ASSERT(mp->m_owner == NULL);
141 mp->m_owner = curthread;
145 mutex_tryenter(kmutex_t *mp)
147 ASSERT(mp->initialized == B_TRUE);
148 ASSERT(mp->m_owner != (void *)-1UL);
149 if (0 == mutex_trylock(&mp->m_lock)) {
150 ASSERT(mp->m_owner == NULL);
151 mp->m_owner = curthread;
159 mutex_exit(kmutex_t *mp)
161 ASSERT(mp->initialized == B_TRUE);
162 ASSERT(mutex_owner(mp) == curthread);
164 VERIFY(mutex_unlock(&mp->m_lock) == 0);
168 mutex_owner(kmutex_t *mp)
170 ASSERT(mp->initialized == B_TRUE);
171 return (mp->m_owner);
175 * =========================================================================
177 * =========================================================================
181 rw_init(krwlock_t *rwlp, char *name, int type, void *arg)
183 rwlock_init(&rwlp->rw_lock, USYNC_THREAD, NULL);
184 rwlp->rw_owner = NULL;
185 rwlp->initialized = B_TRUE;
190 rw_destroy(krwlock_t *rwlp)
192 ASSERT(rwlp->rw_count == 0);
193 rwlock_destroy(&rwlp->rw_lock);
194 rwlp->rw_owner = (void *)-1UL;
195 rwlp->initialized = B_FALSE;
199 rw_enter(krwlock_t *rwlp, krw_t rw)
201 //ASSERT(!RW_LOCK_HELD(rwlp));
202 ASSERT(rwlp->initialized == B_TRUE);
203 ASSERT(rwlp->rw_owner != (void *)-1UL);
204 ASSERT(rwlp->rw_owner != curthread);
206 if (rw == RW_READER) {
207 VERIFY(rw_rdlock(&rwlp->rw_lock) == 0);
208 ASSERT(rwlp->rw_count >= 0);
209 atomic_add_int(&rwlp->rw_count, 1);
211 VERIFY(rw_wrlock(&rwlp->rw_lock) == 0);
212 ASSERT(rwlp->rw_count == 0);
214 rwlp->rw_owner = curthread;
219 rw_exit(krwlock_t *rwlp)
221 ASSERT(rwlp->initialized == B_TRUE);
222 ASSERT(rwlp->rw_owner != (void *)-1UL);
224 if (rwlp->rw_owner == curthread) {
226 ASSERT(rwlp->rw_count == -1);
228 rwlp->rw_owner = NULL;
231 ASSERT(rwlp->rw_count > 0);
232 atomic_add_int(&rwlp->rw_count, -1);
234 VERIFY(rw_unlock(&rwlp->rw_lock) == 0);
238 rw_tryenter(krwlock_t *rwlp, krw_t rw)
242 ASSERT(rwlp->initialized == B_TRUE);
243 ASSERT(rwlp->rw_owner != (void *)-1UL);
244 ASSERT(rwlp->rw_owner != curthread);
247 rv = rw_tryrdlock(&rwlp->rw_lock);
249 rv = rw_trywrlock(&rwlp->rw_lock);
252 ASSERT(rwlp->rw_owner == NULL);
253 if (rw == RW_READER) {
254 ASSERT(rwlp->rw_count >= 0);
255 atomic_add_int(&rwlp->rw_count, 1);
257 ASSERT(rwlp->rw_count == 0);
259 rwlp->rw_owner = curthread;
269 rw_tryupgrade(krwlock_t *rwlp)
271 ASSERT(rwlp->initialized == B_TRUE);
272 ASSERT(rwlp->rw_owner != (void *)-1UL);
278 rw_lock_held(krwlock_t *rwlp)
281 return (rwlp->rw_count != 0);
285 * =========================================================================
286 * condition variables
287 * =========================================================================
291 cv_init(kcondvar_t *cv, char *name, int type, void *arg)
293 VERIFY(cond_init(cv, name, NULL) == 0);
297 cv_destroy(kcondvar_t *cv)
299 VERIFY(cond_destroy(cv) == 0);
303 cv_wait(kcondvar_t *cv, kmutex_t *mp)
305 ASSERT(mutex_owner(mp) == curthread);
307 int ret = cond_wait(cv, &mp->m_lock);
308 VERIFY(ret == 0 || ret == EINTR);
309 mp->m_owner = curthread;
313 cv_timedwait(kcondvar_t *cv, kmutex_t *mp, clock_t abstime)
320 abstime += ddi_get_lbolt();
322 delta = abstime - ddi_get_lbolt();
326 if (gettimeofday(&tv, NULL) != 0)
327 assert(!"gettimeofday() failed");
329 ts.tv_sec = tv.tv_sec + delta / hz;
330 ts.tv_nsec = tv.tv_usec * 1000 + (delta % hz) * (NANOSEC / hz);
331 ASSERT(ts.tv_nsec >= 0);
333 if (ts.tv_nsec >= NANOSEC) {
335 ts.tv_nsec -= NANOSEC;
338 ASSERT(mutex_owner(mp) == curthread);
340 error = pthread_cond_timedwait(cv, &mp->m_lock, &ts);
341 mp->m_owner = curthread;
346 if (error == ETIMEDOUT)
356 cv_timedwait_hires(kcondvar_t *cv, kmutex_t *mp, hrtime_t tim, hrtime_t res,
366 delta = tim - gethrtime();
370 ts.tv_sec = delta / NANOSEC;
371 ts.tv_nsec = delta % NANOSEC;
373 ASSERT(mutex_owner(mp) == curthread);
375 error = pthread_cond_timedwait(cv, &mp->m_lock, &ts);
376 mp->m_owner = curthread;
378 if (error == ETIMEDOUT)
390 cv_signal(kcondvar_t *cv)
392 VERIFY(cond_signal(cv) == 0);
396 cv_broadcast(kcondvar_t *cv)
398 VERIFY(cond_broadcast(cv) == 0);
402 * =========================================================================
404 * =========================================================================
407 * Note: for the xxxat() versions of these functions, we assume that the
408 * starting vp is always rootdir (which is true for spa_directory.c, the only
409 * ZFS consumer of these interfaces). We assert this is true, and then emulate
410 * them by adding '/' in front of the path.
415 vn_open(char *path, int x1, int flags, int mode, vnode_t **vpp, int x2, int x3)
420 char realpath[MAXPATHLEN];
424 * If we're accessing a real disk from userland, we need to use
425 * the character interface to avoid caching. This is particularly
426 * important if we're trying to look at a real in-kernel storage
427 * pool from userland, e.g. via zdb, because otherwise we won't
428 * see the changes occurring under the segmap cache.
429 * On the other hand, the stupid character device returns zero
430 * for its size. So -- gag -- we open the block device to get
431 * its size, and remember it for subsequent VOP_GETATTR().
433 if (strncmp(path, "/dev/", 5) == 0) {
435 fd = open64(path, O_RDONLY);
438 if (fstat64(fd, &st) == -1) {
443 (void) sprintf(realpath, "%s", path);
444 dsk = strstr(path, "/dsk/");
446 (void) sprintf(realpath + (dsk - path) + 1, "r%s",
449 (void) sprintf(realpath, "%s", path);
450 if (!(flags & FCREAT) && stat64(realpath, &st) == -1)
455 old_umask = umask(0);
458 * The construct 'flags - FREAD' conveniently maps combinations of
459 * FREAD and FWRITE to the corresponding O_RDONLY, O_WRONLY, and O_RDWR.
461 fd = open64(realpath, flags - FREAD, mode);
464 (void) umask(old_umask);
469 if (fstat64(fd, &st) == -1) {
474 (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
476 *vpp = vp = umem_zalloc(sizeof (vnode_t), UMEM_NOFAIL);
479 vp->v_size = st.st_size;
480 vp->v_path = spa_strdup(path);
487 vn_openat(char *path, int x1, int flags, int mode, vnode_t **vpp, int x2,
488 int x3, vnode_t *startvp, int fd)
490 char *realpath = umem_alloc(strlen(path) + 2, UMEM_NOFAIL);
493 ASSERT(startvp == rootdir);
494 (void) sprintf(realpath, "/%s", path);
496 /* fd ignored for now, need if want to simulate nbmand support */
497 ret = vn_open(realpath, x1, flags, mode, vpp, x2, x3);
499 umem_free(realpath, strlen(path) + 2);
506 vn_rdwr(int uio, vnode_t *vp, void *addr, ssize_t len, offset_t offset,
507 int x1, int x2, rlim64_t x3, void *x4, ssize_t *residp)
509 ssize_t iolen, split;
511 if (uio == UIO_READ) {
512 iolen = pread64(vp->v_fd, addr, len, offset);
515 * To simulate partial disk writes, we split writes into two
516 * system calls so that the process can be killed in between.
518 int sectors = len >> SPA_MINBLOCKSHIFT;
519 split = (sectors > 0 ? rand() % sectors : 0) <<
521 iolen = pwrite64(vp->v_fd, addr, split, offset);
522 iolen += pwrite64(vp->v_fd, (char *)addr + split,
523 len - split, offset + split);
529 *residp = len - iolen;
530 else if (iolen != len)
536 vn_close(vnode_t *vp, int openflag, cred_t *cr, kthread_t *td)
539 spa_strfree(vp->v_path);
540 umem_free(vp, sizeof (vnode_t));
544 * At a minimum we need to update the size since vdev_reopen()
545 * will no longer call vn_openat().
548 fop_getattr(vnode_t *vp, vattr_t *vap)
552 if (fstat64(vp->v_fd, &st) == -1) {
557 vap->va_size = st.st_size;
564 * =========================================================================
565 * Figure out which debugging statements to print
566 * =========================================================================
569 static char *dprintf_string;
570 static int dprintf_print_all;
573 dprintf_find_string(const char *string)
575 char *tmp_str = dprintf_string;
576 int len = strlen(string);
579 * Find out if this is a string we want to print.
580 * String format: file1.c,function_name1,file2.c,file3.c
583 while (tmp_str != NULL) {
584 if (strncmp(tmp_str, string, len) == 0 &&
585 (tmp_str[len] == ',' || tmp_str[len] == '\0'))
587 tmp_str = strchr(tmp_str, ',');
589 tmp_str++; /* Get rid of , */
595 dprintf_setup(int *argc, char **argv)
600 * Debugging can be specified two ways: by setting the
601 * environment variable ZFS_DEBUG, or by including a
602 * "debug=..." argument on the command line. The command
603 * line setting overrides the environment variable.
606 for (i = 1; i < *argc; i++) {
607 int len = strlen("debug=");
608 /* First look for a command line argument */
609 if (strncmp("debug=", argv[i], len) == 0) {
610 dprintf_string = argv[i] + len;
611 /* Remove from args */
612 for (j = i; j < *argc; j++)
619 if (dprintf_string == NULL) {
620 /* Look for ZFS_DEBUG environment variable */
621 dprintf_string = getenv("ZFS_DEBUG");
625 * Are we just turning on all debugging?
627 if (dprintf_find_string("on"))
628 dprintf_print_all = 1;
632 sysctl_handle_64(SYSCTL_HANDLER_ARGS)
638 * =========================================================================
640 * =========================================================================
643 __dprintf(const char *file, const char *func, int line, const char *fmt, ...)
649 * Get rid of annoying "../common/" prefix to filename.
651 newfile = strrchr(file, '/');
652 if (newfile != NULL) {
653 newfile = newfile + 1; /* Get rid of leading / */
658 if (dprintf_print_all ||
659 dprintf_find_string(newfile) ||
660 dprintf_find_string(func)) {
661 /* Print out just the function name if requested */
663 if (dprintf_find_string("pid"))
664 (void) printf("%d ", getpid());
665 if (dprintf_find_string("tid"))
666 (void) printf("%ul ", thr_self());
668 if (dprintf_find_string("cpu"))
669 (void) printf("%u ", getcpuid());
671 if (dprintf_find_string("time"))
672 (void) printf("%llu ", gethrtime());
673 if (dprintf_find_string("long"))
674 (void) printf("%s, line %d: ", newfile, line);
675 (void) printf("%s: ", func);
677 (void) vprintf(fmt, adx);
683 #endif /* ZFS_DEBUG */
686 * =========================================================================
687 * cmn_err() and panic()
688 * =========================================================================
690 static char ce_prefix[CE_IGNORE][10] = { "", "NOTICE: ", "WARNING: ", "" };
691 static char ce_suffix[CE_IGNORE][2] = { "", "\n", "\n", "" };
694 vpanic(const char *fmt, va_list adx)
696 (void) fprintf(stderr, "error: ");
697 (void) vfprintf(stderr, fmt, adx);
698 (void) fprintf(stderr, "\n");
700 abort(); /* think of it as a "user-level crash dump" */
704 panic(const char *fmt, ...)
714 vcmn_err(int ce, const char *fmt, va_list adx)
718 if (ce != CE_NOTE) { /* suppress noise in userland stress testing */
719 (void) fprintf(stderr, "%s", ce_prefix[ce]);
720 (void) vfprintf(stderr, fmt, adx);
721 (void) fprintf(stderr, "%s", ce_suffix[ce]);
727 cmn_err(int ce, const char *fmt, ...)
732 vcmn_err(ce, fmt, adx);
737 * =========================================================================
739 * =========================================================================
742 kobj_open_file(char *name)
747 /* set vp as the _fd field of the file */
748 if (vn_openat(name, UIO_SYSSPACE, FREAD, 0, &vp, 0, 0, rootdir,
750 return ((void *)-1UL);
752 file = umem_zalloc(sizeof (struct _buf), UMEM_NOFAIL);
753 file->_fd = (intptr_t)vp;
758 kobj_read_file(struct _buf *file, char *buf, unsigned size, unsigned off)
762 vn_rdwr(UIO_READ, (vnode_t *)file->_fd, buf, size, (offset_t)off,
763 UIO_SYSSPACE, 0, 0, 0, &resid);
765 return (size - resid);
769 kobj_close_file(struct _buf *file)
771 vn_close((vnode_t *)file->_fd, 0, NULL, NULL);
772 umem_free(file, sizeof (struct _buf));
776 kobj_get_filesize(struct _buf *file, uint64_t *size)
779 vnode_t *vp = (vnode_t *)file->_fd;
781 if (fstat64(vp->v_fd, &st) == -1) {
782 vn_close(vp, 0, NULL, NULL);
790 * =========================================================================
792 * =========================================================================
798 poll(0, 0, ticks * (1000 / hz));
803 * Find highest one bit set.
804 * Returns bit number + 1 of highest bit that is set, otherwise returns 0.
807 highbit64(uint64_t i)
813 if (i & 0xffffffff00000000ULL) {
816 if (i & 0xffff0000) {
835 static int random_fd = -1, urandom_fd = -1;
838 random_get_bytes_common(uint8_t *ptr, size_t len, int fd)
846 bytes = read(fd, ptr, resid);
847 ASSERT3S(bytes, >=, 0);
856 random_get_bytes(uint8_t *ptr, size_t len)
858 return (random_get_bytes_common(ptr, len, random_fd));
862 random_get_pseudo_bytes(uint8_t *ptr, size_t len)
864 return (random_get_bytes_common(ptr, len, urandom_fd));
868 ddi_strtoul(const char *hw_serial, char **nptr, int base, unsigned long *result)
872 *result = strtoul(hw_serial, &end, base);
879 ddi_strtoull(const char *str, char **nptr, int base, u_longlong_t *result)
883 *result = strtoull(str, &end, base);
892 cyclic_add(cyc_handler_t *hdlr, cyc_time_t *when)
899 cyclic_remove(cyclic_id_t id)
905 cyclic_reprogram(cyclic_id_t id, hrtime_t expiration)
912 * =========================================================================
913 * kernel emulation setup & teardown
914 * =========================================================================
917 umem_out_of_memory(void)
919 char errmsg[] = "out of memory -- generating core dump\n";
921 write(fileno(stderr), errmsg, sizeof (errmsg));
927 kernel_init(int mode)
929 extern uint_t rrw_tsd_key;
931 umem_nofail_callback(umem_out_of_memory);
933 physmem = sysconf(_SC_PHYS_PAGES);
935 dprintf("physmem = %llu pages (%.2f GB)\n", physmem,
936 (double)physmem * sysconf(_SC_PAGE_SIZE) / (1ULL << 30));
938 (void) snprintf(hw_serial, sizeof (hw_serial), "%lu",
939 (mode & FWRITE) ? (unsigned long)gethostid() : 0);
941 VERIFY((random_fd = open("/dev/random", O_RDONLY)) != -1);
942 VERIFY((urandom_fd = open("/dev/urandom", O_RDONLY)) != -1);
947 mutex_init(&cpu_lock, NULL, MUTEX_DEFAULT, NULL);
952 tsd_create(&rrw_tsd_key, rrw_tsd_destroy);
970 z_uncompress(void *dst, size_t *dstlen, const void *src, size_t srclen)
973 uLongf len = *dstlen;
975 if ((ret = uncompress(dst, &len, src, srclen)) == Z_OK)
976 *dstlen = (size_t)len;
982 z_compress_level(void *dst, size_t *dstlen, const void *src, size_t srclen,
986 uLongf len = *dstlen;
988 if ((ret = compress2(dst, &len, src, srclen, level)) == Z_OK)
989 *dstlen = (size_t)len;
1001 crgetruid(cred_t *cr)
1007 crgetgid(cred_t *cr)
1013 crgetngroups(cred_t *cr)
1019 crgetgroups(cred_t *cr)
1025 zfs_secpolicy_snapshot_perms(const char *name, cred_t *cr)
1031 zfs_secpolicy_rename_perms(const char *from, const char *to, cred_t *cr)
1037 zfs_secpolicy_destroy_perms(const char *name, cred_t *cr)
1043 ksid_lookupdomain(const char *dom)
1047 kd = umem_zalloc(sizeof (ksiddomain_t), UMEM_NOFAIL);
1048 kd->kd_name = spa_strdup(dom);
1053 ksiddomain_rele(ksiddomain_t *ksid)
1055 spa_strfree(ksid->kd_name);
1056 umem_free(ksid, sizeof (ksiddomain_t));
1060 * Do not change the length of the returned string; it must be freed
1064 kmem_asprintf(const char *fmt, ...)
1071 size = vsnprintf(NULL, 0, fmt, adx) + 1;
1074 buf = kmem_alloc(size, KM_SLEEP);
1077 size = vsnprintf(buf, size, fmt, adx);
1085 zfs_onexit_fd_hold(int fd, minor_t *minorp)
1093 zfs_onexit_fd_rele(int fd)
1099 zfs_onexit_add_cb(minor_t minor, void (*func)(void *), void *data,
1100 uint64_t *action_handle)
1107 zfs_onexit_del_cb(minor_t minor, uint64_t action_handle, boolean_t fire)
1114 zfs_onexit_cb_data(minor_t minor, uint64_t action_handle, void **data)
1122 zvol_create_minors(const char *name)
1132 bzero(bp, sizeof (buf_t));
1138 if (bp->b_iodone != NULL) {
1139 (*(bp->b_iodone))(bp);
1142 ASSERT((bp->b_flags & B_DONE) == 0);
1143 bp->b_flags |= B_DONE;
1147 bioerror(buf_t *bp, int error)
1153 bp->b_flags |= B_ERROR;
1155 bp->b_flags &= ~B_ERROR;
1157 bp->b_error = error;
1162 geterror(struct buf *bp)
1166 if (bp->b_flags & B_ERROR) {
1167 error = bp->b_error;