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];
52 struct utsname utsname = {
53 "userland", "libzpool", "1", "1", "na"
56 /* this only exists to have its address taken */
60 * =========================================================================
62 * =========================================================================
66 zk_thread_create(void (*func)(), void *arg)
70 VERIFY(thr_create(0, 0, (void *(*)(void *))func, arg, THR_DETACHED,
73 return ((void *)(uintptr_t)tid);
77 * =========================================================================
79 * =========================================================================
83 kstat_create(char *module, int instance, char *name, char *class,
84 uchar_t type, ulong_t ndata, uchar_t ks_flag)
91 kstat_install(kstat_t *ksp)
96 kstat_delete(kstat_t *ksp)
100 * =========================================================================
102 * =========================================================================
105 zmutex_init(kmutex_t *mp)
108 mp->initialized = B_TRUE;
109 (void) _mutex_init(&mp->m_lock, USYNC_THREAD, NULL);
113 zmutex_destroy(kmutex_t *mp)
115 ASSERT(mp->initialized == B_TRUE);
116 ASSERT(mp->m_owner == NULL);
117 (void) _mutex_destroy(&(mp)->m_lock);
118 mp->m_owner = (void *)-1UL;
119 mp->initialized = B_FALSE;
123 zmutex_owned(kmutex_t *mp)
125 ASSERT(mp->initialized == B_TRUE);
127 return (mp->m_owner == curthread);
131 mutex_enter(kmutex_t *mp)
133 ASSERT(mp->initialized == B_TRUE);
134 ASSERT(mp->m_owner != (void *)-1UL);
135 ASSERT(mp->m_owner != curthread);
136 VERIFY(mutex_lock(&mp->m_lock) == 0);
137 ASSERT(mp->m_owner == NULL);
138 mp->m_owner = curthread;
142 mutex_tryenter(kmutex_t *mp)
144 ASSERT(mp->initialized == B_TRUE);
145 ASSERT(mp->m_owner != (void *)-1UL);
146 if (0 == mutex_trylock(&mp->m_lock)) {
147 ASSERT(mp->m_owner == NULL);
148 mp->m_owner = curthread;
156 mutex_exit(kmutex_t *mp)
158 ASSERT(mp->initialized == B_TRUE);
159 ASSERT(mutex_owner(mp) == curthread);
161 VERIFY(mutex_unlock(&mp->m_lock) == 0);
165 mutex_owner(kmutex_t *mp)
167 ASSERT(mp->initialized == B_TRUE);
168 return (mp->m_owner);
172 * =========================================================================
174 * =========================================================================
178 rw_init(krwlock_t *rwlp, char *name, int type, void *arg)
180 rwlock_init(&rwlp->rw_lock, USYNC_THREAD, NULL);
181 rwlp->rw_owner = NULL;
182 rwlp->initialized = B_TRUE;
187 rw_destroy(krwlock_t *rwlp)
189 ASSERT(rwlp->rw_count == 0);
190 rwlock_destroy(&rwlp->rw_lock);
191 rwlp->rw_owner = (void *)-1UL;
192 rwlp->initialized = B_FALSE;
196 rw_enter(krwlock_t *rwlp, krw_t rw)
198 //ASSERT(!RW_LOCK_HELD(rwlp));
199 ASSERT(rwlp->initialized == B_TRUE);
200 ASSERT(rwlp->rw_owner != (void *)-1UL);
201 ASSERT(rwlp->rw_owner != curthread);
203 if (rw == RW_READER) {
204 VERIFY(rw_rdlock(&rwlp->rw_lock) == 0);
205 ASSERT(rwlp->rw_count >= 0);
206 atomic_add_int(&rwlp->rw_count, 1);
208 VERIFY(rw_wrlock(&rwlp->rw_lock) == 0);
209 ASSERT(rwlp->rw_count == 0);
211 rwlp->rw_owner = curthread;
216 rw_exit(krwlock_t *rwlp)
218 ASSERT(rwlp->initialized == B_TRUE);
219 ASSERT(rwlp->rw_owner != (void *)-1UL);
221 if (rwlp->rw_owner == curthread) {
223 ASSERT(rwlp->rw_count == -1);
225 rwlp->rw_owner = NULL;
228 ASSERT(rwlp->rw_count > 0);
229 atomic_add_int(&rwlp->rw_count, -1);
231 VERIFY(rw_unlock(&rwlp->rw_lock) == 0);
235 rw_tryenter(krwlock_t *rwlp, krw_t rw)
239 ASSERT(rwlp->initialized == B_TRUE);
240 ASSERT(rwlp->rw_owner != (void *)-1UL);
241 ASSERT(rwlp->rw_owner != curthread);
244 rv = rw_tryrdlock(&rwlp->rw_lock);
246 rv = rw_trywrlock(&rwlp->rw_lock);
249 ASSERT(rwlp->rw_owner == NULL);
250 if (rw == RW_READER) {
251 ASSERT(rwlp->rw_count >= 0);
252 atomic_add_int(&rwlp->rw_count, 1);
254 ASSERT(rwlp->rw_count == 0);
256 rwlp->rw_owner = curthread;
266 rw_tryupgrade(krwlock_t *rwlp)
268 ASSERT(rwlp->initialized == B_TRUE);
269 ASSERT(rwlp->rw_owner != (void *)-1UL);
275 rw_lock_held(krwlock_t *rwlp)
278 return (rwlp->rw_count != 0);
282 * =========================================================================
283 * condition variables
284 * =========================================================================
288 cv_init(kcondvar_t *cv, char *name, int type, void *arg)
290 VERIFY(cond_init(cv, name, NULL) == 0);
294 cv_destroy(kcondvar_t *cv)
296 VERIFY(cond_destroy(cv) == 0);
300 cv_wait(kcondvar_t *cv, kmutex_t *mp)
302 ASSERT(mutex_owner(mp) == curthread);
304 int ret = cond_wait(cv, &mp->m_lock);
305 VERIFY(ret == 0 || ret == EINTR);
306 mp->m_owner = curthread;
310 cv_timedwait(kcondvar_t *cv, kmutex_t *mp, clock_t abstime)
317 abstime += ddi_get_lbolt();
319 delta = abstime - ddi_get_lbolt();
323 if (gettimeofday(&tv, NULL) != 0)
324 assert(!"gettimeofday() failed");
326 ts.tv_sec = tv.tv_sec + delta / hz;
327 ts.tv_nsec = tv.tv_usec * 1000 + (delta % hz) * (NANOSEC / hz);
328 ASSERT(ts.tv_nsec >= 0);
330 if (ts.tv_nsec >= NANOSEC) {
332 ts.tv_nsec -= NANOSEC;
335 ASSERT(mutex_owner(mp) == curthread);
337 error = pthread_cond_timedwait(cv, &mp->m_lock, &ts);
338 mp->m_owner = curthread;
343 if (error == ETIMEDOUT)
352 cv_signal(kcondvar_t *cv)
354 VERIFY(cond_signal(cv) == 0);
358 cv_broadcast(kcondvar_t *cv)
360 VERIFY(cond_broadcast(cv) == 0);
364 * =========================================================================
366 * =========================================================================
369 * Note: for the xxxat() versions of these functions, we assume that the
370 * starting vp is always rootdir (which is true for spa_directory.c, the only
371 * ZFS consumer of these interfaces). We assert this is true, and then emulate
372 * them by adding '/' in front of the path.
377 vn_open(char *path, int x1, int flags, int mode, vnode_t **vpp, int x2, int x3)
382 char realpath[MAXPATHLEN];
386 * If we're accessing a real disk from userland, we need to use
387 * the character interface to avoid caching. This is particularly
388 * important if we're trying to look at a real in-kernel storage
389 * pool from userland, e.g. via zdb, because otherwise we won't
390 * see the changes occurring under the segmap cache.
391 * On the other hand, the stupid character device returns zero
392 * for its size. So -- gag -- we open the block device to get
393 * its size, and remember it for subsequent VOP_GETATTR().
395 if (strncmp(path, "/dev/", 5) == 0) {
397 fd = open64(path, O_RDONLY);
400 if (fstat64(fd, &st) == -1) {
405 (void) sprintf(realpath, "%s", path);
406 dsk = strstr(path, "/dsk/");
408 (void) sprintf(realpath + (dsk - path) + 1, "r%s",
411 (void) sprintf(realpath, "%s", path);
412 if (!(flags & FCREAT) && stat64(realpath, &st) == -1)
417 old_umask = umask(0);
420 * The construct 'flags - FREAD' conveniently maps combinations of
421 * FREAD and FWRITE to the corresponding O_RDONLY, O_WRONLY, and O_RDWR.
423 fd = open64(realpath, flags - FREAD, mode);
426 (void) umask(old_umask);
431 if (fstat64(fd, &st) == -1) {
436 (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
438 *vpp = vp = umem_zalloc(sizeof (vnode_t), UMEM_NOFAIL);
441 vp->v_size = st.st_size;
442 vp->v_path = spa_strdup(path);
449 vn_openat(char *path, int x1, int flags, int mode, vnode_t **vpp, int x2,
450 int x3, vnode_t *startvp, int fd)
452 char *realpath = umem_alloc(strlen(path) + 2, UMEM_NOFAIL);
455 ASSERT(startvp == rootdir);
456 (void) sprintf(realpath, "/%s", path);
458 /* fd ignored for now, need if want to simulate nbmand support */
459 ret = vn_open(realpath, x1, flags, mode, vpp, x2, x3);
461 umem_free(realpath, strlen(path) + 2);
468 vn_rdwr(int uio, vnode_t *vp, void *addr, ssize_t len, offset_t offset,
469 int x1, int x2, rlim64_t x3, void *x4, ssize_t *residp)
471 ssize_t iolen, split;
473 if (uio == UIO_READ) {
474 iolen = pread64(vp->v_fd, addr, len, offset);
477 * To simulate partial disk writes, we split writes into two
478 * system calls so that the process can be killed in between.
480 int sectors = len >> SPA_MINBLOCKSHIFT;
481 split = (sectors > 0 ? rand() % sectors : 0) <<
483 iolen = pwrite64(vp->v_fd, addr, split, offset);
484 iolen += pwrite64(vp->v_fd, (char *)addr + split,
485 len - split, offset + split);
491 *residp = len - iolen;
492 else if (iolen != len)
498 vn_close(vnode_t *vp, int openflag, cred_t *cr, kthread_t *td)
501 spa_strfree(vp->v_path);
502 umem_free(vp, sizeof (vnode_t));
506 * At a minimum we need to update the size since vdev_reopen()
507 * will no longer call vn_openat().
510 fop_getattr(vnode_t *vp, vattr_t *vap)
514 if (fstat64(vp->v_fd, &st) == -1) {
519 vap->va_size = st.st_size;
526 * =========================================================================
527 * Figure out which debugging statements to print
528 * =========================================================================
531 static char *dprintf_string;
532 static int dprintf_print_all;
535 dprintf_find_string(const char *string)
537 char *tmp_str = dprintf_string;
538 int len = strlen(string);
541 * Find out if this is a string we want to print.
542 * String format: file1.c,function_name1,file2.c,file3.c
545 while (tmp_str != NULL) {
546 if (strncmp(tmp_str, string, len) == 0 &&
547 (tmp_str[len] == ',' || tmp_str[len] == '\0'))
549 tmp_str = strchr(tmp_str, ',');
551 tmp_str++; /* Get rid of , */
557 dprintf_setup(int *argc, char **argv)
562 * Debugging can be specified two ways: by setting the
563 * environment variable ZFS_DEBUG, or by including a
564 * "debug=..." argument on the command line. The command
565 * line setting overrides the environment variable.
568 for (i = 1; i < *argc; i++) {
569 int len = strlen("debug=");
570 /* First look for a command line argument */
571 if (strncmp("debug=", argv[i], len) == 0) {
572 dprintf_string = argv[i] + len;
573 /* Remove from args */
574 for (j = i; j < *argc; j++)
581 if (dprintf_string == NULL) {
582 /* Look for ZFS_DEBUG environment variable */
583 dprintf_string = getenv("ZFS_DEBUG");
587 * Are we just turning on all debugging?
589 if (dprintf_find_string("on"))
590 dprintf_print_all = 1;
594 * =========================================================================
596 * =========================================================================
599 __dprintf(const char *file, const char *func, int line, const char *fmt, ...)
605 * Get rid of annoying "../common/" prefix to filename.
607 newfile = strrchr(file, '/');
608 if (newfile != NULL) {
609 newfile = newfile + 1; /* Get rid of leading / */
614 if (dprintf_print_all ||
615 dprintf_find_string(newfile) ||
616 dprintf_find_string(func)) {
617 /* Print out just the function name if requested */
619 if (dprintf_find_string("pid"))
620 (void) printf("%d ", getpid());
621 if (dprintf_find_string("tid"))
622 (void) printf("%u ", thr_self());
624 if (dprintf_find_string("cpu"))
625 (void) printf("%u ", getcpuid());
627 if (dprintf_find_string("time"))
628 (void) printf("%llu ", gethrtime());
629 if (dprintf_find_string("long"))
630 (void) printf("%s, line %d: ", newfile, line);
631 (void) printf("%s: ", func);
633 (void) vprintf(fmt, adx);
639 #endif /* ZFS_DEBUG */
642 * =========================================================================
643 * cmn_err() and panic()
644 * =========================================================================
646 static char ce_prefix[CE_IGNORE][10] = { "", "NOTICE: ", "WARNING: ", "" };
647 static char ce_suffix[CE_IGNORE][2] = { "", "\n", "\n", "" };
650 vpanic(const char *fmt, va_list adx)
652 (void) fprintf(stderr, "error: ");
653 (void) vfprintf(stderr, fmt, adx);
654 (void) fprintf(stderr, "\n");
656 abort(); /* think of it as a "user-level crash dump" */
660 panic(const char *fmt, ...)
670 vcmn_err(int ce, const char *fmt, va_list adx)
674 if (ce != CE_NOTE) { /* suppress noise in userland stress testing */
675 (void) fprintf(stderr, "%s", ce_prefix[ce]);
676 (void) vfprintf(stderr, fmt, adx);
677 (void) fprintf(stderr, "%s", ce_suffix[ce]);
683 cmn_err(int ce, const char *fmt, ...)
688 vcmn_err(ce, fmt, adx);
693 * =========================================================================
695 * =========================================================================
698 kobj_open_file(char *name)
703 /* set vp as the _fd field of the file */
704 if (vn_openat(name, UIO_SYSSPACE, FREAD, 0, &vp, 0, 0, rootdir,
706 return ((void *)-1UL);
708 file = umem_zalloc(sizeof (struct _buf), UMEM_NOFAIL);
709 file->_fd = (intptr_t)vp;
714 kobj_read_file(struct _buf *file, char *buf, unsigned size, unsigned off)
718 vn_rdwr(UIO_READ, (vnode_t *)file->_fd, buf, size, (offset_t)off,
719 UIO_SYSSPACE, 0, 0, 0, &resid);
721 return (size - resid);
725 kobj_close_file(struct _buf *file)
727 vn_close((vnode_t *)file->_fd, 0, NULL, NULL);
728 umem_free(file, sizeof (struct _buf));
732 kobj_get_filesize(struct _buf *file, uint64_t *size)
735 vnode_t *vp = (vnode_t *)file->_fd;
737 if (fstat64(vp->v_fd, &st) == -1) {
738 vn_close(vp, 0, NULL, NULL);
746 * =========================================================================
748 * =========================================================================
754 poll(0, 0, ticks * (1000 / hz));
759 * Find highest one bit set.
760 * Returns bit number + 1 of highest bit that is set, otherwise returns 0.
761 * High order bit is 31 (or 63 in _LP64 kernel).
771 if (i & 0xffffffff00000000ul) {
775 if (i & 0xffff0000) {
794 static int random_fd = -1, urandom_fd = -1;
797 random_get_bytes_common(uint8_t *ptr, size_t len, int fd)
805 bytes = read(fd, ptr, resid);
806 ASSERT3S(bytes, >=, 0);
815 random_get_bytes(uint8_t *ptr, size_t len)
817 return (random_get_bytes_common(ptr, len, random_fd));
821 random_get_pseudo_bytes(uint8_t *ptr, size_t len)
823 return (random_get_bytes_common(ptr, len, urandom_fd));
827 ddi_strtoul(const char *hw_serial, char **nptr, int base, unsigned long *result)
831 *result = strtoul(hw_serial, &end, base);
838 ddi_strtoull(const char *str, char **nptr, int base, u_longlong_t *result)
842 *result = strtoull(str, &end, base);
851 cyclic_add(cyc_handler_t *hdlr, cyc_time_t *when)
858 cyclic_remove(cyclic_id_t id)
864 cyclic_reprogram(cyclic_id_t id, hrtime_t expiration)
871 * =========================================================================
872 * kernel emulation setup & teardown
873 * =========================================================================
876 umem_out_of_memory(void)
878 char errmsg[] = "out of memory -- generating core dump\n";
880 write(fileno(stderr), errmsg, sizeof (errmsg));
886 kernel_init(int mode)
888 umem_nofail_callback(umem_out_of_memory);
890 physmem = sysconf(_SC_PHYS_PAGES);
892 dprintf("physmem = %llu pages (%.2f GB)\n", physmem,
893 (double)physmem * sysconf(_SC_PAGE_SIZE) / (1ULL << 30));
895 (void) snprintf(hw_serial, sizeof (hw_serial), "%lu",
896 (mode & FWRITE) ? (unsigned long)gethostid() : 0);
898 VERIFY((random_fd = open("/dev/random", O_RDONLY)) != -1);
899 VERIFY((urandom_fd = open("/dev/urandom", O_RDONLY)) != -1);
904 mutex_init(&cpu_lock, NULL, MUTEX_DEFAULT, NULL);
925 z_uncompress(void *dst, size_t *dstlen, const void *src, size_t srclen)
928 uLongf len = *dstlen;
930 if ((ret = uncompress(dst, &len, src, srclen)) == Z_OK)
931 *dstlen = (size_t)len;
937 z_compress_level(void *dst, size_t *dstlen, const void *src, size_t srclen,
941 uLongf len = *dstlen;
943 if ((ret = compress2(dst, &len, src, srclen, level)) == Z_OK)
944 *dstlen = (size_t)len;
962 crgetngroups(cred_t *cr)
968 crgetgroups(cred_t *cr)
974 zfs_secpolicy_snapshot_perms(const char *name, cred_t *cr)
980 zfs_secpolicy_rename_perms(const char *from, const char *to, cred_t *cr)
986 zfs_secpolicy_destroy_perms(const char *name, cred_t *cr)
992 ksid_lookupdomain(const char *dom)
996 kd = umem_zalloc(sizeof (ksiddomain_t), UMEM_NOFAIL);
997 kd->kd_name = spa_strdup(dom);
1002 ksiddomain_rele(ksiddomain_t *ksid)
1004 spa_strfree(ksid->kd_name);
1005 umem_free(ksid, sizeof (ksiddomain_t));
1009 * Do not change the length of the returned string; it must be freed
1013 kmem_asprintf(const char *fmt, ...)
1020 size = vsnprintf(NULL, 0, fmt, adx) + 1;
1023 buf = kmem_alloc(size, KM_SLEEP);
1026 size = vsnprintf(buf, size, fmt, adx);
1034 zfs_onexit_fd_hold(int fd, minor_t *minorp)
1042 zfs_onexit_fd_rele(int fd)
1048 zfs_onexit_add_cb(minor_t minor, void (*func)(void *), void *data,
1049 uint64_t *action_handle)
1056 zfs_onexit_del_cb(minor_t minor, uint64_t action_handle, boolean_t fire)
1063 zfs_onexit_cb_data(minor_t minor, uint64_t action_handle, void **data)
1071 zvol_create_minors(const char *name)