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.
34 #include <sys/processor.h>
35 #include <sys/zfs_context.h>
37 #include <sys/utsname.h>
38 #include <sys/systeminfo.h>
41 * Emulation of kernel services in userland.
46 vnode_t *rootdir = (vnode_t *)0xabcd1234;
47 char hw_serial[HW_HOSTID_LEN];
49 struct utsname utsname = {
50 "userland", "libzpool", "1", "1", "na"
53 /* this only exists to have its address taken */
57 * =========================================================================
59 * =========================================================================
63 zk_thread_create(void (*func)(), void *arg)
67 VERIFY(thr_create(0, 0, (void *(*)(void *))func, arg, THR_DETACHED,
70 return ((void *)(uintptr_t)tid);
74 * =========================================================================
76 * =========================================================================
80 kstat_create(char *module, int instance, char *name, char *class,
81 uchar_t type, ulong_t ndata, uchar_t ks_flag)
88 kstat_install(kstat_t *ksp)
93 kstat_delete(kstat_t *ksp)
97 * =========================================================================
99 * =========================================================================
102 zmutex_init(kmutex_t *mp)
105 mp->initialized = B_TRUE;
106 (void) _mutex_init(&mp->m_lock, USYNC_THREAD, NULL);
110 zmutex_destroy(kmutex_t *mp)
112 ASSERT(mp->initialized == B_TRUE);
113 ASSERT(mp->m_owner == NULL);
114 (void) _mutex_destroy(&(mp)->m_lock);
115 mp->m_owner = (void *)-1UL;
116 mp->initialized = B_FALSE;
120 zmutex_owned(kmutex_t *mp)
122 ASSERT(mp->initialized == B_TRUE);
124 return (mp->m_owner == curthread);
128 mutex_enter(kmutex_t *mp)
130 ASSERT(mp->initialized == B_TRUE);
131 ASSERT(mp->m_owner != (void *)-1UL);
132 ASSERT(mp->m_owner != curthread);
133 VERIFY(mutex_lock(&mp->m_lock) == 0);
134 ASSERT(mp->m_owner == NULL);
135 mp->m_owner = curthread;
139 mutex_tryenter(kmutex_t *mp)
141 ASSERT(mp->initialized == B_TRUE);
142 ASSERT(mp->m_owner != (void *)-1UL);
143 if (0 == mutex_trylock(&mp->m_lock)) {
144 ASSERT(mp->m_owner == NULL);
145 mp->m_owner = curthread;
153 mutex_exit(kmutex_t *mp)
155 ASSERT(mp->initialized == B_TRUE);
156 ASSERT(mutex_owner(mp) == curthread);
158 VERIFY(mutex_unlock(&mp->m_lock) == 0);
162 mutex_owner(kmutex_t *mp)
164 ASSERT(mp->initialized == B_TRUE);
165 return (mp->m_owner);
169 * =========================================================================
171 * =========================================================================
175 rw_init(krwlock_t *rwlp, char *name, int type, void *arg)
177 rwlock_init(&rwlp->rw_lock, USYNC_THREAD, NULL);
178 rwlp->rw_owner = NULL;
179 rwlp->initialized = B_TRUE;
184 rw_destroy(krwlock_t *rwlp)
186 ASSERT(rwlp->rw_count == 0);
187 rwlock_destroy(&rwlp->rw_lock);
188 rwlp->rw_owner = (void *)-1UL;
189 rwlp->initialized = B_FALSE;
193 rw_enter(krwlock_t *rwlp, krw_t rw)
195 //ASSERT(!RW_LOCK_HELD(rwlp));
196 ASSERT(rwlp->initialized == B_TRUE);
197 ASSERT(rwlp->rw_owner != (void *)-1UL);
198 ASSERT(rwlp->rw_owner != curthread);
200 if (rw == RW_READER) {
201 VERIFY(rw_rdlock(&rwlp->rw_lock) == 0);
202 ASSERT(rwlp->rw_count >= 0);
203 atomic_add_int(&rwlp->rw_count, 1);
205 VERIFY(rw_wrlock(&rwlp->rw_lock) == 0);
206 ASSERT(rwlp->rw_count == 0);
208 rwlp->rw_owner = curthread;
213 rw_exit(krwlock_t *rwlp)
215 ASSERT(rwlp->initialized == B_TRUE);
216 ASSERT(rwlp->rw_owner != (void *)-1UL);
218 if (rwlp->rw_owner == curthread) {
220 ASSERT(rwlp->rw_count == -1);
222 rwlp->rw_owner = NULL;
225 ASSERT(rwlp->rw_count > 0);
226 atomic_add_int(&rwlp->rw_count, -1);
228 VERIFY(rw_unlock(&rwlp->rw_lock) == 0);
232 rw_tryenter(krwlock_t *rwlp, krw_t rw)
236 ASSERT(rwlp->initialized == B_TRUE);
237 ASSERT(rwlp->rw_owner != (void *)-1UL);
238 ASSERT(rwlp->rw_owner != curthread);
241 rv = rw_tryrdlock(&rwlp->rw_lock);
243 rv = rw_trywrlock(&rwlp->rw_lock);
246 ASSERT(rwlp->rw_owner == NULL);
247 if (rw == RW_READER) {
248 ASSERT(rwlp->rw_count >= 0);
249 atomic_add_int(&rwlp->rw_count, 1);
251 ASSERT(rwlp->rw_count == 0);
253 rwlp->rw_owner = curthread;
263 rw_tryupgrade(krwlock_t *rwlp)
265 ASSERT(rwlp->initialized == B_TRUE);
266 ASSERT(rwlp->rw_owner != (void *)-1UL);
272 rw_lock_held(krwlock_t *rwlp)
275 return (rwlp->rw_count != 0);
279 * =========================================================================
280 * condition variables
281 * =========================================================================
285 cv_init(kcondvar_t *cv, char *name, int type, void *arg)
287 VERIFY(cond_init(cv, name, NULL) == 0);
291 cv_destroy(kcondvar_t *cv)
293 VERIFY(cond_destroy(cv) == 0);
297 cv_wait(kcondvar_t *cv, kmutex_t *mp)
299 ASSERT(mutex_owner(mp) == curthread);
301 int ret = cond_wait(cv, &mp->m_lock);
302 VERIFY(ret == 0 || ret == EINTR);
303 mp->m_owner = curthread;
307 cv_timedwait(kcondvar_t *cv, kmutex_t *mp, clock_t abstime)
314 abstime += ddi_get_lbolt();
316 delta = abstime - ddi_get_lbolt();
320 if (gettimeofday(&tv, NULL) != 0)
321 assert(!"gettimeofday() failed");
323 ts.tv_sec = tv.tv_sec + delta / hz;
324 ts.tv_nsec = tv.tv_usec * 1000 + (delta % hz) * (NANOSEC / hz);
325 ASSERT(ts.tv_nsec >= 0);
327 if (ts.tv_nsec >= NANOSEC) {
329 ts.tv_nsec -= NANOSEC;
332 ASSERT(mutex_owner(mp) == curthread);
334 error = pthread_cond_timedwait(cv, &mp->m_lock, &ts);
335 mp->m_owner = curthread;
340 if (error == ETIMEDOUT)
349 cv_signal(kcondvar_t *cv)
351 VERIFY(cond_signal(cv) == 0);
355 cv_broadcast(kcondvar_t *cv)
357 VERIFY(cond_broadcast(cv) == 0);
361 * =========================================================================
363 * =========================================================================
366 * Note: for the xxxat() versions of these functions, we assume that the
367 * starting vp is always rootdir (which is true for spa_directory.c, the only
368 * ZFS consumer of these interfaces). We assert this is true, and then emulate
369 * them by adding '/' in front of the path.
374 vn_open(char *path, int x1, int flags, int mode, vnode_t **vpp, int x2, int x3)
379 char realpath[MAXPATHLEN];
383 * If we're accessing a real disk from userland, we need to use
384 * the character interface to avoid caching. This is particularly
385 * important if we're trying to look at a real in-kernel storage
386 * pool from userland, e.g. via zdb, because otherwise we won't
387 * see the changes occurring under the segmap cache.
388 * On the other hand, the stupid character device returns zero
389 * for its size. So -- gag -- we open the block device to get
390 * its size, and remember it for subsequent VOP_GETATTR().
392 if (strncmp(path, "/dev/", 5) == 0) {
394 fd = open64(path, O_RDONLY);
397 if (fstat64(fd, &st) == -1) {
402 (void) sprintf(realpath, "%s", path);
403 dsk = strstr(path, "/dsk/");
405 (void) sprintf(realpath + (dsk - path) + 1, "r%s",
408 (void) sprintf(realpath, "%s", path);
409 if (!(flags & FCREAT) && stat64(realpath, &st) == -1)
414 old_umask = umask(0);
417 * The construct 'flags - FREAD' conveniently maps combinations of
418 * FREAD and FWRITE to the corresponding O_RDONLY, O_WRONLY, and O_RDWR.
420 fd = open64(realpath, flags - FREAD, mode);
423 (void) umask(old_umask);
428 if (fstat64(fd, &st) == -1) {
433 (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
435 *vpp = vp = umem_zalloc(sizeof (vnode_t), UMEM_NOFAIL);
438 vp->v_size = st.st_size;
439 vp->v_path = spa_strdup(path);
446 vn_openat(char *path, int x1, int flags, int mode, vnode_t **vpp, int x2,
447 int x3, vnode_t *startvp, int fd)
449 char *realpath = umem_alloc(strlen(path) + 2, UMEM_NOFAIL);
452 ASSERT(startvp == rootdir);
453 (void) sprintf(realpath, "/%s", path);
455 /* fd ignored for now, need if want to simulate nbmand support */
456 ret = vn_open(realpath, x1, flags, mode, vpp, x2, x3);
458 umem_free(realpath, strlen(path) + 2);
465 vn_rdwr(int uio, vnode_t *vp, void *addr, ssize_t len, offset_t offset,
466 int x1, int x2, rlim64_t x3, void *x4, ssize_t *residp)
468 ssize_t iolen, split;
470 if (uio == UIO_READ) {
471 iolen = pread64(vp->v_fd, addr, len, offset);
474 * To simulate partial disk writes, we split writes into two
475 * system calls so that the process can be killed in between.
477 split = (len > 0 ? rand() % len : 0);
478 iolen = pwrite64(vp->v_fd, addr, split, offset);
479 iolen += pwrite64(vp->v_fd, (char *)addr + split,
480 len - split, offset + split);
486 *residp = len - iolen;
487 else if (iolen != len)
493 vn_close(vnode_t *vp, int openflag, cred_t *cr, kthread_t *td)
496 spa_strfree(vp->v_path);
497 umem_free(vp, sizeof (vnode_t));
501 * At a minimum we need to update the size since vdev_reopen()
502 * will no longer call vn_openat().
505 fop_getattr(vnode_t *vp, vattr_t *vap)
509 if (fstat64(vp->v_fd, &st) == -1) {
514 vap->va_size = st.st_size;
521 * =========================================================================
522 * Figure out which debugging statements to print
523 * =========================================================================
526 static char *dprintf_string;
527 static int dprintf_print_all;
530 dprintf_find_string(const char *string)
532 char *tmp_str = dprintf_string;
533 int len = strlen(string);
536 * Find out if this is a string we want to print.
537 * String format: file1.c,function_name1,file2.c,file3.c
540 while (tmp_str != NULL) {
541 if (strncmp(tmp_str, string, len) == 0 &&
542 (tmp_str[len] == ',' || tmp_str[len] == '\0'))
544 tmp_str = strchr(tmp_str, ',');
546 tmp_str++; /* Get rid of , */
552 dprintf_setup(int *argc, char **argv)
557 * Debugging can be specified two ways: by setting the
558 * environment variable ZFS_DEBUG, or by including a
559 * "debug=..." argument on the command line. The command
560 * line setting overrides the environment variable.
563 for (i = 1; i < *argc; i++) {
564 int len = strlen("debug=");
565 /* First look for a command line argument */
566 if (strncmp("debug=", argv[i], len) == 0) {
567 dprintf_string = argv[i] + len;
568 /* Remove from args */
569 for (j = i; j < *argc; j++)
576 if (dprintf_string == NULL) {
577 /* Look for ZFS_DEBUG environment variable */
578 dprintf_string = getenv("ZFS_DEBUG");
582 * Are we just turning on all debugging?
584 if (dprintf_find_string("on"))
585 dprintf_print_all = 1;
589 * =========================================================================
591 * =========================================================================
594 __dprintf(const char *file, const char *func, int line, const char *fmt, ...)
600 * Get rid of annoying "../common/" prefix to filename.
602 newfile = strrchr(file, '/');
603 if (newfile != NULL) {
604 newfile = newfile + 1; /* Get rid of leading / */
609 if (dprintf_print_all ||
610 dprintf_find_string(newfile) ||
611 dprintf_find_string(func)) {
612 /* Print out just the function name if requested */
614 if (dprintf_find_string("pid"))
615 (void) printf("%d ", getpid());
616 if (dprintf_find_string("tid"))
617 (void) printf("%u ", thr_self());
619 if (dprintf_find_string("cpu"))
620 (void) printf("%u ", getcpuid());
622 if (dprintf_find_string("time"))
623 (void) printf("%llu ", gethrtime());
624 if (dprintf_find_string("long"))
625 (void) printf("%s, line %d: ", newfile, line);
626 (void) printf("%s: ", func);
628 (void) vprintf(fmt, adx);
634 #endif /* ZFS_DEBUG */
637 * =========================================================================
638 * cmn_err() and panic()
639 * =========================================================================
641 static char ce_prefix[CE_IGNORE][10] = { "", "NOTICE: ", "WARNING: ", "" };
642 static char ce_suffix[CE_IGNORE][2] = { "", "\n", "\n", "" };
645 vpanic(const char *fmt, va_list adx)
647 (void) fprintf(stderr, "error: ");
648 (void) vfprintf(stderr, fmt, adx);
649 (void) fprintf(stderr, "\n");
651 abort(); /* think of it as a "user-level crash dump" */
655 panic(const char *fmt, ...)
665 vcmn_err(int ce, const char *fmt, va_list adx)
669 if (ce != CE_NOTE) { /* suppress noise in userland stress testing */
670 (void) fprintf(stderr, "%s", ce_prefix[ce]);
671 (void) vfprintf(stderr, fmt, adx);
672 (void) fprintf(stderr, "%s", ce_suffix[ce]);
678 cmn_err(int ce, const char *fmt, ...)
683 vcmn_err(ce, fmt, adx);
688 * =========================================================================
690 * =========================================================================
693 kobj_open_file(char *name)
698 /* set vp as the _fd field of the file */
699 if (vn_openat(name, UIO_SYSSPACE, FREAD, 0, &vp, 0, 0, rootdir,
701 return ((void *)-1UL);
703 file = umem_zalloc(sizeof (struct _buf), UMEM_NOFAIL);
704 file->_fd = (intptr_t)vp;
709 kobj_read_file(struct _buf *file, char *buf, unsigned size, unsigned off)
713 vn_rdwr(UIO_READ, (vnode_t *)file->_fd, buf, size, (offset_t)off,
714 UIO_SYSSPACE, 0, 0, 0, &resid);
716 return (size - resid);
720 kobj_close_file(struct _buf *file)
722 vn_close((vnode_t *)file->_fd, 0, NULL, NULL);
723 umem_free(file, sizeof (struct _buf));
727 kobj_get_filesize(struct _buf *file, uint64_t *size)
730 vnode_t *vp = (vnode_t *)file->_fd;
732 if (fstat64(vp->v_fd, &st) == -1) {
733 vn_close(vp, 0, NULL, NULL);
741 * =========================================================================
743 * =========================================================================
749 poll(0, 0, ticks * (1000 / hz));
754 * Find highest one bit set.
755 * Returns bit number + 1 of highest bit that is set, otherwise returns 0.
756 * High order bit is 31 (or 63 in _LP64 kernel).
766 if (i & 0xffffffff00000000ul) {
770 if (i & 0xffff0000) {
789 static int random_fd = -1, urandom_fd = -1;
792 random_get_bytes_common(uint8_t *ptr, size_t len, int fd)
800 bytes = read(fd, ptr, resid);
801 ASSERT3S(bytes, >=, 0);
810 random_get_bytes(uint8_t *ptr, size_t len)
812 return (random_get_bytes_common(ptr, len, random_fd));
816 random_get_pseudo_bytes(uint8_t *ptr, size_t len)
818 return (random_get_bytes_common(ptr, len, urandom_fd));
822 ddi_strtoul(const char *hw_serial, char **nptr, int base, unsigned long *result)
826 *result = strtoul(hw_serial, &end, base);
833 ddi_strtoull(const char *str, char **nptr, int base, u_longlong_t *result)
837 *result = strtoull(str, &end, base);
844 * =========================================================================
845 * kernel emulation setup & teardown
846 * =========================================================================
849 umem_out_of_memory(void)
851 char errmsg[] = "out of memory -- generating core dump\n";
853 write(fileno(stderr), errmsg, sizeof (errmsg));
859 kernel_init(int mode)
861 umem_nofail_callback(umem_out_of_memory);
863 physmem = sysconf(_SC_PHYS_PAGES);
865 dprintf("physmem = %llu pages (%.2f GB)\n", physmem,
866 (double)physmem * sysconf(_SC_PAGE_SIZE) / (1ULL << 30));
868 (void) snprintf(hw_serial, sizeof (hw_serial), "%lu",
869 (mode & FWRITE) ? (unsigned long)gethostid() : 0);
871 VERIFY((random_fd = open("/dev/random", O_RDONLY)) != -1);
872 VERIFY((urandom_fd = open("/dev/urandom", O_RDONLY)) != -1);
894 z_uncompress(void *dst, size_t *dstlen, const void *src, size_t srclen)
897 uLongf len = *dstlen;
899 if ((ret = uncompress(dst, &len, src, srclen)) == Z_OK)
900 *dstlen = (size_t)len;
906 z_compress_level(void *dst, size_t *dstlen, const void *src, size_t srclen,
910 uLongf len = *dstlen;
912 if ((ret = compress2(dst, &len, src, srclen, level)) == Z_OK)
913 *dstlen = (size_t)len;
931 crgetngroups(cred_t *cr)
937 crgetgroups(cred_t *cr)
943 zfs_secpolicy_snapshot_perms(const char *name, cred_t *cr)
949 zfs_secpolicy_rename_perms(const char *from, const char *to, cred_t *cr)
955 zfs_secpolicy_destroy_perms(const char *name, cred_t *cr)
961 ksid_lookupdomain(const char *dom)
965 kd = umem_zalloc(sizeof (ksiddomain_t), UMEM_NOFAIL);
966 kd->kd_name = spa_strdup(dom);
971 ksiddomain_rele(ksiddomain_t *ksid)
973 spa_strfree(ksid->kd_name);
974 umem_free(ksid, sizeof (ksiddomain_t));
978 * Do not change the length of the returned string; it must be freed
982 kmem_asprintf(const char *fmt, ...)
989 size = vsnprintf(NULL, 0, fmt, adx) + 1;
992 buf = kmem_alloc(size, KM_SLEEP);
995 size = vsnprintf(buf, size, fmt, adx);
1003 zfs_onexit_fd_hold(int fd, minor_t *minorp)
1011 zfs_onexit_fd_rele(int fd)
1017 zfs_onexit_add_cb(minor_t minor, void (*func)(void *), void *data,
1018 uint64_t *action_handle)
1025 zfs_onexit_del_cb(minor_t minor, uint64_t action_handle, boolean_t fire)
1032 zfs_onexit_cb_data(minor_t minor, uint64_t action_handle, void **data)
1040 zvol_create_minors(const char *name)