xref: /titanic_52/usr/src/lib/libzpool/common/kernel.c (revision 0d63ce2b32a9e1cc8ed71d4d92536c44d66a530a)
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 2007 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 #include <assert.h>
29 #include <fcntl.h>
30 #include <poll.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <zlib.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/zmod.h>
40 
41 /*
42  * Emulation of kernel services in userland.
43  */
44 
45 uint64_t physmem;
46 vnode_t *rootdir = (vnode_t *)0xabcd1234;
47 
48 /*
49  * =========================================================================
50  * threads
51  * =========================================================================
52  */
53 /*ARGSUSED*/
54 kthread_t *
55 zk_thread_create(void (*func)(), void *arg)
56 {
57 	thread_t tid;
58 
59 	VERIFY(thr_create(0, 0, (void *(*)(void *))func, arg, THR_DETACHED,
60 	    &tid) == 0);
61 
62 	return ((void *)(uintptr_t)tid);
63 }
64 
65 /*
66  * =========================================================================
67  * kstats
68  * =========================================================================
69  */
70 /*ARGSUSED*/
71 kstat_t *
72 kstat_create(char *module, int instance, char *name, char *class,
73     uchar_t type, ulong_t ndata, uchar_t ks_flag)
74 {
75 	return (NULL);
76 }
77 
78 /*ARGSUSED*/
79 void
80 kstat_install(kstat_t *ksp)
81 {}
82 
83 /*ARGSUSED*/
84 void
85 kstat_delete(kstat_t *ksp)
86 {}
87 
88 /*
89  * =========================================================================
90  * mutexes
91  * =========================================================================
92  */
93 void
94 zmutex_init(kmutex_t *mp)
95 {
96 	mp->m_owner = NULL;
97 	(void) _mutex_init(&mp->m_lock, USYNC_THREAD, NULL);
98 }
99 
100 void
101 zmutex_destroy(kmutex_t *mp)
102 {
103 	ASSERT(mp->m_owner == NULL);
104 	(void) _mutex_destroy(&(mp)->m_lock);
105 	mp->m_owner = (void *)-1UL;
106 }
107 
108 void
109 mutex_enter(kmutex_t *mp)
110 {
111 	ASSERT(mp->m_owner != (void *)-1UL);
112 	ASSERT(mp->m_owner != curthread);
113 	VERIFY(mutex_lock(&mp->m_lock) == 0);
114 	ASSERT(mp->m_owner == NULL);
115 	mp->m_owner = curthread;
116 }
117 
118 int
119 mutex_tryenter(kmutex_t *mp)
120 {
121 	ASSERT(mp->m_owner != (void *)-1UL);
122 	if (0 == mutex_trylock(&mp->m_lock)) {
123 		ASSERT(mp->m_owner == NULL);
124 		mp->m_owner = curthread;
125 		return (1);
126 	} else {
127 		return (0);
128 	}
129 }
130 
131 void
132 mutex_exit(kmutex_t *mp)
133 {
134 	ASSERT(mutex_owner(mp) == curthread);
135 	mp->m_owner = NULL;
136 	VERIFY(mutex_unlock(&mp->m_lock) == 0);
137 }
138 
139 void *
140 mutex_owner(kmutex_t *mp)
141 {
142 	return (mp->m_owner);
143 }
144 
145 /*
146  * =========================================================================
147  * rwlocks
148  * =========================================================================
149  */
150 /*ARGSUSED*/
151 void
152 rw_init(krwlock_t *rwlp, char *name, int type, void *arg)
153 {
154 	rwlock_init(&rwlp->rw_lock, USYNC_THREAD, NULL);
155 	rwlp->rw_owner = NULL;
156 }
157 
158 void
159 rw_destroy(krwlock_t *rwlp)
160 {
161 	rwlock_destroy(&rwlp->rw_lock);
162 	rwlp->rw_owner = (void *)-1UL;
163 }
164 
165 void
166 rw_enter(krwlock_t *rwlp, krw_t rw)
167 {
168 	ASSERT(!RW_LOCK_HELD(rwlp));
169 	ASSERT(rwlp->rw_owner != (void *)-1UL);
170 	ASSERT(rwlp->rw_owner != curthread);
171 
172 	if (rw == RW_READER)
173 		(void) rw_rdlock(&rwlp->rw_lock);
174 	else
175 		(void) rw_wrlock(&rwlp->rw_lock);
176 
177 	rwlp->rw_owner = curthread;
178 }
179 
180 void
181 rw_exit(krwlock_t *rwlp)
182 {
183 	ASSERT(rwlp->rw_owner != (void *)-1UL);
184 
185 	rwlp->rw_owner = NULL;
186 	(void) rw_unlock(&rwlp->rw_lock);
187 }
188 
189 int
190 rw_tryenter(krwlock_t *rwlp, krw_t rw)
191 {
192 	int rv;
193 
194 	ASSERT(rwlp->rw_owner != (void *)-1UL);
195 
196 	if (rw == RW_READER)
197 		rv = rw_tryrdlock(&rwlp->rw_lock);
198 	else
199 		rv = rw_trywrlock(&rwlp->rw_lock);
200 
201 	if (rv == 0) {
202 		rwlp->rw_owner = curthread;
203 		return (1);
204 	}
205 
206 	return (0);
207 }
208 
209 /*ARGSUSED*/
210 int
211 rw_tryupgrade(krwlock_t *rwlp)
212 {
213 	ASSERT(rwlp->rw_owner != (void *)-1UL);
214 
215 	return (0);
216 }
217 
218 /*
219  * =========================================================================
220  * condition variables
221  * =========================================================================
222  */
223 /*ARGSUSED*/
224 void
225 cv_init(kcondvar_t *cv, char *name, int type, void *arg)
226 {
227 	VERIFY(cond_init(cv, type, NULL) == 0);
228 }
229 
230 void
231 cv_destroy(kcondvar_t *cv)
232 {
233 	VERIFY(cond_destroy(cv) == 0);
234 }
235 
236 void
237 cv_wait(kcondvar_t *cv, kmutex_t *mp)
238 {
239 	ASSERT(mutex_owner(mp) == curthread);
240 	mp->m_owner = NULL;
241 	int ret = cond_wait(cv, &mp->m_lock);
242 	VERIFY(ret == 0 || ret == EINTR);
243 	mp->m_owner = curthread;
244 }
245 
246 clock_t
247 cv_timedwait(kcondvar_t *cv, kmutex_t *mp, clock_t abstime)
248 {
249 	int error;
250 	timestruc_t ts;
251 	clock_t delta;
252 
253 top:
254 	delta = abstime - lbolt;
255 	if (delta <= 0)
256 		return (-1);
257 
258 	ts.tv_sec = delta / hz;
259 	ts.tv_nsec = (delta % hz) * (NANOSEC / hz);
260 
261 	ASSERT(mutex_owner(mp) == curthread);
262 	mp->m_owner = NULL;
263 	error = cond_reltimedwait(cv, &mp->m_lock, &ts);
264 	mp->m_owner = curthread;
265 
266 	if (error == ETIME)
267 		return (-1);
268 
269 	if (error == EINTR)
270 		goto top;
271 
272 	ASSERT(error == 0);
273 
274 	return (1);
275 }
276 
277 void
278 cv_signal(kcondvar_t *cv)
279 {
280 	VERIFY(cond_signal(cv) == 0);
281 }
282 
283 void
284 cv_broadcast(kcondvar_t *cv)
285 {
286 	VERIFY(cond_broadcast(cv) == 0);
287 }
288 
289 /*
290  * =========================================================================
291  * vnode operations
292  * =========================================================================
293  */
294 /*
295  * Note: for the xxxat() versions of these functions, we assume that the
296  * starting vp is always rootdir (which is true for spa_directory.c, the only
297  * ZFS consumer of these interfaces).  We assert this is true, and then emulate
298  * them by adding '/' in front of the path.
299  */
300 
301 /*ARGSUSED*/
302 int
303 vn_open(char *path, int x1, int flags, int mode, vnode_t **vpp, int x2, int x3)
304 {
305 	int fd;
306 	vnode_t *vp;
307 	int old_umask;
308 	char realpath[MAXPATHLEN];
309 	struct stat64 st;
310 
311 	/*
312 	 * If we're accessing a real disk from userland, we need to use
313 	 * the character interface to avoid caching.  This is particularly
314 	 * important if we're trying to look at a real in-kernel storage
315 	 * pool from userland, e.g. via zdb, because otherwise we won't
316 	 * see the changes occurring under the segmap cache.
317 	 * On the other hand, the stupid character device returns zero
318 	 * for its size.  So -- gag -- we open the block device to get
319 	 * its size, and remember it for subsequent VOP_GETATTR().
320 	 */
321 	if (strncmp(path, "/dev/", 5) == 0) {
322 		char *dsk;
323 		fd = open64(path, O_RDONLY);
324 		if (fd == -1)
325 			return (errno);
326 		if (fstat64(fd, &st) == -1) {
327 			close(fd);
328 			return (errno);
329 		}
330 		close(fd);
331 		(void) sprintf(realpath, "%s", path);
332 		dsk = strstr(path, "/dsk/");
333 		if (dsk != NULL)
334 			(void) sprintf(realpath + (dsk - path) + 1, "r%s",
335 			    dsk + 1);
336 	} else {
337 		(void) sprintf(realpath, "%s", path);
338 		if (!(flags & FCREAT) && stat64(realpath, &st) == -1)
339 			return (errno);
340 	}
341 
342 	if (flags & FCREAT)
343 		old_umask = umask(0);
344 
345 	/*
346 	 * The construct 'flags - FREAD' conveniently maps combinations of
347 	 * FREAD and FWRITE to the corresponding O_RDONLY, O_WRONLY, and O_RDWR.
348 	 */
349 	fd = open64(realpath, flags - FREAD, mode);
350 
351 	if (flags & FCREAT)
352 		(void) umask(old_umask);
353 
354 	if (fd == -1)
355 		return (errno);
356 
357 	if (fstat64(fd, &st) == -1) {
358 		close(fd);
359 		return (errno);
360 	}
361 
362 	(void) fcntl(fd, F_SETFD, FD_CLOEXEC);
363 
364 	*vpp = vp = umem_zalloc(sizeof (vnode_t), UMEM_NOFAIL);
365 
366 	vp->v_fd = fd;
367 	vp->v_size = st.st_size;
368 	vp->v_path = spa_strdup(path);
369 
370 	return (0);
371 }
372 
373 int
374 vn_openat(char *path, int x1, int flags, int mode, vnode_t **vpp, int x2,
375     int x3, vnode_t *startvp)
376 {
377 	char *realpath = umem_alloc(strlen(path) + 2, UMEM_NOFAIL);
378 	int ret;
379 
380 	ASSERT(startvp == rootdir);
381 	(void) sprintf(realpath, "/%s", path);
382 
383 	ret = vn_open(realpath, x1, flags, mode, vpp, x2, x3);
384 
385 	umem_free(realpath, strlen(path) + 2);
386 
387 	return (ret);
388 }
389 
390 /*ARGSUSED*/
391 int
392 vn_rdwr(int uio, vnode_t *vp, void *addr, ssize_t len, offset_t offset,
393 	int x1, int x2, rlim64_t x3, void *x4, ssize_t *residp)
394 {
395 	ssize_t iolen, split;
396 
397 	if (uio == UIO_READ) {
398 		iolen = pread64(vp->v_fd, addr, len, offset);
399 	} else {
400 		/*
401 		 * To simulate partial disk writes, we split writes into two
402 		 * system calls so that the process can be killed in between.
403 		 */
404 		split = (len > 0 ? rand() % len : 0);
405 		iolen = pwrite64(vp->v_fd, addr, split, offset);
406 		iolen += pwrite64(vp->v_fd, (char *)addr + split,
407 		    len - split, offset + split);
408 	}
409 
410 	if (iolen == -1)
411 		return (errno);
412 	if (residp)
413 		*residp = len - iolen;
414 	else if (iolen != len)
415 		return (EIO);
416 	return (0);
417 }
418 
419 void
420 vn_close(vnode_t *vp)
421 {
422 	close(vp->v_fd);
423 	spa_strfree(vp->v_path);
424 	umem_free(vp, sizeof (vnode_t));
425 }
426 
427 #ifdef ZFS_DEBUG
428 
429 /*
430  * =========================================================================
431  * Figure out which debugging statements to print
432  * =========================================================================
433  */
434 
435 static char *dprintf_string;
436 static int dprintf_print_all;
437 
438 int
439 dprintf_find_string(const char *string)
440 {
441 	char *tmp_str = dprintf_string;
442 	int len = strlen(string);
443 
444 	/*
445 	 * Find out if this is a string we want to print.
446 	 * String format: file1.c,function_name1,file2.c,file3.c
447 	 */
448 
449 	while (tmp_str != NULL) {
450 		if (strncmp(tmp_str, string, len) == 0 &&
451 		    (tmp_str[len] == ',' || tmp_str[len] == '\0'))
452 			return (1);
453 		tmp_str = strchr(tmp_str, ',');
454 		if (tmp_str != NULL)
455 			tmp_str++; /* Get rid of , */
456 	}
457 	return (0);
458 }
459 
460 void
461 dprintf_setup(int *argc, char **argv)
462 {
463 	int i, j;
464 
465 	/*
466 	 * Debugging can be specified two ways: by setting the
467 	 * environment variable ZFS_DEBUG, or by including a
468 	 * "debug=..."  argument on the command line.  The command
469 	 * line setting overrides the environment variable.
470 	 */
471 
472 	for (i = 1; i < *argc; i++) {
473 		int len = strlen("debug=");
474 		/* First look for a command line argument */
475 		if (strncmp("debug=", argv[i], len) == 0) {
476 			dprintf_string = argv[i] + len;
477 			/* Remove from args */
478 			for (j = i; j < *argc; j++)
479 				argv[j] = argv[j+1];
480 			argv[j] = NULL;
481 			(*argc)--;
482 		}
483 	}
484 
485 	if (dprintf_string == NULL) {
486 		/* Look for ZFS_DEBUG environment variable */
487 		dprintf_string = getenv("ZFS_DEBUG");
488 	}
489 
490 	/*
491 	 * Are we just turning on all debugging?
492 	 */
493 	if (dprintf_find_string("on"))
494 		dprintf_print_all = 1;
495 }
496 
497 /*
498  * =========================================================================
499  * debug printfs
500  * =========================================================================
501  */
502 void
503 __dprintf(const char *file, const char *func, int line, const char *fmt, ...)
504 {
505 	const char *newfile;
506 	va_list adx;
507 
508 	/*
509 	 * Get rid of annoying "../common/" prefix to filename.
510 	 */
511 	newfile = strrchr(file, '/');
512 	if (newfile != NULL) {
513 		newfile = newfile + 1; /* Get rid of leading / */
514 	} else {
515 		newfile = file;
516 	}
517 
518 	if (dprintf_print_all ||
519 	    dprintf_find_string(newfile) ||
520 	    dprintf_find_string(func)) {
521 		/* Print out just the function name if requested */
522 		flockfile(stdout);
523 		if (dprintf_find_string("pid"))
524 			(void) printf("%d ", getpid());
525 		if (dprintf_find_string("tid"))
526 			(void) printf("%u ", thr_self());
527 		if (dprintf_find_string("cpu"))
528 			(void) printf("%u ", getcpuid());
529 		if (dprintf_find_string("time"))
530 			(void) printf("%llu ", gethrtime());
531 		if (dprintf_find_string("long"))
532 			(void) printf("%s, line %d: ", newfile, line);
533 		(void) printf("%s: ", func);
534 		va_start(adx, fmt);
535 		(void) vprintf(fmt, adx);
536 		va_end(adx);
537 		funlockfile(stdout);
538 	}
539 }
540 
541 #endif /* ZFS_DEBUG */
542 
543 /*
544  * =========================================================================
545  * cmn_err() and panic()
546  * =========================================================================
547  */
548 static char ce_prefix[CE_IGNORE][10] = { "", "NOTICE: ", "WARNING: ", "" };
549 static char ce_suffix[CE_IGNORE][2] = { "", "\n", "\n", "" };
550 
551 void
552 vpanic(const char *fmt, va_list adx)
553 {
554 	(void) fprintf(stderr, "error: ");
555 	(void) vfprintf(stderr, fmt, adx);
556 	(void) fprintf(stderr, "\n");
557 
558 	abort();	/* think of it as a "user-level crash dump" */
559 }
560 
561 void
562 panic(const char *fmt, ...)
563 {
564 	va_list adx;
565 
566 	va_start(adx, fmt);
567 	vpanic(fmt, adx);
568 	va_end(adx);
569 }
570 
571 void
572 vcmn_err(int ce, const char *fmt, va_list adx)
573 {
574 	if (ce == CE_PANIC)
575 		vpanic(fmt, adx);
576 	if (ce != CE_NOTE) {	/* suppress noise in userland stress testing */
577 		(void) fprintf(stderr, "%s", ce_prefix[ce]);
578 		(void) vfprintf(stderr, fmt, adx);
579 		(void) fprintf(stderr, "%s", ce_suffix[ce]);
580 	}
581 }
582 
583 /*PRINTFLIKE2*/
584 void
585 cmn_err(int ce, const char *fmt, ...)
586 {
587 	va_list adx;
588 
589 	va_start(adx, fmt);
590 	vcmn_err(ce, fmt, adx);
591 	va_end(adx);
592 }
593 
594 /*
595  * =========================================================================
596  * kobj interfaces
597  * =========================================================================
598  */
599 struct _buf *
600 kobj_open_file(char *name)
601 {
602 	struct _buf *file;
603 	vnode_t *vp;
604 
605 	/* set vp as the _fd field of the file */
606 	if (vn_openat(name, UIO_SYSSPACE, FREAD, 0, &vp, 0, 0, rootdir) != 0)
607 		return ((void *)-1UL);
608 
609 	file = umem_zalloc(sizeof (struct _buf), UMEM_NOFAIL);
610 	file->_fd = (intptr_t)vp;
611 	return (file);
612 }
613 
614 int
615 kobj_read_file(struct _buf *file, char *buf, unsigned size, unsigned off)
616 {
617 	ssize_t resid;
618 
619 	vn_rdwr(UIO_READ, (vnode_t *)file->_fd, buf, size, (offset_t)off,
620 	    UIO_SYSSPACE, 0, 0, 0, &resid);
621 
622 	return (size - resid);
623 }
624 
625 void
626 kobj_close_file(struct _buf *file)
627 {
628 	vn_close((vnode_t *)file->_fd);
629 	umem_free(file, sizeof (struct _buf));
630 }
631 
632 int
633 kobj_get_filesize(struct _buf *file, uint64_t *size)
634 {
635 	struct stat64 st;
636 	vnode_t *vp = (vnode_t *)file->_fd;
637 
638 	if (fstat64(vp->v_fd, &st) == -1) {
639 		vn_close(vp);
640 		return (errno);
641 	}
642 	*size = st.st_size;
643 	return (0);
644 }
645 
646 /*
647  * =========================================================================
648  * misc routines
649  * =========================================================================
650  */
651 
652 void
653 delay(clock_t ticks)
654 {
655 	poll(0, 0, ticks * (1000 / hz));
656 }
657 
658 /*
659  * Find highest one bit set.
660  *	Returns bit number + 1 of highest bit that is set, otherwise returns 0.
661  * High order bit is 31 (or 63 in _LP64 kernel).
662  */
663 int
664 highbit(ulong_t i)
665 {
666 	register int h = 1;
667 
668 	if (i == 0)
669 		return (0);
670 #ifdef _LP64
671 	if (i & 0xffffffff00000000ul) {
672 		h += 32; i >>= 32;
673 	}
674 #endif
675 	if (i & 0xffff0000) {
676 		h += 16; i >>= 16;
677 	}
678 	if (i & 0xff00) {
679 		h += 8; i >>= 8;
680 	}
681 	if (i & 0xf0) {
682 		h += 4; i >>= 4;
683 	}
684 	if (i & 0xc) {
685 		h += 2; i >>= 2;
686 	}
687 	if (i & 0x2) {
688 		h += 1;
689 	}
690 	return (h);
691 }
692 
693 static int
694 random_get_bytes_common(uint8_t *ptr, size_t len, char *devname)
695 {
696 	int fd = open(devname, O_RDONLY);
697 	size_t resid = len;
698 	ssize_t bytes;
699 
700 	ASSERT(fd != -1);
701 
702 	while (resid != 0) {
703 		bytes = read(fd, ptr, resid);
704 		ASSERT(bytes >= 0);
705 		ptr += bytes;
706 		resid -= bytes;
707 	}
708 
709 	close(fd);
710 
711 	return (0);
712 }
713 
714 int
715 random_get_bytes(uint8_t *ptr, size_t len)
716 {
717 	return (random_get_bytes_common(ptr, len, "/dev/random"));
718 }
719 
720 int
721 random_get_pseudo_bytes(uint8_t *ptr, size_t len)
722 {
723 	return (random_get_bytes_common(ptr, len, "/dev/urandom"));
724 }
725 
726 /*
727  * =========================================================================
728  * kernel emulation setup & teardown
729  * =========================================================================
730  */
731 static int
732 umem_out_of_memory(void)
733 {
734 	char errmsg[] = "out of memory -- generating core dump\n";
735 
736 	write(fileno(stderr), errmsg, sizeof (errmsg));
737 	abort();
738 	return (0);
739 }
740 
741 void
742 kernel_init(int mode)
743 {
744 	umem_nofail_callback(umem_out_of_memory);
745 
746 	physmem = sysconf(_SC_PHYS_PAGES);
747 
748 	dprintf("physmem = %llu pages (%.2f GB)\n", physmem,
749 	    (double)physmem * sysconf(_SC_PAGE_SIZE) / (1ULL << 30));
750 
751 	spa_init(mode);
752 }
753 
754 void
755 kernel_fini(void)
756 {
757 	spa_fini();
758 }
759 
760 int
761 z_uncompress(void *dst, size_t *dstlen, const void *src, size_t srclen)
762 {
763 	int ret;
764 	uLongf len = *dstlen;
765 
766 	if ((ret = uncompress(dst, &len, src, srclen)) == Z_OK)
767 		*dstlen = (size_t)len;
768 
769 	return (ret);
770 }
771 
772 int
773 z_compress_level(void *dst, size_t *dstlen, const void *src, size_t srclen,
774     int level)
775 {
776 	int ret;
777 	uLongf len = *dstlen;
778 
779 	if ((ret = compress2(dst, &len, src, srclen, level)) == Z_OK)
780 		*dstlen = (size_t)len;
781 
782 	return (ret);
783 }
784