xref: /freebsd/sys/contrib/openzfs/lib/libzpool/kernel.c (revision 53a2e2635ab2d17bed1de7b4e0d782dd23ceb6ea)
1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3  * CDDL HEADER START
4  *
5  * The contents of this file are subject to the terms of the
6  * Common Development and Distribution License (the "License").
7  * You may not use this file except in compliance with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or https://opensource.org/licenses/CDDL-1.0.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 2012, 2018 by Delphix. All rights reserved.
25  * Copyright (c) 2016 Actifio, Inc. All rights reserved.
26  */
27 
28 #include <assert.h>
29 #include <fcntl.h>
30 #include <libgen.h>
31 #include <poll.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <limits.h>
36 #include <libzutil.h>
37 #include <sys/crypto/icp.h>
38 #include <sys/processor.h>
39 #include <sys/rrwlock.h>
40 #include <sys/spa.h>
41 #include <sys/spa_impl.h>
42 #include <sys/stat.h>
43 #include <sys/systeminfo.h>
44 #include <sys/time.h>
45 #include <sys/utsname.h>
46 #include <sys/zfs_context.h>
47 #include <sys/zfs_onexit.h>
48 #include <sys/zfs_vfsops.h>
49 #include <sys/zstd/zstd.h>
50 #include <sys/zvol.h>
51 #include <zfs_fletcher.h>
52 #include <zlib.h>
53 
54 /*
55  * Emulation of kernel services in userland.
56  */
57 
58 uint64_t physmem;
59 uint32_t hostid;
60 struct utsname hw_utsname;
61 
62 /* If set, all blocks read will be copied to the specified directory. */
63 char *vn_dumpdir = NULL;
64 
65 /* this only exists to have its address taken */
66 struct proc p0;
67 
68 /*
69  * =========================================================================
70  * threads
71  * =========================================================================
72  *
73  * TS_STACK_MIN is dictated by the minimum allowed pthread stack size.  While
74  * TS_STACK_MAX is somewhat arbitrary, it was selected to be large enough for
75  * the expected stack depth while small enough to avoid exhausting address
76  * space with high thread counts.
77  */
78 #define	TS_STACK_MIN	MAX(PTHREAD_STACK_MIN, 32768)
79 #define	TS_STACK_MAX	(256 * 1024)
80 
81 struct zk_thread_wrapper {
82 	void (*func)(void *);
83 	void *arg;
84 };
85 
86 static void *
zk_thread_wrapper(void * arg)87 zk_thread_wrapper(void *arg)
88 {
89 	struct zk_thread_wrapper ztw;
90 	memcpy(&ztw, arg, sizeof (ztw));
91 	free(arg);
92 	ztw.func(ztw.arg);
93 	return (NULL);
94 }
95 
96 kthread_t *
zk_thread_create(const char * name,void (* func)(void *),void * arg,size_t stksize,int state)97 zk_thread_create(const char *name, void (*func)(void *), void *arg,
98     size_t stksize, int state)
99 {
100 	pthread_attr_t attr;
101 	pthread_t tid;
102 	char *stkstr;
103 	struct zk_thread_wrapper *ztw;
104 	int detachstate = PTHREAD_CREATE_DETACHED;
105 
106 	VERIFY0(pthread_attr_init(&attr));
107 
108 	if (state & TS_JOINABLE)
109 		detachstate = PTHREAD_CREATE_JOINABLE;
110 
111 	VERIFY0(pthread_attr_setdetachstate(&attr, detachstate));
112 
113 	/*
114 	 * We allow the default stack size in user space to be specified by
115 	 * setting the ZFS_STACK_SIZE environment variable.  This allows us
116 	 * the convenience of observing and debugging stack overruns in
117 	 * user space.  Explicitly specified stack sizes will be honored.
118 	 * The usage of ZFS_STACK_SIZE is discussed further in the
119 	 * ENVIRONMENT VARIABLES sections of the ztest(1) man page.
120 	 */
121 	if (stksize == 0) {
122 		stkstr = getenv("ZFS_STACK_SIZE");
123 
124 		if (stkstr == NULL)
125 			stksize = TS_STACK_MAX;
126 		else
127 			stksize = MAX(atoi(stkstr), TS_STACK_MIN);
128 	}
129 
130 	VERIFY3S(stksize, >, 0);
131 	stksize = P2ROUNDUP(MAX(stksize, TS_STACK_MIN), PAGESIZE);
132 
133 	/*
134 	 * If this ever fails, it may be because the stack size is not a
135 	 * multiple of system page size.
136 	 */
137 	VERIFY0(pthread_attr_setstacksize(&attr, stksize));
138 	VERIFY0(pthread_attr_setguardsize(&attr, PAGESIZE));
139 
140 	VERIFY(ztw = malloc(sizeof (*ztw)));
141 	ztw->func = func;
142 	ztw->arg = arg;
143 	VERIFY0(pthread_create(&tid, &attr, zk_thread_wrapper, ztw));
144 	VERIFY0(pthread_attr_destroy(&attr));
145 
146 	pthread_setname_np(tid, name);
147 
148 	return ((void *)(uintptr_t)tid);
149 }
150 
151 /*
152  * =========================================================================
153  * kstats
154  * =========================================================================
155  */
156 kstat_t *
kstat_create(const char * module,int instance,const char * name,const char * class,uchar_t type,ulong_t ndata,uchar_t ks_flag)157 kstat_create(const char *module, int instance, const char *name,
158     const char *class, uchar_t type, ulong_t ndata, uchar_t ks_flag)
159 {
160 	(void) module, (void) instance, (void) name, (void) class, (void) type,
161 	    (void) ndata, (void) ks_flag;
162 	return (NULL);
163 }
164 
165 void
kstat_install(kstat_t * ksp)166 kstat_install(kstat_t *ksp)
167 {
168 	(void) ksp;
169 }
170 
171 void
kstat_delete(kstat_t * ksp)172 kstat_delete(kstat_t *ksp)
173 {
174 	(void) ksp;
175 }
176 
177 void
kstat_set_raw_ops(kstat_t * ksp,int (* headers)(char * buf,size_t size),int (* data)(char * buf,size_t size,void * data),void * (* addr)(kstat_t * ksp,loff_t index))178 kstat_set_raw_ops(kstat_t *ksp,
179     int (*headers)(char *buf, size_t size),
180     int (*data)(char *buf, size_t size, void *data),
181     void *(*addr)(kstat_t *ksp, loff_t index))
182 {
183 	(void) ksp, (void) headers, (void) data, (void) addr;
184 }
185 
186 /*
187  * =========================================================================
188  * mutexes
189  * =========================================================================
190  */
191 
192 void
mutex_init(kmutex_t * mp,char * name,int type,void * cookie)193 mutex_init(kmutex_t *mp, char *name, int type, void *cookie)
194 {
195 	(void) name, (void) type, (void) cookie;
196 	VERIFY0(pthread_mutex_init(&mp->m_lock, NULL));
197 	memset(&mp->m_owner, 0, sizeof (pthread_t));
198 }
199 
200 void
mutex_destroy(kmutex_t * mp)201 mutex_destroy(kmutex_t *mp)
202 {
203 	VERIFY0(pthread_mutex_destroy(&mp->m_lock));
204 }
205 
206 void
mutex_enter(kmutex_t * mp)207 mutex_enter(kmutex_t *mp)
208 {
209 	VERIFY0(pthread_mutex_lock(&mp->m_lock));
210 	mp->m_owner = pthread_self();
211 }
212 
213 int
mutex_enter_check_return(kmutex_t * mp)214 mutex_enter_check_return(kmutex_t *mp)
215 {
216 	int error = pthread_mutex_lock(&mp->m_lock);
217 	if (error == 0)
218 		mp->m_owner = pthread_self();
219 	return (error);
220 }
221 
222 int
mutex_tryenter(kmutex_t * mp)223 mutex_tryenter(kmutex_t *mp)
224 {
225 	int error = pthread_mutex_trylock(&mp->m_lock);
226 	if (error == 0) {
227 		mp->m_owner = pthread_self();
228 		return (1);
229 	} else {
230 		VERIFY3S(error, ==, EBUSY);
231 		return (0);
232 	}
233 }
234 
235 void
mutex_exit(kmutex_t * mp)236 mutex_exit(kmutex_t *mp)
237 {
238 	memset(&mp->m_owner, 0, sizeof (pthread_t));
239 	VERIFY0(pthread_mutex_unlock(&mp->m_lock));
240 }
241 
242 /*
243  * =========================================================================
244  * rwlocks
245  * =========================================================================
246  */
247 
248 void
rw_init(krwlock_t * rwlp,char * name,int type,void * arg)249 rw_init(krwlock_t *rwlp, char *name, int type, void *arg)
250 {
251 	(void) name, (void) type, (void) arg;
252 	VERIFY0(pthread_rwlock_init(&rwlp->rw_lock, NULL));
253 	rwlp->rw_readers = 0;
254 	rwlp->rw_owner = 0;
255 }
256 
257 void
rw_destroy(krwlock_t * rwlp)258 rw_destroy(krwlock_t *rwlp)
259 {
260 	VERIFY0(pthread_rwlock_destroy(&rwlp->rw_lock));
261 }
262 
263 void
rw_enter(krwlock_t * rwlp,krw_t rw)264 rw_enter(krwlock_t *rwlp, krw_t rw)
265 {
266 	if (rw == RW_READER) {
267 		VERIFY0(pthread_rwlock_rdlock(&rwlp->rw_lock));
268 		atomic_inc_uint(&rwlp->rw_readers);
269 	} else {
270 		VERIFY0(pthread_rwlock_wrlock(&rwlp->rw_lock));
271 		rwlp->rw_owner = pthread_self();
272 	}
273 }
274 
275 void
rw_exit(krwlock_t * rwlp)276 rw_exit(krwlock_t *rwlp)
277 {
278 	if (RW_READ_HELD(rwlp))
279 		atomic_dec_uint(&rwlp->rw_readers);
280 	else
281 		rwlp->rw_owner = 0;
282 
283 	VERIFY0(pthread_rwlock_unlock(&rwlp->rw_lock));
284 }
285 
286 int
rw_tryenter(krwlock_t * rwlp,krw_t rw)287 rw_tryenter(krwlock_t *rwlp, krw_t rw)
288 {
289 	int error;
290 
291 	if (rw == RW_READER)
292 		error = pthread_rwlock_tryrdlock(&rwlp->rw_lock);
293 	else
294 		error = pthread_rwlock_trywrlock(&rwlp->rw_lock);
295 
296 	if (error == 0) {
297 		if (rw == RW_READER)
298 			atomic_inc_uint(&rwlp->rw_readers);
299 		else
300 			rwlp->rw_owner = pthread_self();
301 
302 		return (1);
303 	}
304 
305 	VERIFY3S(error, ==, EBUSY);
306 
307 	return (0);
308 }
309 
310 uint32_t
zone_get_hostid(void * zonep)311 zone_get_hostid(void *zonep)
312 {
313 	/*
314 	 * We're emulating the system's hostid in userland.
315 	 */
316 	(void) zonep;
317 	return (hostid);
318 }
319 
320 int
rw_tryupgrade(krwlock_t * rwlp)321 rw_tryupgrade(krwlock_t *rwlp)
322 {
323 	(void) rwlp;
324 	return (0);
325 }
326 
327 /*
328  * =========================================================================
329  * condition variables
330  * =========================================================================
331  */
332 
333 void
cv_init(kcondvar_t * cv,char * name,int type,void * arg)334 cv_init(kcondvar_t *cv, char *name, int type, void *arg)
335 {
336 	(void) name, (void) type, (void) arg;
337 	VERIFY0(pthread_cond_init(cv, NULL));
338 }
339 
340 void
cv_destroy(kcondvar_t * cv)341 cv_destroy(kcondvar_t *cv)
342 {
343 	VERIFY0(pthread_cond_destroy(cv));
344 }
345 
346 void
cv_wait(kcondvar_t * cv,kmutex_t * mp)347 cv_wait(kcondvar_t *cv, kmutex_t *mp)
348 {
349 	memset(&mp->m_owner, 0, sizeof (pthread_t));
350 	VERIFY0(pthread_cond_wait(cv, &mp->m_lock));
351 	mp->m_owner = pthread_self();
352 }
353 
354 int
cv_wait_sig(kcondvar_t * cv,kmutex_t * mp)355 cv_wait_sig(kcondvar_t *cv, kmutex_t *mp)
356 {
357 	cv_wait(cv, mp);
358 	return (1);
359 }
360 
361 int
cv_timedwait(kcondvar_t * cv,kmutex_t * mp,clock_t abstime)362 cv_timedwait(kcondvar_t *cv, kmutex_t *mp, clock_t abstime)
363 {
364 	int error;
365 	struct timeval tv;
366 	struct timespec ts;
367 	clock_t delta;
368 
369 	delta = abstime - ddi_get_lbolt();
370 	if (delta <= 0)
371 		return (-1);
372 
373 	VERIFY0(gettimeofday(&tv, NULL));
374 
375 	ts.tv_sec = tv.tv_sec + delta / hz;
376 	ts.tv_nsec = tv.tv_usec * NSEC_PER_USEC + (delta % hz) * (NANOSEC / hz);
377 	if (ts.tv_nsec >= NANOSEC) {
378 		ts.tv_sec++;
379 		ts.tv_nsec -= NANOSEC;
380 	}
381 
382 	memset(&mp->m_owner, 0, sizeof (pthread_t));
383 	error = pthread_cond_timedwait(cv, &mp->m_lock, &ts);
384 	mp->m_owner = pthread_self();
385 
386 	if (error == ETIMEDOUT)
387 		return (-1);
388 
389 	VERIFY0(error);
390 
391 	return (1);
392 }
393 
394 int
cv_timedwait_hires(kcondvar_t * cv,kmutex_t * mp,hrtime_t tim,hrtime_t res,int flag)395 cv_timedwait_hires(kcondvar_t *cv, kmutex_t *mp, hrtime_t tim, hrtime_t res,
396     int flag)
397 {
398 	(void) res;
399 	int error;
400 	struct timeval tv;
401 	struct timespec ts;
402 	hrtime_t delta;
403 
404 	ASSERT(flag == 0 || flag == CALLOUT_FLAG_ABSOLUTE);
405 
406 	delta = tim;
407 	if (flag & CALLOUT_FLAG_ABSOLUTE)
408 		delta -= gethrtime();
409 
410 	if (delta <= 0)
411 		return (-1);
412 
413 	VERIFY0(gettimeofday(&tv, NULL));
414 
415 	ts.tv_sec = tv.tv_sec + delta / NANOSEC;
416 	ts.tv_nsec = tv.tv_usec * NSEC_PER_USEC + (delta % NANOSEC);
417 	if (ts.tv_nsec >= NANOSEC) {
418 		ts.tv_sec++;
419 		ts.tv_nsec -= NANOSEC;
420 	}
421 
422 	memset(&mp->m_owner, 0, sizeof (pthread_t));
423 	error = pthread_cond_timedwait(cv, &mp->m_lock, &ts);
424 	mp->m_owner = pthread_self();
425 
426 	if (error == ETIMEDOUT)
427 		return (-1);
428 
429 	VERIFY0(error);
430 
431 	return (1);
432 }
433 
434 void
cv_signal(kcondvar_t * cv)435 cv_signal(kcondvar_t *cv)
436 {
437 	VERIFY0(pthread_cond_signal(cv));
438 }
439 
440 void
cv_broadcast(kcondvar_t * cv)441 cv_broadcast(kcondvar_t *cv)
442 {
443 	VERIFY0(pthread_cond_broadcast(cv));
444 }
445 
446 /*
447  * =========================================================================
448  * procfs list
449  * =========================================================================
450  */
451 
452 void
seq_printf(struct seq_file * m,const char * fmt,...)453 seq_printf(struct seq_file *m, const char *fmt, ...)
454 {
455 	(void) m, (void) fmt;
456 }
457 
458 void
procfs_list_install(const char * module,const char * submodule,const char * name,mode_t mode,procfs_list_t * procfs_list,int (* show)(struct seq_file * f,void * p),int (* show_header)(struct seq_file * f),int (* clear)(procfs_list_t * procfs_list),size_t procfs_list_node_off)459 procfs_list_install(const char *module,
460     const char *submodule,
461     const char *name,
462     mode_t mode,
463     procfs_list_t *procfs_list,
464     int (*show)(struct seq_file *f, void *p),
465     int (*show_header)(struct seq_file *f),
466     int (*clear)(procfs_list_t *procfs_list),
467     size_t procfs_list_node_off)
468 {
469 	(void) module, (void) submodule, (void) name, (void) mode, (void) show,
470 	    (void) show_header, (void) clear;
471 	mutex_init(&procfs_list->pl_lock, NULL, MUTEX_DEFAULT, NULL);
472 	list_create(&procfs_list->pl_list,
473 	    procfs_list_node_off + sizeof (procfs_list_node_t),
474 	    procfs_list_node_off + offsetof(procfs_list_node_t, pln_link));
475 	procfs_list->pl_next_id = 1;
476 	procfs_list->pl_node_offset = procfs_list_node_off;
477 }
478 
479 void
procfs_list_uninstall(procfs_list_t * procfs_list)480 procfs_list_uninstall(procfs_list_t *procfs_list)
481 {
482 	(void) procfs_list;
483 }
484 
485 void
procfs_list_destroy(procfs_list_t * procfs_list)486 procfs_list_destroy(procfs_list_t *procfs_list)
487 {
488 	ASSERT(list_is_empty(&procfs_list->pl_list));
489 	list_destroy(&procfs_list->pl_list);
490 	mutex_destroy(&procfs_list->pl_lock);
491 }
492 
493 #define	NODE_ID(procfs_list, obj) \
494 		(((procfs_list_node_t *)(((char *)obj) + \
495 		(procfs_list)->pl_node_offset))->pln_id)
496 
497 void
procfs_list_add(procfs_list_t * procfs_list,void * p)498 procfs_list_add(procfs_list_t *procfs_list, void *p)
499 {
500 	ASSERT(MUTEX_HELD(&procfs_list->pl_lock));
501 	NODE_ID(procfs_list, p) = procfs_list->pl_next_id++;
502 	list_insert_tail(&procfs_list->pl_list, p);
503 }
504 
505 /*
506  * =========================================================================
507  * vnode operations
508  * =========================================================================
509  */
510 
511 /*
512  * =========================================================================
513  * Figure out which debugging statements to print
514  * =========================================================================
515  */
516 
517 static char *dprintf_string;
518 static int dprintf_print_all;
519 
520 int
dprintf_find_string(const char * string)521 dprintf_find_string(const char *string)
522 {
523 	char *tmp_str = dprintf_string;
524 	int len = strlen(string);
525 
526 	/*
527 	 * Find out if this is a string we want to print.
528 	 * String format: file1.c,function_name1,file2.c,file3.c
529 	 */
530 
531 	while (tmp_str != NULL) {
532 		if (strncmp(tmp_str, string, len) == 0 &&
533 		    (tmp_str[len] == ',' || tmp_str[len] == '\0'))
534 			return (1);
535 		tmp_str = strchr(tmp_str, ',');
536 		if (tmp_str != NULL)
537 			tmp_str++; /* Get rid of , */
538 	}
539 	return (0);
540 }
541 
542 void
dprintf_setup(int * argc,char ** argv)543 dprintf_setup(int *argc, char **argv)
544 {
545 	int i, j;
546 
547 	/*
548 	 * Debugging can be specified two ways: by setting the
549 	 * environment variable ZFS_DEBUG, or by including a
550 	 * "debug=..."  argument on the command line.  The command
551 	 * line setting overrides the environment variable.
552 	 */
553 
554 	for (i = 1; i < *argc; i++) {
555 		int len = strlen("debug=");
556 		/* First look for a command line argument */
557 		if (strncmp("debug=", argv[i], len) == 0) {
558 			dprintf_string = argv[i] + len;
559 			/* Remove from args */
560 			for (j = i; j < *argc; j++)
561 				argv[j] = argv[j+1];
562 			argv[j] = NULL;
563 			(*argc)--;
564 		}
565 	}
566 
567 	if (dprintf_string == NULL) {
568 		/* Look for ZFS_DEBUG environment variable */
569 		dprintf_string = getenv("ZFS_DEBUG");
570 	}
571 
572 	/*
573 	 * Are we just turning on all debugging?
574 	 */
575 	if (dprintf_find_string("on"))
576 		dprintf_print_all = 1;
577 
578 	if (dprintf_string != NULL)
579 		zfs_flags |= ZFS_DEBUG_DPRINTF;
580 }
581 
582 /*
583  * =========================================================================
584  * debug printfs
585  * =========================================================================
586  */
587 void
__dprintf(boolean_t dprint,const char * file,const char * func,int line,const char * fmt,...)588 __dprintf(boolean_t dprint, const char *file, const char *func,
589     int line, const char *fmt, ...)
590 {
591 	/* Get rid of annoying "../common/" prefix to filename. */
592 	const char *newfile = zfs_basename(file);
593 
594 	va_list adx;
595 	if (dprint) {
596 		/* dprintf messages are printed immediately */
597 
598 		if (!dprintf_print_all &&
599 		    !dprintf_find_string(newfile) &&
600 		    !dprintf_find_string(func))
601 			return;
602 
603 		/* Print out just the function name if requested */
604 		flockfile(stdout);
605 		if (dprintf_find_string("pid"))
606 			(void) printf("%d ", getpid());
607 		if (dprintf_find_string("tid"))
608 			(void) printf("%ju ",
609 			    (uintmax_t)(uintptr_t)pthread_self());
610 		if (dprintf_find_string("cpu"))
611 			(void) printf("%u ", getcpuid());
612 		if (dprintf_find_string("time"))
613 			(void) printf("%llu ", gethrtime());
614 		if (dprintf_find_string("long"))
615 			(void) printf("%s, line %d: ", newfile, line);
616 		(void) printf("dprintf: %s: ", func);
617 		va_start(adx, fmt);
618 		(void) vprintf(fmt, adx);
619 		va_end(adx);
620 		funlockfile(stdout);
621 	} else {
622 		/* zfs_dbgmsg is logged for dumping later */
623 		size_t size;
624 		char *buf;
625 		int i;
626 
627 		size = 1024;
628 		buf = umem_alloc(size, UMEM_NOFAIL);
629 		i = snprintf(buf, size, "%s:%d:%s(): ", newfile, line, func);
630 
631 		if (i < size) {
632 			va_start(adx, fmt);
633 			(void) vsnprintf(buf + i, size - i, fmt, adx);
634 			va_end(adx);
635 		}
636 
637 		__zfs_dbgmsg(buf);
638 
639 		umem_free(buf, size);
640 	}
641 }
642 
643 /*
644  * =========================================================================
645  * cmn_err() and panic()
646  * =========================================================================
647  */
648 static char ce_prefix[CE_IGNORE][10] = { "", "NOTICE: ", "WARNING: ", "" };
649 static char ce_suffix[CE_IGNORE][2] = { "", "\n", "\n", "" };
650 
651 __attribute__((noreturn)) void
vpanic(const char * fmt,va_list adx)652 vpanic(const char *fmt, va_list adx)
653 {
654 	(void) fprintf(stderr, "error: ");
655 	(void) vfprintf(stderr, fmt, adx);
656 	(void) fprintf(stderr, "\n");
657 
658 	abort();	/* think of it as a "user-level crash dump" */
659 }
660 
661 __attribute__((noreturn)) void
panic(const char * fmt,...)662 panic(const char *fmt, ...)
663 {
664 	va_list adx;
665 
666 	va_start(adx, fmt);
667 	vpanic(fmt, adx);
668 	va_end(adx);
669 }
670 
671 void
vcmn_err(int ce,const char * fmt,va_list adx)672 vcmn_err(int ce, const char *fmt, va_list adx)
673 {
674 	if (ce == CE_PANIC)
675 		vpanic(fmt, adx);
676 	if (ce != CE_NOTE) {	/* suppress noise in userland stress testing */
677 		(void) fprintf(stderr, "%s", ce_prefix[ce]);
678 		(void) vfprintf(stderr, fmt, adx);
679 		(void) fprintf(stderr, "%s", ce_suffix[ce]);
680 	}
681 }
682 
683 void
cmn_err(int ce,const char * fmt,...)684 cmn_err(int ce, const char *fmt, ...)
685 {
686 	va_list adx;
687 
688 	va_start(adx, fmt);
689 	vcmn_err(ce, fmt, adx);
690 	va_end(adx);
691 }
692 
693 /*
694  * =========================================================================
695  * misc routines
696  * =========================================================================
697  */
698 
699 void
delay(clock_t ticks)700 delay(clock_t ticks)
701 {
702 	(void) poll(0, 0, ticks * (1000 / hz));
703 }
704 
705 /*
706  * Find highest one bit set.
707  * Returns bit number + 1 of highest bit that is set, otherwise returns 0.
708  * The __builtin_clzll() function is supported by both GCC and Clang.
709  */
710 int
highbit64(uint64_t i)711 highbit64(uint64_t i)
712 {
713 	if (i == 0)
714 	return (0);
715 
716 	return (NBBY * sizeof (uint64_t) - __builtin_clzll(i));
717 }
718 
719 /*
720  * Find lowest one bit set.
721  * Returns bit number + 1 of lowest bit that is set, otherwise returns 0.
722  * The __builtin_ffsll() function is supported by both GCC and Clang.
723  */
724 int
lowbit64(uint64_t i)725 lowbit64(uint64_t i)
726 {
727 	if (i == 0)
728 		return (0);
729 
730 	return (__builtin_ffsll(i));
731 }
732 
733 const char *random_path = "/dev/random";
734 const char *urandom_path = "/dev/urandom";
735 static int random_fd = -1, urandom_fd = -1;
736 
737 void
random_init(void)738 random_init(void)
739 {
740 	VERIFY((random_fd = open(random_path, O_RDONLY | O_CLOEXEC)) != -1);
741 	VERIFY((urandom_fd = open(urandom_path, O_RDONLY | O_CLOEXEC)) != -1);
742 }
743 
744 void
random_fini(void)745 random_fini(void)
746 {
747 	close(random_fd);
748 	close(urandom_fd);
749 
750 	random_fd = -1;
751 	urandom_fd = -1;
752 }
753 
754 static int
random_get_bytes_common(uint8_t * ptr,size_t len,int fd)755 random_get_bytes_common(uint8_t *ptr, size_t len, int fd)
756 {
757 	size_t resid = len;
758 	ssize_t bytes;
759 
760 	ASSERT(fd != -1);
761 
762 	while (resid != 0) {
763 		bytes = read(fd, ptr, resid);
764 		ASSERT3S(bytes, >=, 0);
765 		ptr += bytes;
766 		resid -= bytes;
767 	}
768 
769 	return (0);
770 }
771 
772 int
random_get_bytes(uint8_t * ptr,size_t len)773 random_get_bytes(uint8_t *ptr, size_t len)
774 {
775 	return (random_get_bytes_common(ptr, len, random_fd));
776 }
777 
778 int
random_get_pseudo_bytes(uint8_t * ptr,size_t len)779 random_get_pseudo_bytes(uint8_t *ptr, size_t len)
780 {
781 	return (random_get_bytes_common(ptr, len, urandom_fd));
782 }
783 
784 int
ddi_strtoull(const char * str,char ** nptr,int base,u_longlong_t * result)785 ddi_strtoull(const char *str, char **nptr, int base, u_longlong_t *result)
786 {
787 	errno = 0;
788 	*result = strtoull(str, nptr, base);
789 	if (*result == 0)
790 		return (errno);
791 	return (0);
792 }
793 
794 utsname_t *
utsname(void)795 utsname(void)
796 {
797 	return (&hw_utsname);
798 }
799 
800 /*
801  * =========================================================================
802  * kernel emulation setup & teardown
803  * =========================================================================
804  */
805 static int
umem_out_of_memory(void)806 umem_out_of_memory(void)
807 {
808 	char errmsg[] = "out of memory -- generating core dump\n";
809 
810 	(void) fprintf(stderr, "%s", errmsg);
811 	abort();
812 	return (0);
813 }
814 
815 static void
spa_config_load(void)816 spa_config_load(void)
817 {
818 	void *buf = NULL;
819 	nvlist_t *nvlist, *child;
820 	nvpair_t *nvpair;
821 	char *pathname;
822 	zfs_file_t *fp;
823 	zfs_file_attr_t zfa;
824 	uint64_t fsize;
825 	int err;
826 
827 	/*
828 	 * Open the configuration file.
829 	 */
830 	pathname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
831 
832 	(void) snprintf(pathname, MAXPATHLEN, "%s", spa_config_path);
833 
834 	err = zfs_file_open(pathname, O_RDONLY, 0, &fp);
835 	if (err)
836 		err = zfs_file_open(ZPOOL_CACHE_BOOT, O_RDONLY, 0, &fp);
837 
838 	kmem_free(pathname, MAXPATHLEN);
839 
840 	if (err)
841 		return;
842 
843 	if (zfs_file_getattr(fp, &zfa))
844 		goto out;
845 
846 	fsize = zfa.zfa_size;
847 	buf = kmem_alloc(fsize, KM_SLEEP);
848 
849 	/*
850 	 * Read the nvlist from the file.
851 	 */
852 	if (zfs_file_read(fp, buf, fsize, NULL) < 0)
853 		goto out;
854 
855 	/*
856 	 * Unpack the nvlist.
857 	 */
858 	if (nvlist_unpack(buf, fsize, &nvlist, KM_SLEEP) != 0)
859 		goto out;
860 
861 	/*
862 	 * Iterate over all elements in the nvlist, creating a new spa_t for
863 	 * each one with the specified configuration.
864 	 */
865 	mutex_enter(&spa_namespace_lock);
866 	nvpair = NULL;
867 	while ((nvpair = nvlist_next_nvpair(nvlist, nvpair)) != NULL) {
868 		if (nvpair_type(nvpair) != DATA_TYPE_NVLIST)
869 			continue;
870 
871 		child = fnvpair_value_nvlist(nvpair);
872 
873 		if (spa_lookup(nvpair_name(nvpair)) != NULL)
874 			continue;
875 		(void) spa_add(nvpair_name(nvpair), child, NULL);
876 	}
877 	mutex_exit(&spa_namespace_lock);
878 
879 	nvlist_free(nvlist);
880 
881 out:
882 	if (buf != NULL)
883 		kmem_free(buf, fsize);
884 
885 	zfs_file_close(fp);
886 }
887 
888 void
kernel_init(int mode)889 kernel_init(int mode)
890 {
891 	extern uint_t rrw_tsd_key;
892 
893 	umem_nofail_callback(umem_out_of_memory);
894 
895 	physmem = sysconf(_SC_PHYS_PAGES);
896 
897 	dprintf("physmem = %llu pages (%.2f GB)\n", (u_longlong_t)physmem,
898 	    (double)physmem * sysconf(_SC_PAGE_SIZE) / (1ULL << 30));
899 
900 	hostid = (mode & SPA_MODE_WRITE) ? get_system_hostid() : 0;
901 
902 	random_init();
903 
904 	VERIFY0(uname(&hw_utsname));
905 
906 	system_taskq_init();
907 	icp_init();
908 
909 	zstd_init();
910 
911 	spa_init((spa_mode_t)mode);
912 	spa_config_load();
913 
914 	fletcher_4_init();
915 
916 	tsd_create(&rrw_tsd_key, rrw_tsd_destroy);
917 }
918 
919 void
kernel_fini(void)920 kernel_fini(void)
921 {
922 	fletcher_4_fini();
923 	spa_fini();
924 
925 	zstd_fini();
926 
927 	icp_fini();
928 	system_taskq_fini();
929 
930 	random_fini();
931 }
932 
933 uid_t
crgetuid(cred_t * cr)934 crgetuid(cred_t *cr)
935 {
936 	(void) cr;
937 	return (0);
938 }
939 
940 uid_t
crgetruid(cred_t * cr)941 crgetruid(cred_t *cr)
942 {
943 	(void) cr;
944 	return (0);
945 }
946 
947 gid_t
crgetgid(cred_t * cr)948 crgetgid(cred_t *cr)
949 {
950 	(void) cr;
951 	return (0);
952 }
953 
954 int
crgetngroups(cred_t * cr)955 crgetngroups(cred_t *cr)
956 {
957 	(void) cr;
958 	return (0);
959 }
960 
961 gid_t *
crgetgroups(cred_t * cr)962 crgetgroups(cred_t *cr)
963 {
964 	(void) cr;
965 	return (NULL);
966 }
967 
968 int
zfs_secpolicy_snapshot_perms(const char * name,cred_t * cr)969 zfs_secpolicy_snapshot_perms(const char *name, cred_t *cr)
970 {
971 	(void) name, (void) cr;
972 	return (0);
973 }
974 
975 int
zfs_secpolicy_rename_perms(const char * from,const char * to,cred_t * cr)976 zfs_secpolicy_rename_perms(const char *from, const char *to, cred_t *cr)
977 {
978 	(void) from, (void) to, (void) cr;
979 	return (0);
980 }
981 
982 int
zfs_secpolicy_destroy_perms(const char * name,cred_t * cr)983 zfs_secpolicy_destroy_perms(const char *name, cred_t *cr)
984 {
985 	(void) name, (void) cr;
986 	return (0);
987 }
988 
989 int
secpolicy_zfs(const cred_t * cr)990 secpolicy_zfs(const cred_t *cr)
991 {
992 	(void) cr;
993 	return (0);
994 }
995 
996 ksiddomain_t *
ksid_lookupdomain(const char * dom)997 ksid_lookupdomain(const char *dom)
998 {
999 	ksiddomain_t *kd;
1000 
1001 	kd = umem_zalloc(sizeof (ksiddomain_t), UMEM_NOFAIL);
1002 	kd->kd_name = spa_strdup(dom);
1003 	return (kd);
1004 }
1005 
1006 void
ksiddomain_rele(ksiddomain_t * ksid)1007 ksiddomain_rele(ksiddomain_t *ksid)
1008 {
1009 	spa_strfree(ksid->kd_name);
1010 	umem_free(ksid, sizeof (ksiddomain_t));
1011 }
1012 
1013 char *
kmem_vasprintf(const char * fmt,va_list adx)1014 kmem_vasprintf(const char *fmt, va_list adx)
1015 {
1016 	char *buf = NULL;
1017 	va_list adx_copy;
1018 
1019 	va_copy(adx_copy, adx);
1020 	VERIFY(vasprintf(&buf, fmt, adx_copy) != -1);
1021 	va_end(adx_copy);
1022 
1023 	return (buf);
1024 }
1025 
1026 char *
kmem_asprintf(const char * fmt,...)1027 kmem_asprintf(const char *fmt, ...)
1028 {
1029 	char *buf = NULL;
1030 	va_list adx;
1031 
1032 	va_start(adx, fmt);
1033 	VERIFY(vasprintf(&buf, fmt, adx) != -1);
1034 	va_end(adx);
1035 
1036 	return (buf);
1037 }
1038 
1039 /*
1040  * kmem_scnprintf() will return the number of characters that it would have
1041  * printed whenever it is limited by value of the size variable, rather than
1042  * the number of characters that it did print. This can cause misbehavior on
1043  * subsequent uses of the return value, so we define a safe version that will
1044  * return the number of characters actually printed, minus the NULL format
1045  * character.  Subsequent use of this by the safe string functions is safe
1046  * whether it is snprintf(), strlcat() or strlcpy().
1047  */
1048 int
kmem_scnprintf(char * restrict str,size_t size,const char * restrict fmt,...)1049 kmem_scnprintf(char *restrict str, size_t size, const char *restrict fmt, ...)
1050 {
1051 	int n;
1052 	va_list ap;
1053 
1054 	/* Make the 0 case a no-op so that we do not return -1 */
1055 	if (size == 0)
1056 		return (0);
1057 
1058 	va_start(ap, fmt);
1059 	n = vsnprintf(str, size, fmt, ap);
1060 	va_end(ap);
1061 
1062 	if (n >= size)
1063 		n = size - 1;
1064 
1065 	return (n);
1066 }
1067 
1068 zfs_file_t *
zfs_onexit_fd_hold(int fd,minor_t * minorp)1069 zfs_onexit_fd_hold(int fd, minor_t *minorp)
1070 {
1071 	(void) fd;
1072 	*minorp = 0;
1073 	return (NULL);
1074 }
1075 
1076 void
zfs_onexit_fd_rele(zfs_file_t * fp)1077 zfs_onexit_fd_rele(zfs_file_t *fp)
1078 {
1079 	(void) fp;
1080 }
1081 
1082 int
zfs_onexit_add_cb(minor_t minor,void (* func)(void *),void * data,uintptr_t * action_handle)1083 zfs_onexit_add_cb(minor_t minor, void (*func)(void *), void *data,
1084     uintptr_t *action_handle)
1085 {
1086 	(void) minor, (void) func, (void) data, (void) action_handle;
1087 	return (0);
1088 }
1089 
1090 fstrans_cookie_t
spl_fstrans_mark(void)1091 spl_fstrans_mark(void)
1092 {
1093 	return ((fstrans_cookie_t)0);
1094 }
1095 
1096 void
spl_fstrans_unmark(fstrans_cookie_t cookie)1097 spl_fstrans_unmark(fstrans_cookie_t cookie)
1098 {
1099 	(void) cookie;
1100 }
1101 
1102 int
kmem_cache_reap_active(void)1103 kmem_cache_reap_active(void)
1104 {
1105 	return (0);
1106 }
1107 
1108 void
zvol_create_minors(const char * name)1109 zvol_create_minors(const char *name)
1110 {
1111 	(void) name;
1112 }
1113 
1114 void
zvol_remove_minors(spa_t * spa,const char * name,boolean_t async)1115 zvol_remove_minors(spa_t *spa, const char *name, boolean_t async)
1116 {
1117 	(void) spa, (void) name, (void) async;
1118 }
1119 
1120 void
zvol_rename_minors(spa_t * spa,const char * oldname,const char * newname,boolean_t async)1121 zvol_rename_minors(spa_t *spa, const char *oldname, const char *newname,
1122     boolean_t async)
1123 {
1124 	(void) spa, (void) oldname, (void) newname, (void) async;
1125 }
1126 
1127 /*
1128  * Open file
1129  *
1130  * path - fully qualified path to file
1131  * flags - file attributes O_READ / O_WRITE / O_EXCL
1132  * fpp - pointer to return file pointer
1133  *
1134  * Returns 0 on success underlying error on failure.
1135  */
1136 int
zfs_file_open(const char * path,int flags,int mode,zfs_file_t ** fpp)1137 zfs_file_open(const char *path, int flags, int mode, zfs_file_t **fpp)
1138 {
1139 	int fd;
1140 	int dump_fd;
1141 	int err;
1142 	int old_umask = 0;
1143 	zfs_file_t *fp;
1144 	struct stat64 st;
1145 
1146 	if (!(flags & O_CREAT) && stat64(path, &st) == -1)
1147 		return (errno);
1148 
1149 	if (!(flags & O_CREAT) && S_ISBLK(st.st_mode))
1150 		flags |= O_DIRECT;
1151 
1152 	if (flags & O_CREAT)
1153 		old_umask = umask(0);
1154 
1155 	fd = open64(path, flags, mode);
1156 	if (fd == -1)
1157 		return (errno);
1158 
1159 	if (flags & O_CREAT)
1160 		(void) umask(old_umask);
1161 
1162 	if (vn_dumpdir != NULL) {
1163 		char *dumppath = umem_zalloc(MAXPATHLEN, UMEM_NOFAIL);
1164 		const char *inpath = zfs_basename(path);
1165 
1166 		(void) snprintf(dumppath, MAXPATHLEN,
1167 		    "%s/%s", vn_dumpdir, inpath);
1168 		dump_fd = open64(dumppath, O_CREAT | O_WRONLY, 0666);
1169 		umem_free(dumppath, MAXPATHLEN);
1170 		if (dump_fd == -1) {
1171 			err = errno;
1172 			close(fd);
1173 			return (err);
1174 		}
1175 	} else {
1176 		dump_fd = -1;
1177 	}
1178 
1179 	(void) fcntl(fd, F_SETFD, FD_CLOEXEC);
1180 
1181 	fp = umem_zalloc(sizeof (zfs_file_t), UMEM_NOFAIL);
1182 	fp->f_fd = fd;
1183 	fp->f_dump_fd = dump_fd;
1184 	*fpp = fp;
1185 
1186 	return (0);
1187 }
1188 
1189 void
zfs_file_close(zfs_file_t * fp)1190 zfs_file_close(zfs_file_t *fp)
1191 {
1192 	close(fp->f_fd);
1193 	if (fp->f_dump_fd != -1)
1194 		close(fp->f_dump_fd);
1195 
1196 	umem_free(fp, sizeof (zfs_file_t));
1197 }
1198 
1199 /*
1200  * Stateful write - use os internal file pointer to determine where to
1201  * write and update on successful completion.
1202  *
1203  * fp -  pointer to file (pipe, socket, etc) to write to
1204  * buf - buffer to write
1205  * count - # of bytes to write
1206  * resid -  pointer to count of unwritten bytes  (if short write)
1207  *
1208  * Returns 0 on success errno on failure.
1209  */
1210 int
zfs_file_write(zfs_file_t * fp,const void * buf,size_t count,ssize_t * resid)1211 zfs_file_write(zfs_file_t *fp, const void *buf, size_t count, ssize_t *resid)
1212 {
1213 	ssize_t rc;
1214 
1215 	rc = write(fp->f_fd, buf, count);
1216 	if (rc < 0)
1217 		return (errno);
1218 
1219 	if (resid) {
1220 		*resid = count - rc;
1221 	} else if (rc != count) {
1222 		return (EIO);
1223 	}
1224 
1225 	return (0);
1226 }
1227 
1228 /*
1229  * Stateless write - os internal file pointer is not updated.
1230  *
1231  * fp -  pointer to file (pipe, socket, etc) to write to
1232  * buf - buffer to write
1233  * count - # of bytes to write
1234  * off - file offset to write to (only valid for seekable types)
1235  * resid -  pointer to count of unwritten bytes
1236  *
1237  * Returns 0 on success errno on failure.
1238  */
1239 int
zfs_file_pwrite(zfs_file_t * fp,const void * buf,size_t count,loff_t pos,ssize_t * resid)1240 zfs_file_pwrite(zfs_file_t *fp, const void *buf,
1241     size_t count, loff_t pos, ssize_t *resid)
1242 {
1243 	ssize_t rc, split, done;
1244 	int sectors;
1245 
1246 	/*
1247 	 * To simulate partial disk writes, we split writes into two
1248 	 * system calls so that the process can be killed in between.
1249 	 * This is used by ztest to simulate realistic failure modes.
1250 	 */
1251 	sectors = count >> SPA_MINBLOCKSHIFT;
1252 	split = (sectors > 0 ? rand() % sectors : 0) << SPA_MINBLOCKSHIFT;
1253 	rc = pwrite64(fp->f_fd, buf, split, pos);
1254 	if (rc != -1) {
1255 		done = rc;
1256 		rc = pwrite64(fp->f_fd, (char *)buf + split,
1257 		    count - split, pos + split);
1258 	}
1259 #ifdef __linux__
1260 	if (rc == -1 && errno == EINVAL) {
1261 		/*
1262 		 * Under Linux, this most likely means an alignment issue
1263 		 * (memory or disk) due to O_DIRECT, so we abort() in order
1264 		 * to catch the offender.
1265 		 */
1266 		abort();
1267 	}
1268 #endif
1269 
1270 	if (rc < 0)
1271 		return (errno);
1272 
1273 	done += rc;
1274 
1275 	if (resid) {
1276 		*resid = count - done;
1277 	} else if (done != count) {
1278 		return (EIO);
1279 	}
1280 
1281 	return (0);
1282 }
1283 
1284 /*
1285  * Stateful read - use os internal file pointer to determine where to
1286  * read and update on successful completion.
1287  *
1288  * fp -  pointer to file (pipe, socket, etc) to read from
1289  * buf - buffer to write
1290  * count - # of bytes to read
1291  * resid -  pointer to count of unread bytes (if short read)
1292  *
1293  * Returns 0 on success errno on failure.
1294  */
1295 int
zfs_file_read(zfs_file_t * fp,void * buf,size_t count,ssize_t * resid)1296 zfs_file_read(zfs_file_t *fp, void *buf, size_t count, ssize_t *resid)
1297 {
1298 	int rc;
1299 
1300 	rc = read(fp->f_fd, buf, count);
1301 	if (rc < 0)
1302 		return (errno);
1303 
1304 	if (resid) {
1305 		*resid = count - rc;
1306 	} else if (rc != count) {
1307 		return (EIO);
1308 	}
1309 
1310 	return (0);
1311 }
1312 
1313 /*
1314  * Stateless read - os internal file pointer is not updated.
1315  *
1316  * fp -  pointer to file (pipe, socket, etc) to read from
1317  * buf - buffer to write
1318  * count - # of bytes to write
1319  * off - file offset to read from (only valid for seekable types)
1320  * resid -  pointer to count of unwritten bytes (if short write)
1321  *
1322  * Returns 0 on success errno on failure.
1323  */
1324 int
zfs_file_pread(zfs_file_t * fp,void * buf,size_t count,loff_t off,ssize_t * resid)1325 zfs_file_pread(zfs_file_t *fp, void *buf, size_t count, loff_t off,
1326     ssize_t *resid)
1327 {
1328 	ssize_t rc;
1329 
1330 	rc = pread64(fp->f_fd, buf, count, off);
1331 	if (rc < 0) {
1332 #ifdef __linux__
1333 		/*
1334 		 * Under Linux, this most likely means an alignment issue
1335 		 * (memory or disk) due to O_DIRECT, so we abort() in order to
1336 		 * catch the offender.
1337 		 */
1338 		if (errno == EINVAL)
1339 			abort();
1340 #endif
1341 		return (errno);
1342 	}
1343 
1344 	if (fp->f_dump_fd != -1) {
1345 		int status;
1346 
1347 		status = pwrite64(fp->f_dump_fd, buf, rc, off);
1348 		ASSERT(status != -1);
1349 	}
1350 
1351 	if (resid) {
1352 		*resid = count - rc;
1353 	} else if (rc != count) {
1354 		return (EIO);
1355 	}
1356 
1357 	return (0);
1358 }
1359 
1360 /*
1361  * lseek - set / get file pointer
1362  *
1363  * fp -  pointer to file (pipe, socket, etc) to read from
1364  * offp - value to seek to, returns current value plus passed offset
1365  * whence - see man pages for standard lseek whence values
1366  *
1367  * Returns 0 on success errno on failure (ESPIPE for non seekable types)
1368  */
1369 int
zfs_file_seek(zfs_file_t * fp,loff_t * offp,int whence)1370 zfs_file_seek(zfs_file_t *fp, loff_t *offp, int whence)
1371 {
1372 	loff_t rc;
1373 
1374 	rc = lseek(fp->f_fd, *offp, whence);
1375 	if (rc < 0)
1376 		return (errno);
1377 
1378 	*offp = rc;
1379 
1380 	return (0);
1381 }
1382 
1383 /*
1384  * Get file attributes
1385  *
1386  * filp - file pointer
1387  * zfattr - pointer to file attr structure
1388  *
1389  * Currently only used for fetching size and file mode
1390  *
1391  * Returns 0 on success or error code of underlying getattr call on failure.
1392  */
1393 int
zfs_file_getattr(zfs_file_t * fp,zfs_file_attr_t * zfattr)1394 zfs_file_getattr(zfs_file_t *fp, zfs_file_attr_t *zfattr)
1395 {
1396 	struct stat64 st;
1397 
1398 	if (fstat64_blk(fp->f_fd, &st) == -1)
1399 		return (errno);
1400 
1401 	zfattr->zfa_size = st.st_size;
1402 	zfattr->zfa_mode = st.st_mode;
1403 
1404 	return (0);
1405 }
1406 
1407 /*
1408  * Sync file to disk
1409  *
1410  * filp - file pointer
1411  * flags - O_SYNC and or O_DSYNC
1412  *
1413  * Returns 0 on success or error code of underlying sync call on failure.
1414  */
1415 int
zfs_file_fsync(zfs_file_t * fp,int flags)1416 zfs_file_fsync(zfs_file_t *fp, int flags)
1417 {
1418 	(void) flags;
1419 
1420 	if (fsync(fp->f_fd) < 0)
1421 		return (errno);
1422 
1423 	return (0);
1424 }
1425 
1426 /*
1427  * deallocate - zero and/or deallocate file storage
1428  *
1429  * fp - file pointer
1430  * offset - offset to start zeroing or deallocating
1431  * len - length to zero or deallocate
1432  */
1433 int
zfs_file_deallocate(zfs_file_t * fp,loff_t offset,loff_t len)1434 zfs_file_deallocate(zfs_file_t *fp, loff_t offset, loff_t len)
1435 {
1436 	int rc;
1437 #if defined(__linux__)
1438 	rc = fallocate(fp->f_fd,
1439 	    FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE, offset, len);
1440 #elif defined(__FreeBSD__) && (__FreeBSD_version >= 1400029)
1441 	struct spacectl_range rqsr = {
1442 		.r_offset = offset,
1443 		.r_len = len,
1444 	};
1445 	rc = fspacectl(fp->f_fd, SPACECTL_DEALLOC, &rqsr, 0, &rqsr);
1446 #else
1447 	(void) fp, (void) offset, (void) len;
1448 	rc = EOPNOTSUPP;
1449 #endif
1450 	if (rc)
1451 		return (SET_ERROR(rc));
1452 	return (0);
1453 }
1454 
1455 /*
1456  * Request current file pointer offset
1457  *
1458  * fp - pointer to file
1459  *
1460  * Returns current file offset.
1461  */
1462 loff_t
zfs_file_off(zfs_file_t * fp)1463 zfs_file_off(zfs_file_t *fp)
1464 {
1465 	return (lseek(fp->f_fd, SEEK_CUR, 0));
1466 }
1467 
1468 /*
1469  * unlink file
1470  *
1471  * path - fully qualified file path
1472  *
1473  * Returns 0 on success.
1474  *
1475  * OPTIONAL
1476  */
1477 int
zfs_file_unlink(const char * path)1478 zfs_file_unlink(const char *path)
1479 {
1480 	return (remove(path));
1481 }
1482 
1483 /*
1484  * Get reference to file pointer
1485  *
1486  * fd - input file descriptor
1487  *
1488  * Returns pointer to file struct or NULL.
1489  * Unsupported in user space.
1490  */
1491 zfs_file_t *
zfs_file_get(int fd)1492 zfs_file_get(int fd)
1493 {
1494 	(void) fd;
1495 	abort();
1496 	return (NULL);
1497 }
1498 /*
1499  * Drop reference to file pointer
1500  *
1501  * fp - pointer to file struct
1502  *
1503  * Unsupported in user space.
1504  */
1505 void
zfs_file_put(zfs_file_t * fp)1506 zfs_file_put(zfs_file_t *fp)
1507 {
1508 	abort();
1509 	(void) fp;
1510 }
1511 
1512 void
zfsvfs_update_fromname(const char * oldname,const char * newname)1513 zfsvfs_update_fromname(const char *oldname, const char *newname)
1514 {
1515 	(void) oldname, (void) newname;
1516 }
1517 
1518 void
spa_import_os(spa_t * spa)1519 spa_import_os(spa_t *spa)
1520 {
1521 	(void) spa;
1522 }
1523 
1524 void
spa_export_os(spa_t * spa)1525 spa_export_os(spa_t *spa)
1526 {
1527 	(void) spa;
1528 }
1529 
1530 void
spa_activate_os(spa_t * spa)1531 spa_activate_os(spa_t *spa)
1532 {
1533 	(void) spa;
1534 }
1535 
1536 void
spa_deactivate_os(spa_t * spa)1537 spa_deactivate_os(spa_t *spa)
1538 {
1539 	(void) spa;
1540 }
1541