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