]> git.proxmox.com Git - mirror_zfs-debian.git/blob - lib/libzpool/kernel.c
New upstream version 0.7.6
[mirror_zfs-debian.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 * Copyright (c) 2016 Actifio, Inc. All rights reserved.
24 */
25
26 #include <assert.h>
27 #include <fcntl.h>
28 #include <poll.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <zlib.h>
33 #include <libgen.h>
34 #include <sys/signal.h>
35 #include <sys/spa.h>
36 #include <sys/stat.h>
37 #include <sys/processor.h>
38 #include <sys/zfs_context.h>
39 #include <sys/rrwlock.h>
40 #include <sys/utsname.h>
41 #include <sys/time.h>
42 #include <sys/systeminfo.h>
43 #include <zfs_fletcher.h>
44 #include <sys/crypto/icp.h>
45
46 /*
47 * Emulation of kernel services in userland.
48 */
49
50 int aok;
51 uint64_t physmem;
52 vnode_t *rootdir = (vnode_t *)0xabcd1234;
53 char hw_serial[HW_HOSTID_LEN];
54 struct utsname hw_utsname;
55 vmem_t *zio_arena = NULL;
56
57 /* If set, all blocks read will be copied to the specified directory. */
58 char *vn_dumpdir = NULL;
59
60 /* this only exists to have its address taken */
61 struct proc p0;
62
63 /*
64 * =========================================================================
65 * threads
66 * =========================================================================
67 */
68
69 pthread_cond_t kthread_cond = PTHREAD_COND_INITIALIZER;
70 pthread_mutex_t kthread_lock = PTHREAD_MUTEX_INITIALIZER;
71 pthread_key_t kthread_key;
72 int kthread_nr = 0;
73
74 void
75 thread_init(void)
76 {
77 kthread_t *kt;
78
79 VERIFY3S(pthread_key_create(&kthread_key, NULL), ==, 0);
80
81 /* Create entry for primary kthread */
82 kt = umem_zalloc(sizeof (kthread_t), UMEM_NOFAIL);
83 kt->t_tid = pthread_self();
84 kt->t_func = NULL;
85
86 VERIFY3S(pthread_setspecific(kthread_key, kt), ==, 0);
87
88 /* Only the main thread should be running at the moment */
89 ASSERT3S(kthread_nr, ==, 0);
90 kthread_nr = 1;
91 }
92
93 void
94 thread_fini(void)
95 {
96 kthread_t *kt = curthread;
97
98 ASSERT(pthread_equal(kt->t_tid, pthread_self()));
99 ASSERT3P(kt->t_func, ==, NULL);
100
101 umem_free(kt, sizeof (kthread_t));
102
103 /* Wait for all threads to exit via thread_exit() */
104 VERIFY3S(pthread_mutex_lock(&kthread_lock), ==, 0);
105
106 kthread_nr--; /* Main thread is exiting */
107
108 while (kthread_nr > 0)
109 VERIFY0(pthread_cond_wait(&kthread_cond, &kthread_lock));
110
111 ASSERT3S(kthread_nr, ==, 0);
112 VERIFY3S(pthread_mutex_unlock(&kthread_lock), ==, 0);
113
114 VERIFY3S(pthread_key_delete(kthread_key), ==, 0);
115 }
116
117 kthread_t *
118 zk_thread_current(void)
119 {
120 kthread_t *kt = pthread_getspecific(kthread_key);
121
122 ASSERT3P(kt, !=, NULL);
123
124 return (kt);
125 }
126
127 void *
128 zk_thread_helper(void *arg)
129 {
130 kthread_t *kt = (kthread_t *)arg;
131
132 VERIFY3S(pthread_setspecific(kthread_key, kt), ==, 0);
133
134 VERIFY3S(pthread_mutex_lock(&kthread_lock), ==, 0);
135 kthread_nr++;
136 VERIFY3S(pthread_mutex_unlock(&kthread_lock), ==, 0);
137 (void) setpriority(PRIO_PROCESS, 0, kt->t_pri);
138
139 kt->t_tid = pthread_self();
140 ((thread_func_arg_t)kt->t_func)(kt->t_arg);
141
142 /* Unreachable, thread must exit with thread_exit() */
143 abort();
144
145 return (NULL);
146 }
147
148 kthread_t *
149 zk_thread_create(caddr_t stk, size_t stksize, thread_func_t func, void *arg,
150 uint64_t len, proc_t *pp, int state, pri_t pri, int detachstate)
151 {
152 kthread_t *kt;
153 pthread_attr_t attr;
154 char *stkstr;
155
156 ASSERT0(state & ~TS_RUN);
157 ASSERT0(len);
158
159 kt = umem_zalloc(sizeof (kthread_t), UMEM_NOFAIL);
160 kt->t_func = func;
161 kt->t_arg = arg;
162 kt->t_pri = pri;
163
164 VERIFY0(pthread_attr_init(&attr));
165 VERIFY0(pthread_attr_setdetachstate(&attr, detachstate));
166
167 /*
168 * We allow the default stack size in user space to be specified by
169 * setting the ZFS_STACK_SIZE environment variable. This allows us
170 * the convenience of observing and debugging stack overruns in
171 * user space. Explicitly specified stack sizes will be honored.
172 * The usage of ZFS_STACK_SIZE is discussed further in the
173 * ENVIRONMENT VARIABLES sections of the ztest(1) man page.
174 */
175 if (stksize == 0) {
176 stkstr = getenv("ZFS_STACK_SIZE");
177
178 if (stkstr == NULL)
179 stksize = TS_STACK_MAX;
180 else
181 stksize = MAX(atoi(stkstr), TS_STACK_MIN);
182 }
183
184 VERIFY3S(stksize, >, 0);
185 stksize = P2ROUNDUP(MAX(stksize, TS_STACK_MIN), PAGESIZE);
186 /*
187 * If this ever fails, it may be because the stack size is not a
188 * multiple of system page size.
189 */
190 VERIFY0(pthread_attr_setstacksize(&attr, stksize));
191 VERIFY0(pthread_attr_setguardsize(&attr, PAGESIZE));
192
193 VERIFY0(pthread_create(&kt->t_tid, &attr, &zk_thread_helper, kt));
194 VERIFY0(pthread_attr_destroy(&attr));
195
196 return (kt);
197 }
198
199 void
200 zk_thread_exit(void)
201 {
202 kthread_t *kt = curthread;
203
204 ASSERT(pthread_equal(kt->t_tid, pthread_self()));
205
206 umem_free(kt, sizeof (kthread_t));
207
208 VERIFY0(pthread_mutex_lock(&kthread_lock));
209 kthread_nr--;
210 VERIFY0(pthread_mutex_unlock(&kthread_lock));
211
212 VERIFY0(pthread_cond_broadcast(&kthread_cond));
213 pthread_exit((void *)TS_MAGIC);
214 }
215
216 void
217 zk_thread_join(kt_did_t tid)
218 {
219 void *ret;
220
221 pthread_join((pthread_t)tid, &ret);
222 VERIFY3P(ret, ==, (void *)TS_MAGIC);
223 }
224
225 /*
226 * =========================================================================
227 * kstats
228 * =========================================================================
229 */
230 /*ARGSUSED*/
231 kstat_t *
232 kstat_create(const char *module, int instance, const char *name,
233 const char *class, uchar_t type, ulong_t ndata, uchar_t ks_flag)
234 {
235 return (NULL);
236 }
237
238 /*ARGSUSED*/
239 void
240 kstat_install(kstat_t *ksp)
241 {}
242
243 /*ARGSUSED*/
244 void
245 kstat_delete(kstat_t *ksp)
246 {}
247
248 /*ARGSUSED*/
249 void
250 kstat_waitq_enter(kstat_io_t *kiop)
251 {}
252
253 /*ARGSUSED*/
254 void
255 kstat_waitq_exit(kstat_io_t *kiop)
256 {}
257
258 /*ARGSUSED*/
259 void
260 kstat_runq_enter(kstat_io_t *kiop)
261 {}
262
263 /*ARGSUSED*/
264 void
265 kstat_runq_exit(kstat_io_t *kiop)
266 {}
267
268 /*ARGSUSED*/
269 void
270 kstat_waitq_to_runq(kstat_io_t *kiop)
271 {}
272
273 /*ARGSUSED*/
274 void
275 kstat_runq_back_to_waitq(kstat_io_t *kiop)
276 {}
277
278 void
279 kstat_set_raw_ops(kstat_t *ksp,
280 int (*headers)(char *buf, size_t size),
281 int (*data)(char *buf, size_t size, void *data),
282 void *(*addr)(kstat_t *ksp, loff_t index))
283 {}
284
285 /*
286 * =========================================================================
287 * mutexes
288 * =========================================================================
289 */
290
291 void
292 mutex_init(kmutex_t *mp, char *name, int type, void *cookie)
293 {
294 ASSERT3S(type, ==, MUTEX_DEFAULT);
295 ASSERT3P(cookie, ==, NULL);
296 mp->m_owner = MTX_INIT;
297 mp->m_magic = MTX_MAGIC;
298 VERIFY3S(pthread_mutex_init(&mp->m_lock, NULL), ==, 0);
299 }
300
301 void
302 mutex_destroy(kmutex_t *mp)
303 {
304 ASSERT3U(mp->m_magic, ==, MTX_MAGIC);
305 ASSERT3P(mp->m_owner, ==, MTX_INIT);
306 ASSERT0(pthread_mutex_destroy(&(mp)->m_lock));
307 mp->m_owner = MTX_DEST;
308 mp->m_magic = 0;
309 }
310
311 void
312 mutex_enter(kmutex_t *mp)
313 {
314 ASSERT3U(mp->m_magic, ==, MTX_MAGIC);
315 ASSERT3P(mp->m_owner, !=, MTX_DEST);
316 ASSERT3P(mp->m_owner, !=, curthread);
317 VERIFY3S(pthread_mutex_lock(&mp->m_lock), ==, 0);
318 ASSERT3P(mp->m_owner, ==, MTX_INIT);
319 mp->m_owner = curthread;
320 }
321
322 int
323 mutex_tryenter(kmutex_t *mp)
324 {
325 int err;
326 ASSERT3U(mp->m_magic, ==, MTX_MAGIC);
327 ASSERT3P(mp->m_owner, !=, MTX_DEST);
328 if (0 == (err = pthread_mutex_trylock(&mp->m_lock))) {
329 ASSERT3P(mp->m_owner, ==, MTX_INIT);
330 mp->m_owner = curthread;
331 return (1);
332 } else {
333 VERIFY3S(err, ==, EBUSY);
334 return (0);
335 }
336 }
337
338 void
339 mutex_exit(kmutex_t *mp)
340 {
341 ASSERT3U(mp->m_magic, ==, MTX_MAGIC);
342 ASSERT3P(mutex_owner(mp), ==, curthread);
343 mp->m_owner = MTX_INIT;
344 VERIFY3S(pthread_mutex_unlock(&mp->m_lock), ==, 0);
345 }
346
347 void *
348 mutex_owner(kmutex_t *mp)
349 {
350 ASSERT3U(mp->m_magic, ==, MTX_MAGIC);
351 return (mp->m_owner);
352 }
353
354 int
355 mutex_held(kmutex_t *mp)
356 {
357 return (mp->m_owner == curthread);
358 }
359
360 /*
361 * =========================================================================
362 * rwlocks
363 * =========================================================================
364 */
365
366 void
367 rw_init(krwlock_t *rwlp, char *name, int type, void *arg)
368 {
369 ASSERT3S(type, ==, RW_DEFAULT);
370 ASSERT3P(arg, ==, NULL);
371 VERIFY3S(pthread_rwlock_init(&rwlp->rw_lock, NULL), ==, 0);
372 rwlp->rw_owner = RW_INIT;
373 rwlp->rw_wr_owner = RW_INIT;
374 rwlp->rw_readers = 0;
375 rwlp->rw_magic = RW_MAGIC;
376 }
377
378 void
379 rw_destroy(krwlock_t *rwlp)
380 {
381 ASSERT3U(rwlp->rw_magic, ==, RW_MAGIC);
382 ASSERT(rwlp->rw_readers == 0 && rwlp->rw_wr_owner == RW_INIT);
383 VERIFY3S(pthread_rwlock_destroy(&rwlp->rw_lock), ==, 0);
384 rwlp->rw_magic = 0;
385 }
386
387 void
388 rw_enter(krwlock_t *rwlp, krw_t rw)
389 {
390 ASSERT3U(rwlp->rw_magic, ==, RW_MAGIC);
391 ASSERT3P(rwlp->rw_owner, !=, curthread);
392 ASSERT3P(rwlp->rw_wr_owner, !=, curthread);
393
394 if (rw == RW_READER) {
395 VERIFY3S(pthread_rwlock_rdlock(&rwlp->rw_lock), ==, 0);
396 ASSERT3P(rwlp->rw_wr_owner, ==, RW_INIT);
397
398 atomic_inc_uint(&rwlp->rw_readers);
399 } else {
400 VERIFY3S(pthread_rwlock_wrlock(&rwlp->rw_lock), ==, 0);
401 ASSERT3P(rwlp->rw_wr_owner, ==, RW_INIT);
402 ASSERT3U(rwlp->rw_readers, ==, 0);
403
404 rwlp->rw_wr_owner = curthread;
405 }
406
407 rwlp->rw_owner = curthread;
408 }
409
410 void
411 rw_exit(krwlock_t *rwlp)
412 {
413 ASSERT3U(rwlp->rw_magic, ==, RW_MAGIC);
414 ASSERT(RW_LOCK_HELD(rwlp));
415
416 if (RW_READ_HELD(rwlp))
417 atomic_dec_uint(&rwlp->rw_readers);
418 else
419 rwlp->rw_wr_owner = RW_INIT;
420
421 rwlp->rw_owner = RW_INIT;
422 VERIFY3S(pthread_rwlock_unlock(&rwlp->rw_lock), ==, 0);
423 }
424
425 int
426 rw_tryenter(krwlock_t *rwlp, krw_t rw)
427 {
428 int rv;
429
430 ASSERT3U(rwlp->rw_magic, ==, RW_MAGIC);
431
432 if (rw == RW_READER)
433 rv = pthread_rwlock_tryrdlock(&rwlp->rw_lock);
434 else
435 rv = pthread_rwlock_trywrlock(&rwlp->rw_lock);
436
437 if (rv == 0) {
438 ASSERT3P(rwlp->rw_wr_owner, ==, RW_INIT);
439
440 if (rw == RW_READER)
441 atomic_inc_uint(&rwlp->rw_readers);
442 else {
443 ASSERT3U(rwlp->rw_readers, ==, 0);
444 rwlp->rw_wr_owner = curthread;
445 }
446
447 rwlp->rw_owner = curthread;
448 return (1);
449 }
450
451 VERIFY3S(rv, ==, EBUSY);
452
453 return (0);
454 }
455
456 int
457 rw_tryupgrade(krwlock_t *rwlp)
458 {
459 ASSERT3U(rwlp->rw_magic, ==, RW_MAGIC);
460
461 return (0);
462 }
463
464 /*
465 * =========================================================================
466 * condition variables
467 * =========================================================================
468 */
469
470 void
471 cv_init(kcondvar_t *cv, char *name, int type, void *arg)
472 {
473 ASSERT3S(type, ==, CV_DEFAULT);
474 cv->cv_magic = CV_MAGIC;
475 VERIFY0(pthread_cond_init(&cv->cv, NULL));
476 }
477
478 void
479 cv_destroy(kcondvar_t *cv)
480 {
481 ASSERT3U(cv->cv_magic, ==, CV_MAGIC);
482 VERIFY0(pthread_cond_destroy(&cv->cv));
483 cv->cv_magic = 0;
484 }
485
486 void
487 cv_wait(kcondvar_t *cv, kmutex_t *mp)
488 {
489 ASSERT3U(cv->cv_magic, ==, CV_MAGIC);
490 ASSERT3P(mutex_owner(mp), ==, curthread);
491 mp->m_owner = MTX_INIT;
492 VERIFY0(pthread_cond_wait(&cv->cv, &mp->m_lock));
493 mp->m_owner = curthread;
494 }
495
496 clock_t
497 cv_timedwait(kcondvar_t *cv, kmutex_t *mp, clock_t abstime)
498 {
499 int error;
500 struct timeval tv;
501 timestruc_t ts;
502 clock_t delta;
503
504 ASSERT3U(cv->cv_magic, ==, CV_MAGIC);
505
506 delta = abstime - ddi_get_lbolt();
507 if (delta <= 0)
508 return (-1);
509
510 VERIFY(gettimeofday(&tv, NULL) == 0);
511
512 ts.tv_sec = tv.tv_sec + delta / hz;
513 ts.tv_nsec = tv.tv_usec * NSEC_PER_USEC + (delta % hz) * (NANOSEC / hz);
514 if (ts.tv_nsec >= NANOSEC) {
515 ts.tv_sec++;
516 ts.tv_nsec -= NANOSEC;
517 }
518
519 ASSERT3P(mutex_owner(mp), ==, curthread);
520 mp->m_owner = MTX_INIT;
521 error = pthread_cond_timedwait(&cv->cv, &mp->m_lock, &ts);
522 mp->m_owner = curthread;
523
524 if (error == ETIMEDOUT)
525 return (-1);
526
527 VERIFY0(error);
528
529 return (1);
530 }
531
532 /*ARGSUSED*/
533 clock_t
534 cv_timedwait_hires(kcondvar_t *cv, kmutex_t *mp, hrtime_t tim, hrtime_t res,
535 int flag)
536 {
537 int error;
538 struct timeval tv;
539 timestruc_t ts;
540 hrtime_t delta;
541
542 ASSERT(flag == 0 || flag == CALLOUT_FLAG_ABSOLUTE);
543
544 delta = tim;
545 if (flag & CALLOUT_FLAG_ABSOLUTE)
546 delta -= gethrtime();
547
548 if (delta <= 0)
549 return (-1);
550
551 VERIFY(gettimeofday(&tv, NULL) == 0);
552
553 ts.tv_sec = tv.tv_sec + delta / NANOSEC;
554 ts.tv_nsec = tv.tv_usec * NSEC_PER_USEC + (delta % NANOSEC);
555 if (ts.tv_nsec >= NANOSEC) {
556 ts.tv_sec++;
557 ts.tv_nsec -= NANOSEC;
558 }
559
560 ASSERT(mutex_owner(mp) == curthread);
561 mp->m_owner = MTX_INIT;
562 error = pthread_cond_timedwait(&cv->cv, &mp->m_lock, &ts);
563 mp->m_owner = curthread;
564
565 if (error == ETIMEDOUT)
566 return (-1);
567
568 VERIFY0(error);
569
570 return (1);
571 }
572
573 void
574 cv_signal(kcondvar_t *cv)
575 {
576 ASSERT3U(cv->cv_magic, ==, CV_MAGIC);
577 VERIFY0(pthread_cond_signal(&cv->cv));
578 }
579
580 void
581 cv_broadcast(kcondvar_t *cv)
582 {
583 ASSERT3U(cv->cv_magic, ==, CV_MAGIC);
584 VERIFY0(pthread_cond_broadcast(&cv->cv));
585 }
586
587 /*
588 * =========================================================================
589 * vnode operations
590 * =========================================================================
591 */
592 /*
593 * Note: for the xxxat() versions of these functions, we assume that the
594 * starting vp is always rootdir (which is true for spa_directory.c, the only
595 * ZFS consumer of these interfaces). We assert this is true, and then emulate
596 * them by adding '/' in front of the path.
597 */
598
599 /*ARGSUSED*/
600 int
601 vn_open(char *path, int x1, int flags, int mode, vnode_t **vpp, int x2, int x3)
602 {
603 int fd = -1;
604 int dump_fd = -1;
605 vnode_t *vp;
606 int old_umask = 0;
607 char *realpath;
608 struct stat64 st;
609 int err;
610
611 realpath = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
612
613 /*
614 * If we're accessing a real disk from userland, we need to use
615 * the character interface to avoid caching. This is particularly
616 * important if we're trying to look at a real in-kernel storage
617 * pool from userland, e.g. via zdb, because otherwise we won't
618 * see the changes occurring under the segmap cache.
619 * On the other hand, the stupid character device returns zero
620 * for its size. So -- gag -- we open the block device to get
621 * its size, and remember it for subsequent VOP_GETATTR().
622 */
623 #if defined(__sun__) || defined(__sun)
624 if (strncmp(path, "/dev/", 5) == 0) {
625 #else
626 if (0) {
627 #endif
628 char *dsk;
629 fd = open64(path, O_RDONLY);
630 if (fd == -1) {
631 err = errno;
632 free(realpath);
633 return (err);
634 }
635 if (fstat64(fd, &st) == -1) {
636 err = errno;
637 close(fd);
638 free(realpath);
639 return (err);
640 }
641 close(fd);
642 (void) sprintf(realpath, "%s", path);
643 dsk = strstr(path, "/dsk/");
644 if (dsk != NULL)
645 (void) sprintf(realpath + (dsk - path) + 1, "r%s",
646 dsk + 1);
647 } else {
648 (void) sprintf(realpath, "%s", path);
649 if (!(flags & FCREAT) && stat64(realpath, &st) == -1) {
650 err = errno;
651 free(realpath);
652 return (err);
653 }
654 }
655
656 if (!(flags & FCREAT) && S_ISBLK(st.st_mode)) {
657 #ifdef __linux__
658 flags |= O_DIRECT;
659 #endif
660 /* We shouldn't be writing to block devices in userspace */
661 VERIFY(!(flags & FWRITE));
662 }
663
664 if (flags & FCREAT)
665 old_umask = umask(0);
666
667 /*
668 * The construct 'flags - FREAD' conveniently maps combinations of
669 * FREAD and FWRITE to the corresponding O_RDONLY, O_WRONLY, and O_RDWR.
670 */
671 fd = open64(realpath, flags - FREAD, mode);
672 if (fd == -1) {
673 err = errno;
674 free(realpath);
675 return (err);
676 }
677
678 if (flags & FCREAT)
679 (void) umask(old_umask);
680
681 if (vn_dumpdir != NULL) {
682 char *dumppath = umem_zalloc(MAXPATHLEN, UMEM_NOFAIL);
683 (void) snprintf(dumppath, MAXPATHLEN,
684 "%s/%s", vn_dumpdir, basename(realpath));
685 dump_fd = open64(dumppath, O_CREAT | O_WRONLY, 0666);
686 umem_free(dumppath, MAXPATHLEN);
687 if (dump_fd == -1) {
688 err = errno;
689 free(realpath);
690 close(fd);
691 return (err);
692 }
693 } else {
694 dump_fd = -1;
695 }
696
697 free(realpath);
698
699 if (fstat64_blk(fd, &st) == -1) {
700 err = errno;
701 close(fd);
702 if (dump_fd != -1)
703 close(dump_fd);
704 return (err);
705 }
706
707 (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
708
709 *vpp = vp = umem_zalloc(sizeof (vnode_t), UMEM_NOFAIL);
710
711 vp->v_fd = fd;
712 vp->v_size = st.st_size;
713 vp->v_path = spa_strdup(path);
714 vp->v_dump_fd = dump_fd;
715
716 return (0);
717 }
718
719 /*ARGSUSED*/
720 int
721 vn_openat(char *path, int x1, int flags, int mode, vnode_t **vpp, int x2,
722 int x3, vnode_t *startvp, int fd)
723 {
724 char *realpath = umem_alloc(strlen(path) + 2, UMEM_NOFAIL);
725 int ret;
726
727 ASSERT(startvp == rootdir);
728 (void) sprintf(realpath, "/%s", path);
729
730 /* fd ignored for now, need if want to simulate nbmand support */
731 ret = vn_open(realpath, x1, flags, mode, vpp, x2, x3);
732
733 umem_free(realpath, strlen(path) + 2);
734
735 return (ret);
736 }
737
738 /*ARGSUSED*/
739 int
740 vn_rdwr(int uio, vnode_t *vp, void *addr, ssize_t len, offset_t offset,
741 int x1, int x2, rlim64_t x3, void *x4, ssize_t *residp)
742 {
743 ssize_t rc, done = 0, split;
744
745 if (uio == UIO_READ) {
746 rc = pread64(vp->v_fd, addr, len, offset);
747 if (vp->v_dump_fd != -1 && rc != -1) {
748 int status;
749 status = pwrite64(vp->v_dump_fd, addr, rc, offset);
750 ASSERT(status != -1);
751 }
752 } else {
753 /*
754 * To simulate partial disk writes, we split writes into two
755 * system calls so that the process can be killed in between.
756 */
757 int sectors = len >> SPA_MINBLOCKSHIFT;
758 split = (sectors > 0 ? rand() % sectors : 0) <<
759 SPA_MINBLOCKSHIFT;
760 rc = pwrite64(vp->v_fd, addr, split, offset);
761 if (rc != -1) {
762 done = rc;
763 rc = pwrite64(vp->v_fd, (char *)addr + split,
764 len - split, offset + split);
765 }
766 }
767
768 #ifdef __linux__
769 if (rc == -1 && errno == EINVAL) {
770 /*
771 * Under Linux, this most likely means an alignment issue
772 * (memory or disk) due to O_DIRECT, so we abort() in order to
773 * catch the offender.
774 */
775 abort();
776 }
777 #endif
778 if (rc == -1)
779 return (errno);
780
781 done += rc;
782
783 if (residp)
784 *residp = len - done;
785 else if (done != len)
786 return (EIO);
787 return (0);
788 }
789
790 void
791 vn_close(vnode_t *vp)
792 {
793 close(vp->v_fd);
794 if (vp->v_dump_fd != -1)
795 close(vp->v_dump_fd);
796 spa_strfree(vp->v_path);
797 umem_free(vp, sizeof (vnode_t));
798 }
799
800 /*
801 * At a minimum we need to update the size since vdev_reopen()
802 * will no longer call vn_openat().
803 */
804 int
805 fop_getattr(vnode_t *vp, vattr_t *vap)
806 {
807 struct stat64 st;
808 int err;
809
810 if (fstat64_blk(vp->v_fd, &st) == -1) {
811 err = errno;
812 close(vp->v_fd);
813 return (err);
814 }
815
816 vap->va_size = st.st_size;
817 return (0);
818 }
819
820 /*
821 * =========================================================================
822 * Figure out which debugging statements to print
823 * =========================================================================
824 */
825
826 static char *dprintf_string;
827 static int dprintf_print_all;
828
829 int
830 dprintf_find_string(const char *string)
831 {
832 char *tmp_str = dprintf_string;
833 int len = strlen(string);
834
835 /*
836 * Find out if this is a string we want to print.
837 * String format: file1.c,function_name1,file2.c,file3.c
838 */
839
840 while (tmp_str != NULL) {
841 if (strncmp(tmp_str, string, len) == 0 &&
842 (tmp_str[len] == ',' || tmp_str[len] == '\0'))
843 return (1);
844 tmp_str = strchr(tmp_str, ',');
845 if (tmp_str != NULL)
846 tmp_str++; /* Get rid of , */
847 }
848 return (0);
849 }
850
851 void
852 dprintf_setup(int *argc, char **argv)
853 {
854 int i, j;
855
856 /*
857 * Debugging can be specified two ways: by setting the
858 * environment variable ZFS_DEBUG, or by including a
859 * "debug=..." argument on the command line. The command
860 * line setting overrides the environment variable.
861 */
862
863 for (i = 1; i < *argc; i++) {
864 int len = strlen("debug=");
865 /* First look for a command line argument */
866 if (strncmp("debug=", argv[i], len) == 0) {
867 dprintf_string = argv[i] + len;
868 /* Remove from args */
869 for (j = i; j < *argc; j++)
870 argv[j] = argv[j+1];
871 argv[j] = NULL;
872 (*argc)--;
873 }
874 }
875
876 if (dprintf_string == NULL) {
877 /* Look for ZFS_DEBUG environment variable */
878 dprintf_string = getenv("ZFS_DEBUG");
879 }
880
881 /*
882 * Are we just turning on all debugging?
883 */
884 if (dprintf_find_string("on"))
885 dprintf_print_all = 1;
886
887 if (dprintf_string != NULL)
888 zfs_flags |= ZFS_DEBUG_DPRINTF;
889 }
890
891 /*
892 * =========================================================================
893 * debug printfs
894 * =========================================================================
895 */
896 void
897 __dprintf(const char *file, const char *func, int line, const char *fmt, ...)
898 {
899 const char *newfile;
900 va_list adx;
901
902 /*
903 * Get rid of annoying "../common/" prefix to filename.
904 */
905 newfile = strrchr(file, '/');
906 if (newfile != NULL) {
907 newfile = newfile + 1; /* Get rid of leading / */
908 } else {
909 newfile = file;
910 }
911
912 if (dprintf_print_all ||
913 dprintf_find_string(newfile) ||
914 dprintf_find_string(func)) {
915 /* Print out just the function name if requested */
916 flockfile(stdout);
917 if (dprintf_find_string("pid"))
918 (void) printf("%d ", getpid());
919 if (dprintf_find_string("tid"))
920 (void) printf("%u ", (uint_t)pthread_self());
921 if (dprintf_find_string("cpu"))
922 (void) printf("%u ", getcpuid());
923 if (dprintf_find_string("time"))
924 (void) printf("%llu ", gethrtime());
925 if (dprintf_find_string("long"))
926 (void) printf("%s, line %d: ", newfile, line);
927 (void) printf("%s: ", func);
928 va_start(adx, fmt);
929 (void) vprintf(fmt, adx);
930 va_end(adx);
931 funlockfile(stdout);
932 }
933 }
934
935 /*
936 * =========================================================================
937 * cmn_err() and panic()
938 * =========================================================================
939 */
940 static char ce_prefix[CE_IGNORE][10] = { "", "NOTICE: ", "WARNING: ", "" };
941 static char ce_suffix[CE_IGNORE][2] = { "", "\n", "\n", "" };
942
943 void
944 vpanic(const char *fmt, va_list adx)
945 {
946 (void) fprintf(stderr, "error: ");
947 (void) vfprintf(stderr, fmt, adx);
948 (void) fprintf(stderr, "\n");
949
950 abort(); /* think of it as a "user-level crash dump" */
951 }
952
953 void
954 panic(const char *fmt, ...)
955 {
956 va_list adx;
957
958 va_start(adx, fmt);
959 vpanic(fmt, adx);
960 va_end(adx);
961 }
962
963 void
964 vcmn_err(int ce, const char *fmt, va_list adx)
965 {
966 if (ce == CE_PANIC)
967 vpanic(fmt, adx);
968 if (ce != CE_NOTE) { /* suppress noise in userland stress testing */
969 (void) fprintf(stderr, "%s", ce_prefix[ce]);
970 (void) vfprintf(stderr, fmt, adx);
971 (void) fprintf(stderr, "%s", ce_suffix[ce]);
972 }
973 }
974
975 /*PRINTFLIKE2*/
976 void
977 cmn_err(int ce, const char *fmt, ...)
978 {
979 va_list adx;
980
981 va_start(adx, fmt);
982 vcmn_err(ce, fmt, adx);
983 va_end(adx);
984 }
985
986 /*
987 * =========================================================================
988 * kobj interfaces
989 * =========================================================================
990 */
991 struct _buf *
992 kobj_open_file(char *name)
993 {
994 struct _buf *file;
995 vnode_t *vp;
996
997 /* set vp as the _fd field of the file */
998 if (vn_openat(name, UIO_SYSSPACE, FREAD, 0, &vp, 0, 0, rootdir,
999 -1) != 0)
1000 return ((void *)-1UL);
1001
1002 file = umem_zalloc(sizeof (struct _buf), UMEM_NOFAIL);
1003 file->_fd = (intptr_t)vp;
1004 return (file);
1005 }
1006
1007 int
1008 kobj_read_file(struct _buf *file, char *buf, unsigned size, unsigned off)
1009 {
1010 ssize_t resid = 0;
1011
1012 if (vn_rdwr(UIO_READ, (vnode_t *)file->_fd, buf, size, (offset_t)off,
1013 UIO_SYSSPACE, 0, 0, 0, &resid) != 0)
1014 return (-1);
1015
1016 return (size - resid);
1017 }
1018
1019 void
1020 kobj_close_file(struct _buf *file)
1021 {
1022 vn_close((vnode_t *)file->_fd);
1023 umem_free(file, sizeof (struct _buf));
1024 }
1025
1026 int
1027 kobj_get_filesize(struct _buf *file, uint64_t *size)
1028 {
1029 struct stat64 st;
1030 vnode_t *vp = (vnode_t *)file->_fd;
1031
1032 if (fstat64(vp->v_fd, &st) == -1) {
1033 vn_close(vp);
1034 return (errno);
1035 }
1036 *size = st.st_size;
1037 return (0);
1038 }
1039
1040 /*
1041 * =========================================================================
1042 * misc routines
1043 * =========================================================================
1044 */
1045
1046 void
1047 delay(clock_t ticks)
1048 {
1049 (void) poll(0, 0, ticks * (1000 / hz));
1050 }
1051
1052 /*
1053 * Find highest one bit set.
1054 * Returns bit number + 1 of highest bit that is set, otherwise returns 0.
1055 * High order bit is 31 (or 63 in _LP64 kernel).
1056 */
1057 int
1058 highbit64(uint64_t i)
1059 {
1060 register int h = 1;
1061
1062 if (i == 0)
1063 return (0);
1064 if (i & 0xffffffff00000000ULL) {
1065 h += 32; i >>= 32;
1066 }
1067 if (i & 0xffff0000) {
1068 h += 16; i >>= 16;
1069 }
1070 if (i & 0xff00) {
1071 h += 8; i >>= 8;
1072 }
1073 if (i & 0xf0) {
1074 h += 4; i >>= 4;
1075 }
1076 if (i & 0xc) {
1077 h += 2; i >>= 2;
1078 }
1079 if (i & 0x2) {
1080 h += 1;
1081 }
1082 return (h);
1083 }
1084
1085 /*
1086 * Find lowest one bit set.
1087 * Returns bit number + 1 of lowest bit that is set, otherwise returns 0.
1088 * This is basically a reimplementation of ffsll(), which is GNU specific.
1089 */
1090 int
1091 lowbit64(uint64_t i)
1092 {
1093 register int h = 64;
1094 if (i == 0)
1095 return (0);
1096
1097 if (i & 0x00000000ffffffffULL)
1098 h -= 32;
1099 else
1100 i >>= 32;
1101
1102 if (i & 0x0000ffff)
1103 h -= 16;
1104 else
1105 i >>= 16;
1106
1107 if (i & 0x00ff)
1108 h -= 8;
1109 else
1110 i >>= 8;
1111
1112 if (i & 0x0f)
1113 h -= 4;
1114 else
1115 i >>= 4;
1116
1117 if (i & 0x3)
1118 h -= 2;
1119 else
1120 i >>= 2;
1121
1122 if (i & 0x1)
1123 h -= 1;
1124
1125 return (h);
1126 }
1127
1128 /*
1129 * Find highest one bit set.
1130 * Returns bit number + 1 of highest bit that is set, otherwise returns 0.
1131 * High order bit is 31 (or 63 in _LP64 kernel).
1132 */
1133 int
1134 highbit(ulong_t i)
1135 {
1136 register int h = 1;
1137
1138 if (i == 0)
1139 return (0);
1140 #ifdef _LP64
1141 if (i & 0xffffffff00000000ul) {
1142 h += 32; i >>= 32;
1143 }
1144 #endif
1145 if (i & 0xffff0000) {
1146 h += 16; i >>= 16;
1147 }
1148 if (i & 0xff00) {
1149 h += 8; i >>= 8;
1150 }
1151 if (i & 0xf0) {
1152 h += 4; i >>= 4;
1153 }
1154 if (i & 0xc) {
1155 h += 2; i >>= 2;
1156 }
1157 if (i & 0x2) {
1158 h += 1;
1159 }
1160 return (h);
1161 }
1162
1163 /*
1164 * Find lowest one bit set.
1165 * Returns bit number + 1 of lowest bit that is set, otherwise returns 0.
1166 * Low order bit is 0.
1167 */
1168 int
1169 lowbit(ulong_t i)
1170 {
1171 register int h = 1;
1172
1173 if (i == 0)
1174 return (0);
1175
1176 #ifdef _LP64
1177 if (!(i & 0xffffffff)) {
1178 h += 32; i >>= 32;
1179 }
1180 #endif
1181 if (!(i & 0xffff)) {
1182 h += 16; i >>= 16;
1183 }
1184 if (!(i & 0xff)) {
1185 h += 8; i >>= 8;
1186 }
1187 if (!(i & 0xf)) {
1188 h += 4; i >>= 4;
1189 }
1190 if (!(i & 0x3)) {
1191 h += 2; i >>= 2;
1192 }
1193 if (!(i & 0x1)) {
1194 h += 1;
1195 }
1196 return (h);
1197 }
1198
1199 static int random_fd = -1, urandom_fd = -1;
1200
1201 void
1202 random_init(void)
1203 {
1204 VERIFY((random_fd = open("/dev/random", O_RDONLY)) != -1);
1205 VERIFY((urandom_fd = open("/dev/urandom", O_RDONLY)) != -1);
1206 }
1207
1208 void
1209 random_fini(void)
1210 {
1211 close(random_fd);
1212 close(urandom_fd);
1213
1214 random_fd = -1;
1215 urandom_fd = -1;
1216 }
1217
1218 static int
1219 random_get_bytes_common(uint8_t *ptr, size_t len, int fd)
1220 {
1221 size_t resid = len;
1222 ssize_t bytes;
1223
1224 ASSERT(fd != -1);
1225
1226 while (resid != 0) {
1227 bytes = read(fd, ptr, resid);
1228 ASSERT3S(bytes, >=, 0);
1229 ptr += bytes;
1230 resid -= bytes;
1231 }
1232
1233 return (0);
1234 }
1235
1236 int
1237 random_get_bytes(uint8_t *ptr, size_t len)
1238 {
1239 return (random_get_bytes_common(ptr, len, random_fd));
1240 }
1241
1242 int
1243 random_get_pseudo_bytes(uint8_t *ptr, size_t len)
1244 {
1245 return (random_get_bytes_common(ptr, len, urandom_fd));
1246 }
1247
1248 int
1249 ddi_strtoul(const char *hw_serial, char **nptr, int base, unsigned long *result)
1250 {
1251 char *end;
1252
1253 *result = strtoul(hw_serial, &end, base);
1254 if (*result == 0)
1255 return (errno);
1256 return (0);
1257 }
1258
1259 int
1260 ddi_strtoull(const char *str, char **nptr, int base, u_longlong_t *result)
1261 {
1262 char *end;
1263
1264 *result = strtoull(str, &end, base);
1265 if (*result == 0)
1266 return (errno);
1267 return (0);
1268 }
1269
1270 utsname_t *
1271 utsname(void)
1272 {
1273 return (&hw_utsname);
1274 }
1275
1276 /*
1277 * =========================================================================
1278 * kernel emulation setup & teardown
1279 * =========================================================================
1280 */
1281 static int
1282 umem_out_of_memory(void)
1283 {
1284 char errmsg[] = "out of memory -- generating core dump\n";
1285
1286 (void) fprintf(stderr, "%s", errmsg);
1287 abort();
1288 return (0);
1289 }
1290
1291 #define HOSTID_MASK 0xffffffff
1292
1293 static unsigned long
1294 get_spl_hostid(void)
1295 {
1296 FILE *f;
1297 unsigned long hostid;
1298 char *env;
1299
1300 /*
1301 * Allow the hostid to be subverted for testing.
1302 */
1303 env = getenv("ZFS_HOSTID");
1304 if (env) {
1305 hostid = strtoull(env, NULL, 0);
1306 return (hostid & HOSTID_MASK);
1307 }
1308
1309 f = fopen("/sys/module/spl/parameters/spl_hostid", "r");
1310 if (!f)
1311 return (0);
1312
1313 if (fscanf(f, "%lu", &hostid) != 1)
1314 hostid = 0;
1315
1316 fclose(f);
1317
1318 return (hostid & HOSTID_MASK);
1319 }
1320
1321 unsigned long
1322 get_system_hostid(void)
1323 {
1324 unsigned long system_hostid = get_spl_hostid();
1325 /*
1326 * We do not use the library call gethostid() because
1327 * it generates a hostid value that the kernel is
1328 * unaware of, if the spl_hostid module parameter has not
1329 * been set and there is no system hostid file (e.g.
1330 * /etc/hostid). The kernel and userspace must agree.
1331 * See comments above hostid_read() in the SPL.
1332 */
1333 if (system_hostid == 0) {
1334 int fd, rc;
1335 unsigned long hostid;
1336 int hostid_size = 4; /* 4 bytes regardless of arch */
1337
1338 fd = open("/etc/hostid", O_RDONLY);
1339 if (fd >= 0) {
1340 rc = read(fd, &hostid, hostid_size);
1341 if (rc > 0)
1342 system_hostid = (hostid & HOSTID_MASK);
1343 close(fd);
1344 }
1345 }
1346 return (system_hostid);
1347 }
1348
1349 void
1350 kernel_init(int mode)
1351 {
1352 extern uint_t rrw_tsd_key;
1353
1354 umem_nofail_callback(umem_out_of_memory);
1355
1356 physmem = sysconf(_SC_PHYS_PAGES);
1357
1358 dprintf("physmem = %llu pages (%.2f GB)\n", physmem,
1359 (double)physmem * sysconf(_SC_PAGE_SIZE) / (1ULL << 30));
1360
1361 (void) snprintf(hw_serial, sizeof (hw_serial), "%ld",
1362 (mode & FWRITE) ? get_system_hostid() : 0);
1363
1364 random_init();
1365
1366 VERIFY0(uname(&hw_utsname));
1367
1368 thread_init();
1369 system_taskq_init();
1370 icp_init();
1371
1372 spa_init(mode);
1373
1374 fletcher_4_init();
1375
1376 tsd_create(&rrw_tsd_key, rrw_tsd_destroy);
1377 }
1378
1379 void
1380 kernel_fini(void)
1381 {
1382 fletcher_4_fini();
1383 spa_fini();
1384
1385 icp_fini();
1386 system_taskq_fini();
1387 thread_fini();
1388
1389 random_fini();
1390 }
1391
1392 uid_t
1393 crgetuid(cred_t *cr)
1394 {
1395 return (0);
1396 }
1397
1398 uid_t
1399 crgetruid(cred_t *cr)
1400 {
1401 return (0);
1402 }
1403
1404 gid_t
1405 crgetgid(cred_t *cr)
1406 {
1407 return (0);
1408 }
1409
1410 int
1411 crgetngroups(cred_t *cr)
1412 {
1413 return (0);
1414 }
1415
1416 gid_t *
1417 crgetgroups(cred_t *cr)
1418 {
1419 return (NULL);
1420 }
1421
1422 int
1423 zfs_secpolicy_snapshot_perms(const char *name, cred_t *cr)
1424 {
1425 return (0);
1426 }
1427
1428 int
1429 zfs_secpolicy_rename_perms(const char *from, const char *to, cred_t *cr)
1430 {
1431 return (0);
1432 }
1433
1434 int
1435 zfs_secpolicy_destroy_perms(const char *name, cred_t *cr)
1436 {
1437 return (0);
1438 }
1439
1440 int
1441 secpolicy_zfs(const cred_t *cr)
1442 {
1443 return (0);
1444 }
1445
1446 ksiddomain_t *
1447 ksid_lookupdomain(const char *dom)
1448 {
1449 ksiddomain_t *kd;
1450
1451 kd = umem_zalloc(sizeof (ksiddomain_t), UMEM_NOFAIL);
1452 kd->kd_name = spa_strdup(dom);
1453 return (kd);
1454 }
1455
1456 void
1457 ksiddomain_rele(ksiddomain_t *ksid)
1458 {
1459 spa_strfree(ksid->kd_name);
1460 umem_free(ksid, sizeof (ksiddomain_t));
1461 }
1462
1463 char *
1464 kmem_vasprintf(const char *fmt, va_list adx)
1465 {
1466 char *buf = NULL;
1467 va_list adx_copy;
1468
1469 va_copy(adx_copy, adx);
1470 VERIFY(vasprintf(&buf, fmt, adx_copy) != -1);
1471 va_end(adx_copy);
1472
1473 return (buf);
1474 }
1475
1476 char *
1477 kmem_asprintf(const char *fmt, ...)
1478 {
1479 char *buf = NULL;
1480 va_list adx;
1481
1482 va_start(adx, fmt);
1483 VERIFY(vasprintf(&buf, fmt, adx) != -1);
1484 va_end(adx);
1485
1486 return (buf);
1487 }
1488
1489 /* ARGSUSED */
1490 int
1491 zfs_onexit_fd_hold(int fd, minor_t *minorp)
1492 {
1493 *minorp = 0;
1494 return (0);
1495 }
1496
1497 /* ARGSUSED */
1498 void
1499 zfs_onexit_fd_rele(int fd)
1500 {
1501 }
1502
1503 /* ARGSUSED */
1504 int
1505 zfs_onexit_add_cb(minor_t minor, void (*func)(void *), void *data,
1506 uint64_t *action_handle)
1507 {
1508 return (0);
1509 }
1510
1511 /* ARGSUSED */
1512 int
1513 zfs_onexit_del_cb(minor_t minor, uint64_t action_handle, boolean_t fire)
1514 {
1515 return (0);
1516 }
1517
1518 /* ARGSUSED */
1519 int
1520 zfs_onexit_cb_data(minor_t minor, uint64_t action_handle, void **data)
1521 {
1522 return (0);
1523 }
1524
1525 fstrans_cookie_t
1526 spl_fstrans_mark(void)
1527 {
1528 return ((fstrans_cookie_t)0);
1529 }
1530
1531 void
1532 spl_fstrans_unmark(fstrans_cookie_t cookie)
1533 {
1534 }
1535
1536 int
1537 __spl_pf_fstrans_check(void)
1538 {
1539 return (0);
1540 }
1541
1542 void *zvol_tag = "zvol_tag";
1543
1544 void
1545 zvol_create_minors(spa_t *spa, const char *name, boolean_t async)
1546 {
1547 }
1548
1549 void
1550 zvol_remove_minor(spa_t *spa, const char *name, boolean_t async)
1551 {
1552 }
1553
1554 void
1555 zvol_remove_minors(spa_t *spa, const char *name, boolean_t async)
1556 {
1557 }
1558
1559 void
1560 zvol_rename_minors(spa_t *spa, const char *oldname, const char *newname,
1561 boolean_t async)
1562 {
1563 }