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>
36 #include <sys/rrwlock.h>
38 #include <sys/utsname.h>
39 #include <sys/systeminfo.h>
42 * Emulation of kernel services in userland.
47 vnode_t *rootdir = (vnode_t *)0xabcd1234;
48 char hw_serial[HW_HOSTID_LEN];
53 struct utsname utsname = {
54 "userland", "libzpool", "1", "1", "na"
57 /* this only exists to have its address taken */
61 * =========================================================================
63 * =========================================================================
67 zk_thread_create(void (*func)(), void *arg)
71 VERIFY(thr_create(0, 0, (void *(*)(void *))func, arg, THR_DETACHED,
74 return ((void *)(uintptr_t)tid);
78 * =========================================================================
80 * =========================================================================
84 kstat_create(char *module, int instance, char *name, char *class,
85 uchar_t type, ulong_t ndata, uchar_t ks_flag)
92 kstat_install(kstat_t *ksp)
97 kstat_delete(kstat_t *ksp)
101 * =========================================================================
103 * =========================================================================
106 zmutex_init(kmutex_t *mp)
109 mp->initialized = B_TRUE;
110 (void) _mutex_init(&mp->m_lock, USYNC_THREAD, NULL);
114 zmutex_destroy(kmutex_t *mp)
116 ASSERT(mp->initialized == B_TRUE);
117 ASSERT(mp->m_owner == NULL);
118 (void) _mutex_destroy(&(mp)->m_lock);
119 mp->m_owner = (void *)-1UL;
120 mp->initialized = B_FALSE;
124 zmutex_owned(kmutex_t *mp)
126 ASSERT(mp->initialized == B_TRUE);
128 return (mp->m_owner == curthread);
132 mutex_enter(kmutex_t *mp)
134 ASSERT(mp->initialized == B_TRUE);
135 ASSERT(mp->m_owner != (void *)-1UL);
136 ASSERT(mp->m_owner != curthread);
137 VERIFY(mutex_lock(&mp->m_lock) == 0);
138 ASSERT(mp->m_owner == NULL);
139 mp->m_owner = curthread;
143 mutex_tryenter(kmutex_t *mp)
145 ASSERT(mp->initialized == B_TRUE);
146 ASSERT(mp->m_owner != (void *)-1UL);
147 if (0 == mutex_trylock(&mp->m_lock)) {
148 ASSERT(mp->m_owner == NULL);
149 mp->m_owner = curthread;
157 mutex_exit(kmutex_t *mp)
159 ASSERT(mp->initialized == B_TRUE);
160 ASSERT(mutex_owner(mp) == curthread);
162 VERIFY(mutex_unlock(&mp->m_lock) == 0);
166 mutex_owner(kmutex_t *mp)
168 ASSERT(mp->initialized == B_TRUE);
169 return (mp->m_owner);
173 * =========================================================================
175 * =========================================================================
179 rw_init(krwlock_t *rwlp, char *name, int type, void *arg)
181 rwlock_init(&rwlp->rw_lock, USYNC_THREAD, NULL);
182 rwlp->rw_owner = NULL;
183 rwlp->initialized = B_TRUE;
188 rw_destroy(krwlock_t *rwlp)
190 ASSERT(rwlp->rw_count == 0);
191 rwlock_destroy(&rwlp->rw_lock);
192 rwlp->rw_owner = (void *)-1UL;
193 rwlp->initialized = B_FALSE;
197 rw_enter(krwlock_t *rwlp, krw_t rw)
199 //ASSERT(!RW_LOCK_HELD(rwlp));
200 ASSERT(rwlp->initialized == B_TRUE);
201 ASSERT(rwlp->rw_owner != (void *)-1UL);
202 ASSERT(rwlp->rw_owner != curthread);
204 if (rw == RW_READER) {
205 VERIFY(rw_rdlock(&rwlp->rw_lock) == 0);
206 ASSERT(rwlp->rw_count >= 0);
207 atomic_add_int(&rwlp->rw_count, 1);
209 VERIFY(rw_wrlock(&rwlp->rw_lock) == 0);
210 ASSERT(rwlp->rw_count == 0);
212 rwlp->rw_owner = curthread;
217 rw_exit(krwlock_t *rwlp)
219 ASSERT(rwlp->initialized == B_TRUE);
220 ASSERT(rwlp->rw_owner != (void *)-1UL);
222 if (rwlp->rw_owner == curthread) {
224 ASSERT(rwlp->rw_count == -1);
226 rwlp->rw_owner = NULL;
229 ASSERT(rwlp->rw_count > 0);
230 atomic_add_int(&rwlp->rw_count, -1);
232 VERIFY(rw_unlock(&rwlp->rw_lock) == 0);
236 rw_tryenter(krwlock_t *rwlp, krw_t rw)
240 ASSERT(rwlp->initialized == B_TRUE);
241 ASSERT(rwlp->rw_owner != (void *)-1UL);
242 ASSERT(rwlp->rw_owner != curthread);
245 rv = rw_tryrdlock(&rwlp->rw_lock);
247 rv = rw_trywrlock(&rwlp->rw_lock);
250 ASSERT(rwlp->rw_owner == NULL);
251 if (rw == RW_READER) {
252 ASSERT(rwlp->rw_count >= 0);
253 atomic_add_int(&rwlp->rw_count, 1);
255 ASSERT(rwlp->rw_count == 0);
257 rwlp->rw_owner = curthread;
267 rw_tryupgrade(krwlock_t *rwlp)
269 ASSERT(rwlp->initialized == B_TRUE);
270 ASSERT(rwlp->rw_owner != (void *)-1UL);
276 rw_lock_held(krwlock_t *rwlp)
279 return (rwlp->rw_count != 0);
283 * =========================================================================
284 * condition variables
285 * =========================================================================
289 cv_init(kcondvar_t *cv, char *name, int type, void *arg)
291 VERIFY(cond_init(cv, name, NULL) == 0);
295 cv_destroy(kcondvar_t *cv)
297 VERIFY(cond_destroy(cv) == 0);
301 cv_wait(kcondvar_t *cv, kmutex_t *mp)
303 ASSERT(mutex_owner(mp) == curthread);
305 int ret = cond_wait(cv, &mp->m_lock);
306 VERIFY(ret == 0 || ret == EINTR);
307 mp->m_owner = curthread;
311 cv_timedwait(kcondvar_t *cv, kmutex_t *mp, clock_t abstime)
318 abstime += ddi_get_lbolt();
320 delta = abstime - ddi_get_lbolt();
324 if (gettimeofday(&tv, NULL) != 0)
325 assert(!"gettimeofday() failed");
327 ts.tv_sec = tv.tv_sec + delta / hz;
328 ts.tv_nsec = tv.tv_usec * 1000 + (delta % hz) * (NANOSEC / hz);
329 ASSERT(ts.tv_nsec >= 0);
331 if (ts.tv_nsec >= NANOSEC) {
333 ts.tv_nsec -= NANOSEC;
336 ASSERT(mutex_owner(mp) == curthread);
338 error = pthread_cond_timedwait(cv, &mp->m_lock, &ts);
339 mp->m_owner = curthread;
344 if (error == ETIMEDOUT)
354 cv_timedwait_hires(kcondvar_t *cv, kmutex_t *mp, hrtime_t tim, hrtime_t res,
364 delta = tim - gethrtime();
368 ts.tv_sec = delta / NANOSEC;
369 ts.tv_nsec = delta % NANOSEC;
371 ASSERT(mutex_owner(mp) == curthread);
373 error = pthread_cond_timedwait(cv, &mp->m_lock, &ts);
374 mp->m_owner = curthread;
376 if (error == ETIMEDOUT)
388 cv_signal(kcondvar_t *cv)
390 VERIFY(cond_signal(cv) == 0);
394 cv_broadcast(kcondvar_t *cv)
396 VERIFY(cond_broadcast(cv) == 0);
400 * =========================================================================
402 * =========================================================================
405 * Note: for the xxxat() versions of these functions, we assume that the
406 * starting vp is always rootdir (which is true for spa_directory.c, the only
407 * ZFS consumer of these interfaces). We assert this is true, and then emulate
408 * them by adding '/' in front of the path.
413 vn_open(char *path, int x1, int flags, int mode, vnode_t **vpp, int x2, int x3)
418 char realpath[MAXPATHLEN];
422 * If we're accessing a real disk from userland, we need to use
423 * the character interface to avoid caching. This is particularly
424 * important if we're trying to look at a real in-kernel storage
425 * pool from userland, e.g. via zdb, because otherwise we won't
426 * see the changes occurring under the segmap cache.
427 * On the other hand, the stupid character device returns zero
428 * for its size. So -- gag -- we open the block device to get
429 * its size, and remember it for subsequent VOP_GETATTR().
431 if (strncmp(path, "/dev/", 5) == 0) {
433 fd = open64(path, O_RDONLY);
436 if (fstat64(fd, &st) == -1) {
441 (void) sprintf(realpath, "%s", path);
442 dsk = strstr(path, "/dsk/");
444 (void) sprintf(realpath + (dsk - path) + 1, "r%s",
447 (void) sprintf(realpath, "%s", path);
448 if (!(flags & FCREAT) && stat64(realpath, &st) == -1)
453 old_umask = umask(0);
456 * The construct 'flags - FREAD' conveniently maps combinations of
457 * FREAD and FWRITE to the corresponding O_RDONLY, O_WRONLY, and O_RDWR.
459 fd = open64(realpath, flags - FREAD, mode);
462 (void) umask(old_umask);
467 if (fstat64(fd, &st) == -1) {
472 (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
474 *vpp = vp = umem_zalloc(sizeof (vnode_t), UMEM_NOFAIL);
477 vp->v_size = st.st_size;
478 vp->v_path = spa_strdup(path);
485 vn_openat(char *path, int x1, int flags, int mode, vnode_t **vpp, int x2,
486 int x3, vnode_t *startvp, int fd)
488 char *realpath = umem_alloc(strlen(path) + 2, UMEM_NOFAIL);
491 ASSERT(startvp == rootdir);
492 (void) sprintf(realpath, "/%s", path);
494 /* fd ignored for now, need if want to simulate nbmand support */
495 ret = vn_open(realpath, x1, flags, mode, vpp, x2, x3);
497 umem_free(realpath, strlen(path) + 2);
504 vn_rdwr(int uio, vnode_t *vp, void *addr, ssize_t len, offset_t offset,
505 int x1, int x2, rlim64_t x3, void *x4, ssize_t *residp)
507 ssize_t iolen, split;
509 if (uio == UIO_READ) {
510 iolen = pread64(vp->v_fd, addr, len, offset);
513 * To simulate partial disk writes, we split writes into two
514 * system calls so that the process can be killed in between.
516 int sectors = len >> SPA_MINBLOCKSHIFT;
517 split = (sectors > 0 ? rand() % sectors : 0) <<
519 iolen = pwrite64(vp->v_fd, addr, split, offset);
520 iolen += pwrite64(vp->v_fd, (char *)addr + split,
521 len - split, offset + split);
527 *residp = len - iolen;
528 else if (iolen != len)
534 vn_close(vnode_t *vp, int openflag, cred_t *cr, kthread_t *td)
537 spa_strfree(vp->v_path);
538 umem_free(vp, sizeof (vnode_t));
542 * At a minimum we need to update the size since vdev_reopen()
543 * will no longer call vn_openat().
546 fop_getattr(vnode_t *vp, vattr_t *vap)
550 if (fstat64(vp->v_fd, &st) == -1) {
555 vap->va_size = st.st_size;
562 * =========================================================================
563 * Figure out which debugging statements to print
564 * =========================================================================
567 static char *dprintf_string;
568 static int dprintf_print_all;
571 dprintf_find_string(const char *string)
573 char *tmp_str = dprintf_string;
574 int len = strlen(string);
577 * Find out if this is a string we want to print.
578 * String format: file1.c,function_name1,file2.c,file3.c
581 while (tmp_str != NULL) {
582 if (strncmp(tmp_str, string, len) == 0 &&
583 (tmp_str[len] == ',' || tmp_str[len] == '\0'))
585 tmp_str = strchr(tmp_str, ',');
587 tmp_str++; /* Get rid of , */
593 dprintf_setup(int *argc, char **argv)
598 * Debugging can be specified two ways: by setting the
599 * environment variable ZFS_DEBUG, or by including a
600 * "debug=..." argument on the command line. The command
601 * line setting overrides the environment variable.
604 for (i = 1; i < *argc; i++) {
605 int len = strlen("debug=");
606 /* First look for a command line argument */
607 if (strncmp("debug=", argv[i], len) == 0) {
608 dprintf_string = argv[i] + len;
609 /* Remove from args */
610 for (j = i; j < *argc; j++)
617 if (dprintf_string == NULL) {
618 /* Look for ZFS_DEBUG environment variable */
619 dprintf_string = getenv("ZFS_DEBUG");
623 * Are we just turning on all debugging?
625 if (dprintf_find_string("on"))
626 dprintf_print_all = 1;
630 * =========================================================================
632 * =========================================================================
635 __dprintf(const char *file, const char *func, int line, const char *fmt, ...)
641 * Get rid of annoying "../common/" prefix to filename.
643 newfile = strrchr(file, '/');
644 if (newfile != NULL) {
645 newfile = newfile + 1; /* Get rid of leading / */
650 if (dprintf_print_all ||
651 dprintf_find_string(newfile) ||
652 dprintf_find_string(func)) {
653 /* Print out just the function name if requested */
655 if (dprintf_find_string("pid"))
656 (void) printf("%d ", getpid());
657 if (dprintf_find_string("tid"))
658 (void) printf("%u ", thr_self());
660 if (dprintf_find_string("cpu"))
661 (void) printf("%u ", getcpuid());
663 if (dprintf_find_string("time"))
664 (void) printf("%llu ", gethrtime());
665 if (dprintf_find_string("long"))
666 (void) printf("%s, line %d: ", newfile, line);
667 (void) printf("%s: ", func);
669 (void) vprintf(fmt, adx);
675 #endif /* ZFS_DEBUG */
678 * =========================================================================
679 * cmn_err() and panic()
680 * =========================================================================
682 static char ce_prefix[CE_IGNORE][10] = { "", "NOTICE: ", "WARNING: ", "" };
683 static char ce_suffix[CE_IGNORE][2] = { "", "\n", "\n", "" };
686 vpanic(const char *fmt, va_list adx)
688 (void) fprintf(stderr, "error: ");
689 (void) vfprintf(stderr, fmt, adx);
690 (void) fprintf(stderr, "\n");
692 abort(); /* think of it as a "user-level crash dump" */
696 panic(const char *fmt, ...)
706 vcmn_err(int ce, const char *fmt, va_list adx)
710 if (ce != CE_NOTE) { /* suppress noise in userland stress testing */
711 (void) fprintf(stderr, "%s", ce_prefix[ce]);
712 (void) vfprintf(stderr, fmt, adx);
713 (void) fprintf(stderr, "%s", ce_suffix[ce]);
719 cmn_err(int ce, const char *fmt, ...)
724 vcmn_err(ce, fmt, adx);
729 * =========================================================================
731 * =========================================================================
734 kobj_open_file(char *name)
739 /* set vp as the _fd field of the file */
740 if (vn_openat(name, UIO_SYSSPACE, FREAD, 0, &vp, 0, 0, rootdir,
742 return ((void *)-1UL);
744 file = umem_zalloc(sizeof (struct _buf), UMEM_NOFAIL);
745 file->_fd = (intptr_t)vp;
750 kobj_read_file(struct _buf *file, char *buf, unsigned size, unsigned off)
754 vn_rdwr(UIO_READ, (vnode_t *)file->_fd, buf, size, (offset_t)off,
755 UIO_SYSSPACE, 0, 0, 0, &resid);
757 return (size - resid);
761 kobj_close_file(struct _buf *file)
763 vn_close((vnode_t *)file->_fd, 0, NULL, NULL);
764 umem_free(file, sizeof (struct _buf));
768 kobj_get_filesize(struct _buf *file, uint64_t *size)
771 vnode_t *vp = (vnode_t *)file->_fd;
773 if (fstat64(vp->v_fd, &st) == -1) {
774 vn_close(vp, 0, NULL, NULL);
782 * =========================================================================
784 * =========================================================================
790 poll(0, 0, ticks * (1000 / hz));
795 * Find highest one bit set.
796 * Returns bit number + 1 of highest bit that is set, otherwise returns 0.
797 * High order bit is 31 (or 63 in _LP64 kernel).
807 if (i & 0xffffffff00000000ul) {
811 if (i & 0xffff0000) {
830 static int random_fd = -1, urandom_fd = -1;
833 random_get_bytes_common(uint8_t *ptr, size_t len, int fd)
841 bytes = read(fd, ptr, resid);
842 ASSERT3S(bytes, >=, 0);
851 random_get_bytes(uint8_t *ptr, size_t len)
853 return (random_get_bytes_common(ptr, len, random_fd));
857 random_get_pseudo_bytes(uint8_t *ptr, size_t len)
859 return (random_get_bytes_common(ptr, len, urandom_fd));
863 ddi_strtoul(const char *hw_serial, char **nptr, int base, unsigned long *result)
867 *result = strtoul(hw_serial, &end, base);
874 ddi_strtoull(const char *str, char **nptr, int base, u_longlong_t *result)
878 *result = strtoull(str, &end, base);
887 cyclic_add(cyc_handler_t *hdlr, cyc_time_t *when)
894 cyclic_remove(cyclic_id_t id)
900 cyclic_reprogram(cyclic_id_t id, hrtime_t expiration)
907 * =========================================================================
908 * kernel emulation setup & teardown
909 * =========================================================================
912 umem_out_of_memory(void)
914 char errmsg[] = "out of memory -- generating core dump\n";
916 write(fileno(stderr), errmsg, sizeof (errmsg));
922 kernel_init(int mode)
924 extern uint_t rrw_tsd_key;
926 umem_nofail_callback(umem_out_of_memory);
928 physmem = sysconf(_SC_PHYS_PAGES);
930 dprintf("physmem = %llu pages (%.2f GB)\n", physmem,
931 (double)physmem * sysconf(_SC_PAGE_SIZE) / (1ULL << 30));
933 (void) snprintf(hw_serial, sizeof (hw_serial), "%lu",
934 (mode & FWRITE) ? (unsigned long)gethostid() : 0);
936 VERIFY((random_fd = open("/dev/random", O_RDONLY)) != -1);
937 VERIFY((urandom_fd = open("/dev/urandom", O_RDONLY)) != -1);
942 mutex_init(&cpu_lock, NULL, MUTEX_DEFAULT, NULL);
947 tsd_create(&rrw_tsd_key, rrw_tsd_destroy);
965 z_uncompress(void *dst, size_t *dstlen, const void *src, size_t srclen)
968 uLongf len = *dstlen;
970 if ((ret = uncompress(dst, &len, src, srclen)) == Z_OK)
971 *dstlen = (size_t)len;
977 z_compress_level(void *dst, size_t *dstlen, const void *src, size_t srclen,
981 uLongf len = *dstlen;
983 if ((ret = compress2(dst, &len, src, srclen, level)) == Z_OK)
984 *dstlen = (size_t)len;
996 crgetruid(cred_t *cr)
1002 crgetgid(cred_t *cr)
1008 crgetngroups(cred_t *cr)
1014 crgetgroups(cred_t *cr)
1020 zfs_secpolicy_snapshot_perms(const char *name, cred_t *cr)
1026 zfs_secpolicy_rename_perms(const char *from, const char *to, cred_t *cr)
1032 zfs_secpolicy_destroy_perms(const char *name, cred_t *cr)
1038 ksid_lookupdomain(const char *dom)
1042 kd = umem_zalloc(sizeof (ksiddomain_t), UMEM_NOFAIL);
1043 kd->kd_name = spa_strdup(dom);
1048 ksiddomain_rele(ksiddomain_t *ksid)
1050 spa_strfree(ksid->kd_name);
1051 umem_free(ksid, sizeof (ksiddomain_t));
1055 * Do not change the length of the returned string; it must be freed
1059 kmem_asprintf(const char *fmt, ...)
1066 size = vsnprintf(NULL, 0, fmt, adx) + 1;
1069 buf = kmem_alloc(size, KM_SLEEP);
1072 size = vsnprintf(buf, size, fmt, adx);
1080 zfs_onexit_fd_hold(int fd, minor_t *minorp)
1088 zfs_onexit_fd_rele(int fd)
1094 zfs_onexit_add_cb(minor_t minor, void (*func)(void *), void *data,
1095 uint64_t *action_handle)
1102 zfs_onexit_del_cb(minor_t minor, uint64_t action_handle, boolean_t fire)
1109 zfs_onexit_cb_data(minor_t minor, uint64_t action_handle, void **data)
1117 zvol_create_minors(const char *name)