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.
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.
50 vnode_t *rootdir = (vnode_t *)0xabcd1234;
51 char hw_serial[HW_HOSTID_LEN];
56 /* If set, all blocks read will be copied to the specified directory. */
57 char *vn_dumpdir = NULL;
59 struct utsname utsname = {
60 "userland", "libzpool", "1", "1", "na"
63 /* this only exists to have its address taken */
67 * =========================================================================
69 * =========================================================================
73 zk_thread_create(void (*func)(), void *arg)
77 VERIFY(thr_create(0, 0, (void *(*)(void *))func, arg, THR_DETACHED,
80 return ((void *)(uintptr_t)tid);
84 * =========================================================================
86 * =========================================================================
90 kstat_create(char *module, int instance, char *name, char *class,
91 uchar_t type, ulong_t ndata, uchar_t ks_flag)
98 kstat_install(kstat_t *ksp)
103 kstat_delete(kstat_t *ksp)
107 * =========================================================================
109 * =========================================================================
112 zmutex_init(kmutex_t *mp)
115 mp->initialized = B_TRUE;
116 (void) _mutex_init(&mp->m_lock, USYNC_THREAD, NULL);
120 zmutex_destroy(kmutex_t *mp)
122 ASSERT(mp->initialized == B_TRUE);
123 ASSERT(mp->m_owner == NULL);
124 (void) _mutex_destroy(&(mp)->m_lock);
125 mp->m_owner = (void *)-1UL;
126 mp->initialized = B_FALSE;
130 zmutex_owned(kmutex_t *mp)
132 ASSERT(mp->initialized == B_TRUE);
134 return (mp->m_owner == curthread);
138 mutex_enter(kmutex_t *mp)
140 ASSERT(mp->initialized == B_TRUE);
141 ASSERT(mp->m_owner != (void *)-1UL);
142 ASSERT(mp->m_owner != curthread);
143 VERIFY(mutex_lock(&mp->m_lock) == 0);
144 ASSERT(mp->m_owner == NULL);
145 mp->m_owner = curthread;
149 mutex_tryenter(kmutex_t *mp)
151 ASSERT(mp->initialized == B_TRUE);
152 ASSERT(mp->m_owner != (void *)-1UL);
153 if (0 == mutex_trylock(&mp->m_lock)) {
154 ASSERT(mp->m_owner == NULL);
155 mp->m_owner = curthread;
163 mutex_exit(kmutex_t *mp)
165 ASSERT(mp->initialized == B_TRUE);
166 ASSERT(mutex_owner(mp) == curthread);
168 VERIFY(mutex_unlock(&mp->m_lock) == 0);
172 mutex_owner(kmutex_t *mp)
174 ASSERT(mp->initialized == B_TRUE);
175 return (mp->m_owner);
179 * =========================================================================
181 * =========================================================================
185 rw_init(krwlock_t *rwlp, char *name, int type, void *arg)
187 rwlock_init(&rwlp->rw_lock, USYNC_THREAD, NULL);
188 rwlp->rw_owner = NULL;
189 rwlp->initialized = B_TRUE;
194 rw_destroy(krwlock_t *rwlp)
196 ASSERT(rwlp->rw_count == 0);
197 rwlock_destroy(&rwlp->rw_lock);
198 rwlp->rw_owner = (void *)-1UL;
199 rwlp->initialized = B_FALSE;
203 rw_enter(krwlock_t *rwlp, krw_t rw)
205 //ASSERT(!RW_LOCK_HELD(rwlp));
206 ASSERT(rwlp->initialized == B_TRUE);
207 ASSERT(rwlp->rw_owner != (void *)-1UL);
208 ASSERT(rwlp->rw_owner != curthread);
210 if (rw == RW_READER) {
211 VERIFY(rw_rdlock(&rwlp->rw_lock) == 0);
212 ASSERT(rwlp->rw_count >= 0);
213 atomic_add_int(&rwlp->rw_count, 1);
215 VERIFY(rw_wrlock(&rwlp->rw_lock) == 0);
216 ASSERT(rwlp->rw_count == 0);
218 rwlp->rw_owner = curthread;
223 rw_exit(krwlock_t *rwlp)
225 ASSERT(rwlp->initialized == B_TRUE);
226 ASSERT(rwlp->rw_owner != (void *)-1UL);
228 if (rwlp->rw_owner == curthread) {
230 ASSERT(rwlp->rw_count == -1);
232 rwlp->rw_owner = NULL;
235 ASSERT(rwlp->rw_count > 0);
236 atomic_add_int(&rwlp->rw_count, -1);
238 VERIFY(rw_unlock(&rwlp->rw_lock) == 0);
242 rw_tryenter(krwlock_t *rwlp, krw_t rw)
246 ASSERT(rwlp->initialized == B_TRUE);
247 ASSERT(rwlp->rw_owner != (void *)-1UL);
248 ASSERT(rwlp->rw_owner != curthread);
251 rv = rw_tryrdlock(&rwlp->rw_lock);
253 rv = rw_trywrlock(&rwlp->rw_lock);
256 ASSERT(rwlp->rw_owner == NULL);
257 if (rw == RW_READER) {
258 ASSERT(rwlp->rw_count >= 0);
259 atomic_add_int(&rwlp->rw_count, 1);
261 ASSERT(rwlp->rw_count == 0);
263 rwlp->rw_owner = curthread;
273 rw_tryupgrade(krwlock_t *rwlp)
275 ASSERT(rwlp->initialized == B_TRUE);
276 ASSERT(rwlp->rw_owner != (void *)-1UL);
282 rw_lock_held(krwlock_t *rwlp)
285 return (rwlp->rw_count != 0);
289 * =========================================================================
290 * condition variables
291 * =========================================================================
295 cv_init(kcondvar_t *cv, char *name, int type, void *arg)
297 VERIFY(cond_init(cv, name, NULL) == 0);
301 cv_destroy(kcondvar_t *cv)
303 VERIFY(cond_destroy(cv) == 0);
307 cv_wait(kcondvar_t *cv, kmutex_t *mp)
309 ASSERT(mutex_owner(mp) == curthread);
311 int ret = cond_wait(cv, &mp->m_lock);
312 VERIFY(ret == 0 || ret == EINTR);
313 mp->m_owner = curthread;
317 cv_timedwait(kcondvar_t *cv, kmutex_t *mp, clock_t abstime)
324 abstime += ddi_get_lbolt();
326 delta = abstime - ddi_get_lbolt();
330 if (gettimeofday(&tv, NULL) != 0)
331 assert(!"gettimeofday() failed");
333 ts.tv_sec = tv.tv_sec + delta / hz;
334 ts.tv_nsec = tv.tv_usec * 1000 + (delta % hz) * (NANOSEC / hz);
335 ASSERT(ts.tv_nsec >= 0);
337 if (ts.tv_nsec >= NANOSEC) {
339 ts.tv_nsec -= NANOSEC;
342 ASSERT(mutex_owner(mp) == curthread);
344 error = pthread_cond_timedwait(cv, &mp->m_lock, &ts);
345 mp->m_owner = curthread;
350 if (error == ETIMEDOUT)
360 cv_timedwait_hires(kcondvar_t *cv, kmutex_t *mp, hrtime_t tim, hrtime_t res,
370 delta = tim - gethrtime();
374 ts.tv_sec = delta / NANOSEC;
375 ts.tv_nsec = delta % NANOSEC;
377 ASSERT(mutex_owner(mp) == curthread);
379 error = pthread_cond_timedwait(cv, &mp->m_lock, &ts);
380 mp->m_owner = curthread;
382 if (error == ETIMEDOUT)
394 cv_signal(kcondvar_t *cv)
396 VERIFY(cond_signal(cv) == 0);
400 cv_broadcast(kcondvar_t *cv)
402 VERIFY(cond_broadcast(cv) == 0);
406 * =========================================================================
408 * =========================================================================
411 * Note: for the xxxat() versions of these functions, we assume that the
412 * starting vp is always rootdir (which is true for spa_directory.c, the only
413 * ZFS consumer of these interfaces). We assert this is true, and then emulate
414 * them by adding '/' in front of the path.
419 vn_open(char *path, int x1, int flags, int mode, vnode_t **vpp, int x2, int x3)
425 char realpath[MAXPATHLEN];
429 * If we're accessing a real disk from userland, we need to use
430 * the character interface to avoid caching. This is particularly
431 * important if we're trying to look at a real in-kernel storage
432 * pool from userland, e.g. via zdb, because otherwise we won't
433 * see the changes occurring under the segmap cache.
434 * On the other hand, the stupid character device returns zero
435 * for its size. So -- gag -- we open the block device to get
436 * its size, and remember it for subsequent VOP_GETATTR().
438 if (strncmp(path, "/dev/", 5) == 0) {
440 fd = open64(path, O_RDONLY);
443 if (fstat64(fd, &st) == -1) {
448 (void) sprintf(realpath, "%s", path);
449 dsk = strstr(path, "/dsk/");
451 (void) sprintf(realpath + (dsk - path) + 1, "r%s",
454 (void) sprintf(realpath, "%s", path);
455 if (!(flags & FCREAT) && stat64(realpath, &st) == -1)
460 old_umask = umask(0);
463 * The construct 'flags - FREAD' conveniently maps combinations of
464 * FREAD and FWRITE to the corresponding O_RDONLY, O_WRONLY, and O_RDWR.
466 fd = open64(realpath, flags - FREAD, mode);
469 (void) umask(old_umask);
471 if (vn_dumpdir != NULL) {
472 char dumppath[MAXPATHLEN];
473 (void) snprintf(dumppath, sizeof (dumppath),
474 "%s/%s", vn_dumpdir, basename(realpath));
475 dump_fd = open64(dumppath, O_CREAT | O_WRONLY, 0666);
485 if (fstat64(fd, &st) == -1) {
490 (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
492 *vpp = vp = umem_zalloc(sizeof (vnode_t), UMEM_NOFAIL);
495 vp->v_size = st.st_size;
496 vp->v_path = spa_strdup(path);
497 vp->v_dump_fd = dump_fd;
504 vn_openat(char *path, int x1, int flags, int mode, vnode_t **vpp, int x2,
505 int x3, vnode_t *startvp, int fd)
507 char *realpath = umem_alloc(strlen(path) + 2, UMEM_NOFAIL);
510 ASSERT(startvp == rootdir);
511 (void) sprintf(realpath, "/%s", path);
513 /* fd ignored for now, need if want to simulate nbmand support */
514 ret = vn_open(realpath, x1, flags, mode, vpp, x2, x3);
516 umem_free(realpath, strlen(path) + 2);
523 vn_rdwr(int uio, vnode_t *vp, void *addr, ssize_t len, offset_t offset,
524 int x1, int x2, rlim64_t x3, void *x4, ssize_t *residp)
526 ssize_t iolen, split;
528 if (uio == UIO_READ) {
529 iolen = pread64(vp->v_fd, addr, len, offset);
530 if (vp->v_dump_fd != -1) {
532 pwrite64(vp->v_dump_fd, addr, iolen, offset);
533 ASSERT(status != -1);
537 * To simulate partial disk writes, we split writes into two
538 * system calls so that the process can be killed in between.
540 int sectors = len >> SPA_MINBLOCKSHIFT;
541 split = (sectors > 0 ? rand() % sectors : 0) <<
543 iolen = pwrite64(vp->v_fd, addr, split, offset);
544 iolen += pwrite64(vp->v_fd, (char *)addr + split,
545 len - split, offset + split);
551 *residp = len - iolen;
552 else if (iolen != len)
558 vn_close(vnode_t *vp, int openflag, cred_t *cr, kthread_t *td)
561 if (vp->v_dump_fd != -1)
562 close(vp->v_dump_fd);
563 spa_strfree(vp->v_path);
564 umem_free(vp, sizeof (vnode_t));
568 * At a minimum we need to update the size since vdev_reopen()
569 * will no longer call vn_openat().
572 fop_getattr(vnode_t *vp, vattr_t *vap)
576 if (fstat64(vp->v_fd, &st) == -1) {
581 vap->va_size = st.st_size;
588 * =========================================================================
589 * Figure out which debugging statements to print
590 * =========================================================================
593 static char *dprintf_string;
594 static int dprintf_print_all;
597 dprintf_find_string(const char *string)
599 char *tmp_str = dprintf_string;
600 int len = strlen(string);
603 * Find out if this is a string we want to print.
604 * String format: file1.c,function_name1,file2.c,file3.c
607 while (tmp_str != NULL) {
608 if (strncmp(tmp_str, string, len) == 0 &&
609 (tmp_str[len] == ',' || tmp_str[len] == '\0'))
611 tmp_str = strchr(tmp_str, ',');
613 tmp_str++; /* Get rid of , */
619 dprintf_setup(int *argc, char **argv)
624 * Debugging can be specified two ways: by setting the
625 * environment variable ZFS_DEBUG, or by including a
626 * "debug=..." argument on the command line. The command
627 * line setting overrides the environment variable.
630 for (i = 1; i < *argc; i++) {
631 int len = strlen("debug=");
632 /* First look for a command line argument */
633 if (strncmp("debug=", argv[i], len) == 0) {
634 dprintf_string = argv[i] + len;
635 /* Remove from args */
636 for (j = i; j < *argc; j++)
643 if (dprintf_string == NULL) {
644 /* Look for ZFS_DEBUG environment variable */
645 dprintf_string = getenv("ZFS_DEBUG");
649 * Are we just turning on all debugging?
651 if (dprintf_find_string("on"))
652 dprintf_print_all = 1;
656 sysctl_handle_64(SYSCTL_HANDLER_ARGS)
662 * =========================================================================
664 * =========================================================================
667 __dprintf(const char *file, const char *func, int line, const char *fmt, ...)
673 * Get rid of annoying "../common/" prefix to filename.
675 newfile = strrchr(file, '/');
676 if (newfile != NULL) {
677 newfile = newfile + 1; /* Get rid of leading / */
682 if (dprintf_print_all ||
683 dprintf_find_string(newfile) ||
684 dprintf_find_string(func)) {
685 /* Print out just the function name if requested */
687 if (dprintf_find_string("pid"))
688 (void) printf("%d ", getpid());
689 if (dprintf_find_string("tid"))
690 (void) printf("%ul ", thr_self());
692 if (dprintf_find_string("cpu"))
693 (void) printf("%u ", getcpuid());
695 if (dprintf_find_string("time"))
696 (void) printf("%llu ", gethrtime());
697 if (dprintf_find_string("long"))
698 (void) printf("%s, line %d: ", newfile, line);
699 (void) printf("%s: ", func);
701 (void) vprintf(fmt, adx);
707 #endif /* ZFS_DEBUG */
710 * =========================================================================
711 * cmn_err() and panic()
712 * =========================================================================
714 static char ce_prefix[CE_IGNORE][10] = { "", "NOTICE: ", "WARNING: ", "" };
715 static char ce_suffix[CE_IGNORE][2] = { "", "\n", "\n", "" };
718 vpanic(const char *fmt, va_list adx)
720 (void) fprintf(stderr, "error: ");
721 (void) vfprintf(stderr, fmt, adx);
722 (void) fprintf(stderr, "\n");
724 abort(); /* think of it as a "user-level crash dump" */
728 panic(const char *fmt, ...)
738 vcmn_err(int ce, const char *fmt, va_list adx)
742 if (ce != CE_NOTE) { /* suppress noise in userland stress testing */
743 (void) fprintf(stderr, "%s", ce_prefix[ce]);
744 (void) vfprintf(stderr, fmt, adx);
745 (void) fprintf(stderr, "%s", ce_suffix[ce]);
751 cmn_err(int ce, const char *fmt, ...)
756 vcmn_err(ce, fmt, adx);
761 * =========================================================================
763 * =========================================================================
766 kobj_open_file(char *name)
771 /* set vp as the _fd field of the file */
772 if (vn_openat(name, UIO_SYSSPACE, FREAD, 0, &vp, 0, 0, rootdir,
774 return ((void *)-1UL);
776 file = umem_zalloc(sizeof (struct _buf), UMEM_NOFAIL);
777 file->_fd = (intptr_t)vp;
782 kobj_read_file(struct _buf *file, char *buf, unsigned size, unsigned off)
786 vn_rdwr(UIO_READ, (vnode_t *)file->_fd, buf, size, (offset_t)off,
787 UIO_SYSSPACE, 0, 0, 0, &resid);
789 return (size - resid);
793 kobj_close_file(struct _buf *file)
795 vn_close((vnode_t *)file->_fd, 0, NULL, NULL);
796 umem_free(file, sizeof (struct _buf));
800 kobj_get_filesize(struct _buf *file, uint64_t *size)
803 vnode_t *vp = (vnode_t *)file->_fd;
805 if (fstat64(vp->v_fd, &st) == -1) {
806 vn_close(vp, 0, NULL, NULL);
814 * =========================================================================
816 * =========================================================================
822 poll(0, 0, ticks * (1000 / hz));
827 * Find highest one bit set.
828 * Returns bit number + 1 of highest bit that is set, otherwise returns 0.
831 highbit64(uint64_t i)
837 if (i & 0xffffffff00000000ULL) {
840 if (i & 0xffff0000) {
859 static int random_fd = -1, urandom_fd = -1;
862 random_get_bytes_common(uint8_t *ptr, size_t len, int fd)
870 bytes = read(fd, ptr, resid);
871 ASSERT3S(bytes, >=, 0);
880 random_get_bytes(uint8_t *ptr, size_t len)
882 return (random_get_bytes_common(ptr, len, random_fd));
886 random_get_pseudo_bytes(uint8_t *ptr, size_t len)
888 return (random_get_bytes_common(ptr, len, urandom_fd));
892 ddi_strtoul(const char *hw_serial, char **nptr, int base, unsigned long *result)
896 *result = strtoul(hw_serial, &end, base);
903 ddi_strtoull(const char *str, char **nptr, int base, u_longlong_t *result)
907 *result = strtoull(str, &end, base);
916 cyclic_add(cyc_handler_t *hdlr, cyc_time_t *when)
923 cyclic_remove(cyclic_id_t id)
929 cyclic_reprogram(cyclic_id_t id, hrtime_t expiration)
936 * =========================================================================
937 * kernel emulation setup & teardown
938 * =========================================================================
941 umem_out_of_memory(void)
943 char errmsg[] = "out of memory -- generating core dump\n";
945 write(fileno(stderr), errmsg, sizeof (errmsg));
951 kernel_init(int mode)
953 extern uint_t rrw_tsd_key;
955 umem_nofail_callback(umem_out_of_memory);
957 physmem = sysconf(_SC_PHYS_PAGES);
959 dprintf("physmem = %llu pages (%.2f GB)\n", physmem,
960 (double)physmem * sysconf(_SC_PAGE_SIZE) / (1ULL << 30));
962 (void) snprintf(hw_serial, sizeof (hw_serial), "%lu",
963 (mode & FWRITE) ? (unsigned long)gethostid() : 0);
965 VERIFY((random_fd = open("/dev/random", O_RDONLY)) != -1);
966 VERIFY((urandom_fd = open("/dev/urandom", O_RDONLY)) != -1);
971 mutex_init(&cpu_lock, NULL, MUTEX_DEFAULT, NULL);
976 tsd_create(&rrw_tsd_key, rrw_tsd_destroy);
994 z_uncompress(void *dst, size_t *dstlen, const void *src, size_t srclen)
997 uLongf len = *dstlen;
999 if ((ret = uncompress(dst, &len, src, srclen)) == Z_OK)
1000 *dstlen = (size_t)len;
1006 z_compress_level(void *dst, size_t *dstlen, const void *src, size_t srclen,
1010 uLongf len = *dstlen;
1012 if ((ret = compress2(dst, &len, src, srclen, level)) == Z_OK)
1013 *dstlen = (size_t)len;
1019 crgetuid(cred_t *cr)
1025 crgetruid(cred_t *cr)
1031 crgetgid(cred_t *cr)
1037 crgetngroups(cred_t *cr)
1043 crgetgroups(cred_t *cr)
1049 zfs_secpolicy_snapshot_perms(const char *name, cred_t *cr)
1055 zfs_secpolicy_rename_perms(const char *from, const char *to, cred_t *cr)
1061 zfs_secpolicy_destroy_perms(const char *name, cred_t *cr)
1067 ksid_lookupdomain(const char *dom)
1071 kd = umem_zalloc(sizeof (ksiddomain_t), UMEM_NOFAIL);
1072 kd->kd_name = spa_strdup(dom);
1077 ksiddomain_rele(ksiddomain_t *ksid)
1079 spa_strfree(ksid->kd_name);
1080 umem_free(ksid, sizeof (ksiddomain_t));
1084 * Do not change the length of the returned string; it must be freed
1088 kmem_asprintf(const char *fmt, ...)
1095 size = vsnprintf(NULL, 0, fmt, adx) + 1;
1098 buf = kmem_alloc(size, KM_SLEEP);
1101 size = vsnprintf(buf, size, fmt, adx);
1109 zfs_onexit_fd_hold(int fd, minor_t *minorp)
1117 zfs_onexit_fd_rele(int fd)
1123 zfs_onexit_add_cb(minor_t minor, void (*func)(void *), void *data,
1124 uint64_t *action_handle)
1131 zfs_onexit_del_cb(minor_t minor, uint64_t action_handle, boolean_t fire)
1138 zfs_onexit_cb_data(minor_t minor, uint64_t action_handle, void **data)
1146 zvol_create_minors(const char *name)
1156 bzero(bp, sizeof (buf_t));
1162 if (bp->b_iodone != NULL) {
1163 (*(bp->b_iodone))(bp);
1166 ASSERT((bp->b_flags & B_DONE) == 0);
1167 bp->b_flags |= B_DONE;
1171 bioerror(buf_t *bp, int error)
1177 bp->b_flags |= B_ERROR;
1179 bp->b_flags &= ~B_ERROR;
1181 bp->b_error = error;
1186 geterror(struct buf *bp)
1190 if (bp->b_flags & B_ERROR) {
1191 error = bp->b_error;