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 2009 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>
39 #include <sys/systeminfo.h>
42 * 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"
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 mutex_enter(kmutex_t *mp)
119 ASSERT(mp->initialized == B_TRUE);
120 ASSERT(mp->m_owner != (void *)-1UL);
121 ASSERT(mp->m_owner != curthread);
122 VERIFY(mutex_lock(&mp->m_lock) == 0);
123 ASSERT(mp->m_owner == NULL);
124 mp->m_owner = curthread;
128 mutex_tryenter(kmutex_t *mp)
130 ASSERT(mp->initialized == B_TRUE);
131 ASSERT(mp->m_owner != (void *)-1UL);
132 if (0 == mutex_trylock(&mp->m_lock)) {
133 ASSERT(mp->m_owner == NULL);
134 mp->m_owner = curthread;
142 mutex_exit(kmutex_t *mp)
144 ASSERT(mp->initialized == B_TRUE);
145 ASSERT(mutex_owner(mp) == curthread);
147 VERIFY(mutex_unlock(&mp->m_lock) == 0);
151 mutex_owner(kmutex_t *mp)
153 ASSERT(mp->initialized == B_TRUE);
154 return (mp->m_owner);
158 * =========================================================================
160 * =========================================================================
164 rw_init(krwlock_t *rwlp, char *name, int type, void *arg)
166 rwlock_init(&rwlp->rw_lock, USYNC_THREAD, NULL);
167 rwlp->rw_owner = NULL;
168 rwlp->initialized = B_TRUE;
172 rw_destroy(krwlock_t *rwlp)
174 rwlock_destroy(&rwlp->rw_lock);
175 rwlp->rw_owner = (void *)-1UL;
176 rwlp->initialized = B_FALSE;
180 rw_enter(krwlock_t *rwlp, krw_t rw)
182 ASSERT(!RW_LOCK_HELD(rwlp));
183 ASSERT(rwlp->initialized == B_TRUE);
184 ASSERT(rwlp->rw_owner != (void *)-1UL);
185 ASSERT(rwlp->rw_owner != curthread);
188 VERIFY(rw_rdlock(&rwlp->rw_lock) == 0);
190 VERIFY(rw_wrlock(&rwlp->rw_lock) == 0);
192 rwlp->rw_owner = curthread;
196 rw_exit(krwlock_t *rwlp)
198 ASSERT(rwlp->initialized == B_TRUE);
199 ASSERT(rwlp->rw_owner != (void *)-1UL);
201 rwlp->rw_owner = NULL;
202 VERIFY(rw_unlock(&rwlp->rw_lock) == 0);
206 rw_tryenter(krwlock_t *rwlp, krw_t rw)
210 ASSERT(rwlp->initialized == B_TRUE);
211 ASSERT(rwlp->rw_owner != (void *)-1UL);
214 rv = rw_tryrdlock(&rwlp->rw_lock);
216 rv = rw_trywrlock(&rwlp->rw_lock);
219 rwlp->rw_owner = curthread;
228 rw_tryupgrade(krwlock_t *rwlp)
230 ASSERT(rwlp->initialized == B_TRUE);
231 ASSERT(rwlp->rw_owner != (void *)-1UL);
237 * =========================================================================
238 * condition variables
239 * =========================================================================
243 cv_init(kcondvar_t *cv, char *name, int type, void *arg)
245 VERIFY(cond_init(cv, type, NULL) == 0);
249 cv_destroy(kcondvar_t *cv)
251 VERIFY(cond_destroy(cv) == 0);
255 cv_wait(kcondvar_t *cv, kmutex_t *mp)
257 ASSERT(mutex_owner(mp) == curthread);
259 int ret = cond_wait(cv, &mp->m_lock);
260 VERIFY(ret == 0 || ret == EINTR);
261 mp->m_owner = curthread;
265 cv_timedwait(kcondvar_t *cv, kmutex_t *mp, clock_t abstime)
272 delta = abstime - lbolt;
276 ts.tv_sec = delta / hz;
277 ts.tv_nsec = (delta % hz) * (NANOSEC / hz);
279 ASSERT(mutex_owner(mp) == curthread);
281 error = cond_reltimedwait(cv, &mp->m_lock, &ts);
282 mp->m_owner = curthread;
296 cv_signal(kcondvar_t *cv)
298 VERIFY(cond_signal(cv) == 0);
302 cv_broadcast(kcondvar_t *cv)
304 VERIFY(cond_broadcast(cv) == 0);
308 * =========================================================================
310 * =========================================================================
313 * Note: for the xxxat() versions of these functions, we assume that the
314 * starting vp is always rootdir (which is true for spa_directory.c, the only
315 * ZFS consumer of these interfaces). We assert this is true, and then emulate
316 * them by adding '/' in front of the path.
321 vn_open(char *path, int x1, int flags, int mode, vnode_t **vpp, int x2, int x3)
326 char realpath[MAXPATHLEN];
330 * If we're accessing a real disk from userland, we need to use
331 * the character interface to avoid caching. This is particularly
332 * important if we're trying to look at a real in-kernel storage
333 * pool from userland, e.g. via zdb, because otherwise we won't
334 * see the changes occurring under the segmap cache.
335 * On the other hand, the stupid character device returns zero
336 * for its size. So -- gag -- we open the block device to get
337 * its size, and remember it for subsequent VOP_GETATTR().
339 if (strncmp(path, "/dev/", 5) == 0) {
341 fd = open64(path, O_RDONLY);
344 if (fstat64(fd, &st) == -1) {
349 (void) sprintf(realpath, "%s", path);
350 dsk = strstr(path, "/dsk/");
352 (void) sprintf(realpath + (dsk - path) + 1, "r%s",
355 (void) sprintf(realpath, "%s", path);
356 if (!(flags & FCREAT) && stat64(realpath, &st) == -1)
361 old_umask = umask(0);
364 * The construct 'flags - FREAD' conveniently maps combinations of
365 * FREAD and FWRITE to the corresponding O_RDONLY, O_WRONLY, and O_RDWR.
367 fd = open64(realpath, flags - FREAD, mode);
370 (void) umask(old_umask);
375 if (fstat64(fd, &st) == -1) {
380 (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
382 *vpp = vp = umem_zalloc(sizeof (vnode_t), UMEM_NOFAIL);
385 vp->v_size = st.st_size;
386 vp->v_path = spa_strdup(path);
393 vn_openat(char *path, int x1, int flags, int mode, vnode_t **vpp, int x2,
394 int x3, vnode_t *startvp, int fd)
396 char *realpath = umem_alloc(strlen(path) + 2, UMEM_NOFAIL);
399 ASSERT(startvp == rootdir);
400 (void) sprintf(realpath, "/%s", path);
402 /* fd ignored for now, need if want to simulate nbmand support */
403 ret = vn_open(realpath, x1, flags, mode, vpp, x2, x3);
405 umem_free(realpath, strlen(path) + 2);
412 vn_rdwr(int uio, vnode_t *vp, void *addr, ssize_t len, offset_t offset,
413 int x1, int x2, rlim64_t x3, void *x4, ssize_t *residp)
415 ssize_t iolen, split;
417 if (uio == UIO_READ) {
418 iolen = pread64(vp->v_fd, addr, len, offset);
421 * To simulate partial disk writes, we split writes into two
422 * system calls so that the process can be killed in between.
424 split = (len > 0 ? rand() % len : 0);
425 iolen = pwrite64(vp->v_fd, addr, split, offset);
426 iolen += pwrite64(vp->v_fd, (char *)addr + split,
427 len - split, offset + split);
433 *residp = len - iolen;
434 else if (iolen != len)
440 vn_close(vnode_t *vp)
443 spa_strfree(vp->v_path);
444 umem_free(vp, sizeof (vnode_t));
450 * =========================================================================
451 * Figure out which debugging statements to print
452 * =========================================================================
455 static char *dprintf_string;
456 static int dprintf_print_all;
459 dprintf_find_string(const char *string)
461 char *tmp_str = dprintf_string;
462 int len = strlen(string);
465 * Find out if this is a string we want to print.
466 * String format: file1.c,function_name1,file2.c,file3.c
469 while (tmp_str != NULL) {
470 if (strncmp(tmp_str, string, len) == 0 &&
471 (tmp_str[len] == ',' || tmp_str[len] == '\0'))
473 tmp_str = strchr(tmp_str, ',');
475 tmp_str++; /* Get rid of , */
481 dprintf_setup(int *argc, char **argv)
486 * Debugging can be specified two ways: by setting the
487 * environment variable ZFS_DEBUG, or by including a
488 * "debug=..." argument on the command line. The command
489 * line setting overrides the environment variable.
492 for (i = 1; i < *argc; i++) {
493 int len = strlen("debug=");
494 /* First look for a command line argument */
495 if (strncmp("debug=", argv[i], len) == 0) {
496 dprintf_string = argv[i] + len;
497 /* Remove from args */
498 for (j = i; j < *argc; j++)
505 if (dprintf_string == NULL) {
506 /* Look for ZFS_DEBUG environment variable */
507 dprintf_string = getenv("ZFS_DEBUG");
511 * Are we just turning on all debugging?
513 if (dprintf_find_string("on"))
514 dprintf_print_all = 1;
518 * =========================================================================
520 * =========================================================================
523 __dprintf(const char *file, const char *func, int line, const char *fmt, ...)
529 * Get rid of annoying "../common/" prefix to filename.
531 newfile = strrchr(file, '/');
532 if (newfile != NULL) {
533 newfile = newfile + 1; /* Get rid of leading / */
538 if (dprintf_print_all ||
539 dprintf_find_string(newfile) ||
540 dprintf_find_string(func)) {
541 /* Print out just the function name if requested */
543 if (dprintf_find_string("pid"))
544 (void) printf("%d ", getpid());
545 if (dprintf_find_string("tid"))
546 (void) printf("%u ", thr_self());
547 if (dprintf_find_string("cpu"))
548 (void) printf("%u ", getcpuid());
549 if (dprintf_find_string("time"))
550 (void) printf("%llu ", gethrtime());
551 if (dprintf_find_string("long"))
552 (void) printf("%s, line %d: ", newfile, line);
553 (void) printf("%s: ", func);
555 (void) vprintf(fmt, adx);
561 #endif /* ZFS_DEBUG */
564 * =========================================================================
565 * cmn_err() and panic()
566 * =========================================================================
568 static char ce_prefix[CE_IGNORE][10] = { "", "NOTICE: ", "WARNING: ", "" };
569 static char ce_suffix[CE_IGNORE][2] = { "", "\n", "\n", "" };
572 vpanic(const char *fmt, va_list adx)
574 (void) fprintf(stderr, "error: ");
575 (void) vfprintf(stderr, fmt, adx);
576 (void) fprintf(stderr, "\n");
578 abort(); /* think of it as a "user-level crash dump" */
582 panic(const char *fmt, ...)
592 vcmn_err(int ce, const char *fmt, va_list adx)
596 if (ce != CE_NOTE) { /* suppress noise in userland stress testing */
597 (void) fprintf(stderr, "%s", ce_prefix[ce]);
598 (void) vfprintf(stderr, fmt, adx);
599 (void) fprintf(stderr, "%s", ce_suffix[ce]);
605 cmn_err(int ce, const char *fmt, ...)
610 vcmn_err(ce, fmt, adx);
615 * =========================================================================
617 * =========================================================================
620 kobj_open_file(char *name)
625 /* set vp as the _fd field of the file */
626 if (vn_openat(name, UIO_SYSSPACE, FREAD, 0, &vp, 0, 0, rootdir,
628 return ((void *)-1UL);
630 file = umem_zalloc(sizeof (struct _buf), UMEM_NOFAIL);
631 file->_fd = (intptr_t)vp;
636 kobj_read_file(struct _buf *file, char *buf, unsigned size, unsigned off)
640 vn_rdwr(UIO_READ, (vnode_t *)file->_fd, buf, size, (offset_t)off,
641 UIO_SYSSPACE, 0, 0, 0, &resid);
643 return (size - resid);
647 kobj_close_file(struct _buf *file)
649 vn_close((vnode_t *)file->_fd);
650 umem_free(file, sizeof (struct _buf));
654 kobj_get_filesize(struct _buf *file, uint64_t *size)
657 vnode_t *vp = (vnode_t *)file->_fd;
659 if (fstat64(vp->v_fd, &st) == -1) {
668 * =========================================================================
670 * =========================================================================
676 poll(0, 0, ticks * (1000 / hz));
680 * Find highest one bit set.
681 * Returns bit number + 1 of highest bit that is set, otherwise returns 0.
682 * High order bit is 31 (or 63 in _LP64 kernel).
692 if (i & 0xffffffff00000000ul) {
696 if (i & 0xffff0000) {
714 static int random_fd = -1, urandom_fd = -1;
717 random_get_bytes_common(uint8_t *ptr, size_t len, int fd)
725 bytes = read(fd, ptr, resid);
726 ASSERT3S(bytes, >=, 0);
735 random_get_bytes(uint8_t *ptr, size_t len)
737 return (random_get_bytes_common(ptr, len, random_fd));
741 random_get_pseudo_bytes(uint8_t *ptr, size_t len)
743 return (random_get_bytes_common(ptr, len, urandom_fd));
747 ddi_strtoul(const char *hw_serial, char **nptr, int base, unsigned long *result)
751 *result = strtoul(hw_serial, &end, base);
758 * =========================================================================
759 * kernel emulation setup & teardown
760 * =========================================================================
763 umem_out_of_memory(void)
765 char errmsg[] = "out of memory -- generating core dump\n";
767 write(fileno(stderr), errmsg, sizeof (errmsg));
773 kernel_init(int mode)
775 umem_nofail_callback(umem_out_of_memory);
777 physmem = sysconf(_SC_PHYS_PAGES);
779 dprintf("physmem = %llu pages (%.2f GB)\n", physmem,
780 (double)physmem * sysconf(_SC_PAGE_SIZE) / (1ULL << 30));
782 (void) snprintf(hw_serial, sizeof (hw_serial), "%ld", gethostid());
784 VERIFY((random_fd = open("/dev/random", O_RDONLY)) != -1);
785 VERIFY((urandom_fd = open("/dev/urandom", O_RDONLY)) != -1);
805 z_uncompress(void *dst, size_t *dstlen, const void *src, size_t srclen)
808 uLongf len = *dstlen;
810 if ((ret = uncompress(dst, &len, src, srclen)) == Z_OK)
811 *dstlen = (size_t)len;
817 z_compress_level(void *dst, size_t *dstlen, const void *src, size_t srclen,
821 uLongf len = *dstlen;
823 if ((ret = compress2(dst, &len, src, srclen, level)) == Z_OK)
824 *dstlen = (size_t)len;
842 crgetngroups(cred_t *cr)
848 crgetgroups(cred_t *cr)
854 zfs_secpolicy_snapshot_perms(const char *name, cred_t *cr)
860 zfs_secpolicy_rename_perms(const char *from, const char *to, cred_t *cr)
866 zfs_secpolicy_destroy_perms(const char *name, cred_t *cr)
872 ksid_lookupdomain(const char *dom)
876 kd = umem_zalloc(sizeof (ksiddomain_t), UMEM_NOFAIL);
877 kd->kd_name = spa_strdup(dom);
882 ksiddomain_rele(ksiddomain_t *ksid)
884 spa_strfree(ksid->kd_name);
885 umem_free(ksid, sizeof (ksiddomain_t));