1 /*
2 * CDDL HEADER START
3 *
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.
7 *
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.
12 *
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]
18 *
19 * CDDL HEADER END
20 */
21 /*
22 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23 * Copyright (c) 2012, 2015 by Delphix. All rights reserved.
24 * Copyright (c) 2013, Joyent, Inc. All rights reserved.
25 */
26
27 #include <assert.h>
28 #include <fcntl.h>
29 #include <poll.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <zlib.h>
34 #include <libgen.h>
35 #include <sys/spa.h>
36 #include <sys/stat.h>
37 #include <sys/processor.h>
38 #include <sys/zfs_context.h>
39 #include <sys/rrwlock.h>
40 #include <sys/zmod.h>
41 #include <sys/utsname.h>
42 #include <sys/systeminfo.h>
43
44 /*
45 * Emulation of kernel services in userland.
46 */
47
48 #ifndef __FreeBSD__
49 int aok;
50 #endif
51 uint64_t physmem;
52 vnode_t *rootdir = (vnode_t *)0xabcd1234;
53 char hw_serial[HW_HOSTID_LEN];
54 #ifdef illumos
55 kmutex_t cpu_lock;
56 #endif
57
58 /* If set, all blocks read will be copied to the specified directory. */
59 char *vn_dumpdir = NULL;
60
61 struct utsname utsname = {
62 "userland", "libzpool", "1", "1", "na"
63 };
64
65 /* this only exists to have its address taken */
66 struct proc p0;
67
68 /*
69 * =========================================================================
70 * threads
71 * =========================================================================
72 */
73 /*ARGSUSED*/
74 kthread_t *
zk_thread_create(void (* func)(),void * arg)75 zk_thread_create(void (*func)(), void *arg)
76 {
77 thread_t tid;
78
79 VERIFY(thr_create(0, 0, (void *(*)(void *))func, arg, THR_DETACHED,
80 &tid) == 0);
81
82 return ((void *)(uintptr_t)tid);
83 }
84
85 /*
86 * =========================================================================
87 * kstats
88 * =========================================================================
89 */
90 /*ARGSUSED*/
91 kstat_t *
kstat_create(char * module,int instance,char * name,char * class,uchar_t type,ulong_t ndata,uchar_t ks_flag)92 kstat_create(char *module, int instance, char *name, char *class,
93 uchar_t type, ulong_t ndata, uchar_t ks_flag)
94 {
95 return (NULL);
96 }
97
98 /*ARGSUSED*/
99 void
kstat_named_init(kstat_named_t * knp,const char * name,uchar_t type)100 kstat_named_init(kstat_named_t *knp, const char *name, uchar_t type)
101 {}
102
103 /*ARGSUSED*/
104 void
kstat_install(kstat_t * ksp)105 kstat_install(kstat_t *ksp)
106 {}
107
108 /*ARGSUSED*/
109 void
kstat_delete(kstat_t * ksp)110 kstat_delete(kstat_t *ksp)
111 {}
112
113 /*
114 * =========================================================================
115 * mutexes
116 * =========================================================================
117 */
118 void
zmutex_init(kmutex_t * mp)119 zmutex_init(kmutex_t *mp)
120 {
121 mp->m_owner = NULL;
122 mp->initialized = B_TRUE;
123 (void) _mutex_init(&mp->m_lock, USYNC_THREAD, NULL);
124 }
125
126 void
zmutex_destroy(kmutex_t * mp)127 zmutex_destroy(kmutex_t *mp)
128 {
129 ASSERT(mp->initialized == B_TRUE);
130 ASSERT(mp->m_owner == NULL);
131 (void) _mutex_destroy(&(mp)->m_lock);
132 mp->m_owner = (void *)-1UL;
133 mp->initialized = B_FALSE;
134 }
135
136 int
zmutex_owned(kmutex_t * mp)137 zmutex_owned(kmutex_t *mp)
138 {
139 ASSERT(mp->initialized == B_TRUE);
140
141 return (mp->m_owner == curthread);
142 }
143
144 void
mutex_enter(kmutex_t * mp)145 mutex_enter(kmutex_t *mp)
146 {
147 ASSERT(mp->initialized == B_TRUE);
148 ASSERT(mp->m_owner != (void *)-1UL);
149 ASSERT(mp->m_owner != curthread);
150 VERIFY(mutex_lock(&mp->m_lock) == 0);
151 ASSERT(mp->m_owner == NULL);
152 mp->m_owner = curthread;
153 }
154
155 int
mutex_tryenter(kmutex_t * mp)156 mutex_tryenter(kmutex_t *mp)
157 {
158 ASSERT(mp->initialized == B_TRUE);
159 ASSERT(mp->m_owner != (void *)-1UL);
160 if (0 == mutex_trylock(&mp->m_lock)) {
161 ASSERT(mp->m_owner == NULL);
162 mp->m_owner = curthread;
163 return (1);
164 } else {
165 return (0);
166 }
167 }
168
169 void
mutex_exit(kmutex_t * mp)170 mutex_exit(kmutex_t *mp)
171 {
172 ASSERT(mp->initialized == B_TRUE);
173 ASSERT(mutex_owner(mp) == curthread);
174 mp->m_owner = NULL;
175 VERIFY(mutex_unlock(&mp->m_lock) == 0);
176 }
177
178 void *
mutex_owner(kmutex_t * mp)179 mutex_owner(kmutex_t *mp)
180 {
181 ASSERT(mp->initialized == B_TRUE);
182 return (mp->m_owner);
183 }
184
185 /*
186 * =========================================================================
187 * rwlocks
188 * =========================================================================
189 */
190 /*ARGSUSED*/
191 void
rw_init(krwlock_t * rwlp,char * name,int type,void * arg)192 rw_init(krwlock_t *rwlp, char *name, int type, void *arg)
193 {
194 rwlock_init(&rwlp->rw_lock, USYNC_THREAD, NULL);
195 rwlp->rw_owner = NULL;
196 rwlp->initialized = B_TRUE;
197 rwlp->rw_count = 0;
198 }
199
200 void
rw_destroy(krwlock_t * rwlp)201 rw_destroy(krwlock_t *rwlp)
202 {
203 ASSERT(rwlp->rw_count == 0);
204 rwlock_destroy(&rwlp->rw_lock);
205 rwlp->rw_owner = (void *)-1UL;
206 rwlp->initialized = B_FALSE;
207 }
208
209 void
rw_enter(krwlock_t * rwlp,krw_t rw)210 rw_enter(krwlock_t *rwlp, krw_t rw)
211 {
212 //ASSERT(!RW_LOCK_HELD(rwlp));
213 ASSERT(rwlp->initialized == B_TRUE);
214 ASSERT(rwlp->rw_owner != (void *)-1UL);
215 ASSERT(rwlp->rw_owner != curthread);
216
217 if (rw == RW_READER) {
218 VERIFY(rw_rdlock(&rwlp->rw_lock) == 0);
219 ASSERT(rwlp->rw_count >= 0);
220 atomic_add_int(&rwlp->rw_count, 1);
221 } else {
222 VERIFY(rw_wrlock(&rwlp->rw_lock) == 0);
223 ASSERT(rwlp->rw_count == 0);
224 rwlp->rw_count = -1;
225 rwlp->rw_owner = curthread;
226 }
227 }
228
229 void
rw_exit(krwlock_t * rwlp)230 rw_exit(krwlock_t *rwlp)
231 {
232 ASSERT(rwlp->initialized == B_TRUE);
233 ASSERT(rwlp->rw_owner != (void *)-1UL);
234
235 if (rwlp->rw_owner == curthread) {
236 /* Write locked. */
237 ASSERT(rwlp->rw_count == -1);
238 rwlp->rw_count = 0;
239 rwlp->rw_owner = NULL;
240 } else {
241 /* Read locked. */
242 ASSERT(rwlp->rw_count > 0);
243 atomic_add_int(&rwlp->rw_count, -1);
244 }
245 VERIFY(rw_unlock(&rwlp->rw_lock) == 0);
246 }
247
248 int
rw_tryenter(krwlock_t * rwlp,krw_t rw)249 rw_tryenter(krwlock_t *rwlp, krw_t rw)
250 {
251 int rv;
252
253 ASSERT(rwlp->initialized == B_TRUE);
254 ASSERT(rwlp->rw_owner != (void *)-1UL);
255 ASSERT(rwlp->rw_owner != curthread);
256
257 if (rw == RW_READER)
258 rv = rw_tryrdlock(&rwlp->rw_lock);
259 else
260 rv = rw_trywrlock(&rwlp->rw_lock);
261
262 if (rv == 0) {
263 ASSERT(rwlp->rw_owner == NULL);
264 if (rw == RW_READER) {
265 ASSERT(rwlp->rw_count >= 0);
266 atomic_add_int(&rwlp->rw_count, 1);
267 } else {
268 ASSERT(rwlp->rw_count == 0);
269 rwlp->rw_count = -1;
270 rwlp->rw_owner = curthread;
271 }
272 return (1);
273 }
274
275 return (0);
276 }
277
278 /*ARGSUSED*/
279 int
rw_tryupgrade(krwlock_t * rwlp)280 rw_tryupgrade(krwlock_t *rwlp)
281 {
282 ASSERT(rwlp->initialized == B_TRUE);
283 ASSERT(rwlp->rw_owner != (void *)-1UL);
284
285 return (0);
286 }
287
288 int
rw_lock_held(krwlock_t * rwlp)289 rw_lock_held(krwlock_t *rwlp)
290 {
291
292 return (rwlp->rw_count != 0);
293 }
294
295 /*
296 * =========================================================================
297 * condition variables
298 * =========================================================================
299 */
300 /*ARGSUSED*/
301 void
cv_init(kcondvar_t * cv,char * name,int type,void * arg)302 cv_init(kcondvar_t *cv, char *name, int type, void *arg)
303 {
304 VERIFY(cond_init(cv, name, NULL) == 0);
305 }
306
307 void
cv_destroy(kcondvar_t * cv)308 cv_destroy(kcondvar_t *cv)
309 {
310 VERIFY(cond_destroy(cv) == 0);
311 }
312
313 void
cv_wait(kcondvar_t * cv,kmutex_t * mp)314 cv_wait(kcondvar_t *cv, kmutex_t *mp)
315 {
316 ASSERT(mutex_owner(mp) == curthread);
317 mp->m_owner = NULL;
318 int ret = cond_wait(cv, &mp->m_lock);
319 VERIFY(ret == 0 || ret == EINTR);
320 mp->m_owner = curthread;
321 }
322
323 clock_t
cv_timedwait(kcondvar_t * cv,kmutex_t * mp,clock_t abstime)324 cv_timedwait(kcondvar_t *cv, kmutex_t *mp, clock_t abstime)
325 {
326 int error;
327 struct timespec ts;
328 struct timeval tv;
329 clock_t delta;
330
331 abstime += ddi_get_lbolt();
332 top:
333 delta = abstime - ddi_get_lbolt();
334 if (delta <= 0)
335 return (-1);
336
337 if (gettimeofday(&tv, NULL) != 0)
338 assert(!"gettimeofday() failed");
339
340 ts.tv_sec = tv.tv_sec + delta / hz;
341 ts.tv_nsec = tv.tv_usec * 1000 + (delta % hz) * (NANOSEC / hz);
342 ASSERT(ts.tv_nsec >= 0);
343
344 if (ts.tv_nsec >= NANOSEC) {
345 ts.tv_sec++;
346 ts.tv_nsec -= NANOSEC;
347 }
348
349 ASSERT(mutex_owner(mp) == curthread);
350 mp->m_owner = NULL;
351 error = pthread_cond_timedwait(cv, &mp->m_lock, &ts);
352 mp->m_owner = curthread;
353
354 if (error == EINTR)
355 goto top;
356
357 if (error == ETIMEDOUT)
358 return (-1);
359
360 ASSERT(error == 0);
361
362 return (1);
363 }
364
365 /*ARGSUSED*/
366 clock_t
cv_timedwait_hires(kcondvar_t * cv,kmutex_t * mp,hrtime_t tim,hrtime_t res,int flag)367 cv_timedwait_hires(kcondvar_t *cv, kmutex_t *mp, hrtime_t tim, hrtime_t res,
368 int flag)
369 {
370 int error;
371 timespec_t ts;
372 hrtime_t delta;
373
374 ASSERT(flag == 0 || flag == CALLOUT_FLAG_ABSOLUTE);
375
376 top:
377 delta = tim;
378 if (flag & CALLOUT_FLAG_ABSOLUTE)
379 delta -= gethrtime();
380
381 if (delta <= 0)
382 return (-1);
383
384 clock_gettime(CLOCK_REALTIME, &ts);
385 ts.tv_sec += delta / NANOSEC;
386 ts.tv_nsec += delta % NANOSEC;
387 if (ts.tv_nsec >= NANOSEC) {
388 ts.tv_sec++;
389 ts.tv_nsec -= NANOSEC;
390 }
391
392 ASSERT(mutex_owner(mp) == curthread);
393 mp->m_owner = NULL;
394 error = pthread_cond_timedwait(cv, &mp->m_lock, &ts);
395 mp->m_owner = curthread;
396
397 if (error == ETIMEDOUT)
398 return (-1);
399
400 if (error == EINTR)
401 goto top;
402
403 ASSERT(error == 0);
404
405 return (1);
406 }
407
408 void
cv_signal(kcondvar_t * cv)409 cv_signal(kcondvar_t *cv)
410 {
411 VERIFY(cond_signal(cv) == 0);
412 }
413
414 void
cv_broadcast(kcondvar_t * cv)415 cv_broadcast(kcondvar_t *cv)
416 {
417 VERIFY(cond_broadcast(cv) == 0);
418 }
419
420 /*
421 * =========================================================================
422 * vnode operations
423 * =========================================================================
424 */
425 /*
426 * Note: for the xxxat() versions of these functions, we assume that the
427 * starting vp is always rootdir (which is true for spa_directory.c, the only
428 * ZFS consumer of these interfaces). We assert this is true, and then emulate
429 * them by adding '/' in front of the path.
430 */
431
432 /*ARGSUSED*/
433 int
vn_open(char * path,int x1,int flags,int mode,vnode_t ** vpp,int x2,int x3)434 vn_open(char *path, int x1, int flags, int mode, vnode_t **vpp, int x2, int x3)
435 {
436 int fd;
437 int dump_fd;
438 vnode_t *vp;
439 int old_umask;
440 char realpath[MAXPATHLEN];
441 struct stat64 st;
442
443 /*
444 * If we're accessing a real disk from userland, we need to use
445 * the character interface to avoid caching. This is particularly
446 * important if we're trying to look at a real in-kernel storage
447 * pool from userland, e.g. via zdb, because otherwise we won't
448 * see the changes occurring under the segmap cache.
449 * On the other hand, the stupid character device returns zero
450 * for its size. So -- gag -- we open the block device to get
451 * its size, and remember it for subsequent VOP_GETATTR().
452 */
453 if (strncmp(path, "/dev/", 5) == 0) {
454 char *dsk;
455 fd = open64(path, O_RDONLY);
456 if (fd == -1)
457 return (errno);
458 if (fstat64(fd, &st) == -1) {
459 close(fd);
460 return (errno);
461 }
462 close(fd);
463 (void) sprintf(realpath, "%s", path);
464 dsk = strstr(path, "/dsk/");
465 if (dsk != NULL)
466 (void) sprintf(realpath + (dsk - path) + 1, "r%s",
467 dsk + 1);
468 } else {
469 (void) sprintf(realpath, "%s", path);
470 if (!(flags & FCREAT) && stat64(realpath, &st) == -1)
471 return (errno);
472 }
473
474 if (flags & FCREAT)
475 old_umask = umask(0);
476
477 /*
478 * The construct 'flags - FREAD' conveniently maps combinations of
479 * FREAD and FWRITE to the corresponding O_RDONLY, O_WRONLY, and O_RDWR.
480 */
481 fd = open64(realpath, flags - FREAD, mode);
482
483 if (flags & FCREAT)
484 (void) umask(old_umask);
485
486 if (vn_dumpdir != NULL) {
487 char dumppath[MAXPATHLEN];
488 (void) snprintf(dumppath, sizeof (dumppath),
489 "%s/%s", vn_dumpdir, basename(realpath));
490 dump_fd = open64(dumppath, O_CREAT | O_WRONLY, 0666);
491 if (dump_fd == -1)
492 return (errno);
493 } else {
494 dump_fd = -1;
495 }
496
497 if (fd == -1)
498 return (errno);
499
500 if (fstat64(fd, &st) == -1) {
501 close(fd);
502 return (errno);
503 }
504
505 (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
506
507 *vpp = vp = umem_zalloc(sizeof (vnode_t), UMEM_NOFAIL);
508
509 vp->v_fd = fd;
510 vp->v_size = st.st_size;
511 vp->v_path = spa_strdup(path);
512 vp->v_dump_fd = dump_fd;
513
514 return (0);
515 }
516
517 /*ARGSUSED*/
518 int
vn_openat(char * path,int x1,int flags,int mode,vnode_t ** vpp,int x2,int x3,vnode_t * startvp,int fd)519 vn_openat(char *path, int x1, int flags, int mode, vnode_t **vpp, int x2,
520 int x3, vnode_t *startvp, int fd)
521 {
522 char *realpath = umem_alloc(strlen(path) + 2, UMEM_NOFAIL);
523 int ret;
524
525 ASSERT(startvp == rootdir);
526 (void) sprintf(realpath, "/%s", path);
527
528 /* fd ignored for now, need if want to simulate nbmand support */
529 ret = vn_open(realpath, x1, flags, mode, vpp, x2, x3);
530
531 umem_free(realpath, strlen(path) + 2);
532
533 return (ret);
534 }
535
536 /*ARGSUSED*/
537 int
vn_rdwr(int uio,vnode_t * vp,void * addr,ssize_t len,offset_t offset,int x1,int x2,rlim64_t x3,void * x4,ssize_t * residp)538 vn_rdwr(int uio, vnode_t *vp, void *addr, ssize_t len, offset_t offset,
539 int x1, int x2, rlim64_t x3, void *x4, ssize_t *residp)
540 {
541 ssize_t iolen, split;
542
543 if (uio == UIO_READ) {
544 iolen = pread64(vp->v_fd, addr, len, offset);
545 if (vp->v_dump_fd != -1) {
546 int status =
547 pwrite64(vp->v_dump_fd, addr, iolen, offset);
548 ASSERT(status != -1);
549 }
550 } else {
551 /*
552 * To simulate partial disk writes, we split writes into two
553 * system calls so that the process can be killed in between.
554 */
555 int sectors = len >> SPA_MINBLOCKSHIFT;
556 split = (sectors > 0 ? rand() % sectors : 0) <<
557 SPA_MINBLOCKSHIFT;
558 iolen = pwrite64(vp->v_fd, addr, split, offset);
559 iolen += pwrite64(vp->v_fd, (char *)addr + split,
560 len - split, offset + split);
561 }
562
563 if (iolen == -1)
564 return (errno);
565 if (residp)
566 *residp = len - iolen;
567 else if (iolen != len)
568 return (EIO);
569 return (0);
570 }
571
572 void
vn_close(vnode_t * vp,int openflag,cred_t * cr,kthread_t * td)573 vn_close(vnode_t *vp, int openflag, cred_t *cr, kthread_t *td)
574 {
575 close(vp->v_fd);
576 if (vp->v_dump_fd != -1)
577 close(vp->v_dump_fd);
578 spa_strfree(vp->v_path);
579 umem_free(vp, sizeof (vnode_t));
580 }
581
582 /*
583 * At a minimum we need to update the size since vdev_reopen()
584 * will no longer call vn_openat().
585 */
586 int
fop_getattr(vnode_t * vp,vattr_t * vap)587 fop_getattr(vnode_t *vp, vattr_t *vap)
588 {
589 struct stat64 st;
590
591 if (fstat64(vp->v_fd, &st) == -1) {
592 close(vp->v_fd);
593 return (errno);
594 }
595
596 vap->va_size = st.st_size;
597 return (0);
598 }
599
600 #ifdef ZFS_DEBUG
601
602 /*
603 * =========================================================================
604 * Figure out which debugging statements to print
605 * =========================================================================
606 */
607
608 static char *dprintf_string;
609 static int dprintf_print_all;
610
611 int
dprintf_find_string(const char * string)612 dprintf_find_string(const char *string)
613 {
614 char *tmp_str = dprintf_string;
615 int len = strlen(string);
616
617 /*
618 * Find out if this is a string we want to print.
619 * String format: file1.c,function_name1,file2.c,file3.c
620 */
621
622 while (tmp_str != NULL) {
623 if (strncmp(tmp_str, string, len) == 0 &&
624 (tmp_str[len] == ',' || tmp_str[len] == '\0'))
625 return (1);
626 tmp_str = strchr(tmp_str, ',');
627 if (tmp_str != NULL)
628 tmp_str++; /* Get rid of , */
629 }
630 return (0);
631 }
632
633 void
dprintf_setup(int * argc,char ** argv)634 dprintf_setup(int *argc, char **argv)
635 {
636 int i, j;
637
638 /*
639 * Debugging can be specified two ways: by setting the
640 * environment variable ZFS_DEBUG, or by including a
641 * "debug=..." argument on the command line. The command
642 * line setting overrides the environment variable.
643 */
644
645 for (i = 1; i < *argc; i++) {
646 int len = strlen("debug=");
647 /* First look for a command line argument */
648 if (strncmp("debug=", argv[i], len) == 0) {
649 dprintf_string = argv[i] + len;
650 /* Remove from args */
651 for (j = i; j < *argc; j++)
652 argv[j] = argv[j+1];
653 argv[j] = NULL;
654 (*argc)--;
655 }
656 }
657
658 if (dprintf_string == NULL) {
659 /* Look for ZFS_DEBUG environment variable */
660 dprintf_string = getenv("ZFS_DEBUG");
661 }
662
663 /*
664 * Are we just turning on all debugging?
665 */
666 if (dprintf_find_string("on"))
667 dprintf_print_all = 1;
668
669 if (dprintf_string != NULL)
670 zfs_flags |= ZFS_DEBUG_DPRINTF;
671 }
672
673 int
sysctl_handle_64(SYSCTL_HANDLER_ARGS)674 sysctl_handle_64(SYSCTL_HANDLER_ARGS)
675 {
676 return (0);
677 }
678
679 /*
680 * =========================================================================
681 * debug printfs
682 * =========================================================================
683 */
684 void
__dprintf(const char * file,const char * func,int line,const char * fmt,...)685 __dprintf(const char *file, const char *func, int line, const char *fmt, ...)
686 {
687 const char *newfile;
688 va_list adx;
689
690 /*
691 * Get rid of annoying "../common/" prefix to filename.
692 */
693 newfile = strrchr(file, '/');
694 if (newfile != NULL) {
695 newfile = newfile + 1; /* Get rid of leading / */
696 } else {
697 newfile = file;
698 }
699
700 if (dprintf_print_all ||
701 dprintf_find_string(newfile) ||
702 dprintf_find_string(func)) {
703 /* Print out just the function name if requested */
704 flockfile(stdout);
705 if (dprintf_find_string("pid"))
706 (void) printf("%d ", getpid());
707 if (dprintf_find_string("tid"))
708 (void) printf("%lu ", thr_self());
709 #if 0
710 if (dprintf_find_string("cpu"))
711 (void) printf("%u ", getcpuid());
712 #endif
713 if (dprintf_find_string("time"))
714 (void) printf("%llu ", gethrtime());
715 if (dprintf_find_string("long"))
716 (void) printf("%s, line %d: ", newfile, line);
717 (void) printf("%s: ", func);
718 va_start(adx, fmt);
719 (void) vprintf(fmt, adx);
720 va_end(adx);
721 funlockfile(stdout);
722 }
723 }
724
725 #endif /* ZFS_DEBUG */
726
727 /*
728 * =========================================================================
729 * cmn_err() and panic()
730 * =========================================================================
731 */
732 static char ce_prefix[CE_IGNORE][10] = { "", "NOTICE: ", "WARNING: ", "" };
733 static char ce_suffix[CE_IGNORE][2] = { "", "\n", "\n", "" };
734
735 void
vpanic(const char * fmt,va_list adx)736 vpanic(const char *fmt, va_list adx)
737 {
738 char buf[512];
739 (void) vsnprintf(buf, 512, fmt, adx);
740 assfail(buf, NULL, 0);
741 abort(); /* necessary to make vpanic meet noreturn requirements */
742 }
743
744 void
panic(const char * fmt,...)745 panic(const char *fmt, ...)
746 {
747 va_list adx;
748
749 va_start(adx, fmt);
750 vpanic(fmt, adx);
751 va_end(adx);
752 }
753
754 void
vcmn_err(int ce,const char * fmt,va_list adx)755 vcmn_err(int ce, const char *fmt, va_list adx)
756 {
757 if (ce == CE_PANIC)
758 vpanic(fmt, adx);
759 if (ce != CE_NOTE) { /* suppress noise in userland stress testing */
760 (void) fprintf(stderr, "%s", ce_prefix[ce]);
761 (void) vfprintf(stderr, fmt, adx);
762 (void) fprintf(stderr, "%s", ce_suffix[ce]);
763 }
764 }
765
766 /*PRINTFLIKE2*/
767 void
cmn_err(int ce,const char * fmt,...)768 cmn_err(int ce, const char *fmt, ...)
769 {
770 va_list adx;
771
772 va_start(adx, fmt);
773 vcmn_err(ce, fmt, adx);
774 va_end(adx);
775 }
776
777 /*
778 * =========================================================================
779 * kobj interfaces
780 * =========================================================================
781 */
782 struct _buf *
kobj_open_file(char * name)783 kobj_open_file(char *name)
784 {
785 struct _buf *file;
786 vnode_t *vp;
787
788 /* set vp as the _fd field of the file */
789 if (vn_openat(name, UIO_SYSSPACE, FREAD, 0, &vp, 0, 0, rootdir,
790 -1) != 0)
791 return ((void *)-1UL);
792
793 file = umem_zalloc(sizeof (struct _buf), UMEM_NOFAIL);
794 file->_fd = (intptr_t)vp;
795 return (file);
796 }
797
798 int
kobj_read_file(struct _buf * file,char * buf,unsigned size,unsigned off)799 kobj_read_file(struct _buf *file, char *buf, unsigned size, unsigned off)
800 {
801 ssize_t resid;
802
803 vn_rdwr(UIO_READ, (vnode_t *)file->_fd, buf, size, (offset_t)off,
804 UIO_SYSSPACE, 0, 0, 0, &resid);
805
806 return (size - resid);
807 }
808
809 void
kobj_close_file(struct _buf * file)810 kobj_close_file(struct _buf *file)
811 {
812 vn_close((vnode_t *)file->_fd, 0, NULL, NULL);
813 umem_free(file, sizeof (struct _buf));
814 }
815
816 int
kobj_get_filesize(struct _buf * file,uint64_t * size)817 kobj_get_filesize(struct _buf *file, uint64_t *size)
818 {
819 struct stat64 st;
820 vnode_t *vp = (vnode_t *)file->_fd;
821
822 if (fstat64(vp->v_fd, &st) == -1) {
823 vn_close(vp, 0, NULL, NULL);
824 return (errno);
825 }
826 *size = st.st_size;
827 return (0);
828 }
829
830 /*
831 * =========================================================================
832 * misc routines
833 * =========================================================================
834 */
835
836 void
delay(clock_t ticks)837 delay(clock_t ticks)
838 {
839 poll(0, 0, ticks * (1000 / hz));
840 }
841
842 #if 0
843 /*
844 * Find highest one bit set.
845 * Returns bit number + 1 of highest bit that is set, otherwise returns 0.
846 */
847 int
848 highbit64(uint64_t i)
849 {
850 int h = 1;
851
852 if (i == 0)
853 return (0);
854 if (i & 0xffffffff00000000ULL) {
855 h += 32; i >>= 32;
856 }
857 if (i & 0xffff0000) {
858 h += 16; i >>= 16;
859 }
860 if (i & 0xff00) {
861 h += 8; i >>= 8;
862 }
863 if (i & 0xf0) {
864 h += 4; i >>= 4;
865 }
866 if (i & 0xc) {
867 h += 2; i >>= 2;
868 }
869 if (i & 0x2) {
870 h += 1;
871 }
872 return (h);
873 }
874 #endif
875
876 static int random_fd = -1, urandom_fd = -1;
877
878 static int
random_get_bytes_common(uint8_t * ptr,size_t len,int fd)879 random_get_bytes_common(uint8_t *ptr, size_t len, int fd)
880 {
881 size_t resid = len;
882 ssize_t bytes;
883
884 ASSERT(fd != -1);
885
886 while (resid != 0) {
887 bytes = read(fd, ptr, resid);
888 ASSERT3S(bytes, >=, 0);
889 ptr += bytes;
890 resid -= bytes;
891 }
892
893 return (0);
894 }
895
896 int
random_get_bytes(uint8_t * ptr,size_t len)897 random_get_bytes(uint8_t *ptr, size_t len)
898 {
899 return (random_get_bytes_common(ptr, len, random_fd));
900 }
901
902 int
random_get_pseudo_bytes(uint8_t * ptr,size_t len)903 random_get_pseudo_bytes(uint8_t *ptr, size_t len)
904 {
905 return (random_get_bytes_common(ptr, len, urandom_fd));
906 }
907
908 int
ddi_strtoul(const char * hw_serial,char ** nptr,int base,unsigned long * result)909 ddi_strtoul(const char *hw_serial, char **nptr, int base, unsigned long *result)
910 {
911 char *end;
912
913 *result = strtoul(hw_serial, &end, base);
914 if (*result == 0)
915 return (errno);
916 return (0);
917 }
918
919 int
ddi_strtoull(const char * str,char ** nptr,int base,u_longlong_t * result)920 ddi_strtoull(const char *str, char **nptr, int base, u_longlong_t *result)
921 {
922 char *end;
923
924 *result = strtoull(str, &end, base);
925 if (*result == 0)
926 return (errno);
927 return (0);
928 }
929
930 #ifdef illumos
931 /* ARGSUSED */
932 cyclic_id_t
cyclic_add(cyc_handler_t * hdlr,cyc_time_t * when)933 cyclic_add(cyc_handler_t *hdlr, cyc_time_t *when)
934 {
935 return (1);
936 }
937
938 /* ARGSUSED */
939 void
cyclic_remove(cyclic_id_t id)940 cyclic_remove(cyclic_id_t id)
941 {
942 }
943
944 /* ARGSUSED */
945 int
cyclic_reprogram(cyclic_id_t id,hrtime_t expiration)946 cyclic_reprogram(cyclic_id_t id, hrtime_t expiration)
947 {
948 return (1);
949 }
950 #endif
951
952 /*
953 * =========================================================================
954 * kernel emulation setup & teardown
955 * =========================================================================
956 */
957 static int
umem_out_of_memory(void)958 umem_out_of_memory(void)
959 {
960 char errmsg[] = "out of memory -- generating core dump\n";
961
962 write(fileno(stderr), errmsg, sizeof (errmsg));
963 abort();
964 return (0);
965 }
966
967 void
kernel_init(int mode)968 kernel_init(int mode)
969 {
970 extern uint_t rrw_tsd_key;
971
972 umem_nofail_callback(umem_out_of_memory);
973
974 physmem = sysconf(_SC_PHYS_PAGES);
975
976 dprintf("physmem = %llu pages (%.2f GB)\n", physmem,
977 (double)physmem * sysconf(_SC_PAGE_SIZE) / (1ULL << 30));
978
979 (void) snprintf(hw_serial, sizeof (hw_serial), "%lu",
980 (mode & FWRITE) ? (unsigned long)gethostid() : 0);
981
982 VERIFY((random_fd = open("/dev/random", O_RDONLY)) != -1);
983 VERIFY((urandom_fd = open("/dev/urandom", O_RDONLY)) != -1);
984
985 system_taskq_init();
986
987 #ifdef illumos
988 mutex_init(&cpu_lock, NULL, MUTEX_DEFAULT, NULL);
989 #endif
990
991 spa_init(mode);
992
993 tsd_create(&rrw_tsd_key, rrw_tsd_destroy);
994 }
995
996 void
kernel_fini(void)997 kernel_fini(void)
998 {
999 spa_fini();
1000
1001 system_taskq_fini();
1002
1003 close(random_fd);
1004 close(urandom_fd);
1005
1006 random_fd = -1;
1007 urandom_fd = -1;
1008 }
1009
1010 /* ARGSUSED */
1011 uint32_t
zone_get_hostid(void * zonep)1012 zone_get_hostid(void *zonep)
1013 {
1014 /*
1015 * We're emulating the system's hostid in userland.
1016 */
1017 return (strtoul(hw_serial, NULL, 10));
1018 }
1019
1020 int
z_uncompress(void * dst,size_t * dstlen,const void * src,size_t srclen)1021 z_uncompress(void *dst, size_t *dstlen, const void *src, size_t srclen)
1022 {
1023 int ret;
1024 uLongf len = *dstlen;
1025
1026 if ((ret = uncompress(dst, &len, src, srclen)) == Z_OK)
1027 *dstlen = (size_t)len;
1028
1029 return (ret);
1030 }
1031
1032 int
z_compress_level(void * dst,size_t * dstlen,const void * src,size_t srclen,int level)1033 z_compress_level(void *dst, size_t *dstlen, const void *src, size_t srclen,
1034 int level)
1035 {
1036 int ret;
1037 uLongf len = *dstlen;
1038
1039 if ((ret = compress2(dst, &len, src, srclen, level)) == Z_OK)
1040 *dstlen = (size_t)len;
1041
1042 return (ret);
1043 }
1044
1045 uid_t
crgetuid(cred_t * cr)1046 crgetuid(cred_t *cr)
1047 {
1048 return (0);
1049 }
1050
1051 uid_t
crgetruid(cred_t * cr)1052 crgetruid(cred_t *cr)
1053 {
1054 return (0);
1055 }
1056
1057 gid_t
crgetgid(cred_t * cr)1058 crgetgid(cred_t *cr)
1059 {
1060 return (0);
1061 }
1062
1063 int
crgetngroups(cred_t * cr)1064 crgetngroups(cred_t *cr)
1065 {
1066 return (0);
1067 }
1068
1069 gid_t *
crgetgroups(cred_t * cr)1070 crgetgroups(cred_t *cr)
1071 {
1072 return (NULL);
1073 }
1074
1075 int
zfs_secpolicy_snapshot_perms(const char * name,cred_t * cr)1076 zfs_secpolicy_snapshot_perms(const char *name, cred_t *cr)
1077 {
1078 return (0);
1079 }
1080
1081 int
zfs_secpolicy_rename_perms(const char * from,const char * to,cred_t * cr)1082 zfs_secpolicy_rename_perms(const char *from, const char *to, cred_t *cr)
1083 {
1084 return (0);
1085 }
1086
1087 int
zfs_secpolicy_destroy_perms(const char * name,cred_t * cr)1088 zfs_secpolicy_destroy_perms(const char *name, cred_t *cr)
1089 {
1090 return (0);
1091 }
1092
1093 ksiddomain_t *
ksid_lookupdomain(const char * dom)1094 ksid_lookupdomain(const char *dom)
1095 {
1096 ksiddomain_t *kd;
1097
1098 kd = umem_zalloc(sizeof (ksiddomain_t), UMEM_NOFAIL);
1099 kd->kd_name = spa_strdup(dom);
1100 return (kd);
1101 }
1102
1103 void
ksiddomain_rele(ksiddomain_t * ksid)1104 ksiddomain_rele(ksiddomain_t *ksid)
1105 {
1106 spa_strfree(ksid->kd_name);
1107 umem_free(ksid, sizeof (ksiddomain_t));
1108 }
1109
1110 /*
1111 * Do not change the length of the returned string; it must be freed
1112 * with strfree().
1113 */
1114 char *
kmem_asprintf(const char * fmt,...)1115 kmem_asprintf(const char *fmt, ...)
1116 {
1117 int size;
1118 va_list adx;
1119 char *buf;
1120
1121 va_start(adx, fmt);
1122 size = vsnprintf(NULL, 0, fmt, adx) + 1;
1123 va_end(adx);
1124
1125 buf = kmem_alloc(size, KM_SLEEP);
1126
1127 va_start(adx, fmt);
1128 size = vsnprintf(buf, size, fmt, adx);
1129 va_end(adx);
1130
1131 return (buf);
1132 }
1133
1134 /* ARGSUSED */
1135 int
zfs_onexit_fd_hold(int fd,minor_t * minorp)1136 zfs_onexit_fd_hold(int fd, minor_t *minorp)
1137 {
1138 *minorp = 0;
1139 return (0);
1140 }
1141
1142 /* ARGSUSED */
1143 void
zfs_onexit_fd_rele(int fd)1144 zfs_onexit_fd_rele(int fd)
1145 {
1146 }
1147
1148 /* ARGSUSED */
1149 int
zfs_onexit_add_cb(minor_t minor,void (* func)(void *),void * data,uint64_t * action_handle)1150 zfs_onexit_add_cb(minor_t minor, void (*func)(void *), void *data,
1151 uint64_t *action_handle)
1152 {
1153 return (0);
1154 }
1155
1156 /* ARGSUSED */
1157 int
zfs_onexit_del_cb(minor_t minor,uint64_t action_handle,boolean_t fire)1158 zfs_onexit_del_cb(minor_t minor, uint64_t action_handle, boolean_t fire)
1159 {
1160 return (0);
1161 }
1162
1163 /* ARGSUSED */
1164 int
zfs_onexit_cb_data(minor_t minor,uint64_t action_handle,void ** data)1165 zfs_onexit_cb_data(minor_t minor, uint64_t action_handle, void **data)
1166 {
1167 return (0);
1168 }
1169
1170 #ifdef __FreeBSD__
1171 /* ARGSUSED */
1172 int
zvol_create_minors(const char * name)1173 zvol_create_minors(const char *name)
1174 {
1175 return (0);
1176 }
1177 #endif
1178
1179 #ifdef illumos
1180 void
bioinit(buf_t * bp)1181 bioinit(buf_t *bp)
1182 {
1183 bzero(bp, sizeof (buf_t));
1184 }
1185
1186 void
biodone(buf_t * bp)1187 biodone(buf_t *bp)
1188 {
1189 if (bp->b_iodone != NULL) {
1190 (*(bp->b_iodone))(bp);
1191 return;
1192 }
1193 ASSERT((bp->b_flags & B_DONE) == 0);
1194 bp->b_flags |= B_DONE;
1195 }
1196
1197 void
bioerror(buf_t * bp,int error)1198 bioerror(buf_t *bp, int error)
1199 {
1200 ASSERT(bp != NULL);
1201 ASSERT(error >= 0);
1202
1203 if (error != 0) {
1204 bp->b_flags |= B_ERROR;
1205 } else {
1206 bp->b_flags &= ~B_ERROR;
1207 }
1208 bp->b_error = error;
1209 }
1210
1211
1212 int
geterror(struct buf * bp)1213 geterror(struct buf *bp)
1214 {
1215 int error = 0;
1216
1217 if (bp->b_flags & B_ERROR) {
1218 error = bp->b_error;
1219 if (!error)
1220 error = EIO;
1221 }
1222 return (error);
1223 }
1224 #endif
1225