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 int sectors = len >> SPA_MINBLOCKSHIFT;
478 split = (sectors > 0 ? rand() % sectors : 0) <<
480 iolen = pwrite64(vp->v_fd, addr, split, offset);
481 iolen += pwrite64(vp->v_fd, (char *)addr + split,
482 len - split, offset + split);
488 *residp = len - iolen;
489 else if (iolen != len)
495 vn_close(vnode_t *vp, int openflag, cred_t *cr, kthread_t *td)
498 spa_strfree(vp->v_path);
499 umem_free(vp, sizeof (vnode_t));
503 * At a minimum we need to update the size since vdev_reopen()
504 * will no longer call vn_openat().
507 fop_getattr(vnode_t *vp, vattr_t *vap)
511 if (fstat64(vp->v_fd, &st) == -1) {
516 vap->va_size = st.st_size;
523 * =========================================================================
524 * Figure out which debugging statements to print
525 * =========================================================================
528 static char *dprintf_string;
529 static int dprintf_print_all;
532 dprintf_find_string(const char *string)
534 char *tmp_str = dprintf_string;
535 int len = strlen(string);
538 * Find out if this is a string we want to print.
539 * String format: file1.c,function_name1,file2.c,file3.c
542 while (tmp_str != NULL) {
543 if (strncmp(tmp_str, string, len) == 0 &&
544 (tmp_str[len] == ',' || tmp_str[len] == '\0'))
546 tmp_str = strchr(tmp_str, ',');
548 tmp_str++; /* Get rid of , */
554 dprintf_setup(int *argc, char **argv)
559 * Debugging can be specified two ways: by setting the
560 * environment variable ZFS_DEBUG, or by including a
561 * "debug=..." argument on the command line. The command
562 * line setting overrides the environment variable.
565 for (i = 1; i < *argc; i++) {
566 int len = strlen("debug=");
567 /* First look for a command line argument */
568 if (strncmp("debug=", argv[i], len) == 0) {
569 dprintf_string = argv[i] + len;
570 /* Remove from args */
571 for (j = i; j < *argc; j++)
578 if (dprintf_string == NULL) {
579 /* Look for ZFS_DEBUG environment variable */
580 dprintf_string = getenv("ZFS_DEBUG");
584 * Are we just turning on all debugging?
586 if (dprintf_find_string("on"))
587 dprintf_print_all = 1;
591 * =========================================================================
593 * =========================================================================
596 __dprintf(const char *file, const char *func, int line, const char *fmt, ...)
602 * Get rid of annoying "../common/" prefix to filename.
604 newfile = strrchr(file, '/');
605 if (newfile != NULL) {
606 newfile = newfile + 1; /* Get rid of leading / */
611 if (dprintf_print_all ||
612 dprintf_find_string(newfile) ||
613 dprintf_find_string(func)) {
614 /* Print out just the function name if requested */
616 if (dprintf_find_string("pid"))
617 (void) printf("%d ", getpid());
618 if (dprintf_find_string("tid"))
619 (void) printf("%u ", thr_self());
621 if (dprintf_find_string("cpu"))
622 (void) printf("%u ", getcpuid());
624 if (dprintf_find_string("time"))
625 (void) printf("%llu ", gethrtime());
626 if (dprintf_find_string("long"))
627 (void) printf("%s, line %d: ", newfile, line);
628 (void) printf("%s: ", func);
630 (void) vprintf(fmt, adx);
636 #endif /* ZFS_DEBUG */
639 * =========================================================================
640 * cmn_err() and panic()
641 * =========================================================================
643 static char ce_prefix[CE_IGNORE][10] = { "", "NOTICE: ", "WARNING: ", "" };
644 static char ce_suffix[CE_IGNORE][2] = { "", "\n", "\n", "" };
647 vpanic(const char *fmt, va_list adx)
649 (void) fprintf(stderr, "error: ");
650 (void) vfprintf(stderr, fmt, adx);
651 (void) fprintf(stderr, "\n");
653 abort(); /* think of it as a "user-level crash dump" */
657 panic(const char *fmt, ...)
667 vcmn_err(int ce, const char *fmt, va_list adx)
671 if (ce != CE_NOTE) { /* suppress noise in userland stress testing */
672 (void) fprintf(stderr, "%s", ce_prefix[ce]);
673 (void) vfprintf(stderr, fmt, adx);
674 (void) fprintf(stderr, "%s", ce_suffix[ce]);
680 cmn_err(int ce, const char *fmt, ...)
685 vcmn_err(ce, fmt, adx);
690 * =========================================================================
692 * =========================================================================
695 kobj_open_file(char *name)
700 /* set vp as the _fd field of the file */
701 if (vn_openat(name, UIO_SYSSPACE, FREAD, 0, &vp, 0, 0, rootdir,
703 return ((void *)-1UL);
705 file = umem_zalloc(sizeof (struct _buf), UMEM_NOFAIL);
706 file->_fd = (intptr_t)vp;
711 kobj_read_file(struct _buf *file, char *buf, unsigned size, unsigned off)
715 vn_rdwr(UIO_READ, (vnode_t *)file->_fd, buf, size, (offset_t)off,
716 UIO_SYSSPACE, 0, 0, 0, &resid);
718 return (size - resid);
722 kobj_close_file(struct _buf *file)
724 vn_close((vnode_t *)file->_fd, 0, NULL, NULL);
725 umem_free(file, sizeof (struct _buf));
729 kobj_get_filesize(struct _buf *file, uint64_t *size)
732 vnode_t *vp = (vnode_t *)file->_fd;
734 if (fstat64(vp->v_fd, &st) == -1) {
735 vn_close(vp, 0, NULL, NULL);
743 * =========================================================================
745 * =========================================================================
751 poll(0, 0, ticks * (1000 / hz));
756 * Find highest one bit set.
757 * Returns bit number + 1 of highest bit that is set, otherwise returns 0.
758 * High order bit is 31 (or 63 in _LP64 kernel).
768 if (i & 0xffffffff00000000ul) {
772 if (i & 0xffff0000) {
791 static int random_fd = -1, urandom_fd = -1;
794 random_get_bytes_common(uint8_t *ptr, size_t len, int fd)
802 bytes = read(fd, ptr, resid);
803 ASSERT3S(bytes, >=, 0);
812 random_get_bytes(uint8_t *ptr, size_t len)
814 return (random_get_bytes_common(ptr, len, random_fd));
818 random_get_pseudo_bytes(uint8_t *ptr, size_t len)
820 return (random_get_bytes_common(ptr, len, urandom_fd));
824 ddi_strtoul(const char *hw_serial, char **nptr, int base, unsigned long *result)
828 *result = strtoul(hw_serial, &end, base);
835 ddi_strtoull(const char *str, char **nptr, int base, u_longlong_t *result)
839 *result = strtoull(str, &end, base);
846 * =========================================================================
847 * kernel emulation setup & teardown
848 * =========================================================================
851 umem_out_of_memory(void)
853 char errmsg[] = "out of memory -- generating core dump\n";
855 write(fileno(stderr), errmsg, sizeof (errmsg));
861 kernel_init(int mode)
863 umem_nofail_callback(umem_out_of_memory);
865 physmem = sysconf(_SC_PHYS_PAGES);
867 dprintf("physmem = %llu pages (%.2f GB)\n", physmem,
868 (double)physmem * sysconf(_SC_PAGE_SIZE) / (1ULL << 30));
870 (void) snprintf(hw_serial, sizeof (hw_serial), "%lu",
871 (mode & FWRITE) ? (unsigned long)gethostid() : 0);
873 VERIFY((random_fd = open("/dev/random", O_RDONLY)) != -1);
874 VERIFY((urandom_fd = open("/dev/urandom", O_RDONLY)) != -1);
896 z_uncompress(void *dst, size_t *dstlen, const void *src, size_t srclen)
899 uLongf len = *dstlen;
901 if ((ret = uncompress(dst, &len, src, srclen)) == Z_OK)
902 *dstlen = (size_t)len;
908 z_compress_level(void *dst, size_t *dstlen, const void *src, size_t srclen,
912 uLongf len = *dstlen;
914 if ((ret = compress2(dst, &len, src, srclen, level)) == Z_OK)
915 *dstlen = (size_t)len;
933 crgetngroups(cred_t *cr)
939 crgetgroups(cred_t *cr)
945 zfs_secpolicy_snapshot_perms(const char *name, cred_t *cr)
951 zfs_secpolicy_rename_perms(const char *from, const char *to, cred_t *cr)
957 zfs_secpolicy_destroy_perms(const char *name, cred_t *cr)
963 ksid_lookupdomain(const char *dom)
967 kd = umem_zalloc(sizeof (ksiddomain_t), UMEM_NOFAIL);
968 kd->kd_name = spa_strdup(dom);
973 ksiddomain_rele(ksiddomain_t *ksid)
975 spa_strfree(ksid->kd_name);
976 umem_free(ksid, sizeof (ksiddomain_t));
980 * Do not change the length of the returned string; it must be freed
984 kmem_asprintf(const char *fmt, ...)
991 size = vsnprintf(NULL, 0, fmt, adx) + 1;
994 buf = kmem_alloc(size, KM_SLEEP);
997 size = vsnprintf(buf, size, fmt, adx);
1005 zfs_onexit_fd_hold(int fd, minor_t *minorp)
1013 zfs_onexit_fd_rele(int fd)
1019 zfs_onexit_add_cb(minor_t minor, void (*func)(void *), void *data,
1020 uint64_t *action_handle)
1027 zfs_onexit_del_cb(minor_t minor, uint64_t action_handle, boolean_t fire)
1034 zfs_onexit_cb_data(minor_t minor, uint64_t action_handle, void **data)
1042 zvol_create_minors(const char *name)