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];
50 struct utsname utsname = {
51 "userland", "libzpool", "1", "1", "na"
54 /* this only exists to have its address taken */
58 * =========================================================================
60 * =========================================================================
64 zk_thread_create(void (*func)(), void *arg)
68 VERIFY(thr_create(0, 0, (void *(*)(void *))func, arg, THR_DETACHED,
71 return ((void *)(uintptr_t)tid);
75 * =========================================================================
77 * =========================================================================
81 kstat_create(char *module, int instance, char *name, char *class,
82 uchar_t type, ulong_t ndata, uchar_t ks_flag)
89 kstat_install(kstat_t *ksp)
94 kstat_delete(kstat_t *ksp)
98 * =========================================================================
100 * =========================================================================
103 zmutex_init(kmutex_t *mp)
106 mp->initialized = B_TRUE;
107 (void) _mutex_init(&mp->m_lock, USYNC_THREAD, NULL);
111 zmutex_destroy(kmutex_t *mp)
113 ASSERT(mp->initialized == B_TRUE);
114 ASSERT(mp->m_owner == NULL);
115 (void) _mutex_destroy(&(mp)->m_lock);
116 mp->m_owner = (void *)-1UL;
117 mp->initialized = B_FALSE;
121 zmutex_owned(kmutex_t *mp)
123 ASSERT(mp->initialized == B_TRUE);
125 return (mp->m_owner == curthread);
129 mutex_enter(kmutex_t *mp)
131 ASSERT(mp->initialized == B_TRUE);
132 ASSERT(mp->m_owner != (void *)-1UL);
133 ASSERT(mp->m_owner != curthread);
134 VERIFY(mutex_lock(&mp->m_lock) == 0);
135 ASSERT(mp->m_owner == NULL);
136 mp->m_owner = curthread;
140 mutex_tryenter(kmutex_t *mp)
142 ASSERT(mp->initialized == B_TRUE);
143 ASSERT(mp->m_owner != (void *)-1UL);
144 if (0 == mutex_trylock(&mp->m_lock)) {
145 ASSERT(mp->m_owner == NULL);
146 mp->m_owner = curthread;
154 mutex_exit(kmutex_t *mp)
156 ASSERT(mp->initialized == B_TRUE);
157 ASSERT(mutex_owner(mp) == curthread);
159 VERIFY(mutex_unlock(&mp->m_lock) == 0);
163 mutex_owner(kmutex_t *mp)
165 ASSERT(mp->initialized == B_TRUE);
166 return (mp->m_owner);
170 * =========================================================================
172 * =========================================================================
176 rw_init(krwlock_t *rwlp, char *name, int type, void *arg)
178 rwlock_init(&rwlp->rw_lock, USYNC_THREAD, NULL);
179 rwlp->rw_owner = NULL;
180 rwlp->initialized = B_TRUE;
185 rw_destroy(krwlock_t *rwlp)
187 ASSERT(rwlp->rw_count == 0);
188 rwlock_destroy(&rwlp->rw_lock);
189 rwlp->rw_owner = (void *)-1UL;
190 rwlp->initialized = B_FALSE;
194 rw_enter(krwlock_t *rwlp, krw_t rw)
196 //ASSERT(!RW_LOCK_HELD(rwlp));
197 ASSERT(rwlp->initialized == B_TRUE);
198 ASSERT(rwlp->rw_owner != (void *)-1UL);
199 ASSERT(rwlp->rw_owner != curthread);
201 if (rw == RW_READER) {
202 VERIFY(rw_rdlock(&rwlp->rw_lock) == 0);
203 ASSERT(rwlp->rw_count >= 0);
204 atomic_add_int(&rwlp->rw_count, 1);
206 VERIFY(rw_wrlock(&rwlp->rw_lock) == 0);
207 ASSERT(rwlp->rw_count == 0);
209 rwlp->rw_owner = curthread;
214 rw_exit(krwlock_t *rwlp)
216 ASSERT(rwlp->initialized == B_TRUE);
217 ASSERT(rwlp->rw_owner != (void *)-1UL);
219 if (rwlp->rw_owner == curthread) {
221 ASSERT(rwlp->rw_count == -1);
223 rwlp->rw_owner = NULL;
226 ASSERT(rwlp->rw_count > 0);
227 atomic_add_int(&rwlp->rw_count, -1);
229 VERIFY(rw_unlock(&rwlp->rw_lock) == 0);
233 rw_tryenter(krwlock_t *rwlp, krw_t rw)
237 ASSERT(rwlp->initialized == B_TRUE);
238 ASSERT(rwlp->rw_owner != (void *)-1UL);
239 ASSERT(rwlp->rw_owner != curthread);
242 rv = rw_tryrdlock(&rwlp->rw_lock);
244 rv = rw_trywrlock(&rwlp->rw_lock);
247 ASSERT(rwlp->rw_owner == NULL);
248 if (rw == RW_READER) {
249 ASSERT(rwlp->rw_count >= 0);
250 atomic_add_int(&rwlp->rw_count, 1);
252 ASSERT(rwlp->rw_count == 0);
254 rwlp->rw_owner = curthread;
264 rw_tryupgrade(krwlock_t *rwlp)
266 ASSERT(rwlp->initialized == B_TRUE);
267 ASSERT(rwlp->rw_owner != (void *)-1UL);
273 rw_lock_held(krwlock_t *rwlp)
276 return (rwlp->rw_count != 0);
280 * =========================================================================
281 * condition variables
282 * =========================================================================
286 cv_init(kcondvar_t *cv, char *name, int type, void *arg)
288 VERIFY(cond_init(cv, name, NULL) == 0);
292 cv_destroy(kcondvar_t *cv)
294 VERIFY(cond_destroy(cv) == 0);
298 cv_wait(kcondvar_t *cv, kmutex_t *mp)
300 ASSERT(mutex_owner(mp) == curthread);
302 int ret = cond_wait(cv, &mp->m_lock);
303 VERIFY(ret == 0 || ret == EINTR);
304 mp->m_owner = curthread;
308 cv_timedwait(kcondvar_t *cv, kmutex_t *mp, clock_t abstime)
315 abstime += ddi_get_lbolt();
317 delta = abstime - ddi_get_lbolt();
321 if (gettimeofday(&tv, NULL) != 0)
322 assert(!"gettimeofday() failed");
324 ts.tv_sec = tv.tv_sec + delta / hz;
325 ts.tv_nsec = tv.tv_usec * 1000 + (delta % hz) * (NANOSEC / hz);
326 ASSERT(ts.tv_nsec >= 0);
328 if (ts.tv_nsec >= NANOSEC) {
330 ts.tv_nsec -= NANOSEC;
333 ASSERT(mutex_owner(mp) == curthread);
335 error = pthread_cond_timedwait(cv, &mp->m_lock, &ts);
336 mp->m_owner = curthread;
341 if (error == ETIMEDOUT)
351 cv_timedwait_hires(kcondvar_t *cv, kmutex_t *mp, hrtime_t tim, hrtime_t res,
361 delta = tim - gethrtime();
365 ts.tv_sec = delta / NANOSEC;
366 ts.tv_nsec = delta % NANOSEC;
368 ASSERT(mutex_owner(mp) == curthread);
370 error = pthread_cond_timedwait(cv, &mp->m_lock, &ts);
371 mp->m_owner = curthread;
373 if (error == ETIMEDOUT)
385 cv_signal(kcondvar_t *cv)
387 VERIFY(cond_signal(cv) == 0);
391 cv_broadcast(kcondvar_t *cv)
393 VERIFY(cond_broadcast(cv) == 0);
397 * =========================================================================
399 * =========================================================================
402 * Note: for the xxxat() versions of these functions, we assume that the
403 * starting vp is always rootdir (which is true for spa_directory.c, the only
404 * ZFS consumer of these interfaces). We assert this is true, and then emulate
405 * them by adding '/' in front of the path.
410 vn_open(char *path, int x1, int flags, int mode, vnode_t **vpp, int x2, int x3)
415 char realpath[MAXPATHLEN];
419 * If we're accessing a real disk from userland, we need to use
420 * the character interface to avoid caching. This is particularly
421 * important if we're trying to look at a real in-kernel storage
422 * pool from userland, e.g. via zdb, because otherwise we won't
423 * see the changes occurring under the segmap cache.
424 * On the other hand, the stupid character device returns zero
425 * for its size. So -- gag -- we open the block device to get
426 * its size, and remember it for subsequent VOP_GETATTR().
428 if (strncmp(path, "/dev/", 5) == 0) {
430 fd = open64(path, O_RDONLY);
433 if (fstat64(fd, &st) == -1) {
438 (void) sprintf(realpath, "%s", path);
439 dsk = strstr(path, "/dsk/");
441 (void) sprintf(realpath + (dsk - path) + 1, "r%s",
444 (void) sprintf(realpath, "%s", path);
445 if (!(flags & FCREAT) && stat64(realpath, &st) == -1)
450 old_umask = umask(0);
453 * The construct 'flags - FREAD' conveniently maps combinations of
454 * FREAD and FWRITE to the corresponding O_RDONLY, O_WRONLY, and O_RDWR.
456 fd = open64(realpath, flags - FREAD, mode);
459 (void) umask(old_umask);
464 if (fstat64(fd, &st) == -1) {
469 (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
471 *vpp = vp = umem_zalloc(sizeof (vnode_t), UMEM_NOFAIL);
474 vp->v_size = st.st_size;
475 vp->v_path = spa_strdup(path);
482 vn_openat(char *path, int x1, int flags, int mode, vnode_t **vpp, int x2,
483 int x3, vnode_t *startvp, int fd)
485 char *realpath = umem_alloc(strlen(path) + 2, UMEM_NOFAIL);
488 ASSERT(startvp == rootdir);
489 (void) sprintf(realpath, "/%s", path);
491 /* fd ignored for now, need if want to simulate nbmand support */
492 ret = vn_open(realpath, x1, flags, mode, vpp, x2, x3);
494 umem_free(realpath, strlen(path) + 2);
501 vn_rdwr(int uio, vnode_t *vp, void *addr, ssize_t len, offset_t offset,
502 int x1, int x2, rlim64_t x3, void *x4, ssize_t *residp)
504 ssize_t iolen, split;
506 if (uio == UIO_READ) {
507 iolen = pread64(vp->v_fd, addr, len, offset);
510 * To simulate partial disk writes, we split writes into two
511 * system calls so that the process can be killed in between.
513 int sectors = len >> SPA_MINBLOCKSHIFT;
514 split = (sectors > 0 ? rand() % sectors : 0) <<
516 iolen = pwrite64(vp->v_fd, addr, split, offset);
517 iolen += pwrite64(vp->v_fd, (char *)addr + split,
518 len - split, offset + split);
524 *residp = len - iolen;
525 else if (iolen != len)
531 vn_close(vnode_t *vp, int openflag, cred_t *cr, kthread_t *td)
534 spa_strfree(vp->v_path);
535 umem_free(vp, sizeof (vnode_t));
539 * At a minimum we need to update the size since vdev_reopen()
540 * will no longer call vn_openat().
543 fop_getattr(vnode_t *vp, vattr_t *vap)
547 if (fstat64(vp->v_fd, &st) == -1) {
552 vap->va_size = st.st_size;
559 * =========================================================================
560 * Figure out which debugging statements to print
561 * =========================================================================
564 static char *dprintf_string;
565 static int dprintf_print_all;
568 dprintf_find_string(const char *string)
570 char *tmp_str = dprintf_string;
571 int len = strlen(string);
574 * Find out if this is a string we want to print.
575 * String format: file1.c,function_name1,file2.c,file3.c
578 while (tmp_str != NULL) {
579 if (strncmp(tmp_str, string, len) == 0 &&
580 (tmp_str[len] == ',' || tmp_str[len] == '\0'))
582 tmp_str = strchr(tmp_str, ',');
584 tmp_str++; /* Get rid of , */
590 dprintf_setup(int *argc, char **argv)
595 * Debugging can be specified two ways: by setting the
596 * environment variable ZFS_DEBUG, or by including a
597 * "debug=..." argument on the command line. The command
598 * line setting overrides the environment variable.
601 for (i = 1; i < *argc; i++) {
602 int len = strlen("debug=");
603 /* First look for a command line argument */
604 if (strncmp("debug=", argv[i], len) == 0) {
605 dprintf_string = argv[i] + len;
606 /* Remove from args */
607 for (j = i; j < *argc; j++)
614 if (dprintf_string == NULL) {
615 /* Look for ZFS_DEBUG environment variable */
616 dprintf_string = getenv("ZFS_DEBUG");
620 * Are we just turning on all debugging?
622 if (dprintf_find_string("on"))
623 dprintf_print_all = 1;
627 sysctl_handle_64(SYSCTL_HANDLER_ARGS)
633 * =========================================================================
635 * =========================================================================
638 __dprintf(const char *file, const char *func, int line, const char *fmt, ...)
644 * Get rid of annoying "../common/" prefix to filename.
646 newfile = strrchr(file, '/');
647 if (newfile != NULL) {
648 newfile = newfile + 1; /* Get rid of leading / */
653 if (dprintf_print_all ||
654 dprintf_find_string(newfile) ||
655 dprintf_find_string(func)) {
656 /* Print out just the function name if requested */
658 if (dprintf_find_string("pid"))
659 (void) printf("%d ", getpid());
660 if (dprintf_find_string("tid"))
661 (void) printf("%ul ", thr_self());
663 if (dprintf_find_string("cpu"))
664 (void) printf("%u ", getcpuid());
666 if (dprintf_find_string("time"))
667 (void) printf("%llu ", gethrtime());
668 if (dprintf_find_string("long"))
669 (void) printf("%s, line %d: ", newfile, line);
670 (void) printf("%s: ", func);
672 (void) vprintf(fmt, adx);
678 #endif /* ZFS_DEBUG */
681 * =========================================================================
682 * cmn_err() and panic()
683 * =========================================================================
685 static char ce_prefix[CE_IGNORE][10] = { "", "NOTICE: ", "WARNING: ", "" };
686 static char ce_suffix[CE_IGNORE][2] = { "", "\n", "\n", "" };
689 vpanic(const char *fmt, va_list adx)
691 (void) fprintf(stderr, "error: ");
692 (void) vfprintf(stderr, fmt, adx);
693 (void) fprintf(stderr, "\n");
695 abort(); /* think of it as a "user-level crash dump" */
699 panic(const char *fmt, ...)
709 vcmn_err(int ce, const char *fmt, va_list adx)
713 if (ce != CE_NOTE) { /* suppress noise in userland stress testing */
714 (void) fprintf(stderr, "%s", ce_prefix[ce]);
715 (void) vfprintf(stderr, fmt, adx);
716 (void) fprintf(stderr, "%s", ce_suffix[ce]);
722 cmn_err(int ce, const char *fmt, ...)
727 vcmn_err(ce, fmt, adx);
732 * =========================================================================
734 * =========================================================================
737 kobj_open_file(char *name)
742 /* set vp as the _fd field of the file */
743 if (vn_openat(name, UIO_SYSSPACE, FREAD, 0, &vp, 0, 0, rootdir,
745 return ((void *)-1UL);
747 file = umem_zalloc(sizeof (struct _buf), UMEM_NOFAIL);
748 file->_fd = (intptr_t)vp;
753 kobj_read_file(struct _buf *file, char *buf, unsigned size, unsigned off)
757 vn_rdwr(UIO_READ, (vnode_t *)file->_fd, buf, size, (offset_t)off,
758 UIO_SYSSPACE, 0, 0, 0, &resid);
760 return (size - resid);
764 kobj_close_file(struct _buf *file)
766 vn_close((vnode_t *)file->_fd, 0, NULL, NULL);
767 umem_free(file, sizeof (struct _buf));
771 kobj_get_filesize(struct _buf *file, uint64_t *size)
774 vnode_t *vp = (vnode_t *)file->_fd;
776 if (fstat64(vp->v_fd, &st) == -1) {
777 vn_close(vp, 0, NULL, NULL);
785 * =========================================================================
787 * =========================================================================
793 poll(0, 0, ticks * (1000 / hz));
798 * Find highest one bit set.
799 * Returns bit number + 1 of highest bit that is set, otherwise returns 0.
800 * High order bit is 31 (or 63 in _LP64 kernel).
810 if (i & 0xffffffff00000000ul) {
814 if (i & 0xffff0000) {
833 static int random_fd = -1, urandom_fd = -1;
836 random_get_bytes_common(uint8_t *ptr, size_t len, int fd)
844 bytes = read(fd, ptr, resid);
845 ASSERT3S(bytes, >=, 0);
854 random_get_bytes(uint8_t *ptr, size_t len)
856 return (random_get_bytes_common(ptr, len, random_fd));
860 random_get_pseudo_bytes(uint8_t *ptr, size_t len)
862 return (random_get_bytes_common(ptr, len, urandom_fd));
866 ddi_strtoul(const char *hw_serial, char **nptr, int base, unsigned long *result)
870 *result = strtoul(hw_serial, &end, base);
877 ddi_strtoull(const char *str, char **nptr, int base, u_longlong_t *result)
881 *result = strtoull(str, &end, base);
888 * =========================================================================
889 * kernel emulation setup & teardown
890 * =========================================================================
893 umem_out_of_memory(void)
895 char errmsg[] = "out of memory -- generating core dump\n";
897 write(fileno(stderr), errmsg, sizeof (errmsg));
903 kernel_init(int mode)
905 extern uint_t rrw_tsd_key;
907 umem_nofail_callback(umem_out_of_memory);
909 physmem = sysconf(_SC_PHYS_PAGES);
911 dprintf("physmem = %llu pages (%.2f GB)\n", physmem,
912 (double)physmem * sysconf(_SC_PAGE_SIZE) / (1ULL << 30));
914 (void) snprintf(hw_serial, sizeof (hw_serial), "%lu",
915 (mode & FWRITE) ? (unsigned long)gethostid() : 0);
917 VERIFY((random_fd = open("/dev/random", O_RDONLY)) != -1);
918 VERIFY((urandom_fd = open("/dev/urandom", O_RDONLY)) != -1);
924 tsd_create(&rrw_tsd_key, rrw_tsd_destroy);
942 z_uncompress(void *dst, size_t *dstlen, const void *src, size_t srclen)
945 uLongf len = *dstlen;
947 if ((ret = uncompress(dst, &len, src, srclen)) == Z_OK)
948 *dstlen = (size_t)len;
954 z_compress_level(void *dst, size_t *dstlen, const void *src, size_t srclen,
958 uLongf len = *dstlen;
960 if ((ret = compress2(dst, &len, src, srclen, level)) == Z_OK)
961 *dstlen = (size_t)len;
973 crgetruid(cred_t *cr)
985 crgetngroups(cred_t *cr)
991 crgetgroups(cred_t *cr)
997 zfs_secpolicy_snapshot_perms(const char *name, cred_t *cr)
1003 zfs_secpolicy_rename_perms(const char *from, const char *to, cred_t *cr)
1009 zfs_secpolicy_destroy_perms(const char *name, cred_t *cr)
1015 ksid_lookupdomain(const char *dom)
1019 kd = umem_zalloc(sizeof (ksiddomain_t), UMEM_NOFAIL);
1020 kd->kd_name = spa_strdup(dom);
1025 ksiddomain_rele(ksiddomain_t *ksid)
1027 spa_strfree(ksid->kd_name);
1028 umem_free(ksid, sizeof (ksiddomain_t));
1032 * Do not change the length of the returned string; it must be freed
1036 kmem_asprintf(const char *fmt, ...)
1043 size = vsnprintf(NULL, 0, fmt, adx) + 1;
1046 buf = kmem_alloc(size, KM_SLEEP);
1049 size = vsnprintf(buf, size, fmt, adx);
1057 zfs_onexit_fd_hold(int fd, minor_t *minorp)
1065 zfs_onexit_fd_rele(int fd)
1071 zfs_onexit_add_cb(minor_t minor, void (*func)(void *), void *data,
1072 uint64_t *action_handle)
1079 zfs_onexit_del_cb(minor_t minor, uint64_t action_handle, boolean_t fire)
1086 zfs_onexit_cb_data(minor_t minor, uint64_t action_handle, void **data)
1094 zvol_create_minors(const char *name)
1104 bzero(bp, sizeof (buf_t));
1110 if (bp->b_iodone != NULL) {
1111 (*(bp->b_iodone))(bp);
1114 ASSERT((bp->b_flags & B_DONE) == 0);
1115 bp->b_flags |= B_DONE;
1119 bioerror(buf_t *bp, int error)
1125 bp->b_flags |= B_ERROR;
1127 bp->b_flags &= ~B_ERROR;
1129 bp->b_error = error;
1134 geterror(struct buf *bp)
1138 if (bp->b_flags & B_ERROR) {
1139 error = bp->b_error;