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];
333 * If we're accessing a real disk from userland, we need to use
334 * the character interface to avoid caching. This is particularly
335 * important if we're trying to look at a real in-kernel storage
336 * pool from userland, e.g. via zdb, because otherwise we won't
337 * see the changes occurring under the segmap cache.
338 * On the other hand, the stupid character device returns zero
339 * for its size. So -- gag -- we open the block device to get
340 * its size, and remember it for subsequent VOP_GETATTR().
342 if (strncmp(path, "/dev/", 5) == 0) {
344 fd = open64(path, O_RDONLY);
347 if (fstat64(fd, &st) == -1) {
352 (void) sprintf(realpath, "%s", path);
353 dsk = strstr(path, "/dsk/");
355 (void) sprintf(realpath + (dsk - path) + 1, "r%s",
358 (void) sprintf(realpath, "%s", path);
359 if (!(flags & FCREAT) && stat64(realpath, &st) == -1)
364 old_umask = umask(0);
367 * The construct 'flags - FREAD' conveniently maps combinations of
368 * FREAD and FWRITE to the corresponding O_RDONLY, O_WRONLY, and O_RDWR.
370 fd = open64(realpath, flags - FREAD, mode);
373 (void) umask(old_umask);
378 if (fstat64(fd, &st) == -1) {
383 (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
385 *vpp = vp = umem_zalloc(sizeof (vnode_t), UMEM_NOFAIL);
388 vp->v_size = st.st_size;
389 vp->v_path = spa_strdup(path);
396 vn_openat(char *path, int x1, int flags, int mode, vnode_t **vpp, int x2,
397 int x3, vnode_t *startvp, int fd)
399 char *realpath = umem_alloc(strlen(path) + 2, UMEM_NOFAIL);
402 ASSERT(startvp == rootdir);
403 (void) sprintf(realpath, "/%s", path);
405 /* fd ignored for now, need if want to simulate nbmand support */
406 ret = vn_open(realpath, x1, flags, mode, vpp, x2, x3);
408 umem_free(realpath, strlen(path) + 2);
415 vn_rdwr(int uio, vnode_t *vp, void *addr, ssize_t len, offset_t offset,
416 int x1, int x2, rlim64_t x3, void *x4, ssize_t *residp)
418 ssize_t iolen, split;
420 if (uio == UIO_READ) {
421 iolen = pread64(vp->v_fd, addr, len, offset);
424 * To simulate partial disk writes, we split writes into two
425 * system calls so that the process can be killed in between.
427 split = (len > 0 ? rand() % len : 0);
428 iolen = pwrite64(vp->v_fd, addr, split, offset);
429 iolen += pwrite64(vp->v_fd, (char *)addr + split,
430 len - split, offset + split);
436 *residp = len - iolen;
437 else if (iolen != len)
443 vn_close(vnode_t *vp)
446 spa_strfree(vp->v_path);
447 umem_free(vp, sizeof (vnode_t));
451 * At a minimum we need to update the size since vdev_reopen()
452 * will no longer call vn_openat().
455 fop_getattr(vnode_t *vp, vattr_t *vap)
459 if (fstat64(vp->v_fd, &st) == -1) {
464 vap->va_size = st.st_size;
471 * =========================================================================
472 * Figure out which debugging statements to print
473 * =========================================================================
476 static char *dprintf_string;
477 static int dprintf_print_all;
480 dprintf_find_string(const char *string)
482 char *tmp_str = dprintf_string;
483 int len = strlen(string);
486 * Find out if this is a string we want to print.
487 * String format: file1.c,function_name1,file2.c,file3.c
490 while (tmp_str != NULL) {
491 if (strncmp(tmp_str, string, len) == 0 &&
492 (tmp_str[len] == ',' || tmp_str[len] == '\0'))
494 tmp_str = strchr(tmp_str, ',');
496 tmp_str++; /* Get rid of , */
502 dprintf_setup(int *argc, char **argv)
507 * Debugging can be specified two ways: by setting the
508 * environment variable ZFS_DEBUG, or by including a
509 * "debug=..." argument on the command line. The command
510 * line setting overrides the environment variable.
513 for (i = 1; i < *argc; i++) {
514 int len = strlen("debug=");
515 /* First look for a command line argument */
516 if (strncmp("debug=", argv[i], len) == 0) {
517 dprintf_string = argv[i] + len;
518 /* Remove from args */
519 for (j = i; j < *argc; j++)
526 if (dprintf_string == NULL) {
527 /* Look for ZFS_DEBUG environment variable */
528 dprintf_string = getenv("ZFS_DEBUG");
532 * Are we just turning on all debugging?
534 if (dprintf_find_string("on"))
535 dprintf_print_all = 1;
539 * =========================================================================
541 * =========================================================================
544 __dprintf(const char *file, const char *func, int line, const char *fmt, ...)
550 * Get rid of annoying "../common/" prefix to filename.
552 newfile = strrchr(file, '/');
553 if (newfile != NULL) {
554 newfile = newfile + 1; /* Get rid of leading / */
559 if (dprintf_print_all ||
560 dprintf_find_string(newfile) ||
561 dprintf_find_string(func)) {
562 /* Print out just the function name if requested */
564 if (dprintf_find_string("pid"))
565 (void) printf("%d ", getpid());
566 if (dprintf_find_string("tid"))
567 (void) printf("%u ", thr_self());
568 if (dprintf_find_string("cpu"))
569 (void) printf("%u ", getcpuid());
570 if (dprintf_find_string("time"))
571 (void) printf("%llu ", gethrtime());
572 if (dprintf_find_string("long"))
573 (void) printf("%s, line %d: ", newfile, line);
574 (void) printf("%s: ", func);
576 (void) vprintf(fmt, adx);
582 #endif /* ZFS_DEBUG */
585 * =========================================================================
586 * cmn_err() and panic()
587 * =========================================================================
589 static char ce_prefix[CE_IGNORE][10] = { "", "NOTICE: ", "WARNING: ", "" };
590 static char ce_suffix[CE_IGNORE][2] = { "", "\n", "\n", "" };
593 vpanic(const char *fmt, va_list adx)
595 (void) fprintf(stderr, "error: ");
596 (void) vfprintf(stderr, fmt, adx);
597 (void) fprintf(stderr, "\n");
599 abort(); /* think of it as a "user-level crash dump" */
603 panic(const char *fmt, ...)
613 vcmn_err(int ce, const char *fmt, va_list adx)
617 if (ce != CE_NOTE) { /* suppress noise in userland stress testing */
618 (void) fprintf(stderr, "%s", ce_prefix[ce]);
619 (void) vfprintf(stderr, fmt, adx);
620 (void) fprintf(stderr, "%s", ce_suffix[ce]);
626 cmn_err(int ce, const char *fmt, ...)
631 vcmn_err(ce, fmt, adx);
636 * =========================================================================
638 * =========================================================================
641 kobj_open_file(char *name)
646 /* set vp as the _fd field of the file */
647 if (vn_openat(name, UIO_SYSSPACE, FREAD, 0, &vp, 0, 0, rootdir,
649 return ((void *)-1UL);
651 file = umem_zalloc(sizeof (struct _buf), UMEM_NOFAIL);
652 file->_fd = (intptr_t)vp;
657 kobj_read_file(struct _buf *file, char *buf, unsigned size, unsigned off)
661 vn_rdwr(UIO_READ, (vnode_t *)file->_fd, buf, size, (offset_t)off,
662 UIO_SYSSPACE, 0, 0, 0, &resid);
664 return (size - resid);
668 kobj_close_file(struct _buf *file)
670 vn_close((vnode_t *)file->_fd);
671 umem_free(file, sizeof (struct _buf));
675 kobj_get_filesize(struct _buf *file, uint64_t *size)
678 vnode_t *vp = (vnode_t *)file->_fd;
680 if (fstat64(vp->v_fd, &st) == -1) {
689 * =========================================================================
691 * =========================================================================
697 poll(0, 0, ticks * (1000 / hz));
701 * Find highest one bit set.
702 * Returns bit number + 1 of highest bit that is set, otherwise returns 0.
703 * High order bit is 31 (or 63 in _LP64 kernel).
713 if (i & 0xffffffff00000000ul) {
717 if (i & 0xffff0000) {
735 static int random_fd = -1, urandom_fd = -1;
738 random_get_bytes_common(uint8_t *ptr, size_t len, int fd)
746 bytes = read(fd, ptr, resid);
747 ASSERT3S(bytes, >=, 0);
756 random_get_bytes(uint8_t *ptr, size_t len)
758 return (random_get_bytes_common(ptr, len, random_fd));
762 random_get_pseudo_bytes(uint8_t *ptr, size_t len)
764 return (random_get_bytes_common(ptr, len, urandom_fd));
768 ddi_strtoul(const char *hw_serial, char **nptr, int base, unsigned long *result)
772 *result = strtoul(hw_serial, &end, base);
779 ddi_strtoull(const char *str, char **nptr, int base, u_longlong_t *result)
783 *result = strtoull(str, &end, base);
790 * =========================================================================
791 * kernel emulation setup & teardown
792 * =========================================================================
795 umem_out_of_memory(void)
797 char errmsg[] = "out of memory -- generating core dump\n";
799 (void) fprintf(stderr, "%s", errmsg);
805 kernel_init(int mode)
807 umem_nofail_callback(umem_out_of_memory);
809 physmem = sysconf(_SC_PHYS_PAGES);
811 dprintf("physmem = %llu pages (%.2f GB)\n", physmem,
812 (double)physmem * sysconf(_SC_PAGE_SIZE) / (1ULL << 30));
814 (void) snprintf(hw_serial, sizeof (hw_serial), "%ld",
815 (mode & FWRITE) ? gethostid() : 0);
817 VERIFY((random_fd = open("/dev/random", O_RDONLY)) != -1);
818 VERIFY((urandom_fd = open("/dev/urandom", O_RDONLY)) != -1);
840 z_uncompress(void *dst, size_t *dstlen, const void *src, size_t srclen)
843 uLongf len = *dstlen;
845 if ((ret = uncompress(dst, &len, src, srclen)) == Z_OK)
846 *dstlen = (size_t)len;
852 z_compress_level(void *dst, size_t *dstlen, const void *src, size_t srclen,
856 uLongf len = *dstlen;
858 if ((ret = compress2(dst, &len, src, srclen, level)) == Z_OK)
859 *dstlen = (size_t)len;
877 crgetngroups(cred_t *cr)
883 crgetgroups(cred_t *cr)
889 zfs_secpolicy_snapshot_perms(const char *name, cred_t *cr)
895 zfs_secpolicy_rename_perms(const char *from, const char *to, cred_t *cr)
901 zfs_secpolicy_destroy_perms(const char *name, cred_t *cr)
907 ksid_lookupdomain(const char *dom)
911 kd = umem_zalloc(sizeof (ksiddomain_t), UMEM_NOFAIL);
912 kd->kd_name = spa_strdup(dom);
917 ksiddomain_rele(ksiddomain_t *ksid)
919 spa_strfree(ksid->kd_name);
920 umem_free(ksid, sizeof (ksiddomain_t));
924 * Do not change the length of the returned string; it must be freed
928 kmem_asprintf(const char *fmt, ...)
935 size = vsnprintf(NULL, 0, fmt, adx) + 1;
938 buf = kmem_alloc(size, KM_SLEEP);
941 size = vsnprintf(buf, size, fmt, adx);
949 zfs_onexit_fd_hold(int fd, minor_t *minorp)
957 zfs_onexit_fd_rele(int fd)
963 zfs_onexit_add_cb(minor_t minor, void (*func)(void *), void *data,
964 uint64_t *action_handle)
971 zfs_onexit_del_cb(minor_t minor, uint64_t action_handle, boolean_t fire)
978 zfs_onexit_cb_data(minor_t minor, uint64_t action_handle, void **data)