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)
353 cv_signal(kcondvar_t *cv)
355 VERIFY(cond_signal(cv) == 0);
359 cv_broadcast(kcondvar_t *cv)
361 VERIFY(cond_broadcast(cv) == 0);
365 * =========================================================================
367 * =========================================================================
370 * Note: for the xxxat() versions of these functions, we assume that the
371 * starting vp is always rootdir (which is true for spa_directory.c, the only
372 * ZFS consumer of these interfaces). We assert this is true, and then emulate
373 * them by adding '/' in front of the path.
378 vn_open(char *path, int x1, int flags, int mode, vnode_t **vpp, int x2, int x3)
383 char realpath[MAXPATHLEN];
387 * If we're accessing a real disk from userland, we need to use
388 * the character interface to avoid caching. This is particularly
389 * important if we're trying to look at a real in-kernel storage
390 * pool from userland, e.g. via zdb, because otherwise we won't
391 * see the changes occurring under the segmap cache.
392 * On the other hand, the stupid character device returns zero
393 * for its size. So -- gag -- we open the block device to get
394 * its size, and remember it for subsequent VOP_GETATTR().
396 if (strncmp(path, "/dev/", 5) == 0) {
398 fd = open64(path, O_RDONLY);
401 if (fstat64(fd, &st) == -1) {
406 (void) sprintf(realpath, "%s", path);
407 dsk = strstr(path, "/dsk/");
409 (void) sprintf(realpath + (dsk - path) + 1, "r%s",
412 (void) sprintf(realpath, "%s", path);
413 if (!(flags & FCREAT) && stat64(realpath, &st) == -1)
418 old_umask = umask(0);
421 * The construct 'flags - FREAD' conveniently maps combinations of
422 * FREAD and FWRITE to the corresponding O_RDONLY, O_WRONLY, and O_RDWR.
424 fd = open64(realpath, flags - FREAD, mode);
427 (void) umask(old_umask);
432 if (fstat64(fd, &st) == -1) {
437 (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
439 *vpp = vp = umem_zalloc(sizeof (vnode_t), UMEM_NOFAIL);
442 vp->v_size = st.st_size;
443 vp->v_path = spa_strdup(path);
450 vn_openat(char *path, int x1, int flags, int mode, vnode_t **vpp, int x2,
451 int x3, vnode_t *startvp, int fd)
453 char *realpath = umem_alloc(strlen(path) + 2, UMEM_NOFAIL);
456 ASSERT(startvp == rootdir);
457 (void) sprintf(realpath, "/%s", path);
459 /* fd ignored for now, need if want to simulate nbmand support */
460 ret = vn_open(realpath, x1, flags, mode, vpp, x2, x3);
462 umem_free(realpath, strlen(path) + 2);
469 vn_rdwr(int uio, vnode_t *vp, void *addr, ssize_t len, offset_t offset,
470 int x1, int x2, rlim64_t x3, void *x4, ssize_t *residp)
472 ssize_t iolen, split;
474 if (uio == UIO_READ) {
475 iolen = pread64(vp->v_fd, addr, len, offset);
478 * To simulate partial disk writes, we split writes into two
479 * system calls so that the process can be killed in between.
481 int sectors = len >> SPA_MINBLOCKSHIFT;
482 split = (sectors > 0 ? rand() % sectors : 0) <<
484 iolen = pwrite64(vp->v_fd, addr, split, offset);
485 iolen += pwrite64(vp->v_fd, (char *)addr + split,
486 len - split, offset + split);
492 *residp = len - iolen;
493 else if (iolen != len)
499 vn_close(vnode_t *vp, int openflag, cred_t *cr, kthread_t *td)
502 spa_strfree(vp->v_path);
503 umem_free(vp, sizeof (vnode_t));
507 * At a minimum we need to update the size since vdev_reopen()
508 * will no longer call vn_openat().
511 fop_getattr(vnode_t *vp, vattr_t *vap)
515 if (fstat64(vp->v_fd, &st) == -1) {
520 vap->va_size = st.st_size;
527 * =========================================================================
528 * Figure out which debugging statements to print
529 * =========================================================================
532 static char *dprintf_string;
533 static int dprintf_print_all;
536 dprintf_find_string(const char *string)
538 char *tmp_str = dprintf_string;
539 int len = strlen(string);
542 * Find out if this is a string we want to print.
543 * String format: file1.c,function_name1,file2.c,file3.c
546 while (tmp_str != NULL) {
547 if (strncmp(tmp_str, string, len) == 0 &&
548 (tmp_str[len] == ',' || tmp_str[len] == '\0'))
550 tmp_str = strchr(tmp_str, ',');
552 tmp_str++; /* Get rid of , */
558 dprintf_setup(int *argc, char **argv)
563 * Debugging can be specified two ways: by setting the
564 * environment variable ZFS_DEBUG, or by including a
565 * "debug=..." argument on the command line. The command
566 * line setting overrides the environment variable.
569 for (i = 1; i < *argc; i++) {
570 int len = strlen("debug=");
571 /* First look for a command line argument */
572 if (strncmp("debug=", argv[i], len) == 0) {
573 dprintf_string = argv[i] + len;
574 /* Remove from args */
575 for (j = i; j < *argc; j++)
582 if (dprintf_string == NULL) {
583 /* Look for ZFS_DEBUG environment variable */
584 dprintf_string = getenv("ZFS_DEBUG");
588 * Are we just turning on all debugging?
590 if (dprintf_find_string("on"))
591 dprintf_print_all = 1;
595 * =========================================================================
597 * =========================================================================
600 __dprintf(const char *file, const char *func, int line, const char *fmt, ...)
606 * Get rid of annoying "../common/" prefix to filename.
608 newfile = strrchr(file, '/');
609 if (newfile != NULL) {
610 newfile = newfile + 1; /* Get rid of leading / */
615 if (dprintf_print_all ||
616 dprintf_find_string(newfile) ||
617 dprintf_find_string(func)) {
618 /* Print out just the function name if requested */
620 if (dprintf_find_string("pid"))
621 (void) printf("%d ", getpid());
622 if (dprintf_find_string("tid"))
623 (void) printf("%u ", thr_self());
625 if (dprintf_find_string("cpu"))
626 (void) printf("%u ", getcpuid());
628 if (dprintf_find_string("time"))
629 (void) printf("%llu ", gethrtime());
630 if (dprintf_find_string("long"))
631 (void) printf("%s, line %d: ", newfile, line);
632 (void) printf("%s: ", func);
634 (void) vprintf(fmt, adx);
640 #endif /* ZFS_DEBUG */
643 * =========================================================================
644 * cmn_err() and panic()
645 * =========================================================================
647 static char ce_prefix[CE_IGNORE][10] = { "", "NOTICE: ", "WARNING: ", "" };
648 static char ce_suffix[CE_IGNORE][2] = { "", "\n", "\n", "" };
651 vpanic(const char *fmt, va_list adx)
653 (void) fprintf(stderr, "error: ");
654 (void) vfprintf(stderr, fmt, adx);
655 (void) fprintf(stderr, "\n");
657 abort(); /* think of it as a "user-level crash dump" */
661 panic(const char *fmt, ...)
671 vcmn_err(int ce, const char *fmt, va_list adx)
675 if (ce != CE_NOTE) { /* suppress noise in userland stress testing */
676 (void) fprintf(stderr, "%s", ce_prefix[ce]);
677 (void) vfprintf(stderr, fmt, adx);
678 (void) fprintf(stderr, "%s", ce_suffix[ce]);
684 cmn_err(int ce, const char *fmt, ...)
689 vcmn_err(ce, fmt, adx);
694 * =========================================================================
696 * =========================================================================
699 kobj_open_file(char *name)
704 /* set vp as the _fd field of the file */
705 if (vn_openat(name, UIO_SYSSPACE, FREAD, 0, &vp, 0, 0, rootdir,
707 return ((void *)-1UL);
709 file = umem_zalloc(sizeof (struct _buf), UMEM_NOFAIL);
710 file->_fd = (intptr_t)vp;
715 kobj_read_file(struct _buf *file, char *buf, unsigned size, unsigned off)
719 vn_rdwr(UIO_READ, (vnode_t *)file->_fd, buf, size, (offset_t)off,
720 UIO_SYSSPACE, 0, 0, 0, &resid);
722 return (size - resid);
726 kobj_close_file(struct _buf *file)
728 vn_close((vnode_t *)file->_fd, 0, NULL, NULL);
729 umem_free(file, sizeof (struct _buf));
733 kobj_get_filesize(struct _buf *file, uint64_t *size)
736 vnode_t *vp = (vnode_t *)file->_fd;
738 if (fstat64(vp->v_fd, &st) == -1) {
739 vn_close(vp, 0, NULL, NULL);
747 * =========================================================================
749 * =========================================================================
755 poll(0, 0, ticks * (1000 / hz));
760 * Find highest one bit set.
761 * Returns bit number + 1 of highest bit that is set, otherwise returns 0.
762 * High order bit is 31 (or 63 in _LP64 kernel).
772 if (i & 0xffffffff00000000ul) {
776 if (i & 0xffff0000) {
795 static int random_fd = -1, urandom_fd = -1;
798 random_get_bytes_common(uint8_t *ptr, size_t len, int fd)
806 bytes = read(fd, ptr, resid);
807 ASSERT3S(bytes, >=, 0);
816 random_get_bytes(uint8_t *ptr, size_t len)
818 return (random_get_bytes_common(ptr, len, random_fd));
822 random_get_pseudo_bytes(uint8_t *ptr, size_t len)
824 return (random_get_bytes_common(ptr, len, urandom_fd));
828 ddi_strtoul(const char *hw_serial, char **nptr, int base, unsigned long *result)
832 *result = strtoul(hw_serial, &end, base);
839 ddi_strtoull(const char *str, char **nptr, int base, u_longlong_t *result)
843 *result = strtoull(str, &end, base);
852 cyclic_add(cyc_handler_t *hdlr, cyc_time_t *when)
859 cyclic_remove(cyclic_id_t id)
865 cyclic_reprogram(cyclic_id_t id, hrtime_t expiration)
872 * =========================================================================
873 * kernel emulation setup & teardown
874 * =========================================================================
877 umem_out_of_memory(void)
879 char errmsg[] = "out of memory -- generating core dump\n";
881 write(fileno(stderr), errmsg, sizeof (errmsg));
887 kernel_init(int mode)
889 extern uint_t rrw_tsd_key;
891 umem_nofail_callback(umem_out_of_memory);
893 physmem = sysconf(_SC_PHYS_PAGES);
895 dprintf("physmem = %llu pages (%.2f GB)\n", physmem,
896 (double)physmem * sysconf(_SC_PAGE_SIZE) / (1ULL << 30));
898 (void) snprintf(hw_serial, sizeof (hw_serial), "%lu",
899 (mode & FWRITE) ? (unsigned long)gethostid() : 0);
901 VERIFY((random_fd = open("/dev/random", O_RDONLY)) != -1);
902 VERIFY((urandom_fd = open("/dev/urandom", O_RDONLY)) != -1);
907 mutex_init(&cpu_lock, NULL, MUTEX_DEFAULT, NULL);
912 tsd_create(&rrw_tsd_key, rrw_tsd_destroy);
930 z_uncompress(void *dst, size_t *dstlen, const void *src, size_t srclen)
933 uLongf len = *dstlen;
935 if ((ret = uncompress(dst, &len, src, srclen)) == Z_OK)
936 *dstlen = (size_t)len;
942 z_compress_level(void *dst, size_t *dstlen, const void *src, size_t srclen,
946 uLongf len = *dstlen;
948 if ((ret = compress2(dst, &len, src, srclen, level)) == Z_OK)
949 *dstlen = (size_t)len;
961 crgetruid(cred_t *cr)
973 crgetngroups(cred_t *cr)
979 crgetgroups(cred_t *cr)
985 zfs_secpolicy_snapshot_perms(const char *name, cred_t *cr)
991 zfs_secpolicy_rename_perms(const char *from, const char *to, cred_t *cr)
997 zfs_secpolicy_destroy_perms(const char *name, cred_t *cr)
1003 ksid_lookupdomain(const char *dom)
1007 kd = umem_zalloc(sizeof (ksiddomain_t), UMEM_NOFAIL);
1008 kd->kd_name = spa_strdup(dom);
1013 ksiddomain_rele(ksiddomain_t *ksid)
1015 spa_strfree(ksid->kd_name);
1016 umem_free(ksid, sizeof (ksiddomain_t));
1020 * Do not change the length of the returned string; it must be freed
1024 kmem_asprintf(const char *fmt, ...)
1031 size = vsnprintf(NULL, 0, fmt, adx) + 1;
1034 buf = kmem_alloc(size, KM_SLEEP);
1037 size = vsnprintf(buf, size, fmt, adx);
1045 zfs_onexit_fd_hold(int fd, minor_t *minorp)
1053 zfs_onexit_fd_rele(int fd)
1059 zfs_onexit_add_cb(minor_t minor, void (*func)(void *), void *data,
1060 uint64_t *action_handle)
1067 zfs_onexit_del_cb(minor_t minor, uint64_t action_handle, boolean_t fire)
1074 zfs_onexit_cb_data(minor_t minor, uint64_t action_handle, void **data)
1082 zvol_create_minors(const char *name)