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 2008 Sun Microsystems, Inc. All rights reserved.
23 * Use is subject to license terms.
35 #include <sys/processor.h>
36 #include <sys/zfs_context.h>
38 #include <sys/utsname.h>
41 * Emulation of kernel services in userland.
44 int hz = 119; /* frequency when using gethrtime() >> 23 for lbolt */
46 vnode_t *rootdir = (vnode_t *)0xabcd1234;
49 struct utsname utsname = {
50 "userland", "libzpool", "1", "1", "na"
54 * =========================================================================
56 * =========================================================================
60 zk_thread_create(void (*func)(), void *arg)
64 VERIFY(thr_create(0, 0, (void *(*)(void *))func, arg, THR_DETACHED,
67 return ((void *)(uintptr_t)tid);
71 * =========================================================================
73 * =========================================================================
77 kstat_create(char *module, int instance, char *name, char *class,
78 uchar_t type, ulong_t ndata, uchar_t ks_flag)
85 kstat_install(kstat_t *ksp)
90 kstat_delete(kstat_t *ksp)
94 * =========================================================================
96 * =========================================================================
99 zmutex_init(kmutex_t *mp)
102 mp->initialized = B_TRUE;
103 (void) _mutex_init(&mp->m_lock, USYNC_THREAD, NULL);
107 zmutex_destroy(kmutex_t *mp)
109 ASSERT(mp->initialized == B_TRUE);
110 ASSERT(mp->m_owner == NULL);
111 (void) _mutex_destroy(&(mp)->m_lock);
112 mp->m_owner = (void *)-1UL;
113 mp->initialized = B_FALSE;
117 zmutex_owned(kmutex_t *mp)
119 ASSERT(mp->initialized == B_TRUE);
121 return (mp->m_owner == curthread);
125 mutex_enter(kmutex_t *mp)
127 ASSERT(mp->initialized == B_TRUE);
128 ASSERT(mp->m_owner != (void *)-1UL);
129 ASSERT(mp->m_owner != curthread);
130 VERIFY(mutex_lock(&mp->m_lock) == 0);
131 ASSERT(mp->m_owner == NULL);
132 mp->m_owner = curthread;
136 mutex_tryenter(kmutex_t *mp)
138 ASSERT(mp->initialized == B_TRUE);
139 ASSERT(mp->m_owner != (void *)-1UL);
140 if (mutex_trylock(&mp->m_lock) == 0) {
141 ASSERT(mp->m_owner == NULL);
142 mp->m_owner = curthread;
150 mutex_exit(kmutex_t *mp)
152 ASSERT(mp->initialized == B_TRUE);
153 ASSERT(mp->m_owner == curthread);
155 VERIFY(mutex_unlock(&mp->m_lock) == 0);
159 mutex_owner(kmutex_t *mp)
161 ASSERT(mp->initialized == B_TRUE);
162 return (mp->m_owner);
166 * =========================================================================
168 * =========================================================================
172 rw_init(krwlock_t *rwlp, char *name, int type, void *arg)
174 rwlock_init(&rwlp->rw_lock, USYNC_THREAD, NULL);
175 rwlp->rw_owner = NULL;
176 rwlp->initialized = B_TRUE;
181 rw_destroy(krwlock_t *rwlp)
183 ASSERT(rwlp->rw_count == 0);
184 rwlock_destroy(&rwlp->rw_lock);
185 rwlp->rw_owner = (void *)-1UL;
186 rwlp->initialized = B_FALSE;
190 rw_enter(krwlock_t *rwlp, krw_t rw)
192 //ASSERT(!RW_LOCK_HELD(rwlp));
193 ASSERT(rwlp->initialized == B_TRUE);
194 ASSERT(rwlp->rw_owner != (void *)-1UL);
195 ASSERT(rwlp->rw_owner != curthread);
197 if (rw == RW_READER) {
198 VERIFY(rw_rdlock(&rwlp->rw_lock) == 0);
199 ASSERT(rwlp->rw_count >= 0);
200 atomic_add_int(&rwlp->rw_count, 1);
202 VERIFY(rw_wrlock(&rwlp->rw_lock) == 0);
203 ASSERT(rwlp->rw_count == 0);
205 rwlp->rw_owner = curthread;
210 rw_exit(krwlock_t *rwlp)
212 ASSERT(rwlp->initialized == B_TRUE);
213 ASSERT(rwlp->rw_owner != (void *)-1UL);
215 if (rwlp->rw_owner == curthread) {
217 ASSERT(rwlp->rw_count == -1);
219 rwlp->rw_owner = NULL;
222 ASSERT(rwlp->rw_count > 0);
223 atomic_add_int(&rwlp->rw_count, -1);
225 VERIFY(rw_unlock(&rwlp->rw_lock) == 0);
229 rw_tryenter(krwlock_t *rwlp, krw_t rw)
233 ASSERT(rwlp->initialized == B_TRUE);
234 ASSERT(rwlp->rw_owner != (void *)-1UL);
235 ASSERT(rwlp->rw_owner != curthread);
238 rv = rw_tryrdlock(&rwlp->rw_lock);
240 rv = rw_trywrlock(&rwlp->rw_lock);
243 ASSERT(rwlp->rw_owner == NULL);
244 if (rw == RW_READER) {
245 ASSERT(rwlp->rw_count >= 0);
246 atomic_add_int(&rwlp->rw_count, 1);
248 ASSERT(rwlp->rw_count == 0);
250 rwlp->rw_owner = curthread;
260 rw_tryupgrade(krwlock_t *rwlp)
262 ASSERT(rwlp->initialized == B_TRUE);
263 ASSERT(rwlp->rw_owner != (void *)-1UL);
269 rw_lock_held(krwlock_t *rwlp)
272 return (rwlp->rw_count != 0);
276 * =========================================================================
277 * condition variables
278 * =========================================================================
282 cv_init(kcondvar_t *cv, char *name, int type, void *arg)
284 VERIFY(cond_init(cv, name, NULL) == 0);
288 cv_destroy(kcondvar_t *cv)
290 VERIFY(cond_destroy(cv) == 0);
294 cv_wait(kcondvar_t *cv, kmutex_t *mp)
296 ASSERT(mutex_owner(mp) == curthread);
298 int ret = cond_wait(cv, &mp->m_lock);
299 VERIFY(ret == 0 || ret == EINTR);
300 mp->m_owner = curthread;
304 cv_timedwait(kcondvar_t *cv, kmutex_t *mp, clock_t abstime)
313 delta = abstime - lbolt;
317 if (gettimeofday(&tv, NULL) != 0)
318 assert(!"gettimeofday() failed");
320 ts.tv_sec = tv.tv_sec + delta / hz;
321 ts.tv_nsec = tv.tv_usec * 1000 + (delta % hz) * (NANOSEC / hz);
322 ASSERT(ts.tv_nsec >= 0);
324 if (ts.tv_nsec >= NANOSEC) {
326 ts.tv_nsec -= NANOSEC;
329 ASSERT(mutex_owner(mp) == curthread);
331 error = pthread_cond_timedwait(cv, &mp->m_lock, &ts);
332 mp->m_owner = curthread;
337 if (error == ETIMEDOUT)
346 cv_signal(kcondvar_t *cv)
348 VERIFY(cond_signal(cv) == 0);
352 cv_broadcast(kcondvar_t *cv)
354 VERIFY(cond_broadcast(cv) == 0);
358 * =========================================================================
360 * =========================================================================
363 * Note: for the xxxat() versions of these functions, we assume that the
364 * starting vp is always rootdir (which is true for spa_directory.c, the only
365 * ZFS consumer of these interfaces). We assert this is true, and then emulate
366 * them by adding '/' in front of the path.
371 vn_open(char *path, int x1, int flags, int mode, vnode_t **vpp, int x2, int x3)
376 char realpath[MAXPATHLEN];
380 * If we're accessing a real disk from userland, we need to use
381 * the character interface to avoid caching. This is particularly
382 * important if we're trying to look at a real in-kernel storage
383 * pool from userland, e.g. via zdb, because otherwise we won't
384 * see the changes occurring under the segmap cache.
385 * On the other hand, the stupid character device returns zero
386 * for its size. So -- gag -- we open the block device to get
387 * its size, and remember it for subsequent VOP_GETATTR().
389 if (strncmp(path, "/dev/", 5) == 0) {
391 fd = open64(path, O_RDONLY);
394 if (fstat64(fd, &st) == -1) {
399 (void) sprintf(realpath, "%s", path);
400 dsk = strstr(path, "/dsk/");
402 (void) sprintf(realpath + (dsk - path) + 1, "r%s",
405 (void) sprintf(realpath, "%s", path);
406 if (!(flags & FCREAT) && stat64(realpath, &st) == -1)
411 old_umask = umask(0);
414 * The construct 'flags - FREAD' conveniently maps combinations of
415 * FREAD and FWRITE to the corresponding O_RDONLY, O_WRONLY, and O_RDWR.
417 fd = open64(realpath, flags - FREAD, mode);
420 (void) umask(old_umask);
425 if (fstat64(fd, &st) == -1) {
430 (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
432 *vpp = vp = umem_zalloc(sizeof (vnode_t), UMEM_NOFAIL);
435 if (S_ISCHR(st.st_mode))
436 ioctl(fd, DIOCGMEDIASIZE, &vp->v_size);
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));
503 * =========================================================================
504 * Figure out which debugging statements to print
505 * =========================================================================
508 static char *dprintf_string;
509 static int dprintf_print_all;
512 dprintf_find_string(const char *string)
514 char *tmp_str = dprintf_string;
515 int len = strlen(string);
518 * Find out if this is a string we want to print.
519 * String format: file1.c,function_name1,file2.c,file3.c
522 while (tmp_str != NULL) {
523 if (strncmp(tmp_str, string, len) == 0 &&
524 (tmp_str[len] == ',' || tmp_str[len] == '\0'))
526 tmp_str = strchr(tmp_str, ',');
528 tmp_str++; /* Get rid of , */
534 dprintf_setup(int *argc, char **argv)
539 * Debugging can be specified two ways: by setting the
540 * environment variable ZFS_DEBUG, or by including a
541 * "debug=..." argument on the command line. The command
542 * line setting overrides the environment variable.
545 for (i = 1; i < *argc; i++) {
546 int len = strlen("debug=");
547 /* First look for a command line argument */
548 if (strncmp("debug=", argv[i], len) == 0) {
549 dprintf_string = argv[i] + len;
550 /* Remove from args */
551 for (j = i; j < *argc; j++)
558 if (dprintf_string == NULL) {
559 /* Look for ZFS_DEBUG environment variable */
560 dprintf_string = getenv("ZFS_DEBUG");
564 * Are we just turning on all debugging?
566 if (dprintf_find_string("on"))
567 dprintf_print_all = 1;
571 * =========================================================================
573 * =========================================================================
576 __dprintf(const char *file, const char *func, int line, const char *fmt, ...)
582 * Get rid of annoying "../common/" prefix to filename.
584 newfile = strrchr(file, '/');
585 if (newfile != NULL) {
586 newfile = newfile + 1; /* Get rid of leading / */
591 if (dprintf_print_all ||
592 dprintf_find_string(newfile) ||
593 dprintf_find_string(func)) {
594 /* Print out just the function name if requested */
596 if (dprintf_find_string("pid"))
597 (void) printf("%d ", getpid());
598 if (dprintf_find_string("tid"))
599 (void) printf("%u ", thr_self());
601 if (dprintf_find_string("cpu"))
602 (void) printf("%u ", getcpuid());
604 if (dprintf_find_string("time"))
605 (void) printf("%llu ", gethrtime());
606 if (dprintf_find_string("long"))
607 (void) printf("%s, line %d: ", newfile, line);
608 (void) printf("%s: ", func);
610 (void) vprintf(fmt, adx);
616 #endif /* ZFS_DEBUG */
619 * =========================================================================
620 * cmn_err() and panic()
621 * =========================================================================
623 static char ce_prefix[CE_IGNORE][10] = { "", "NOTICE: ", "WARNING: ", "" };
624 static char ce_suffix[CE_IGNORE][2] = { "", "\n", "\n", "" };
627 vpanic(const char *fmt, va_list adx)
629 (void) fprintf(stderr, "error: ");
630 (void) vfprintf(stderr, fmt, adx);
631 (void) fprintf(stderr, "\n");
633 abort(); /* think of it as a "user-level crash dump" */
637 panic(const char *fmt, ...)
647 vcmn_err(int ce, const char *fmt, va_list adx)
651 if (ce != CE_NOTE) { /* suppress noise in userland stress testing */
652 (void) fprintf(stderr, "%s", ce_prefix[ce]);
653 (void) vfprintf(stderr, fmt, adx);
654 (void) fprintf(stderr, "%s", ce_suffix[ce]);
660 cmn_err(int ce, const char *fmt, ...)
665 vcmn_err(ce, fmt, adx);
670 * =========================================================================
672 * =========================================================================
675 kobj_open_file(char *name)
680 /* set vp as the _fd field of the file */
681 if (vn_openat(name, UIO_SYSSPACE, FREAD, 0, &vp, 0, 0, rootdir,
683 return ((void *)-1UL);
685 file = umem_zalloc(sizeof (struct _buf), UMEM_NOFAIL);
686 file->_fd = (intptr_t)vp;
691 kobj_read_file(struct _buf *file, char *buf, unsigned size, unsigned off)
695 vn_rdwr(UIO_READ, (vnode_t *)file->_fd, buf, size, (offset_t)off,
696 UIO_SYSSPACE, 0, 0, 0, &resid);
698 return (size - resid);
702 kobj_close_file(struct _buf *file)
704 vn_close((vnode_t *)file->_fd, 0, NULL, NULL);
705 umem_free(file, sizeof (struct _buf));
709 kobj_get_filesize(struct _buf *file, uint64_t *size)
712 vnode_t *vp = (vnode_t *)file->_fd;
714 if (fstat64(vp->v_fd, &st) == -1) {
715 vn_close(vp, 0, NULL, NULL);
723 * =========================================================================
725 * =========================================================================
731 poll(0, 0, ticks * (1000 / hz));
736 * Find highest one bit set.
737 * Returns bit number + 1 of highest bit that is set, otherwise returns 0.
738 * High order bit is 31 (or 63 in _LP64 kernel).
748 if (i & 0xffffffff00000000ul) {
752 if (i & 0xffff0000) {
771 static int random_fd = -1, urandom_fd = -1;
774 random_get_bytes_common(uint8_t *ptr, size_t len, int fd)
782 bytes = read(fd, ptr, resid);
783 ASSERT3S(bytes, >=, 0);
792 random_get_bytes(uint8_t *ptr, size_t len)
794 return (random_get_bytes_common(ptr, len, random_fd));
798 random_get_pseudo_bytes(uint8_t *ptr, size_t len)
800 return (random_get_bytes_common(ptr, len, urandom_fd));
804 ddi_strtoul(const char *hw_serial, char **nptr, int base, unsigned long *result)
808 *result = strtoul(hw_serial, &end, base);
815 * =========================================================================
816 * kernel emulation setup & teardown
817 * =========================================================================
820 umem_out_of_memory(void)
822 char errmsg[] = "out of memory -- generating core dump\n";
824 write(fileno(stderr), errmsg, sizeof (errmsg));
830 kernel_init(int mode)
832 umem_nofail_callback(umem_out_of_memory);
834 physmem = sysconf(_SC_PHYS_PAGES);
836 dprintf("physmem = %llu pages (%.2f GB)\n", physmem,
837 (double)physmem * sysconf(_SC_PAGE_SIZE) / (1ULL << 30));
839 snprintf(hw_serial, sizeof (hw_serial), "%lu",
840 (unsigned long)gethostid());
842 VERIFY((random_fd = open("/dev/random", O_RDONLY)) != -1);
843 VERIFY((urandom_fd = open("/dev/urandom", O_RDONLY)) != -1);
863 z_uncompress(void *dst, size_t *dstlen, const void *src, size_t srclen)
866 uLongf len = *dstlen;
868 if ((ret = uncompress(dst, &len, src, srclen)) == Z_OK)
869 *dstlen = (size_t)len;
875 z_compress_level(void *dst, size_t *dstlen, const void *src, size_t srclen,
879 uLongf len = *dstlen;
881 if ((ret = compress2(dst, &len, src, srclen, level)) == Z_OK)
882 *dstlen = (size_t)len;
900 crgetngroups(cred_t *cr)
906 crgetgroups(cred_t *cr)
912 zfs_secpolicy_snapshot_perms(const char *name, cred_t *cr)
918 zfs_secpolicy_rename_perms(const char *from, const char *to, cred_t *cr)
924 zfs_secpolicy_destroy_perms(const char *name, cred_t *cr)
930 ksid_lookupdomain(const char *dom)
934 kd = umem_zalloc(sizeof (ksiddomain_t), UMEM_NOFAIL);
935 kd->kd_name = spa_strdup(dom);
940 ksiddomain_rele(ksiddomain_t *ksid)
942 spa_strfree(ksid->kd_name);
943 umem_free(ksid, sizeof (ksiddomain_t));