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