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