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;
180 rw_destroy(krwlock_t *rwlp)
182 rwlock_destroy(&rwlp->rw_lock);
183 rwlp->rw_owner = (void *)-1UL;
184 rwlp->initialized = B_FALSE;
188 rw_enter(krwlock_t *rwlp, krw_t rw)
190 //ASSERT(!RW_LOCK_HELD(rwlp));
191 ASSERT(rwlp->initialized == B_TRUE);
192 ASSERT(rwlp->rw_owner != (void *)-1UL);
193 ASSERT(rwlp->rw_owner != curthread);
195 if (rw == RW_READER) {
196 VERIFY(rw_rdlock(&rwlp->rw_lock) == 0);
197 ASSERT(rwlp->rw_count >= 0);
198 atomic_add_int(&rwlp->rw_count, 1);
200 VERIFY(rw_wrlock(&rwlp->rw_lock) == 0);
201 ASSERT(rwlp->rw_count == 0);
203 rwlp->rw_owner = curthread;
208 rw_exit(krwlock_t *rwlp)
210 ASSERT(rwlp->initialized == B_TRUE);
211 ASSERT(rwlp->rw_owner != (void *)-1UL);
213 if (rwlp->rw_owner == curthread) {
215 ASSERT(rwlp->rw_count == -1);
217 rwlp->rw_owner = NULL;
220 ASSERT(rwlp->rw_count > 0);
221 atomic_add_int(&rwlp->rw_count, -1);
223 VERIFY(rw_unlock(&rwlp->rw_lock) == 0);
227 rw_tryenter(krwlock_t *rwlp, krw_t rw)
231 ASSERT(rwlp->initialized == B_TRUE);
232 ASSERT(rwlp->rw_owner != (void *)-1UL);
233 ASSERT(rwlp->rw_owner != curthread);
236 rv = rw_tryrdlock(&rwlp->rw_lock);
238 rv = rw_trywrlock(&rwlp->rw_lock);
241 ASSERT(rwlp->rw_owner == NULL);
242 if (rw == RW_READER) {
243 ASSERT(rwlp->rw_count >= 0);
244 atomic_add_int(&rwlp->rw_count, 1);
246 ASSERT(rwlp->rw_count == 0);
248 rwlp->rw_owner = curthread;
258 rw_tryupgrade(krwlock_t *rwlp)
260 ASSERT(rwlp->initialized == B_TRUE);
261 ASSERT(rwlp->rw_owner != (void *)-1UL);
267 rw_lock_held(krwlock_t *rwlp)
270 return (rwlp->rw_count != 0);
274 * =========================================================================
275 * condition variables
276 * =========================================================================
280 cv_init(kcondvar_t *cv, char *name, int type, void *arg)
282 VERIFY(cond_init(cv, name, NULL) == 0);
286 cv_destroy(kcondvar_t *cv)
288 VERIFY(cond_destroy(cv) == 0);
292 cv_wait(kcondvar_t *cv, kmutex_t *mp)
294 ASSERT(mutex_owner(mp) == curthread);
296 int ret = cond_wait(cv, &mp->m_lock);
297 VERIFY(ret == 0 || ret == EINTR);
298 mp->m_owner = curthread;
302 cv_timedwait(kcondvar_t *cv, kmutex_t *mp, clock_t abstime)
315 if (gettimeofday(&tv, NULL) != 0)
316 assert(!"gettimeofday() failed");
318 ts.tv_sec = tv.tv_sec + delta / hz;
319 ts.tv_nsec = tv.tv_usec * 1000 + (delta % hz) * (NANOSEC / hz);
320 ASSERT(ts.tv_nsec >= 0);
322 if(ts.tv_nsec >= NANOSEC) {
324 ts.tv_nsec -= NANOSEC;
327 ASSERT(mutex_owner(mp) == curthread);
329 error = pthread_cond_timedwait(cv, &mp->m_lock, &ts);
330 mp->m_owner = curthread;
335 if (error == ETIMEDOUT)
344 cv_signal(kcondvar_t *cv)
346 VERIFY(cond_signal(cv) == 0);
350 cv_broadcast(kcondvar_t *cv)
352 VERIFY(cond_broadcast(cv) == 0);
356 * =========================================================================
358 * =========================================================================
361 * Note: for the xxxat() versions of these functions, we assume that the
362 * starting vp is always rootdir (which is true for spa_directory.c, the only
363 * ZFS consumer of these interfaces). We assert this is true, and then emulate
364 * them by adding '/' in front of the path.
369 vn_open(char *path, int x1, int flags, int mode, vnode_t **vpp, int x2, int x3)
374 char realpath[MAXPATHLEN];
378 * If we're accessing a real disk from userland, we need to use
379 * the character interface to avoid caching. This is particularly
380 * important if we're trying to look at a real in-kernel storage
381 * pool from userland, e.g. via zdb, because otherwise we won't
382 * see the changes occurring under the segmap cache.
383 * On the other hand, the stupid character device returns zero
384 * for its size. So -- gag -- we open the block device to get
385 * its size, and remember it for subsequent VOP_GETATTR().
387 if (strncmp(path, "/dev/", 5) == 0) {
389 fd = open64(path, O_RDONLY);
392 if (fstat64(fd, &st) == -1) {
397 (void) sprintf(realpath, "%s", path);
398 dsk = strstr(path, "/dsk/");
400 (void) sprintf(realpath + (dsk - path) + 1, "r%s",
403 (void) sprintf(realpath, "%s", path);
404 if (!(flags & FCREAT) && stat64(realpath, &st) == -1)
409 old_umask = umask(0);
412 * The construct 'flags - FREAD' conveniently maps combinations of
413 * FREAD and FWRITE to the corresponding O_RDONLY, O_WRONLY, and O_RDWR.
415 fd = open64(realpath, flags - FREAD, mode);
418 (void) umask(old_umask);
423 if (fstat64(fd, &st) == -1) {
428 (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
430 *vpp = vp = umem_zalloc(sizeof (vnode_t), UMEM_NOFAIL);
433 if (S_ISCHR(st.st_mode))
434 ioctl(fd, DIOCGMEDIASIZE, &vp->v_size);
436 vp->v_size = st.st_size;
437 vp->v_path = spa_strdup(path);
444 vn_openat(char *path, int x1, int flags, int mode, vnode_t **vpp, int x2,
445 int x3, vnode_t *startvp, int fd)
447 char *realpath = umem_alloc(strlen(path) + 2, UMEM_NOFAIL);
450 ASSERT(startvp == rootdir);
451 (void) sprintf(realpath, "/%s", path);
453 /* fd ignored for now, need if want to simulate nbmand support */
454 ret = vn_open(realpath, x1, flags, mode, vpp, x2, x3);
456 umem_free(realpath, strlen(path) + 2);
463 vn_rdwr(int uio, vnode_t *vp, void *addr, ssize_t len, offset_t offset,
464 int x1, int x2, rlim64_t x3, void *x4, ssize_t *residp)
466 ssize_t iolen, split;
468 if (uio == UIO_READ) {
469 iolen = pread64(vp->v_fd, addr, len, offset);
472 * To simulate partial disk writes, we split writes into two
473 * system calls so that the process can be killed in between.
475 split = (len > 0 ? rand() % len : 0);
476 iolen = pwrite64(vp->v_fd, addr, split, offset);
477 iolen += pwrite64(vp->v_fd, (char *)addr + split,
478 len - split, offset + split);
484 *residp = len - iolen;
485 else if (iolen != len)
491 vn_close(vnode_t *vp, int openflag, cred_t *cr, kthread_t *td)
494 spa_strfree(vp->v_path);
495 umem_free(vp, sizeof (vnode_t));
501 * =========================================================================
502 * Figure out which debugging statements to print
503 * =========================================================================
506 static char *dprintf_string;
507 static int dprintf_print_all;
510 dprintf_find_string(const char *string)
512 char *tmp_str = dprintf_string;
513 int len = strlen(string);
516 * Find out if this is a string we want to print.
517 * String format: file1.c,function_name1,file2.c,file3.c
520 while (tmp_str != NULL) {
521 if (strncmp(tmp_str, string, len) == 0 &&
522 (tmp_str[len] == ',' || tmp_str[len] == '\0'))
524 tmp_str = strchr(tmp_str, ',');
526 tmp_str++; /* Get rid of , */
532 dprintf_setup(int *argc, char **argv)
537 * Debugging can be specified two ways: by setting the
538 * environment variable ZFS_DEBUG, or by including a
539 * "debug=..." argument on the command line. The command
540 * line setting overrides the environment variable.
543 for (i = 1; i < *argc; i++) {
544 int len = strlen("debug=");
545 /* First look for a command line argument */
546 if (strncmp("debug=", argv[i], len) == 0) {
547 dprintf_string = argv[i] + len;
548 /* Remove from args */
549 for (j = i; j < *argc; j++)
556 if (dprintf_string == NULL) {
557 /* Look for ZFS_DEBUG environment variable */
558 dprintf_string = getenv("ZFS_DEBUG");
562 * Are we just turning on all debugging?
564 if (dprintf_find_string("on"))
565 dprintf_print_all = 1;
569 * =========================================================================
571 * =========================================================================
574 __dprintf(const char *file, const char *func, int line, const char *fmt, ...)
580 * Get rid of annoying "../common/" prefix to filename.
582 newfile = strrchr(file, '/');
583 if (newfile != NULL) {
584 newfile = newfile + 1; /* Get rid of leading / */
589 if (dprintf_print_all ||
590 dprintf_find_string(newfile) ||
591 dprintf_find_string(func)) {
592 /* Print out just the function name if requested */
594 if (dprintf_find_string("pid"))
595 (void) printf("%d ", getpid());
596 if (dprintf_find_string("tid"))
597 (void) printf("%u ", thr_self());
599 if (dprintf_find_string("cpu"))
600 (void) printf("%u ", getcpuid());
602 if (dprintf_find_string("time"))
603 (void) printf("%llu ", gethrtime());
604 if (dprintf_find_string("long"))
605 (void) printf("%s, line %d: ", newfile, line);
606 (void) printf("%s: ", func);
608 (void) vprintf(fmt, adx);
614 #endif /* ZFS_DEBUG */
617 * =========================================================================
618 * cmn_err() and panic()
619 * =========================================================================
621 static char ce_prefix[CE_IGNORE][10] = { "", "NOTICE: ", "WARNING: ", "" };
622 static char ce_suffix[CE_IGNORE][2] = { "", "\n", "\n", "" };
625 vpanic(const char *fmt, va_list adx)
627 (void) fprintf(stderr, "error: ");
628 (void) vfprintf(stderr, fmt, adx);
629 (void) fprintf(stderr, "\n");
631 abort(); /* think of it as a "user-level crash dump" */
635 panic(const char *fmt, ...)
645 vcmn_err(int ce, const char *fmt, va_list adx)
649 if (ce != CE_NOTE) { /* suppress noise in userland stress testing */
650 (void) fprintf(stderr, "%s", ce_prefix[ce]);
651 (void) vfprintf(stderr, fmt, adx);
652 (void) fprintf(stderr, "%s", ce_suffix[ce]);
658 cmn_err(int ce, const char *fmt, ...)
663 vcmn_err(ce, fmt, adx);
668 * =========================================================================
670 * =========================================================================
673 kobj_open_file(char *name)
678 /* set vp as the _fd field of the file */
679 if (vn_openat(name, UIO_SYSSPACE, FREAD, 0, &vp, 0, 0, rootdir,
681 return ((void *)-1UL);
683 file = umem_zalloc(sizeof (struct _buf), UMEM_NOFAIL);
684 file->_fd = (intptr_t)vp;
689 kobj_read_file(struct _buf *file, char *buf, unsigned size, unsigned off)
693 vn_rdwr(UIO_READ, (vnode_t *)file->_fd, buf, size, (offset_t)off,
694 UIO_SYSSPACE, 0, 0, 0, &resid);
696 return (size - resid);
700 kobj_close_file(struct _buf *file)
702 vn_close((vnode_t *)file->_fd, 0, NULL, NULL);
703 umem_free(file, sizeof (struct _buf));
707 kobj_get_filesize(struct _buf *file, uint64_t *size)
710 vnode_t *vp = (vnode_t *)file->_fd;
712 if (fstat64(vp->v_fd, &st) == -1) {
713 vn_close(vp, 0, NULL, NULL);
721 * =========================================================================
723 * =========================================================================
729 poll(0, 0, ticks * (1000 / hz));
734 * Find highest one bit set.
735 * Returns bit number + 1 of highest bit that is set, otherwise returns 0.
736 * High order bit is 31 (or 63 in _LP64 kernel).
746 if (i & 0xffffffff00000000ul) {
750 if (i & 0xffff0000) {
769 static int random_fd = -1, urandom_fd = -1;
772 random_get_bytes_common(uint8_t *ptr, size_t len, int fd)
780 bytes = read(fd, ptr, resid);
781 ASSERT3S(bytes, >=, 0);
790 random_get_bytes(uint8_t *ptr, size_t len)
792 return (random_get_bytes_common(ptr, len, random_fd));
796 random_get_pseudo_bytes(uint8_t *ptr, size_t len)
798 return (random_get_bytes_common(ptr, len, urandom_fd));
802 ddi_strtoul(const char *hw_serial, char **nptr, int base, unsigned long *result)
806 *result = strtoul(hw_serial, &end, base);
813 * =========================================================================
814 * kernel emulation setup & teardown
815 * =========================================================================
818 umem_out_of_memory(void)
820 char errmsg[] = "out of memory -- generating core dump\n";
822 write(fileno(stderr), errmsg, sizeof (errmsg));
828 kernel_init(int mode)
830 umem_nofail_callback(umem_out_of_memory);
832 physmem = sysconf(_SC_PHYS_PAGES);
834 dprintf("physmem = %llu pages (%.2f GB)\n", physmem,
835 (double)physmem * sysconf(_SC_PAGE_SIZE) / (1ULL << 30));
837 snprintf(hw_serial, sizeof (hw_serial), "%lu",
838 (unsigned long)gethostid());
840 VERIFY((random_fd = open("/dev/random", O_RDONLY)) != -1);
841 VERIFY((urandom_fd = open("/dev/urandom", O_RDONLY)) != -1);
861 z_uncompress(void *dst, size_t *dstlen, const void *src, size_t srclen)
864 uLongf len = *dstlen;
866 if ((ret = uncompress(dst, &len, src, srclen)) == Z_OK)
867 *dstlen = (size_t)len;
873 z_compress_level(void *dst, size_t *dstlen, const void *src, size_t srclen,
877 uLongf len = *dstlen;
879 if ((ret = compress2(dst, &len, src, srclen, level)) == Z_OK)
880 *dstlen = (size_t)len;
898 crgetngroups(cred_t *cr)
904 crgetgroups(cred_t *cr)
910 zfs_secpolicy_snapshot_perms(const char *name, cred_t *cr)
916 zfs_secpolicy_rename_perms(const char *from, const char *to, cred_t *cr)
922 zfs_secpolicy_destroy_perms(const char *name, cred_t *cr)
928 ksid_lookupdomain(const char *dom)
932 kd = umem_zalloc(sizeof (ksiddomain_t), UMEM_NOFAIL);
933 kd->kd_name = spa_strdup(dom);
938 ksiddomain_rele(ksiddomain_t *ksid)
940 spa_strfree(ksid->kd_name);
941 umem_free(ksid, sizeof (ksiddomain_t));