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 mutex_enter(kmutex_t *mp)
122 ASSERT(mp->initialized == B_TRUE);
123 ASSERT(mp->m_owner != (void *)-1UL);
124 ASSERT(mp->m_owner != curthread);
125 VERIFY(mutex_lock(&mp->m_lock) == 0);
126 ASSERT(mp->m_owner == NULL);
127 mp->m_owner = curthread;
131 mutex_tryenter(kmutex_t *mp)
133 ASSERT(mp->initialized == B_TRUE);
134 ASSERT(mp->m_owner != (void *)-1UL);
135 if (0 == mutex_trylock(&mp->m_lock)) {
136 ASSERT(mp->m_owner == NULL);
137 mp->m_owner = curthread;
145 mutex_exit(kmutex_t *mp)
147 ASSERT(mp->initialized == B_TRUE);
148 ASSERT(mutex_owner(mp) == curthread);
150 VERIFY(mutex_unlock(&mp->m_lock) == 0);
154 mutex_owner(kmutex_t *mp)
156 ASSERT(mp->initialized == B_TRUE);
157 return (mp->m_owner);
161 * =========================================================================
163 * =========================================================================
167 rw_init(krwlock_t *rwlp, char *name, int type, void *arg)
169 rwlock_init(&rwlp->rw_lock, USYNC_THREAD, NULL);
170 rwlp->rw_owner = NULL;
171 rwlp->initialized = B_TRUE;
175 rw_destroy(krwlock_t *rwlp)
177 rwlock_destroy(&rwlp->rw_lock);
178 rwlp->rw_owner = (void *)-1UL;
179 rwlp->initialized = B_FALSE;
183 rw_enter(krwlock_t *rwlp, krw_t rw)
185 ASSERT(!RW_LOCK_HELD(rwlp));
186 ASSERT(rwlp->initialized == B_TRUE);
187 ASSERT(rwlp->rw_owner != (void *)-1UL);
188 ASSERT(rwlp->rw_owner != curthread);
191 VERIFY(rw_rdlock(&rwlp->rw_lock) == 0);
193 VERIFY(rw_wrlock(&rwlp->rw_lock) == 0);
195 rwlp->rw_owner = curthread;
199 rw_exit(krwlock_t *rwlp)
201 ASSERT(rwlp->initialized == B_TRUE);
202 ASSERT(rwlp->rw_owner != (void *)-1UL);
204 rwlp->rw_owner = NULL;
205 VERIFY(rw_unlock(&rwlp->rw_lock) == 0);
209 rw_tryenter(krwlock_t *rwlp, krw_t rw)
213 ASSERT(rwlp->initialized == B_TRUE);
214 ASSERT(rwlp->rw_owner != (void *)-1UL);
217 rv = rw_tryrdlock(&rwlp->rw_lock);
219 rv = rw_trywrlock(&rwlp->rw_lock);
222 rwlp->rw_owner = curthread;
231 rw_tryupgrade(krwlock_t *rwlp)
233 ASSERT(rwlp->initialized == B_TRUE);
234 ASSERT(rwlp->rw_owner != (void *)-1UL);
240 * =========================================================================
241 * condition variables
242 * =========================================================================
246 cv_init(kcondvar_t *cv, char *name, int type, void *arg)
248 VERIFY(cond_init(cv, type, NULL) == 0);
252 cv_destroy(kcondvar_t *cv)
254 VERIFY(cond_destroy(cv) == 0);
258 cv_wait(kcondvar_t *cv, kmutex_t *mp)
260 ASSERT(mutex_owner(mp) == curthread);
262 int ret = cond_wait(cv, &mp->m_lock);
263 VERIFY(ret == 0 || ret == EINTR);
264 mp->m_owner = curthread;
268 cv_timedwait(kcondvar_t *cv, kmutex_t *mp, clock_t abstime)
275 delta = abstime - ddi_get_lbolt();
279 ts.tv_sec = delta / hz;
280 ts.tv_nsec = (delta % hz) * (NANOSEC / hz);
282 ASSERT(mutex_owner(mp) == curthread);
284 error = cond_reltimedwait(cv, &mp->m_lock, &ts);
285 mp->m_owner = curthread;
299 cv_signal(kcondvar_t *cv)
301 VERIFY(cond_signal(cv) == 0);
305 cv_broadcast(kcondvar_t *cv)
307 VERIFY(cond_broadcast(cv) == 0);
311 * =========================================================================
313 * =========================================================================
316 * Note: for the xxxat() versions of these functions, we assume that the
317 * starting vp is always rootdir (which is true for spa_directory.c, the only
318 * ZFS consumer of these interfaces). We assert this is true, and then emulate
319 * them by adding '/' in front of the path.
324 vn_open(char *path, int x1, int flags, int mode, vnode_t **vpp, int x2, int x3)
329 char realpath[MAXPATHLEN];
334 * If we're accessing a real disk from userland, we need to use
335 * the character interface to avoid caching. This is particularly
336 * important if we're trying to look at a real in-kernel storage
337 * pool from userland, e.g. via zdb, because otherwise we won't
338 * see the changes occurring under the segmap cache.
339 * On the other hand, the stupid character device returns zero
340 * for its size. So -- gag -- we open the block device to get
341 * its size, and remember it for subsequent VOP_GETATTR().
343 if (strncmp(path, "/dev/", 5) == 0) {
345 fd = open64(path, O_RDONLY);
348 if (fstat64(fd, &st) == -1) {
353 (void) sprintf(realpath, "%s", path);
354 dsk = strstr(path, "/dsk/");
356 (void) sprintf(realpath + (dsk - path) + 1, "r%s",
359 (void) sprintf(realpath, "%s", path);
360 if (!(flags & FCREAT) && stat64(realpath, &st) == -1)
365 old_umask = umask(0);
368 * The construct 'flags - FREAD' conveniently maps combinations of
369 * FREAD and FWRITE to the corresponding O_RDONLY, O_WRONLY, and O_RDWR.
371 fd = open64(realpath, flags - FREAD, mode);
374 (void) umask(old_umask);
379 if (fstat64(fd, &st) == -1) {
385 (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
387 *vpp = vp = umem_zalloc(sizeof (vnode_t), UMEM_NOFAIL);
390 vp->v_size = st.st_size;
391 vp->v_path = spa_strdup(path);
398 vn_openat(char *path, int x1, int flags, int mode, vnode_t **vpp, int x2,
399 int x3, vnode_t *startvp, int fd)
401 char *realpath = umem_alloc(strlen(path) + 2, UMEM_NOFAIL);
404 ASSERT(startvp == rootdir);
405 (void) sprintf(realpath, "/%s", path);
407 /* fd ignored for now, need if want to simulate nbmand support */
408 ret = vn_open(realpath, x1, flags, mode, vpp, x2, x3);
410 umem_free(realpath, strlen(path) + 2);
417 vn_rdwr(int uio, vnode_t *vp, void *addr, ssize_t len, offset_t offset,
418 int x1, int x2, rlim64_t x3, void *x4, ssize_t *residp)
420 ssize_t rc, done = 0, split;
422 if (uio == UIO_READ) {
423 rc = pread64(vp->v_fd, addr, len, offset);
426 * To simulate partial disk writes, we split writes into two
427 * system calls so that the process can be killed in between.
429 split = (len > 0 ? rand() % len : 0);
430 rc = pwrite64(vp->v_fd, addr, split, offset);
433 rc = pwrite64(vp->v_fd, (char *)addr + split,
434 len - split, offset + split);
444 *residp = len - done;
445 else if (done != len)
451 vn_close(vnode_t *vp)
454 spa_strfree(vp->v_path);
455 umem_free(vp, sizeof (vnode_t));
459 * At a minimum we need to update the size since vdev_reopen()
460 * will no longer call vn_openat().
463 fop_getattr(vnode_t *vp, vattr_t *vap)
467 if (fstat64(vp->v_fd, &st) == -1) {
472 vap->va_size = st.st_size;
479 * =========================================================================
480 * Figure out which debugging statements to print
481 * =========================================================================
484 static char *dprintf_string;
485 static int dprintf_print_all;
488 dprintf_find_string(const char *string)
490 char *tmp_str = dprintf_string;
491 int len = strlen(string);
494 * Find out if this is a string we want to print.
495 * String format: file1.c,function_name1,file2.c,file3.c
498 while (tmp_str != NULL) {
499 if (strncmp(tmp_str, string, len) == 0 &&
500 (tmp_str[len] == ',' || tmp_str[len] == '\0'))
502 tmp_str = strchr(tmp_str, ',');
504 tmp_str++; /* Get rid of , */
510 dprintf_setup(int *argc, char **argv)
515 * Debugging can be specified two ways: by setting the
516 * environment variable ZFS_DEBUG, or by including a
517 * "debug=..." argument on the command line. The command
518 * line setting overrides the environment variable.
521 for (i = 1; i < *argc; i++) {
522 int len = strlen("debug=");
523 /* First look for a command line argument */
524 if (strncmp("debug=", argv[i], len) == 0) {
525 dprintf_string = argv[i] + len;
526 /* Remove from args */
527 for (j = i; j < *argc; j++)
534 if (dprintf_string == NULL) {
535 /* Look for ZFS_DEBUG environment variable */
536 dprintf_string = getenv("ZFS_DEBUG");
540 * Are we just turning on all debugging?
542 if (dprintf_find_string("on"))
543 dprintf_print_all = 1;
547 * =========================================================================
549 * =========================================================================
552 __dprintf(const char *file, const char *func, int line, const char *fmt, ...)
558 * Get rid of annoying "../common/" prefix to filename.
560 newfile = strrchr(file, '/');
561 if (newfile != NULL) {
562 newfile = newfile + 1; /* Get rid of leading / */
567 if (dprintf_print_all ||
568 dprintf_find_string(newfile) ||
569 dprintf_find_string(func)) {
570 /* Print out just the function name if requested */
572 if (dprintf_find_string("pid"))
573 (void) printf("%d ", getpid());
574 if (dprintf_find_string("tid"))
575 (void) printf("%u ", thr_self());
576 if (dprintf_find_string("cpu"))
577 (void) printf("%u ", getcpuid());
578 if (dprintf_find_string("time"))
579 (void) printf("%llu ", gethrtime());
580 if (dprintf_find_string("long"))
581 (void) printf("%s, line %d: ", newfile, line);
582 (void) printf("%s: ", func);
584 (void) vprintf(fmt, adx);
590 #endif /* ZFS_DEBUG */
593 * =========================================================================
594 * cmn_err() and panic()
595 * =========================================================================
597 static char ce_prefix[CE_IGNORE][10] = { "", "NOTICE: ", "WARNING: ", "" };
598 static char ce_suffix[CE_IGNORE][2] = { "", "\n", "\n", "" };
601 vpanic(const char *fmt, va_list adx)
603 (void) fprintf(stderr, "error: ");
604 (void) vfprintf(stderr, fmt, adx);
605 (void) fprintf(stderr, "\n");
607 abort(); /* think of it as a "user-level crash dump" */
611 panic(const char *fmt, ...)
621 vcmn_err(int ce, const char *fmt, va_list adx)
625 if (ce != CE_NOTE) { /* suppress noise in userland stress testing */
626 (void) fprintf(stderr, "%s", ce_prefix[ce]);
627 (void) vfprintf(stderr, fmt, adx);
628 (void) fprintf(stderr, "%s", ce_suffix[ce]);
634 cmn_err(int ce, const char *fmt, ...)
639 vcmn_err(ce, fmt, adx);
644 * =========================================================================
646 * =========================================================================
649 kobj_open_file(char *name)
654 /* set vp as the _fd field of the file */
655 if (vn_openat(name, UIO_SYSSPACE, FREAD, 0, &vp, 0, 0, rootdir,
657 return ((void *)-1UL);
659 file = umem_zalloc(sizeof (struct _buf), UMEM_NOFAIL);
660 file->_fd = (intptr_t)vp;
665 kobj_read_file(struct _buf *file, char *buf, unsigned size, unsigned off)
669 vn_rdwr(UIO_READ, (vnode_t *)file->_fd, buf, size, (offset_t)off,
670 UIO_SYSSPACE, 0, 0, 0, &resid);
672 return (size - resid);
676 kobj_close_file(struct _buf *file)
678 vn_close((vnode_t *)file->_fd);
679 umem_free(file, sizeof (struct _buf));
683 kobj_get_filesize(struct _buf *file, uint64_t *size)
686 vnode_t *vp = (vnode_t *)file->_fd;
688 if (fstat64(vp->v_fd, &st) == -1) {
697 * =========================================================================
699 * =========================================================================
705 poll(0, 0, ticks * (1000 / hz));
709 * Find highest one bit set.
710 * Returns bit number + 1 of highest bit that is set, otherwise returns 0.
711 * High order bit is 31 (or 63 in _LP64 kernel).
721 if (i & 0xffffffff00000000ul) {
725 if (i & 0xffff0000) {
743 static int random_fd = -1, urandom_fd = -1;
746 random_get_bytes_common(uint8_t *ptr, size_t len, int fd)
754 bytes = read(fd, ptr, resid);
755 ASSERT3S(bytes, >=, 0);
764 random_get_bytes(uint8_t *ptr, size_t len)
766 return (random_get_bytes_common(ptr, len, random_fd));
770 random_get_pseudo_bytes(uint8_t *ptr, size_t len)
772 return (random_get_bytes_common(ptr, len, urandom_fd));
776 ddi_strtoul(const char *hw_serial, char **nptr, int base, unsigned long *result)
780 *result = strtoul(hw_serial, &end, base);
787 ddi_strtoull(const char *str, char **nptr, int base, u_longlong_t *result)
791 *result = strtoull(str, &end, base);
798 * =========================================================================
799 * kernel emulation setup & teardown
800 * =========================================================================
803 umem_out_of_memory(void)
805 char errmsg[] = "out of memory -- generating core dump\n";
807 (void) fprintf(stderr, "%s", errmsg);
813 kernel_init(int mode)
815 umem_nofail_callback(umem_out_of_memory);
817 physmem = sysconf(_SC_PHYS_PAGES);
819 dprintf("physmem = %llu pages (%.2f GB)\n", physmem,
820 (double)physmem * sysconf(_SC_PAGE_SIZE) / (1ULL << 30));
822 (void) snprintf(hw_serial, sizeof (hw_serial), "%ld",
823 (mode & FWRITE) ? gethostid() : 0);
825 VERIFY((random_fd = open("/dev/random", O_RDONLY)) != -1);
826 VERIFY((urandom_fd = open("/dev/urandom", O_RDONLY)) != -1);
848 z_uncompress(void *dst, size_t *dstlen, const void *src, size_t srclen)
851 uLongf len = *dstlen;
853 if ((ret = uncompress(dst, &len, src, srclen)) == Z_OK)
854 *dstlen = (size_t)len;
860 z_compress_level(void *dst, size_t *dstlen, const void *src, size_t srclen,
864 uLongf len = *dstlen;
866 if ((ret = compress2(dst, &len, src, srclen, level)) == Z_OK)
867 *dstlen = (size_t)len;
885 crgetngroups(cred_t *cr)
891 crgetgroups(cred_t *cr)
897 zfs_secpolicy_snapshot_perms(const char *name, cred_t *cr)
903 zfs_secpolicy_rename_perms(const char *from, const char *to, cred_t *cr)
909 zfs_secpolicy_destroy_perms(const char *name, cred_t *cr)
915 ksid_lookupdomain(const char *dom)
919 kd = umem_zalloc(sizeof (ksiddomain_t), UMEM_NOFAIL);
920 kd->kd_name = spa_strdup(dom);
925 ksiddomain_rele(ksiddomain_t *ksid)
927 spa_strfree(ksid->kd_name);
928 umem_free(ksid, sizeof (ksiddomain_t));
932 * Do not change the length of the returned string; it must be freed
936 kmem_asprintf(const char *fmt, ...)
943 size = vsnprintf(NULL, 0, fmt, adx) + 1;
946 buf = kmem_alloc(size, KM_SLEEP);
949 size = vsnprintf(buf, size, fmt, adx);
957 zfs_onexit_fd_hold(int fd, minor_t *minorp)
965 zfs_onexit_fd_rele(int fd)
971 zfs_onexit_add_cb(minor_t minor, void (*func)(void *), void *data,
972 uint64_t *action_handle)
979 zfs_onexit_del_cb(minor_t minor, uint64_t action_handle, boolean_t fire)
986 zfs_onexit_cb_data(minor_t minor, uint64_t action_handle, void **data)