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.
23 * Copyright (c) 2012, 2014 by Delphix. All rights reserved.
24 * Copyright (c) 2013, Joyent, Inc. All rights reserved.
36 #include <sys/processor.h>
37 #include <sys/zfs_context.h>
38 #include <sys/rrwlock.h>
40 #include <sys/utsname.h>
41 #include <sys/systeminfo.h>
44 * Emulation of kernel services in userland.
51 vnode_t *rootdir = (vnode_t *)0xabcd1234;
52 char hw_serial[HW_HOSTID_LEN];
57 struct utsname utsname = {
58 "userland", "libzpool", "1", "1", "na"
61 /* this only exists to have its address taken */
65 * =========================================================================
67 * =========================================================================
71 zk_thread_create(void (*func)(), void *arg)
75 VERIFY(thr_create(0, 0, (void *(*)(void *))func, arg, THR_DETACHED,
78 return ((void *)(uintptr_t)tid);
82 * =========================================================================
84 * =========================================================================
88 kstat_create(char *module, int instance, char *name, char *class,
89 uchar_t type, ulong_t ndata, uchar_t ks_flag)
96 kstat_install(kstat_t *ksp)
101 kstat_delete(kstat_t *ksp)
105 * =========================================================================
107 * =========================================================================
110 zmutex_init(kmutex_t *mp)
113 mp->initialized = B_TRUE;
114 (void) _mutex_init(&mp->m_lock, USYNC_THREAD, NULL);
118 zmutex_destroy(kmutex_t *mp)
120 ASSERT(mp->initialized == B_TRUE);
121 ASSERT(mp->m_owner == NULL);
122 (void) _mutex_destroy(&(mp)->m_lock);
123 mp->m_owner = (void *)-1UL;
124 mp->initialized = B_FALSE;
128 zmutex_owned(kmutex_t *mp)
130 ASSERT(mp->initialized == B_TRUE);
132 return (mp->m_owner == curthread);
136 mutex_enter(kmutex_t *mp)
138 ASSERT(mp->initialized == B_TRUE);
139 ASSERT(mp->m_owner != (void *)-1UL);
140 ASSERT(mp->m_owner != curthread);
141 VERIFY(mutex_lock(&mp->m_lock) == 0);
142 ASSERT(mp->m_owner == NULL);
143 mp->m_owner = curthread;
147 mutex_tryenter(kmutex_t *mp)
149 ASSERT(mp->initialized == B_TRUE);
150 ASSERT(mp->m_owner != (void *)-1UL);
151 if (0 == mutex_trylock(&mp->m_lock)) {
152 ASSERT(mp->m_owner == NULL);
153 mp->m_owner = curthread;
161 mutex_exit(kmutex_t *mp)
163 ASSERT(mp->initialized == B_TRUE);
164 ASSERT(mutex_owner(mp) == curthread);
166 VERIFY(mutex_unlock(&mp->m_lock) == 0);
170 mutex_owner(kmutex_t *mp)
172 ASSERT(mp->initialized == B_TRUE);
173 return (mp->m_owner);
177 * =========================================================================
179 * =========================================================================
183 rw_init(krwlock_t *rwlp, char *name, int type, void *arg)
185 rwlock_init(&rwlp->rw_lock, USYNC_THREAD, NULL);
186 rwlp->rw_owner = NULL;
187 rwlp->initialized = B_TRUE;
192 rw_destroy(krwlock_t *rwlp)
194 ASSERT(rwlp->rw_count == 0);
195 rwlock_destroy(&rwlp->rw_lock);
196 rwlp->rw_owner = (void *)-1UL;
197 rwlp->initialized = B_FALSE;
201 rw_enter(krwlock_t *rwlp, krw_t rw)
203 //ASSERT(!RW_LOCK_HELD(rwlp));
204 ASSERT(rwlp->initialized == B_TRUE);
205 ASSERT(rwlp->rw_owner != (void *)-1UL);
206 ASSERT(rwlp->rw_owner != curthread);
208 if (rw == RW_READER) {
209 VERIFY(rw_rdlock(&rwlp->rw_lock) == 0);
210 ASSERT(rwlp->rw_count >= 0);
211 atomic_add_int(&rwlp->rw_count, 1);
213 VERIFY(rw_wrlock(&rwlp->rw_lock) == 0);
214 ASSERT(rwlp->rw_count == 0);
216 rwlp->rw_owner = curthread;
221 rw_exit(krwlock_t *rwlp)
223 ASSERT(rwlp->initialized == B_TRUE);
224 ASSERT(rwlp->rw_owner != (void *)-1UL);
226 if (rwlp->rw_owner == curthread) {
228 ASSERT(rwlp->rw_count == -1);
230 rwlp->rw_owner = NULL;
233 ASSERT(rwlp->rw_count > 0);
234 atomic_add_int(&rwlp->rw_count, -1);
236 VERIFY(rw_unlock(&rwlp->rw_lock) == 0);
240 rw_tryenter(krwlock_t *rwlp, krw_t rw)
244 ASSERT(rwlp->initialized == B_TRUE);
245 ASSERT(rwlp->rw_owner != (void *)-1UL);
246 ASSERT(rwlp->rw_owner != curthread);
249 rv = rw_tryrdlock(&rwlp->rw_lock);
251 rv = rw_trywrlock(&rwlp->rw_lock);
254 ASSERT(rwlp->rw_owner == NULL);
255 if (rw == RW_READER) {
256 ASSERT(rwlp->rw_count >= 0);
257 atomic_add_int(&rwlp->rw_count, 1);
259 ASSERT(rwlp->rw_count == 0);
261 rwlp->rw_owner = curthread;
271 rw_tryupgrade(krwlock_t *rwlp)
273 ASSERT(rwlp->initialized == B_TRUE);
274 ASSERT(rwlp->rw_owner != (void *)-1UL);
280 rw_lock_held(krwlock_t *rwlp)
283 return (rwlp->rw_count != 0);
287 * =========================================================================
288 * condition variables
289 * =========================================================================
293 cv_init(kcondvar_t *cv, char *name, int type, void *arg)
295 VERIFY(cond_init(cv, name, NULL) == 0);
299 cv_destroy(kcondvar_t *cv)
301 VERIFY(cond_destroy(cv) == 0);
305 cv_wait(kcondvar_t *cv, kmutex_t *mp)
307 ASSERT(mutex_owner(mp) == curthread);
309 int ret = cond_wait(cv, &mp->m_lock);
310 VERIFY(ret == 0 || ret == EINTR);
311 mp->m_owner = curthread;
315 cv_timedwait(kcondvar_t *cv, kmutex_t *mp, clock_t abstime)
322 abstime += ddi_get_lbolt();
324 delta = abstime - ddi_get_lbolt();
328 if (gettimeofday(&tv, NULL) != 0)
329 assert(!"gettimeofday() failed");
331 ts.tv_sec = tv.tv_sec + delta / hz;
332 ts.tv_nsec = tv.tv_usec * 1000 + (delta % hz) * (NANOSEC / hz);
333 ASSERT(ts.tv_nsec >= 0);
335 if (ts.tv_nsec >= NANOSEC) {
337 ts.tv_nsec -= NANOSEC;
340 ASSERT(mutex_owner(mp) == curthread);
342 error = pthread_cond_timedwait(cv, &mp->m_lock, &ts);
343 mp->m_owner = curthread;
348 if (error == ETIMEDOUT)
358 cv_timedwait_hires(kcondvar_t *cv, kmutex_t *mp, hrtime_t tim, hrtime_t res,
368 delta = tim - gethrtime();
372 ts.tv_sec = delta / NANOSEC;
373 ts.tv_nsec = delta % NANOSEC;
375 ASSERT(mutex_owner(mp) == curthread);
377 error = pthread_cond_timedwait(cv, &mp->m_lock, &ts);
378 mp->m_owner = curthread;
380 if (error == ETIMEDOUT)
392 cv_signal(kcondvar_t *cv)
394 VERIFY(cond_signal(cv) == 0);
398 cv_broadcast(kcondvar_t *cv)
400 VERIFY(cond_broadcast(cv) == 0);
404 * =========================================================================
406 * =========================================================================
409 * Note: for the xxxat() versions of these functions, we assume that the
410 * starting vp is always rootdir (which is true for spa_directory.c, the only
411 * ZFS consumer of these interfaces). We assert this is true, and then emulate
412 * them by adding '/' in front of the path.
417 vn_open(char *path, int x1, int flags, int mode, vnode_t **vpp, int x2, int x3)
422 char realpath[MAXPATHLEN];
426 * If we're accessing a real disk from userland, we need to use
427 * the character interface to avoid caching. This is particularly
428 * important if we're trying to look at a real in-kernel storage
429 * pool from userland, e.g. via zdb, because otherwise we won't
430 * see the changes occurring under the segmap cache.
431 * On the other hand, the stupid character device returns zero
432 * for its size. So -- gag -- we open the block device to get
433 * its size, and remember it for subsequent VOP_GETATTR().
435 if (strncmp(path, "/dev/", 5) == 0) {
437 fd = open64(path, O_RDONLY);
440 if (fstat64(fd, &st) == -1) {
445 (void) sprintf(realpath, "%s", path);
446 dsk = strstr(path, "/dsk/");
448 (void) sprintf(realpath + (dsk - path) + 1, "r%s",
451 (void) sprintf(realpath, "%s", path);
452 if (!(flags & FCREAT) && stat64(realpath, &st) == -1)
457 old_umask = umask(0);
460 * The construct 'flags - FREAD' conveniently maps combinations of
461 * FREAD and FWRITE to the corresponding O_RDONLY, O_WRONLY, and O_RDWR.
463 fd = open64(realpath, flags - FREAD, mode);
466 (void) umask(old_umask);
471 if (fstat64(fd, &st) == -1) {
476 (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
478 *vpp = vp = umem_zalloc(sizeof (vnode_t), UMEM_NOFAIL);
481 vp->v_size = st.st_size;
482 vp->v_path = spa_strdup(path);
489 vn_openat(char *path, int x1, int flags, int mode, vnode_t **vpp, int x2,
490 int x3, vnode_t *startvp, int fd)
492 char *realpath = umem_alloc(strlen(path) + 2, UMEM_NOFAIL);
495 ASSERT(startvp == rootdir);
496 (void) sprintf(realpath, "/%s", path);
498 /* fd ignored for now, need if want to simulate nbmand support */
499 ret = vn_open(realpath, x1, flags, mode, vpp, x2, x3);
501 umem_free(realpath, strlen(path) + 2);
508 vn_rdwr(int uio, vnode_t *vp, void *addr, ssize_t len, offset_t offset,
509 int x1, int x2, rlim64_t x3, void *x4, ssize_t *residp)
511 ssize_t iolen, split;
513 if (uio == UIO_READ) {
514 iolen = pread64(vp->v_fd, addr, len, offset);
517 * To simulate partial disk writes, we split writes into two
518 * system calls so that the process can be killed in between.
520 int sectors = len >> SPA_MINBLOCKSHIFT;
521 split = (sectors > 0 ? rand() % sectors : 0) <<
523 iolen = pwrite64(vp->v_fd, addr, split, offset);
524 iolen += pwrite64(vp->v_fd, (char *)addr + split,
525 len - split, offset + split);
531 *residp = len - iolen;
532 else if (iolen != len)
538 vn_close(vnode_t *vp, int openflag, cred_t *cr, kthread_t *td)
541 spa_strfree(vp->v_path);
542 umem_free(vp, sizeof (vnode_t));
546 * At a minimum we need to update the size since vdev_reopen()
547 * will no longer call vn_openat().
550 fop_getattr(vnode_t *vp, vattr_t *vap)
554 if (fstat64(vp->v_fd, &st) == -1) {
559 vap->va_size = st.st_size;
566 * =========================================================================
567 * Figure out which debugging statements to print
568 * =========================================================================
571 static char *dprintf_string;
572 static int dprintf_print_all;
575 dprintf_find_string(const char *string)
577 char *tmp_str = dprintf_string;
578 int len = strlen(string);
581 * Find out if this is a string we want to print.
582 * String format: file1.c,function_name1,file2.c,file3.c
585 while (tmp_str != NULL) {
586 if (strncmp(tmp_str, string, len) == 0 &&
587 (tmp_str[len] == ',' || tmp_str[len] == '\0'))
589 tmp_str = strchr(tmp_str, ',');
591 tmp_str++; /* Get rid of , */
597 dprintf_setup(int *argc, char **argv)
602 * Debugging can be specified two ways: by setting the
603 * environment variable ZFS_DEBUG, or by including a
604 * "debug=..." argument on the command line. The command
605 * line setting overrides the environment variable.
608 for (i = 1; i < *argc; i++) {
609 int len = strlen("debug=");
610 /* First look for a command line argument */
611 if (strncmp("debug=", argv[i], len) == 0) {
612 dprintf_string = argv[i] + len;
613 /* Remove from args */
614 for (j = i; j < *argc; j++)
621 if (dprintf_string == NULL) {
622 /* Look for ZFS_DEBUG environment variable */
623 dprintf_string = getenv("ZFS_DEBUG");
627 * Are we just turning on all debugging?
629 if (dprintf_find_string("on"))
630 dprintf_print_all = 1;
634 sysctl_handle_64(SYSCTL_HANDLER_ARGS)
640 * =========================================================================
642 * =========================================================================
645 __dprintf(const char *file, const char *func, int line, const char *fmt, ...)
651 * Get rid of annoying "../common/" prefix to filename.
653 newfile = strrchr(file, '/');
654 if (newfile != NULL) {
655 newfile = newfile + 1; /* Get rid of leading / */
660 if (dprintf_print_all ||
661 dprintf_find_string(newfile) ||
662 dprintf_find_string(func)) {
663 /* Print out just the function name if requested */
665 if (dprintf_find_string("pid"))
666 (void) printf("%d ", getpid());
667 if (dprintf_find_string("tid"))
668 (void) printf("%ul ", thr_self());
670 if (dprintf_find_string("cpu"))
671 (void) printf("%u ", getcpuid());
673 if (dprintf_find_string("time"))
674 (void) printf("%llu ", gethrtime());
675 if (dprintf_find_string("long"))
676 (void) printf("%s, line %d: ", newfile, line);
677 (void) printf("%s: ", func);
679 (void) vprintf(fmt, adx);
685 #endif /* ZFS_DEBUG */
688 * =========================================================================
689 * cmn_err() and panic()
690 * =========================================================================
692 static char ce_prefix[CE_IGNORE][10] = { "", "NOTICE: ", "WARNING: ", "" };
693 static char ce_suffix[CE_IGNORE][2] = { "", "\n", "\n", "" };
696 vpanic(const char *fmt, va_list adx)
698 (void) fprintf(stderr, "error: ");
699 (void) vfprintf(stderr, fmt, adx);
700 (void) fprintf(stderr, "\n");
702 abort(); /* think of it as a "user-level crash dump" */
706 panic(const char *fmt, ...)
716 vcmn_err(int ce, const char *fmt, va_list adx)
720 if (ce != CE_NOTE) { /* suppress noise in userland stress testing */
721 (void) fprintf(stderr, "%s", ce_prefix[ce]);
722 (void) vfprintf(stderr, fmt, adx);
723 (void) fprintf(stderr, "%s", ce_suffix[ce]);
729 cmn_err(int ce, const char *fmt, ...)
734 vcmn_err(ce, fmt, adx);
739 * =========================================================================
741 * =========================================================================
744 kobj_open_file(char *name)
749 /* set vp as the _fd field of the file */
750 if (vn_openat(name, UIO_SYSSPACE, FREAD, 0, &vp, 0, 0, rootdir,
752 return ((void *)-1UL);
754 file = umem_zalloc(sizeof (struct _buf), UMEM_NOFAIL);
755 file->_fd = (intptr_t)vp;
760 kobj_read_file(struct _buf *file, char *buf, unsigned size, unsigned off)
764 vn_rdwr(UIO_READ, (vnode_t *)file->_fd, buf, size, (offset_t)off,
765 UIO_SYSSPACE, 0, 0, 0, &resid);
767 return (size - resid);
771 kobj_close_file(struct _buf *file)
773 vn_close((vnode_t *)file->_fd, 0, NULL, NULL);
774 umem_free(file, sizeof (struct _buf));
778 kobj_get_filesize(struct _buf *file, uint64_t *size)
781 vnode_t *vp = (vnode_t *)file->_fd;
783 if (fstat64(vp->v_fd, &st) == -1) {
784 vn_close(vp, 0, NULL, NULL);
792 * =========================================================================
794 * =========================================================================
800 poll(0, 0, ticks * (1000 / hz));
805 * Find highest one bit set.
806 * Returns bit number + 1 of highest bit that is set, otherwise returns 0.
809 highbit64(uint64_t i)
815 if (i & 0xffffffff00000000ULL) {
818 if (i & 0xffff0000) {
837 static int random_fd = -1, urandom_fd = -1;
840 random_get_bytes_common(uint8_t *ptr, size_t len, int fd)
848 bytes = read(fd, ptr, resid);
849 ASSERT3S(bytes, >=, 0);
858 random_get_bytes(uint8_t *ptr, size_t len)
860 return (random_get_bytes_common(ptr, len, random_fd));
864 random_get_pseudo_bytes(uint8_t *ptr, size_t len)
866 return (random_get_bytes_common(ptr, len, urandom_fd));
870 ddi_strtoul(const char *hw_serial, char **nptr, int base, unsigned long *result)
874 *result = strtoul(hw_serial, &end, base);
881 ddi_strtoull(const char *str, char **nptr, int base, u_longlong_t *result)
885 *result = strtoull(str, &end, base);
894 cyclic_add(cyc_handler_t *hdlr, cyc_time_t *when)
901 cyclic_remove(cyclic_id_t id)
907 cyclic_reprogram(cyclic_id_t id, hrtime_t expiration)
914 * =========================================================================
915 * kernel emulation setup & teardown
916 * =========================================================================
919 umem_out_of_memory(void)
921 char errmsg[] = "out of memory -- generating core dump\n";
923 write(fileno(stderr), errmsg, sizeof (errmsg));
929 kernel_init(int mode)
931 extern uint_t rrw_tsd_key;
933 umem_nofail_callback(umem_out_of_memory);
935 physmem = sysconf(_SC_PHYS_PAGES);
937 dprintf("physmem = %llu pages (%.2f GB)\n", physmem,
938 (double)physmem * sysconf(_SC_PAGE_SIZE) / (1ULL << 30));
940 (void) snprintf(hw_serial, sizeof (hw_serial), "%lu",
941 (mode & FWRITE) ? (unsigned long)gethostid() : 0);
943 VERIFY((random_fd = open("/dev/random", O_RDONLY)) != -1);
944 VERIFY((urandom_fd = open("/dev/urandom", O_RDONLY)) != -1);
949 mutex_init(&cpu_lock, NULL, MUTEX_DEFAULT, NULL);
954 tsd_create(&rrw_tsd_key, rrw_tsd_destroy);
972 z_uncompress(void *dst, size_t *dstlen, const void *src, size_t srclen)
975 uLongf len = *dstlen;
977 if ((ret = uncompress(dst, &len, src, srclen)) == Z_OK)
978 *dstlen = (size_t)len;
984 z_compress_level(void *dst, size_t *dstlen, const void *src, size_t srclen,
988 uLongf len = *dstlen;
990 if ((ret = compress2(dst, &len, src, srclen, level)) == Z_OK)
991 *dstlen = (size_t)len;
1003 crgetruid(cred_t *cr)
1009 crgetgid(cred_t *cr)
1015 crgetngroups(cred_t *cr)
1021 crgetgroups(cred_t *cr)
1027 zfs_secpolicy_snapshot_perms(const char *name, cred_t *cr)
1033 zfs_secpolicy_rename_perms(const char *from, const char *to, cred_t *cr)
1039 zfs_secpolicy_destroy_perms(const char *name, cred_t *cr)
1045 ksid_lookupdomain(const char *dom)
1049 kd = umem_zalloc(sizeof (ksiddomain_t), UMEM_NOFAIL);
1050 kd->kd_name = spa_strdup(dom);
1055 ksiddomain_rele(ksiddomain_t *ksid)
1057 spa_strfree(ksid->kd_name);
1058 umem_free(ksid, sizeof (ksiddomain_t));
1062 * Do not change the length of the returned string; it must be freed
1066 kmem_asprintf(const char *fmt, ...)
1073 size = vsnprintf(NULL, 0, fmt, adx) + 1;
1076 buf = kmem_alloc(size, KM_SLEEP);
1079 size = vsnprintf(buf, size, fmt, adx);
1087 zfs_onexit_fd_hold(int fd, minor_t *minorp)
1095 zfs_onexit_fd_rele(int fd)
1101 zfs_onexit_add_cb(minor_t minor, void (*func)(void *), void *data,
1102 uint64_t *action_handle)
1109 zfs_onexit_del_cb(minor_t minor, uint64_t action_handle, boolean_t fire)
1116 zfs_onexit_cb_data(minor_t minor, uint64_t action_handle, void **data)
1124 zvol_create_minors(const char *name)
1134 bzero(bp, sizeof (buf_t));
1140 if (bp->b_iodone != NULL) {
1141 (*(bp->b_iodone))(bp);
1144 ASSERT((bp->b_flags & B_DONE) == 0);
1145 bp->b_flags |= B_DONE;
1149 bioerror(buf_t *bp, int error)
1155 bp->b_flags |= B_ERROR;
1157 bp->b_flags &= ~B_ERROR;
1159 bp->b_error = error;
1164 geterror(struct buf *bp)
1168 if (bp->b_flags & B_ERROR) {
1169 error = bp->b_error;