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,
372 delta = tim - gethrtime();
376 ts.tv_sec = delta / NANOSEC;
377 ts.tv_nsec = delta % NANOSEC;
379 ASSERT(mutex_owner(mp) == curthread);
381 error = pthread_cond_timedwait(cv, &mp->m_lock, &ts);
382 mp->m_owner = curthread;
384 if (error == ETIMEDOUT)
396 cv_signal(kcondvar_t *cv)
398 VERIFY(cond_signal(cv) == 0);
402 cv_broadcast(kcondvar_t *cv)
404 VERIFY(cond_broadcast(cv) == 0);
408 * =========================================================================
410 * =========================================================================
413 * Note: for the xxxat() versions of these functions, we assume that the
414 * starting vp is always rootdir (which is true for spa_directory.c, the only
415 * ZFS consumer of these interfaces). We assert this is true, and then emulate
416 * them by adding '/' in front of the path.
421 vn_open(char *path, int x1, int flags, int mode, vnode_t **vpp, int x2, int x3)
427 char realpath[MAXPATHLEN];
431 * If we're accessing a real disk from userland, we need to use
432 * the character interface to avoid caching. This is particularly
433 * important if we're trying to look at a real in-kernel storage
434 * pool from userland, e.g. via zdb, because otherwise we won't
435 * see the changes occurring under the segmap cache.
436 * On the other hand, the stupid character device returns zero
437 * for its size. So -- gag -- we open the block device to get
438 * its size, and remember it for subsequent VOP_GETATTR().
440 if (strncmp(path, "/dev/", 5) == 0) {
442 fd = open64(path, O_RDONLY);
445 if (fstat64(fd, &st) == -1) {
450 (void) sprintf(realpath, "%s", path);
451 dsk = strstr(path, "/dsk/");
453 (void) sprintf(realpath + (dsk - path) + 1, "r%s",
456 (void) sprintf(realpath, "%s", path);
457 if (!(flags & FCREAT) && stat64(realpath, &st) == -1)
462 old_umask = umask(0);
465 * The construct 'flags - FREAD' conveniently maps combinations of
466 * FREAD and FWRITE to the corresponding O_RDONLY, O_WRONLY, and O_RDWR.
468 fd = open64(realpath, flags - FREAD, mode);
471 (void) umask(old_umask);
473 if (vn_dumpdir != NULL) {
474 char dumppath[MAXPATHLEN];
475 (void) snprintf(dumppath, sizeof (dumppath),
476 "%s/%s", vn_dumpdir, basename(realpath));
477 dump_fd = open64(dumppath, O_CREAT | O_WRONLY, 0666);
487 if (fstat64(fd, &st) == -1) {
492 (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
494 *vpp = vp = umem_zalloc(sizeof (vnode_t), UMEM_NOFAIL);
497 vp->v_size = st.st_size;
498 vp->v_path = spa_strdup(path);
499 vp->v_dump_fd = dump_fd;
506 vn_openat(char *path, int x1, int flags, int mode, vnode_t **vpp, int x2,
507 int x3, vnode_t *startvp, int fd)
509 char *realpath = umem_alloc(strlen(path) + 2, UMEM_NOFAIL);
512 ASSERT(startvp == rootdir);
513 (void) sprintf(realpath, "/%s", path);
515 /* fd ignored for now, need if want to simulate nbmand support */
516 ret = vn_open(realpath, x1, flags, mode, vpp, x2, x3);
518 umem_free(realpath, strlen(path) + 2);
525 vn_rdwr(int uio, vnode_t *vp, void *addr, ssize_t len, offset_t offset,
526 int x1, int x2, rlim64_t x3, void *x4, ssize_t *residp)
528 ssize_t iolen, split;
530 if (uio == UIO_READ) {
531 iolen = pread64(vp->v_fd, addr, len, offset);
532 if (vp->v_dump_fd != -1) {
534 pwrite64(vp->v_dump_fd, addr, iolen, offset);
535 ASSERT(status != -1);
539 * To simulate partial disk writes, we split writes into two
540 * system calls so that the process can be killed in between.
542 int sectors = len >> SPA_MINBLOCKSHIFT;
543 split = (sectors > 0 ? rand() % sectors : 0) <<
545 iolen = pwrite64(vp->v_fd, addr, split, offset);
546 iolen += pwrite64(vp->v_fd, (char *)addr + split,
547 len - split, offset + split);
553 *residp = len - iolen;
554 else if (iolen != len)
560 vn_close(vnode_t *vp, int openflag, cred_t *cr, kthread_t *td)
563 if (vp->v_dump_fd != -1)
564 close(vp->v_dump_fd);
565 spa_strfree(vp->v_path);
566 umem_free(vp, sizeof (vnode_t));
570 * At a minimum we need to update the size since vdev_reopen()
571 * will no longer call vn_openat().
574 fop_getattr(vnode_t *vp, vattr_t *vap)
578 if (fstat64(vp->v_fd, &st) == -1) {
583 vap->va_size = st.st_size;
590 * =========================================================================
591 * Figure out which debugging statements to print
592 * =========================================================================
595 static char *dprintf_string;
596 static int dprintf_print_all;
599 dprintf_find_string(const char *string)
601 char *tmp_str = dprintf_string;
602 int len = strlen(string);
605 * Find out if this is a string we want to print.
606 * String format: file1.c,function_name1,file2.c,file3.c
609 while (tmp_str != NULL) {
610 if (strncmp(tmp_str, string, len) == 0 &&
611 (tmp_str[len] == ',' || tmp_str[len] == '\0'))
613 tmp_str = strchr(tmp_str, ',');
615 tmp_str++; /* Get rid of , */
621 dprintf_setup(int *argc, char **argv)
626 * Debugging can be specified two ways: by setting the
627 * environment variable ZFS_DEBUG, or by including a
628 * "debug=..." argument on the command line. The command
629 * line setting overrides the environment variable.
632 for (i = 1; i < *argc; i++) {
633 int len = strlen("debug=");
634 /* First look for a command line argument */
635 if (strncmp("debug=", argv[i], len) == 0) {
636 dprintf_string = argv[i] + len;
637 /* Remove from args */
638 for (j = i; j < *argc; j++)
645 if (dprintf_string == NULL) {
646 /* Look for ZFS_DEBUG environment variable */
647 dprintf_string = getenv("ZFS_DEBUG");
651 * Are we just turning on all debugging?
653 if (dprintf_find_string("on"))
654 dprintf_print_all = 1;
658 sysctl_handle_64(SYSCTL_HANDLER_ARGS)
664 * =========================================================================
666 * =========================================================================
669 __dprintf(const char *file, const char *func, int line, const char *fmt, ...)
675 * Get rid of annoying "../common/" prefix to filename.
677 newfile = strrchr(file, '/');
678 if (newfile != NULL) {
679 newfile = newfile + 1; /* Get rid of leading / */
684 if (dprintf_print_all ||
685 dprintf_find_string(newfile) ||
686 dprintf_find_string(func)) {
687 /* Print out just the function name if requested */
689 if (dprintf_find_string("pid"))
690 (void) printf("%d ", getpid());
691 if (dprintf_find_string("tid"))
692 (void) printf("%ul ", thr_self());
694 if (dprintf_find_string("cpu"))
695 (void) printf("%u ", getcpuid());
697 if (dprintf_find_string("time"))
698 (void) printf("%llu ", gethrtime());
699 if (dprintf_find_string("long"))
700 (void) printf("%s, line %d: ", newfile, line);
701 (void) printf("%s: ", func);
703 (void) vprintf(fmt, adx);
709 #endif /* ZFS_DEBUG */
712 * =========================================================================
713 * cmn_err() and panic()
714 * =========================================================================
716 static char ce_prefix[CE_IGNORE][10] = { "", "NOTICE: ", "WARNING: ", "" };
717 static char ce_suffix[CE_IGNORE][2] = { "", "\n", "\n", "" };
720 vpanic(const char *fmt, va_list adx)
722 (void) fprintf(stderr, "error: ");
723 (void) vfprintf(stderr, fmt, adx);
724 (void) fprintf(stderr, "\n");
726 abort(); /* think of it as a "user-level crash dump" */
730 panic(const char *fmt, ...)
740 vcmn_err(int ce, const char *fmt, va_list adx)
744 if (ce != CE_NOTE) { /* suppress noise in userland stress testing */
745 (void) fprintf(stderr, "%s", ce_prefix[ce]);
746 (void) vfprintf(stderr, fmt, adx);
747 (void) fprintf(stderr, "%s", ce_suffix[ce]);
753 cmn_err(int ce, const char *fmt, ...)
758 vcmn_err(ce, fmt, adx);
763 * =========================================================================
765 * =========================================================================
768 kobj_open_file(char *name)
773 /* set vp as the _fd field of the file */
774 if (vn_openat(name, UIO_SYSSPACE, FREAD, 0, &vp, 0, 0, rootdir,
776 return ((void *)-1UL);
778 file = umem_zalloc(sizeof (struct _buf), UMEM_NOFAIL);
779 file->_fd = (intptr_t)vp;
784 kobj_read_file(struct _buf *file, char *buf, unsigned size, unsigned off)
788 vn_rdwr(UIO_READ, (vnode_t *)file->_fd, buf, size, (offset_t)off,
789 UIO_SYSSPACE, 0, 0, 0, &resid);
791 return (size - resid);
795 kobj_close_file(struct _buf *file)
797 vn_close((vnode_t *)file->_fd, 0, NULL, NULL);
798 umem_free(file, sizeof (struct _buf));
802 kobj_get_filesize(struct _buf *file, uint64_t *size)
805 vnode_t *vp = (vnode_t *)file->_fd;
807 if (fstat64(vp->v_fd, &st) == -1) {
808 vn_close(vp, 0, NULL, NULL);
816 * =========================================================================
818 * =========================================================================
824 poll(0, 0, ticks * (1000 / hz));
829 * Find highest one bit set.
830 * Returns bit number + 1 of highest bit that is set, otherwise returns 0.
833 highbit64(uint64_t i)
839 if (i & 0xffffffff00000000ULL) {
842 if (i & 0xffff0000) {
861 static int random_fd = -1, urandom_fd = -1;
864 random_get_bytes_common(uint8_t *ptr, size_t len, int fd)
872 bytes = read(fd, ptr, resid);
873 ASSERT3S(bytes, >=, 0);
882 random_get_bytes(uint8_t *ptr, size_t len)
884 return (random_get_bytes_common(ptr, len, random_fd));
888 random_get_pseudo_bytes(uint8_t *ptr, size_t len)
890 return (random_get_bytes_common(ptr, len, urandom_fd));
894 ddi_strtoul(const char *hw_serial, char **nptr, int base, unsigned long *result)
898 *result = strtoul(hw_serial, &end, base);
905 ddi_strtoull(const char *str, char **nptr, int base, u_longlong_t *result)
909 *result = strtoull(str, &end, base);
918 cyclic_add(cyc_handler_t *hdlr, cyc_time_t *when)
925 cyclic_remove(cyclic_id_t id)
931 cyclic_reprogram(cyclic_id_t id, hrtime_t expiration)
938 * =========================================================================
939 * kernel emulation setup & teardown
940 * =========================================================================
943 umem_out_of_memory(void)
945 char errmsg[] = "out of memory -- generating core dump\n";
947 write(fileno(stderr), errmsg, sizeof (errmsg));
953 kernel_init(int mode)
955 extern uint_t rrw_tsd_key;
957 umem_nofail_callback(umem_out_of_memory);
959 physmem = sysconf(_SC_PHYS_PAGES);
961 dprintf("physmem = %llu pages (%.2f GB)\n", physmem,
962 (double)physmem * sysconf(_SC_PAGE_SIZE) / (1ULL << 30));
964 (void) snprintf(hw_serial, sizeof (hw_serial), "%lu",
965 (mode & FWRITE) ? (unsigned long)gethostid() : 0);
967 VERIFY((random_fd = open("/dev/random", O_RDONLY)) != -1);
968 VERIFY((urandom_fd = open("/dev/urandom", O_RDONLY)) != -1);
973 mutex_init(&cpu_lock, NULL, MUTEX_DEFAULT, NULL);
978 tsd_create(&rrw_tsd_key, rrw_tsd_destroy);
996 z_uncompress(void *dst, size_t *dstlen, const void *src, size_t srclen)
999 uLongf len = *dstlen;
1001 if ((ret = uncompress(dst, &len, src, srclen)) == Z_OK)
1002 *dstlen = (size_t)len;
1008 z_compress_level(void *dst, size_t *dstlen, const void *src, size_t srclen,
1012 uLongf len = *dstlen;
1014 if ((ret = compress2(dst, &len, src, srclen, level)) == Z_OK)
1015 *dstlen = (size_t)len;
1021 crgetuid(cred_t *cr)
1027 crgetruid(cred_t *cr)
1033 crgetgid(cred_t *cr)
1039 crgetngroups(cred_t *cr)
1045 crgetgroups(cred_t *cr)
1051 zfs_secpolicy_snapshot_perms(const char *name, cred_t *cr)
1057 zfs_secpolicy_rename_perms(const char *from, const char *to, cred_t *cr)
1063 zfs_secpolicy_destroy_perms(const char *name, cred_t *cr)
1069 ksid_lookupdomain(const char *dom)
1073 kd = umem_zalloc(sizeof (ksiddomain_t), UMEM_NOFAIL);
1074 kd->kd_name = spa_strdup(dom);
1079 ksiddomain_rele(ksiddomain_t *ksid)
1081 spa_strfree(ksid->kd_name);
1082 umem_free(ksid, sizeof (ksiddomain_t));
1086 * Do not change the length of the returned string; it must be freed
1090 kmem_asprintf(const char *fmt, ...)
1097 size = vsnprintf(NULL, 0, fmt, adx) + 1;
1100 buf = kmem_alloc(size, KM_SLEEP);
1103 size = vsnprintf(buf, size, fmt, adx);
1111 zfs_onexit_fd_hold(int fd, minor_t *minorp)
1119 zfs_onexit_fd_rele(int fd)
1125 zfs_onexit_add_cb(minor_t minor, void (*func)(void *), void *data,
1126 uint64_t *action_handle)
1133 zfs_onexit_del_cb(minor_t minor, uint64_t action_handle, boolean_t fire)
1140 zfs_onexit_cb_data(minor_t minor, uint64_t action_handle, void **data)
1148 zvol_create_minors(const char *name)
1158 bzero(bp, sizeof (buf_t));
1164 if (bp->b_iodone != NULL) {
1165 (*(bp->b_iodone))(bp);
1168 ASSERT((bp->b_flags & B_DONE) == 0);
1169 bp->b_flags |= B_DONE;
1173 bioerror(buf_t *bp, int error)
1179 bp->b_flags |= B_ERROR;
1181 bp->b_flags &= ~B_ERROR;
1183 bp->b_error = error;
1188 geterror(struct buf *bp)
1192 if (bp->b_flags & B_ERROR) {
1193 error = bp->b_error;