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 by Delphix. All rights reserved.
35 #include <sys/processor.h>
36 #include <sys/zfs_context.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 vmem_t
*zio_arena
= NULL
;
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 mutex_enter(kmutex_t
*mp
)
125 ASSERT(mp
->initialized
== B_TRUE
);
126 ASSERT(mp
->m_owner
!= (void *)-1UL);
127 ASSERT(mp
->m_owner
!= curthread
);
128 VERIFY(mutex_lock(&mp
->m_lock
) == 0);
129 ASSERT(mp
->m_owner
== NULL
);
130 mp
->m_owner
= curthread
;
134 mutex_tryenter(kmutex_t
*mp
)
136 ASSERT(mp
->initialized
== B_TRUE
);
137 ASSERT(mp
->m_owner
!= (void *)-1UL);
138 if (0 == mutex_trylock(&mp
->m_lock
)) {
139 ASSERT(mp
->m_owner
== NULL
);
140 mp
->m_owner
= curthread
;
148 mutex_exit(kmutex_t
*mp
)
150 ASSERT(mp
->initialized
== B_TRUE
);
151 ASSERT(mutex_owner(mp
) == curthread
);
153 VERIFY(mutex_unlock(&mp
->m_lock
) == 0);
157 mutex_owner(kmutex_t
*mp
)
159 ASSERT(mp
->initialized
== B_TRUE
);
160 return (mp
->m_owner
);
164 * =========================================================================
166 * =========================================================================
170 rw_init(krwlock_t
*rwlp
, char *name
, int type
, void *arg
)
172 rwlock_init(&rwlp
->rw_lock
, USYNC_THREAD
, NULL
);
173 rwlp
->rw_owner
= NULL
;
174 rwlp
->initialized
= B_TRUE
;
178 rw_destroy(krwlock_t
*rwlp
)
180 rwlock_destroy(&rwlp
->rw_lock
);
181 rwlp
->rw_owner
= (void *)-1UL;
182 rwlp
->initialized
= B_FALSE
;
186 rw_enter(krwlock_t
*rwlp
, krw_t rw
)
188 ASSERT(!RW_LOCK_HELD(rwlp
));
189 ASSERT(rwlp
->initialized
== B_TRUE
);
190 ASSERT(rwlp
->rw_owner
!= (void *)-1UL);
191 ASSERT(rwlp
->rw_owner
!= curthread
);
194 VERIFY(rw_rdlock(&rwlp
->rw_lock
) == 0);
196 VERIFY(rw_wrlock(&rwlp
->rw_lock
) == 0);
198 rwlp
->rw_owner
= curthread
;
202 rw_exit(krwlock_t
*rwlp
)
204 ASSERT(rwlp
->initialized
== B_TRUE
);
205 ASSERT(rwlp
->rw_owner
!= (void *)-1UL);
207 rwlp
->rw_owner
= NULL
;
208 VERIFY(rw_unlock(&rwlp
->rw_lock
) == 0);
212 rw_tryenter(krwlock_t
*rwlp
, krw_t rw
)
216 ASSERT(rwlp
->initialized
== B_TRUE
);
217 ASSERT(rwlp
->rw_owner
!= (void *)-1UL);
220 rv
= rw_tryrdlock(&rwlp
->rw_lock
);
222 rv
= rw_trywrlock(&rwlp
->rw_lock
);
225 rwlp
->rw_owner
= curthread
;
234 rw_tryupgrade(krwlock_t
*rwlp
)
236 ASSERT(rwlp
->initialized
== B_TRUE
);
237 ASSERT(rwlp
->rw_owner
!= (void *)-1UL);
243 * =========================================================================
244 * condition variables
245 * =========================================================================
249 cv_init(kcondvar_t
*cv
, char *name
, int type
, void *arg
)
251 VERIFY(cond_init(cv
, type
, NULL
) == 0);
255 cv_destroy(kcondvar_t
*cv
)
257 VERIFY(cond_destroy(cv
) == 0);
261 cv_wait(kcondvar_t
*cv
, kmutex_t
*mp
)
263 ASSERT(mutex_owner(mp
) == curthread
);
265 int ret
= cond_wait(cv
, &mp
->m_lock
);
266 VERIFY(ret
== 0 || ret
== EINTR
);
267 mp
->m_owner
= curthread
;
271 cv_timedwait(kcondvar_t
*cv
, kmutex_t
*mp
, clock_t abstime
)
278 delta
= abstime
- ddi_get_lbolt();
282 ts
.tv_sec
= delta
/ hz
;
283 ts
.tv_nsec
= (delta
% hz
) * (NANOSEC
/ hz
);
285 ASSERT(mutex_owner(mp
) == curthread
);
287 error
= cond_reltimedwait(cv
, &mp
->m_lock
, &ts
);
288 mp
->m_owner
= curthread
;
302 cv_signal(kcondvar_t
*cv
)
304 VERIFY(cond_signal(cv
) == 0);
308 cv_broadcast(kcondvar_t
*cv
)
310 VERIFY(cond_broadcast(cv
) == 0);
314 * =========================================================================
316 * =========================================================================
319 * Note: for the xxxat() versions of these functions, we assume that the
320 * starting vp is always rootdir (which is true for spa_directory.c, the only
321 * ZFS consumer of these interfaces). We assert this is true, and then emulate
322 * them by adding '/' in front of the path.
327 vn_open(char *path
, int x1
, int flags
, int mode
, vnode_t
**vpp
, int x2
, int x3
)
332 char realpath
[MAXPATHLEN
];
336 * If we're accessing a real disk from userland, we need to use
337 * the character interface to avoid caching. This is particularly
338 * important if we're trying to look at a real in-kernel storage
339 * pool from userland, e.g. via zdb, because otherwise we won't
340 * see the changes occurring under the segmap cache.
341 * On the other hand, the stupid character device returns zero
342 * for its size. So -- gag -- we open the block device to get
343 * its size, and remember it for subsequent VOP_GETATTR().
345 if (strncmp(path
, "/dev/", 5) == 0) {
347 fd
= open64(path
, O_RDONLY
);
350 if (fstat64(fd
, &st
) == -1) {
355 (void) sprintf(realpath
, "%s", path
);
356 dsk
= strstr(path
, "/dsk/");
358 (void) sprintf(realpath
+ (dsk
- path
) + 1, "r%s",
361 (void) sprintf(realpath
, "%s", path
);
362 if (!(flags
& FCREAT
) && stat64(realpath
, &st
) == -1)
367 old_umask
= umask(0);
370 * The construct 'flags - FREAD' conveniently maps combinations of
371 * FREAD and FWRITE to the corresponding O_RDONLY, O_WRONLY, and O_RDWR.
373 fd
= open64(realpath
, flags
- FREAD
, mode
);
376 (void) umask(old_umask
);
381 if (fstat64(fd
, &st
) == -1) {
386 (void) fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
388 *vpp
= vp
= umem_zalloc(sizeof (vnode_t
), UMEM_NOFAIL
);
391 vp
->v_size
= st
.st_size
;
392 vp
->v_path
= spa_strdup(path
);
399 vn_openat(char *path
, int x1
, int flags
, int mode
, vnode_t
**vpp
, int x2
,
400 int x3
, vnode_t
*startvp
, int fd
)
402 char *realpath
= umem_alloc(strlen(path
) + 2, UMEM_NOFAIL
);
405 ASSERT(startvp
== rootdir
);
406 (void) sprintf(realpath
, "/%s", path
);
408 /* fd ignored for now, need if want to simulate nbmand support */
409 ret
= vn_open(realpath
, x1
, flags
, mode
, vpp
, x2
, x3
);
411 umem_free(realpath
, strlen(path
) + 2);
418 vn_rdwr(int uio
, vnode_t
*vp
, void *addr
, ssize_t len
, offset_t offset
,
419 int x1
, int x2
, rlim64_t x3
, void *x4
, ssize_t
*residp
)
421 ssize_t iolen
, split
;
423 if (uio
== UIO_READ
) {
424 iolen
= pread64(vp
->v_fd
, addr
, len
, offset
);
427 * To simulate partial disk writes, we split writes into two
428 * system calls so that the process can be killed in between.
430 int sectors
= len
>> SPA_MINBLOCKSHIFT
;
431 split
= (sectors
> 0 ? rand() % sectors
: 0) <<
433 iolen
= pwrite64(vp
->v_fd
, addr
, split
, offset
);
434 iolen
+= pwrite64(vp
->v_fd
, (char *)addr
+ split
,
435 len
- split
, offset
+ split
);
441 *residp
= len
- iolen
;
442 else if (iolen
!= len
)
448 vn_close(vnode_t
*vp
)
451 spa_strfree(vp
->v_path
);
452 umem_free(vp
, sizeof (vnode_t
));
456 * At a minimum we need to update the size since vdev_reopen()
457 * will no longer call vn_openat().
460 fop_getattr(vnode_t
*vp
, vattr_t
*vap
)
464 if (fstat64(vp
->v_fd
, &st
) == -1) {
469 vap
->va_size
= st
.st_size
;
476 * =========================================================================
477 * Figure out which debugging statements to print
478 * =========================================================================
481 static char *dprintf_string
;
482 static int dprintf_print_all
;
485 dprintf_find_string(const char *string
)
487 char *tmp_str
= dprintf_string
;
488 int len
= strlen(string
);
491 * Find out if this is a string we want to print.
492 * String format: file1.c,function_name1,file2.c,file3.c
495 while (tmp_str
!= NULL
) {
496 if (strncmp(tmp_str
, string
, len
) == 0 &&
497 (tmp_str
[len
] == ',' || tmp_str
[len
] == '\0'))
499 tmp_str
= strchr(tmp_str
, ',');
501 tmp_str
++; /* Get rid of , */
507 dprintf_setup(int *argc
, char **argv
)
512 * Debugging can be specified two ways: by setting the
513 * environment variable ZFS_DEBUG, or by including a
514 * "debug=..." argument on the command line. The command
515 * line setting overrides the environment variable.
518 for (i
= 1; i
< *argc
; i
++) {
519 int len
= strlen("debug=");
520 /* First look for a command line argument */
521 if (strncmp("debug=", argv
[i
], len
) == 0) {
522 dprintf_string
= argv
[i
] + len
;
523 /* Remove from args */
524 for (j
= i
; j
< *argc
; j
++)
531 if (dprintf_string
== NULL
) {
532 /* Look for ZFS_DEBUG environment variable */
533 dprintf_string
= getenv("ZFS_DEBUG");
537 * Are we just turning on all debugging?
539 if (dprintf_find_string("on"))
540 dprintf_print_all
= 1;
544 * =========================================================================
546 * =========================================================================
549 __dprintf(const char *file
, const char *func
, int line
, const char *fmt
, ...)
555 * Get rid of annoying "../common/" prefix to filename.
557 newfile
= strrchr(file
, '/');
558 if (newfile
!= NULL
) {
559 newfile
= newfile
+ 1; /* Get rid of leading / */
564 if (dprintf_print_all
||
565 dprintf_find_string(newfile
) ||
566 dprintf_find_string(func
)) {
567 /* Print out just the function name if requested */
569 if (dprintf_find_string("pid"))
570 (void) printf("%d ", getpid());
571 if (dprintf_find_string("tid"))
572 (void) printf("%u ", thr_self());
573 if (dprintf_find_string("cpu"))
574 (void) printf("%u ", getcpuid());
575 if (dprintf_find_string("time"))
576 (void) printf("%llu ", gethrtime());
577 if (dprintf_find_string("long"))
578 (void) printf("%s, line %d: ", newfile
, line
);
579 (void) printf("%s: ", func
);
581 (void) vprintf(fmt
, adx
);
587 #endif /* ZFS_DEBUG */
590 * =========================================================================
591 * cmn_err() and panic()
592 * =========================================================================
594 static char ce_prefix
[CE_IGNORE
][10] = { "", "NOTICE: ", "WARNING: ", "" };
595 static char ce_suffix
[CE_IGNORE
][2] = { "", "\n", "\n", "" };
598 vpanic(const char *fmt
, va_list adx
)
600 (void) fprintf(stderr
, "error: ");
601 (void) vfprintf(stderr
, fmt
, adx
);
602 (void) fprintf(stderr
, "\n");
604 abort(); /* think of it as a "user-level crash dump" */
608 panic(const char *fmt
, ...)
618 vcmn_err(int ce
, const char *fmt
, va_list adx
)
622 if (ce
!= CE_NOTE
) { /* suppress noise in userland stress testing */
623 (void) fprintf(stderr
, "%s", ce_prefix
[ce
]);
624 (void) vfprintf(stderr
, fmt
, adx
);
625 (void) fprintf(stderr
, "%s", ce_suffix
[ce
]);
631 cmn_err(int ce
, const char *fmt
, ...)
636 vcmn_err(ce
, fmt
, adx
);
641 * =========================================================================
643 * =========================================================================
646 kobj_open_file(char *name
)
651 /* set vp as the _fd field of the file */
652 if (vn_openat(name
, UIO_SYSSPACE
, FREAD
, 0, &vp
, 0, 0, rootdir
,
654 return ((void *)-1UL);
656 file
= umem_zalloc(sizeof (struct _buf
), UMEM_NOFAIL
);
657 file
->_fd
= (intptr_t)vp
;
662 kobj_read_file(struct _buf
*file
, char *buf
, unsigned size
, unsigned off
)
666 vn_rdwr(UIO_READ
, (vnode_t
*)file
->_fd
, buf
, size
, (offset_t
)off
,
667 UIO_SYSSPACE
, 0, 0, 0, &resid
);
669 return (size
- resid
);
673 kobj_close_file(struct _buf
*file
)
675 vn_close((vnode_t
*)file
->_fd
);
676 umem_free(file
, sizeof (struct _buf
));
680 kobj_get_filesize(struct _buf
*file
, uint64_t *size
)
683 vnode_t
*vp
= (vnode_t
*)file
->_fd
;
685 if (fstat64(vp
->v_fd
, &st
) == -1) {
694 * =========================================================================
696 * =========================================================================
702 poll(0, 0, ticks
* (1000 / hz
));
706 * Find highest one bit set.
707 * Returns bit number + 1 of highest bit that is set, otherwise returns 0.
708 * High order bit is 31 (or 63 in _LP64 kernel).
718 if (i
& 0xffffffff00000000ul
) {
722 if (i
& 0xffff0000) {
740 static int random_fd
= -1, urandom_fd
= -1;
743 random_get_bytes_common(uint8_t *ptr
, size_t len
, int fd
)
751 bytes
= read(fd
, ptr
, resid
);
752 ASSERT3S(bytes
, >=, 0);
761 random_get_bytes(uint8_t *ptr
, size_t len
)
763 return (random_get_bytes_common(ptr
, len
, random_fd
));
767 random_get_pseudo_bytes(uint8_t *ptr
, size_t len
)
769 return (random_get_bytes_common(ptr
, len
, urandom_fd
));
773 ddi_strtoul(const char *hw_serial
, char **nptr
, int base
, unsigned long *result
)
777 *result
= strtoul(hw_serial
, &end
, base
);
784 ddi_strtoull(const char *str
, char **nptr
, int base
, u_longlong_t
*result
)
788 *result
= strtoull(str
, &end
, base
);
796 cyclic_add(cyc_handler_t
*hdlr
, cyc_time_t
*when
)
803 cyclic_remove(cyclic_id_t id
)
809 cyclic_reprogram(cyclic_id_t id
, hrtime_t expiration
)
815 * =========================================================================
816 * kernel emulation setup & teardown
817 * =========================================================================
820 umem_out_of_memory(void)
822 char errmsg
[] = "out of memory -- generating core dump\n";
824 write(fileno(stderr
), errmsg
, sizeof (errmsg
));
830 kernel_init(int mode
)
832 umem_nofail_callback(umem_out_of_memory
);
834 physmem
= sysconf(_SC_PHYS_PAGES
);
836 dprintf("physmem = %llu pages (%.2f GB)\n", physmem
,
837 (double)physmem
* sysconf(_SC_PAGE_SIZE
) / (1ULL << 30));
839 (void) snprintf(hw_serial
, sizeof (hw_serial
), "%ld",
840 (mode
& FWRITE
) ? gethostid() : 0);
842 VERIFY((random_fd
= open("/dev/random", O_RDONLY
)) != -1);
843 VERIFY((urandom_fd
= open("/dev/urandom", O_RDONLY
)) != -1);
847 mutex_init(&cpu_lock
, NULL
, MUTEX_DEFAULT
, NULL
);
867 z_uncompress(void *dst
, size_t *dstlen
, const void *src
, size_t srclen
)
870 uLongf len
= *dstlen
;
872 if ((ret
= uncompress(dst
, &len
, src
, srclen
)) == Z_OK
)
873 *dstlen
= (size_t)len
;
879 z_compress_level(void *dst
, size_t *dstlen
, const void *src
, size_t srclen
,
883 uLongf len
= *dstlen
;
885 if ((ret
= compress2(dst
, &len
, src
, srclen
, level
)) == Z_OK
)
886 *dstlen
= (size_t)len
;
898 crgetruid(cred_t
*cr
)
910 crgetngroups(cred_t
*cr
)
916 crgetgroups(cred_t
*cr
)
922 zfs_secpolicy_snapshot_perms(const char *name
, cred_t
*cr
)
928 zfs_secpolicy_rename_perms(const char *from
, const char *to
, cred_t
*cr
)
934 zfs_secpolicy_destroy_perms(const char *name
, cred_t
*cr
)
940 ksid_lookupdomain(const char *dom
)
944 kd
= umem_zalloc(sizeof (ksiddomain_t
), UMEM_NOFAIL
);
945 kd
->kd_name
= spa_strdup(dom
);
950 ksiddomain_rele(ksiddomain_t
*ksid
)
952 spa_strfree(ksid
->kd_name
);
953 umem_free(ksid
, sizeof (ksiddomain_t
));
957 * Do not change the length of the returned string; it must be freed
961 kmem_asprintf(const char *fmt
, ...)
968 size
= vsnprintf(NULL
, 0, fmt
, adx
) + 1;
971 buf
= kmem_alloc(size
, KM_SLEEP
);
974 size
= vsnprintf(buf
, size
, fmt
, adx
);
982 zfs_onexit_fd_hold(int fd
, minor_t
*minorp
)
990 zfs_onexit_fd_rele(int fd
)
996 zfs_onexit_add_cb(minor_t minor
, void (*func
)(void *), void *data
,
997 uint64_t *action_handle
)
1004 zfs_onexit_del_cb(minor_t minor
, uint64_t action_handle
, boolean_t fire
)
1011 zfs_onexit_cb_data(minor_t minor
, uint64_t action_handle
, void **data
)